(function createIndex () { function setRealPageNumbers () { let pages = document.querySelectorAll('.pagedjs_page'), realPageCounter = 0; const pageCounterResetPatt = /page (\d+)/; // Set an extra data-attribute with the 'real' pagenumber // Loop through all the pages. for (let i = 0; i < pages.length; i++) { const page = pages[i], m = window.getComputedStyle(page).getPropertyValue('counter-reset').match(pageCounterResetPatt); // Test through getComputedStyles whether there is a counter reset. if (m && m.length) { // Set js counter to that value console.log('Page counter reset to:', m[1], 'on page', page.dataset.pageNumber); realPageCounter = parseInt(m[1]); } // Increment js counter by one realPageCounter++; // Set it on the page. page.dataset.realPageNumber = realPageCounter; } } function triggerDownload (content, filename, mime) { const a = document.createElement('a'); a.setAttribute('href', `data:${mime};charset=utf-8,${encodeURIComponent(content)}`); a.setAttribute('download', filename); if (document.createEvent) { const event = document.createEvent('MouseEvents'); event.initEvent('click', true, true); a.dispatchEvent(event); } else { a.click(); } } function getPageNum (el) { if ('realPageNumber' in el.dataset) { return parseInt(el.dataset.realPageNumber); } else if (el.parentElement) { return getPageNum(el.parentElement); } } function createToc(tocQueries){ var toc = []; for(let i = 0; i < tocQueries.length; ++i){ let tocElements = document.querySelectorAll(tocQueries[i]['query']), level = tocQueries[i]['level']; for (let e = 0; e < tocElements.length; e++) { const tocElement = tocElements[e], pageNum = getPageNum(tocElement); toc.push({ level: level, page: pageNum, label: tocElement.innerText }); } } return toc; } function createJsonToc (tocQueries) { let urlParameters = new URLSearchParams(window.location.search), pathParts = window.location.pathname.split('/'), lastPathPart = pathParts[pathParts.length - 1], downloadName = 'toc.json'; if (lastPathPart) { downloadName = 'toc-' + lastPathPart.replace('.html', '.json'); // Ugly, insecure, but here it'll work. MVP for the win. } if (urlParameters.has('makeToc')) { setRealPageNumbers(); const index = createToc(tocQueries); triggerDownload(JSON.stringify(index), downloadName, 'application/json'); } } window.createJsonToc = createJsonToc; })();