toc_generate

in _plugins/toc.rb [8:101]


   def toc_generate(html)
        
        
        no_toc = @context.environments.first["page"]["noToc"] || false;

        if no_toc
            return
        end

        config = @context.registers[:site].config
        
        min_items_to_show_toc = config["minItemsToShowToc"] || 0

        anchor_prefix = config["anchorPrefix"] || 'tocAnchor-'

        
        contents_label = config["contentsLabel"] || 'Table of Contents'
        hide_label = config["hideLabel"] || 'hide'
        show_label = config["showLabel"] || 'show'
        show_toggle_button = config["showToggleButton"]

        toc_html = ''
        toc_level = 1
        toc_section = 1
        item_number = 1
        level_html = ''

        doc = Nokogiri::HTML(html)

        
        doc.css('h2').each do |h1|
            
            ct  = h1.xpath('count(following-sibling::h2)')
            h2s = h1.xpath("following-sibling::h3[count(following-sibling::h2)=#{ct}]")

            level_html = '';
            inner_section = 0;

            h2s.map.each do |h2|
                inner_section += 1;
                anchor_id = h2['id']
                
                

                level_html += create_level_html(anchor_id,
                    toc_level + 1,
                    toc_section + inner_section,
                    item_number.to_s + '.' + inner_section.to_s,
                    h2.text,
                    '')
            end
            if level_html.length > 0
                level_html = '<ul>' + level_html + '</ul>';
            end
            anchor_id = h1['id']
            
            

            toc_html += create_level_html(anchor_id,
                toc_level,
                toc_section,
                item_number,
                h1.text,
                level_html);

            toc_section += 1 + inner_section;
            item_number += 1;
        end

        
        
        toc_index_count = item_number - 1

        if toc_html.length > 0
            hide_html = '';
            if (show_toggle_button)
                hide_html = HIDE_HTML.gsub('%1', hide_label)
            end

            if min_items_to_show_toc <= toc_index_count
                replaced_toggle_html = TOGGLE_HTML
                    .gsub('%1', contents_label)
                    .gsub('%2', hide_html);
                toc_table = TOC_CONTAINER_HTML
                    .gsub('%1', replaced_toggle_html)
                    .gsub('%2', toc_html);
                return toc_table;
            end
            doc.css('body').children.to_xhtml(indent:3, indent_text:" ")
        else
            return
        end
   end