tui-treelistview 0.2.0

Interactive tree list widget for Ratatui
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::cmp::Ordering;
use std::hash::Hash;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};

static NEXT_QUERY_POLICY_GENERATION: AtomicU64 = AtomicU64::new(1);

/// The state of a node's child list.
///
/// Unlike an empty slice, `Unloaded` and `Loading` preserve the fact that a node is a branch
/// whose children may be loaded asynchronously.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TreeChildren<'a, Id> {
    /// The node is known to be a leaf.
    Leaf,
    /// Children exist or may exist, but have not been loaded yet.
    Unloaded,
    /// Children are currently loading.
    Loading,
    /// Children are loaded and exposed as a stable slice.
    Loaded(&'a [Id]),
}

impl<'a, Id> TreeChildren<'a, Id> {
    /// Creates a loaded state, converting an empty slice into a leaf.
    #[must_use]
    pub const fn loaded(children: &'a [Id]) -> Self {
        if children.is_empty() {
            Self::Leaf
        } else {
            Self::Loaded(children)
        }
    }

    /// Returns the loaded children or an empty slice.
    #[must_use]
    pub const fn loaded_slice(self) -> &'a [Id] {
        match self {
            Self::Loaded(children) => children,
            Self::Leaf | Self::Unloaded | Self::Loading => &[],
        }
    }

    /// Returns `true` when the node is a potentially expandable branch.
    #[must_use]
    pub const fn is_branch(self) -> bool {
        !matches!(self, Self::Leaf)
    }
}

/// Controls how roots are projected.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TreeRootVisibility {
    /// Every root is displayed as a regular row.
    #[default]
    Visible,
    /// Roots are synthetic; their loaded children are displayed at level `0`.
    Hidden,
}

/// Selection policy used when the selected node disappears from the projection.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TreeSelectionFallback {
    /// Prefer the nearest visible ancestor, then the nearest row.
    #[default]
    ParentThenNearest,
    /// Select the row nearest to the previous index.
    Nearest,
    /// Clear the selection.
    Clear,
}

/// Tree filtering configuration.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TreeFilterConfig {
    /// Filtering is disabled.
    #[default]
    Disabled,
    /// Keep matching nodes and the paths leading to them.
    Enabled {
        /// Force filtered paths to expand.
        auto_expand: bool,
    },
}

impl TreeFilterConfig {
    /// Enables filtering with automatic path expansion.
    #[must_use]
    pub const fn enabled() -> Self {
        Self::Enabled { auto_expand: true }
    }

    /// Enables filtering with manual path expansion.
    #[must_use]
    pub const fn enabled_manual_expand() -> Self {
        Self::Enabled { auto_expand: false }
    }
}

/// A monotonically increasing revision of model, filter, or sorting data.
///
/// The projection cache is rebuilt whenever any participating revision changes. A
/// [`TreeModel`] implementation must return a new value after changing its contents.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TreeRevision(u64);

impl TreeRevision {
    /// The initial revision of an immutable value.
    pub const INITIAL: Self = Self(0);

    /// Creates a revision from an external counter.
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the numeric revision value.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }

    /// Returns the next revision.
    #[must_use]
    pub const fn next(self) -> Self {
        Self(self.0.wrapping_add(1))
    }

    /// Advances the counter to the next revision.
    pub const fn advance(&mut self) {
        *self = self.next();
    }
}

impl From<u64> for TreeRevision {
    fn from(value: u64) -> Self {
        Self::new(value)
    }
}

/// A filter that matches every node.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NoFilter;

impl<T: TreeModel> TreeFilter<T> for NoFilter {
    #[inline]
    fn is_match(&self, _model: &T, _id: T::Id) -> bool {
        true
    }
}

/// No sorting; preserves model order.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NoSort;

impl<T: TreeModel> TreeSort<T> for NoSort {
    fn compare(&self, _model: &T, _left: T::Id, _right: T::Id) -> Ordering {
        Ordering::Equal
    }

