Class: Utopia::Project::Sidebar

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/project/sidebar.rb

Overview

Generates a sidebar navigation from markdown document headings.

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(entries) ⇒ Sidebar

Initialize with an array of entries.



47
48
49
# File 'lib/utopia/project/sidebar.rb', line 47

def initialize(entries)
	@entries = entries
end

Instance Attribute Details

#entriesObject (readonly)

The navigation entries.



53
54
55
# File 'lib/utopia/project/sidebar.rb', line 53

def entries
  @entries
end

Class Method Details

.build(document) ⇒ Object

Build a sidebar from a markdown document by extracting headings.



40
41
42
43
# File 'lib/utopia/project/sidebar.rb', line 40

def self.build(document)
	entries = extract_headings_from_document(document)
	new(entries)
end

.extract_headings_from_document(document) ⇒ Object



96
97
98
99
100
101
102
103
104
105
# File 'lib/utopia/project/sidebar.rb', line 96

def self.extract_headings_from_document(document)
	return [] unless document&.root
	
	Markly::Renderer::Headings.extract(document.root, min_level: 2, max_level: 3).map do |heading|
		fragment = heading.node.dup.extract_children
		title = XRB::Markup.raw(fragment.to_html)
		
		Entry.new(title, heading.level, heading.anchor)
	end
end

Instance Method Details

#any?Boolean

Check if there are any navigation entries.

Returns:

  • (Boolean)


57
58
59
# File 'lib/utopia/project/sidebar.rb', line 57

def any?
	!entries.empty?
end

#to_html(sidebar: false, title: "Table of Contents") ⇒ Object

Generate HTML markup for the sidebar navigation.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/utopia/project/sidebar.rb', line 65

def to_html(sidebar: false, title: "Table of Contents")
	return XRB::Markup.raw("") unless any?
	
	XRB::Builder.fragment do |builder|
		builder.tag :nav do
			builder.tag :heading do
				builder.text title
			end
			builder.tag :ul do
				entries.each do |entry|
					if entry.level > 2
						builder.tag :li, {class: "level-#{entry.level}"} do
							builder.tag :a, {href: "##{entry.anchor}"} do
								builder << entry.title_html
							end
						end
					else
						builder.tag :li do
							builder.tag :a, {href: "##{entry.anchor}"} do
								builder << entry.title_html
							end
						end
					end
				end
			end
		end
	end
end