Fix up user links

This commit is contained in:
Carl Chenet 2017-05-20 15:26:11 +02:00
parent 9288c83ef5
commit 9aac91a71e

View file

@ -9,6 +9,11 @@ class Markdowner
exts = [:tagfilter, :autolink]
root = CommonMarker.render_doc(text.to_s, [:SMART], exts)
unless opts[:disable_profile_links]
walk_text_nodes(root) {|n| postprocess_text_node(n)}
end
ng = Nokogiri::HTML(root.to_html([:SAFE], exts))
# change <h1>, <h2>, etc. headings to just bold tags
@ -22,34 +27,51 @@ class Markdowner
# make links have rel=nofollow
ng.css("a").each do |h|
h[:rel] = "nofollow"
h[:rel] = "nofollow" unless h[:href].starts_with?("/")
end
# XXX: t.replace(tx) unescapes HTML, so disable for now. this probably
# needs to split text into separate nodes and then replace the @username
# with a proper 'a' node
if false
unless opts[:disable_profile_links]
# make @username link to that user's profile
ng.search("//text()").each do |t|
if t.parent && t.parent.name.downcase == "a"
# don't replace inside <a>s
next
end
tx = t.text.gsub(/\B\@([\w\-]+)/) do |u|
if User.exists?(:username => u[1 .. -1])
"<a href=\"/u/#{u[1 .. -1]}\">#{u}</a>"
else
u
end
end
t.replace(tx)
end
end
end
ng.at_css("body").inner_html
end
def self.walk_text_nodes(node, &block)
return if node.type == :link
return block.call(node) if node.type == :text
node.each do |child|
walk_text_nodes(child, &block)
end
end
def self.postprocess_text_node(node)
while node
return unless node.string_content =~ /\B(@[\w\-]+)/
before, user, after = $`, $1, $'
node.string_content = before
if User.exists?(:username => user[1..-1])
link = CommonMarker::Node.new(:link)
link.url = "/u/#{user[1..-1]}"
node.insert_after(link)
link_text = CommonMarker::Node.new(:text)
link_text.string_content = user
link.append_child(link_text)
node = link
else
node.string_content += user
end
if after.length > 0
remainder = CommonMarker::Node.new(:text)
remainder.string_content = after
node.insert_after(remainder)
node = remainder
else
node = nil
end
end
end
end