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.)

目前为 2018-04-25 提交的版本,查看 最新版本

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