summaryrefslogtreecommitdiff
path: root/src/js/sidenotes.js
blob: f31bef7c0e8c36cf889f684e19d839a40890e67d (plain)
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
'use strict';

function getPos(element) {
  /* Element.getBoundingClientRect()
   * Return box of the element relatively to viewport.
   */
  const rect = element.getBoundingClientRect();

  /* The properties window.scrollX and window.scrollY
   * return the viewport position relatively to the document
   */
  return {
    x: rect.left + window.scrollX,
    y: rect.top + window.scrollY,
  };
}

const getTop = element => element.offsetTop + (element.offsetParent && getTop(element.offsetParent));
let sidenotes = undefined;
const resize = () => {

  for (const sidenote of sidenotes) {
    if (sidenote.offsetWidth < 200 || window.screen.width < 1400) {
      sidenote.innerHTML = '';
      return;
    }

    const articleRef = sidenote.attributes.for.value;
    const article = document.querySelector(`#${articleRef}`);
    console.log(article, articleRef);
    const notes = Array.from(article.querySelectorAll('li'))
      .filter(element => element.id.startsWith('user-content-fn'));
    const newSidenotes = notes.map(sidenoteLi => {
      const div = document.createElement('div');
      const refName = sidenoteLi.querySelector('.data-footnote-backref').attributes.href.value;
      const refSideNode = article.querySelector(refName);

      const sup = document.createElement('sup');
      sup.textContent = refSideNode.textContent + ' ';

      for (const element of sidenoteLi.children) {
        const child = element.cloneNode(true);
        div.append(child);
      }

      div.children[0].prepend(sup);
      div.style.top = `${getPos(refSideNode).y}px`;
      div.classList.add('sidenote');

      return div;
    });

    sidenote.replaceChildren(...newSidenotes);

    if (sidenote.offsetWidth < 100 || window.screen.width < 1400) {
      sidenote.innerHTML = '';
      return;
    }
  }
};

if (sidenotes.length > 0) {
  new ResizeObserver(resize).observe(sidenotes[0])
}

// window.addEventListener('resize', resize);
window.addEventListener('DOMContentLoaded') () => {

};
window.addEventListener('DOMContentLoaded', () => {
  if(document.querySelectorAll('.math-display').length > 0) {
    document.head.innerHTML += '<link href="/s/css/katex.css" rel="stylesheet"/>';
  }
});