BigW Consortium Gitlab

markup_helper.rb 7.31 KB
Newer Older
1 2
require 'nokogiri'

3
module MarkupHelper
4 5 6
  include ActionView::Helpers::TagHelper
  include ActionView::Context

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  def plain?(filename)
    Gitlab::MarkupHelper.plain?(filename)
  end

  def markup?(filename)
    Gitlab::MarkupHelper.markup?(filename)
  end

  def gitlab_markdown?(filename)
    Gitlab::MarkupHelper.gitlab_markdown?(filename)
  end

  def asciidoc?(filename)
    Gitlab::MarkupHelper.asciidoc?(filename)
  end

23
  # Use this in places where you would normally use link_to(gfm(...), ...).
24 25 26 27 28 29 30 31 32 33 34 35
  def link_to_markdown(body, url, html_options = {})
    return '' if body.blank?

    link_to_html(markdown(body, pipeline: :single_line), url, html_options)
  end

  def link_to_markdown_field(object, field, url, html_options = {})
    rendered_field = markdown_field(object, field)

    link_to_html(rendered_field, url, html_options)
  end

36 37 38 39
  # It solves a problem occurring with nested links (i.e.
  # "<a>outer text <a>gfm ref</a> more outer text</a>"). This will not be
  # interpreted as intended. Browsers will parse something like
  # "<a>outer text </a><a>gfm ref</a> more outer text" (notice the last part is
40
  # not linked any more). link_to_html corrects that. It wraps all parts to
41 42
  # explicitly produce the correct linking behavior (i.e.
  # "<a>outer text </a><a>gfm ref</a><a> more outer text</a>").
43 44
  def link_to_html(redacted, url, html_options = {})
    fragment = Nokogiri::HTML::DocumentFragment.parse(redacted)
45

46 47 48 49 50 51 52 53 54 55 56 57
    if fragment.children.size == 1 && fragment.children[0].name == 'a'
      # Fragment has only one node, and it's a link generated by `gfm`.
      # Replace it with our requested link.
      text = fragment.children[0].text
      fragment.children[0].replace(link_to(text, url, html_options))
    else
      # Traverse the fragment's first generation of children looking for pure
      # text, wrapping anything found in the requested link
      fragment.children.each do |node|
        next unless node.text?
        node.replace(link_to(node.text, url, html_options))
      end
58 59
    end

60 61 62 63 64
    # Add any custom CSS classes to the GFM-generated reference links
    if html_options[:class]
      fragment.css('a.gfm').add_class(html_options[:class])
    end

65
    fragment.to_html.html_safe
66
  end
randx committed
67

Douwe Maan committed
68 69 70 71 72 73
  # Return the first line of +text+, up to +max_chars+, after parsing the line
  # as Markdown.  HTML tags in the parsed output are not counted toward the
  # +max_chars+ limit.  If the length limit falls within a tag's contents, then
  # the tag contents are truncated without removing the closing tag.
  def first_line_in_markdown(text, max_chars = nil, options = {})
    md = markdown(text, options).strip
74

Douwe Maan committed
75
    truncate_visible(md, max_chars || md.length) if md.present?
76 77
  end

Douwe Maan committed
78
  def markdown(text, context = {})
79
    return '' unless text.present?
80

81
    context[:project] ||= @project
82
    html = markdown_unsafe(text, context)
83
    prepare_for_rendering(html, context)
84
  end
85

86 87
  def markdown_field(object, field)
    object = object.for_display if object.respond_to?(:for_display)
88 89
    redacted_field_html = object.try(:"redacted_#{field}_html")

90
    return '' unless object.present?
91
    return redacted_field_html if redacted_field_html
92

93
    html = Banzai.render_field(object, field)
94
    prepare_for_rendering(html, object.banzai_render_context(field))
95 96
  end

Douwe Maan committed
97
  def markup(file_name, text, context = {})
98
    context[:project] ||= @project
Douwe Maan committed
99
    html = context.delete(:rendered) || markup_unsafe(file_name, text, context)
100
    prepare_for_rendering(html, context)
101 102
  end

Douwe Maan committed
103 104
  def render_wiki_content(wiki_page)
    text = wiki_page.content
105
    return '' unless text.present?
106

Douwe Maan committed
107
    context = { pipeline: :wiki, project: @project, project_wiki: @project_wiki, page_slug: wiki_page.slug }
108

