From 7a993324342d5542dcb40902eed097f7eaac3f1b Mon Sep 17 00:00:00 2001 From: Javan Makhmali Date: Wed, 3 Oct 2018 12:46:05 -0400 Subject: WIP: Image gallery support --- lib/action_text/attachment_gallery.rb | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 lib/action_text/attachment_gallery.rb (limited to 'lib/action_text/attachment_gallery.rb') diff --git a/lib/action_text/attachment_gallery.rb b/lib/action_text/attachment_gallery.rb new file mode 100644 index 0000000000..6f690551e6 --- /dev/null +++ b/lib/action_text/attachment_gallery.rb @@ -0,0 +1,62 @@ +module ActionText + class AttachmentGallery + include ActiveModel::Model + + class << self + def fragment_by_canonicalizing_attachment_galleries(content) + fragment_by_replacing_attachment_gallery_nodes(content) do |node| + "<#{TAG_NAME}>#{node.inner_html}" + 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) + Fragment.wrap(content).find_all(SELECTOR).select do |node| + node.children.all? do |child| + if child.text? + child.text =~ /\A(\n|\ )*\z/ + else + child.matches? ATTACHMENT_SELECTOR + end + end + end + end + + def from_node(node) + new(node) + end + end + + attr_reader :node + + def initialize(node) + @node = node + end + + def attachments + @attachments ||= node.css(ATTACHMENT_SELECTOR).map do |node| + ActionText::Attachment.from_node(node).with_full_attributes + end + end + + def size + attachments.size + end + + def inspect + "#<#{self.class.name} size=#{size.inspect}>" + end + + private + TAG_NAME = "div" + ATTACHMENT_SELECTOR = "#{ActionText::Attachment::SELECTOR}[presentation=gallery]" + SELECTOR = "#{TAG_NAME}:has(#{ATTACHMENT_SELECTOR} + #{ATTACHMENT_SELECTOR})" + end +end -- cgit v1.2.3