jekyll-toc-generator 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c6d4565912821695402aa8731d39c5fa37db228a1d913a43b1b1c081541dbca8
4
- data.tar.gz: d1eb16a8e95e4cd052d9974b03175a41bef067a2fa5959221930138375c8a24f
3
+ metadata.gz: f4750cc8d63b1c942c89bf0188b7579591582b84347f98b1740d559ac263c5e3
4
+ data.tar.gz: 15a758c89e43015a95f442dac939f299f4aa9a097bef1a230bf82d9bf0e42604
5
5
  SHA512:
6
- metadata.gz: 4d1d48cfe71db0b1a126ed5ea41c4c61b3aba641d9d9c2b536cd7aa46ff02d6fe75c124810970bcef33dde90553a4681f36417aae6ee877a2c7a65bc4783f67b
7
- data.tar.gz: 585b4df874534717b07f4b948569cf3aa951bb2d5e691b501d2cf05a4913eab3b794611167831b356b11f21023ed1c643c677ee253de61d177e757b6f2eb1378
6
+ metadata.gz: 7f71746156c9a5432970564e52752042e637d472faa78c47134613623c135c2d30c3bef0f205f0fce08c7560b6bd0a44d833d59c0f83d00201c44b65a9d462e5
7
+ data.tar.gz: c5b448409ae13edae788d20a90030bca0cbfb17c6ca1fb5d90c50dae0c58932aa1a6221e96e60fd12087ac8724075fbfe888a7d84d5a41704618b3b2d5ee11ff
data/LICENSE.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Jason Chance
3
+ Copyright (c) 2026 Jason Chance
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # jekyll-toc-generator
2
2
 
3
- Hook-based table of contents injection for Jekyll. Posts and pages with `toc: true` in frontmatter automatically get a TOC injected — no Liquid tag required in the content.
3
+ Hook-based table of contents injection for Jekyll. Posts and pages with `toc: true` in frontmatter automatically get a TOC injected, with no Liquid tag required in the content.
4
4
 
5
5
  ## Installation
6
6
 
@@ -30,7 +30,9 @@ toc: true
30
30
  ---
31
31
  ```
32
32
 
33
- The plugin automatically injects a `<nav class="toc">` element immediately before the first `<h2>` in the rendered HTML. No Liquid tag needed.
33
+ The plugin builds a `<nav class="toc">` from the headings in that document's own content and inserts it right before the first `<h2>`. It runs after Markdown is converted and before your layout is applied, so headings in your header, footer or sidebar never show up in the TOC and the TOC never lands in layout markup. Posts, pages and collection documents each get one TOC.
34
+
35
+ The plugin only touches pages that output HTML. If the content already contains a `<nav class="toc">`, it is left alone.
34
36
 
35
37
  ## Configuration
36
38
 
@@ -38,24 +40,26 @@ All options are optional. Add to `_config.yml`:
38
40
 
39
41
  ```yaml
40
42
  toc:
41
- min_headings: 2 # don't inject TOC if fewer than N h2s (default: 2)
42
- title: "Contents" # TOC nav title (default: "Table of Contents")
43
- levels: [2, 3] # heading levels to include (default: [2, 3])
43
+ min_headings: 2 # skip the TOC if fewer than N headings are listed (default: 2)
44
+ title: "Contents" # visible title; false or "" turns it off (default: "Table of Contents")
45
+ title_tag: h2 # element for the title: h1-h6, p, div or span (default: h2)
46
+ levels: [2, 3] # heading levels to list (default: [2, 3])
44
47
  ```
45
48
 
46
49
  ### Options
47
50
 
48
51
  | Option | Default | Description |
49
52
  |---|---|---|
50
- | `min_headings` | `2` | Minimum number of `<h2>` elements required to inject a TOC |
51
- | `title` | `"Table of Contents"` | Text shown in the TOC `<h2>` title |
52
- | `levels` | `[2, 3]` | Heading levels to include in the TOC |
53
+ | `min_headings` | `2` | Minimum number of headings (in the configured `levels`) needed to add a TOC |
54
+ | `title` | `"Table of Contents"` | Visible title text, escaped for you. Set `false` or `""` to drop the title |
55
+ | `title_tag` | `"h2"` | Element used for the title. Use `p` if you don't want the title in the page's heading outline |
56
+ | `levels` | `[2, 3]` | Heading levels to list. Deeper levels nest under the closest earlier heading, including when a level is skipped (an `<h4>` right after an `<h2>`) |
53
57
 
54
58
  ## TOC HTML Structure
55
59
 
56
60
  ```html