Douwe Maan committed
109 110 111 112 113 114 115 116 117
    html =
      case wiki_page.format
      when :markdown
        markdown_unsafe(text, context)
      when :asciidoc
        asciidoc_unsafe(text)
      else
        wiki_page.formatted_content.html_safe
      end
118

119
    prepare_for_rendering(html, context)
120 121
  end

Douwe Maan committed
122
  def markup_unsafe(file_name, text, context = {})
123
    return '' unless text.present?
Douwe Maan committed
124

125
    if gitlab_markdown?(file_name)
126
      markdown_unsafe(text, context)
127
    elsif asciidoc?(file_name)
128
      asciidoc_unsafe(text, context)
129 130
    elsif plain?(file_name)
      content_tag :pre, class: 'plain-readme' do
Douwe Maan committed
131
        text
132 133
      end
    else
134
      other_markup_unsafe(file_name, text, context)
135 136
    end
  rescue RuntimeError
Douwe Maan committed
137 138 139
    simple_format(text)
  end

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  # Returns the text necessary to reference `entity` across projects
  #
  # project - Project to reference
  # entity  - Object that responds to `to_reference`
  #
  # Examples:
  #
  #   cross_project_reference(project, project.issues.first)
  #   # => 'namespace1/project1#123'
  #
  #   cross_project_reference(project, project.merge_requests.first)
  #   # => 'namespace1/project1!345'
  #
  # Returns a String
  def cross_project_reference(project, entity)
    if entity.respond_to?(:to_reference)
      entity.to_reference(project, full: true)
    else
      ''
    end
  end

162 163 164 165 166 167 168
  private

  # Return +text+, truncated to +max_chars+ characters, excluding any HTML
  # tags.
  def truncate_visible(text, max_chars)
    doc = Nokogiri::HTML.fragment(text)
    content_length = 0
169
    truncated = false
170 171 172

    doc.traverse do |node|
      if node.text? || node.content.empty?
173
        if truncated
174 175 176 177
          node.remove
          next
        end

178 179 180 181 182 183
        # Handle line breaks within a node
        if node.content.strip.lines.length > 1
          node.content = "#{node.content.lines.first.chomp}..."
          truncated = true
        end

184 185 186
        num_remaining = max_chars - content_length
        if node.content.length > num_remaining
          node.content = node.content.truncate(num_remaining)
187
          truncated = true
188 189 190
        end
        content_length += node.content.length
      end
191 192

      truncated = truncate_if_block(node, truncated)
193 194 195 196
    end

    doc.to_html
  end
197 198 199 200 201

  # Used by #truncate_visible.  If +node+ is the first block element, and the
  # text hasn't already been truncated, then append "..." to the node contents
  # and return true.  Otherwise return false.
  def truncate_if_block(node, truncated)
Douwe Maan committed
202 203 204
    return true if truncated

    if node.element? && (node.description&.block? || node.matches?('pre > code > .line'))
205
      node.inner_html = "#{node.inner_html}..." if node.next_sibling
206 207 208 209 210
      true
    else
      truncated
    end
  end
211

212
  def markdown_toolbar_button(options = {})
213
    data = options[:data].merge({ container: 'body' })
214
    content_tag :button,
215 216
      type: 'button',
      class: 'toolbar-btn js-md has-tooltip hidden-xs',
217 218 219 220 221 222 223
      tabindex: -1,
      data: data,
      title: options[:title],
      aria: { label: options[:title] } do
      icon(options[:icon])
    end
  end
224

225 226 227 228
  def markdown_unsafe(text, context = {})
    Banzai.render(text, context)
  end

229 230
  def asciidoc_unsafe(text, context = {})
    Gitlab::Asciidoc.render(text, context)
231 232
  end

233 234
  def other_markup_unsafe(file_name, text, context = {})
    Gitlab::OtherMarkup.render(file_name, text, context)
235 236
  end

237
  def prepare_for_rendering(html, context = {})
238
    return '' unless html.present?
Douwe Maan committed
239

240 241 242 243
    context.merge!(
      current_user:   (current_user if defined?(current_user)),

      # RelativeLinkFilter
244
      commit:         @commit,
245
      project_wiki:   @project_wiki,
246 247
      ref:            @ref,
      requested_path: @path
248 249
    )

250 251 252
    html = Banzai.post_process(html, context)

    Hamlit::RailsHelpers.preserve(html)
253
  end
254 255

  extend self
256
end