forked from magento/devdocs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoc.js
94 lines (79 loc) · 2.41 KB
/
toc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
93
94
// TODO: Refactor this
// This script copies markdown toc into the .page-info
//$('#markdown-toc').clone().addClass('nav').appendTo( '.page-info' );
$('#markdown-toc').hide();
// Prepend link anchor to content headers
var $toc = $('<div>',{
class: 'page-toc',
});
$toc.appendTo('.page-info');
$toc.append('<ul class="nav"></ul>');
// Loop through each h2..h3 and build a TOC
$(".content-wrap :header:not(h1)").each(function(){
var $this = $(this),
id = $this.attr('id'),
no_toc = $this.hasClass('no_toc'),
inside_collapsible = $this.parents('.collapsible').length,
collapsible_title = $this.hasClass('collapsible-title'),
anchor_text = '',
show = true;
// check if we need to process the link. do not process links that are hidden inside collapsible blocks
if ( inside_collapsible ) {
show = false;
if ( collapsible_title) {
show = true;
}
}
if ( no_toc ) {
show = false;
}
if ( show ) {
// check if we have id on heading already
if ( id ) {
// use that id for the anchor
anchor_text = id;
} else {
// generate id from the heading text
var text = $this.text();
anchor_text = text;
}
// clean up the anchor
anchor_text = anchor_text.replace(/\s/g, '-').replace(/[`~!@#$%^&*()|+\=?;:'",.<>\{\}\[\]\\\/]/gi, '');
// prepend anhor to title
var $link = $('<a>',{
href: '#' + anchor_text,
class: 'anchor'
});
// Add link to the header
$this.prepend( $link );
// Add id to the header if needed
if ( !id ) {
$this.attr('id', anchor_text);
}
// Allow only h2 and h3 tags in page toc
var tag_name = $this.prop('tagName').toLowerCase();
if ( tag_name == 'h2' || tag_name == 'h3' ) {
var $li = $('<li class="' + tag_name + '"><a href="#' + anchor_text + '"></a></li>');
$li.find('a').text( $this.text() );
$toc.find('ul').append($li);
}
//console.log(anchor_text);
}
});
// do not show toc for less than 2 headings
if ( $toc.find('li').length <= 1 ) {
$toc.hide();
}
// Page toc on right side sticks to the browser window
$('body').scrollspy({
target: '.page-info',
offset: 61
});
$('.page-info .page-toc').affix({
offset: {
top: 40,
bottom: function () {
return (this.bottom = $('#footer').outerHeight(true))
}
}
});