aboutsummaryrefslogtreecommitdiff
path: root/public/js/script.js
blob: e90198cf8cc1fcb791a9d92cb6854fc8f7a8af86 (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
'use strict';

/* global document XMLHttpRequest */

document.addEventListener('DOMContentLoaded', () => {
  const httpRequest = new XMLHttpRequest();

  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === 4 && httpRequest.status === 200) {
      const response = httpRequest.responseText;
      const data = JSON.parse(response);
      document.getElementById('tree').appendChild(addDirectory(data));

      Array.from(document.getElementsByTagName('a')).forEach(a => {
        a.onclick = (function (e) {
          e.preventDefault();
          e.stopPropagation();
          const setMd = new XMLHttpRequest();
          setMd.onreadystatechange = () => {
            if (setMd.readyState === 4 && setMd.status === 200) {
              document.getElementById('md').innerHTML = setMd.responseText;
            }
          };
          setMd.open('GET', a.href);
          setMd.send();
        });
      });
      Array.from(document.getElementsByClassName('directory')).forEach(dir => {
        dir.querySelectorAll('ul').forEach(ul => {
          ul.style.display = 'none';
        });
        dir.onclick = (e => {
          e.stopPropagation();

          dir.querySelectorAll('ul').forEach(ul => {
            ul.style.display = ul.style.display === 'none' ? 'block' : 'none';
          });
        });
      });
    }
  };
  httpRequest.open('GET', '/data');
  httpRequest.send();
});

function addDirectory(data) {
  const ul = document.createElement('ul');
  data.children.forEach(item => {
    const li = document.createElement('li');
    const text = document.createTextNode(item.name);

    if (item.type === 'file') {
      const a = document.createElement('a');
      a.appendChild(text);
      a.href = item.path;
      li.appendChild(a);
      li.classList.add('file');
    } else {
      li.appendChild(text);
      li.tabIndex = 0;
      li.appendChild(addDirectory(item));
      li.classList.add('directory');
    }
    ul.appendChild(li);
  });
  return ul;
}