]> git.openstreetmap.org Git - rails.git/blob - lib/rich_text.rb
Pretty-print URLs in linkify
[rails.git] / lib / rich_text.rb
1 # frozen_string_literal: true
2
3 module RichText
4   DESCRIPTION_MAX_LENGTH = 500
5   DESCRIPTION_WORD_BREAK_THRESHOLD_LENGTH = 450
6   URL_UNSAFE_CHARS = "[^\\w!#$%&'*+,./:;=?@_~^\\-]"
7
8   def self.new(format, text)
9     case format
10     when "html" then HTML.new(text || "")
11     when "markdown" then Markdown.new(text || "")
12     when "text" then Text.new(text || "")
13     end
14   end
15
16   class SimpleFormat
17     include ActionView::Helpers::TextHelper
18     include ActionView::Helpers::OutputSafetyHelper
19
20     def sanitize(text, _options = {})
21       Sanitize.clean(text, Sanitize::Config::OSM).html_safe
22     end
23   end
24
25   class Base < String
26     def image
27       nil
28     end
29
30     def image_alt
31       nil
32     end
33
34     def description
35       nil
36     end
37
38     def truncate_html(max_length = nil, img_length = 1000)
39       html_doc = to_html
40       return html_doc if max_length.nil?
41
42       doc = Nokogiri::HTML::DocumentFragment.parse(html_doc)
43       keep_or_discards = %w[p h1 h2 h3 h4 h5 h6 pre a table ul ol dl]
44       accumulated_length = 0
45       exceeded_node_parent = nil
46       truncated = false
47
48       doc.traverse do |node|
49         if accumulated_length >= max_length
50           if node == exceeded_node_parent
51             exceeded_node_parent = node.parent
52             node.remove if keep_or_discards.include?(node.name)
53           else
54             node.remove
55           end
56           next
57         end
58
59         next unless node.children.empty?
60
61         if node.text?
62           accumulated_length += node.text.length
63         elsif node.name == "img"
64           accumulated_length += img_length
65         end
66
67         if accumulated_length >= max_length
68           truncated = true
69           exceeded_node_parent = node.parent
70           node.remove
71         end
72       end
73
74       {
75         :truncated => truncated,
76         :html => doc.to_html.html_safe
77       }
78     end
79
80     protected
81
82     def simple_format(text)
83       SimpleFormat.new.simple_format(text, :dir => "auto")
84     end
85
86     def sanitize(text)
87       Sanitize.clean(text, Sanitize::Config::OSM).html_safe
88     end
89
90     def linkify(text, mode = :urls)
91       ERB::Util.html_escape(text)
92                .then { |html| expand_link_shorthands(html) }
93                .then { |html| expand_host_shorthands(html) }
94                .then { |html| auto_link(html, mode) }
95                .html_safe
96     end
97
98     private
99
100     def gsub_pairs_for_linkify_detection
101       Array
102         .wrap(Settings.linkify&.detection_rules)
103         .select { |rule| rule.path_template && rule.patterns.is_a?(Array) }
104         .flat_map do |rule|
105           expanded_path = "#{rule.host || "#{Settings.server_protocol}://#{Settings.server_url}"}/#{rule.path_template}"
106           rule.patterns
107               .select { |pattern| pattern.is_a?(String) }
108               .map { |pattern| [Regexp.new("(?<=^|#{URL_UNSAFE_CHARS})#{pattern}", Regexp::IGNORECASE), expanded_path] }
109         end
110     end
111
112     def expand_link_shorthands(text)
113       gsub_pairs_for_linkify_detection
114         .reduce(text) { |text, (pattern, replacement)| text.gsub(pattern, replacement) }
115     end
116
117     def expand_host_shorthands(text)
118       [
119         [Settings.linkify_hosts, Settings.linkify_hosts_replacement],
120         [Settings.linkify_wiki_hosts, Settings.linkify_wiki_hosts_replacement]
121       ]
122         .select { |hosts, replacement| replacement && hosts&.any? }
123         .reduce(text) do |text, (hosts, replacement)|
124           text.gsub(/(?<=^|#{URL_UNSAFE_CHARS})\b#{Regexp.escape(replacement)}/) do
125             "#{Settings.server_protocol}://#{hosts[0]}"
126           end
127         end
128     end
129
130     def auto_link(text, mode)
131       link_attr = 'rel="nofollow noopener noreferrer" dir="auto"'
132       Rinku.auto_link(text, mode, link_attr) { |url| format_link_text(url) }
133     end
134
135     def format_link_text(url)
136       url = shorten_host(url, Settings.linkify_hosts, Settings.linkify_hosts_replacement)
137       url = shorten_host(url, Settings.linkify_wiki_hosts, Settings.linkify_wiki_hosts_replacement) do |path|
138         path.sub(Regexp.new(Settings.linkify_wiki_optional_path_prefix || ""), "")
139       end
140       Array.wrap(Settings.linkify&.display_rules)
141            .select { |rule| rule.pattern && rule.replacement }
142            .reduce(url) { |url, rule| url.sub(Regexp.new(rule.pattern), rule.replacement) }
143     end
144
145     def shorten_host(url, hosts, hosts_replacement)
146       %r{^(https?://([^/]*))(.*)$}.match(url) do |m|
147         scheme_host, host, path = m.captures
148         if hosts&.include?(host)
149           path = yield(path) if block_given?
150           if hosts_replacement
151             "#{hosts_replacement}#{path}"
152           else
153             "#{scheme_host}#{path}"
154           end
155         end || url
156       end || url
157     end
158   end
159
160   class HTML < Base
161     def to_html
162       linkify(simple_format(self))
163     end
164
165     def to_text
166       to_s
167     end
168   end
169
170   class Markdown < Base
171     def to_html
172       linkify(sanitize(document.to_html), :all)
173     end
174
175     def to_text
176       to_s
177     end
178
179     def image
180       @image_element = first_image_element(document.root) unless defined? @image_element
181       @image_element.attr["src"] if @image_element
182     end
183
184     def image_alt
185       @image_element = first_image_element(document.root) unless defined? @image_element
186       @image_element.attr["alt"] if @image_element
187     end
188
189     def description
190       return @description if defined? @description
191
192       @description = first_truncated_text_content(document.root)
193     end
194
195     private
196
197     def document
198       return @document if @document
199
200       @document = Kramdown::Document.new(self)
201
202       should_get_dir_auto = lambda do |el|
203         dir_auto_types = [:p, :header, :codespan, :codeblock, :pre, :ul, :ol, :table, :dl, :math]
204         return true if dir_auto_types.include?(el.type)
205         return true if el.type == :a && el.children.length == 1 && el.children[0].type == :text && el.children[0].value == el.attr["href"]
206
207         false
208       end
209
210       add_dir = lambda do |element|
211         element.attr["dir"] ||= "auto" if should_get_dir_auto.call(element)
212         element.children.each(&add_dir)
213       end
214       add_dir.call(@document.root)
215
216       @document
217     end
218
219     def first_image_element(element)
220       return element if image?(element) && element.attr["src"].present?
221
222       element.children.find do |child|
223         nested_image = first_image_element(child)
224         break nested_image if nested_image
225       end
226     end
227
228     def first_truncated_text_content(element)
229       if paragraph?(element)
230         truncated_text_content(element)
231       else
232         element.children.find do |child|
233           text = first_truncated_text_content(child)
234           break text unless text.nil?
235         end
236       end
237     end
238
239     def truncated_text_content(element)
240       text = +""
241
242       append_text = lambda do |child|
243         if child.type == :text
244           text << child.value
245         else
246           child.children.each do |c|
247             append_text.call(c)
248             break if text.length > DESCRIPTION_MAX_LENGTH
249           end
250         end
251       end
252       append_text.call(element)
253
254       return nil if text.blank?
255
256       text_truncated_to_word_break = text.truncate(DESCRIPTION_MAX_LENGTH, :separator => /(?<!\s)\s+/)
257
258       if text_truncated_to_word_break.length >= DESCRIPTION_WORD_BREAK_THRESHOLD_LENGTH
259         text_truncated_to_word_break
260       else
261         text.truncate(DESCRIPTION_MAX_LENGTH)
262       end
263     end
264
265     def image?(element)
266       element.type == :img || (element.type == :html_element && element.value == "img")
267     end
268
269     def paragraph?(element)
270       element.type == :p || (element.type == :html_element && element.value == "p")
271     end
272   end
273
274   class Text < Base
275     def to_html
276       linkify(simple_format(ERB::Util.html_escape(self)))
277     end
278
279     def to_text
280       to_s
281     end
282   end
283 end