aboutsummaryrefslogtreecommitdiff
path: root/router.js
blob: 2aac572066985b609bdcef9cd91be58cd785c61d (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
(function () {

  this.addEventListener('hashchange', router);
  this.addEventListener('load', router);

  function router() {
    const url = location.hash.slice(2) || 'presentation';
    const contentElement = document.getElementById('content');
    const htmlElement = document.querySelector('html');
    addClass(htmlElement, 'waitCursor');
    fetchFile('Pages/' + url + '.md', function(contentMd) {
      removeClass(htmlElement, 'waitCursor');
      contentElement.innerHTML = markdown.toHTML(contentMd);
    }, function() {
      const notFoundPage = '<h1>Page non trouvée</h1><a href="#">Retour à l\'accueil</a>';
      contentElement.innerHTML = notFoundPage;
    });
  }

  function addClass(element, myClass) {
    element.className = element.className + ' ' + myClass;
  }

  function removeClass(element, myClass) {
    element.className = element.className.replace(new RegExp('(?:^|\\s)' + myClass + '(?!\\S)') , '');
  }

  function fetchFile(url, successHandler, errorHandler) {
    const xhr = typeof XMLHttpRequest != 'undefined'
      ? new XMLHttpRequest()
      : new ActiveXObject('Microsoft.XMLHTTP');
    xhr.open('get', url, true);
    xhr.responseType = 'text';
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        const status = xhr.status;
        if (status === 200 || status === 0) {
          const data = xhr.responseText;
          successHandler && successHandler(data);
        } else {
          errorHandler && errorHandler(status);
        }
      }
    };
    try {
      xhr.send();
    } catch(err) {
      errorHandler && errorHandler(err);
    }
  };

})();