Skip to content

Commit

Permalink
Add id attributes to heading elements
Browse files Browse the repository at this point in the history
This changes the generated HTML to include `id` attributes on any heading (e.g. `h3`) elements.

Currently, `bit-docs-html-toc` will add `id` attributes when it parses the content and creates the TOC links. This means that JS has to be downloaded, parsed, and run before `bit-docs-html-toc` runs its code, and _then_ there has to be more JS to scroll down to the right fragment.

This takes JS completely out of the equation by including the `id` attributes in the source HTML, so JS doesn’t need to load and `bit-docs-html-toc` isn’t required to make fragment URLs work either.

Part of https://bitovi.atlassian.net/browse/LD-203
  • Loading branch information
chasenlehara committed Aug 17, 2024
1 parent 3fa4d7c commit a8c428c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
1 change: 1 addition & 0 deletions html_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ var readFile = Q.denodeify(fs.readFile);
var bitDocsHTML = require("./bit-docs");

require("./build/build_test");
require("./stmd_test");

describe("bit-docs-generate-html", function(){
beforeEach(function(){
Expand Down
15 changes: 13 additions & 2 deletions stmd.js
Original file line number Diff line number Diff line change
Expand Up @@ -1476,8 +1476,12 @@ var renderBlock = function(block, in_tight_list) {
this.innersep);
case 'ATXHeader':
case 'SetextHeader':
var rendered = this.renderInlines(block.inline_content);
tag = 'h' + block.level;
return inTags(tag, [], this.renderInlines(block.inline_content));
attr = [
['id', makeHeadingId(rendered)]
];
return inTags(tag, attr, rendered);
case 'IndentedCode':
return inTags('pre', [],
inTags('code', [], this.escape(block.string_content)));
Expand Down Expand Up @@ -1544,4 +1548,11 @@ function HtmlRenderer(){
exports.DocParser = DocParser;
exports.HtmlRenderer = HtmlRenderer;

})(typeof exports === 'undefined' ? this.stmd = {} : exports);
})(typeof exports === 'undefined' ? this.stmd = {} : exports);

function makeHeadingId(text) {
return (text || "")
.replace(/\s/g, "-") // replace spaces with dashes
.replace(/[^\w\-]/g, "") // remove punctuation
.toLowerCase();
}
14 changes: 14 additions & 0 deletions stmd_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var assert = require('assert');

var stmd = require("./stmd");

describe("bit-docs-generate-html/stmd", function () {
it("adds id attributes to heading elements", function () {
var parser = new stmd.DocParser();
var renderer = new stmd.HtmlRenderer();
var markdown = "# Hello world"
var rendered = renderer.render(parser.parse(markdown));
var expected = '<h1 id="hello-world">Hello world</h1>';
assert.equal(rendered.trim(), expected, "id attributes are present");
});
});

0 comments on commit a8c428c

Please sign in to comment.