57
- <nav class="toc" aria-label="Table of contents">
58
- <h2 class="toc__title">Table of Contents</h2>
61
+ <nav class="toc" aria-labelledby="toc-title">
62
+ <h2 class="toc__title" id="toc-title">Table of Contents</h2>
59
63
  <ul class="toc__list">
60
64
  <li class="toc__item"><a href="#heading-slug">Heading Text</a>
61
65
  <ul class="toc__sublist">
@@ -66,16 +70,18 @@ toc:
66
70
  </nav>
67
71
  ```
68
72
 
73
+ The `<nav>` is labelled by its title through `aria-labelledby`. With `title: false` it gets `aria-label="Table of contents"` instead. The title is never listed as a TOC entry. If the title id would clash with an id in your content, it becomes `toc-title-1` and so on.
74
+
69
75
  ### CSS Classes
70
76
 
71
77
  | Class | Element | Description |
72
78
  |---|---|---|
73
79
  | `.toc` | `<nav>` | Outer TOC container |
74
- | `.toc__title` | `<h2>` | TOC section title |
80
+ | `.toc__title` | `<h2>` (or `title_tag`) | TOC title |
75
81
  | `.toc__list` | `<ul>` | Top-level heading list |
76
82
  | `.toc__item` | `<li>` | Top-level heading item |
77
- | `.toc__sublist` | `<ul>` | Nested subheading list |
78
- | `.toc__item--sub` | `<li>` | Subheading item |
83
+ | `.toc__sublist` | `<ul>` | Nested subheading list (used at every depth) |
84
+ | `.toc__item--sub` | `<li>` | Subheading item (used at every depth) |
79
85
 
80
86
  ### Example CSS
81
87
 
@@ -113,23 +119,26 @@ toc:
113
119
  }
114
120
  ```
115
121
 
