Class: Coradoc::Html::TocBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/coradoc/html/toc_builder.rb

Overview

Builds a CoreModel::Toc from a document’s StructuralElement tree.

Walks the section hierarchy, assigns section numbers, and returns a Toc model with nested TocEntry children. Section numbers are derived from tree position — single source of truth for both TOC rendering and heading numbering.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_level: 6, numbered: false, section_number_levels: 3) ⇒ TocBuilder

Returns a new instance of TocBuilder.



12
13
14
15
16
# File 'lib/coradoc/html/toc_builder.rb', line 12

def initialize(max_level: 6, numbered: false, section_number_levels: 3)
  @max_level = max_level
  @numbered = numbered
  @section_number_levels = section_number_levels
end

Class Method Details

.from_options(options) ⇒ TocBuilder

Build a TocBuilder from renderer-style options hash.

Parameters:

  • options (Hash)

    options with :section_number_levels, :toc_levels, :section_numbers

Returns:



22
23
24
25
26
27
# File 'lib/coradoc/html/toc_builder.rb', line 22

def self.from_options(options)
  section_number_levels = options[:section_number_levels] || 3
  toc_levels = options[:toc_levels] || 2
  max_level = [toc_levels, section_number_levels].min
  new(max_level: max_level, numbered: options[:section_numbers] == true, section_number_levels: section_number_levels)
end

Instance Method Details

#build(document) ⇒ CoreModel::Toc

Build a Toc model from a document.

Parameters:

  • document (CoreModel::StructuralElement)

    the root document

Returns:

  • (CoreModel::Toc)

    the built TOC with entries and section numbers



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/coradoc/html/toc_builder.rb', line 33

def build(document)
  entries = []
  counters = [0]
  collect_entries(document.children, entries, 1, counters) if document.children

  CoreModel::Toc.new(
    entries: entries,
    min_level: 1,
    max_level: @max_level,
    numbered: @numbered
  )
end

#section_number_map(document) ⇒ Hash{String => String}

Compute a mapping of section_id => section_number_string. Always computes numbers regardless of the numbered flag, since this is used for heading annotation in the body.

Parameters:

  • document (CoreModel::StructuralElement)

    the root document

Returns:

  • (Hash{String => String})

    mapping of section ID to number (e.g., “2.1”)



52
53
54
55
56
57
58
59
# File 'lib/coradoc/html/toc_builder.rb', line 52

def section_number_map(document)
  map = {}
  entries = []
  counters = [0]
  collect_entries(document.children, entries, 1, counters, always_number: true) if document.children
  flatten_numbers(entries, map)
  map
end