Toc Bar, 文章大纲

在页面右侧展示一个浮动的文章大纲目录

当前为 2020-07-07 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Toc Bar
  3. // @name:zh-CN Toc Bar, 文章大纲
  4. // @author hikerpig
  5. // @namespace https://github.com/hikerpig
  6. // @license MIT
  7. // @description A floating table of content widget
  8. // @description:zh-CN 在页面右侧展示一个浮动的文章大纲目录
  9. // @version 1.3.0
  10. // @match *://www.jianshu.com/p/*
  11. // @match *://cdn2.jianshu.io/p/*
  12. // @match *://zhuanlan.zhihu.com/p/*
  13. // @match *://mp.weixin.qq.com/s*
  14. // @match *://cnodejs.org/topic/*
  15. // @match *://*zcfy.cc/article/*
  16. // @match *://juejin.im/entry/*
  17. // @match *://dev.to/*/*
  18. // @exclude *://dev.to/settings/*
  19. // @match *://web.dev/*
  20. // @match *://medium.com/*
  21. // @match *://css-tricks.com/*
  22. // @match *://www.smashingmagazine.com/*/*
  23. // @match *://distill.pub/*
  24. // @match *://github.com/*/*
  25. // @match *://developer.mozilla.org/*/docs/*
  26. // @match *://learning.oreilly.com/library/view/*
  27. // @run-at document-idle
  28. // @grant GM_getResourceText
  29. // @grant GM_addStyle
  30. // @grant GM_setValue
  31. // @grant GM_getValue
  32. // @require https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.min.js
  33. // @icon https://raw.githubusercontent.com/hikerpig/toc-bar-userscript/master/toc-logo.svg
  34. // @homepageURL https://github.com/hikerpig/toc-bar-userscript
  35. // ==/UserScript==
  36.  
  37. (function () {
  38. const SITE_SETTINGS = {
  39. jianshu: {
  40. contentSelector: '.ouvJEz',
  41. style: {
  42. top: '55px',
  43. color: '#ea6f5a',
  44. },
  45. },
  46. 'zhuanlan.zhihu.com': {
  47. contentSelector: 'article',
  48. scrollSmoothOffset: -52,
  49. shouldShow() {
  50. return location.pathname.startsWith('/p/')
  51. },
  52. },
  53. zcfy: {
  54. contentSelector: '.markdown-body',
  55. },
  56. qq: {
  57. contentSelector: '.rich_media_content',
  58. },
  59. 'juejin.im': {
  60. contentSelector: '.entry-public-main',
  61. },
  62. 'dev.to': {
  63. contentSelector: 'article',
  64. scrollSmoothOffset: -56,
  65. shouldShow() {
  66. return ['/search', '/top/'].every(s => !location.pathname.startsWith(s))
  67. },
  68. },
  69. 'medium.com': {
  70. contentSelector: 'article'
  71. },
  72. 'css-tricks.com': {
  73. contentSelector: 'main'
  74. },
  75. 'distill.pub': {
  76. contentSelector: 'body'
  77. },
  78. 'smashingmagazine': {
  79. contentSelector: 'article'
  80. },
  81. 'web.dev': {
  82. contentSelector: '#content'
  83. },
  84. 'github.com': {
  85. contentSelector() {
  86. const README_SEL = '#readme'
  87. const WIKI_CONTENT_SEL = '.repository-content'
  88. const matchedSel = [README_SEL, WIKI_CONTENT_SEL].find((sel) => {
  89. return !!document.querySelector(README_SEL)
  90. })
  91.  
  92. if (matchedSel) return matchedSel
  93.  
  94. return false
  95. },
  96. initialTop: 500,
  97. },
  98. 'developer.mozilla.org': {
  99. contentSelector: '#content'
  100. },
  101. 'learning.oreilly.com': {
  102. contentSelector: '#sbo-rt-content'
  103. },
  104. }
  105.  
  106. function getSiteInfo() {
  107. let siteName
  108. if (SITE_SETTINGS[location.hostname]) {
  109. siteName = location.hostname
  110. } else {
  111. const match = location.href.match(
  112. /([\d\w]+)\.(com|cn|net|org|im|io|cc|site|tv)/i
  113. )
  114. siteName = match ? match[1] : null
  115. }
  116. if (siteName && SITE_SETTINGS[siteName]) {
  117. return {
  118. siteName,
  119. siteSetting: SITE_SETTINGS[siteName],
  120. }
  121. }
  122. }
  123.  
  124. function getPageTocOptions() {
  125. let siteInfo = getSiteInfo()
  126. if (siteInfo) {
  127. let siteSetting = siteInfo.siteSetting
  128. if (siteSetting.shouldShow && !siteSetting.shouldShow()) {
  129. return
  130. }
  131. if (typeof siteSetting.contentSelector === 'function') {
  132. const contentSelector = siteSetting.contentSelector()
  133. if (!contentSelector) return
  134. siteSetting = {...siteSetting, contentSelector}
  135. }
  136. console.log('[toc-bar] found site info for', siteInfo.siteName)
  137. return siteSetting
  138. }
  139. }
  140.  
  141. function guessThemeColor() {
  142. const meta = document.head.querySelector('meta[name="theme-color"]')
  143. if (meta) {
  144. return meta.getAttribute('content')
  145. }
  146. }
  147.  
  148. /**
  149. * @param {String} content
  150. * @return {String}
  151. */
  152. function doContentHash(content) {
  153. const val = content.split('').reduce((prevHash, currVal) => (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
  154. return val.toString(32)
  155. }
  156.  
  157. const POSITION_STORAGE = {
  158. cache: null,
  159. checkCache() {
  160. if (!POSITION_STORAGE.cache) {
  161. POSITION_STORAGE.cache = GM_getValue('tocbar-positions', {})
  162. }
  163. },
  164. get(k) {
  165. k = k || location.host
  166. POSITION_STORAGE.checkCache()
  167. return POSITION_STORAGE.cache[k]
  168. },
  169. set(k, position) {
  170. k = k || location.host
  171. POSITION_STORAGE.checkCache()
  172. POSITION_STORAGE.cache[k] = position
  173. GM_setValue('tocbar-positions', POSITION_STORAGE.cache)
  174. },
  175. }
  176.  
  177. function isEmpty(input) {
  178. if (input) {
  179. return Object.keys(input).length > 0
  180. }
  181. return true
  182. }
  183.  
  184. // ---------------- TocBar ----------------------
  185. const TOC_BAR_STYLE = `
  186. .toc-bar {
  187. --toc-bar-active-color: #54BC4B;
  188.  
  189. position: fixed;
  190. z-index: 9000;
  191. right: 5px;
  192. top: 80px;
  193. width: 340px;
  194. font-size: 14px;
  195. box-sizing: border-box;
  196. padding: 0 10px 10px 0;
  197. box-shadow: 0 1px 3px #DDD;
  198. border-radius: 4px;
  199. transition: width 0.2s ease;
  200. color: #333;
  201. background: #FEFEFE;
  202. }
  203.  
  204. .toc-bar.toc-bar--collapsed {
  205. width: 30px;
  206. height: 30px;
  207. padding: 0;
  208. overflow: hidden;
  209. }
  210.  
  211. .toc-bar--collapsed .toc {
  212. display: none;
  213. }
  214.  
  215. .toc-bar--collapsed .hidden-when-collapsed {
  216. display: none;
  217. }
  218.  
  219. .toc-bar__header {
  220. font-weight: bold;
  221. padding-bottom: 5px;
  222. display: flex;
  223. justify-content: space-between;
  224. align-items: center;
  225. cursor: move;
  226. }
  227.  
  228. .toc-bar__refresh {
  229. position: relative;
  230. top: -2px;
  231. }
  232.  
  233. .toc-bar__icon-btn {
  234. height: 1em;
  235. width: 1em;
  236. cursor: pointer;
  237. transition: transform 0.2s ease;
  238. }
  239.  
  240. .toc-bar__icon-btn:hover {
  241. opacity: 0.7;
  242. }
  243.  
  244. .toc-bar__icon-btn svg {
  245. max-width: 100%;
  246. max-height: 100%;
  247. vertical-align: top;
  248. }
  249.  
  250. .toc-bar__header-left {
  251. align-items: center;
  252. }
  253.  
  254. .toc-bar__toggle {
  255. cursor: pointer;
  256. padding: 8px 8px;
  257. box-sizing: content-box;
  258. transition: transform 0.2s ease;
  259. }
  260.  
  261. .toc-bar__title {
  262. margin-left: 5px;
  263. }
  264.  
  265. .toc-bar a.toc-link {
  266. overflow: hidden;
  267. text-overflow: ellipsis;
  268. white-space: nowrap;
  269. display: block;
  270. line-height: 1.6;
  271. }
  272.  
  273. .flex {
  274. display: flex;
  275. }
  276.  
  277. /* tocbot related */
  278. .toc-bar__toc {
  279. max-height: 80vh;
  280. overflow-y: scroll;
  281. }
  282.  
  283. .toc-list-item > a:hover {
  284. text-decoration: underline;
  285. }
  286.  
  287. .toc-list {
  288. padding-inline-start: 0;
  289. }
  290.  
  291. .toc-bar__toc > .toc-list {
  292. margin: 0;
  293. overflow: hidden;
  294. position: relative;
  295. padding-left: 5px;
  296. }
  297.  
  298. .toc-bar__toc>.toc-list li {
  299. list-style: none;
  300. padding-left: 8px;
  301. position: static;
  302. }
  303.  
  304. a.toc-link {
  305. color: currentColor;
  306. height: 100%;
  307. }
  308.  
  309. .is-collapsible {
  310. max-height: 1000px;
  311. overflow: hidden;
  312. transition: all 300ms ease-in-out;
  313. }
  314.  
  315. .is-collapsed {
  316. max-height: 0;
  317. }
  318.  
  319. .is-position-fixed {
  320. position: fixed !important;
  321. top: 0;
  322. }
  323.  
  324. .is-active-link {
  325. font-weight: 700;
  326. }
  327.  
  328. .toc-link::before {
  329. background-color: #EEE;
  330. content: ' ';
  331. display: inline-block;
  332. height: inherit;
  333. left: 0;
  334. margin-top: -1px;
  335. position: absolute;
  336. width: 2px;
  337. }
  338.  
  339. .is-active-link::before {
  340. background-color: var(--toc-bar-active-color);
  341. }
  342. /* end tocbot related */
  343. `
  344.  
  345. const TOCBOT_CONTAINTER_CLASS = 'toc-bar__toc'
  346.  
  347. /**
  348. * @class
  349. */
  350. function TocBar(options={}) {
  351. this.options = options
  352.  
  353. // inject style
  354. GM_addStyle(TOC_BAR_STYLE)
  355.  
  356. this.element = document.createElement('div')
  357. this.element.id = 'toc-bar'
  358. this.element.classList.add('toc-bar')
  359. document.body.appendChild(this.element)
  360.  
  361. /** @type {Boolean} */
  362. this.visible = true
  363.  
  364. this.initHeader()
  365.  
  366. // create a container tocbot
  367. const tocElement = document.createElement('div')
  368. this.tocElement = tocElement
  369. tocElement.classList.add(TOCBOT_CONTAINTER_CLASS)
  370. this.element.appendChild(tocElement)
  371.  
  372. const cachedPosition = POSITION_STORAGE.get(options.siteName)
  373. if (!isEmpty(cachedPosition)) {
  374. this.element.style.top = `${cachedPosition.top}px`
  375. this.element.style.right = `${cachedPosition.right}px`
  376. } else if (options.hasOwnProperty('initialTop')) {
  377. this.element.style.top = `${options.initialTop}px`
  378. }
  379.  
  380. if (GM_getValue('tocbar-hidden', false)) {
  381. this.toggle(false)
  382. }
  383. }
  384.  
  385. const REFRESH_ICON = `<svg t="1593614403764" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5002" width="200" height="200"><path d="M918 702.8 918 702.8c45.6-98.8 52-206 26-303.6-30-112.4-104-212.8-211.6-273.6L780 23.2l-270.8 70.8 121.2 252.4 50-107.6c72.8 44.4 122.8 114.4 144 192.8 18.8 70.8 14.4 147.6-18.8 219.6-42 91.2-120.8 153.6-210.8 177.6-13.2 3.6-26.4 6-39.6 8l56 115.6c5.2-1.2 10.4-2.4 16-4C750.8 915.2 860 828.8 918 702.8L918 702.8M343.2 793.2c-74-44.4-124.8-114.8-146-194-18.8-70.8-14.4-147.6 18.8-219.6 42-91.2 120.8-153.6 210.8-177.6 14.8-4 30-6.8 45.6-8.8l-55.6-116c-7.2 1.6-14.8 3.2-22 5.2-124 33.2-233.6 119.6-291.2 245.6-45.6 98.8-52 206-26 303.2l0 0.4c30.4 113.2 105.2 214 213.6 274.8l-45.2 98 270.4-72-122-252L343.2 793.2 343.2 793.2M343.2 793.2 343.2 793.2z" p-id="5003"></path></svg>`
  386.  
  387. const TOC_ICON = `
  388. <?xml version="1.0" encoding="utf-8"?>
  389. <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  390. viewBox="0 0 1024 1024" style="enable-background:new 0 0 1024 1024;" xml:space="preserve">
  391. <g>
  392. <g>
  393. <path d="M835.2,45.9H105.2v166.8l93.2,61.5h115.8H356h30.6v-82.8H134.2v-24.9h286.2v107.6h32.2V141.6H134.2V118h672.1v23.6H486.4
  394. v132.5h32V166.5h287.8v24.9H553.8v82.8h114.1H693h225.6V114.5L835.2,45.9z M806.2,93.2H134.2V67.2h672.1v26.1H806.2z"/>
  395. <polygon points="449.3,1008.2 668,1008.2 668,268.9 553.8,268.9 553.8,925.4 518.4,925.4 518.4,268.9 486.4,268.9 486.4,925.4
  396. 452.6,925.4 452.6,268.9 420.4,268.9 420.4,925.4 386.6,925.4 386.6,268.9 356,268.9 356,946.7 "/>
  397. </g>
  398. </g>
  399. </svg>
  400. `
  401.  
  402. TocBar.prototype = {
  403. /**
  404. * @method TocBar
  405. */
  406. initHeader() {
  407. const header = document.createElement('div')
  408. header.classList.add('toc-bar__header')
  409. header.innerHTML = `
  410. <div class="flex toc-bar__header-left">
  411. <div class="toc-bar__toggle toc-bar__icon-btn" title="Toggle TOC Bar">
  412. ${TOC_ICON}
  413. </div>
  414. <div class="toc-bar__title hidden-when-collapsed">TOC Bar</div>
  415. </div>
  416. <div class="toc-bar__actions hidden-when-collapsed">
  417. <div class="toc-bar__refresh toc-bar__icon-btn" title="Refresh TOC">
  418. ${REFRESH_ICON}
  419. </div>
  420. </div>
  421. `
  422. const toggleElement = header.querySelector('.toc-bar__toggle')
  423. toggleElement.addEventListener('click', () => {
  424. this.toggle()
  425. GM_setValue('tocbar-hidden', !this.visible)
  426. })
  427. this.logoSvg = toggleElement.querySelector('svg')
  428.  
  429. const refreshElement = header.querySelector('.toc-bar__refresh')
  430. refreshElement.addEventListener('click', () => {
  431. tocbot.refresh()
  432. })
  433. // ---------------- header drag ----------------------
  434. const dragState = {
  435. startMouseX: 0,
  436. startMouseY: 0,
  437. startPositionX: 0,
  438. startPositionY: 0,
  439. startElementDisToRight: 0,
  440. isDragging: false,
  441. curRight: 0,
  442. curTop: 0,
  443. }
  444.  
  445. const onMouseMove = (e) => {
  446. if (!dragState.isDragging) return
  447. const deltaX = e.pageX - dragState.startMouseX
  448. const deltaY = e.pageY - dragState.startMouseY
  449. // 要换算为 right 数字
  450. const newRight = dragState.startElementDisToRight - deltaX
  451. const newTop = dragState.startPositionY + deltaY
  452. Object.assign(dragState, {
  453. curTop: newTop,
  454. curRight: newRight,
  455. })
  456. // console.table({ newRight, newTop})
  457. this.element.style.right = `${newRight}px`
  458. this.element.style.top = `${newTop}px`
  459. }
  460.  
  461. const onMouseUp = (e) => {
  462. Object.assign(dragState, {
  463. isDragging: false,
  464. })
  465. document.body.removeEventListener('mousemove', onMouseMove)
  466. document.body.removeEventListener('mouseup', onMouseUp)
  467.  
  468. POSITION_STORAGE.set(this.options.siteName, {
  469. top: dragState.curTop,
  470. right: dragState.curRight,
  471. })
  472. }
  473.  
  474. header.addEventListener('mousedown', (e) => {
  475. if (e.target === toggleElement) return
  476. const bbox = this.element.getBoundingClientRect()
  477. Object.assign(dragState, {
  478. isDragging: true,
  479. startMouseX: e.pageX,
  480. startMouseY: e.pageY,
  481. startPositionX: bbox.x,
  482. startPositionY: bbox.y,
  483. startElementDisToRight: document.body.clientWidth - bbox.right,
  484. })
  485. document.body.addEventListener('mousemove', onMouseMove)
  486. document.body.addEventListener('mouseup', onMouseUp)
  487. })
  488. // ----------------end header drag -------------------
  489.  
  490. this.element.appendChild(header)
  491. },
  492. /**
  493. * @method TocBar
  494. */
  495. initTocbot(options) {
  496. const me = this
  497. const tocbotOptions = Object.assign(
  498. {},
  499. {
  500. tocSelector: `.${TOCBOT_CONTAINTER_CLASS}`,
  501. scrollSmoothOffset: options.scrollSmoothOffset || 0,
  502. // hasInnerContainers: true,
  503. headingObjectCallback(obj, ele) {
  504. // if there is no id on the header element, add one that derived from hash of header title
  505. if (!ele.id) {
  506. const newId = me.generateHeaderId(obj, ele)
  507. ele.setAttribute('id', newId)
  508. obj.id = newId
  509. }
  510. return obj
  511. },
  512. headingSelector: 'h1, h2, h3, h4, h5',
  513. collapseDepth: 4,
  514. },
  515. options
  516. )
  517. // console.log('tocbotOptions', tocbotOptions);
  518. tocbot.init(tocbotOptions)
  519. },
  520. generateHeaderId(obj, ele) {
  521. return `tocbar-${doContentHash(obj.textContent)}`
  522. },
  523. /**
  524. * @method TocBar
  525. */
  526. toggle(shouldShow = !this.visible) {
  527. const HIDDEN_CLASS = 'toc-bar--collapsed'
  528. const LOGO_HIDDEN_CLASS = 'toc-logo--collapsed'
  529. if (shouldShow) {
  530. this.element.classList.remove(HIDDEN_CLASS)
  531. this.logoSvg && this.logoSvg.classList.remove(LOGO_HIDDEN_CLASS)
  532. } else {
  533. this.element.classList.add(HIDDEN_CLASS)
  534. this.logoSvg && this.logoSvg.classList.add(LOGO_HIDDEN_CLASS)
  535. }
  536. this.visible = shouldShow
  537. },
  538. refreshStyle() {
  539. const themeColor = guessThemeColor()
  540. if (themeColor) {
  541. this.element.style.setProperty('--toc-bar-active-color', themeColor);
  542. }
  543. },
  544. }
  545. // ----------------end TocBar -------------------
  546.  
  547. function main() {
  548. const options = getPageTocOptions()
  549. if (options) {
  550.  
  551. const tocBar = new TocBar(options)
  552. tocBar.initTocbot(options)
  553. tocBar.refreshStyle()
  554. }
  555. }
  556.  
  557. main()
  558. })()

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址