UNPKG

@anjuna/docs

Version:

Anjuna Documentation Web Components

84 lines (83 loc) 2.72 kB
export class Toc { constructor() { this.activeId = '#overview'; this.docs = {}; } onDemosChange() { this.sectionIds = ['#overview'].concat(this.demos.map(d => `#${d.usage}`)).concat('#api'); } componentDidLoad() { this.navigate = debounce(this.navigate.bind(this), 50); this.onScroll = debounce(this.onScroll.bind(this), 10); this.onDemosChange(); if (window.location.hash) { this.navigate(); } } onScroll() { const els = this.sectionIds.map(id => document.querySelector(id)); let closest = els[0]; els.slice(1).forEach(el => { if (el && Math.abs(window.scrollY - el.offsetTop) < Math.abs(window.scrollY - closest.offsetTop)) { closest = el; } }); this.activeId = `#${closest.getAttribute('id')}`; } parseTitle(id) { const usage = id.replace('#', ''); const doc = this.docs[usage]; return doc ? doc.split(/##(.*?)\n/).find(p => p !== '').trim() : usage; } anchorClass(usage) { return usage === this.activeId ? 'anj-active' : ''; } navigate() { return new Promise(resolve => { window.setTimeout(() => { this.activeId = window.location.hash; const el = document.querySelector(this.activeId); window.scrollTo(0, el.offsetTop); resolve(); }, 500); }); } render() { if (!this.sectionIds) { return; } const path = window.location.pathname; return (h("div", { class: "anj-toc" }, this.sectionIds.map(id => h("a", { href: `${path}${id}`, onClick: () => this.activeId = id, class: this.anchorClass(id) }, this.parseTitle(id))))); } static get is() { return "ad-toc"; } static get properties() { return { "activeId": { "state": true }, "demos": { "type": "Any", "attr": "demos", "watchCallbacks": ["onDemosChange"] }, "docs": { "type": "Any", "attr": "docs" }, "sectionIds": { "state": true } }; } static get listeners() { return [{ "name": "window:scroll", "method": "onScroll", "passive": true }]; } static get style() { return "/**style-placeholder:ad-toc:**/"; } } const debounce = (func, wait = 0) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(func, wait, ...args); }; };