Class: Jekyll::JtdTocNav::Injector

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll/jtd_toc_nav/injector.rb

Constant Summary collapse

DEFAULT_LEVELS =
(2..4).to_a

Instance Method Summary collapse

Constructor Details

#initialize(site:) ⇒ Injector

Returns a new instance of Injector.



8
9
10
# File 'lib/jekyll/jtd_toc_nav/injector.rb', line 8

def initialize(site:)
  @site = site
end

Instance Method Details

#expand_all?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/jekyll/jtd_toc_nav/injector.rb', line 31

def expand_all?
  @site.config.fetch("sidebar_toc_expand", true) != false
end

#levelsObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/jekyll/jtd_toc_nav/injector.rb', line 12

def levels
  raw = @site.config["sidebar_toc_levels"]
  return DEFAULT_LEVELS if raw.nil?

  if raw.is_a?(String) && raw.include?("..")
    a, b = raw.split("..", 2).map { |x| Integer(x) rescue nil }
    return DEFAULT_LEVELS if a.nil? || b.nil?
    return (a..b).to_a
  end

  if raw.is_a?(Array)
    ints = raw.map { |x| Integer(x) rescue nil }.compact
    return DEFAULT_LEVELS if ints.empty?
    return ints
  end

  DEFAULT_LEVELS
end

#process!(page_like) ⇒ Object



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
62
63
64
65
66
67
68
69
# File 'lib/jekyll/jtd_toc_nav/injector.rb', line 35

def process!(page_like)
  return if page_like.output.nil? || page_like.output.empty?

  html = page_like.output
  doc = Nokogiri::HTML(html)

  headings = extract_headings(doc)
  return if headings.empty?

  nav = doc.at_css("#site-nav")
  return unless nav

  page_url = page_like.url
  link = find_nav_link(nav, page_url)
  return unless link

  nav_item = link.ancestors("li.nav-list-item").first
  return unless nav_item

  # Remove any prior injection
  nav_item.css("> ul.nav-list[data-jtd-toc-nav='true']").remove

  outline_ul = build_outline_ul(doc, headings)
  outline_ul["data-jtd-toc-nav"] = "true"

  # Ensure current page can expand/collapse like other nav items.
  ensure_expander!(doc, nav_item, label: "Toggle page sections")

  nav_item.add_class("active")
  nav_item.add_child(outline_ul)

  page_like.output = doc.to_html
rescue StandardError => e
  Jekyll.logger.warn("jtd-toc-nav:", "failed to inject sidebar toc for #{page_like.url}: #{e.class}: #{e.message}")
end