app/models/coupdoeil/popover/option/placement.rb



# frozen_string_literal: true

module Coupdoeil
  class Popover
    class Option
      class Placement < Coupdoeil::Popover::Option
        self.bit_size = 4 * 4

        VALUES = [
          "auto",
          ["top", "top-start", "top-end"],
          ["right", "right-start", "right-end"],
          ["bottom", "bottom-start", "bottom-end"],
          ["left", "left-start", "left-end"],
        ].flatten.freeze
        INDEX_BY_VALUES = VALUES.each_with_index.to_h.with_indifferent_access.freeze

        class << self
          def parse(value)
            values = value.to_s.split(",")
            4.times.sum do |index|
              next 0 unless (placement = values[index])

              placement.strip!
              placement_index = INDEX_BY_VALUES[placement]
              placement_index << (index * 4)
            end
          end
        end

        def validate!
          values = value.to_s.split(",")

          values.each do |placement_value|
            next if placement_value.strip.in?(VALUES)

            values_sentence = VALUES.to_sentence(last_word_connector: " or ")
            raise_invalid_option("Value must be one of: #{values_sentence}")
          end
        end
      end
    end
  end
end