Class: Banzai::Filter::CodeLanguageFilter

Inherits:
HTML::Pipeline::Filter
  • Object
show all
Includes:
OutputSafety
Defined in:
lib/banzai/filter/code_language_filter.rb

Overview

HTML Filter to convert use of ‘lang` attribute into a common format, data-canonical-lang, as the `lang` attribute is really meant for accessibility and not for specifying code highlight language. See developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang#accessibility This also provides one place to transform the language specification format, whether it sits on the `pre` or `code`, or in a `class` or `lang` attribute

Constant Summary collapse

LANG_PARAMS_DELIMITER =
':'
LANG_ATTR =
'data-canonical-lang'
LANG_PARAMS_ATTR =
'data-lang-params'
CSS =
'pre > code:only-child'
XPATH =
Gitlab::Utils::Nokogiri.css_to_xpath(CSS).freeze

Instance Method Summary collapse

Methods included from OutputSafety

#escape_once

Instance Method Details

#callObject



21
22
23
24
25
26
27
# File 'lib/banzai/filter/code_language_filter.rb', line 21

def call
  doc.xpath(XPATH).each do |node|
    transform_node(node)
  end

  doc
end

#transform_node(code_node) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/banzai/filter/code_language_filter.rb', line 29

def transform_node(code_node)
  return if code_node.parent&.parent.nil?

  lang, lang_params = parse_lang_params(code_node)
  pre_node = code_node.parent

  if lang.present?
    code_node.remove_attribute('lang')
    pre_node.remove_attribute('lang')
  end

  pre_node.set_attribute(LANG_ATTR, escape_once(lang)) if lang.present?
  pre_node.set_attribute(LANG_PARAMS_ATTR, escape_once(lang_params)) if lang_params.present?

  # cmark-gfm added this, it's now in data-lang-params
  pre_node.remove_attribute('data-meta')
  code_node.remove_attribute('data-meta')
end