Narabe.Tree (Narabe v0.1.0)

Copy Markdown View Source

A tree's items, flat, as a page shows them: each after its parent, with its level and its place among its siblings.

Narabe.Components.tree/1 and tree_picker/1 take the items as the database has them, a flat list with a parent id each, in their order (Narabe.Ecto.ordered/2), and lay them out with rows/2.

Summary

Types

A row of a tree.

Functions

The rows of a tree, in the order a page shows them: depth first, each item's children after it, siblings in the order of items.

Types

row()

@type row() :: %{
  item: term(),
  id: term(),
  parent: term(),
  level: pos_integer(),
  index: non_neg_integer(),
  count: pos_integer(),
  children: boolean()
}

A row of a tree.

Functions

rows(items, opts \\ [])

@spec rows([term()], keyword()) :: [row()]

The rows of a tree, in the order a page shows them: depth first, each item's children after it, siblings in the order of items.

An item whose parent is not among the items is at the top: a tree may show a branch, or the levels loaded so far.

Options:

  • :id - the item's id: a key or a function (:id).
  • :parent - its parent's id: a key or a function (:parent_id).
  • :children - whether it has children that are not loaded yet: a key or a function, or nil (none). An item with loaded children has children either way.

Examples

iex> items = [%{id: 1, parent_id: nil}, %{id: 2, parent_id: nil}, %{id: 3, parent_id: 1}]
iex> for row <- Narabe.Tree.rows(items), do: {row.id, row.level, row.index, row.count, row.children}
[{1, 1, 0, 2, true}, {3, 2, 0, 1, false}, {2, 1, 1, 2, false}]