BigW Consortium Gitlab

markup_helper.rb 7.06 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 24 25 26 27 28 29 30 31
  # Use this in places where you would normally use link_to(gfm(...), ...).
  #
  # 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
  # not linked any more). link_to_gfm corrects that. It wraps all parts to
  # explicitly produce the correct linking behavior (i.e.
  # "<a>outer text </a><a>gfm ref</a><a> more outer text</a>").
32
  def link_to_gfm(body, url, html_options = {})
33
    return '' if body.blank?
34

35 36 37
    context = {
      project: @project,
      current_user: (current_user if defined?(current_user)),
38
      pipeline: :single_line
39 40
    }
    gfm_body = Banzai.render(body, context)
41

SAKATA Sinji committed
42
    fragment = Nokogiri::HTML::DocumentFragment.parse(gfm_body)
43 44 45 46 47 48 49 50 51 52 53 54
    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
55 56
    end

57 58 59 60 61
    # 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

62
    fragment.to_html.html_safe
63
  end
randx committed
64

Douwe Maan committed
65 66 67 68 69 70
  # 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
71

Douwe Maan committed
72
    truncate_visible(md, max_chars || md.length) if md.present?
73 74
  end

Douwe Maan committed
75
  def markdown(text, context = {})
76
    return '' unless text.present?
77

78
    context[:project] ||= @project
79
    html = markdown_unsafe(text, context)
80
    prepare_for_rendering(html, context)
81
  end
82

83 84
  def markdown_field(object, field)
    object = object.for_display if object.respond_to?(:for_display)
85
    return '' unless object.present?
86

87
    html = Banzai.render_field(object, field)
88
    prepare_for_rendering(html, object.banzai_render_context(field))
89 90
  end

Douwe Maan committed
91
  def markup(file_name, text, context = {})
92
    context[:project] ||= @project
Douwe Maan committed
93
    html = context.delete(:rendered) || markup_unsafe(file_name, text, context)
94
    prepare_for_rendering(html, context)
95 96
  end

Douwe Maan committed
97 98
  def render_wiki_content(wiki_page)
    text = wiki_page.content
99
    return '' unless text.present?
100

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

Douwe Maan committed
103 104 105 106 107 108 109 110 111
    html =
      case wiki_page.format
      when :markdown
        markdown_unsafe(text, context)
      when :asciidoc
        asciidoc_unsafe(text)
      else
        wiki_page.formatted_content.html_safe
      end
112

113
    prepare_for_rendering(html, context)
114 115
  end

Douwe Maan committed
116
  def markup_unsafe(file_name, text, context = {})
117
    return '' unless text.present?
Douwe Maan committed
118

119
    if gitlab_markdown?(file_name)
120
      markdown_unsafe(text, context)
121
    elsif asciidoc?(file_name)
122
      asciidoc_unsafe(text, context)
123 124
    elsif plain?(file_name)
      content_tag :pre, class: 'plain-readme' do
Douwe Maan committed
125
        text
126 127
      end
    else
128
      other_markup_unsafe(file_name, text, context)
129 130
    end
  rescue RuntimeError
Douwe Maan committed
131 132 133
    simple_format(text)
  end

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  # 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

156 157 158 159 160 161 162
  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
163
    truncated = false
164 165 166

    doc.traverse do |node|
      if node.text? || node.content.empty?
167
        if truncated
168 169 170 171
          node.remove
          next
        end

172 173 174 175 176 177
        # Handle line breaks within a node
        if node.content.strip.lines.length > 1
          node.content = "#{node.content.lines.first.chomp}..."
          truncated = true
        end

178 179 180
        num_remaining = max_chars - content_length
        if node.content.length > num_remaining
          node.content = node.content.truncate(num_remaining)
181
          truncated = true
182 183 184
        end
        content_length += node.content.length
      end
185 186

      truncated = truncate_if_block(node, truncated)
187 188 189 190
    end

    doc.to_html
  end
191 192 193 194 195

  # 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
196 197 198
    return true if truncated

    if node.element? && (node.description&.block? || node.matches?('pre > code > .line'))
199
      node.inner_html = "#{node.inner_html}..." if node.next_sibling
200 201 202 203 204
      true
    else
      truncated
    end
  end
205

206
  def markdown_toolbar_button(options = {})
207
    data = options[:data].merge({ container: 'body' })
208
    content_tag :button,
209 210
      type: 'button',
      class: 'toolbar-btn js-md has-tooltip hidden-xs',
211 212 213 214 215 216 217
      tabindex: -1,
      data: data,
      title: options[:title],
      aria: { label: options[:title] } do
      icon(options[:icon])
    end
  end
218

219 220 221 222
  def markdown_unsafe(text, context = {})
    Banzai.render(text, context)
  end

223 224
  def asciidoc_unsafe(text, context = {})
    Gitlab::Asciidoc.render(text, context)
225 226
  end

227 228
  def other_markup_unsafe(file_name, text, context = {})
    Gitlab::OtherMarkup.render(file_name, text, context)
229 230
  end

231
  def prepare_for_rendering(html, context = {})
232
    return '' unless html.present?
Douwe Maan committed
233

234 235 236 237
    context.merge!(
      current_user:   (current_user if defined?(current_user)),

      # RelativeLinkFilter
238
      commit:         @commit,
239
      project_wiki:   @project_wiki,
240 241
      ref:            @ref,
      requested_path: @path
242 243
    )

244 245 246
    html = Banzai.post_process(html, context)

    Hamlit::RailsHelpers.preserve(html)
247
  end
248 249

  extend self
250
end