-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatejs.js
691 lines (584 loc) · 24.4 KB
/
statejs.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/**
* A module that provides a loading spinner functionality.
*
* The `loader` object has the following methods:
*
* - `show(customHtml = null)`: Displays a loading spinner on the page. If `customHtml` is provided, it will be used as the content of the spinner. Otherwise, a default spinner HTML is used.
* - `hide()`: Removes the loading spinner from the page.
* - `addBlur()`: Adds a semi-transparent blur effect to the background behind the loading spinner.
* - `addAnimationStyles()`: Adds the necessary CSS styles for the loading spinner animation.
* - `getDefaultHtml()`: Returns the default HTML for the loading spinner.
*
* The `watch` function is used to create a watched variable that can be accessed from outside the module and have its value changes listened to.
*
* The `parseTemplate` function is used to parse JavaScript expressions enclosed in `{{}}` within a template string.
*
* The `createRangeArray` function is used to create an array of numbers within a specified range and step.
*
* The `CustomForLoop` class is a custom HTML element that implements a for-loop functionality within the HTML.
*
* The `setState` function is used to update the state of various elements on the page, such as loops, templates, and conditions.
*
* The `convertRelativeToAbsolute` function is used to convert relative URLs to absolute URLs within an HTML string.
*
* The `extractDirectory` function is used to extract the directory from a relative URL.
*
* The `includeTemplate` class is a custom HTML element that allows for the inclusion of external HTML templates.
*
* The `IfCondition` and `ElseCondition` classes are custom HTML elements that implement conditional rendering within the HTML.
*
* The `Customcondition` class is a custom HTML element that implements a more complex conditional rendering within the HTML.
*
* The `getType` function is used to determine the type of a given input.
*
* The `passValue` function is used to pass a value to other pages, handling different data types.
*
* The `parseURL` function is used to parse the current URL and store the parsed data in the `UrlDetails` global variable.
*
* The `initState` function is used to define the custom HTML elements used in the code.
*/
//show a loader
const loader = {
show: function (customHtml = null) {
this.addAnimationStyles();
const loaderHtml = customHtml || this.getDefaultHtml();
// Create a new loader element
const loaderElement = document.createElement('div');
loaderElement.innerHTML = loaderHtml;
loaderElement.classList.add('loader64645446554dfd5ff4dfe82422fdf34521dsddsdadderere');
// Add styles to the loader element
loaderElement.style.position = 'fixed';
loaderElement.style.top = '50%';
loaderElement.style.left = '50%';
loaderElement.style.transform = 'translate(-50%, -50%)';
loaderElement.style.zIndex = '9999';
loaderElement.style.background = '#fff';
// Append the loader element to the body
document.body.appendChild(loaderElement);
this.addBlur();
},
hide: function () {
// Remove the loader element from the body
const loaderElement = document.querySelector('.loader64645446554dfd5ff4dfe82422fdf34521dsddsdadderere');
if (loaderElement) {
loaderElement.parentElement.removeChild(loaderElement);
}
const blurElement = document.querySelector('.blur');
if (blurElement) {
blurElement.parentElement.removeChild(blurElement);
}
},
addBlur: function () {
// Create a new element for blur effect
const blurElement = document.createElement('div');
blurElement.classList.add('blur');
// Append the blur element to the body
document.body.appendChild(blurElement);
},
addAnimationStyles: function () {
// Create style element
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `
.blur {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.5); /* Semi-transparent white */
backdrop-filter: blur(50px); /* Fallback for browsers that support backdrop-filter */
z-index: 9998; /* Make sure it's below the loader */
}
@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
// Append style element to the head
document.head.appendChild(style);
},
getDefaultHtml: function () {
// Default loader HTML with animation
return '<div class="loader64645446554dfd5ff4dfe82422fdf34521dsddsdadderere" style="border: 8px solid #f3f3f3; border-radius: 50%; border-top: 8px solid #3498db; width: 50px; height: 50px; animation: spin 1s linear infinite;"></div>';
}
};
//create such variable so we can access it from outside of this module and listen to its value change so we can update state via setState
const watchedVars = []
function watch(propName, cb, defaultValue = undefined) {
let _value = defaultValue; // Private variable for storing the value
// Define the property with getter and setter
Object.defineProperty(window, propName, {
get: function () {
return _value;
},
set: function (value) {
_value = value;
// console.log(`${propName} has been changed:`, value);
cb(propName, value)
}
});
watchedVars.push(propName)
}
//parse the js expressions inside of html {{}}
function parseTemplate(template) {
return template.replace(/\{\{(.*?)\}\}/gs, function (match, expression) {
try {
// Evaluate the expression within the global scope
var result = (0, eval)(expression.trim()); // Using (0, eval) to evaluate in global scope
// If the result is not undefined, return it
if (result !== undefined) {
return result;
}
} catch (error) {
throw new Error('Error while evaluating JS Expression "' + expression + '":\n' + error);
// If there is an error evaluating the expression, return the original match
//console.error("Error evaluating expression:", expression, error);
}
// If the result is undefined or there's an error, return the original match
return match;
});
}
//array creation
function createRangeArray(start, end, step = 1) {
const result = [];
if (step > 0) {
for (let i = start; i <= end; i += step) {
result.push(i);
}
} else if (step < 0) {
for (let i = start; i >= end; i += step) {
result.push(i);
}
}
return result;
}
//for loop in html implementation.
class CustomForLoop extends HTMLElement {
constructor() {
super();
// Get start and end attributes
}
connectedCallback() {
// Perform actions after the element is connected to the DOM
this.render()
}
render() {
try {
this.style.display = "contents";
var array = (0, eval)(this.getAttribute('array')) || [];
var start = eval(this.getAttribute('start')) || 0;
var step = eval(this.getAttribute('step')) || 1;
var end = eval(this.getAttribute('end')) || array.length;
var valueVar = this.getAttribute('valueVar');
var indexVar = this.getAttribute('indexVar');
var append = eval(this.getAttribute('append')) || false;
if (array.length <= 0 && start >= 0 && end >= 0) {
array = createRangeArray(start, end, step)
}
var templateContent
//const shadow = this.attachShadow({ mode: 'open' });
// console.log(this.ATTRIBUTE_NODE,"attributes are ",this.attributes,this.querySelector('template'))
try {
if (this.getAttribute('loopid') == '' || this.getAttribute('loopid') == null || this.getAttribute('loopid') == undefined) {
throw new Error("Missing attribute `loopid` ")
}
templateContent = this.querySelector(`template[loopid="${this.getAttribute('loopid')}"]`).content.cloneNode(true);
} catch (error) {
this.innerHTML = "💥templateERROR: template tag with a loopid attribute is required.inside of for-loop tag."
throw error;
} var temp = document.createElement("div")
temp.appendChild(templateContent)
var stringContent = temp.innerHTML;
// Define the regular expression pattern
// Create a shadow root
var tempHTML = ``
const pattern = /\$\{(.*?)\}/gs;
var vr = new RegExp("\\b" + valueVar + "\\b", "g");
var ir = new RegExp("\\b" + indexVar + "\\b", "g");
stringContent = stringContent.replaceAll(vr, "value").replaceAll(ir, "index")
//console.log(stringContent)
for (let i = start; i < end; i++) {
var value = array[i]
var index = i
//console.log("value", value)
var x = stringContent.replace(pattern, function (match, expression) {
try {
// Evaluate the expression within the global scope
var result = eval(expression.trim()); // Using (0, eval) to evaluate in global scope
// If the result is not undefined, return it
if (result !== undefined) {
return result;
}
} catch (error) {
// If there is an error evaluating the expression, return the original match
console.error("Error evaluating expression:", expression, error);
}
// If the result is undefined or there's an error, return the original match
return match;
}
)
tempHTML += x//stringContent.replaceAll("${"+index+"}",`${i}`).replaceAll("${"+value+"}",`${JSON.stringify(array[i])}`)
}
//console.log(parseTemplate(tempHTML))
var templateCopy = `<template loopid="${this.getAttribute('loopid')}">
${temp.innerHTML}
</template>`
try {
if (append == true) {
var tempdiv = document.createElement('div');
tempdiv.id = "tempcopy" + Math.random() * 12345678
tempdiv.style.display = "contents"
tempdiv.innerHTML = parseTemplate(tempHTML);
this.appendChild(tempdiv)
} else {
this.innerHTML = parseTemplate(tempHTML) + templateCopy
}
} catch (error) {
throw new Error(`Failed to parse due to ${error}`);
}
//this.appendChild(templateContent.cloneNode(true));
} catch (error) {
console.error(error)
}
}
rerender() {
this.render();
}
}
// Define the custom element
//set state or refresh ui when data changes
setState = ({ loopid = false, ifid = false, showloader = true, datajs = true, innerhtml = true, loops = true, templates = false, conditions = true } = {}) => {
try {
if (showloader) { loader.show(); }
if (loopid) {
try {
var loopele = document.querySelectorAll(`[loopid="${loopid}"]`);
loopele.forEach(function (element) {
element.render();
console.log(element)
});
}
catch (err) {
console.error(err)
}
if (showloader) { loader.hide(); }
return
}
if (ifid) {
try {
var ifele = document.querySelectorAll(`[ifid="${ifid}"]`);
ifele.forEach(function (element) {
element.render();
});
}
catch (err) {
console.error(err)
}
if (showloader) { loader.hide(); }
return
}
if (datajs) {
var elementsWithDataJS = document.querySelectorAll("[data-js]");
elementsWithDataJS.forEach(function (element) {
eval(element.dataset.js.replace("this", "element"));
});
}
if (innerhtml) {
var elementsWithDataInnerHTML = document.querySelectorAll("[data-innerhtml]");
elementsWithDataInnerHTML.forEach((element) => {
if (element.dataset.innerhtml !== undefined) {
let content = eval(element.dataset.innerhtml);
content = content.replace(/</g, "<").replace(/>/g, ">");
element.innerHTML = content;
}
});
}
if (loops) {
var loopElements = document.querySelectorAll("for-loop");
loopElements.forEach(function (element) {
element.render();
});
}
if (templates) {
var includedTemplates = document.querySelectorAll("include-template");
includedTemplates.forEach((templateElement) => {
templateElement.render();
});
}
if (conditions) {
var conditionBlocks = document.querySelectorAll("condition-block");
conditionBlocks.forEach((templateElement) => {
templateElement.render();
});
}
if (showloader) { loader.hide(); }
} catch (error) {
if (showloader) { loader.hide(); }
console.error(error);
}
};
// replace relative url to absolute url
function convertRelativeToAbsolute(htmlString, baseUrl) {
// Regular expression to match relative URLs in HTML attributes
var regex = /(?:src|href)=["'](\.{1,2}\/[^"']+)["']/g;
// Replace relative URLs with absolute URLs
htmlString = htmlString.replace(regex, function (match, url) {
// Construct the absolute URL based on the base URL
var absoluteUrl = new URL(url, baseUrl).href;
return match.replace(url, absoluteUrl);
});
return htmlString;
}
//get directory from a relative url
function extractDirectory(relativeUrl) {
// Create a dummy anchor element
var anchor = document.createElement('a');
anchor.href = relativeUrl;
// Extract the directory from the anchor's pathname
var directory = anchor.pathname.substring(0, anchor.pathname.lastIndexOf('/'));
// Return the directory
return directory;
}
//custom include function like php's include
class includeTemplate extends HTMLElement {
constructor() {
super();
this.render()
}
async render() {
try {
loader.show()
this.style.display = "contents";
var file = this.getAttribute('file');
var response = await fetch(file)
var html = await response.text()
var dir = extractDirectory(file);
var anchor = document.createElement('a');
anchor.href = dir;
html = convertRelativeToAbsolute(html, anchor.href + "/");
this.innerHTML = parseTemplate(html)
// Manually execute scripts
var scripts = this.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
var newScript = document.createElement("script");
newScript.text = script.text;
script.parentNode.replaceChild(newScript, script);
}
loader.hide()
} catch (error) {
console.error(error)
loader.hide()
}
}
rerender() {
this.render();
}
}
//if statement inside of html itself
class IfCondition extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
// Perform actions after the element is connected to the DOM
this.style.display = "contents";
this.render()
}
render() {
var elseId;
try {
try {
if ((this.parentElement).parentElement.tagName != "TEMPLATE" && (this.parentElement).parentElement.tagName != "FOR-LOOP" && (this.parentElement).parentElement.tagName != "condition-block".toUpperCase()) {
throw Error("1IfConditions must be nested within a Template/for-loop/condition-block tag.")
}
} catch (error) {
//console.log("error",error,"nnn",(this.parentElement).parentElement)
if ((this.parentElement).tagName != "TEMPLATE" && (this.parentElement).tagName != "FOR-LOOP" && (this.parentElement).tagName != "condition-block".toUpperCase()) {
throw Error("2IfConditions must be nested within a Template/for-loop/condition-block tag.")
}
}
const value = this.getAttribute('value');
const eq = this.getAttribute('eq');
const neq = this.getAttribute('neq');
elseId = this.getAttribute('elseid') || "";
if (value == null || (eq == null && neq == null)) {
throw "if condition must have a 'value' and an 'eq'/'neq' attribute";
}
if (!neq) {
console.log(`${value}==${eq}`)
if (eval(`${value}==${eq}`)) {
const elseElement = document.querySelector(`else-condition[elseid="${elseId}"]`);
if (elseElement) {
elseElement.remove()
}
try {
// Manually execute scripts
var scripts = this.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
var newScript = document.createElement("script");
newScript.text = script.text;
script.parentNode.replaceChild(newScript, script);
}
} catch (err) {
console.error("No Scripts in this block.or some problems happened in the element.", this)
}
} else {
this.remove();
}
} else {
if (eval(`${value}!=${neq}`)) {
const elseElement = document.querySelector(`else-condition[elseid="${elseId}"]`);
if (elseElement) {
elseElement.remove()
}
try {
// Manually execute scripts
var scripts = this.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
var newScript = document.createElement("script");
newScript.text = script.text;
script.parentNode.replaceChild(newScript, script);
}
} catch (err) {
console.error("No Scripts in this block.or some problems happened in the element.", this)
}
} else {
this.remove();
}
}
} catch (error) {
this.innerHTML = error
try {
document.querySelector(`else-condition[elseid="${elseId}"]`).remove()
} catch (error) {
}
console.error(error)
}
}
rerender() {
this.render();
}
}
class ElseCondition extends HTMLElement {
connectedCallback() {
try {
this.style.display = "contents";
const elseId = this.getAttribute('elseid');
const ifElement = document.querySelector(`if-condition[elseid="${elseId}"]`);
if (!ifElement) {
throw Error(`Else condition without corresponding If: ${this.outerHTML}`);
}
}
catch (error) {
// console.error(error)
}
}
}
class Customcondition extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
// Perform actions after the element is connected to the DOM
this.render()
}
render() {
try {
this.style.display = "contents";
var templateContent
//const shadow = this.attachShadow({ mode: 'open' });
// console.log(this.ATTRIBUTE_NODE,"attributes are ",this.attributes,this.querySelector('template'))
try {
if (this.getAttribute('ifid') == '' || this.getAttribute('ifid') == null || this.getAttribute('ifid') == undefined) {
throw new Error("Missing attribute `ifid` ")
}
templateContent = this.querySelector(`template[ifid="${this.getAttribute('ifid')}"]`).content.cloneNode(true);
} catch (error) {
this.innerHTML = "💥templateERROR: template tag is required.inside of condition-block tag."
throw error;
} var temp = document.createElement("div")
temp.appendChild(templateContent)
var stringContent = temp.innerHTML;
// Define the regular expression pattern
// Create a shadow root
//stringContent.replaceAll("${"+index+"}",`${i}`).replaceAll("${"+value+"}",`${JSON.stringify(array[i])}`)
//console.log(parseTemplate(tempHTML))
var templateCopy = `<template ifid="${this.getAttribute("ifid")}">
${temp.innerHTML}
</template>`
this.innerHTML = parseTemplate(stringContent) + templateCopy;
// if (append == true) {
// console.log(this.innerHTML)
// var c = this.innerHTML + parseTemplate(tempHTML).replaceAll(templateCopy, '') + templateCopy;
// console.log("c is ", c)
// this.innerHTML = c
// }
//this.appendChild(templateContent.cloneNode(true));
setState({ showloader: false, conditions: false, templates: false })
} catch (error) {
console.error(error)
}
}
rerender() {
this.render();
}
}
// Define the custom element
//Get true input type
function getType(input) {
if (Array.isArray(input)) {
return 'array';
} else if (input === null) {
return 'null';
} else {
return typeof input;
}
}
// use this to pass value to other pages inside of for loop or something like that.or you can use as it is as a function.
function passValue(value) {
if (getType(value) == "array" || getType(value) == "object") {
return encodeURI(JSON.stringify(value))
} else {
return encodeURI(value.toString)
}
}
// parse url and add to the window(global) by default and default url is location.href
function parseURL(url = location.href, global = true) {
const parsedUrl = new URL(url);
const parsedData = {
protocol: parsedUrl.protocol,
hostname: parsedUrl.hostname,
pathname: parsedUrl.pathname,
params: Object.fromEntries(parsedUrl.searchParams.entries())
};
// Iterate over each query parameter and attempt JSON parsing
for (const key in parsedData.params) {
if (parsedData.params.hasOwnProperty(key)) {
const value = parsedData.params[key];
try {
parsedData.params[key] = JSON.parse(value);
} catch (error) {
// Ignore if JSON parsing fails
}
}
}
if (global) { window["UrlDetails"] = parsedData; }
return parsedData;
}
//call it to autometically add at the time of initializing
parseURL()
function initState() {
customElements.define('for-loop', CustomForLoop);
customElements.define('include-template', includeTemplate);
customElements.define('if-condition', IfCondition);
customElements.define('else-condition', ElseCondition);
customElements.define('condition-block', Customcondition);
}