From 37e7984e7efab3767badb9d940b7368b2b6f8493 Mon Sep 17 00:00:00 2001 From: "cinwell.li" Date: Sun, 27 Nov 2016 18:53:31 +0800 Subject: [PATCH] feat: custom sidebar, #4 (#5) * feat: custom sidebar, #4 * fix dev html * fix doc * fix doc --- docs/README.md | 23 +++++++++++++++++++++++ docs/zh-cn.md | 22 ++++++++++++++++++++++ src/bind-event.js | 8 ++++---- src/gen-toc.js | 11 +++++++---- src/index.js | 18 +++++++++++++----- src/render.js | 4 ++-- 6 files changed, 71 insertions(+), 15 deletions(-) diff --git a/docs/README.md b/docs/README.md index c9b84ee..5b439d3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -121,3 +121,26 @@ Root element. ``` +#### sidebar + +Custom sidebar. if it'set, the TOC will be disabeld. Bind global variables on the `data-sidebar`. + +![image](https://cloud.githubusercontent.com/assets/7565692/20647425/de5ab1c2-b4ce-11e6-863a-135868f2f9b4.png) + +```html + + +``` + diff --git a/docs/zh-cn.md b/docs/zh-cn.md index 090b2f9..7c1baa7 100644 --- a/docs/zh-cn.md +++ b/docs/zh-cn.md @@ -119,4 +119,26 @@ docsify serve docs ``` +#### sidebar + +设置后 TOC 功能将不可用,适合导航较多的文档,`data-sidebar` 传入全局变量名。 + +![image](https://cloud.githubusercontent.com/assets/7565692/20647425/de5ab1c2-b4ce-11e6-863a-135868f2f9b4.png) + +```html + + +``` diff --git a/src/bind-event.js b/src/bind-event.js index 1fc7fe3..505ed1f 100644 --- a/src/bind-event.js +++ b/src/bind-event.js @@ -1,5 +1,5 @@ -function scrollActiveSidebar () { - if (/mobile/i.test(navigator.userAgent)) return +function scrollActiveSidebar (isCustom) { + if (/mobile/i.test(navigator.userAgent) || isCustom) return const anchors = document.querySelectorAll('.anchor') const nav = {} @@ -48,6 +48,6 @@ function scrollActiveSidebar () { scrollIntoView() } -export default function () { - scrollActiveSidebar() +export default function (isCustom) { + scrollActiveSidebar(isCustom) } diff --git a/src/gen-toc.js b/src/gen-toc.js index 16734e7..ee89e37 100644 --- a/src/gen-toc.js +++ b/src/gen-toc.js @@ -25,8 +25,8 @@ const tocToTree = function (toc, maxLevel) { const buildHeadlinesTree = function (tree, tpl = '') { if (!tree || !tree.length) return '' - tree.forEach((node) => { - tpl += `
  • ${node.title}
  • ` + tree.forEach(node => { + tpl += `
  • ${node.title}
  • ` if (node.children) { tpl += `
  • ` } @@ -35,7 +35,10 @@ const buildHeadlinesTree = function (tree, tpl = '') { return tpl } -export default function (toc, maxLevel) { - var tree = tocToTree(toc, maxLevel) +export default function (toc, opts) { + var tree = Array.isArray(opts.sidebar) + ? opts.sidebar + : tocToTree(toc, opts['max-level']) + return buildHeadlinesTree(tree, '