Class: Jekyll::FastReader::Transformer

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll/fast_reader/transformer.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Transformer

Returns a new instance of Transformer.



6
7
8
9
# File 'lib/jekyll/fast_reader/transformer.rb', line 6

def initialize(config)
  @config = config
  @walker = HtmlWalker.new(config.exclude_selectors)
end

Instance Method Details

#call(html, stop_words: nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/jekyll/fast_reader/transformer.rb', line 11

def call(html, stop_words: nil)
  return html unless html =~ /<body\b/i

  had_head = html.include?("</head>")
  had_body = html.include?("</body>")

  doc  = Nokogiri::HTML(html)
  body = doc.at_css("body")
  return html unless body

  words     = stop_words || @config.stop_words_extra
  processor = TextProcessor.new(StopWords.new(words))

  text_nodes = []
  @walker.walk(body) { |node| text_nodes << node }
  text_nodes.each { |node| node.replace(processor.process(node.content)) }

  inject_stylesheet(doc) if had_head
  inject_script(doc)     if had_head && @config.toggle
  inject_body_class(body, "fr-opt-in") unless @config.default_on
  inject_toggle(body)    if had_body && @config.toggle

  doc.to_html
end