    fn is_enabled(&self) -> bool {
        false
    }
}

/// A complete query for building the visible projection.
#[derive(Clone, Debug)]
pub struct TreeQuery<F = NoFilter, S = NoSort> {
    filter: QueryPolicy<F>,
    sort: QueryPolicy<S>,
    filter_config: TreeFilterConfig,
    root_visibility: TreeRootVisibility,
    selection_fallback: TreeSelectionFallback,
}

impl TreeQuery {
    /// Creates a query without filtering or sorting.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            filter: QueryPolicy::new(NoFilter, TreeRevision::INITIAL),
            sort: QueryPolicy::new(NoSort, TreeRevision::INITIAL),
            filter_config: TreeFilterConfig::Disabled,
            root_visibility: TreeRootVisibility::Visible,
            selection_fallback: TreeSelectionFallback::ParentThenNearest,
        }
    }
}

impl<F, S> TreeQuery<F, S> {
    /// Sets the filter and its current revision.
    #[must_use]
    pub fn with_filter<NF>(
        self,
        filter: NF,
        config: TreeFilterConfig,
        revision: TreeRevision,
    ) -> TreeQuery<NF, S> {
        TreeQuery {
            filter: QueryPolicy::replacement(filter, revision),
            sort: self.sort,
            filter_config: config,
            root_visibility: self.root_visibility,
            selection_fallback: self.selection_fallback,
        }
    }

    /// Sets the sorting policy and its current revision.
    #[must_use]
    pub fn with_sort<NS>(self, sort: NS, revision: TreeRevision) -> TreeQuery<F, NS> {
        TreeQuery {
            filter: self.filter,
            sort: QueryPolicy::replacement(sort, revision),
            filter_config: self.filter_config,
            root_visibility: self.root_visibility,
            selection_fallback: self.selection_fallback,
        }
    }

    /// Sets the filtering mode while preserving the filter itself.
    #[must_use]
    pub const fn with_filter_config(mut self, config: TreeFilterConfig) -> Self {
        self.filter_config = config;
        self
    }

    /// Sets how roots are displayed.
    #[must_use]
    pub const fn with_root_visibility(mut self, visibility: TreeRootVisibility) -> Self {
        self.root_visibility = visibility;
        self
    }

    /// Sets the selection fallback policy.
    #[must_use]
    pub const fn with_selection_fallback(mut self, fallback: TreeSelectionFallback) -> Self {
        self.selection_fallback = fallback;
        self
    }

    /// Returns the filter policy.
    #[must_use]
    pub const fn filter(&self) -> &F {
        &self.filter.value
    }

    /// Returns the mutable filter and automatically advances its revision.
    pub const fn filter_mut(&mut self) -> &mut F {
        self.filter.value_mut()
    }

    /// Returns the sibling sorting policy.
    #[must_use]
    pub const fn sort(&self) -> &S {
        &self.sort.value
    }

    /// Returns the mutable sorting policy and automatically advances its revision.
    pub const fn sort_mut(&mut self) -> &mut S {
        self.sort.value_mut()
    }

    /// Explicitly advances the filter revision, for example after captured data changes.
    pub const fn touch_filter(&mut self) {
        self.filter.touch();
    }

    /// Explicitly advances the sort revision, for example after captured data changes.
    pub const fn touch_sort(&mut self) {
        self.sort.touch();
    }

    /// Changes the filtering mode while preserving the filter itself.
    pub fn set_filter_config(&mut self, config: TreeFilterConfig) -> bool {
        if self.filter_config == config {
            return false;
        }
        self.filter_config = config;
        true
    }

    /// Changes how roots are displayed.
    pub fn set_root_visibility(&mut self, visibility: TreeRootVisibility) -> bool {
        let changed = self.root_visibility != visibility;
        self.root_visibility = visibility;
        changed
    }

    /// Changes the selection fallback policy.
    pub fn set_selection_fallback(&mut self, fallback: TreeSelectionFallback) -> bool {
        let changed = self.selection_fallback != fallback;
        self.selection_fallback = fallback;
        changed
    }

