Skip to content

Commit

Permalink
Append identical header ids with counter
Browse files Browse the repository at this point in the history
This ensures unique HTML id's in line with the HTML spec, and allows anchors
to always reference the intended header.

Fixes GitbookIO#27
  • Loading branch information
emilbayes committed Sep 20, 2015
1 parent e7b8675 commit fe44809
Show file tree
Hide file tree
Showing 7 changed files with 28 additions and 15 deletions.
19 changes: 18 additions & 1 deletion lib/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ var defaultOptions = {

function Renderer(options) {
this.options = options || defaultOptions;

this._idCounter = {}
}

Renderer.prototype.code = function(code, lang, escaped) {
Expand Down Expand Up @@ -56,7 +58,22 @@ Renderer.prototype._createId = function(str) {
} catch (e) {
str = str.replace(/[^\w]+/g, '-');
}
return str.replace(/-$/, '');
str = str.replace(/-$/, '');

// make sure internal id has the current id registered. If not, initialize it
// at 0
if (this._idCounter[str] === undefined) {
this._idCounter[str] = 0;
}

// Increment the internal counter for the current id, and save new count
var cnt = ++this._idCounter[str];

if (cnt > 1) {
str = str + '-' + cnt
}

return str;
};

Renderer.prototype.heading = function(text, level, raw) {
Expand Down
2 changes: 2 additions & 0 deletions test/new/identical_header_1.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h1 id="identical-ids">Identical IDs</h1>
<h1 id="identical-ids-2">Identical IDs</h1>
3 changes: 3 additions & 0 deletions test/new/identical_header_1.text
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# identical ids

# identical ids
2 changes: 2 additions & 0 deletions test/new/identical_header_2.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h1 id="identical-ids">Identical IDs</h1>
<h1 id="identical-ids-2">Identical IDs</h1>
3 changes: 3 additions & 0 deletions test/new/identical_header_2.text
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# identical ids

# identical ids
7 changes: 0 additions & 7 deletions test/tests/header_id.html

This file was deleted.

7 changes: 0 additions & 7 deletions test/tests/header_id.txt

This file was deleted.

0 comments on commit fe44809

Please sign in to comment.