Class: Pdfrb::Layout::ColumnBox

Inherits:
Box
  • Object
show all
Defined in:
lib/pdfrb/layout/column_box.rb

Overview

Lays out children into N columns of equal width separated by gutters. Children flow top-to-bottom in column 1, then wrap to column 2 when column 1 fills, etc.

Instance Attribute Summary collapse

Attributes inherited from Box

#height, #style, #width

Instance Method Summary collapse

Methods inherited from Box

#draw, #supports_position_flow?

Constructor Details

#initialize(children:, columns: 2, gutter: 20) ⇒ ColumnBox

Returns a new instance of ColumnBox.



11
12
13
14
15
16
# File 'lib/pdfrb/layout/column_box.rb', line 11

def initialize(children:, columns: 2, gutter: 20, **)
  super(**)
  @children = children
  @columns = columns.to_i
  @gutter = gutter.to_f
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



9
10
11
# File 'lib/pdfrb/layout/column_box.rb', line 9

def children
  @children
end

#columnsObject (readonly)

Returns the value of attribute columns.



9
10
11
# File 'lib/pdfrb/layout/column_box.rb', line 9

def columns
  @columns
end

#gutterObject (readonly)

Returns the value of attribute gutter.



9
10
11
# File 'lib/pdfrb/layout/column_box.rb', line 9

def gutter
  @gutter
end

Instance Method Details

#draw_content(canvas, x, y) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/pdfrb/layout/column_box.rb', line 44

def draw_content(canvas, x, y)
  idx = 0
  @column_heights.each_with_index do |_h, col_idx|
    col_x = x + (col_idx * (@column_width + @gutter))
    col_y = y
    while idx < @children.size
      child = @children[idx]
      break if child_height_in_column(idx, col_idx).nil?

      child.draw(canvas, col_x, col_y)
      col_y -= child.height
      idx += 1
    end
  end
end

#empty?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/pdfrb/layout/column_box.rb', line 60

def empty?
  @children.empty?
end

#fit?(available_width, available_height) ⇒ Boolean

Returns:

  • (Boolean)


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
# File 'lib/pdfrb/layout/column_box.rb', line 18

def fit?(available_width, available_height)
  column_w = (available_width - (@gutter * (@columns - 1))) / @columns
  @child_heights = []
  remaining_children = @children.dup
  col_heights = Array.new(@columns, 0.0)

  @columns.times do |col_idx|
    col_remaining = available_height
    while remaining_children.any?
      child = remaining_children.first
      if child.fit?(column_w, col_remaining)
        col_heights[col_idx] += child.height
        col_remaining -= child.height
        remaining_children.shift
      else
        break
      end
    end
  end
  @column_width = column_w
  @column_heights = col_heights
  @width = available_width
  @height = available_height
  remaining_children.empty?
end