Struct Tree

Source
pub struct Tree { /* private fields */ }
Expand description

A tree node that can contain both a value and child nodes.

Tree is the main building block for creating hierarchical tree structures. Unlike Leaf nodes, trees can have children and support advanced features like custom styling, enumerators, indenters, and offset-based child filtering.

§Key Features

  • Hierarchical structure: Can contain child nodes forming a tree
  • Custom styling: Support for root, item, and enumerator styling
  • Custom rendering: Override enumerators and indenters per-node
  • Child filtering: Use offsets to display only a subset of children
  • Builder pattern: Fluent API for easy tree construction

§Examples

use lipgloss_tree::Tree;

let tree = Tree::new()
    .root("My Project")
    .child(vec![
        "file1.txt".into(),
        "file2.txt".into(),
        Tree::new()
            .root("subfolder")
            .child(vec!["nested.txt".into()])
            .into(),
    ]);

println!("{}", tree);

This creates a tree structure like:

My Project
├── file1.txt
├── file2.txt
├── subfolder
│   └── nested.txt

Implementations§

Source§

impl Tree

Source

pub fn new() -> Self

Creates a new empty tree with default settings.

The tree starts with no root value, no children, and default rendering settings.

§Examples
use lipgloss_tree::{Tree, Node, Children};

let tree = Tree::new();
assert!(tree.value().is_empty());
assert_eq!(tree.children().length(), 0);
Source

pub fn root(self, root: impl Into<String>) -> Self

Sets the root value of this tree.

The root value is displayed at the top of the tree when rendered. If no root is set, the tree will start directly with its children.

§Arguments
  • root - The root value (anything convertible to String)
§Examples
use lipgloss_tree::{Tree, Node};

let tree = Tree::new().root("My Root");
assert_eq!(tree.value(), "My Root");
Source

pub fn hide(self, hide: bool) -> Self

Sets the visibility of this tree.

Hidden trees are not rendered in the output, but their children may still be visible depending on the rendering context.

§Arguments
  • hide - true to hide this tree, false to show it
§Examples
use lipgloss_tree::{Tree, Node};

let hidden_tree = Tree::new().root("Hidden").hide(true);
assert!(hidden_tree.hidden());
Source

pub fn offset(self, start: usize, end: usize) -> Self

Sets the offset range for displaying children.

This allows you to display only a subset of the tree’s children, which is useful for pagination or filtering large trees.

§Arguments
  • start - Starting index (inclusive) for child display
  • end - Ending index (exclusive) for child display
§Examples
use lipgloss_tree::Tree;

let tree = Tree::new()
    .child(vec!["A".into(), "B".into(), "C".into(), "D".into()])
    .offset(1, 3); // Will only show children B and C
§Note

If start > end, the values will be swapped. If end exceeds the number of children, it will be clamped to the children count.

Source

pub fn child(self, children: Vec<Box<dyn Node>>) -> Self

Adds multiple children to this tree.

This method accepts a vector of boxed nodes and appends them all to the tree’s children collection. It matches Go’s Child(...any) method for API compatibility.

§Arguments
  • children - A vector of boxed nodes to add as children
§Examples
use lipgloss_tree::{Tree, Node, Children};

let tree = Tree::new()
    .root("Parent")
    .child(vec![
        "Child 1".into(),
        "Child 2".into(),
        Tree::new().root("Nested").into(),
    ]);

assert_eq!(tree.children().length(), 3);
Source

pub fn add_child(self, child: impl Into<Box<dyn Node>>) -> Self

Adds a single child to this tree.

This is a convenience method for adding one child at a time, accepting anything that can be converted into a boxed node.

§Arguments
  • child - A node (or convertible value) to add as a child
§Examples
use lipgloss_tree::{Tree, Leaf, Node, Children};

let tree = Tree::new()
    .root("Parent")
    .add_child("String child")
    .add_child(Leaf::new("Leaf child", false))
    .add_child(Tree::new().root("Tree child"));

assert_eq!(tree.children().length(), 3);
Source

pub fn enumerator(self, enumerator: Enumerator) -> Self

Sets a custom enumerator function for this tree.

The enumerator generates branch characters (like ├──, └──) based on each child’s position. This overrides the default enumerator for this tree.

§Arguments
  • enumerator - A function that takes (children, index) and returns a string
§Examples
use lipgloss_tree::Tree;

let tree = Tree::new()
    .root("Custom")
    .enumerator(|children, i| {
        if i == children.length() - 1 {
            "╰──".to_string()  // Rounded last branch
        } else {
            "├──".to_string()  // Standard branch
        }
    })
    .child(vec!["A".into(), "B".into()]);
