/*
* @title TOC
* @description create table of contents w/ Autopaging
* @include http://*
* @include https://*
* @license MIT License http://opensource.org/licenses/MIT
* @contributor rikuba http://let.hatelabo.jp/rikuba/let/gYC-yqG0xYLkFw (Fork of)
* @author noromanba
* @javascript_url
*/
// # Changes
// - replace Array generics to prototype call
// - support AutoPatchWork and AutoPager
(function () {
init(document);
Array.prototype.forEach.call(frames, function (frame) {
try {
init(frame.document);
} catch (e) {}
});
function init(doc) {
var container = doc.querySelector('#bookmarklet_TOC');
if (container) {
container.parentNode.removeChild(container);
return;
}
container = doc.createElement('div');
container.id = 'bookmarklet_TOC';
container.appendChild(createTOC(doc));
doc.body.appendChild(container);
var style = doc.createElement('style');
style.type = 'text/css';
style.textContent = [
'#bookmarklet_TOC { background: rgba(0, 0, 0, 0.9); color: #fff;',
'text-align: left; font: 90%/1.5 sans-serif;',
'width: 30px; height: 30px; z-index: 256;',
'max-width: 600px; max-height: 600px; overflow-y: auto;',
'position: fixed; top: 0; right: 0; margin: 0; padding: 0;',
'-moz-border-radius: 0 0 0 8px; border-radius: 0 0 0 8px; }',
'#bookmarklet_TOC:hover { width: auto; height: auto;',
'padding: 1ex 1em; }',
'#bookmarklet_TOC ol { list-style: none; display: none;',
'margin: 0; padding: 0; }',
'#bookmarklet_TOC ol ol { margin-left: 1.5em; }',
'#bookmarklet_TOC:hover ol { display: block; }',
'#bookmarklet_TOC span:hover { cursor: pointer; ',
'text-decoration: underline; }'
].join('\n');
doc.querySelector('head').appendChild(style);
// TODO replace to MutiotionObserver
[
'AutoPagerize_DOMNodeInserted',
'AutoPatchWork.DOMNodeInserted',
'AutoPagerAfterInsert'
].forEach(function (pager) {
doc.addEventListener(pager, function (evt) {
container.appendChild(createTOC(evt.target));
}, false);
});
}
function createTOC(root) {
var doc = root.ownerDocument || root;
var contents, listContainer;
contents = listContainer = doc.createElement('ol');
var lastLevel = 1;
Array.prototype.forEach.call(root.querySelectorAll('h1, h2, h3, h4, h5, h6'), function (headline) {
// create paragraph
var hLevel = Number(headline.nodeName.slice(1));
var depth = lastLevel - hLevel; // TODO remove depth
if (lastLevel < hLevel) {
while (depth++) { // nest paragraph
listContainer = (listContainer.hasChildNodes() ? listContainer.lastChild : listContainer.appendChild(doc.createElement('li'))).
appendChild(doc.createElement('ol'));
}
} else if (hLevel < lastLevel) {
while (depth--) {
listContainer = listContainer.parentNode.parentNode; // parent <ol>
}
}
var title = listContainer.appendChild(doc.createElement('li')).appendChild(doc.createElement('span'));
title.appendChild(doc.createTextNode(headline.textContent || ''));
title.addEventListener('click', function () {
headline.scrollIntoView();
}, false);
lastLevel = hLevel;
});
return contents;
}
})();