demarches-normaliennes/app/components/editable_champ/section_component.rb
2024-03-04 10:59:11 +01:00

58 lines
1.4 KiB
Ruby

class EditableChamp::SectionComponent < ApplicationComponent
include ApplicationHelper
include TreeableConcern
def initialize(nodes: nil, types_de_champ: nil, row_id: nil, champs_by_stable_id_with_row:)
nodes ||= to_tree(types_de_champ:)
@champs_by_stable_id_with_row = champs_by_stable_id_with_row
@row_id = row_id
@nodes = to_fieldset(nodes:)
end
def render_within_fieldset?
first_champ_is_an_header_section?
end
def header_section
node = @nodes.first
champ_for_type_de_champ(node) if node.is_a?(TypeDeChamp) && node.header_section?
end
def splitted_tail
tail.map { split_section_champ(_1) }
end
def tail
return @nodes if !first_champ_is_an_header_section?
_, *rest_of_champ = @nodes
rest_of_champ
end
def tag_for_depth
"h#{header_section.level + 1}"
end
def split_section_champ(node)
case node
when EditableChamp::SectionComponent
[node, nil]
else
[nil, champ_for_type_de_champ(node)]
end
end
private
def to_fieldset(nodes:)
nodes.map { _1.is_a?(Array) ? EditableChamp::SectionComponent.new(nodes: _1, row_id: @row_id, champs_by_stable_id_with_row: @champs_by_stable_id_with_row) : _1 }
end
def first_champ_is_an_header_section?
header_section.present?
end
def champ_for_type_de_champ(type_de_champ)
@champs_by_stable_id_with_row[[@row_id, type_de_champ.stable_id].compact]
end
end