lib/prawn_html/tags/table.rb



# frozen_string_literal: true

module PrawnHtml
  module Tags
    class Table < Tag
      ELEMENTS = [:table].freeze

      def block?
        true
        puts "TABLE: I am a block, watch out for margin"
      end

      def custom_render(pdf, _context)
        @pdf_wrapper = pdf
      end

      def on_context_add(_context)
        @rows = []
        @col_widths = []
      end

      def add_col_width(width)
        @col_widths << width
      end

      def on_context_remove(_context)
        return if @pdf_wrapper.nil?

        cell_style = {
          borders: [:top, :bottom, :left, :right],
          border_width: 1,
          border_color: '000000',
          padding: 5,
          inline_format: true
        }

        # @pdf_wrapper.pdf.move_up(100)
        if @col_widths.any?
          @pdf_wrapper.table(@rows, column_widths: @col_widths, cell_style: cell_style)
        else
          # When providing column_widths, Prawn::Table transform nil into [] and raise error. Better not to provide it at all.
          @pdf_wrapper.table(@rows, cell_style: cell_style)
        end

        @rows = []
      end

      def add_row(row_data)
        @rows << row_data
      end
    end
  end
end