Greasy Fork 还支持 简体中文。

Toc Bar, auto-generating table of content

A floating table of content widget

目前為 2022-01-19 提交的版本,檢視 最新版本

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