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

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

当前为 2021-12-24 提交的版本,查看 最新版本

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