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
|
# File 'lib/qiita/markdown/filters/html_toc.rb', line 8
def call
headings = doc.search("h1, h2, h3, h4, h5, h6")
return "" if headings.empty?
toc = %W[<ul>\n]
top_level = nil
last_level = nil
depth = 1
headings.each do |node|
heading_rank = node.name.match(/h(\d)/)[1].to_i
top_level ||= heading_rank
current_level = [heading_rank, top_level].max
link = toc_with_link(node.text, node.attributes["id"]&.value)
toc << (nest_string(last_level, current_level) + link)
depth += current_level - last_level if last_level
last_level = current_level
end
toc << ("</li>\n</ul>\n" * depth)
toc.join
end
|