module Ecoportal module API class V2 class Page class Component class ChecklistField < Page::Component embeds_many :items, klass: "Ecoportal::API::V2::Page::Component::ChecklistItem", order_key: :weight def add_item(label:, pos: NOT_USED, before: NOT_USED, after: NOT_USED) itm_doc = items.stops.items_class.new_doc items.upsert!(itm_doc, pos: pos, before: before, after: after) do |item| item.label = label if prev = previous_item(item) item.weight = prev.weight end yield(item) if block_given? fix_item_weights! end end def ordered_items items.each_with_index.sort_by do |item, index| (item.weight >= 9999) ? [index, index] : [item.weight, index] end.map(&:first) end private def fix_item_weights! ordered_items.each_with_index do |item, index| item.weight = index end end def previous_item(value) itms = ordered_items pos = itms.index(value) - 1 return if pos < 0 itms[pos] end end end end end end end require 'ecoportal/api/v2/page/component/checklist_item'