Source

pub fn indenter(self, indenter: Indenter) -> Self

Sets a custom indenter function for this tree.

The indenter generates indentation strings for nested child content. This overrides the default indenter for this tree.

§Arguments
  • indenter - A function that takes (children, index) and returns an indentation string
§Examples
use lipgloss_tree::Tree;

let tree = Tree::new()
    .indenter(|children, i| {
        if i == children.length() - 1 {
            "    ".to_string()  // Spaces for last child
        } else {
            "│   ".to_string()  // Vertical line for continuing
        }
    });
Source

pub fn root_style(self, style: Style) -> Self

Sets the styling for the root value of this tree.

§Arguments
  • style - The lipgloss Style to apply to the root
§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .root("Styled Root")
    .root_style(Style::new().bold(true).foreground("blue"));
Source

pub fn item_style(self, style: Style) -> Self

Sets the base style applied to all child items.

This style is applied to item content before any style functions.

§Arguments
  • style - The lipgloss Style to apply to all items
§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["Item 1".into(), "Item 2".into()])
    .item_style(Style::new().foreground("green"));
Source

pub fn enumerator_style(self, style: Style) -> Self

Sets the base style applied to all enumerators (branch characters).

This style is applied to enumerators before any style functions.

§Arguments
  • style - The lipgloss Style to apply to all enumerators
§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["Item 1".into(), "Item 2".into()])
    .enumerator_style(Style::new().foreground("yellow"));
Source

pub fn item_style_func(self, func: StyleFunc) -> Self

Sets a dynamic styling function for child items.

The function receives the children collection and the current index, allowing for context-aware styling decisions.

§Arguments
  • func - A function that takes (children, index) and returns a Style
§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["First".into(), "Second".into(), "Third".into()])
    .item_style_func(|_children, i| {
        if i % 2 == 0 {
            Style::new().foreground("red")
        } else {
            Style::new().foreground("blue")
        }
    });
Source

pub fn enumerator_style_func(self, func: StyleFunc) -> Self

Sets a dynamic styling function for enumerators (branch characters).

The function receives the children collection and the current index, allowing for context-aware styling of branch characters.

§Arguments
  • func - A function that takes (children, index) and returns a Style
§Examples
use lipgloss_tree::{Tree, Children};
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["Item 1".into(), "Item 2".into()])
    .enumerator_style_func(|children, i| {
        if i == children.length() - 1 {
            Style::new().foreground("red")   // Last item in red
        } else {
            Style::new().foreground("green") // Others in green
        }
    });
Source

pub fn get_enumerator(&self) -> Option<&Enumerator>

Returns the custom enumerator function for this tree.

The enumerator function generates branch characters (like ├──, └──) for this tree’s children based on their position in the collection. This allows for custom tree rendering styles.

§Returns

An optional reference to the enumerator function. Returns Some if a custom enumerator has been set with Tree::enumerator, or None if using the default enumerator.

§Examples
use lipgloss_tree::Tree;

let tree = Tree::new()
    .enumerator(|children, i| {
        if i == children.length() - 1 {
            "└──".to_string()
        } else {
            "├──".to_string()
        }
    });

assert!(tree.get_enumerator().is_some());
Source

pub fn get_indenter(&self) -> Option<&Indenter>

Returns the custom indenter function for this tree.

The indenter function generates indentation strings for nested content under this tree’s children. This determines how deeply nested items are visually offset in the rendered output.

§Returns

An optional reference to the indenter function. Returns Some if a custom indenter has been set with Tree::indenter, or None if using the default indenter.

§Examples
use lipgloss_tree::Tree;

let tree = Tree::new()
    .indenter(|children, i| {
        if i == children.length() - 1 {
            "    ".to_string()  // Spaces for last child
        } else {
            "│   ".to_string()  // Vertical line continuing
        }
    });

assert!(tree.get_indenter().is_some());
Source

pub fn get_root_style(&self) -> Option<&Style>

Returns the styling configuration for this tree’s root value.

The root style is applied to the tree’s main value when rendered, allowing for custom colors, formatting, and visual effects on the top-level tree node.

§Returns

An optional reference to the root style. Returns Some if a custom style has been set with Tree::root_style, or None if using the default (unstyled) appearance.

§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .root("Project Root")
    .root_style(Style::new().bold(true).foreground("blue"));

assert!(tree.get_root_style().is_some());
Source

pub fn get_item_style_func(&self) -> Option<&StyleFunc>

Returns the dynamic styling function for this tree’s child items.

