formatter.rb 1.85 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6
require 'singleton'

class Formatter
  include Singleton
Eugen Rochko's avatar
Eugen Rochko committed
7
  include RoutingHelper
8 9 10 11 12

  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::SanitizeHelper

  def format(status)
13
    return reformat(status.content) unless status.local?
14 15 16

    html = status.text
    html = encode(html)
17
    html = simple_format(html, sanitize: false)
18 19
    html = link_urls(html)
    html = link_mentions(html, status.mentions)
Eugen Rochko's avatar
Eugen Rochko committed
20
    html = link_hashtags(html)
21

22
    html.html_safe # rubocop:disable Rails/OutputSafety
23 24
  end

25 26 27 28 29 30 31 32 33 34
  def reformat(html)
    sanitize(html, tags: %w(a br p), attributes: %w(href rel))
  end

  def simplified_format(account)
    return reformat(account.note) unless account.local?

    html = encode(account.note)
    html = link_urls(html)

35
    html.html_safe # rubocop:disable Rails/OutputSafety
36 37 38 39 40 41 42 43 44
  end

  private

  def encode(html)
    HTMLEntities.new.encode(html)
  end

  def link_urls(html)
45 46 47
    auto_link(html, link: :urls, html: { rel: 'nofollow noopener' }) do |text|
      truncate(text.gsub(/\Ahttps?:\/\/(www\.)?/, ''), length: 30)
    end
48 49 50 51 52
  end

  def link_mentions(html, mentions)
    html.gsub(Account::MENTION_RE) do |match|
      acct    = Account::MENTION_RE.match(match)[1]
Eugen Rochko's avatar
Eugen Rochko committed
53
      mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
54

55
      mention.nil? ? match : mention_html(match, mention.account)
56 57 58
    end
  end

Eugen Rochko's avatar
Eugen Rochko committed
59 60 61 62 63 64 65 66
  def link_hashtags(html)
    html.gsub(Tag::HASHTAG_RE) do |match|
      hashtag_html(match)
    end
  end

  def hashtag_html(match)
    prefix, affix = match.split('#')
Eugen Rochko's avatar
Eugen Rochko committed
67
    "#{prefix}<a href=\"#{tag_url(affix.downcase)}\" class=\"mention hashtag\">#<span>#{affix}</span></a>"
Eugen Rochko's avatar
Eugen Rochko committed
68 69
  end

70
  def mention_html(match, account)
71
    "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"h-card u-url p-nickname mention\">@<span>#{account.username}</span></a>"
72 73
  end
end