miradocs 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 miradocs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # miradocs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A static documentation framework built in JavaScript. Write pages in Markdown, organize navigation with folders, and customize the interface through CSS variables and reusable components.
4
+
5
+ [Documentation and live examples](https://fatalmistake02.github.io/miradocs/)
6
+
7
+ The documentation site is built with miradocs and includes working examples of its components.
8
+
9
+ Requires Node.js 20.19 or newer.
10
+
11
+ Create a documentation site with the `create-miradocs` starter:
12
+
13
+ ```sh
14
+ npm create miradocs@latest my-docs
15
+ cd my-docs
16
+ npm install
17
+ npm run dev
18
+ ```
19
+
20
+ To run this repository’s documentation site locally, use `npm ci` and `npm run dev`.
21
+
22
+ The starter creates your content folder, configuration, and theme stylesheet. miradocs is installed as a dependency. See [Installation](docs/01-getting-started/01-installation.md) for setup instructions with npm, pnpm, Yarn, and Bun.
23
+
24
+ Open http://localhost:8000. Development mode watches content, configuration, theme, and component files and reloads the browser after successful builds.
25
+
26
+ ```sh
27
+ npm run build
28
+ ```
29
+
30
+ Deploy the contents of `site/` to any static host. The output has no server runtime requirement. The CLI can also be used directly with Node.js or installed through any compatible JavaScript package manager.
31
+
32
+ The framework includes:
33
+
34
+ - CommonMark, tables, task lists, footnotes, images, and highlighted code.
35
+ - Automatic nested navigation, explicit sidebar configuration, pagination, and a pinned outline.
36
+ - Light, dark, and system themes, semantic CSS tokens, custom styles, logos, and links.
37
+ - Lazy-loaded fuzzy search with platform-aware keyboard shortcuts.
38
+ - Locale folders, language switching, translated interface dictionaries, and RTL layout support.
39
+ - Tabs, callouts, disclosures, cards, buttons, steps, badges, file trees, searchable lists and tables, content groups, and custom HTML components.
40
+ - Optional React, Vue, Svelte, and browser module components with per-page bundles and navigation cleanup.
41
+ - Landing pages without sidebars.
42
+ - Static metadata, sitemap generation, 404 pages, drafts, and internal link checking.
43
+ - Atomic builds that preserve previous output on failure.
44
+
45
+ Configuration lives in `miradocs.config.json`. The `docs/` directory contains the documentation for miradocs. `miradocs.schema.json` provides editor completion and validation.
46
+
47
+ Run `npm test` for integration checks, or `npm run check` for tests and a production documentation build. GitHub Actions runs checks on Windows, macOS, and Linux with Node.js 20, 22, and 24.
48
+
49
+ MIT licensed. Interface icons are from Lucide; brand icons are from Simple Icons and retain their respective trademark associations.
package/assets/app.js ADDED
@@ -0,0 +1,150 @@
1
+ import { enableNavigation } from './navigation.js';
2
+ import { initializeClientComponents } from './client-components.js';
3
+ import { initializeOutline } from './outline.js';
4
+ import { initializeLists } from './lists.js';
5
+
6
+ const $ = (selector, parent = document) => parent.querySelector(selector);
7
+ const $$ = (selector, parent = document) => [...parent.querySelectorAll(selector)];
8
+ const storage = { get(key) { try { return localStorage.getItem(key); } catch { return null; } }, set(key,value) { try { localStorage.setItem(key,value); } catch {} } };
9
+ const searchCache = new Map();
10
+ let cleanup = () => {};
11
+
12
+ function initializePage() {
13
+ cleanup();
14
+ const controller = new AbortController(), cleanups = [];
15
+ const { signal } = controller;
16
+ cleanup = () => { controller.abort(); cleanups.forEach(dispose => dispose()); };
17
+ const on = (target, event, listener) => target?.addEventListener(event, listener, { signal });
18
+ const config = JSON.parse($('#miradocs-data').textContent), { ui } = config;
19
+ on(document,'miradocs:before-navigate',cleanup);
20
+ initializeClientComponents(signal,ui);
21
+ initializeLists(signal,ui);
22
+ const visit = url => {
23
+ if (config.clientNavigation !== false) document.dispatchEvent(new CustomEvent('miradocs:visit', { detail: { url } }));
24
+ else location.assign(url);
25
+ };
26
+
27
+ const theme = $('.theme-toggle'), systemTheme = matchMedia('(prefers-color-scheme: dark)');
28
+ function renderTheme() {
29
+ const preference = document.documentElement.dataset.theme;
30
+ const mode = ['light','dark'].includes(preference) ? preference : systemTheme.matches ? 'dark' : 'light';
31
+ theme.dataset.selected = mode;
32
+ const name = ui.themeSwitch.replace('{current}',ui[mode]).replace('{next}',ui[mode === 'dark' ? 'light' : 'dark']);
33
+ theme.setAttribute('aria-label',name); theme.title = name;
34
+ }
35
+ on(theme,'click', () => {
36
+ const mode = theme.dataset.selected === 'dark' ? 'light' : 'dark';
37
+ document.documentElement.dataset.theme = mode; storage.set('miradocs-theme',mode); renderTheme();
38
+ });
39
+ on(systemTheme,'change',renderTheme);
40
+ on(window,'storage',event=>{if(event.key === 'miradocs-theme'){document.documentElement.dataset.theme=event.newValue || 'system';renderTheme();}});
41
+ renderTheme();
42
+ on($('.language-select'),'change',event=>visit(event.target.value));
43
+
44
+ const menu = $('.menu-toggle'), sidebar = $('.sidebar');
45
+ function closeMenu() { sidebar?.classList.remove('open'); menu?.setAttribute('aria-expanded','false'); $('#main').inert = false; document.body.classList.remove('menu-open'); }
46
+ on(menu,'click', () => {
47
+ if (!sidebar) return;
48
+ const open = !sidebar.classList.contains('open');
49
+ sidebar.classList.toggle('open',open); menu.setAttribute('aria-expanded',String(open)); $('#main').inert = open; document.body.classList.toggle('menu-open',open);
50
+ if(open) $('a,summary',sidebar)?.focus();
51
+ });
52
+ on(document,'keydown',event=>{if(event.key === 'Escape' && sidebar?.classList.contains('open')){closeMenu();menu.focus();}});
53
+ on(matchMedia('(min-width: 761px)'),'change',closeMenu);
54
+
55
+ $$('.copy-code').forEach(button => on(button,'click', async () => {
56
+ try { await navigator.clipboard.writeText(button.closest('.code-block').querySelector('pre code').textContent); button.textContent = ui.copied; }
57
+ catch { button.textContent = ui.copyError; }
58
+ button.setAttribute('aria-label',button.textContent);
59
+ const timer = setTimeout(() => { if (!signal.aborted) { button.textContent = ui.copy;button.setAttribute('aria-label',ui.copy); } },1800);
60
+ cleanups.push(()=>clearTimeout(timer));
61
+ }));
62
+ $$('.tabs').forEach(tabs => {
63
+ const list = [...tabs.children].find(e => e.classList.contains('tab-list'));
64
+ const buttons = $$(':scope > button',list), panels = [...tabs.children].filter(e => e.classList.contains('tab-panel'));
65
+ const activate = index => {
66
+ buttons.forEach((button,i) => {button.setAttribute('aria-selected',String(i===index));button.tabIndex=i===index?0:-1;});
67
+ panels.forEach((panel,i)=>panel.hidden=i!==index);
68
+ };
69
+ buttons.forEach((button,i) => {
70
+ on(button,'click',()=>activate(i));
71
+ on(button,'keydown',event=>{
72
+ let index;
73
+ if(event.key==='ArrowRight')index=(i+1)%buttons.length;
74
+ if(event.key==='ArrowLeft')index=(i-1+buttons.length)%buttons.length;
75
+ if(event.key==='Home')index=0;
76
+ if(event.key==='End')index=buttons.length-1;
77
+ if(index!==undefined){event.preventDefault();activate(index);buttons[index].focus();}
78
+ });
79
+ });
80
+ activate(0);
81
+ });
82
+
83
+ initializeOutline(signal);
84
+
85
+ const trigger=$('.search-trigger'),dialog=$('.search-dialog');
86
+ if(trigger && dialog) {
87
+ const input=$('input',dialog),results=$('.search-results',dialog),status=$('.search-status',dialog),clear=$('.search-clear',dialog),resultsLabel=$('.search-results-label',dialog);
88
+ const cached=searchCache.get(config.searchUrl);
89
+ let documents=cached?.documents || [],fuse=cached?.fuse,selected=0,opener,loading;
90
+ $('kbd',trigger).textContent=/Mac|iPhone|iPad/.test(navigator.userAgentData?.platform || navigator.platform)?'⌘ K':'Ctrl K';
91
+ input.setAttribute('role','combobox');input.setAttribute('aria-expanded','false');input.setAttribute('aria-autocomplete','list');results.setAttribute('role','listbox');
92
+ const message=text=>{results.replaceChildren();const div=document.createElement('div');div.className='search-empty';div.textContent=text;results.append(div);status.textContent=text;input.removeAttribute('aria-activedescendant');};
93
+ function select(index,scroll=true) {
94
+ const links=$$('.search-result',results);if(!links.length)return;
95
+ selected=(index+links.length)%links.length;
96
+ links.forEach((link,i)=>{link.classList.toggle('selected',i===selected);link.setAttribute('aria-selected',String(i===selected));});
97
+ input.setAttribute('aria-activedescendant',links[selected].id);if(scroll)links[selected].scrollIntoView({block:'nearest'});
98
+ }
99
+ on(results,'pointermove',event=>{const link=event.target.closest('.search-result');if(link)select(Number(link.dataset.index),false);});
100
+ function render() {
101
+ if(!fuse)return;
102
+ const query=input.value.trim();clear.hidden=!input.value;resultsLabel.textContent=query?ui.searchResultsLabel:ui.searchSuggested;
103
+ const found=query?fuse.search(query,{limit:config.search.limit || 10}).map(result=>result.item):documents.slice(0,6);
104
+ if(!found.length){message(ui.searchEmpty);return;}
105
+ results.replaceChildren();
106
+ found.forEach((page,index)=>{
107
+ const link=document.createElement('a');link.className='search-result';link.href=page.url;link.id='search-result-'+index;link.dataset.index=String(index);link.setAttribute('role','option');
108
+ const title=document.createElement('strong'),match=query && page.title.toLocaleLowerCase().indexOf(query.toLocaleLowerCase());
109
+ if(query && match>=0){const mark=document.createElement('mark');mark.textContent=page.title.slice(match,match+query.length);title.append(page.title.slice(0,match),mark,page.title.slice(match+query.length));}else title.textContent=page.title;
110
+ const text=document.createElement('small');text.textContent=page.description || page.text.slice(0,140);
111
+ const body=document.createElement('span');body.className='search-result-body';
112
+ const context=document.createElement('span');context.className='search-result-context';context.textContent=page.section || '';body.append(context,title,text);
113
+ const returnIcon=document.createElement('span');returnIcon.className='search-result-return';returnIcon.append($('#search-return-icon',dialog).content.cloneNode(true));
114
+ link.append($('#search-document-icon',dialog).content.cloneNode(true),body,returnIcon);results.append(link);
115
+ });
116
+ status.textContent=ui.searchResults.replace('{count}',String(found.length));select(Math.min(selected,found.length-1));
117
+ }
118
+ async function load() {
119
+ if(fuse)return;if(loading)return loading;
120
+ loading=(async()=>{
121
+ message(ui.searchLoading);
122
+ const [module,response]=await Promise.all([import('./fuse.js'),fetch(config.searchUrl,{signal})]);
123
+ if(!response.ok)throw Error('Search index unavailable');documents=await response.json();
124
+ fuse=new module.default(documents,{keys:[{name:'title',weight:.55},{name:'description',weight:.3},{name:'text',weight:.15}],threshold:config.search.threshold ?? .35,ignoreLocation:true,minMatchCharLength:2});
125
+ searchCache.set(config.searchUrl,{documents,fuse});
126
+ })();
127
+ try{await loading;}finally{loading=null;}
128
+ }
129
+ async function open() {
130
+ if(dialog.open)return;
131
+ opener=document.activeElement;dialog.showModal();input.setAttribute('aria-expanded','true');input.focus();
132
+ try{await load();if(!signal.aborted)render();}catch{if(!signal.aborted)message(ui.searchError);}
133
+ }
134
+ on(trigger,'click',open);
135
+ on($('.search-close',dialog),'click',()=>dialog.close());
136
+ on(clear,'click',()=>{input.value='';selected=0;render();input.focus();});
137
+ on(dialog,'close',()=>{input.setAttribute('aria-expanded','false');opener?.focus();});
138
+ on(dialog,'click',event=>{if(event.target===dialog)dialog.close();});
139
+ on(document,'keydown',event=>{if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='k'){event.preventDefault();if(dialog.open)dialog.close();else open();}});
140
+ on(input,'input',()=>{selected=0;render();});
141
+ on(input,'keydown',event=>{
142
+ if(event.key==='Escape'){event.preventDefault();dialog.close();return;}
143
+ if(event.key==='ArrowDown'||event.key==='ArrowUp'){event.preventDefault();select(selected+(event.key==='ArrowDown'?1:-1));}
144
+ if(event.key==='Enter'){const link=$$('.search-result',results)[selected];if(link)visit(link.href);}
145
+ });
146
+ }
147
+ }
148
+
149
+ initializePage();
150
+ if(JSON.parse($('#miradocs-data').textContent).clientNavigation !== false)enableNavigation(initializePage);
@@ -0,0 +1,43 @@
1
+ export function initializeClientComponents(signal, ui, loadModule = source => import(source)) {
2
+ const disposers = new Set(), scheduled = new Set();
3
+ const hosts = [...document.querySelectorAll('[data-component-src]')];
4
+ const started = new WeakSet();
5
+ let observer;
6
+ async function mount(host) {
7
+ if (signal.aborted || started.has(host) || !host.isConnected) return;
8
+ started.add(host);host.dataset.componentStatus='loading';
9
+ const fallback = host.innerHTML;
10
+ try {
11
+ const module = await loadModule(host.dataset.componentSrc);
12
+ if(signal.aborted || !host.isConnected)return;
13
+ host.replaceChildren();
14
+ const dispose = await module.mount(host,JSON.parse(host.dataset.componentProps || '{}'),{signal});
15
+ if(typeof dispose === 'function') {
16
+ if(signal.aborted) await dispose();else disposers.add(dispose);
17
+ }
18
+ if(!signal.aborted)host.dataset.componentStatus='ready';
19
+ }catch(error){
20
+ if(signal.aborted || !host.isConnected)return;
21
+ host.innerHTML=fallback;host.dataset.componentStatus='error';
22
+ const message=document.createElement('p');message.className='client-component-error';message.textContent=ui.componentError;host.append(message);
23
+ console.error(`Could not mount ${host.dataset.component}`,error);
24
+ }
25
+ }
26
+ if('IntersectionObserver' in window)observer=new IntersectionObserver(entries=>{
27
+ for(const entry of entries)if(entry.isIntersecting){observer.unobserve(entry.target);mount(entry.target);}
28
+ },{rootMargin:'200px'});
29
+ for(const host of hosts) {
30
+ const mode=host.dataset.componentLoad;
31
+ if(mode==='eager')mount(host);
32
+ else if(mode==='idle') {
33
+ const idle='requestIdleCallback' in window;
34
+ const handle=idle?requestIdleCallback(()=>mount(host),{timeout:1500}):setTimeout(()=>mount(host),50);
35
+ scheduled.add(()=>idle?cancelIdleCallback(handle):clearTimeout(handle));
36
+ }else if(observer)observer.observe(host);else mount(host);
37
+ }
38
+ signal.addEventListener('abort',()=>{
39
+ observer?.disconnect();for(const cancel of scheduled)cancel();
40
+ for(const dispose of disposers)try{Promise.resolve(dispose()).catch(console.error);}catch(error){console.error(error);}
41
+ scheduled.clear();disposers.clear();
42
+ },{once:true});
43
+ }
@@ -0,0 +1,55 @@
1
+ const normalize = value => value.normalize('NFKD').replace(/\p{M}/gu, '').toLocaleLowerCase().replace(/\s+/g, ' ').trim();
2
+
3
+ export function initializeLists(signal, ui) {
4
+ for (const list of document.querySelectorAll('.content-list')) {
5
+ const content = list.querySelector(':scope > .list-content');
6
+ const items = content.firstElementChild;
7
+ const elements = items.tagName === 'TABLE' ? items.tBodies[0]?.rows || [] : items.children;
8
+ const rows = [...elements].map(element => ({ element, text: normalize(element.textContent) }));
9
+ const alignments = list.dataset.listAlignments && JSON.parse(list.dataset.listAlignments);
10
+ const alignColumns = () => {
11
+ if (!alignments) return;
12
+ const columns = getComputedStyle(items).gridTemplateColumns.split(/\s+/).filter(track => Number.parseFloat(track) > 0).length || Number(list.dataset.listColumns);
13
+ let index = 0;
14
+ for (const { element } of rows) {
15
+ if (element.hidden) continue;
16
+ const alignment = Array.isArray(alignments) ? alignments[index++ % columns] ?? 'start' : alignments;
17
+ if (element.dataset.listAlign !== alignment) element.dataset.listAlign = alignment;
18
+ }
19
+ };
20
+ alignColumns();
21
+ if (alignments && typeof ResizeObserver === 'function') {
22
+ const observer = new ResizeObserver(alignColumns);
23
+ observer.observe(items);
24
+ signal.addEventListener('abort', () => observer.disconnect(), { once: true });
25
+ }
26
+ if (!list.hasAttribute('data-list-search')) continue;
27
+ const header = list.querySelector(':scope > .list-header');
28
+ const filter = header.querySelector(':scope > .list-filter');
29
+ const input = filter.querySelector('input');
30
+ const clear = filter.querySelector('.list-clear');
31
+ const empty = list.querySelector(':scope > .list-empty');
32
+ const status = list.querySelector(':scope > .list-status');
33
+ const update = (announce = true) => {
34
+ const words = normalize(input.value).split(' ').filter(Boolean);
35
+ let visible = 0;
36
+ for (const row of rows) {
37
+ row.element.hidden = !words.every(word => row.text.includes(word));
38
+ if (!row.element.hidden) visible++;
39
+ }
40
+ clear.hidden = !input.value;
41
+ alignColumns();
42
+ empty.hidden = visible !== 0;
43
+ if (announce) status.textContent = visible ? ui.listResults.replace('{visible}', String(visible)).replace('{total}', String(rows.length)) : empty.textContent;
44
+ };
45
+ const reset = () => { input.value = ''; update(); input.focus(); };
46
+ input.addEventListener('input', () => update(), { signal });
47
+ input.addEventListener('keydown', event => {
48
+ if (event.key === 'Escape' && input.value) { event.preventDefault(); event.stopPropagation(); reset(); }
49
+ }, { signal });
50
+ clear.addEventListener('click', reset, { signal });
51
+ update(false);
52
+ filter.hidden = false;
53
+ header.hidden = false;
54
+ }
55
+ }
@@ -0,0 +1,127 @@
1
+ // Static HTML remains the source of truth; this layer enhances same-site links.
2
+ export function enableNavigation(initializePage) {
3
+ let controller, navigating = false, displayed = new URL(location.href);
4
+ const cache = new Map();
5
+ history.scrollRestoration = 'manual';
6
+
7
+ function remember() {
8
+ if (navigating) return;
9
+ history.replaceState({ ...history.state, miradocsScroll: [scrollX, scrollY] }, '', location.href);
10
+ }
11
+ let scrollFrame;
12
+ addEventListener('scroll', () => {
13
+ if (!scrollFrame) scrollFrame = requestAnimationFrame(() => { scrollFrame = null; remember(); });
14
+ }, { passive: true });
15
+ remember();
16
+
17
+ function position(url, saved) {
18
+ const target = url.hash && document.getElementById(decodeURIComponent(url.hash.slice(1)));
19
+ const previous = document.documentElement.style.scrollBehavior;
20
+ document.documentElement.style.scrollBehavior = 'auto';
21
+ if (saved) scrollTo(...saved);
22
+ else if (target) target.scrollIntoView();
23
+ else scrollTo(0, 0);
24
+ document.documentElement.style.scrollBehavior = previous;
25
+ }
26
+
27
+ async function navigate(url, { pop = false, saved } = {}) {
28
+ controller?.abort(); controller = new AbortController();
29
+ if (!pop) remember();
30
+ const request = controller;
31
+ navigating = true; document.documentElement.dataset.navigating = 'true';
32
+ document.querySelector('main')?.setAttribute('aria-busy', 'true');
33
+ try {
34
+ let html = cache.get(url.pathname + url.search);
35
+ let finalURL = url;
36
+ if (!html) {
37
+ const response = await fetch(url, { signal: request.signal, headers: { Accept: 'text/html' } });
38
+ if (!response.ok || !response.headers.get('content-type')?.includes('text/html')) throw Error('Navigation unavailable');
39
+ html = await response.text();
40
+ finalURL = new URL(response.url); finalURL.hash = url.hash;
41
+ cache.set(finalURL.pathname + finalURL.search, html);
42
+ if (cache.size > 20) cache.delete(cache.keys().next().value);
43
+ }
44
+ if (request.signal.aborted) return;
45
+ const page = new DOMParser().parseFromString(html, 'text/html');
46
+ if (!page.querySelector('#miradocs-data') || !page.querySelector('.layout')) throw Error('Not a documentation page');
47
+ const styleSelector='link[data-miradocs-component-style]';
48
+ const nextStyles=[...page.head.querySelectorAll(styleSelector)],styleURLs=new Set(nextStyles.map(link=>new URL(link.getAttribute('href'),url).href));
49
+ await Promise.all(nextStyles.map(link=>{
50
+ const href=new URL(link.getAttribute('href'),url).href;
51
+ if([...document.head.querySelectorAll(styleSelector)].some(existing=>existing.href===href))return;
52
+ return new Promise((resolve,reject)=>{
53
+ const style=document.importNode(link,true);style.href=href;
54
+ const cancel=()=>{style.remove();reject(Error('Navigation cancelled'));};
55
+ request.signal.addEventListener('abort',cancel,{once:true});
56
+ style.onload=()=>{request.signal.removeEventListener('abort',cancel);resolve();};
57
+ style.onerror=()=>{request.signal.removeEventListener('abort',cancel);style.remove();reject(Error('Component stylesheet unavailable'));};
58
+ document.head.insertBefore(style,document.head.querySelector('link[data-miradocs-theme]'));
59
+ });
60
+ }));
61
+ if(request.signal.aborted)return;
62
+ const sidebarScroll = document.querySelector('.sidebar-inner')?.scrollTop || 0;
63
+ document.querySelector('dialog[open]')?.close();
64
+ document.dispatchEvent(new CustomEvent('miradocs:before-navigate'));
65
+ document.body.classList.remove('menu-open');
66
+ for (const selector of ['.skip-link', '.topbar', '.layout', '.search-dialog', '#miradocs-data']) {
67
+ const current = document.querySelector(selector), next = page.querySelector(selector);
68
+ if (current && next) current.replaceWith(document.importNode(next, true));
69
+ else if (current) current.remove();
70
+ else if (next) document.body.append(document.importNode(next, true));
71
+ }
72
+ document.title = page.title;
73
+ document.documentElement.lang = page.documentElement.lang;
74
+ document.documentElement.dir = page.documentElement.dir;
75
+ const metadata = 'meta[name="description"], meta[property^="og:"], link[rel="canonical"], link[rel="alternate"]';
76
+ document.head.querySelectorAll(metadata).forEach(node => node.remove());
77
+ page.head.querySelectorAll(metadata).forEach(node => document.head.append(document.importNode(node, true)));
78
+ document.head.querySelectorAll(styleSelector).forEach(link=>{if(!styleURLs.has(link.href))link.remove();});
79
+ if (!pop) history.pushState({ miradocsScroll: [0, 0] }, '', finalURL);
80
+ displayed = finalURL;
81
+ initializePage();
82
+ const scroller = document.querySelector('.sidebar-inner');
83
+ if (scroller) {
84
+ scroller.scrollTop = sidebarScroll;
85
+ const active = scroller.querySelector('[aria-current="page"]');
86
+ if (active && scroller.clientHeight) {
87
+ const item = active.getBoundingClientRect(), pane = scroller.getBoundingClientRect();
88
+ if (item.bottom > pane.bottom) scroller.scrollTop += item.bottom - pane.bottom + 16;
89
+ else if (item.top < pane.top) scroller.scrollTop -= pane.top - item.top + 16;
90
+ }
91
+ }
92
+ document.querySelector('main')?.focus({ preventScroll: true });
93
+ position(finalURL, saved);
94
+ if (!matchMedia('(prefers-reduced-motion: reduce)').matches) document.querySelector('main')?.animate([{ opacity: .4 }, { opacity: 1 }], { duration: 140, easing: 'ease-out' });
95
+ document.dispatchEvent(new CustomEvent('miradocs:navigate', { detail: { url: finalURL.href } }));
96
+ } catch (error) {
97
+ if (request.signal.aborted) return;
98
+ // Preserve normal browser navigation if the host cannot supply HTML.
99
+ if (pop) location.reload(); else location.assign(url);
100
+ } finally {
101
+ if (controller === request) {
102
+ navigating = false; delete document.documentElement.dataset.navigating;
103
+ document.querySelector('main')?.removeAttribute('aria-busy');
104
+ }
105
+ }
106
+ }
107
+
108
+ document.addEventListener('click', event => {
109
+ const link = event.target.closest('a[href]');
110
+ if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || link.hasAttribute('download') || link.hasAttribute('data-no-router') || (link.target && link.target !== '_self')) return;
111
+ const url = new URL(link.href), base = document.body.dataset.base;
112
+ if (url.origin !== location.origin || !url.pathname.startsWith(base) || /\.[a-z0-9]+$/i.test(url.pathname) && !url.pathname.endsWith('.html')) return;
113
+ if (url.pathname === location.pathname && url.search === location.search) {
114
+ if (url.hash) return;
115
+ event.preventDefault();
116
+ if(url.href !== location.href) { remember(); history.pushState({miradocsScroll:[0,0]},'',url); displayed=url; }
117
+ position(url); return;
118
+ }
119
+ event.preventDefault(); navigate(url);
120
+ });
121
+ addEventListener('popstate', event => {
122
+ const url = new URL(location.href);
123
+ if (url.pathname === displayed.pathname && url.search === displayed.search) { displayed = url; position(url, event.state?.miradocsScroll); return; }
124
+ navigate(url, { pop: true, saved: event.state?.miradocsScroll });
125
+ });
126
+ document.addEventListener('miradocs:visit', event => navigate(new URL(event.detail.url, location.href)));
127
+ }
@@ -0,0 +1,57 @@
1
+ export function initializeOutline(signal) {
2
+ const links = [...document.querySelectorAll('.toc a, .mobile-toc a')];
3
+ const headings = [...document.querySelectorAll('.article h2[id], .article h3[id], .article h4[id], .article h5[id], .article h6[id]')];
4
+ if (!links.length || !headings.length) return;
5
+ const idFromHash = hash => { try { return decodeURIComponent(hash.slice(1)); } catch { return ''; } };
6
+ let selected, scrollingToAnchor = false, frame, settleTimer;
7
+ const on = (target, event, listener, options = {}) => target.addEventListener(event, listener, {...options, signal});
8
+ function activate(id) {
9
+ for (const link of links) {
10
+ const active = idFromHash(link.hash) === id;
11
+ link.classList.toggle('active', active);
12
+ if (active) link.setAttribute('aria-current', 'location'); else link.removeAttribute('aria-current');
13
+ }
14
+ }
15
+ function settle() {
16
+ clearTimeout(settleTimer);
17
+ settleTimer = setTimeout(() => { scrollingToAnchor = false; }, 180);
18
+ }
19
+ function chooseAnchor(hash) {
20
+ const id = idFromHash(hash);
21
+ if (!headings.some(heading => heading.id === id)) return false;
22
+ selected = id; scrollingToAnchor = true; settle(); activate(id);
23
+ return true;
24
+ }
25
+ function update() {
26
+ frame = null;
27
+ if (selected) { activate(selected); return; }
28
+ const threshold = (document.querySelector('.topbar')?.getBoundingClientRect().bottom || 0) + 28;
29
+ let current = headings[0];
30
+ for (const heading of headings) {
31
+ if (heading.getBoundingClientRect().top > threshold) break;
32
+ current = heading;
33
+ }
34
+ const page = document.documentElement;
35
+ if (page.scrollHeight > window.innerHeight && window.scrollY + window.innerHeight >= page.scrollHeight - 2) current = headings.at(-1);
36
+ activate(current.id);
37
+ }
38
+ function schedule() { if (frame == null) frame = requestAnimationFrame(update); }
39
+ function resumeTracking() { scrollingToAnchor = false; clearTimeout(settleTimer); }
40
+ for (const link of links) on(link, 'click', event => {
41
+ if (event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey) chooseAnchor(link.hash);
42
+ });
43
+ on(window, 'hashchange', () => { if (!chooseAnchor(location.hash)) { selected = null; resumeTracking(); schedule(); } });
44
+ on(window, 'scroll', () => {
45
+ if (selected && scrollingToAnchor) { settle(); return; }
46
+ selected = null; schedule();
47
+ }, {passive: true});
48
+ on(window, 'wheel', resumeTracking, {passive: true});
49
+ on(window, 'touchmove', resumeTracking, {passive: true});
50
+ on(window, 'keydown', event => {
51
+ if (event.target.closest('input,textarea,select,[contenteditable]')) return;
52
+ if (['ArrowDown', 'ArrowUp', 'PageDown', 'PageUp', 'Home', 'End', ' '].includes(event.key)) resumeTracking();
53
+ });
54
+ on(window, 'resize', schedule);
55
+ signal.addEventListener('abort', () => { cancelAnimationFrame(frame); clearTimeout(settleTimer); }, {once: true});
56
+ if (!chooseAnchor(location.hash)) update();
57
+ }