diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
(() => {
  const disclosure = document.querySelector('.nav-disclosure');
  const sidebar = document.querySelector('.layout > nav');
  const narrow = matchMedia('(max-width:760px)');
  const wide = matchMedia('(min-width:1100px)');
  const menu = document.querySelector('.mobile-menu');
  const closeMenu = () => { menu.open = false; };
  document.addEventListener('click', event => {
    if (!menu.contains(event.target) || event.target.closest('a[href]')) closeMenu();
  });
  document.addEventListener('keydown', event => {
    if (event.key !== 'Escape' || !menu.open) return;
    closeMenu();
    menu.querySelector('summary').focus({ preventScroll: true });
  });
  narrow.addEventListener('change', closeMenu);
  document.addEventListener('diplodocus:page-change', closeMenu);
  for (const dropdown of document.querySelectorAll('.repository-menu, .api-menu')) {
    const closeDropdown = () => { dropdown.open = false; };
    document.addEventListener('click', event => {
      if (!dropdown.contains(event.target) || event.target.closest('a[href]')) closeDropdown();
    });
    document.addEventListener('keydown', event => {
      if (event.key !== 'Escape' || !dropdown.open) return;
      event.preventDefault();
      closeDropdown();
      dropdown.querySelector('summary').focus({ preventScroll: true });
    });
    narrow.addEventListener('change', closeDropdown);
    document.addEventListener('diplodocus:page-change', closeDropdown);
  }
  const initializeToc = () => {
    const toc = document.querySelector('.toc-disclosure');
    if (!toc) return;
    toc.open = wide.matches;
    toc.dataset.ready = '';
  };
  disclosure.open = !narrow.matches;
  disclosure.dataset.ready = '';
  const drawer = document.createElement('dialog');
  drawer.className = 'documentation-drawer';
  drawer.setAttribute('aria-label', 'Documentation menu');
  drawer.innerHTML = '<div class="drawer-heading"><strong>Menu</strong><button type="button" aria-label="Close menu" autofocus>×</button></div>';
  sidebar.append(drawer);
  const drawerToggle = disclosure.querySelector(':scope > summary');
  drawerToggle.setAttribute('aria-haspopup', 'dialog');
  const closeDrawer = () => {
    if (drawer.open) drawer.close();
    if (narrow.matches) disclosure.open = false;
  };
  const placeNavigation = () => {
    closeDrawer();
    const contextual = document.querySelector('.contextual-nav');
    (narrow.matches ? drawer : disclosure).append(contextual);
    disclosure.open = !narrow.matches;
  };
  placeNavigation();
  drawerToggle.addEventListener('click', event => {
    if (!narrow.matches) return;
    event.preventDefault();
    closeMenu();
    disclosure.open = true;
    drawer.showModal();
  });
  drawer.querySelector('button').addEventListener('click', closeDrawer);
  drawer.addEventListener('close', () => {
    if (narrow.matches && !drawer.open) disclosure.open = false;
  });
  drawer.addEventListener('click', event => {
    const bounds = drawer.getBoundingClientRect();
    if (event.target.closest('a[href]') || (event.target === drawer
        && (event.clientX < bounds.left || event.clientX > bounds.right
          || event.clientY < bounds.top || event.clientY > bounds.bottom))) closeDrawer();
  });
  narrow.addEventListener('change', placeNavigation);
  wide.addEventListener('change', initializeToc);
  document.addEventListener('diplodocus:page-change', initializeToc);
  initializeToc();
  document.addEventListener('click', event => {
    const toc = document.querySelector('.toc-disclosure');
    if (wide.matches || !toc?.open) return;
    if (!toc.contains(event.target) || event.target.closest('a[href]')) toc.open = false;
  });
  document.addEventListener('keydown', event => {
    const toc = document.querySelector('.toc-disclosure');
    if (event.key !== 'Escape' || wide.matches || !toc?.open) return;
    event.preventDefault();
    toc.open = false;
    toc.querySelector('summary').focus({ preventScroll: true });
  });
  // Responsive navigation can change the sticky header's height.
  const header = document.querySelector('header');
  const updateHeaderBorder = () => {
    header.toggleAttribute('data-scrolled', scrollY > 0);
    document.body.toggleAttribute('data-controls-stuck', narrow.matches && header.getBoundingClientRect().bottom <= 0);
  };
  addEventListener('scroll', updateHeaderBorder, { passive: true });
  document.addEventListener('diplodocus:page-change', updateHeaderBorder);
  narrow.addEventListener('change', updateHeaderBorder);
  updateHeaderBorder();
  new ResizeObserver(() => {
    document.documentElement.style.setProperty('--header-height', `${header.getBoundingClientRect().height}px`);
    updateHeaderBorder();
  }).observe(header);

  if (!['http:', 'https:'].includes(location.protocol) || !window.fetch || !window.AbortController) return;
  const protocol = document.body.dataset.diplodocusNavigation;
  const shell = document.body.dataset.diplodocusShell;
  if (protocol !== '1' || !shell) return;
  document.documentElement.dataset.diplodocusRouter = 'true';

  const normalizeUrls = (root, base) => {
    for (const element of root.querySelectorAll('[href], [src]')) {
      for (const attribute of ['href', 'src']) {
        if (element.hasAttribute(attribute)) {
          element.setAttribute(attribute, new URL(element.getAttribute(attribute), base).href);
        }
      }
    }
  };
  // Retained elements must keep their destinations when pushState changes the base URL.
  normalizeUrls(document, location.href);
  document.querySelector('.skip-link').setAttribute('href', '#main');
  const home = document.querySelector('.brand').href;
  const documentKey = url => `${url.origin}${url.pathname}${url.search}`;
  const assetUrls = new Set();
  const rememberAssets = root => {
    for (const element of root.querySelectorAll('[src], link[rel="stylesheet"], link[rel="alternate"][type="text/markdown"]')) {
      assetUrls.add(documentKey(new URL(element.getAttribute('src') || element.getAttribute('href'))));
    }
  };
  rememberAssets(document);
  const emit = (name, detail) => document.dispatchEvent(new CustomEvent(`diplodocus:${name}`, { detail }));
  const sidebarStates = new Map();
  const scrollPositions = new Map();
  let serial = 0;
  let sequence = 0;
  let controller;
  let pendingPosition;
  let mountedUrl = new URL(location.href);
  let mountedEntry;
  const newEntry = () => ({ id: `${Date.now()}-${++serial}`, scroll: [0, 0], sidebar: [0, 0] });
  const entry = state => state?.diplodocus;
  const writeEntry = (value, url, push = false) => {
    const state = { ...history.state, diplodocus: value };
    if (push) history.pushState(state, '', url);
    else history.replaceState(state, '', url);
    scrollPositions.set(value.id, value);
    mountedEntry = value;
    mountedUrl = new URL(url);
  };
  const initialEntry = entry(history.state);
  writeEntry(initialEntry || newEntry(), location.href);
  history.scrollRestoration = 'manual';

  const viewportEntry = () => ({
    ...mountedEntry,
    scroll: [scrollX, scrollY],
    sidebar: [(narrow.matches ? drawer : disclosure).scrollTop, sidebar.scrollTop],
  });
  const recordPosition = () => {
    // During traversal the address bar already belongs to an unmounted page.
    if (pendingPosition || location.href !== mountedUrl.href || entry(history.state)?.id !== mountedEntry.id) return;
    writeEntry(viewportEntry(), location.href);
  };
  let scrollTimer;
  const recordScroll = () => {
    // History writes notify the browser process; keep them out of active scrolling.
    if (!pendingPosition && location.href === mountedUrl.href && entry(history.state)?.id === mountedEntry.id) {
      scrollPositions.set(mountedEntry.id, viewportEntry());
    }
    clearTimeout(scrollTimer);
    scrollTimer = setTimeout(recordPosition, 120);
  };
  window.addEventListener('scroll', recordScroll, { passive: true });
  disclosure.addEventListener('scroll', recordScroll, { passive: true });
  drawer.addEventListener('scroll', recordScroll, { passive: true });
  sidebar.addEventListener('scroll', recordScroll, { passive: true });
  window.addEventListener('pagehide', recordPosition);
  window.addEventListener('pageshow', () => { history.scrollRestoration = 'manual'; });

  const sidebarDisclosures = '.item-disclosure, .sidebar-disclosure';
  const disclosureKey = details => details.dataset.sidebarKey ?? details.querySelector('a').href;
  const rememberSidebar = () => {
    const contextual = document.querySelector('.contextual-nav');
    sidebarStates.set(contextual.dataset.section, {
      open: new Map(Array.from(contextual.querySelectorAll(sidebarDisclosures), details => [disclosureKey(details), details.open])),
      scroll: [(narrow.matches ? drawer : disclosure).scrollTop, sidebar.scrollTop],
    });
  };
  const updateSidebar = next => {
    const contextual = document.querySelector('.contextual-nav');
    const replacement = next.querySelector('.contextual-nav');
    const saved = sidebarStates.get(replacement.dataset.section);
    if (saved) {
      for (const details of replacement.querySelectorAll(sidebarDisclosures)) {
        const remembered = saved.open.get(disclosureKey(details));
        if (details.classList.contains('sidebar-disclosure')) {
          if (remembered !== undefined) details.open = remembered || !!details.querySelector('[aria-current="page"]');
        } else {
          details.open ||= remembered || false;
        }
      }
    }
    contextual.replaceWith(replacement);
    (narrow.matches ? drawer : disclosure).scrollTop = saved?.scroll[0] || 0;
    sidebar.scrollTop = saved?.scroll[1] || 0;
    for (const selector of ['.desktop-sections', '.mobile-sections']) {
      const selected = next.querySelector(`${selector} [aria-current]`)?.href;
      for (const link of document.querySelectorAll(`${selector} a`)) {
        if (link.href === selected) link.setAttribute('aria-current', 'true');
        else link.removeAttribute('aria-current');
      }
    }
  };

  const metadata = 'meta[name="description"], meta[property^="og:"], meta[name^="twitter:"], link[rel="canonical"], link[rel="alternate"][type="text/markdown"]';
  const styles = new Map(Array.from(document.querySelectorAll('link[rel="stylesheet"]'), link => [link.href, Promise.resolve()]));
  const loadStyles = next => Promise.all(Array.from(next.querySelectorAll('link[rel="stylesheet"]'), source => {
    if (!styles.has(source.href)) {
      const link = source.cloneNode(true);
      const loaded = new Promise((resolve, reject) => {
        const timeout = setTimeout(() => failed(), 10000);
        const failed = () => {
          clearTimeout(timeout);
          link.remove();
          styles.delete(source.href);
          reject(new Error('Unable to load page styles.'));
        };
        link.addEventListener('load', () => { clearTimeout(timeout); resolve(); }, { once: true });
        link.addEventListener('error', failed, { once: true });
        document.head.append(link);
      });
      styles.set(source.href, loaded);
    }
    return styles.get(source.href);
  }));

  const fragmentTarget = url => {
    let target;
    try { target = document.getElementById(decodeURIComponent(url.hash.slice(1))); } catch { return; }
    if (!target) return;
    if (target.classList.contains('fragment-alias')) {
      const owner = target.parentElement;
      target = owner.querySelector(':scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > h5, :scope > h6') || owner;
    }
    emit('reveal-fragment', { target });
    return target.classList.contains('tabset-heading') ? target.parentElement : target;
  };
  const focus = target => {
    if (!target.hasAttribute('tabindex') && target.tabIndex < 0) target.setAttribute('tabindex', '-1');
    target.focus({ preventScroll: true });
  };
  const positionPage = (url, saved, changedPage, moveFocus = true) => {
    const request = sequence;
    let active = true;
    const target = url.hash ? fragmentTarget(url) : undefined;
    if (narrow.matches) closeDrawer();
    if (moveFocus && (changedPage || target)) focus(target || document.querySelector('#main'));
    const correct = () => {
      if (!active || request !== sequence) return;
      if (saved) {
        window.scrollTo({ left: saved.scroll[0], top: saved.scroll[1], behavior: 'instant' });
        (narrow.matches ? drawer : disclosure).scrollTop = saved.sidebar?.[0] || 0;
        sidebar.scrollTop = saved.sidebar?.[1] || 0;
      } else if (target) {
        target.scrollIntoView({ block: 'start', behavior: 'instant' });
      } else if (changedPage || !url.hash || url.hash.toLowerCase() === '#top') {
        window.scrollTo({ left: 0, top: 0, behavior: 'instant' });
      }
      // A new fragment entry needs a position even if another link wins before layout settles.
      if (!saved) writeEntry(viewportEntry(), location.href);
    };
    correct();
    if (!saved && !target) {
      recordPosition();
      return;
    }
    // Images without intrinsic dimensions can otherwise clamp and erase a saved position.
    const cleanup = [];
    const finish = (restore = true) => {
      if (pendingPosition !== finish) return;
      for (const dispose of cleanup) dispose();
      pendingPosition = undefined;
      if (restore) correct();
      active = false;
      if (request === sequence) recordPosition();
    };
    pendingPosition = finish;
    const main = document.querySelector('#main');
    const observer = new ResizeObserver(correct);
    observer.observe(main);
    cleanup.push(() => observer.disconnect());
    const images = Array.from(main.querySelectorAll('img')).filter(image => !image.complete);
    const loaded = images.map(image => new Promise(resolve => {
      const done = () => { correct(); resolve(); };
      image.addEventListener('load', done, { once: true });
      image.addEventListener('error', done, { once: true });
      cleanup.push(() => {
        image.removeEventListener('load', done);
        image.removeEventListener('error', done);
      });
    }));
    loaded.push(document.fonts.ready);
    Promise.all(loaded).then(() => requestAnimationFrame(() => requestAnimationFrame(() => finish())));
    const timeout = setTimeout(finish, 5000);
    cleanup.push(() => clearTimeout(timeout));
  };
  const cancelPosition = () => {
    const pending = pendingPosition;
    // Superseding navigation keeps the intended position until its entry is left.
    pending?.(false);
  };
  for (const event of ['wheel', 'touchstart', 'pointerdown', 'keydown']) {
    window.addEventListener(event, () => pendingPosition?.(false), { passive: true, capture: true });
  }

  const navigate = async (destination, traversal = false, state) => {
    const request = ++sequence;
    const positioning = !!pendingPosition;
    cancelPosition();
    controller?.abort();
    controller = new AbortController();
    const signal = controller.signal;
    if (!traversal && !positioning) recordPosition();
    const current = () => request === sequence;
    const historyEntry = traversal ? entry(state) : undefined;
    const saved = scrollPositions.get(historyEntry?.id) || historyEntry;
    try {
      if (documentKey(destination) === documentKey(mountedUrl)) {
        if (traversal) writeEntry(saved || newEntry(), destination.href);
        else if (destination.href !== location.href) writeEntry(newEntry(), destination.href, true);
        positionPage(destination, saved, false, !traversal);
        return;
      }
      const response = await fetch(destination, { signal, headers: { Accept: 'text/html' } });
      if (!current()) return;
      if (!response.ok || response.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'text/html'
          || response.headers.get('content-disposition')?.toLowerCase().startsWith('attachment')) {
        throw new Error('Destination is not a documentation page.');
      }
      const finalUrl = new URL(response.url);
      if (finalUrl.origin !== location.origin) throw new Error('Destination is outside this site.');
      finalUrl.hash = finalUrl.hash || destination.hash;
      const html = await response.text();
      if (!current()) return;
      const next = new DOMParser().parseFromString(html, 'text/html');
      normalizeUrls(next, finalUrl);
      if (next.body.dataset.diplodocusNavigation !== protocol || next.body.dataset.diplodocusShell !== shell
          || next.querySelector('.brand')?.href !== home || !next.querySelector('.contextual-nav')
          || !next.querySelector('.page-content main#main') || !next.querySelector('.desktop-sections')
          || !next.querySelector('.mobile-sections') || !next.querySelector('title')) {
        throw new Error('Destination has an incompatible site shell.');
      }
      await loadStyles(next);
      if (!current()) return;
      rememberAssets(next);
      if (!positioning) recordPosition();
      rememberSidebar();
      emit('before-page-change');
      writeEntry(saved || newEntry(), finalUrl.href, !traversal);
      document.title = next.title;
      for (const element of document.head.querySelectorAll(metadata)) element.remove();
      for (const element of next.head.querySelectorAll(metadata)) document.head.append(element);
      if (next.body.dataset.layout) document.body.dataset.layout = next.body.dataset.layout;
      else delete document.body.dataset.layout;
      updateSidebar(next);
      document.querySelector('.page-content').replaceWith(next.querySelector('.page-content'));
      document.querySelector('#search').value = '';
      document.querySelector('#search-results').replaceChildren();
      emit('page-change');
      positionPage(finalUrl, saved, true);
    } catch {
      if (!current() || signal.aborted) return;
      if (traversal) location.reload();
      else location.assign(destination.href);
    }
  };

  document.addEventListener('click', event => {
    if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
    const link = event.target.closest?.('a[href]');
    if (!link || link.hasAttribute('download') || (link.target && link.target.toLowerCase() !== '_self')
        || link.relList.contains('external') || (link.type && link.type !== 'text/html')) return;
    const destination = new URL(link.getAttribute('href'), mountedUrl);
    if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin
        || assetUrls.has(documentKey(destination))) return;
    event.preventDefault();
    void navigate(destination);
  });
  const nativeFragment = () => {
    const destination = new URL(location.href);
    ++sequence;
    cancelPosition();
    controller?.abort();
    writeEntry(newEntry(), destination.href);
    let marker;
    try { marker = document.getElementById(decodeURIComponent(destination.hash.slice(1))); } catch {}
    if (marker?.classList.contains('fragment-alias')) {
      // Native navigation focuses the marker after popstate; restore its owner's focus afterward.
      const request = sequence;
      requestAnimationFrame(() => {
        if (request === sequence && location.href === destination.href) positionPage(destination, undefined, false);
      });
    } else positionPage(destination, undefined, false);
  };
  window.addEventListener('popstate', event => {
    const destination = new URL(location.href);
    // A native location.hash assignment clones the old entry instead of creating router state.
    if (documentKey(destination) === documentKey(mountedUrl) && destination.href !== mountedUrl.href
        && (!entry(event.state) || entry(event.state).id === mountedEntry.id)) nativeFragment();
    else void navigate(destination, true, event.state);
  });
  window.addEventListener('hashchange', () => {
    // Traversal also emits hashchange; only native fragment changes need another update.
    if (location.href === mountedUrl.href || documentKey(new URL(location.href)) !== documentKey(mountedUrl)) return;
    nativeFragment();
  });
  document.addEventListener('DOMContentLoaded', () => {
    if (initialEntry) positionPage(new URL(location.href), initialEntry, false, false);
    else {
      if (location.hash) positionPage(new URL(location.href), undefined, false, false);
      else recordPosition();
    }
  });
})();