File: plantuml_filter.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (45 lines) | stat: -rw-r--r-- 1,235 bytes parent folder | download
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
# frozen_string_literal: true

require "nokogiri"
require "asciidoctor_plantuml/plantuml"

module Banzai
  module Filter
    # HTML that replaces all `lang plantuml` tags with PlantUML img tags.
    #
    class PlantumlFilter < HTML::Pipeline::Filter
      prepend Concerns::PipelineTimingCheck

      def call
        return doc unless settings.plantuml_enabled? && doc.at_xpath(lang_tag)

        Gitlab::Plantuml.configure

        doc.xpath(lang_tag).each do |node|
          img_tag = Nokogiri::HTML::DocumentFragment.parse(
            Asciidoctor::PlantUml::Processor.plantuml_content(node.content, {})).css('img').first

          next if img_tag.nil?

          img_tag.set_attribute('data-diagram', 'plantuml')
          img_tag.set_attribute('data-diagram-src', "data:text/plain;base64,#{Base64.strict_encode64(node.content)}")

          node.parent.replace(img_tag)
        end

        doc
      end

      private

      def lang_tag
        @lang_tag ||= Gitlab::Utils::Nokogiri
          .css_to_xpath('pre[data-canonical-lang="plantuml"] > code, pre > code[data-canonical-lang="plantuml"]').freeze
      end

      def settings
        Gitlab::CurrentSettings.current_application_settings
      end
    end
  end
end