summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/issuable_state_filter.rb
blob: 8e2358694d43b7ff648e8b569782d4301ca415b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true

module Banzai
  module Filter
    # HTML filter that appends state information to issuable links.
    # Runs as a post-process filter as issuable state might change whilst
    # Markdown is in the cache.
    #
    # This filter supports cross-project references.
    class IssuableStateFilter < HTML::Pipeline::Filter
      VISIBLE_STATES = %w(closed merged).freeze

      def call
        return doc unless context[:issuable_state_filter_enabled]

        context = RenderContext.new(project, current_user)
        extractor = Banzai::IssuableExtractor.new(context)
        issuables = extractor.extract([doc])

        issuables.each do |node, issuable|
          next if !can_read_cross_project? && cross_reference?(issuable)

          if VISIBLE_STATES.include?(issuable.state) && issuable_reference?(node.inner_html, issuable)
            node.content += " (#{issuable.state})"
          end
        end

        doc
      end

      private

      def issuable_reference?(text, issuable)
        CGI.unescapeHTML(text) == issuable.reference_link_text(project || group)
      end

      def cross_reference?(issuable)
        return true if issuable.project != project
        return true if issuable.respond_to?(:group) && issuable.group != group

        false
      end

      def can_read_cross_project?
        Ability.allowed?(current_user, :read_cross_project)
      end

      def current_user
        context[:current_user]
      end

      def project
        context[:project]
      end

      def group
        context[:group]
      end
    end
  end
end