]>
cat aescling's git repositories - mastodon.git/blob - app/lib/toc_generator.rb
1 # frozen_string_literal: true
4 TARGET_ELEMENTS
= %w(h1 h2 h3 h4 h5 h6
).freeze
5 LISTED_ELEMENTS
= %w(h2 h3
).freeze
8 attr_accessor
:depth, :title, :children, :anchor
10 def initialize(depth
, title
, anchor
)
17 delegate
:<<, to
: :children
20 def initialize(source_html
)
21 @source_html = source_html
25 @slugs = Hash
.new
{ |h
, k
| h
[k
] = 0 }
29 parse_and_transform
unless @processed
34 parse_and_transform
unless @processed
40 def parse_and_transform
41 return if @source_html.blank
?
43 parsed_html
= Nokogiri
::HTML.fragment(@source_html)
45 parsed_html
.traverse
do |node
|
46 next unless TARGET_ELEMENTS
.include?(node
.name
)
48 anchor
= node
['id'] || node
.text
.parameterize
50 anchor
= "#{anchor}-#{@slugs[anchor]}" if @slugs[anchor
] > 1
54 next unless LISTED_ELEMENTS
.include?(node
.name
)
56 depth
= node
.name
[1..-1]
57 latest_section
= @headers.last
59 if latest_section
.nil? || latest_section
.depth
>= depth
60 @headers << Section
.new(depth
, node
.text
, anchor
)
62 latest_section
<< Section
.new(depth
, node
.text
, anchor
)
66 @target_html = parsed_html
.to_s
This page took 0.149695 seconds and 4 git commands to generate.