debian-mirror-gitlab/lib/banzai/filter/math_filter.rb

52 lines
1.4 KiB
Ruby
Raw Normal View History

2018-11-18 11:00:15 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
require 'uri'
2019-03-02 22:35:43 +05:30
# Generated HTML is transformed back to GFM by:
# - app/assets/javascripts/behaviors/markdown/marks/math.js
# - app/assets/javascripts/behaviors/markdown/nodes/code_block.js
2017-08-17 22:00:37 +05:30
module Banzai
module Filter
# HTML filter that adds class="code math" and removes the dollar sign in $`2+2`$.
#
class MathFilter < HTML::Pipeline::Filter
# Attribute indicating inline or display math.
2019-12-04 20:38:33 +05:30
STYLE_ATTRIBUTE = 'data-math-style'
2017-08-17 22:00:37 +05:30
# Class used for tagging elements that should be rendered
2019-12-04 20:38:33 +05:30
TAG_CLASS = 'js-render-math'
2017-08-17 22:00:37 +05:30
2019-12-04 20:38:33 +05:30
INLINE_CLASSES = "code math #{TAG_CLASS}"
2017-08-17 22:00:37 +05:30
2019-12-04 20:38:33 +05:30
DOLLAR_SIGN = '$'
2017-08-17 22:00:37 +05:30
def call
doc.css('code').each do |code|
closing = code.next
opening = code.previous
# We need a sibling before and after.
# They should end and start with $ respectively.
if closing && opening &&
closing.text? && opening.text? &&
closing.content.first == DOLLAR_SIGN &&
opening.content.last == DOLLAR_SIGN
code[:class] = INLINE_CLASSES
code[STYLE_ATTRIBUTE] = 'inline'
closing.content = closing.content[1..-1]
opening.content = opening.content[0..-2]
end
end
doc.css('pre.code.math').each do |el|
el[STYLE_ATTRIBUTE] = 'display'
el[:class] += " #{TAG_CLASS}"
end
doc
end
end
end
end