83 lines
1.8 KiB
Ruby
83 lines
1.8 KiB
Ruby
# frozen_string_literal: true
|
||
|
||
module Repubmark
|
||
module Elems
|
||
class List < Base
|
||
parents :Canvas, :ListItem
|
||
|
||
def initialize(parent, links:, ordered:)
|
||
super parent
|
||
|
||
@links = !!links
|
||
@ordered = !!ordered
|
||
|
||
@items = []
|
||
end
|
||
|
||
#################
|
||
# Basic methods #
|
||
#################
|
||
|
||
def word_count = @items.sum(&:word_count)
|
||
|
||
def to_html
|
||
[
|
||
"<#{tag_name}>\n",
|
||
*@items.map(&:to_html),
|
||
"</#{tag_name}>\n",
|
||
].join.freeze
|
||
end
|
||
|
||
def to_gemtext = @items.map(&:to_gemtext).join
|
||
|
||
##################
|
||
# Helper methods #
|
||
##################
|
||
|
||
def level = parent.instance_of?(ListItem) ? parent.level + 1 : 0
|
||
|
||
def items_count = @items.count
|
||
|
||
def unicode_decor
|
||
return if level <= 1
|
||
|
||
"#{parent.unicode_decor_parent}#{parent.last? ? '⠀ ' : '│ '}"
|
||
end
|
||
|
||
###################
|
||
# Builder methods #
|
||
###################
|
||
|
||
def item(...) = @links ? item_links(...) : item_nolinks(...)
|
||
|
||
private
|
||
|
||
def parent=(parent)
|
||
unless parent.instance_of?(Canvas) || parent.instance_of?(ListItem)
|
||
raise TypeError,
|
||
"Expected #{Canvas} or #{ListItem}, got #{parent.class}"
|
||
end
|
||
|
||
@parent = parent
|
||
end
|
||
|
||
def tag_name = @ordered ? 'ol' : 'ul'
|
||
|
||
def item_nolinks
|
||
list_item = ListItem.new self, @items.count
|
||
@items << list_item
|
||
yield list_item
|
||
nil
|
||
end
|
||
|
||
def item_links(ref_url, ref_title = nil)
|
||
titled_ref = TitledRef.new ref_url, ref_title
|
||
list_item = ListItem.new self, @items.count, titled_ref
|
||
@items << list_item
|
||
yield list_item if block_given?
|
||
nil
|
||
end
|
||
end
|
||
end
|
||
end
|