The item style function provides context-aware styling based on each child’s position within the tree. It receives the children collection and the current child’s index, allowing for complex styling logic.

§Returns

An optional reference to the item style function. Returns Some if a custom function has been set with Tree::item_style_func, or None if using the default (no dynamic styling).

§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["Item 1".into(), "Item 2".into()])
    .item_style_func(|_children, i| {
        if i % 2 == 0 {
            Style::new().foreground("red")
        } else {
            Style::new().foreground("blue")
        }
    });

assert!(tree.get_item_style_func().is_some());
Source

pub fn get_enumerator_style_func(&self) -> Option<&StyleFunc>

Returns the dynamic styling function for this tree’s branch characters.

The enumerator style function provides context-aware styling for the branch characters (like ├──, └──) based on each child’s position. It receives the children collection and current index for styling decisions.

§Returns

An optional reference to the enumerator style function. Returns Some if a custom function has been set with Tree::enumerator_style_func, or None if using the default (no dynamic styling).

§Examples
use lipgloss_tree::{Tree, Children};
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["First".into(), "Last".into()])
    .enumerator_style_func(|children, i| {
        if i == children.length() - 1 {
            Style::new().foreground("red")    // Last item
        } else {
            Style::new().foreground("green")  // Others
        }
    });

assert!(tree.get_enumerator_style_func().is_some());
Source

pub fn get_item_style(&self) -> Option<&Style>

Returns the base styling configuration for this tree’s child items.

The item style is applied to all child item content before any dynamic style functions are applied. This provides a consistent base appearance for all children in the tree.

§Returns

An optional reference to the base item style. Returns Some if a custom style has been set with Tree::item_style, or None if using the default (unstyled) appearance.

§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["Item 1".into(), "Item 2".into()])
    .item_style(Style::new().foreground("green").italic(true));

assert!(tree.get_item_style().is_some());
Source

pub fn get_enumerator_style(&self) -> Option<&Style>

Returns the base styling configuration for this tree’s branch characters.

The enumerator style is applied to all branch characters (like ├──, └──) before any dynamic style functions are applied. This provides consistent base styling for all tree branch elements.

§Returns

An optional reference to the base enumerator style. Returns Some if a custom style has been set with Tree::enumerator_style, or None if using the default (unstyled) appearance.

§Examples
use lipgloss_tree::Tree;
use lipgloss::Style;

let tree = Tree::new()
    .child(vec!["Item 1".into(), "Item 2".into()])
    .enumerator_style(Style::new().foreground("yellow").bold(true));

assert!(tree.get_enumerator_style().is_some());

Trait Implementations§

Source§

impl Clone for Tree

Source§

fn clone(&self) -> Tree

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for Tree

Source§

fn default() -> Self

Creates a default tree instance.

Equivalent to Tree::new() - creates an empty tree with no root value, no children, and default rendering settings.

Source§

impl Display for Tree

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Tree> for Box<dyn Node>

Source§

fn from(tree: Tree) -> Self

Converts to this type from the input type.
Source§

impl Node for Tree

Source§

fn value(&self) -> String

Returns the string value of this node. Read more
Source§

fn children(&self) -> Box<dyn Children>

Returns the children of this node. Read more
Source§

fn hidden(&self) -> bool

Returns whether this node is hidden from rendering. Read more
Source§

fn set_hidden(&mut self, hidden: bool)

Sets the visibility state of this node. Read more
Source§

fn set_value(&mut self, value: String)

Updates the value of this node. Read more
Source§

fn get_enumerator(&self) -> Option<&Enumerator>

Returns the custom enumerator function for this node, if any. Read more
Source§

fn get_indenter(&self) -> Option<&Indenter>

Returns the custom indenter function for this node, if any. Read more
Source§

fn get_item_style(&self) -> Option<&Style>

Returns the base item style for this node, if any. Read more
Source§

fn get_enumerator_style(&self) -> Option<&Style>

Returns the base enumerator style for this node, if any. Read more
Source§

fn get_item_style_func(&self) -> Option<&StyleFunc>

Returns the item style function for this node, if any. Read more
Source§

fn get_enumerator_style_func(&self) -> Option<&StyleFunc>

Returns the enumerator style function for this node, if any. Read more

Auto Trait Implementations§

§

impl Freeze for Tree

§

impl !RefUnwindSafe for Tree

§

impl !Send for Tree

§

impl !Sync for Tree

§

impl Unpin for Tree

§

impl !UnwindSafe for Tree

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T> CloneNode for T
where T: 'static + Node + Clone,

Source§

fn clone_node(&self) -> Box<dyn Node>

Creates a cloned copy of this node as a boxed trait object. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.