Toc Bar, 自动生成文章大纲。知乎、微信公众号等阅读好伴侣

自动生成文章大纲目录,在页面右侧展示一个浮动的组件。覆盖常用在线阅读资讯站(技术向)。github/medium/MDN/掘金/简书等

当前为 2021-11-02 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Toc Bar, auto-generating table of content
  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 自动生成文章大纲目录,在页面右侧展示一个浮动的组件。覆盖常用在线阅读资讯站(技术向)。github/medium/MDN/掘金/简书等
  9. // @version 1.8.1
  10. // @match *://www.jianshu.com/p/*
  11. // @match *://cdn2.jianshu.io/p/*
  12. // @match *://zhuanlan.zhihu.com/p/*
  13. // @match *://www.zhihu.com/pub/reader/*
  14. // @match *://mp.weixin.qq.com/s*
  15. // @match *://cnodejs.org/topic/*
  16. // @match *://*zcfy.cc/article/*
  17. // @match *://juejin.cn/post/*
  18. // @match *://dev.to/*/*
  19. // @exclude *://dev.to/settings/*
  20. // @match *://web.dev/*
  21. // @match *://medium.com/*
  22. // @exclude *://medium.com/media/*
  23. // @match *://itnext.io/*
  24. // @match *://www.infoq.cn/article/*
  25. // @match *://towardsdatascience.com/*
  26. // @match *://hackernoon.com/*
  27. // @match *://css-tricks.com/*
  28. // @match *://www.smashingmagazine.com/*/*
  29. // @match *://distill.pub/*
  30. // @match *://github.com/*/*
  31. // @match *://github.com/*/issues/*
  32. // @match *://developer.mozilla.org/*/docs/*
  33. // @match *://learning.oreilly.com/library/view/*
  34. // @match *://developer.chrome.com/extensions/*
  35. // @match *://app.getpocket.com/read/*
  36. // @match *://indepth.dev/posts/*
  37. // @run-at document-idle
  38. // @grant GM_getResourceText
  39. // @grant GM_addStyle
  40. // @grant GM_setValue
  41. // @grant GM_getValue
  42. // @require https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.min.js
  43. // @icon https://raw.githubusercontent.com/hikerpig/toc-bar-userscript/master/toc-logo.svg
  44. // @homepageURL https://github.com/hikerpig/toc-bar-userscript
  45. // ==/UserScript==
  46.  
  47. (function () {
  48. const SITE_SETTINGS = {
  49. jianshu: {
  50. contentSelector: '.ouvJEz',
  51. style: {
  52. top: '55px',
  53. color: '#ea6f5a',
  54. },
  55. },
  56. 'zhuanlan.zhihu.com': {
  57. contentSelector: 'article',
  58. scrollSmoothOffset: -52,
  59. shouldShow() {
  60. return location.pathname.startsWith('/p/')
  61. },
  62. },
  63. 'www.zhihu.com': {
  64. contentSelector: '.reader-chapter-content',
  65. scrollSmoothOffset: -52,
  66. },
  67. zcfy: {
  68. contentSelector: '.markdown-body',
  69. },
  70. qq: {
  71. contentSelector: '.rich_media_content',
  72. },
  73. 'juejin.im': {
  74. contentSelector: '.entry-public-main',
  75. },
  76. 'dev.to': {
  77. contentSelector: 'article',
  78. scrollSmoothOffset: -56,
  79. shouldShow() {
  80. return ['/search', '/top/'].every(s => !location.pathname.startsWith(s))
  81. },
  82. },
  83. 'medium.com': {
  84. contentSelector: 'article'
  85. },
  86. 'hackernoon.com': {
  87. contentSelector: 'main',
  88. scrollSmoothOffset: -80,
  89. },
  90. 'towardsdatascience.com': {
  91. contentSelector: 'article'
  92. },
  93. 'css-tricks.com': {
  94. contentSelector: 'main'
  95. },
  96. 'distill.pub': {
  97. contentSelector: 'body'
  98. },
  99. 'smashingmagazine': {
  100. contentSelector: 'article'
  101. },
  102. 'web.dev': {
  103. contentSelector: '#content'
  104. },
  105. 'github.com': function () {
  106. const README_SEL = '#readme'
  107. const WIKI_CONTENT_SEL = '#wiki-body'
  108. const ISSUE_CONTENT_SEL = '.comment .comment-body'
  109.  
  110. let matchedContainer
  111. const matchedSel = [README_SEL, ISSUE_CONTENT_SEL, WIKI_CONTENT_SEL].find((sel) => {
  112. const c = document.querySelector(sel)
  113. if (c) {
  114. matchedContainer = c
  115. return true
  116. }
  117. })
  118.  
  119. if (!matchedSel) {
  120. return {
  121. contentSelect: false,
  122. }
  123. }
  124.  
  125. const isIssueDetail = /\/issues\//.test(location.pathname)
  126. const ISSUE_DETAIL_HEADING_OFFSET = 60
  127.  
  128. /** Ugly hack for github issues */
  129. const onClick = isIssueDetail ? function (e) {
  130. const href = e.target.getAttribute('href')
  131. const header = document.body.querySelector(href)
  132. if (header) {
  133. const rect = header.getBoundingClientRect()
  134. const currentWindowScrollTop = document.documentElement.scrollTop
  135. const scrollY = rect.y + currentWindowScrollTop - ISSUE_DETAIL_HEADING_OFFSET
  136.  
  137. window.scrollTo(0, scrollY)
  138.  
  139. location.hash = href
  140.  
  141. e.preventDefault()
  142. e.stopPropagation()
  143. }
  144. }: null
  145.  
  146. return {
  147. contentSelector: matchedSel,
  148. hasInnerContainers: isIssueDetail ? true: false,
  149. scrollSmoothOffset: isIssueDetail ? -ISSUE_DETAIL_HEADING_OFFSET: 0,
  150. headingsOffset: isIssueDetail ? ISSUE_DETAIL_HEADING_OFFSET: 0,
  151. initialTop: 500,
  152. onClick,
  153. }
  154. },
  155. 'developer.mozilla.org': {
  156. contentSelector: '#content'
  157. },
  158. 'learning.oreilly.com': {
  159. contentSelector: '#sbo-rt-content'
  160. },
  161. 'developer.chrome.com': {
  162. contentSelector: 'article'
  163. },
  164. 'www.infoq.cn': {
  165. contentSelector: '.article-main',
  166. scrollSmoothOffset: -107
  167. },
  168. 'app.getpocket.com': {
  169. contentSelector: '[role=main]',
  170. },
  171. 'indepth.dev': {
  172. contentSelector: '.content',
  173. },
  174. }
  175.  
  176. function getSiteInfo() {
  177. let siteName
  178. if (SITE_SETTINGS[location.hostname]) {
  179. siteName = location.hostname
  180. } else {
  181. const match = location.href.match(
  182. /([\d\w]+)\.(com|cn|net|org|im|io|cc|site|tv)/i
  183. )
  184. siteName = match ? match[1] : null
  185. }
  186. if (siteName && SITE_SETTINGS[siteName]) {
  187. return {
  188. siteName,
  189. siteSetting: SITE_SETTINGS[siteName],
  190. }
  191. }
  192. }
  193.  
  194. function getPageTocOptions() {
  195. let siteInfo = getSiteInfo()
  196. if (siteInfo) {
  197. if (typeof siteInfo.siteSetting === 'function') {
  198. return siteInfo.siteSetting()
  199. }
  200.  
  201. let siteSetting = { ...siteInfo.siteSetting }
  202. if (siteSetting.shouldShow && !siteSetting.shouldShow()) {
  203. return
  204. }
  205. if (typeof siteSetting.contentSelector === 'function') {
  206. const contentSelector = siteSetting.contentSelector()
  207. if (!contentSelector) return
  208. siteSetting = {...siteSetting, contentSelector}
  209. }
  210. if (typeof siteSetting.scrollSmoothOffset === 'function') {
  211. siteSetting.scrollSmoothOffset = siteSetting.scrollSmoothOffset()
  212. }
  213.  
  214. console.log('[toc-bar] found site info for', siteInfo.siteName)
  215. return siteSetting
  216. }
  217. }
  218.  
  219. function guessThemeColor() {
  220. const meta = document.head.querySelector('meta[name="theme-color"]')
  221. if (meta) {
  222. return meta.getAttribute('content')
  223. }
  224. }
  225.  
  226. /**
  227. * @param {String} content
  228. * @return {String}
  229. */
  230. function doContentHash(content) {
  231. const val = content.split('').reduce((prevHash, currVal) => (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
  232. return val.toString(32)
  233. }
  234.  
  235. const POSITION_STORAGE = {
  236. cache: null,
  237. checkCache() {
  238. if (!POSITION_STORAGE.cache) {
  239. POSITION_STORAGE.cache = GM_getValue('tocbar-positions', {})
  240. }
  241. },
  242. get(k) {
  243. k = k || location.host
  244. POSITION_STORAGE.checkCache()
  245. return POSITION_STORAGE.cache[k]
  246. },
  247. set(k, position) {
  248. k = k || location.host
  249. POSITION_STORAGE.checkCache()
  250. POSITION_STORAGE.cache[k] = position
  251. GM_setValue('tocbar-positions', POSITION_STORAGE.cache)
  252. },
  253. }
  254.  
  255. function isEmpty(input) {
  256. if (input) {
  257. return Object.keys(input).length === 0
  258. }
  259. return true
  260. }
  261.  
  262. /** 宽度,也用于计算拖动时的最小 right */
  263. const TOC_BAR_WIDTH = 340
  264.  
  265. const TOC_BAR_DEFAULT_ACTIVE_COLOR = '#54BC4B';
  266.  
  267. // ---------------- TocBar ----------------------
  268. const TOC_BAR_STYLE = `
  269. .toc-bar {
  270. --toc-bar-active-color: ${TOC_BAR_DEFAULT_ACTIVE_COLOR};
  271. --toc-bar-text-color: #333;
  272. --toc-bar-background-color: #FEFEFE;
  273.  
  274. position: fixed;
  275. z-index: 9000;
  276. right: 5px;
  277. top: 80px;
  278. width: ${TOC_BAR_WIDTH}px;
  279. font-size: 14px;
  280. box-sizing: border-box;
  281. padding: 0 10px 10px 0;
  282. box-shadow: 0 1px 3px #DDD;
  283. border-radius: 4px;
  284. transition: width 0.2s ease;
  285. color: var(--toc-bar-text-color);
  286. background: var(--toc-bar-background-color);
  287.  
  288. user-select:none;
  289. -moz-user-select:none;
  290. -webkit-user-select: none;
  291. -ms-user-select: none;
  292. }
  293.  
  294. .toc-bar[colorscheme="dark"] {
  295. --toc-bar-text-color: #fafafa;
  296. --toc-bar-background-color: #333;
  297. }
  298. .toc-bar[colorscheme="dark"] svg {
  299. fill: var(--toc-bar-text-color);
  300. stroke: var(--toc-bar-text-color);
  301. }
  302.  
  303. .toc-bar.toc-bar--collapsed {
  304. width: 30px;
  305. height: 30px;
  306. padding: 0;
  307. overflow: hidden;
  308. }
  309.  
  310. .toc-bar--collapsed .toc {
  311. display: none;
  312. }
  313.  
  314. .toc-bar--collapsed .hidden-when-collapsed {
  315. display: none;
  316. }
  317.  
  318. .toc-bar__header {
  319. font-weight: bold;
  320. padding-bottom: 5px;
  321. display: flex;
  322. justify-content: space-between;
  323. align-items: center;
  324. cursor: move;
  325. }
  326.  
  327. .toc-bar__refresh {
  328. position: relative;
  329. top: -2px;
  330. }
  331.  
  332. .toc-bar__icon-btn {
  333. height: 1em;
  334. width: 1em;
  335. cursor: pointer;
  336. transition: transform 0.2s ease;
  337. }
  338.  
  339. .toc-bar__icon-btn:hover {
  340. opacity: 0.7;
  341. }
  342.  
  343. .toc-bar__icon-btn svg {
  344. max-width: 100%;
  345. max-height: 100%;
  346. vertical-align: top;
  347. }
  348.  
  349. .toc-bar__actions {
  350. align-items: center;
  351. }
  352. .toc-bar__actions .toc-bar__icon-btn {
  353. margin-left: 1em;
  354. }
  355.  
  356. .toc-bar__scheme {
  357. transform: translateY(-1px) scale(1.1);
  358. }
  359.  
  360. .toc-bar__header-left {
  361. align-items: center;
  362. }
  363.  
  364. .toc-bar__toggle {
  365. cursor: pointer;
  366. padding: 8px 8px;
  367. box-sizing: content-box;
  368. transition: transform 0.2s ease;
  369. }
  370.  
  371. .toc-bar__title {
  372. margin-left: 5px;
  373. }
  374.  
  375. .toc-bar a.toc-link {
  376. overflow: hidden;
  377. text-overflow: ellipsis;
  378. white-space: nowrap;
  379. display: block;
  380. line-height: 1.6;
  381. }
  382.  
  383. .flex {
  384. display: flex;
  385. }
  386.  
  387. /* tocbot related */
  388. .toc-bar__toc {
  389. max-height: 80vh;
  390. overflow-y: auto;
  391. }
  392.  
  393. .toc-list-item > a:hover {
  394. text-decoration: underline;
  395. }
  396.  
  397. .toc-list {
  398. padding-inline-start: 0;
  399. }
  400.  
  401. .toc-bar__toc > .toc-list {
  402. margin: 0;
  403. overflow: hidden;
  404. position: relative;
  405. padding-left: 5px;
  406. }
  407.  
  408. .toc-bar__toc>.toc-list li {
  409. list-style: none;
  410. padding-left: 8px;
  411. position: static;
  412. }
  413.  
  414. a.toc-link {
  415. color: currentColor;
  416. height: 100%;
  417. }
  418.  
  419. .is-collapsible {
  420. max-height: 1000px;
  421. overflow: hidden;
  422. transition: all 300ms ease-in-out;
  423. }
  424.  
  425. .is-collapsed {
  426. max-height: 0;
  427. }
  428.  
  429. .is-position-fixed {
  430. position: fixed !important;
  431. top: 0;
  432. }
  433.  
  434. .is-active-link {
  435. font-weight: 700;
  436. }
  437.  
  438. .toc-link::before {
  439. background-color: var(--toc-bar-background-color);
  440. content: ' ';
  441. display: inline-block;
  442. height: inherit;
  443. left: 0;
  444. margin-top: -1px;
  445. position: absolute;
  446. width: 2px;
  447. }
  448.  
  449. .is-active-link::before {
  450. background-color: var(--toc-bar-active-color);
  451. }
  452.  
  453. @media print {
  454. .toc-bar__no-print { display: none !important; }
  455. }
  456. /* end tocbot related */
  457. `
  458.  
  459. const TOCBOT_CONTAINTER_CLASS = 'toc-bar__toc'
  460.  
  461. const DARKMODE_KEY = 'tocbar-darkmode'
  462.  
  463. /**
  464. * @class
  465. */
  466. function TocBar(options={}) {
  467. this.options = options
  468.  
  469. // inject style
  470. GM_addStyle(TOC_BAR_STYLE)
  471.  
  472. this.element = document.createElement('div')
  473. this.element.id = 'toc-bar'
  474. this.element.classList.add('toc-bar', 'toc-bar__no-print')
  475. document.body.appendChild(this.element)
  476.  
  477. /** @type {Boolean} */
  478. this.visible = true
  479.  
  480. this.initHeader()
  481.  
  482. // create a container tocbot
  483. const tocElement = document.createElement('div')
  484. this.tocElement = tocElement
  485. tocElement.classList.add(TOCBOT_CONTAINTER_CLASS)
  486. this.element.appendChild(tocElement)
  487.  
  488. const cachedPosition = POSITION_STORAGE.get(options.siteName)
  489. if (!isEmpty(cachedPosition)) {
  490. this.element.style.top = `${Math.max(0, cachedPosition.top)}px`
  491. this.element.style.right = `${cachedPosition.right}px`
  492. } else if (options.hasOwnProperty('initialTop')) {
  493. this.element.style.top = `${options.initialTop}px`
  494. }
  495.  
  496. if (GM_getValue('tocbar-hidden', false)) {
  497. this.toggle(false)
  498. }
  499.  
  500. const isDark = Boolean(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
  501. /** @type {Boolean} */
  502. this.isDarkMode = isDark
  503.  
  504. if (GM_getValue(DARKMODE_KEY, false)) {
  505. this.toggleScheme(true)
  506. }
  507. }
  508.  
  509. 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>`
  510.  
  511. const TOC_ICON = `
  512. <?xml version="1.0" encoding="utf-8"?>
  513. <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  514. viewBox="0 0 1024 1024" style="enable-background:new 0 0 1024 1024;" xml:space="preserve">
  515. <g>
  516. <g>
  517. <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
  518. v132.5h32V166.5h287.8v24.9H553.8v82.8h114.1H693h225.6V114.5L835.2,45.9z M806.2,93.2H134.2V67.2h672.1v26.1H806.2z"/>
  519. <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
  520. 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 "/>
  521. </g>
  522. </g>
  523. </svg>
  524. `
  525.  
  526. const LIGHT_ICON = `
  527. <?xml version="1.0" encoding="iso-8859-1"?>
  528. <!-- Generator: Adobe Illustrator 18.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
  529. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  530. <svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  531. viewBox="0 0 181.328 181.328" style="enable-background:new 0 0 181.328 181.328;" xml:space="preserve" style="transform: translateY(-1px);">
  532. <g>
  533. <path d="M118.473,46.308V14.833c0-4.142-3.358-7.5-7.5-7.5H70.357c-4.142,0-7.5,3.358-7.5,7.5v31.474
  534. C51.621,54.767,44.34,68.214,44.34,83.331c0,25.543,20.781,46.324,46.324,46.324s46.324-20.781,46.324-46.324
  535. C136.988,68.215,129.708,54.769,118.473,46.308z M77.857,22.333h25.615v16.489c-4.071-1.174-8.365-1.815-12.809-1.815
  536. c-4.443,0-8.736,0.642-12.807,1.814V22.333z M90.664,114.655c-17.273,0-31.324-14.052-31.324-31.324
  537. c0-17.272,14.052-31.324,31.324-31.324s31.324,14.052,31.324,31.324C121.988,100.604,107.937,114.655,90.664,114.655z"/>
  538. <path d="M40.595,83.331c0-4.142-3.358-7.5-7.5-7.5H7.5c-4.142,0-7.5,3.358-7.5,7.5c0,4.142,3.358,7.5,7.5,7.5h25.595
  539. C37.237,90.831,40.595,87.473,40.595,83.331z"/>
  540. <path d="M173.828,75.831h-25.595c-4.142,0-7.5,3.358-7.5,7.5c0,4.142,3.358,7.5,7.5,7.5h25.595c4.142,0,7.5-3.358,7.5-7.5
  541. C181.328,79.189,177.97,75.831,173.828,75.831z"/>
  542. <path d="M44.654,47.926c1.464,1.465,3.384,2.197,5.303,2.197c1.919,0,3.839-0.732,5.303-2.197c2.929-2.929,2.929-7.678,0-10.606
  543. L37.162,19.222c-2.929-2.93-7.678-2.929-10.606,0c-2.929,2.929-2.929,7.678,0,10.606L44.654,47.926z"/>
  544. <path d="M136.674,118.735c-2.93-2.929-7.678-2.928-10.607,0c-2.929,2.929-2.928,7.678,0,10.607l18.1,18.098
  545. c1.465,1.464,3.384,2.196,5.303,2.196c1.919,0,3.839-0.732,5.304-2.197c2.929-2.929,2.928-7.678,0-10.607L136.674,118.735z"/>
  546. <path d="M44.654,118.736l-18.099,18.098c-2.929,2.929-2.929,7.677,0,10.607c1.464,1.465,3.384,2.197,5.303,2.197
  547. c1.919,0,3.839-0.732,5.303-2.197l18.099-18.098c2.929-2.929,2.929-7.677,0-10.606C52.332,115.807,47.583,115.807,44.654,118.736z"
  548. />
  549. <path d="M131.371,50.123c1.919,0,3.839-0.732,5.303-2.196l18.1-18.098c2.929-2.929,2.929-7.678,0-10.607
  550. c-2.929-2.928-7.678-2.929-10.607-0.001l-18.1,18.098c-2.929,2.929-2.929,7.678,0,10.607
  551. C127.532,49.391,129.452,50.123,131.371,50.123z"/>
  552. <path d="M90.664,133.4c-4.142,0-7.5,3.358-7.5,7.5v25.595c0,4.142,3.358,7.5,7.5,7.5c4.142,0,7.5-3.358,7.5-7.5V140.9
  553. C98.164,136.758,94.806,133.4,90.664,133.4z"/>
  554. </g>
  555. </svg>
  556. `
  557.  
  558. TocBar.prototype = {
  559. /**
  560. * @method TocBar
  561. */
  562. initHeader() {
  563. const header = document.createElement('div')
  564. header.classList.add('toc-bar__header')
  565. header.innerHTML = `
  566. <div class="flex toc-bar__header-left">
  567. <div class="toc-bar__toggle toc-bar__icon-btn" title="Toggle TOC Bar">
  568. ${TOC_ICON}
  569. </div>
  570. <div class="toc-bar__title hidden-when-collapsed">TOC Bar</div>
  571. </div>
  572. <div class="toc-bar__actions flex hidden-when-collapsed">
  573. <div class="toc-bar__scheme toc-bar__icon-btn" title="Toggle Light/Dark Mode">
  574. ${LIGHT_ICON}
  575. </div>
  576. <div class="toc-bar__refresh toc-bar__icon-btn" title="Refresh TOC">
  577. ${REFRESH_ICON}
  578. </div>
  579. </div>
  580. `
  581. const toggleElement = header.querySelector('.toc-bar__toggle')
  582. toggleElement.addEventListener('click', () => {
  583. this.toggle()
  584. GM_setValue('tocbar-hidden', !this.visible)
  585. })
  586. this.logoSvg = toggleElement.querySelector('svg')
  587.  
  588. const refreshElement = header.querySelector('.toc-bar__refresh')
  589. refreshElement.addEventListener('click', () => {
  590. tocbot.refresh()
  591. })
  592.  
  593. const toggleSchemeElement = header.querySelector('.toc-bar__scheme')
  594. toggleSchemeElement.addEventListener('click', () => {
  595. this.toggleScheme()
  596. })
  597. // ---------------- header drag ----------------------
  598. const dragState = {
  599. startMouseX: 0,
  600. startMouseY: 0,
  601. startPositionX: 0,
  602. startPositionY: 0,
  603. startElementDisToRight: 0,
  604. isDragging: false,
  605. curRight: 0,
  606. curTop: 0,
  607. }
  608.  
  609. const onMouseMove = (e) => {
  610. if (!dragState.isDragging) return
  611. const deltaX = e.pageX - dragState.startMouseX
  612. const deltaY = e.pageY - dragState.startMouseY
  613. // 要换算为 right 数字
  614. const newRight = Math.max(30 - TOC_BAR_WIDTH, dragState.startElementDisToRight - deltaX)
  615. const newTop = Math.max(0, dragState.startPositionY + deltaY)
  616. Object.assign(dragState, {
  617. curTop: newTop,
  618. curRight: newRight,
  619. })
  620. // console.table({ newRight, newTop})
  621. this.element.style.right = `${newRight}px`
  622. this.element.style.top = `${newTop}px`
  623. }
  624.  
  625. const onMouseUp = (e) => {
  626. Object.assign(dragState, {
  627. isDragging: false,
  628. })
  629. document.body.removeEventListener('mousemove', onMouseMove)
  630. document.body.removeEventListener('mouseup', onMouseUp)
  631.  
  632. POSITION_STORAGE.set(this.options.siteName, {
  633. top: dragState.curTop,
  634. right: dragState.curRight,
  635. })
  636. }
  637.  
  638. header.addEventListener('mousedown', (e) => {
  639. if (e.target === toggleElement) return
  640. const bbox = this.element.getBoundingClientRect()
  641. Object.assign(dragState, {
  642. isDragging: true,
  643. startMouseX: e.pageX,
  644. startMouseY: e.pageY,
  645. startPositionX: bbox.x,
  646. startPositionY: bbox.y,
  647. startElementDisToRight: document.body.clientWidth - bbox.right,
  648. })
  649. document.body.addEventListener('mousemove', onMouseMove)
  650. document.body.addEventListener('mouseup', onMouseUp)
  651. })
  652. // ----------------end header drag -------------------
  653.  
  654. this.element.appendChild(header)
  655. },
  656. /**
  657. * @method TocBar
  658. */
  659. initTocbot(options) {
  660. const me = this
  661.  
  662. /**
  663. * records for existing ids to prevent id conflict (when there are headings of same content)
  664. * @type {Object} {[key: string]: number}
  665. **/
  666. this._tocContentCountCache = {}
  667.  
  668. const tocbotOptions = Object.assign(
  669. {},
  670. {
  671. tocSelector: `.${TOCBOT_CONTAINTER_CLASS}`,
  672. scrollSmoothOffset: options.scrollSmoothOffset || 0,
  673. // hasInnerContainers: true,
  674. headingObjectCallback(obj, ele) {
  675. // if there is no id on the header element, add one that derived from hash of header title
  676. if (!ele.id) {
  677. const newId = me.generateHeaderId(obj, ele)
  678. ele.setAttribute('id', newId)
  679. obj.id = newId
  680. }
  681. return obj
  682. },
  683. headingSelector: 'h1, h2, h3, h4, h5',
  684. collapseDepth: 4,
  685. },
  686. options
  687. )
  688. // console.log('tocbotOptions', tocbotOptions);
  689. tocbot.init(tocbotOptions)
  690. },
  691. generateHeaderId(obj, ele) {
  692. const hash = doContentHash(obj.textContent)
  693. let count = 1
  694. let resultHash = hash
  695. if (this._tocContentCountCache[hash]) {
  696. count = this._tocContentCountCache[hash] + 1
  697. resultHash = doContentHash(`${hash}-${count}`)
  698. }
  699. this._tocContentCountCache[hash] = count
  700. return `tocbar-${resultHash}`
  701. },
  702. /**
  703. * @method TocBar
  704. */
  705. toggle(shouldShow = !this.visible) {
  706. const HIDDEN_CLASS = 'toc-bar--collapsed'
  707. const LOGO_HIDDEN_CLASS = 'toc-logo--collapsed'
  708. if (shouldShow) {
  709. this.element.classList.remove(HIDDEN_CLASS)
  710. this.logoSvg && this.logoSvg.classList.remove(LOGO_HIDDEN_CLASS)
  711. } else {
  712. this.element.classList.add(HIDDEN_CLASS)
  713. this.logoSvg && this.logoSvg.classList.add(LOGO_HIDDEN_CLASS)
  714.  
  715. const right = parseInt(this.element.style.right)
  716. if (right && right < 0) {
  717. this.element.style.right = "0px"
  718. const cachedPosition = POSITION_STORAGE.cache
  719. if (!isEmpty(cachedPosition)) {
  720. POSITION_STORAGE.set(null, {...cachedPosition, right: 0 })
  721. }
  722. }
  723. }
  724. this.visible = shouldShow
  725. },
  726. /**
  727. * Toggle light/dark scheme
  728. * @method TocBar
  729. */
  730. toggleScheme(isDark) {
  731. const isDarkMode = typeof isDark === 'undefined' ? !this.isDarkMode: isDark
  732. this.element.setAttribute('colorscheme', isDarkMode ? 'dark': 'light')
  733. console.log('[toc-bar] toggle scheme', isDarkMode)
  734. this.isDarkMode = isDarkMode
  735.  
  736. GM_setValue(DARKMODE_KEY, isDarkMode)
  737. this.refreshStyle()
  738. },
  739. refreshStyle() {
  740. const themeColor = guessThemeColor()
  741. if (themeColor && !this.isDarkMode) {
  742. this.element.style.setProperty('--toc-bar-active-color', themeColor);
  743. } else if (this.isDarkMode) {
  744. this.element.style.setProperty('--toc-bar-active-color', TOC_BAR_DEFAULT_ACTIVE_COLOR);
  745. }
  746. },
  747. }
  748. // ----------------end TocBar -------------------
  749.  
  750. function main() {
  751. const options = getPageTocOptions()
  752.  
  753. if (options) {
  754. const tocBar = new TocBar(options)
  755. tocBar.initTocbot(options)
  756. tocBar.refreshStyle()
  757. }
  758. }
  759.  
  760. main()
  761. })()