-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElroid.js
294 lines (245 loc) · 10.7 KB
/
Elroid.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
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
// Class Elroid: A simple templating engine that compiles a template string with data and binds event listeners based on the provided options.
class Elroid {
constructor(options) {
// Cache the provided element selector, data, and template.
this.el = options.el;
this.data = options.data;
this.template = document.querySelector(options.el).innerHTML;
// Compile the initial template and bind events.
this.compile();
this.bindEvents();
}
// Compile all elements matching the element selector provided in the options.
compile() {
const elements = document.querySelectorAll(this.el);
elements.forEach((element) => {
this.compileElement(element);
});
}
// Compile a single element's template string.
compileElement(element) {
const template = element.innerHTML;
const compiled = this.compileTemplate(template);
element.innerHTML = compiled;
}
// Compile a template string with data.
compileTemplate(template) {
const regex = /\{\{(.*?)\}\}/g; // Use a regex to match all instances of {{...}} in the template.
const compiled = template.replace(regex, (match, p1) => {
return p1.split('.').reduce((acc, key) => acc[key.trim()], this.data) || ''; // Replace each matched string with the corresponding data value.
});
return compiled;
}
// Bind event listeners to elements with the el-click attribute.
bindEvents() {
const elements = document.querySelectorAll('[el-click]');
elements.forEach((element) => {
const methodName = element.getAttribute('el-click');
const method = this.data.methods[methodName];
if (method && typeof method === 'function') {
element.addEventListener('click', () => {
method.bind(this.data)(); // Bind the method to the data object and invoke it on click.
const route = this.data.route || '/';
router.navigateTo(route); // Navigate to the route specified in the data object, or the root route by default.
});
}
});
}
// Update the data object and recompile the template.
update(data) {
Object.assign(this.data, data);
const compiledTemplate = this.compileTemplate(this.template);
const el = document.querySelector(this.el);
el.innerHTML = compiledTemplate;
this.bindEvents();
}
}
// Class Elroid Component: A subclass of Elroid that represents a single component with its own template and data.
class ElComponent {
constructor(options) {
// Cache the provided template, data, route, and element selector.
this.template = options.template;
this.data = options.data;
this.route = options.route;
this.el = document.querySelector(options.el);
// Compile the initial template and bind events.
this.compile();
this.bindEvents();
}
// Compile the component's template string.
compile() {
const compiledTemplate = this.compileTemplate(this.template);
this.el.innerHTML = compiledTemplate;
}
// Compile a template string with data.
compileTemplate(template) {
const regex = /\{\{(.*?)\}\}/g; // Use a regex to match all instances of {{...}} in the template.
const compiled = template.replace(regex, (match, p1) => {
return p1.split('.').reduce((acc, key) => acc[key.trim()], this.data) || ''; // Replace each matched string with the corresponding data value.
});
return compiled;
}
// Bind event listeners to elements with the el-click attribute.
bindEvents() {
const elements = this.el.querySelectorAll('[el-click]');
elements.forEach((element) => {
const methodName = element.getAttribute('el-click');
const method = this.data.methods[methodName];
if (method && typeof method === 'function') {
element.addEventListener('click', () => {
method.bind(this.data)(); // Bind the method to the data object and invoke it on click.
const route = this.data.route || '/';
router.navigateTo(route); // Navigate to the route specified in the data object, or the root route by default.
});
}
});
}
// Update the data object and recompile the template.
update(data) {
Object.assign(this.data, data);
const compiledTemplate = this.compileTemplate(this.template);
this.el.innerHTML = compiledTemplate;
this.bindEvents();
}
}
// ElRouter: A simple client-side router for single-page applications.
class ElRouter {
constructor(options) {
this.routes = options.routes; // An array of route objects, where each object contains a route and a component.
this.defaultRoute = options.defaultRoute; // The default route to navigate to if no matching route is found.
this.errorRoute = options.errorRoute; // The error route to navigate to if a matching route is not found.
this.el = options.el; // The DOM element to render components into.
this.visitedRoutes = []; // An array of visited routes.
this.init(); // Initialize the router.
}
// Initialize the router by setting up event listeners and handling the initial page load.
init() {
// Handle initial page load
this.navigateTo(window.location.pathname);
// Handle back/forward button clicks
window.addEventListener('popstate', () => {
this.goToPreviousRoute();
});
// Handle anchor tag clicks
document.addEventListener('click', (event) => {
const anchor = event.target.closest('a');
if (anchor && anchor.getAttribute('href').startsWith('/')) {
event.preventDefault();
this.navigateTo(anchor.getAttribute('href'));
}
});
}
// Navigate to the specified path by finding the corresponding route and rendering the component.
navigateTo(path) {
const route = this.findRoute(path) || this.findRoute(this.errorRoute); // Find the route object for the specified path or the error route.
const { component, data } = route; // Destructure the component and data properties from the route object.
// Create a new component instance
const elComponent = new component({ el: this.el, data });
// Add the current route to the visited routes array
this.visitedRoutes.push(path);
// Update the browser history without reloading the page
history.pushState({ path }, '', path);
}
// Navigate to the previous route by retrieving the previous path from the visited routes array and rendering the corresponding component.
goToPreviousRoute() {
if (this.visitedRoutes.length > 1) {
// Remove the current route from the visited routes array
this.visitedRoutes.pop();
// Retrieve the previous route from the visited routes array
const previousPath = this.visitedRoutes[this.visitedRoutes.length - 1];
const previousRoute = this.findRoute(previousPath) || this.findRoute(this.errorRoute);
const { component: previousComponent, data: previousData } = previousRoute;
// Create a new component instance for the previous route
const previousElComponent = new previousComponent({ el: this.el, data: previousData });
// Update the browser history without reloading the page
history.pushState({ path: previousPath }, '', previousPath);
}
}
// Find the route object for the specified path.
findRoute(path) {
return this.routes.find((route) => route.route === path);
}
}
// ElRequest: A simple XMLHttpRequest wrapper for making HTTP requests.
class ElRequest {
constructor() {
this.http = new XMLHttpRequest(); // Create a new instance of XMLHttpRequest.
this.headers = {}; // Initialize an empty headers object.
}
// Set a header for the request.
setHeader(key, value) {
this.headers[key] = value;
}
// Make a GET request.
get(url = '', data = {}, callback = () => { }) {
// Convert the data object to a query string.
const queryString = Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
this.http.open('GET', `${url}?${queryString}`, true); // Open a GET request to the provided URL with the query string.
// Set any headers provided.
for (const [key, value] of Object.entries(this.headers)) {
this.http.setRequestHeader(key, value);
}
// Handle the response when it loads.
this.http.onload = function () {
if (this.http.status === 200) {
callback(null, this.http.responseText); // Invoke the callback with no errors and the response text.
} else {
callback(`Error: ${this.http.status}`); // Invoke the callback with an error message.
}
}.bind(this);
this.http.send(); // Send the request.
}
// Make a POST request.
post(url = '', data = {}, callback = () => { }) {
this.http.open('POST', url, true); // Open a POST request to the provided URL.
// Set any headers provided.
for (const [key, value] of Object.entries(this.headers)) {
this.http.setRequestHeader(key, value);
}
// Handle the response when it loads.
this.http.onload = function () {
callback(null, this.http.responseText); // Invoke the callback with no errors and the response text.
}.bind(this);
// Convert the data object to a request body string.
const requestBody = Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
this.http.send(requestBody); // Send the request with the request body.
}
// Make a PUT request.
put(url = '', data = {}, callback = () => { }) {
this.http.open('PUT', url, true); // Open a PUT request to the provided URL.
// Set any headers provided.
for (const [key, value] of Object.entries(this.headers)) {
this.http.setRequestHeader(key, value);
}
// Handle the response when it loads.
this.http.onload = function () {
callback(null, this.http.responseText); // Invoke the callback with no errors and the response text.
}.bind(this);
// Convert the data object to a request body string.
const requestBody = Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
this.http.send(requestBody); // Send the request with the request body.
}
// Make a DELETE request.
delete(url = '', callback = () => { }) {
this.http.open('DELETE', url, true); // Open a DELETE request to the provided URL.
// Set any headers provided.
for (const [key, value] of Object.entries(this.headers)) {
this.http.setRequestHeader(key, value);
}
// Handle the response when it loads.
this.http.onload = function () {
if (this.http.status === 200) {
callback(null, 'Post Deleted!'); // Invoke the callback with no errors and a success message.
} else {
callback(`Error: ${this.http.status}`); // Invoke the callback with an error message.
}
}.bind(this);
this.http.send(); // Send the request.
}
}