Skip to main content

gpui_form_component/infinite_select/
path.rs

1use super::InfiniteSelectValue;
2use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
3use std::str::FromStr;
4use std::{error::Error, fmt};
5
6/// Represents an index-based selection path through nested infinite-select enums.
7#[derive(Clone, Debug, Default, Eq, PartialEq)]
8pub struct InfiniteSelectPath {
9    indices: Vec<usize>,
10}
11
12impl InfiniteSelectPath {
13    /// Creates a new empty selection path.
14    pub fn new() -> Self {
15        Self {
16            indices: Vec::new(),
17        }
18    }
19
20    /// Creates a path with the given indices.
21    pub fn with_indices(indices: Vec<usize>) -> Self {
22        Self { indices }
23    }
24
25    /// Returns the selection index at a given depth.
26    pub fn get(&self, depth: usize) -> Option<usize> {
27        self.indices.get(depth).copied()
28    }
29
30    /// Sets the selection at a given depth, truncating deeper selections.
31    pub fn set(&mut self, depth: usize, index: usize) {
32        self.indices.truncate(depth);
33        self.indices.push(index);
34    }
35
36    /// Clears selections from a given depth onwards.
37    pub fn clear_from(&mut self, depth: usize) {
38        self.indices.truncate(depth);
39    }
40
41    /// Truncates the path to the given length.
42    pub fn truncate(&mut self, len: usize) {
43        self.indices.truncate(len);
44    }
45
46    /// Returns the current depth of the selection.
47    pub fn len(&self) -> usize {
48        self.indices.len()
49    }
50
51    /// Returns all indices as a slice.
52    pub fn indices(&self) -> &[usize] {
53        &self.indices
54    }
55
56    /// Returns true if the path is empty.
57    pub fn is_empty(&self) -> bool {
58        self.indices.is_empty()
59    }
60}
61
62/// Represents a key-based selection path through nested infinite-select enums.
63#[derive(Clone, Debug, Default, Eq, PartialEq)]
64pub struct InfiniteSelectKeyPath {
65    keys: Vec<String>,
66}
67
68impl InfiniteSelectKeyPath {
69    /// Creates a new empty key path.
70    pub fn new() -> Self {
71        Self { keys: Vec::new() }
72    }
73
74    /// Creates a key path with the given keys.
75    pub fn with_keys(keys: Vec<String>) -> Self {
76        Self { keys }
77    }
78
79    /// Returns the selected key at a given depth.
80    pub fn get(&self, depth: usize) -> Option<&str> {
81        self.keys.get(depth).map(String::as_str)
82    }
83
84    /// Sets the selected key at a given depth, truncating deeper selections.
85    pub fn set(&mut self, depth: usize, key: impl Into<String>) {
86        self.keys.truncate(depth);
87        self.keys.push(key.into());
88    }
89
90    /// Clears selections from a given depth onwards.
91    pub fn clear_from(&mut self, depth: usize) {
92        self.keys.truncate(depth);
93    }
94
95    /// Truncates the path to the given length.
96    pub fn truncate(&mut self, len: usize) {
97        self.keys.truncate(len);
98    }
99
100    /// Returns the current depth of the selection.
101    pub fn len(&self) -> usize {
102        self.keys.len()
103    }
104
105    /// Returns all keys as a slice.
106    pub fn keys(&self) -> &[String] {
107        &self.keys
108    }
109
110    /// Returns true if the path is empty.
111    pub fn is_empty(&self) -> bool {
112        self.keys.is_empty()
113    }
114}
115
116impl fmt::Display for InfiniteSelectKeyPath {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        for (index, key) in self.keys.iter().enumerate() {
119            if index > 0 {
120                write!(f, "/")?;
121            }
122
123            for ch in key.chars() {
124                match ch {
125                    '\\' => write!(f, "\\\\")?,
126                    '/' => write!(f, "\\/")?,
127                    _ => write!(f, "{ch}")?,
128                }
129            }
130        }
131
132        Ok(())
133    }
134}
135
136/// A parse failure for the string form of `InfiniteSelectKeyPath`.
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub struct InfiniteSelectKeyPathParseError {
139    input: String,
140    reason: InfiniteSelectKeyPathParseErrorReason,
141}
142
143impl InfiniteSelectKeyPathParseError {
144    fn dangling_escape(input: &str) -> Self {
145        Self {
146            input: input.to_string(),
147            reason: InfiniteSelectKeyPathParseErrorReason::DanglingEscape,
148        }
149    }
150
151    /// Returns the original string input that failed to parse.
152    pub fn input(&self) -> &str {
153        &self.input
154    }
155
156    /// Returns the typed parse failure reason.
157    pub fn reason(&self) -> &InfiniteSelectKeyPathParseErrorReason {
158        &self.reason
159    }
160}
161
162impl fmt::Display for InfiniteSelectKeyPathParseError {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        match self.reason {
165            InfiniteSelectKeyPathParseErrorReason::DanglingEscape => {
166                write!(
167                    f,
168                    "infinite-select key path {:?} ends with an incomplete escape sequence",
169                    self.input
170                )
171            },
172        }
173    }
174}
175
176impl Error for InfiniteSelectKeyPathParseError {}
177
178/// The reason a string key path could not be parsed.
179#[derive(Clone, Debug, Eq, PartialEq)]
180pub enum InfiniteSelectKeyPathParseErrorReason {
181    DanglingEscape,
182}
183
184impl FromStr for InfiniteSelectKeyPath {
185    type Err = InfiniteSelectKeyPathParseError;
186
187    fn from_str(value: &str) -> Result<Self, Self::Err> {
188        if value.is_empty() {
189            return Ok(Self::new());
190        }
191
192        let mut keys = Vec::new();
193        let mut current = String::new();
194        let mut escaped = false;
195
196        for ch in value.chars() {
197            if escaped {
198                current.push(ch);
199                escaped = false;
200                continue;
201            }
202
203            match ch {
204                '\\' => escaped = true,
205                '/' => {
206                    keys.push(std::mem::take(&mut current));
207                },
208                _ => current.push(ch),
209            }
210        }
211
212        if escaped {
213            return Err(InfiniteSelectKeyPathParseError::dangling_escape(value));
214        }
215
216        keys.push(current);
217        Ok(Self::with_keys(keys))
218    }
219}
220
221impl Serialize for InfiniteSelectKeyPath {
222    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
223    where
224        S: Serializer,
225    {
226        serializer.serialize_str(&self.to_string())
227    }
228}
229
230impl<'de> Deserialize<'de> for InfiniteSelectKeyPath {
231    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
232    where
233        D: Deserializer<'de>,
234    {
235        let value = String::deserialize(deserializer)?;
236        value.parse().map_err(D::Error::custom)
237    }
238}
239
240/// Returns the current selection path for a concrete infinite-select value.
241pub fn path_from_value<T: InfiniteSelectValue>(value: &T) -> InfiniteSelectPath {
242    value.selection_path()
243}
244
245/// Returns the current key path for a concrete infinite-select value.
246pub fn key_path_from_value<T: InfiniteSelectValue>(value: &T) -> InfiniteSelectKeyPath {
247    value.selection_key_path()
248}
249
250/// The failing segment of an index- or key-based infinite-select path.
251#[derive(Clone, Debug, Eq, PartialEq)]
252pub enum InfiniteSelectPathSegment {
253    Index(usize),
254    Key(String),
255}
256
257impl InfiniteSelectPathSegment {
258    /// Returns the segment as an index when this is an index-based path error.
259    pub fn as_index(&self) -> Option<usize> {
260        match self {
261            Self::Index(index) => Some(*index),
262            Self::Key(_) => None,
263        }
264    }
265
266    /// Returns the segment as a key when this is a key-based path error.
267    pub fn as_key(&self) -> Option<&str> {
268        match self {
269            Self::Index(_) => None,
270            Self::Key(key) => Some(key),
271        }
272    }
273}
274
275/// The reason an infinite-select path failed to resolve.
276#[derive(Clone, Debug, Eq, PartialEq)]
277pub enum InfiniteSelectPathErrorReason {
278    EmptyPath,
279    MissingSelectionOptions,
280    InvalidIndex { option_count: usize },
281    UnknownKey { available_keys: Vec<String> },
282}
283
284/// A typed path-resolution failure for infinite-select helpers.
285#[derive(Clone, Debug, Eq, PartialEq)]
286pub struct InfiniteSelectPathError {
287    depth: usize,
288    segment: Option<InfiniteSelectPathSegment>,
289    reason: InfiniteSelectPathErrorReason,
290}
291
292impl InfiniteSelectPathError {
293    fn empty() -> Self {
294        Self {
295            depth: 0,
296            segment: None,
297            reason: InfiniteSelectPathErrorReason::EmptyPath,
298        }
299    }
300
301    pub(super) fn missing_selection_options(
302        depth: usize,
303        segment: InfiniteSelectPathSegment,
304    ) -> Self {
305        Self {
306            depth,
307            segment: Some(segment),
308            reason: InfiniteSelectPathErrorReason::MissingSelectionOptions,
309        }
310    }
311
312    fn invalid_index(depth: usize, index: usize, option_count: usize) -> Self {
313        Self {
314            depth,
315            segment: Some(InfiniteSelectPathSegment::Index(index)),
316            reason: InfiniteSelectPathErrorReason::InvalidIndex { option_count },
317        }
318    }
319
320    fn unknown_key(depth: usize, key: &str, available_keys: Vec<String>) -> Self {
321        Self {
322            depth,
323            segment: Some(InfiniteSelectPathSegment::Key(key.to_string())),
324            reason: InfiniteSelectPathErrorReason::UnknownKey { available_keys },
325        }
326    }
327
328    /// Returns the depth where path resolution failed.
329    pub fn depth(&self) -> usize {
330        self.depth
331    }
332
333    /// Returns the failing path segment, when available.
334    pub fn segment(&self) -> Option<&InfiniteSelectPathSegment> {
335        self.segment.as_ref()
336    }
337
338    /// Returns the typed failure reason.
339    pub fn reason(&self) -> &InfiniteSelectPathErrorReason {
340        &self.reason
341    }
342}
343
344impl fmt::Display for InfiniteSelectPathError {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        match (&self.segment, &self.reason) {
347            (None, InfiniteSelectPathErrorReason::EmptyPath) => {
348                write!(f, "infinite-select path is empty")
349            },
350            (
351                Some(InfiniteSelectPathSegment::Index(index)),
352                InfiniteSelectPathErrorReason::MissingSelectionOptions,
353            ) => {
354                write!(
355                    f,
356                    "no selectable options exist at depth {} for index {}",
357                    self.depth, index
358                )
359            },
360            (
361                Some(InfiniteSelectPathSegment::Key(key)),
362                InfiniteSelectPathErrorReason::MissingSelectionOptions,
363            ) => {
364                write!(
365                    f,
366                    "no selectable options exist at depth {} for key {:?}",
367                    self.depth, key
368                )
369            },
370            (
371                Some(InfiniteSelectPathSegment::Index(index)),
372                InfiniteSelectPathErrorReason::InvalidIndex { option_count },
373            ) => write!(
374                f,
375                "index {} is out of bounds at depth {} ({} options available)",
376                index, self.depth, option_count
377            ),
378            (
379                Some(InfiniteSelectPathSegment::Key(key)),
380                InfiniteSelectPathErrorReason::UnknownKey { available_keys },
381            ) => write!(
382                f,
383                "key {:?} is not valid at depth {} (available keys: {:?})",
384                key, self.depth, available_keys
385            ),
386            _ => write!(f, "invalid infinite-select path at depth {}", self.depth),
387        }
388    }
389}
390
391impl Error for InfiniteSelectPathError {}
392
393/// Rebuilds a value from an index-based selection path.
394pub fn build_from_path<T: InfiniteSelectValue>(
395    path: &InfiniteSelectPath,
396) -> Result<T, InfiniteSelectPathError> {
397    if path.is_empty() {
398        return Err(InfiniteSelectPathError::empty());
399    }
400
401    let variants = T::variants();
402    let root_index = path
403        .get(0)
404        .expect("non-empty paths include the root selection");
405    let Some(mut current_value) = variants.get(root_index).cloned() else {
406        return Err(InfiniteSelectPathError::invalid_index(
407            0,
408            root_index,
409            variants.len(),
410        ));
411    };
412
413    for depth in 1..path.len() {
414        let index = path
415            .get(depth)
416            .expect("path length guarantees a selection at each iterated depth");
417        let values = child_values_for_level(&current_value, depth - 1);
418
419        if values.is_empty() {
420            return Err(InfiniteSelectPathError::missing_selection_options(
421                depth,
422                InfiniteSelectPathSegment::Index(index),
423            ));
424        }
425
426        let Some(value) = values.get(index) else {
427            return Err(InfiniteSelectPathError::invalid_index(
428                depth,
429                index,
430                values.len(),
431            ));
432        };
433
434        current_value = value.clone();
435    }
436
437    Ok(current_value)
438}
439
440/// Rebuilds a value from a key-based selection path.
441pub fn build_from_key_path<T: InfiniteSelectValue>(
442    path: &InfiniteSelectKeyPath,
443) -> Result<T, InfiniteSelectPathError> {
444    if path.is_empty() {
445        return Err(InfiniteSelectPathError::empty());
446    }
447
448    let root_key = path
449        .get(0)
450        .expect("non-empty key paths include the root selection");
451    let variants = T::variants();
452    let Some(mut current_value) = variants
453        .iter()
454        .find(|variant| variant.variant_key() == root_key)
455        .cloned()
456    else {
457        return Err(InfiniteSelectPathError::unknown_key(
458            0,
459            root_key,
460            variants
461                .iter()
462                .map(|variant| variant.variant_key().to_string())
463                .collect(),
464        ));
465    };
466
467    for depth in 1..path.len() {
468        let key = path
469            .get(depth)
470            .expect("path length guarantees a selection at each iterated depth");
471        let values = child_values_for_level(&current_value, depth - 1);
472
473        if values.is_empty() {
474            return Err(InfiniteSelectPathError::missing_selection_options(
475                depth,
476                InfiniteSelectPathSegment::Key(key.to_string()),
477            ));
478        }
479
480        let available_keys: Vec<String> = values
481            .iter()
482            .filter_map(|value| value.selection_key_path().get(depth).map(str::to_string))
483            .collect();
484
485        let Some(value) = values.iter().find(|value| {
486            value
487                .selection_key_path()
488                .get(depth)
489                .is_some_and(|candidate| candidate == key)
490        }) else {
491            return Err(InfiniteSelectPathError::unknown_key(
492                depth,
493                key,
494                available_keys,
495            ));
496        };
497
498        current_value = value.clone();
499    }
500
501    Ok(current_value)
502}
503
504fn child_values_for_level<T: InfiniteSelectValue>(current_value: &T, level: usize) -> Vec<T> {
505    let option_count = if level == 0 {
506        current_value.child_variant_keys().len()
507    } else {
508        current_value.inner_child_variant_keys().len()
509    };
510
511    (0..option_count)
512        .filter_map(|index| {
513            if level == 0 {
514                current_value.set_child_by_index(index)
515            } else {
516                current_value.inner_set_child_by_index(index)
517            }
518        })
519        .collect()
520}