-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnavigator.es6.js
95 lines (85 loc) · 2.93 KB
/
navigator.es6.js
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
/**
* Navigator - A JS Single-Page Library
* @author Felix Rewer <[email protected]>
* @copyright Felix Rewer 2018
* @version 2.0
* @license GPL-v3 LICENSE.md
*/
'use strict';
/**
* Navigator Class
* @class
*/
export class navigator {
/**
* @desc Constructor
* @constructs navigator
* @param {Object} confObj - Configuration Object
* @param {string} confObj.root - Root folder
* @param {string} confObj.links - Selector for NavLinks
* @param {string} confObj.output - Selector for the output
* @param {string} confObj.standard - Standard NavURL
* @param {string} [confObj.extension=html] - File extension for navigations (e.g. php)
*/
constructor(confObj) {
this.root = confObj.root;
this.links = confObj.links;
this.extension = confObj.extension || 'html';
document.addEventListener('DOMContentLoaded', () => {
this.output = document.querySelector(confObj.output);
this.navLinks(document.querySelectorAll(this.links));
window.location.pathname === '/' ?
this.navigate(confObj.standard) :
this.navigate(window.location.pathname, window.location.search);
});
window.addEventListener('popstate', () => {
this.navigate(window.history.state.page);
});
}
/**
* @func
* @desc NavLinks initialization
* @param {NodeListOf<HTMLElemen>} navLinksList - List with all NavLinks
*/
navLinks(navLinksList) {
Array.from(navLinksList).forEach(el => {
el.addEventListener('click', e => {
e.preventDefault();
var navURL = el.getAttribute('href');
var state = {
page: navURL,
host: window.location.host,
port: window.location.port
};
window.history.pushState(state, navURL, navURL);
this.navigate(navURL);
});
});
};
/**
* @func
* @desc Navigate by URL
* @param {string} navURL - URL to Navigate (e.g. /start)
* @param {string} navURLSearchParams - SearchParams to attach to URL (e.g. ?id=1)
* @async
*/
navigate(navURL, navURLSearchParams = false) {
var navArray = navURL.split('?');
navURL = navArray[0];
navURLSearchParams =
navArray[1] === undefined ? navURLSearchParams : '?' + navArray[1];
fetch(
navURLSearchParams ?
`${this.root}${navURL}.${this.extension}${navURLSearchParams}` :
`${this.root}${navURL}.${this.extension}`
)
.then(response => response.text())
.then(text => {
this.output.innerHTML = text;
this.navLinks(this.output.querySelectorAll(this.links));
})
.catch(error => {
throw new Error(error);
});
};
}