116
- ## Slug Generation
122
+ ## Heading IDs
123
+
124
+ Each TOC link points at the `id` the heading already has. With kramdown (Jekyll's default), that means duplicate headings link to `dup`, `dup-1` and so on, and `Café & Crème` links to `#café--crème`, exactly as kramdown wrote them.
125
+
126
+ If a heading has no `id` (raw HTML, or kramdown's `auto_ids` turned off), the plugin makes one and adds it to the heading so the link works:
117
127
 
118
- Heading IDs are slugified to match Jekyll's default anchor generation:
128
+ - Lowercase, with punctuation removed and spaces turned into `-`
129
+ - Letters in any script, digits and underscores are kept
130
+ - Made unique against every id in the content with a `-1`, `-2` suffix
119
131
 
120
- - Lowercase
121
- - Non-alphanumeric characters removed
122
- - Spaces and underscores replaced with `-`
123
- - Leading/trailing hyphens stripped
132
+ Example: `"What's New?"` becomes `id="whats-new"`.
124
133
 
125
- Example: `"What's New?"` → `#whats-new`
134
+ The TOC text is each heading's text content, so inline code, links and emphasis are reduced to plain, escaped text. Headings inside `<pre>` blocks, comments and `<script>` are ignored.
126
135
 
127
136
  ## Requirements
128
137
 
129
- - Jekyll >= 4.0
130
- - Ruby >= 2.7
138
+ - Jekyll >= 4.2 (the `:post_convert` hook arrived in 4.2.0)
139
+ - Ruby >= 3.0
131
140
  - No additional gem dependencies (pure Ruby, no Nokogiri)
132
141
 
133
142
  ## License
134
143
 
135
- MIT © Jason Chance 2025
144
+ MIT © Jason Chance 2026
@@ -1,10 +1,18 @@
1
+ require "jekyll"
1
2
  require "jekyll-toc-generator/version"
2
3
  require "jekyll-toc-generator/toc_builder"
3
4
 
4
- Jekyll::Hooks.register [:posts, :pages, :documents], :post_render do |doc|
5
+ # Runs once per page or document, after Markdown is converted and before the
6
+ # layout is applied, so only the document's own headings are used and the TOC
7
+ # is inserted into the document's own content.
8
+ #
9
+ # Posts and other collection documents are documents: Jekyll fires the
10
+ # collection's hook (:posts) and :documents for them, so registering for
11
+ # :documents (plus :pages) covers everything exactly once.
12
+ Jekyll::Hooks.register [:pages, :documents], :post_convert do |doc|
5
13
  next unless doc.data["toc"] == true
14
+ next unless doc.output_ext == ".html"
6
15
 
7
16
  config = doc.site.config["toc"] || {}
8
- builder = Jekyll::TocGenerator::TocBuilder.new(doc.output, config)
9
- doc.output = builder.build
17
+ doc.content = Jekyll::TocGenerator::TocBuilder.new(doc.content, config).build
10
18
  end
@@ -1,100 +1,218 @@
1
+ require "cgi"
2
+
1
3
  module Jekyll
2
4
  module TocGenerator
5
+ # Builds a table of contents from a document's converted HTML (the content
6
+ # before the layout is applied) and inserts it into that same HTML.
7
+ #
8
+ # Links point at the `id` attribute each heading already has (kramdown adds
9
+ # these). A heading with no id gets a unique one, which is written back to
10
+ # the heading so the link has somewhere to land.
3
11
  class TocBuilder
12
+ DEFAULT_TITLE = "Table of Contents".freeze
13
+ DEFAULT_LEVELS = [2, 3].freeze
14
+ TITLE_TAGS = %w[h1 h2 h3 h4 h5 h6 p div span].freeze
15
+ TITLE_ID = "toc-title".freeze
16
+
17
+ HEADING = %r{<h([1-6])((?:\s[^>]*)?)>(.*?)</h\1\s*>}im
18
+ ID_ATTR = /\sid\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i
19
+ ANY_ID_ATTR = /\sid\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s"'>]+))/i
20
+ # Regions where something that looks like a heading is not one.
21
+ IGNORED = [
22
+ /<!--.*?-->/m,
23
+ %r{<pre\b.*?</pre\s*>}im,
24
+ %r{<script\b.*?</script\s*>}im,
25
+ %r{<style\b.*?</style\s*>}im,
26
+ %r{<textarea\b.*?</textarea\s*>}im
27
+ ].freeze
28
+
29
+ Heading = Struct.new(:level, :text, :id, :children)
30
+
4
31
  def initialize(html, config = {})
32
+ config ||= {}
5
33
  @html = html
6
- @min_headings = config["min_headings"] || 2
7
- @title = config["title"] || "Table of Contents"
8
- @levels = config["levels"] || [2, 3]
34
+ @min_headings = integer_option(config["min_headings"], 2)
35
+ @levels = normalize_levels(config["levels"])
36
+ @title = config.key?("title") ? config["title"] : DEFAULT_TITLE
37
+ @title = nil if @title == false || @title.to_s.strip.empty?
38
+ @title_tag = TITLE_TAGS.include?(config["title_tag"].to_s.downcase) ? config["title_tag"].to_s.downcase : "h2"
9
39
  end
10
40
 
11
41
  def build
12
42
  return @html if @html.nil? || @html.empty?
43
+ return @html if @html.include?('<nav class="toc"')
13
44
 
14
- headings = extract_headings
15
- h2s = headings.select { |h| h[:level] == 2 }
16
- return @html if h2s.size < @min_headings
45
+ found = find_headings
46
+ listed = found.select { |h| @levels.include?(h[:level]) && !h[:text].empty? }
47
+ return @html if listed.empty? || listed.size < @min_headings
17
48
 
18
- toc_html = build_toc(headings)
19
- inject_toc(toc_html)
49
+ edits = {}
50
+ taken = assign_ids(found, listed, edits)
51
+ tree = build_tree(listed)
52
+
53
+ anchor = found.find { |h| h[:level] == 2 } || listed.first
54
+ toc = build_toc(tree, taken)
55
+ edits[anchor[:start]] = toc.chomp + (edits[anchor[:start]] || @html[anchor[:start], anchor[:tag].length])
56
+ splice(edits, found, anchor)
20
57
  end
21
58
 
22
59
  private
23
60
 
24
- def extract_headings
25
- levels_pattern = @levels.map(&:to_s).join
61
+ def integer_option(value, default)
62
+ Integer(value)
63
+ rescue ArgumentError, TypeError
64
+ default
65
+ end
66
+
67
+ def normalize_levels(value)
68
+ levels = Array(value.nil? ? DEFAULT_LEVELS : value).map { |l| Integer(l.to_s, exception: false) }
69
+ levels = levels.compact.select { |l| (1..6).cover?(l) }.uniq
70
+ levels.empty? ? DEFAULT_LEVELS : levels
71
+ end
72
+
73
+ # Every heading in the content, with positions, skipping look-alikes in
74
+ # code blocks, comments and scripts.
75
+ def find_headings
76
+ ignored = ignored_ranges
26
77
  headings = []
27
- @html.scan(/<h([#{levels_pattern}])[^>]*>(.*?)<\/h\1>/im) do |level, content|
28
- text = strip_tags(content)
29
- headings << { level: level.to_i, text: text, slug: slugify(text) }
78
+ pos = 0
79
+ while (m = HEADING.match(@html, pos))
80
+ pos = m.end(0)
81
+ next if ignored.any? { |r| r.cover?(m.begin(0)) }
82
+
83
+ attrs = m[2].to_s
84
+ id = attrs[ID_ATTR, 1] || attrs[ID_ATTR, 2] || attrs[ID_ATTR, 3]
85
+ headings << {
86
+ level: m[1].to_i, attrs: attrs, id: (id.nil? || id.strip.empty? ? nil : id),
87
+ text: heading_text(m[3]), start: m.begin(0),
88
+ tag: "<h#{m[1]}#{attrs}>"
89
+ }
30
90
  end
31
91
  headings
32
92
  end
33
93
 
34
- def strip_tags(html)
35
- html.gsub(/<[^>]+>/, "").strip
94
+ def ignored_ranges
95
+ IGNORED.flat_map do |re|
96
+ ranges = []
97
+ pos = 0
98
+ while (m = re.match(@html, pos))
99
+ ranges << (m.begin(0)...m.end(0))
100
+ pos = m.end(0)
101
+ end
102
+ ranges
103
+ end
36
104
  end
37
105
 
38
- def slugify(text)
39
- text.downcase.gsub(/[^\w\s-]/, "").gsub(/[\s_]+/, "-").gsub(/^-+|-+$/, "")
106
+ # Text content of the heading's inner HTML. The input is already HTML
107
+ # text, so entities are kept as they are; anything that could still be
108
+ # read as markup is escaped.
109
+ def heading_text(inner)
110
+ text = inner.gsub(/<!--.*?-->/m, "").gsub(/<[^>]*>/m, "")
111
+ text = text.gsub(/&(?!(?:[a-zA-Z][a-zA-Z0-9]*|#\d+|#[xX]\h+);)/, "&amp;")
112
+ text = text.gsub("<", "&lt;").gsub(">", "&gt;")
113
+ text.gsub(/\s+/, " ").strip
40
114
  end
41
115
 
42
- def build_toc(headings)
43
- items_html = build_items(headings)
44
- <<~HTML
45
- <nav class="toc" aria-label="Table of contents">
46
- <h2 class="toc__title">#{@title}</h2>
47
- <ul class="toc__list">
48
- #{items_html.chomp}
49
- </ul>
50
- </nav>
51
- HTML
52
- end
116
+ # Gives every listed heading without an id a unique one, unique against
117
+ # every id already in the content. Returns the set of ids in use.
118
+ def assign_ids(found, listed, edits)
119
+ taken = {}
120
+ @html.scan(ANY_ID_ATTR) { |a, b, c| taken[a || b || c] = true }
121
+ listed.each do |h|
122
+ next if h[:id]
53
123
 
54
- def build_items(headings)
55
- html = ""
56
- current_h2 = nil
57
- pending_subs = []
58
-
59
- flush = lambda do
60
- if current_h2
61
- html += " <li class=\"toc__item\"><a href=\"##{current_h2[:slug]}\">#{current_h2[:text]}</a>"
62
- unless pending_subs.empty?
63
- html += "\n <ul class=\"toc__sublist\">\n"
64
- pending_subs.each do |sub|
65
- html += " <li class=\"toc__item--sub\"><a href=\"##{sub[:slug]}\">#{sub[:text]}</a></li>\n"
66
- end
67
- html += " </ul>\n "
68
- end
69
- html += "</li>\n"
70
- pending_subs = []
71
- current_h2 = nil
124
+ base = slugify(h[:text])
125
+ candidate = base
126
+ n = 0
127
+ while taken[candidate]
128
+ n += 1
129
+ candidate = "#{base}-#{n}"
72
130
  end
131
+ taken[candidate] = true
132
+ h[:id] = candidate
133
+ edits[h[:start]] = with_id(h)
73
134
  end
135
+ taken
136
+ end
74
137
 
75
- headings.each do |h|
76
- if h[:level] == 2
77
- flush.call
78
- current_h2 = h
79
- else
80
- if current_h2
81
- pending_subs << h
82
- else
83
- # h3 with no preceding h2 — treat as top-level
84
- html += " <li class=\"toc__item\"><a href=\"##{h[:slug]}\">#{h[:text]}</a></li>\n"
85
- end
86
- end
138
+ def with_id(heading)
139
+ attrs = heading[:attrs]
140
+ attrs = attrs.sub(ID_ATTR, "") # drop an empty id=""
141
+ "<h#{heading[:level]} id=\"#{heading[:id]}\"#{attrs}>"
142
+ end
143
+
144
+ # Text to anchor-style slug. Keeps letters (any script), digits,
145
+ # underscores and hyphens like kramdown does.
146
+ def slugify(text)
147
+ plain = CGI.unescapeHTML(text.to_s)
148
+ slug = plain.downcase.gsub(/[^\p{Alnum}\s_-]/, "").strip.gsub(/\s+/, "-").gsub(/\A-+|-+\z/, "")
149
+ slug.empty? ? "section" : slug
150
+ end
151
+
152
+ # Nest by level. A heading becomes a child of the nearest earlier heading
153
+ # with a lower level, so skipped levels (h2 then h4) still nest.
154
+ def build_tree(listed)
155
+ roots = []
156
+ stack = []
157
+ listed.each do |h|
158
+ node = Heading.new(h[:level], h[:text], h[:id], [])
159
+ stack.pop while stack.any? && stack.last.level >= node.level
160
+ (stack.empty? ? roots : stack.last.children) << node
161
+ stack << node
162
+ end
163
+ roots
164
+ end
165
+
166
+ def build_toc(tree, taken)
167
+ title_id = unique_title_id(taken)
168
+ open_tag = if @title
169
+ %(<nav class="toc" aria-labelledby="#{title_id}">)
170
+ else
171
+ '<nav class="toc" aria-label="Table of contents">'
172
+ end
173
+ out = +"#{open_tag}\n"
174
+ if @title
175
+ out << %( <#{@title_tag} class="toc__title" id="#{title_id}">#{CGI.escapeHTML(@title.to_s)}</#{@title_tag}>\n)
87
176
  end
177
+ out << " <ul class=\"toc__list\">\n"
178
+ tree.each { |node| out << item_html(node, 1, "toc__item") }
179
+ out << " </ul>\n</nav>\n"
180
+ end
88
181
 
89
- flush.call
90
- html
182
+ def unique_title_id(taken)
183
+ id = TITLE_ID
184
+ n = 0
185
+ while taken[id]
186
+ n += 1
187
+ id = "#{TITLE_ID}-#{n}"
188
+ end
189
+ id
91
190
  end
92
191
 
93
- def inject_toc(toc_html)
94
- first_h2 = @html.match(/<h2[^>]*>/i)
95
- return @html unless first_h2
192
+ def item_html(node, depth, css)
193
+ pad = " " * (depth + 1)
194
+ href = node.id.gsub('"', "&quot;")
195
+ out = +"#{pad}<li class=\"#{css}\"><a href=\"##{href}\">#{node.text}</a>"
196
+ if node.children.empty?
197
+ out << "</li>\n"
198
+ else
199
+ out << "\n#{pad} <ul class=\"toc__sublist\">\n"
200
+ node.children.each { |child| out << item_html(child, depth + 2, "toc__item--sub") }
201
+ out << "#{pad} </ul>\n#{pad}</li>\n"
202
+ end
203
+ out
204
+ end
96
205
 
97
- @html.sub(first_h2[0], toc_html.chomp + first_h2[0])
206
+ # Applies the heading and insertion edits. Edits replace the opening tag
207
+ # that starts at the given offset; applied from the end so offsets hold.
208
+ def splice(edits, found, anchor)
209
+ result = @html.dup
210
+ edits.keys.sort.reverse_each do |start|
211
+ heading = found.find { |h| h[:start] == start }
212
+ length = heading[:tag].length
213
+ result[start, length] = edits[start]
214
+ end
215
+ result
98
216
  end
99
217
  end
100
218
  end
@@ -1,5 +1,5 @@
1
1
  module Jekyll
2
2
  module TocGenerator
3
- VERSION = "0.1.0"
3
+ VERSION = "0.2.0"
4
4
  end
5
5
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-toc-generator
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jason Chance
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-08-21 00:00:00.000000000 Z
10
+ date: 2026-11-29 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: jekyll
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: '4.0'
18
+ version: '4.2'
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
- version: '4.0'
25
+ version: '4.2'
26
26
  email:
27
27
  - jason@jasonchance.com
28
28
  executables: []
@@ -38,7 +38,11 @@ files:
38
38
  homepage: https://github.com/jchance/jekyll-toc-generator
39
39
  licenses:
40
40
  - MIT
41
- metadata: {}
41
+ metadata:
42
+ source_code_uri: https://github.com/jchance/jekyll-toc-generator
43
+ changelog_uri: https://github.com/jchance/jekyll-toc-generator/blob/master/CHANGELOG.md
44
+ bug_tracker_uri: https://github.com/jchance/jekyll-toc-generator/issues
45
+ rubygems_mfa_required: 'true'
42
46
  rdoc_options: []
43
47
  require_paths:
44
48
  - lib
@@ -46,7 +50,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
46
50
  requirements:
47
51
  - - ">="
48
52
  - !ruby/object:Gem::Version
49
- version: '2.7'
53
+ version: '3.0'
50
54
  required_rubygems_version: !ruby/object:Gem::Requirement
51
55
  requirements:
52
56
  - - ">="