trix icon indicating copy to clipboard operation
trix copied to clipboard

Anyone figure out how to link uploaded images in Trix?

Open maxwell opened this issue 3 years ago • 4 comments

Reading through lots of history, I came across https://github.com/basecamp/trix/issues/561

anyone find a workaround to add a click through link for images using Trix/ActionText?

maxwell avatar May 24 '22 05:05 maxwell

Sorry I don't have an exact solution but on this GoRails Guide the user mentioned in a comment is a clickable link, which does not seem relevant, except that @excid3 does this by attaching the mentioned user as a Trix Attachment. Might be a mechanism to do this for the uploaded image??

jaykilleen avatar Jun 24 '22 02:06 jaykilleen

Interested on this aswell

silva96 avatar Aug 08 '22 19:08 silva96

Ok, this is kind of a gnarly hack we've come up with that really just works around the limitation. Rather than extending Trix, we are abusing the "caption" feature within Trix/ActionText. The general gist is that inside of the caption, we use XML-ish(🤮 ) tags, and parse them out in the html that gets generated. See our usage docs here

A bonus is that this works for alt text as well as images.

Like this:

image

The code needed to make this work:

1st: The "CaptionOptionParser"


class CaptionOptionParser
  def initialize(caption)
    @caption = caption
  end

  def url
    get_node('url')
  end

  def caption
    if node_caption = get_node('caption')
      return node_caption
    elsif url.blank? && alt.blank?
      @caption
    end
  end

  def alt
    get_node('alt')
  end

  private

  def get_node(name)
    if node = parser.css(name).first
      node.text
    end
  end

  def parser
    @parser ||= Nokogiri::HTML.fragment(@caption)
  end

end

Then, in our active_storage/action_text/_blob.html.erb


<% if local_assigns[:in_gallery] %>
  <% w, h = [800, 600] %>
<% else %>
  <% w, h = [1024, nil] %>
<% end %>
<% caption_option_parser = CaptionOptionParser.new(blob.caption) %>

<figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %> attachment--<%= blob.filename.extension %>">
  <% if blob.representable? %>
      
      <% image_tag_with_options = image_tag(blob.key,  alt: caption_option_parser.alt ) %>
      
      <% if caption_option_parser.url.present? %>
        <%= link_to image_tag_with_options, url %>
      <% else %>
        <%= image_tag_with_options %>
      <% end %>
  <% end %>

  <% if caption = caption_option_parser.caption %>
    <figcaption class="attachment__caption">
      <%= caption %>
    </figcaption>
  <% end %>
</figure>

It's kind of gross, but seems to get the job done.

maxwell avatar Aug 20 '22 00:08 maxwell