Class: Kward::SessionTreeRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/session_tree_renderer.rb

Overview

Terminal renderer for persisted session tree choices.

Instance Method Summary collapse

Constructor Details

#initialize(roots:, current_leaf_id:) ⇒ SessionTreeRenderer

Returns a new instance of SessionTreeRenderer.



10
11
12
13
# File 'lib/kward/session_tree_renderer.rb', line 10

def initialize(roots:, current_leaf_id:)
  @roots = roots
  @current_leaf_id = current_leaf_id
end

Instance Method Details

#itemsObject



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
# File 'lib/kward/session_tree_renderer.rb', line 15

def items
  active_path = session_tree_active_path(@roots, @current_leaf_id)
  tool_calls_by_id = session_tree_tool_calls(@roots)
  visible_roots = @roots.flat_map { |root| visible_session_tree_nodes(root) }
  multiple_roots = visible_roots.length > 1
  result = []

  walk = lambda do |node, indent, just_branched, show_connector, is_last, gutters, virtual_root_child|
    entry = node[:source]["entry"] || {}
    display_indent = multiple_roots ? [indent - 1, 0].max : indent
    prefix = session_tree_visual_prefix(display_indent, gutters, show_connector && !virtual_root_child, is_last, !node[:children].empty?)
    result << {
      entry: entry,
      label: session_tree_label(entry, node[:source], prefix, active_path.include?(entry["id"].to_s), tool_calls_by_id)
    }

    children = node[:children].sort_by { |child| session_tree_contains_active_path?(child, active_path) ? 0 : 1 }
    multiple_children = children.length > 1
    child_indent = if multiple_children
                     indent + 1
                   elsif just_branched && indent.positive?
                     indent + 1
                   else
                     indent
                   end
    connector_position = [display_indent - 1, 0].max
    child_gutters = show_connector && !virtual_root_child ? gutters + [{ position: connector_position, show: !is_last }] : gutters

    children.each_with_index do |child, index|
      walk.call(child, child_indent, multiple_children, multiple_children, index == children.length - 1, child_gutters, false)
    end
  end

  visible_roots.sort_by { |root| session_tree_contains_active_path?(root, active_path) ? 0 : 1 }.each_with_index do |root, index|
    walk.call(root, multiple_roots ? 1 : 0, multiple_roots, multiple_roots, index == visible_roots.length - 1, [], multiple_roots)
  end

  result
end