Code · 232 lines · 5510 bytes
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/**
 * 
 *	@name		pure-dom netproxy and template api
 * 
 *	@author     Alphons van der Heijden <alphons@heijden.com>
 *	@version    3.0.4 (last revision 30 aug, 2025)
 *	@copyright  (c) 2019-2025 Alphons van der Heijden
 *	@alias      netproxy, netproxyasync, Element.Template, TemplateHtml
 * 
 */

// please use defer in script tag
(function ()
{
	'use strict';

	// Escape functie om XSS te voorkomen
	function escapeHtml(unsafe)
	{
		if (Array.isArray(unsafe))
		{
			return unsafe.map(item => escapeHtml(item)).join(', ');
		}
		if (unsafe === null || unsafe === undefined)
		{
			return '';
		}
		return String(unsafe).replace(/[&<>"']/g, function (match)
		{
			return {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#39;'
			}[match];
		});
	}

	// Helper functie voor spinner logica
	function manageSpinner(spinner, show, timeoutSpinner)
	{
		if (spinner)
		{
			spinner.style.display = show ? 'block' : 'none';
		}
		if (timeoutSpinner && !show)
		{
			clearTimeout(timeoutSpinner);
		}
	}

	// Netproxy functionaliteit
	window.netproxy = function (url, data, onsuccess, onerror, onprogress, timeout = 30000)
	{
		const spinner = document.getElementById("netproxyspinner");
		if (typeof remote !== 'undefined')
		{
			url = remote + url;
		}

		const timeoutSpinner = spinner ? setTimeout(() => manageSpinner(spinner, true), 1000) : null;
		const xhr = new XMLHttpRequest();
		xhr.open(data ? 'POST' : 'GET', url, true);
		xhr.withCredentials = url.indexOf(window.location.host) < 0 && url[0] !== '/';

		if (!(data instanceof FormData))
		{
			xhr.timeout = timeout;
			xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
		}

		xhr.onloadend = function ()
		{
			manageSpinner(spinner, false, timeoutSpinner);

			if (xhr.status === 204)
			{
				if (typeof onsuccess === 'function')
				{
					onsuccess.call(null, null);
				}
				return;
			}

			if (xhr.status >= 200 && xhr.status < 300)
			{
				const contentDisposition = xhr.getResponseHeader('Content-Disposition');
				if (contentDisposition && contentDisposition.includes('attachment'))
				{
					const blob = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') });
					const filename = contentDisposition.split('filename="')[1]?.split('"')[0] || 'download';
					const a = document.createElement('a');
					a.href = URL.createObjectURL(blob);
					a.download = filename;
					a.rel = 'noopener';
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a);
					setTimeout(() => URL.revokeObjectURL(a.href), 40000);
					return;
				}

				let response = xhr.response;
				try
				{
					response = JSON.parse(xhr.responseText);
				}
				catch (e)
				{
					// Blijf bij tekst als JSON-parsen faalt
				}

				try
				{
					if (typeof onsuccess === 'function')
					{
						onsuccess.call(response, response);
					}
					return;
				}
				catch (error)
				{
					if (typeof onerror === 'function')
					{
						onerror.call(xhr, error);
					}
					return;
				}
			}

			if (xhr.status >= 400)
			{
				const error = new Error(`Http:${xhr.status}`);
				error.path = url;
				if (typeof onerror === 'function')
				{
					onerror.call(xhr, error);
					return;
				}
				throw error;
			}

			if (xhr.status === 0)
			{
				const error = xhr.timedout
					? new Error(`Timeout ${timeout}ms for ${url}`)
					: new Error(`Network error or request canceled for ${url}`);
				error.path = url;
				if (typeof onerror === 'function')
				{
					onerror.call(xhr, error);
					return;
				}
				throw error;
			}
		};

		if (typeof onprogress === 'function')
		{
			xhr.upload.onprogress = onprogress;
			xhr.onprogress = onprogress;
		}

		xhr.send(data instanceof FormData ? data : JSON.stringify(data));
	};

	window.netproxyasync = function (url, data, onprogress, timeout = 30000)
	{
		return new Promise((resolve, reject) =>
		{
			window.netproxy(url, data, resolve, reject, onprogress, timeout);
		});
	};

	// Template functionaliteit
	Element.prototype.Template = function (template, data, append)
	{
		var strHtml = window.TemplateHtml(template, data);
		if (append)
		{
			var temp = document.createElement("span");
			this.insertAdjacentElement('beforeend', temp);
			temp.outerHTML = strHtml;
		}
		else
		{
			this.innerHTML = strHtml;
		}
	};

	window.TemplateHtml = function (template, data)
	{
		try
		{
			var element = typeof template === "string" ? document.getElementById(template) : template;
			if (!element)
				throw new Error("Template niet gevonden.");
			if (!element.jscache)
			{
				var html = element.innerHTML.replace(/[\t\r\n]/g, " ");
				var js = "let _='';";
				var direct, intI, intJ = 0;
				while (intJ < html.length)
				{
					intI = html.indexOf("{{", intJ);
					if (intI < 0)
						break;
					js += `_+='${html.substring(intJ, intI).replace(/'/g, "\\'")}';`;
					intJ = intI + 2;
					direct = (html[intJ] === "=");
					if (direct)
						intJ++;
					intI = html.indexOf("}}", intJ);
					if (intI < 0)
						break;
					js += direct ? `_+=escapeHtml(${html.substring(intJ, intI).trim()});` : html.substring(intJ, intI).trim() + ";";
					intJ = intI + 2;
				}
				js += `_+='${html.substring(intJ).replace(/'/g, "\\'")}'; return _;`;
				element.jscache = new Function('escapeHtml', 'data', js);
				element.innerHTML = '';
			}
			return element.jscache.call(data, escapeHtml);
		}
		catch (err)
		{
			console.error("Template fout:", err.message);
			return "";
		}
	};
})();