Table of Contents Everywhere

On pages which do not have a Table of Contents, but should do, create one! (I actually use this as a bookmarklet, so I can load it onto the current page only when I want it.)

  1. // ==UserScript==
  2. // @name Table of Contents Everywhere
  3. // @description On pages which do not have a Table of Contents, but should do, create one! (I actually use this as a bookmarklet, so I can load it onto the current page only when I want it.)
  4. // @downstreamURL http://userscripts.org/scripts/source/123255.user.js
  5. // @license ISC
  6. // @version 1.0.5
  7. // @include http://*/*
  8. // @include https://*/*
  9. // @include file://*
  10. // @grant none
  11. // @namespace https://greatest.deepsurf.us/users/8615
  12. // ==/UserScript==
  13.  
  14. var minimumItems = 4; // Don't display a TOC for fewer than this number of entries.
  15. var maximumItems = 800; // Don't display a TOC for more than this number of entries.
  16. var delayBeforeRunning = 1600;
  17. var showAnchors = true;
  18. var pushAnchorsToBottom = true; // They can look messy interspersed amongst TOC tree
  19. var startRolledUp = false;
  20. var runInIframes = false;
  21.  
  22. // 2015-05-12 Improved shadow styling
  23. // 2015-01-02 Improved styling
  24. // 2012-02-19 Removed verbose log. Added showAnchors. Added https since everyone is forcing that now (e.g. github).
  25. // 2012-02-18 Fixed sorting of TOC elements. Added anchor unicode.
  26. // 2012-01-30 Implemented GM_log and GM_addStyle so this script can be included on any web page.
  27.  
  28. // TODO: derbyjs.com is an example of a site with a <div id=toc> that has no
  29. // hide or close buttons. Perhaps we should add close and rollup buttons if we
  30. // cannot find any recognisable buttons. (Medawiki tocs for example, do have a
  31. // show/hide button, so we don't want to add to them!)
  32.  
  33. // TODO: whatwg.org presents its own TOC but with no title. Our buttons appear in the wrong place!
  34.  
  35. // BUG: Displays links for elements which may be invisible due to CSS. (e.g. see github markdown pages)
  36.  
  37. // TODO CONSIDER: TOC hijacking _whitelist_ to avoid creeping fixes for per-site issues. Different problems are appearing on a small proportion of websites when we try to consume/hijack their existing TOC. It would be better to create our own *separate* TOC as standard, and only hijack *known* friendly TOCs such as WikiMedia's / Wikia's.
  38. // (We might offer a tiny button "Try to Use Page TOC" allowing us to test hijack before adding the site to the whitelist.)
  39.  
  40. // Do not run in iframes
  41. if (self !== window.top && !runInIframes) {
  42. return;
  43. }
  44.  
  45. setTimeout(function(){
  46.  
  47.  
  48.  
  49. // Implementing these two means we can run as a stand-alone script on any page.
  50. if (typeof GM_log == "undefined") {
  51. GM_log = function() {
  52. // Firefox's console.log does not have apply or call functions!
  53. var txt = Array.prototype.join.call(arguments," ");
  54. console.log(txt);
  55. };
  56. }
  57. if (typeof GM_addStyle == "undefined") {
  58. this.GM_addStyle = function(css) {
  59. var s = document.createElement("style");
  60. s.type = 'text/css';
  61. s.innerHTML = css;
  62. document.getElementsByTagName("head")[0].appendChild(s);
  63. };
  64. }
  65.  
  66. // Implementing these allows us to remember toggled state. (Chrome's set/getValue don't work.)
  67. if (typeof GM_setValue == 'undefined' || window.navigator.vendor.match(/Google/)) {
  68. GM_log("[TOCE] Adding fallback implementation of GM_set/getValue");
  69.  
  70. if (typeof localStorage == 'undefined') {
  71.  
  72. GM_getValue = function(name, defaultValue) {
  73. return defaultValue;
  74. };
  75.  
  76. } else {
  77.  
  78. GM_setValue = function(name, value) {
  79. value = (typeof value)[0] + value;
  80. localStorage.setItem(name, value);
  81. };
  82.  
  83. GM_getValue = function(name, defaultValue) {
  84. var value = localStorage.getItem(name);
  85. if (!value)
  86. return defaultValue;
  87. var type = value[0];
  88. value = value.substring(1);
  89. switch (type) {
  90. case 'b':
  91. return value == 'true';
  92. case 'n':
  93. return Number(value);
  94. default:
  95. return value;
  96. }
  97. };
  98.  
  99. }
  100.  
  101. }
  102.  
  103. function loadScript(url,thenCallFn) {
  104. GM_log("[TOCE] Loading fallback: "+url);
  105. var scr = document.createElement("script");
  106. scr.src = url;
  107. scr.type = "text/javascript"; // Konqueror 3.5 needs this!
  108. if (thenCallFn) {
  109. var called = false;
  110. function onceOnlyCallback(evt) {
  111. if (!called) {
  112. called = true;
  113. thenCallFn(evt);
  114. }
  115. }
  116. function errorCallback(evt) {
  117. GM_log("[TOCE] Failed to load: "+url,evt);
  118. onceOnlyCallback(evt);
  119. }
  120. scr.addEventListener('load',onceOnlyCallback,false);
  121. scr.addEventListener('error',errorCallback,false);
  122. // Fallback in case above events unsupported by browser (e.g. Konq 3.5)
  123. setTimeout(onceOnlyCallback,5000);
  124. }
  125. document.body.appendChild(scr);
  126. }
  127.  
  128. // Modified for this script's needs.
  129. // Returns e.g. "/*[2]/*[4]/*[9]"
  130. function getXPath(node) {
  131. var parent = node.parentNode;
  132. if (!parent) {
  133. return '';
  134. }
  135. var siblings = parent.childNodes;
  136. var totalCount = 0;
  137. var thisCount = -1;
  138. for (var i=0;i<siblings.length;i++) {
  139. var sibling = siblings[i];
  140. if (true /*sibling.nodeType == node.nodeType*/) {
  141. totalCount++;
  142. }
  143. if (sibling == node) {
  144. thisCount = totalCount;
  145. break;
  146. }
  147. }
  148. // return getXPath(parent) + '/*' /*node.nodeName.toLowerCase()*/ + (totalCount>1 ? '[' + thisCount + ']' : '' );
  149. // Remain consistent:
  150. return getXPath(parent) + '/*' + '[' + thisCount + ']';
  151. }
  152.  
  153. // Konqueror 3.5 lacks some things!
  154. if (!Array.prototype.map) {
  155. Array.prototype.map = function(fn) {
  156. var l = [];
  157. for (var i=0;i<this.length;i++) {
  158. l.push(fn(this[i]));
  159. }
  160. return l;
  161. };
  162. }
  163. if (!String.prototype.trim) {
  164. String.prototype.trim = function() {
  165. return this.replace(/^[ \t]+/,'').replace(/[ \t]+$/,'');
  166. };
  167. }
  168.  
  169.  
  170.  
  171. // The following block is mirrored in wikiindent.user.js
  172.  
  173. // See also: resetProps
  174. function clearStyle(elem) {
  175. // We set some crucial defaults, so we don't inherit CSS from the page:
  176. elem.style.display = 'inline';
  177. elem.style.position = 'static';
  178. elem.style.top = 'auto';
  179. elem.style.right = 'auto';
  180. elem.style.bottom = 'auto';
  181. elem.style.left = 'auto';
  182. elem.style.color = 'black';
  183. elem.style.backgroundColor = '#f4f4f4';
  184. elem.style.border = '0px solid magenta';
  185. elem.style.padding = '0px';
  186. elem.style.margin = '1px';
  187. return elem;
  188. }
  189.  
  190. function newNode(tag,data) {
  191. var elem = document.createElement(tag);
  192. if (data) {
  193. for (var prop in data) {
  194. elem[prop] = data[prop];
  195. }
  196. }
  197. return elem;
  198. }
  199.  
  200. function newSpan(text) {
  201. return clearStyle(newNode("span",{textContent:text}));
  202. }
  203.  
  204. function addCloseButtonTo(where, toc) {
  205. var closeButton = newSpan("[X]");
  206. // closeButton.style.float = 'right';
  207. // closeButton.style.cssFloat = 'right'; // Firefox
  208. // closeButton.style.styleFloat = 'right'; // IE7
  209. closeButton.style.cursor = 'pointer';
  210. closeButton.style.paddingLeft = '5px';
  211. closeButton.onclick = function() { toc.parentNode.removeChild(toc); };
  212. closeButton.id = "closeTOC";
  213. where.appendChild(closeButton);
  214. }
  215.  
  216. function addHideButtonTo(toc, tocInner) {
  217. var rollupButton = newSpan("[-]");
  218. // rollupButton.style.float = 'right';
  219. // rollupButton.style.cssFloat = 'right'; // Firefox
  220. // rollupButton.style.styleFloat = 'right'; // IE7
  221. rollupButton.style.cursor = 'pointer';
  222. rollupButton.style.paddingLeft = '10px';
  223. function toggleRollUp() {
  224. if (tocInner.style.display == 'none') {
  225. tocInner.style.display = '';
  226. rollupButton.textContent = "[-]";
  227. } else {
  228. tocInner.style.display = 'none';
  229. rollupButton.textContent = "[+]";
  230. }
  231. setTimeout(function(){
  232. GM_setValue("TOCE_rolledUp", tocInner.style.display=='none');
  233. },5);
  234. }
  235. rollupButton.onclick = toggleRollUp;
  236. rollupButton.id = "togglelink";
  237. toc.appendChild(rollupButton);
  238. if (startRolledUp || GM_getValue("TOCE_rolledUp",false)) {
  239. toggleRollUp();
  240. }
  241. }
  242.  
  243. function addButtonsConditionally(toc) {
  244.  
  245. function verbosely(fn) {
  246. return function() {
  247. // GM_log("[WI] Calling: "+fn+" with ",arguments);
  248. return fn.apply(this,arguments);
  249. };
  250. };
  251.  
  252. // Provide a hide/show toggle button if the TOC does not already have one.
  253.  
  254. // Wikimedia's toc element is actually a table. We must put the
  255. // buttons in the title div, if we can find it!
  256.  
  257. var tocTitle = document.getElementById("toctitle"); // Wikipedia
  258. tocTitle = tocTitle || toc.getElementsByTagName("h2")[0]; // Mozdev
  259. // tocTitle = tocTitle || toc.getElementsByTagName("div")[0]; // Fingers crossed for general
  260. tocTitle = tocTitle || toc.firstChild; // Fingers crossed for general
  261.  
  262. // Sometimes Wikimedia does not add a hide/show button (if the TOC is small).
  263. // We cannot test this immediately, because it gets loaded in later!
  264. function addButtonsNow() {
  265.  
  266. var hideShowButton = document.getElementById("togglelink");
  267. if (!hideShowButton) {
  268. var tocInner = toc.getElementsByTagName("ol")[0]; // Mozdev (can't get them all!)
  269. tocInner = tocInner || toc.getElementsByTagName("ul")[0]; // Wikipedia
  270. tocInner = tocInner || toc.getElementsByTagName("div")[0]; // Our own
  271. if (tocInner) {
  272. verbosely(addHideButtonTo)(tocTitle || toc, tocInner);
  273. }
  274. }
  275.  
  276. // We do this later, to ensure it appears on the right of
  277. // any existing [hide/show] button.
  278. if (document.getElementById("closeTOC") == null) {
  279. verbosely(addCloseButtonTo)(tocTitle || toc, toc);
  280. }
  281.  
  282. }
  283.  
  284. // Sometimes Wikimedia does not add a hide/show button (if the TOC is small).
  285. // We cannot test this immediately, because it gets loaded in later!
  286. if (document.location.href.indexOf("wiki") >= 0) {
  287. setTimeout(addButtonsNow,2000);
  288. } else {
  289. addButtonsNow();
  290. }
  291.  
  292. }
  293.  
  294. // End mirror.
  295.  
  296.  
  297.  
  298. // == Main == //
  299.  
  300. function buildTableOfContents() {
  301.  
  302. // Can we make a TOC?
  303. var headers = "//h1 | //h2 | //h3 | //h4 | //h5 | //h6 | //h7 | //h8";
  304. var anchors = "//a[@name]";
  305. // For coffeescript.org:
  306. var elementsMarkedAsHeader = "//*[@class='header']";
  307. // However on many sites that might be the thing opposite the footer, and probably not of note.
  308.  
  309. var xpathQuery = headers+(showAnchors?"|"+anchors:"")+"|"+elementsMarkedAsHeader;
  310. var nodeSnapshot = document.evaluate(xpathQuery,document,null,6,null);
  311. //// Chrome needs lower-case 'h', Firefox needs upper-case 'H'!
  312. // var nodeSnapshot = document.evaluate("//*[starts-with(name(.),'h') and substring(name(.),2) = string(number(substring(name(.),2)))]",document,null,6,null);
  313. // var nodeSnapshot = document.evaluate("//*[starts-with(name(.),'H') and substring(name(.),2) = string(number(substring(name(.),2)))]",document,null,6,null);
  314.  
  315. if (nodeSnapshot.snapshotLength > maximumItems) {
  316. GM_log("[TOCE] Too many nodes for table (sanity): "+nodeSnapshot.snapshotLength);
  317. } else if (nodeSnapshot.snapshotLength >= minimumItems) {
  318.  
  319. GM_log("[TOCE] Making TOC with "+nodeSnapshot.snapshotLength+" nodes.");
  320.  
  321. var toc = newNode("div");
  322. toc.id = 'toc';
  323.  
  324. // var heading = newSpan("Table of Contents");
  325. var heading = clearStyle(newNode("h2",{textContent:"Table of Contents"}));
  326. heading.id = 'toctitle'; // Like Wikipedia
  327. heading.style.fontWeight = "bold";
  328. heading.style.fontSize = "100%";
  329. toc.appendChild(heading);
  330.  
  331. var table = newNode("div");
  332. // addHideButtonTo(toc,table);
  333. table.id = 'toctable'; // Our own
  334. toc.appendChild(table);
  335.  
  336. // We need to do this *after* adding the table.
  337. addButtonsConditionally(toc);
  338.  
  339. // The xpath query did not return the elements in page-order.
  340. // We sort them back into the order they appear in the document
  341. // Yep it's goofy code, but it works.
  342. var nodeArray = [];
  343. for (var i=0;i<nodeSnapshot.snapshotLength;i++) {
  344. var node = nodeSnapshot.snapshotItem(i);
  345. nodeArray.push(node);
  346. // We need to sort numerically, since with strings "24" < "4"
  347. node.magicPath = getXPath(node).substring(3).slice(0,-1).split("]/*[").map(Number);
  348. if (pushAnchorsToBottom && node.tagName==="A") {
  349. node.magicPath.unshift(+Infinity);
  350. }
  351. }
  352. nodeArray.sort(function(a,b){
  353. // GM_log("[TOCE] Comparing "+a.magicPath+" against "+b.magicPath);
  354. for (var i=0;i<a.magicPath.length;i++) {
  355. if (i >= b.magicPath.length) {
  356. return +1; // b wins (comes earlier)
  357. }
  358. if (a.magicPath[i] > b.magicPath[i]) {
  359. return +1; // b wins
  360. }
  361. if (a.magicPath[i] < b.magicPath[i]) {
  362. return -1; // a wins
  363. }
  364. }
  365. return -1; // assume b is longer, or they are equal
  366. });
  367.  
  368. for (var i=0;i<nodeArray.length;i++) {
  369. var node = nodeArray[i];
  370.  
  371. var level = (node.tagName.substring(1) | 0) - 1;
  372. if (level < 0) {
  373. level = 0;
  374. }
  375.  
  376. var linkText = node.textContent && node.textContent.trim() || node.name;
  377. if (!linkText) {
  378. continue; // skip things we cannot name
  379. }
  380.  
  381. var link = clearStyle(newNode("A"));
  382. if (linkText.length > 40) {
  383. link.title = linkText; // Show full title on hover
  384. linkText = linkText.substring(0,32)+"...";
  385. }
  386. link.textContent = linkText;
  387. /* Dirty hack for Wikimedia: */
  388. if (link.textContent.substring(0,7) == "[edit] ") {
  389. link.textContent = link.textContent.substring(7);
  390. }
  391. if (node.tagName == "A") {
  392. link.href = '#'+node.name;
  393. } else {
  394. (function(node){
  395. link.onclick = function(evt){
  396. node.scrollIntoView();
  397.  
  398. // Optional: CSS animation
  399. // NOT WORKING!
  400. /*
  401. node.id = "toc_current_hilight";
  402. ["","-moz-","-webkit-"].forEach(function(insMode){
  403. GM_addStyle("#toc_current_hilight { "+insMode+"animation: 'fadeHighlight 4s ease-in 1s alternate infinite'; }@"+insMode+"keyframes fadeHighlight { 0%: { background-color: yellow; } 100% { background-color: rgba(255,255,0,0); } }");
  404. });
  405. */
  406.  
  407. evt.preventDefault();
  408. return false;
  409. };
  410. })(node);
  411. link.href = '#';
  412. }
  413. table.appendChild(link);
  414.  
  415. // For better layout, we will now replace that link with a neater li.
  416. liType = "li";
  417. if (node.tagName == "A") {
  418. liType = "div";
  419. }
  420. var li = newNode(liType);
  421. // clearStyle(li); // display:inline; is bad on LIs!
  422. // li.style.display = 'list-item'; // not working on Github
  423. link.parentNode.replaceChild(li,link);
  424. if (node.tagName == "A") {
  425. li.appendChild(document.createTextNode("\u2693 "));
  426. }
  427. li.appendChild(link);
  428. li.style.paddingLeft = (1.5*level)+"em";
  429. li.style.fontSize = (100-6*(level+1))+"%";
  430. li.style.size = li.style.fontSize;
  431.  
  432. // Debugging:
  433. /*
  434. li.title = node.tagName;
  435. if (node.name)
  436. li.title += " (#"+node.name+")";
  437. li.title = getXPath(node);
  438. */
  439.  
  440. }
  441.  
  442. document.body.appendChild(toc);
  443.  
  444. // TODO scrollIntoView if newly matching 1.hash exists
  445.  
  446. postTOC(toc);
  447.  
  448. } else {
  449. GM_log("[TOCE] Not enough items found to create toc.");
  450. }
  451.  
  452. return toc;
  453.  
  454. }
  455.  
  456. function postTOC(toc) {
  457. if (toc) {
  458.  
  459. // We make the TOC float regardless whether we created it or it already existed.
  460. // Interestingly, the overflow settings seems to apply to all sub-elements.
  461. // E.g.: http://mewiki.project357.com/wiki/X264_Settings#Input.2FOutput
  462. // FIXED: Some of the sub-trees are so long that they also get scrollbars, which is a bit messy!
  463. // FIXED : max-width does not do what I want! To see, find a TOC with really wide section titles (long lines).
  464.  
  465. // Also in Related_Links_Pager.user.js
  466. // See also: clearStyle
  467. var resetProps = " width: auto; height: auto; max-width: none; max-height: none; ";
  468.  
  469. if (toc.id === "") {
  470. toc.id = "toc";
  471. }
  472. var tocID = toc.id;
  473. GM_addStyle("#"+tocID+" { position: fixed; top: 10%; right: 4%; background-color: #f4f4f4; color: black; font-weight: normal; padding: 5px; border: 1px solid grey; z-index: 9999999; "+resetProps+" }" // max-height: 80%; max-width: 32%; overflow: auto;
  474. + "#"+tocID+" { opacity: 0.4; }"
  475. + "#"+tocID+":hover { box-shadow: 0px 2px 10px 1px rgba(0,0,0,0.4); }"
  476. + "#"+tocID+":hover { -webkit-box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.4); }"
  477. + "#"+tocID+":hover { opacity: 1.0; }"
  478. + "#"+tocID+" > * > * { opacity: 0.0; }"
  479. + "#"+tocID+":hover > * > * { opacity: 1.0; }"
  480. + "#"+tocID+" , #"+tocID+" > * > * { transition: opacity; transition-duration: 400ms; }"
  481. + "#"+tocID+" , #"+tocID+" > * > * { -webkit-transition: opacity; -webkit-transition-duration: 400ms; }"
  482. );
  483. GM_addStyle("#"+tocID+" > * { "+resetProps+" }");
  484.  
  485. var maxWidth = window.innerWidth * 0.40 | 0;
  486. var maxHeight = window.innerHeight * 0.80 | 0;
  487.  
  488. var table = document.getElementById("toctable");
  489. table = table || toc.getElementsByTagName("ul")[0]; // Wikipedia
  490. table = table || toc; // Give up, set for whole element
  491. table.style.overflow = 'auto';
  492. table.style.maxWidth = maxWidth+"px";
  493. table.style.maxHeight = maxHeight+"px";
  494.  
  495. }
  496. }
  497.  
  498. function searchForTOC() {
  499.  
  500. try {
  501.  
  502. var tocFound = document.getElementById("toc");
  503. // Konqueror 3.5 does NOT have document.getElementsByClassName(), so we check for it.
  504. tocFound = tocFound || (document.getElementsByClassName && document.getElementsByClassName("toc")[0]);
  505. tocFound = tocFound || document.getElementById("article-nav"); // developer.mozilla.org
  506. tocFound = tocFound || document.getElementById("page-toc"); // developer.mozilla.org
  507. tocFound = tocFound || (document.getElementsByClassName && document.getElementsByClassName("twikiToc")[0]); // TWiki
  508. tocFound = tocFound || document.getElementById("TOC"); // meteorpedia.com
  509. tocFound = tocFound || document.location.host==="developer.android.com" && document.getElementById("qv");
  510. if (document.location.host.indexOf("dartlang.org")>=0) {
  511. tocFound = null; // The toc they gives us contains top-level only. It's preferable to generate our own full tree.
  512. }
  513. // whatwg.org:
  514. /* if (document.getElementsByTagName("nav").length == 1) {
  515. GM_log("[TOCE] Using nav element.");
  516. tocFound = document.getElementsByTagName("nav")[0];
  517. } */
  518.  
  519. var toc = tocFound;
  520.  
  521. // With the obvious exception of Wikimedia sites, most found tocs do not contain a hide/close button.
  522. // TODO: If we are going to make the toc float, we should give it rollup/close buttons, unless it already has them.
  523. // The difficulty here is: where to add the buttons in the TOC, and which part of the TOC to hide, without hiding the buttons!
  524. // Presumably we need to identify the title element (first with textContent) and collect everything after that into a hideable block (or hide/unhide each individually when needed).
  525.  
  526. if (toc) {
  527.  
  528. postTOC(toc);
  529.  
  530. addButtonsConditionally(toc);
  531.  
  532. } else {
  533.  
  534. toc = buildTableOfContents();
  535.  
  536. }
  537.  
  538. } catch (e) {
  539. GM_log("[TOCE] Error! "+e);
  540. }
  541.  
  542. }
  543.  
  544. if (document.evaluate /*this.XPathResult*/) {
  545. searchForTOC();
  546. } else {
  547. loadScript("http://hwi.ath.cx/javascript/xpath.js", searchForTOC);
  548. }
  549.  
  550.  
  551.  
  552. },delayBeforeRunning);
  553. // We want it to run fairly soon but it can be quite heavy on large pages - big XPath search.
  554.