Tocbot は、HTML ドキュメントの見出しから目次(TOC)を作成します。これを使うとWeb サイトのドキュメントや長いマークダウンページでのナビゲーションが簡単になるので便利です。このライブラリは Tocifyからアイディアを得て作られました。主な違いは、 Tocbot はネイティブ DOM メソッドを使用し、jQuery および jQuery UI の依存関係を回避していることです。
原文を見る
Tocbot builds a table of contents (TOC) from headings in an HTML document. This is useful for documentation websites or long markdown pages because it makes them easier to navigate. This library was inspired by Tocify, the main difference is that Tocbot uses native DOM methods and avoids the jQuery & jQuery UI dependencies.
はじめる
npm を使用してインストールするか、HTML でページにスクリプトをインクルードすることができます。
原文を見る
You can use npm to install it or include the script on the page with HTML.
JavaScriptのインクルード
npm を使ってインストールします。
npm install --save tocbot次に、commonjs または ESM インポートのいずれかを使用します。:
const tocbot = require('tocbot/dist/tocbot.js')
// もしくは
import tocbot from 'tocbot'
// tocbotを初期化する
tocbot.init()もしくは
ページの下部のbodyの終了タグの前でスクリプトをインクルードします。
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.30.0/tocbot.min.js"></script>原文を見る
Install it with npm.
npm install --save tocbotThen use with either commonjs or ESM imports:
const tocbot = require('tocbot/dist/tocbot.js') // OR import tocbot from 'tocbot' // Initialize tocbot tocbot.init()OR
Include the script at the bottom of the page before the closing body tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.30.0/tocbot.min.js"></script>
CSSのインクルード
CSS は、グループの展開と折りたたみ、およびいくつかの基本的なスタイル設定に使用されます。
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.30.0/tocbot.css">もしくは
npmを使ってTocbotをインストールし、sass / postcssを使用している場合は、「node_modules」からスタイルをインポートしてみてください。詳細については、includePath オプションのドキュメントを参照してください。
@import 'tocbot/src/scss/tocbot';原文を見る
CSS is used for expanding & collapsing groupings and some basic styling.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.30.0/tocbot.css">OR
If you installed it with npm and use sass / postcss you might try importing the styles from ‘node_modules’, see the includePath option documentation for more info.
@import 'tocbot/src/scss/tocbot';
使い方
ページの下部、body の終了タグの前でスクリプトを初期化します。
tocbot.init({
// 目次をレンダリングする場所。
tocSelector: '.js-toc',
// 目次を作成するための見出しを取得する場所。
contentSelector: '.js-toc-content',
// contentSelector要素内で取得する見出し。
headingSelector: 'h1, h2, h3',
// コンテンツ内で相対配置または絶対配置されたコンテナー内の見出し用の設定。
hasInnerContainers: true,
});NOTE: 本文がスクロール可能であり、ドキュメントの見出しに id 属性が設定されていることを確認してください。tocbot とブラウザでは、ハッシュを適切な見出しにジャンプさせるためにこれらが必要です。一部のマークダウンライブラリ (markedなど) を使っていれば既にこの処理は行われています。
div 内のコンテンツが変更された場合は、refresh を実行します (必要に応じて新しいオプションを設定してください)。
tocbot.refresh();また、Typescript でも使用できます。:
import * as tocbot from 'tocbot';
tocbot.init({
// オプション
});
tocbot.refresh();
tocbot.destroy();原文を見る
Initialize the script at the bottom of the page before the closing body tag.
tocbot.init({ // Where to render the table of contents. tocSelector: '.js-toc', // Where to grab the headings to build the table of contents. contentSelector: '.js-toc-content', // Which headings to grab inside of the contentSelector element. headingSelector: 'h1, h2, h3', // For headings inside relative or absolute positioned containers within content. hasInnerContainers: true, });NOTE: Make sure the body is scrollable and the document headings have id attributes, tocbot and your browser needs these things to make hashes jump to the proper heading, some markdown libraries (like marked) already do this for you.
If content in the div has changed then trigger a refresh (optionally with new options).
tocbot.refresh();Also you can use it within typescript:
import * as tocbot from 'tocbot'; tocbot.init({ // Options }); tocbot.refresh(); tocbot.destroy();
例
- Tocbot のホームページ
- Storybook ではTocbotを使用しています
- Tocbot はStorybookの内部で使用されており、Storybookのコンポーネントドキュメントの 目次生成を提供しています。
この一覧にあなたのページを追加したい場合は、プルリクエストを開いてください。
原文を見る
- Tocbot Homepage
- Storybook uses Tocbot
- Tocbot is used under the hood in storybook to provide TOC generation for component docs in storybook.
If you’d like to add your page to this list open a pull request.
要件
このライブラリはVanilla JavaScriptを使用しています。CSS は350バイト未満、JavaScript は約 3.6キロバイト (縮小および gzip 圧縮) で依存関係もありません。
このスクリプトはすべての最新ブラウザと IE 9 以降で動作します。
レンダリングされた見出しに id 属性が設定されていることを確認してください。一部のマークダウン ライブラリ (markedなど) を使っていれば既にこの処理は行われています。あなた自身でこの作業を行う必要がある場合は、このスクリプトを参照してください。
注意: アンカー要素をスムーズスクロールから除外するには、no-smooth-scrollクラスを追加します。
原文を見る
This library uses vanilla JavaScript. It is less than 350 bytes of CSS and about 3.6Kb of JavaScript (minified and gzipped) it also has no dependencies.
This script works in all modern browsers and IE 9+.
Make sure rendered headings have id attributes, some markdown libraries (like marked) already do this. If you need to do this client side see this script.
NOTE: to exclude anchor elements from smooth scrolling, add the class
no-smooth-scroll.
固定ヘッダー
tocbot で固定ヘッダーに対応するには、ヘッダーのオフセットを tocbot のオプションとして渡すだけです。たとえば、高さ40ピクセルの固定ヘッダーに必要なオプションは次のようになります。:
tocbot.init({
headingsOffset: 40,
scrollSmoothOffset: -40
})原文を見る
To handle fixed headers with tocbot, just pass the header offsets as options to tocbot. For example, the options needed for a 40px tall fixed header would be:
tocbot.init({ headingsOffset: 40, scrollSmoothOffset: -40 })
API
オプション
// 目次をレンダリングする場所。
tocSelector: '.js-toc',
// もしくは、代わりにDOMノードを渡すこともできます。
tocElement: null,
// 目次を作成するための見出しを取得する場所。
contentSelector: '.js-toc-content',
// もしくは、代わりにDOMノードを渡すこともできます。
contentElement: null,
//contentSelector要素内で取得する見出し。
headingSelector: 'h1, h2, h3',
// ignoreSelector に一致する見出しはスキップされます。
ignoreSelector: '.js-toc-ignore',
// コンテンツ内で相対配置または絶対配置されたコンテナー内の見出し用の設定。
hasInnerContainers: false,
// リンクに追加するメインクラス。
linkClass: 'toc-link',
// リンクに追加するその他クラス。
extraLinkClasses: '',
// アクティブ リンクに追加するクラス。
// これはページの一番上の見出しに対応するリンクです。
activeLinkClass: 'is-active-link',
// リストに追加するメインクラス。
listClass: 'toc-list',
// リストに追加するその他クラス。
extraListClasses: '',
// リストを折りたたむ必要がある時に追加されるクラス。
isCollapsedClass: 'is-collapsed',
// リストを折りたたむことはできるが、必ずしも折りたたまれる訳ではない場合に追加されるクラス。
collapsibleClass: 'is-collapsible',
// リスト項目に追加するクラス。
listItemClass: 'toc-list-item',
// アクティブなリスト項目に追加するクラス。
activeListItemClass: 'is-active-li',
// 折りたたまない見出しレベル数。
// たとえば、数字の6を設定するとはすべての見出しを表示します。
// 見出しレベルは6つしかないためです。数字の0を設定するとすべてを折りたたみます。
// 見出しへのスクロールに応じて、非表示のセクションは開いたり閉じたりします。
collapseDepth: 0,
// スムーズスクロール機能を有効にします。
scrollSmooth: true,
// スムーズスクロールの期間。
scrollSmoothDuration: 420,
// スムーズスクロールのオフセット。
scrollSmoothOffset: 0,
// スクロールが終了した時に呼び出されるコールバック。
scrollEndCallback: function (e) {},
// 見出しとドキュメント上部との間の見出しオフセット (これは微調整に使います)。
headingsOffset: 1,
// イベントの発生間隔にタイムアウトを設定して、
// あまり速くなり過ぎないようにします(パフォーマンス上の理由)。
throttleTimeout: 50,
// positionFixedClass を追加する要素。
positionFixedSelector: null,
// fixedSidebarOffset を超えて下にスクロールした後に
// サイドバーを固定するために追加する固定位置クラス。
positionFixedClass: 'is-position-fixed',
// fixedSidebarOffset は任意の数値を設定できますが、デフォルトでは auto に設定されています。
// 初期化時にはドキュメント上部からサイドバー要素までの offsetTopに対して
// fixedSidebarOffset が設定されます。
fixedSidebarOffset: 'auto',
// includeHtml を true に設定すると、
// innerText だけでなく見出しノードからの HTML マークアップも含めることができます。
includeHtml: false,
// includeTitleTags はリンクのHTMLタイトルタグをタイトルと一致するように自動的に設定します。
// これはSEO目的やタイトルを切り捨てる時に役立ちます。
includeTitleTags: false,
// onclick 関数は、目次内の全てのリンクに適用されます。
// 第一引数としてeventが渡され、これを使ってアクションを停止させたり伝播させたり、
// デフォルトのアクションを阻止したり任意のアクションを実行したりできます。
onClick: function (e) {},
// orderedList を false に設定すると、
// 順序付きリスト(ol)ではなく順序なしリスト(ul)が生成されます。
orderedList: true,
// 固定記事スクロールコンテナがある場合は、オフセットを計算するように設定します。
scrollContainer: null,
// 既に外部システムによってレンダリングされている場合は、目次のDOM のレンダリングを阻止します。
skipRendering: false,
// 見出しラベルを変更するための任意のコールバック。
// たとえば、長すぎると思われる複数行の見出しを切り詰めて省略記号を付けるために使用できます。
// 見出しが解析されるたびに呼び出されます。
// 引数として文字列を受け取り、表示するための変更されたラベルを戻り値として返します。
// さらに、見出しで`data-heading-label`属性を使用して、目次で使用する短い文字列を指定することもできます。
// function (string) => string
headingLabelCallback: false,
// DOM で隠されている見出しを無視します。
ignoreHiddenElements: false,
// 解析された見出しのプロパティを変更するための任意のコールバック。
// 見出し要素はnode引数として渡され、デフォルトのパーサーによって解析された情報は
// obj 引数として提供されます。
// この関数は引数と同じobjか引数を編集したobj を戻り値として返す必要があります。
// 戻り値を何も返されない場合、その見出しは目次から除外されます。
// function (object, HTMLElement) => object | void
headingObjectCallback: null,
// ベースパスを設定します。`head` で `base` タグを使用する場合に便利です。
basePath: '',
// `to Selector` がスクロールしている時のみ有効です。
// 目次のスクロール位置をコンテンツと同期させます。
disableTocScrollSync: false,
// この設定が null の場合は、代わりに `tocElement` や `tocSelector` が使用されるだけです。
// 設定する場合は`disableTocScrollSync` にfalseを設定してください。
// これにより目次を含む外側の要素 (検索機能付きのナビゲーション パネルなど) をスクロールできるようになります。
// セレクターではなく要素を設定してください。
tocScrollingWrapper: null,
// ページをスクロールする時の目次スクロール (上) 位置のオフセット。
// `disableTocScrollSync` が false の場合にのみ有効です。
tocScrollOffset: 0,
// ユーザーがページをスクロールする時に、URL ハッシュが適切な見出し ID で更新されるようにします。
enableUrlHashUpdateOnScroll: false原文を見る
// Where to render the table of contents. tocSelector: '.js-toc', // Or, you can pass in a DOM node instead tocElement: null, // Where to grab the headings to build the table of contents. contentSelector: '.js-toc-content', // Or, you can pass in a DOM node instead contentElement: null, // Which headings to grab inside of the contentSelector element. headingSelector: 'h1, h2, h3', // Headings that match the ignoreSelector will be skipped. ignoreSelector: '.js-toc-ignore', // For headings inside relative or absolute positioned // containers within content. hasInnerContainers: false, // Main class to add to links. linkClass: 'toc-link', // Extra classes to add to links. extraLinkClasses: '', // Class to add to active links, // the link corresponding to the top most heading on the page. activeLinkClass: 'is-active-link', // Main class to add to lists. listClass: 'toc-list', // Extra classes to add to lists. extraListClasses: '', // Class that gets added when a list should be collapsed. isCollapsedClass: 'is-collapsed', // Class that gets added when a list should be able // to be collapsed but isn't necessarily collapsed. collapsibleClass: 'is-collapsible', // Class to add to list items. listItemClass: 'toc-list-item', // Class to add to active list items. activeListItemClass: 'is-active-li', // How many heading levels should not be collapsed. // For example, number 6 will show everything since // there are only 6 heading levels and number 0 will collapse them all. // The sections that are hidden will open // and close as you scroll to headings within them. collapseDepth: 0, // Smooth scrolling enabled. scrollSmooth: true, // Smooth scroll duration. scrollSmoothDuration: 420, // Smooth scroll offset. scrollSmoothOffset: 0, // Callback for scroll end. scrollEndCallback: function (e) {}, // Headings offset between the headings and the top of // the document (this is meant for minor adjustments). headingsOffset: 1, // Timeout between events firing to make sure it's // not too rapid (for performance reasons). throttleTimeout: 50, // Element to add the positionFixedClass to. positionFixedSelector: null, // Fixed position class to add to make sidebar fixed after scrolling // down past the fixedSidebarOffset. positionFixedClass: 'is-position-fixed', // fixedSidebarOffset can be any number but by default is set // to auto which sets the fixedSidebarOffset to the sidebar // element's offsetTop from the top of the document on init. fixedSidebarOffset: 'auto', // includeHtml can be set to true to include the HTML markup from the // heading node instead of just including the innerText. includeHtml: false, // includeTitleTags automatically sets the html title tag of the link // to match the title. This can be useful for SEO purposes or // when truncating titles. includeTitleTags: false, // onclick function to apply to all links in toc. will be called with // the event as the first parameter, and this can be used to stop, // propagation, prevent default or perform action onClick: function (e) {}, // orderedList can be set to false to generate unordered lists (ul) // instead of ordered lists (ol) orderedList: true, // If there is a fixed article scroll container, set to calculate offset. scrollContainer: null, // prevent ToC DOM rendering if it's already rendered by an external system. skipRendering: false, // Optional callback to change heading labels. // For example it can be used to cut down and put ellipses on multiline headings you deem too long. // Called each time a heading is parsed. Expects a string and returns the modified label to display. // Additionally, the attribute `data-heading-label` may be used on a heading to specify // a shorter string to be used in the TOC. // function (string) => string headingLabelCallback: false, // ignore headings that are hidden in DOM ignoreHiddenElements: false, // Optional callback to modify properties of parsed headings. // The heading element is passed in node parameter and information // parsed by default parser is provided in obj parameter. // Function has to return the same or modified obj. // The heading will be excluded from TOC if nothing is returned. // function (object, HTMLElement) => object | void headingObjectCallback: null, // Set the base path, useful if you use a `base` tag in `head`. basePath: '', // Only takes affect when `tocSelector` is scrolling, // keep the toc scroll position in sync with the content. disableTocScrollSync: false, // If this is null then just use `tocElement` or `tocSelector` instead // assuming `disableTocScrollSync` is set to false. This allows for // scrolling an outer element (like a nav panel w/ search) containing the toc. // Please pass an element, not a selector here. tocScrollingWrapper: null, // Offset for the toc scroll (top) position when scrolling the page. // Only effective if `disableTocScrollSync` is false. tocScrollOffset: 0, // Enable the URL hash to update with the proper heading ID as // a user scrolls the page. enableUrlHashUpdateOnScroll: false
メソッド
.init
options オブジェクトを使用して tocbot を初期化します。
tocbot.init(options)原文を見る
Initialize tocbot with an options object.
tocbot.init(options)
.destroy
tocbot を破棄し、イベント リスナーを削除します。
tocbot.destroy()原文を見る
Destroy tocbot and remove event listeners.
tocbot.destroy()
.refresh
ドキュメントが変更されて再構築する必要がある場合、tocbot を更新します。
tocbot.refresh()原文を見る
Refresh tocbot if the document changes and it needs to be rebuilt.
tocbot.refresh()
トラブルシューティング
- Tocbot はクリックすると正しい位置までスクロールしますが、ハイライト表示ではアクティブなセクションが表示されないかもしれません。
- コンソールから以下を実行してみてください:
tocbot.refresh({ ...tocbot.options, hasInnerContainers: true })。これが機能する場合は、内部コンテナーを処理するための 1 つのオプション (hasInnerContainers: true) を追加するだけで十分です。
- コンソールから以下を実行してみてください:
- 目次が非常に長く、見出しが切り捨てられている場合は、このissueを参照して回避策を見つけ、解決してください。
原文を見る
- Tocbot scrolls to the right position onClick but highlighting doesn’t seem to show the active section
- Try running this from the console:
tocbot.refresh({ ...tocbot.options, hasInnerContainers: true }). If that works then one option (hasInnerContainers: true) to handle inner containers should be all you need to add.- If you have a really long TOC and are seeing headings getting truncated, then have a look at this issue for a workaround to resolve it.
貢献活動
貢献活動や提案は大歓迎です! 問題に遭遇したり、機能のリクエストがある場合は、遠慮なく問題を報告してください。迅速に回答できるよう最善を尽くします。
プルリクエストを開きたい場合は、リポジトリをフォークするだけですが、すべてのテストと lint に合格していることを確認してください。
原文を見る
Contributions and suggestions are welcome! Please feel free to open an issue if you run into a problem or have a feature request. I’ll do my best to respond in a timely fashion.
If you want to open a pull request just fork the repo but please make sure all tests and lint pass.
テストを実行する
npm run test公開手順
- ブランチをプッシュしてプルリクエストを開きます
npm version <patch|minor|major>を実行します- readme.md に注釈を記述して更新します
- プルリクエストをマージします
- dist/ をコミットします
npm publishを実行します- githubでリリースします
原文を見る
- Push a branch and open a pull request
- run
npm version <patch|minor|major>- Update readme.md with notes
- Merge the pull request
- commit dist/
- run
npm publish- make release