2018-10-08 17:44:25 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-10-03 12:46:05 -04:00
|
|
|
module ActionText
|
|
|
|
class AttachmentGallery
|
|
|
|
include ActiveModel::Model
|
|
|
|
|
2021-03-30 14:46:01 -04:00
|
|
|
TAG_NAME = "div"
|
|
|
|
private_constant :TAG_NAME
|
|
|
|
|
2018-10-03 12:46:05 -04:00
|
|
|
class << self
|
|
|
|
def fragment_by_canonicalizing_attachment_galleries(content)
|
|
|
|
fragment_by_replacing_attachment_gallery_nodes(content) do |node|
|
|
|
|
"<#{TAG_NAME}>#{node.inner_html}</#{TAG_NAME}>"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def fragment_by_replacing_attachment_gallery_nodes(content)
|
|
|
|
Fragment.wrap(content).update do |source|
|
|
|
|
find_attachment_gallery_nodes(source).each do |node|
|
|
|
|
node.replace(yield(node).to_s)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def find_attachment_gallery_nodes(content)
|
2021-03-30 14:46:01 -04:00
|
|
|
Fragment.wrap(content).find_all(selector).select do |node|
|
2018-10-03 12:46:05 -04:00
|
|
|
node.children.all? do |child|
|
|
|
|
if child.text?
|
2019-07-29 01:23:10 -04:00
|
|
|
/\A(\n|\ )*\z/.match?(child.text)
|
2018-10-03 12:46:05 -04:00
|
|
|
else
|
2021-03-30 14:46:01 -04:00
|
|
|
child.matches? attachment_selector
|
2018-10-03 12:46:05 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def from_node(node)
|
|
|
|
new(node)
|
|
|
|
end
|
2021-03-30 14:46:01 -04:00
|
|
|
|
|
|
|
def attachment_selector
|
|
|
|
"#{ActionText::Attachment.tag_name}[presentation=gallery]"
|
|
|
|
end
|
|
|
|
|
|
|
|
def selector
|
|
|
|
"#{TAG_NAME}:has(#{attachment_selector} + #{attachment_selector})"
|
|
|
|
end
|
2018-10-03 12:46:05 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
attr_reader :node
|
|
|
|
|
|
|
|
def initialize(node)
|
|
|
|
@node = node
|
|
|
|
end
|
|
|
|
|
|
|
|
def attachments
|
2021-03-30 14:46:01 -04:00
|
|
|
@attachments ||= node.css(ActionText::AttachmentGallery.attachment_selector).map do |node|
|
2018-10-03 12:46:05 -04:00
|
|
|
ActionText::Attachment.from_node(node).with_full_attributes
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def size
|
|
|
|
attachments.size
|
|
|
|
end
|
|
|
|
|
|
|
|
def inspect
|
|
|
|
"#<#{self.class.name} size=#{size.inspect}>"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|