Skip to main content

gpui_rhai/
state.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt;
3use std::rc::Rc;
4
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7
8use crate::{SchemaDefinitionError, SchemaValidationError, UiValue, ValueSchema};
9
10#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
11pub struct ComponentInstancePath(Vec<ComponentInstanceSegment>);
12
13#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
14struct ComponentInstanceSegment {
15    component: String,
16    key: String,
17}
18
19impl ComponentInstancePath {
20    #[must_use]
21    pub fn root(component: impl Into<String>, key: impl Into<String>) -> Self {
22        Self(vec![ComponentInstanceSegment {
23            component: component.into(),
24            key: key.into(),
25        }])
26    }
27
28    #[must_use]
29    pub fn child(&self, component: impl Into<String>, key: impl Into<String>) -> Self {
30        let mut segments = self.0.clone();
31        segments.push(ComponentInstanceSegment {
32            component: component.into(),
33            key: key.into(),
34        });
35        Self(segments)
36    }
37
38    #[must_use]
39    pub fn parent(&self) -> Option<Self> {
40        if self.0.len() <= 1 {
41            return None;
42        }
43        let mut segments = self.0.clone();
44        segments.pop();
45        Some(Self(segments))
46    }
47
48    #[must_use]
49    pub fn leaf_key(&self) -> Option<&str> {
50        self.0.last().map(|segment| segment.key.as_str())
51    }
52
53    #[must_use]
54    pub fn is_within(&self, ancestor: &Self) -> bool {
55        self.0.starts_with(&ancestor.0)
56    }
57
58    pub(crate) fn segments(&self) -> impl ExactSizeIterator<Item = (&str, &str)> {
59        self.0
60            .iter()
61            .map(|segment| (segment.component.as_str(), segment.key.as_str()))
62    }
63
64    pub(crate) fn single_root_key(&self, component: &str) -> Option<&str> {
65        (self.0.len() == 1 && self.0[0].component == component).then_some(self.0[0].key.as_str())
66    }
67}
68
69impl fmt::Display for ComponentInstancePath {
70    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71        for segment in &self.0 {
72            write!(formatter, "/{}[{}]", segment.component, segment.key)?;
73        }
74        Ok(())
75    }
76}
77
78pub(crate) fn topmost_paths(paths: &BTreeSet<ComponentInstancePath>) -> Vec<ComponentInstancePath> {
79    let mut roots = Vec::<ComponentInstancePath>::new();
80    // Lexicographic component paths place each ancestor before its contiguous
81    // subtree. Keep disjoint roots without a quadratic all-pairs scan.
82    for path in paths {
83        if roots.last().is_none_or(|root| !path.is_within(root)) {
84            roots.push(path.clone());
85        }
86    }
87    roots
88}
89
90#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
91pub struct StateField {
92    pub schema: ValueSchema,
93    pub default: UiValue,
94    #[serde(default)]
95    pub sensitive: bool,
96}
97
98impl StateField {
99    #[must_use]
100    pub fn new(schema: ValueSchema, default: UiValue) -> Self {
101        Self {
102            schema,
103            default,
104            sensitive: false,
105        }
106    }
107
108    #[must_use]
109    pub const fn sensitive(mut self, sensitive: bool) -> Self {
110        self.sensitive = sensitive;
111        self
112    }
113}
114
115#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
116pub struct ComponentStateSchema {
117    fields: BTreeMap<String, StateField>,
118}
119
120impl ComponentStateSchema {
121    /// Create a state schema after validating every declared default.
122    ///
123    /// # Errors
124    ///
125    /// Returns [`StateError::InvalidDefault`] when a default does not satisfy
126    /// its field schema.
127    pub fn new(fields: BTreeMap<String, StateField>) -> Result<Self, StateError> {
128        for (name, field) in &fields {
129            field
130                .schema
131                .validate_definition()
132                .map_err(|source| StateError::InvalidSchema {
133                    field: name.clone(),
134                    source,
135                })?;
136            field
137                .schema
138                .validate_ui_value(&field.default)
139                .map_err(|source| StateError::InvalidDefault {
140                    field: name.clone(),
141                    source,
142                })?;
143        }
144        Ok(Self { fields })
145    }
146
147    #[must_use]
148    pub fn is_empty(&self) -> bool {
149        self.fields.is_empty()
150    }
151
152    #[must_use]
153    pub fn field(&self, name: &str) -> Option<&StateField> {
154        self.fields.get(name)
155    }
156
157    #[must_use]
158    pub fn fields(&self) -> &BTreeMap<String, StateField> {
159        &self.fields
160    }
161
162    fn defaults(&self) -> BTreeMap<String, UiValue> {
163        self.fields
164            .iter()
165            .map(|(name, field)| (name.clone(), field.default.clone()))
166            .collect()
167    }
168}
169
170#[derive(Clone, Debug, Default)]
171pub struct StateStore {
172    instances: Rc<BTreeMap<ComponentInstancePath, ComponentState>>,
173}
174
175#[derive(Clone, Debug)]
176struct ComponentState {
177    schema: Rc<ComponentStateSchema>,
178    values: Rc<BTreeMap<String, UiValue>>,
179}
180
181impl StateStore {
182    #[must_use]
183    pub fn new() -> Self {
184        Self::default()
185    }
186
187    /// Start an isolated render-state transaction.
188    ///
189    /// Dropping the transaction leaves the committed store unchanged. Passing
190    /// it to [`StateStore::commit_render`] installs compatible state and removes
191    /// instances not reached during the successful render.
192    #[must_use]
193    pub fn begin_render(&self) -> RenderStateTransaction {
194        RenderStateTransaction {
195            instances: Rc::clone(&self.instances),
196            seen: BTreeSet::new(),
197            scope: None,
198        }
199    }
200
201    /// Start a transaction that reconciles only one component subtree.
202    /// State belonging to other window roots remains untouched on commit.
203    #[must_use]
204    pub fn begin_render_scope(&self, scope: ComponentInstancePath) -> RenderStateTransaction {
205        RenderStateTransaction {
206            instances: Rc::clone(&self.instances),
207            seen: BTreeSet::new(),
208            scope: Some(scope),
209        }
210    }
211
212    pub fn commit_render(&mut self, transaction: RenderStateTransaction) {
213        let active = transaction.seen.clone();
214        self.commit_render_batch([transaction], &active);
215    }
216
217    pub(crate) fn commit_render_batch(
218        &mut self,
219        transactions: impl IntoIterator<Item = RenderStateTransaction>,
220        active: &BTreeSet<ComponentInstancePath>,
221    ) {
222        let candidate = Rc::make_mut(&mut self.instances);
223        let mut scopes = BTreeSet::new();
224        let mut global = false;
225        for transaction in transactions {
226            for path in &transaction.seen {
227                if transaction
228                    .scope
229                    .as_ref()
230                    .is_none_or(|scope| path.is_within(scope))
231                    && let Some(state) = transaction.instances.get(path)
232                {
233                    candidate.insert(path.clone(), state.clone());
234                }
235            }
236            if let Some(scope) = transaction.scope {
237                scopes.insert(scope);
238            } else {
239                global = true;
240            }
241        }
242        let scopes = topmost_paths(&scopes).into_iter().collect::<BTreeSet<_>>();
243        candidate.retain(|path, _| {
244            let covered = global
245                || scopes
246                    .range((std::ops::Bound::Unbounded, std::ops::Bound::Included(path)))
247                    .next_back()
248                    .is_some_and(|scope| path.is_within(scope));
249            !covered || active.contains(path)
250        });
251    }
252
253    /// Remove one component subtree, including every descendant instance.
254    pub fn remove_scope(&mut self, scope: &ComponentInstancePath) {
255        Rc::make_mut(&mut self.instances).retain(|path, _| !path.is_within(scope));
256    }
257
258    /// Mount or reconcile one instance without cleaning any other path.
259    /// Used to make candidate component defaults readable during `view`.
260    ///
261    /// # Errors
262    ///
263    /// Returns invalid-schema/default errors.
264    pub fn mount_instance(
265        &mut self,
266        path: ComponentInstancePath,
267        schema: &ComponentStateSchema,
268    ) -> Result<StateReconcileReport, StateError> {
269        let report = reconcile_instance(Rc::make_mut(&mut self.instances), path, schema)?;
270        Ok(report)
271    }
272
273    #[must_use]
274    pub fn get(&self, path: &ComponentInstancePath, field: &str) -> Option<&UiValue> {
275        self.instances.get(path)?.values.get(field)
276    }
277
278    /// Update a declared field on a committed component instance.
279    ///
280    /// # Errors
281    ///
282    /// Returns [`StateError::UnknownInstance`], [`StateError::UnknownField`], or
283    /// [`StateError::InvalidValue`] when the update violates committed state.
284    pub fn set(
285        &mut self,
286        path: &ComponentInstancePath,
287        field: &str,
288        value: UiValue,
289    ) -> Result<bool, StateError> {
290        let state = Rc::make_mut(&mut self.instances)
291            .get_mut(path)
292            .ok_or_else(|| StateError::UnknownInstance(path.clone()))?;
293        let state_field = state
294            .schema
295            .field(field)
296            .ok_or_else(|| StateError::UnknownField {
297                path: path.clone(),
298                field: field.to_owned(),
299            })?;
300        state_field
301            .schema
302            .validate_ui_value(&value)
303            .map_err(|source| StateError::InvalidValue {
304                path: path.clone(),
305                field: field.to_owned(),
306                source,
307            })?;
308        if state.values.get(field) == Some(&value) {
309            return Ok(false);
310        }
311        Rc::make_mut(&mut state.values).insert(field.to_owned(), value);
312        Ok(true)
313    }
314
315    #[must_use]
316    pub fn instance_count(&self) -> usize {
317        self.instances.len()
318    }
319
320    pub(crate) fn contains_instance(&self, path: &ComponentInstancePath) -> bool {
321        self.instances.contains_key(path)
322    }
323
324    #[must_use]
325    pub fn paths(&self) -> BTreeSet<ComponentInstancePath> {
326        self.instances.keys().cloned().collect()
327    }
328
329    #[must_use]
330    pub fn is_sensitive(&self, path: &ComponentInstancePath, field: &str) -> bool {
331        self.instances
332            .get(path)
333            .and_then(|state| state.schema.field(field))
334            .is_some_and(|field| field.sensitive)
335    }
336
337    #[must_use]
338    pub fn inspect(&self) -> Vec<StateInstanceSnapshot> {
339        self.instances
340            .iter()
341            .map(|(path, state)| state_instance_snapshot(path, state))
342            .collect()
343    }
344
345    /// Inspect one component instance without cloning unrelated component state.
346    #[must_use]
347    pub fn inspect_instance(&self, path: &ComponentInstancePath) -> Option<StateInstanceSnapshot> {
348        self.instances
349            .get(path)
350            .map(|state| state_instance_snapshot(path, state))
351    }
352}
353
354fn state_instance_snapshot(
355    path: &ComponentInstancePath,
356    state: &ComponentState,
357) -> StateInstanceSnapshot {
358    StateInstanceSnapshot {
359        path: path.clone(),
360        fields: state
361            .values
362            .iter()
363            .map(|(name, value)| {
364                let sensitive = state
365                    .schema
366                    .field(name)
367                    .is_some_and(|field| field.sensitive);
368                (
369                    name.clone(),
370                    StateValueSnapshot {
371                        value: if sensitive {
372                            UiValue::String("<sensitive>".to_owned())
373                        } else {
374                            value.clone()
375                        },
376                        sensitive,
377                    },
378                )
379            })
380            .collect(),
381    }
382}
383
384#[derive(Clone, Debug, PartialEq)]
385pub struct StateInstanceSnapshot {
386    pub path: ComponentInstancePath,
387    pub fields: BTreeMap<String, StateValueSnapshot>,
388}
389
390#[derive(Clone, Debug, PartialEq)]
391pub struct StateValueSnapshot {
392    pub value: UiValue,
393    pub sensitive: bool,
394}
395
396#[derive(Clone, Debug)]
397pub struct RenderStateTransaction {
398    instances: Rc<BTreeMap<ComponentInstancePath, ComponentState>>,
399    seen: BTreeSet<ComponentInstancePath>,
400    scope: Option<ComponentInstancePath>,
401}
402
403impl RenderStateTransaction {
404    pub(crate) fn retains_root(&self) -> bool {
405        self.scope
406            .as_ref()
407            .is_some_and(|root| self.seen.contains(root))
408    }
409    /// Retain a previously mounted instance without changing its schema.
410    #[must_use]
411    pub fn retain_existing(&mut self, path: &ComponentInstancePath) -> bool {
412        if self.instances.contains_key(path) {
413            self.seen.insert(path.clone());
414            true
415        } else {
416            false
417        }
418    }
419
420    /// Mount or reconcile an instance inside this prospective render.
421    ///
422    /// # Errors
423    ///
424    /// Returns [`StateError::InvalidDefault`] if a programmatically constructed
425    /// schema contains an invalid default.
426    pub fn mount(
427        &mut self,
428        path: ComponentInstancePath,
429        schema: &ComponentStateSchema,
430    ) -> Result<StateReconcileReport, StateError> {
431        let report = reconcile_instance(Rc::make_mut(&mut self.instances), path.clone(), schema)?;
432        self.seen.insert(path);
433        Ok(report)
434    }
435}
436
437fn reconcile_instance(
438    instances: &mut BTreeMap<ComponentInstancePath, ComponentState>,
439    path: ComponentInstancePath,
440    schema: &ComponentStateSchema,
441) -> Result<StateReconcileReport, StateError> {
442    // Public serde construction can bypass `ComponentStateSchema::new`.
443    ComponentStateSchema::new(schema.fields.clone())?;
444
445    let next = match instances.get(&path) {
446        None => (
447            ComponentState {
448                schema: Rc::new(schema.clone()),
449                values: Rc::new(schema.defaults()),
450            },
451            StateReconcileReport {
452                created: true,
453                reset_fields: Vec::new(),
454            },
455        ),
456        Some(previous) => {
457            let mut reset_fields = Vec::new();
458            let values = schema
459                .fields
460                .iter()
461                .map(|(name, field)| {
462                    let value = previous
463                        .values
464                        .get(name)
465                        .filter(|value| field.schema.validate_ui_value(value).is_ok())
466                        .cloned()
467                        .unwrap_or_else(|| {
468                            if previous.values.contains_key(name) {
469                                reset_fields.push(name.clone());
470                            }
471                            field.default.clone()
472                        });
473                    (name.clone(), value)
474                })
475                .collect();
476            (
477                ComponentState {
478                    schema: Rc::new(schema.clone()),
479                    values: Rc::new(values),
480                },
481                StateReconcileReport {
482                    created: false,
483                    reset_fields,
484                },
485            )
486        }
487    };
488    instances.insert(path, next.0);
489    Ok(next.1)
490}
491
492#[derive(Clone, Debug, Default, Eq, PartialEq)]
493pub struct StateReconcileReport {
494    pub created: bool,
495    pub reset_fields: Vec<String>,
496}
497
498#[derive(Clone, Debug, Error, Eq, PartialEq)]
499pub enum StateError {
500    #[error("schema for state field `{field}` is invalid: {source}")]
501    InvalidSchema {
502        field: String,
503        source: SchemaDefinitionError,
504    },
505    #[error("default for state field `{field}` is invalid: {source}")]
506    InvalidDefault {
507        field: String,
508        source: SchemaValidationError,
509    },
510    #[error("component state instance `{0}` does not exist")]
511    UnknownInstance(ComponentInstancePath),
512    #[error("state field `{field}` is not declared for component `{path}`")]
513    UnknownField {
514        path: ComponentInstancePath,
515        field: String,
516    },
517    #[error("state value for `{path}.{field}` is invalid: {source}")]
518    InvalidValue {
519        path: ComponentInstancePath,
520        field: String,
521        source: SchemaValidationError,
522    },
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    #[test]
530    fn scoped_candidates_preserve_latest_outside_writes_and_deletions() {
531        let first = ComponentInstancePath::root("View", "first");
532        let second = ComponentInstancePath::root("View", "second");
533        let removed = second.child("Counter", "gone");
534        let schema = ComponentStateSchema::new(BTreeMap::from([(
535            "count".into(),
536            StateField::new(ValueSchema::integer(), UiValue::Integer(7)),
537        )]))
538        .unwrap();
539        let mut states = StateStore::new();
540        let mut initial = states.begin_render();
541        for path in [&first, &second, &removed] {
542            initial.mount(path.clone(), &schema).unwrap();
543        }
544        states.commit_render(initial);
545        let mut candidate = states.begin_render_scope(first.clone());
546        candidate.mount(first.clone(), &schema).unwrap();
547        states.set(&second, "count", UiValue::Integer(9)).unwrap();
548        states.remove_scope(&removed);
549        states.commit_render(candidate);
550        assert_eq!(states.get(&second, "count"), Some(&UiValue::Integer(9)));
551        assert!(states.get(&removed, "count").is_none());
552    }
553
554    fn schema(value_schema: ValueSchema, default: UiValue) -> ComponentStateSchema {
555        ComponentStateSchema::new(BTreeMap::from([(
556            "value".to_owned(),
557            StateField::new(value_schema, default),
558        )]))
559        .unwrap()
560    }
561
562    #[test]
563    fn failed_render_does_not_change_committed_state() {
564        let path = ComponentInstancePath::root("App", "root").child("Combobox", "country");
565        let bool_schema = schema(ValueSchema::Bool, UiValue::Bool(false));
566        let mut store = StateStore::new();
567
568        let mut initial = store.begin_render();
569        initial.mount(path.clone(), &bool_schema).unwrap();
570        store.commit_render(initial);
571        store.set(&path, "value", UiValue::Bool(true)).unwrap();
572
573        let mut failed = store.begin_render();
574        failed
575            .mount(
576                path.clone(),
577                &schema(
578                    ValueSchema::enumeration(["new"]),
579                    UiValue::String("new".to_owned()),
580                ),
581            )
582            .unwrap();
583        drop(failed);
584
585        assert_eq!(store.get(&path, "value"), Some(&UiValue::Bool(true)));
586    }
587
588    #[test]
589    fn successful_render_resets_only_incompatible_fields() {
590        let path = ComponentInstancePath::root("App", "root");
591        let mut store = StateStore::new();
592        let bool_schema = schema(ValueSchema::Bool, UiValue::Bool(false));
593        let mut initial = store.begin_render();
594        initial.mount(path.clone(), &bool_schema).unwrap();
595        store.commit_render(initial);
596        store.set(&path, "value", UiValue::Bool(true)).unwrap();
597
598        let string_schema = schema(ValueSchema::string(), UiValue::String("reset".to_owned()));
599        let mut reload = store.begin_render();
600        let report = reload.mount(path.clone(), &string_schema).unwrap();
601        store.commit_render(reload);
602
603        assert_eq!(report.reset_fields, vec!["value"]);
604        assert_eq!(
605            store.get(&path, "value"),
606            Some(&UiValue::String("reset".to_owned()))
607        );
608    }
609
610    #[test]
611    fn inspect_instance_is_exact_and_redacts_sensitive_values() {
612        let selected = ComponentInstancePath::root("App", "root").child("Panel", "selected");
613        let unrelated = ComponentInstancePath::root("App", "root").child("Panel", "other");
614        let schema = ComponentStateSchema::new(BTreeMap::from([(
615            "token".to_owned(),
616            StateField::new(ValueSchema::string(), UiValue::String("secret".to_owned()))
617                .sensitive(true),
618        )]))
619        .unwrap();
620        let mut store = StateStore::new();
621        let mut render = store.begin_render();
622        render.mount(selected.clone(), &schema).unwrap();
623        render.mount(unrelated, &schema).unwrap();
624        store.commit_render(render);
625
626        let snapshot = store.inspect_instance(&selected).unwrap();
627        assert_eq!(snapshot.path, selected);
628        assert_eq!(
629            snapshot.fields["token"].value,
630            UiValue::String("<sensitive>".to_owned())
631        );
632        assert!(snapshot.fields["token"].sensitive);
633        assert!(
634            store
635                .inspect_instance(&ComponentInstancePath::root("missing", "root"))
636                .is_none()
637        );
638    }
639
640    #[test]
641    fn successful_render_cleans_unreachable_instances() {
642        let first = ComponentInstancePath::root("App", "root").child("Row", "first");
643        let second = ComponentInstancePath::root("App", "root").child("Row", "second");
644        let state_schema = schema(ValueSchema::integer(), UiValue::Integer(0));
645        let mut store = StateStore::new();
646        let mut initial = store.begin_render();
647        initial.mount(first.clone(), &state_schema).unwrap();
648        initial.mount(second, &state_schema).unwrap();
649        store.commit_render(initial);
650        assert_eq!(store.instance_count(), 2);
651
652        let mut next = store.begin_render();
653        next.mount(first, &state_schema).unwrap();
654        store.commit_render(next);
655        assert_eq!(store.instance_count(), 1);
656    }
657
658    #[test]
659    fn snapshots_share_instances_until_one_store_mutates() {
660        let path = ComponentInstancePath::root("Counter", "one");
661        let schema = schema(ValueSchema::integer(), UiValue::Integer(0));
662        let mut store = StateStore::new();
663        store.mount_instance(path.clone(), &schema).unwrap();
664        let snapshot = store.clone();
665        assert!(Rc::ptr_eq(&store.instances, &snapshot.instances));
666        store.set(&path, "value", UiValue::Integer(4)).unwrap();
667        assert!(!Rc::ptr_eq(&store.instances, &snapshot.instances));
668        assert_eq!(snapshot.get(&path, "value"), Some(&UiValue::Integer(0)));
669    }
670
671    #[test]
672    fn updates_are_schema_checked() {
673        let path = ComponentInstancePath::root("App", "root");
674        let state_schema = schema(ValueSchema::Bool, UiValue::Bool(false));
675        let mut store = StateStore::new();
676        let mut render = store.begin_render();
677        render.mount(path.clone(), &state_schema).unwrap();
678        store.commit_render(render);
679
680        assert!(matches!(
681            store.set(&path, "value", UiValue::String("no".to_owned())),
682            Err(StateError::InvalidValue { .. })
683        ));
684    }
685
686    #[test]
687    fn scoped_commit_preserves_other_window_roots_and_remove_scope_cleans_one() {
688        let state_schema = schema(ValueSchema::string(), UiValue::String("ready".to_owned()));
689        let main = ComponentInstancePath::root("App", "main");
690        let settings = ComponentInstancePath::root("App", "settings");
691        let mut store = StateStore::new();
692        let mut initial = store.begin_render();
693        initial.mount(main.clone(), &state_schema).unwrap();
694        initial.mount(settings.clone(), &state_schema).unwrap();
695        store.commit_render(initial);
696
697        let mut main_render = store.begin_render_scope(main.clone());
698        main_render.mount(main.clone(), &state_schema).unwrap();
699        store.commit_render(main_render);
700        assert!(store.get(&settings, "value").is_some());
701
702        store.remove_scope(&main);
703        assert!(store.get(&main, "value").is_none());
704        assert!(store.get(&settings, "value").is_some());
705    }
706}