    /// Returns the current filtering mode.
    #[must_use]
    pub const fn filter_config(&self) -> TreeFilterConfig {
        self.filter_config
    }

    /// Returns the current root display mode.
    #[must_use]
    pub const fn root_visibility(&self) -> TreeRootVisibility {
        self.root_visibility
    }

    /// Returns the current selection fallback policy.
    #[must_use]
    pub const fn selection_fallback(&self) -> TreeSelectionFallback {
        self.selection_fallback
    }

    /// Returns the current filter-data revision.
    #[must_use]
    pub const fn filter_revision(&self) -> TreeRevision {
        self.filter.revision
    }

    /// Returns the current sort-data revision.
    #[must_use]
    pub const fn sort_revision(&self) -> TreeRevision {
        self.sort.revision
    }

    pub(crate) const fn filter_generation(&self) -> TreeRevision {
        self.filter.generation
    }

    pub(crate) const fn sort_generation(&self) -> TreeRevision {
        self.sort.generation
    }
}

impl Default for TreeQuery {
    fn default() -> Self {
        Self::new()
    }
}
#[derive(Clone, Debug)]
struct QueryPolicy<P> {
    value: P,
    revision: TreeRevision,
    generation: TreeRevision,
}

impl<P> QueryPolicy<P> {
    const fn new(value: P, revision: TreeRevision) -> Self {
        Self {
            value,
            revision,
            generation: TreeRevision::INITIAL,
        }
    }

    fn replacement(value: P, revision: TreeRevision) -> Self {
        Self {
            value,
            revision,
            generation: next_query_policy_generation(),
        }
    }

    const fn value_mut(&mut self) -> &mut P {
        self.revision.advance();
        &mut self.value
    }

    const fn touch(&mut self) {
        self.revision.advance();
    }
}

/// The minimal contract for a tree or forest data source.
///
/// The data must form a real tree without cycles or shared children. Identifiers must be stable
/// and cheap to copy. Every identifier returned by `roots` or `children` must be valid for later
/// model method calls.
pub trait TreeModel {
    /// The node identifier type.
    type Id: Copy + Eq + Hash;

    /// Returns forest roots in deterministic order.
    fn roots(&self) -> impl Iterator<Item = Self::Id> + '_;

    /// Returns the node's child state and loaded children.
    fn children(&self, id: Self::Id) -> TreeChildren<'_, Self::Id>;

    /// Returns the revision of the model structure and display data.
    fn revision(&self) -> TreeRevision;

    /// Returns an approximate number of available nodes.
    fn size_hint(&self) -> usize {
        0
    }
}

/// A node visibility filter.
pub trait TreeFilter<T: TreeModel> {
    /// Returns `true` when the node directly matches the filter.
    fn is_match(&self, model: &T, id: T::Id) -> bool;
}

impl<T, F> TreeFilter<T> for F
where
    T: TreeModel,
    F: Fn(&T, T::Id) -> bool,
{
    #[inline]
    fn is_match(&self, model: &T, id: T::Id) -> bool {
        self(model, id)
    }
}

/// A policy for sorting sibling nodes.
pub trait TreeSort<T: TreeModel> {
    /// Compares two sibling nodes.
    fn compare(&self, model: &T, left: T::Id, right: T::Id) -> Ordering;

    /// Returns `true` when sorting should be applied.
    fn is_enabled(&self) -> bool {
        true
    }
}

impl<T, F> TreeSort<T> for F
where
    T: TreeModel,
    F: Fn(&T, T::Id, T::Id) -> Ordering,
{
    fn compare(&self, model: &T, left: T::Id, right: T::Id) -> Ordering {
        self(model, left, right)
    }
}

fn next_query_policy_generation() -> TreeRevision {
    TreeRevision::new(NEXT_QUERY_POLICY_GENERATION.fetch_add(1, AtomicOrdering::Relaxed))
}