Class: Canopus::Project::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/canopus/project/tree.rb,
sig/workspace_services.rbs

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(files, expanded: Set.new) ⇒ Tree

Returns a new instance of Tree.

Parameters:

  • files (Array[String])
  • expanded: (Set[String]) (defaults to: Set.new)


9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/canopus/project/tree.rb', line 9

def initialize(files, expanded: Set.new)
  @expanded, @children = expanded, Hash.new { |hash, key| hash[key] = {} }
  files.each do |path|
    parent = ""
    pieces = path.split("/")
    pieces.each_with_index do |piece, index|
      current = parent.empty? ? piece : "#{parent}/#{piece}"
      @children[parent][piece] = [current, index < pieces.length - 1 || path.end_with?("/")]
      parent = current
    end
  end
  @children.transform_values! { |children| children.sort_by { |name, (_, directory)| [directory ? 0 : 1, name.downcase, name] } }
end

Instance Attribute Details

#expanded ⇒ Set[String] (readonly)

Returns the value of attribute expanded.

Returns:

  • (Set[String])


8
9
10
# File 'lib/canopus/project/tree.rb', line 8

def expanded
  @expanded
end

Instance Method Details

#reveal(path) ⇒ void

This method returns an undefined value.

Parameters:

  • path (String)


26
27
28
29
30
# File 'lib/canopus/project/tree.rb', line 26

def reveal(path)
  pieces = path.split("/")[0...-1]
  pieces.length.times { |index| @expanded.add(pieces.first(index + 1).join("/")) }
  @visible = nil
end

#toggle(path) ⇒ void

This method returns an undefined value.

Parameters:

  • path (String)


22
23
24
25
# File 'lib/canopus/project/tree.rb', line 22

def toggle(path)
  @expanded.include?(path) ? @expanded.delete(path) : @expanded.add(path)
  @visible = nil
end

#visible ⇒ Array[Entry]

Returns:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/canopus/project/tree.rb', line 31

def visible
  @visible ||= begin
    output, stack = [], [["", 0]]
    until stack.empty?
      path, depth = stack.pop
      @children.fetch(path, []).reverse_each do |name, (child, directory)|
        stack << [Entry.new(child, name, depth, directory, @expanded.include?(child)), nil]
      end if path.is_a?(String)
      if path.is_a?(Entry)
        output << path
        stack << [path.path, path.depth + 1] if path.directory && path.expanded
      end
    end
    output.freeze
  end
end