-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstapling-1.5.js
More file actions
571 lines (423 loc) · 18 KB
/
stapling-1.5.js
File metadata and controls
571 lines (423 loc) · 18 KB
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
/**
* Stapling 1.5
*
* JSON XSLT Parser, use XSLT to transform JSON
*
* @author Björn Wikström <bjorn@welcom.se>
* @license LGPL v3 <http://www.gnu.org/licenses/lgpl.html>
* @version 1.5
* @copyright Welcom Web i Göteborg AB 2012
*/
;(function (window, document, undef) {
/**
* If Stapling is already loaded, don't load it again
*/
if (!!window.Stapling) {
return;
}
/**
* IE7/IE8 doesn't have the Array.indexOf() method
* nativly, so we manually have to implement it
*/
Array.prototype.indexOf = Array.prototype.indexOf || function (obj, start) {
for (var i = (start || 0); i < this.length; i++) {
if (this[i] === obj) {
return i;
}
}
return -1;
};
/**
* IE7/IE8 and FireFox < 1.5 doesn't have the Array.forEach()
* method nativly, so we have to add this manually for
* these broswsers as well
*/
Array.prototype.forEach = Array.prototype.forEach || function (callback, thisArg) {
for (var i = 0; i < this.length; i++) {
callback.call(thisArg, this[i]);
}
};
var Stapling = function () {
/**
* Older IE versions handle XML and XSLT throught ActiveX-components,
* so we need to check if we can use modern functionality or if
* we have to fall back to ActiveX-components
*/
var activeXParsing = !(window.DOMParser && window.XSLTProcessor),
activeXRequest = !window.XMLHttpRequest;
/**
* The event callback queue
*/
var _events = {
'parse': [],
'request': []
};
/**
* Do an asynchronous Ajax call for a resource,
* either a XSLT template or a JSON webservice
*
* @param url {String} A URI for the resource
* @param callback {Function} A callback for a successful Ajax call
* @returns {Void}
* @throws {Exception} If the resource couldn't be fetched
*/
var _request = function (url, callback) {
/* If we have any request events, call them to see
if we should proceed with the request */
if (!!_events['request'] && _events['request'].length > 0) {
var shouldRequest = true;
_events['request'].forEach(function (fn) {
if (!fn.call(this, url)) shouldRequest = false;
}, this);
if (!shouldRequest) {
return;
}
}
var request;
if (activeXRequest) {
request = new ActiveXObject("Msxml2.XMLHTTP");
} else {
request = new XMLHttpRequest();
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request.responseText);
} else if (request.readyState == 4) {
throw {
"type": "ServerException",
"message": "The resource could not be fetched from '" + url + "'"
};
}
};
var operator = url.indexOf('?') >= 0 ? '&' : '?';
var path = url + operator + 'cache=' + (new Date()).getMilliseconds() + (new Date()).getSeconds();
request.open("GET", path, true);
request.send("");
};
/**
* Create a XMLDocument from a XML string
*
* @param string {String} The XML in string format
* @returns {XMLDocument}
*/
var _xmlFromString = function (string) {
if (!activeXParsing) {
return (new DOMParser()).parseFromString(string, "text/xml");
}
var x = new ActiveXObject("Msxml2.DOMDocument");
x.loadXML(string);
return x;
};
/**
* Create a XMLDocument|DOMDocument from a XSL string
*
* @param string {String} The XSL in string format
* @returns {XMLDocument|DOMDocument}
*/
var _xslFromString = function (string) {
if (!activeXParsing) {
return (new DOMParser()).parseFromString(string, "text/xml");
}
var x = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
x.loadXML(string);
return x;
};
/**
* Create a "full" XML-like string
*
* @param content {String} The XML content
* @returns {String}
*/
var _fullXmlString = function (xmlPart) {
return '<' + '?xml version="1.0" encoding="UTF-8" ?' + '><json>' + xmlPart + '</json>';
};
/**
* Sanitizes a node name from a JSON name, only
* allow a-z, A-Z, 0-9, - and _
*
* @param name {String} The name of the node
* @returns {String}
*/
var _sanitize = function (name) {
return name.replace(/[^a-z0-9\-_]/ig, '');
};
/**
* Parse a JavaScript array to a XML node list
*
* @param name {String} The name of the node
* @param elements {Array} The JSON array
* @returns {Array}
*/
var _parseList = function (name, elements) {
var list = [];
for (var i = 0; i < elements.length; i++) {
/* Is it a regular JavaScript object? */
if (Object.prototype.toString.call(elements[i]) === '[object Object]') {
var children = _parseObject(elements[i]);
list.push('<item>');
for (var j = 0; j < children.length; j++) {
list.push(children[j]);
}
list.push('</item>');
} /* Is it an array? */
else if (Object.prototype.toString.call(elements[i]) === '[object Array]') {
var children = _parseList('item', elements[i]);
for (var j = 0; j < children.length; j++) {
list.push(children[j]);
}
} /* It's something that can be translated to a string */
else {
list.push('<' + _sanitize(name) + '>' + elements[i] + '</' + _sanitize(name) + '>');
}
}
return list;
};
/**
* Parse a JavaScript object (not array) to a XML node list
*
* @param obj {Object} The container object
* @returns {Array}
*/
var _parseObject = function (obj) {
var list = [];
for (var p in obj) {
/* Is it a regular JavaScript object? */
if (Object.prototype.toString.call(obj[p]) === '[object Object]') {
var children = _parseObject(obj[p]);
var xmlString = '<' + _sanitize(p) + '>';
for (var i = 0; i < children.length; i++) {
xmlString += children[i];
}
xmlString += '</' + _sanitize(p) + '>';
list.push(xmlString);
} /* Is it an array? */
else if (Object.prototype.toString.call(obj[p]) === '[object Array]') {
var children = _parseList(p, obj[p]);
var xmlString = '<' + _sanitize(p) + '>';
for (var i = 0; i < children.length; i++) {
xmlString += children[i];
}
xmlString += '</' + _sanitize(p) + '>';
list.push(xmlString);
} /* It's something that can be translated to a string */
else {
list.push('<' + _sanitize(p) + '>' + obj[p] + '</' + _sanitize(p) + '>');
}
}
return list;
};
/**
* Helper function to parse JSON -> XML String
*
* @param json {Object} Either an array or actual JSON object
* @returns {String}
*/
var _xmlFromJSON = function (json) {
json = Object.prototype.toString.call(json) === '[object Object]' ? json : {"list-items": json};
var children = _parseObject(json),
content = '';
for (var i = 0; i < children.length; i++) {
content += children[i];
}
var xml = _fullXmlString(content);
return xml;
};
/**
* Parse a XMLDocument through a XSLT template
*
* @param xsl {XMLDocument} The XSLT as a XMLDocument
* @param xml {XMLDocument} The JSON as a XMLDocument
* @param callback {Function} Called and supplied with the generated document
* @returns {Void}
*/
var _parse = function (xmlDocument, xslDocument, callback) {
var result = false;
if (activeXParsing) {
var template = new ActiveXObject("Msxml2.XSLTemplate");
template.stylesheet = xslDocument;
var processor = template.createProcessor();
processor.input = xmlDocument;
processor.transform();
var fragment = document.createDocumentFragment();
var container = document.createElement('div');
fragment.appendChild(container);
container.outerHTML = processor.output;
result = fragment;
} else {
var processor = new XSLTProcessor();
processor.importStylesheet(xslDocument);
result = processor.transformToFragment(xmlDocument, document);
}
callback.call(result, xmlDocument);
};
/**
* Store a resousource, as a string, for the specified resource URI
*
* @param name {String} The name (url) of the resource
* @param content {String} The content of the resource
* @returns {Void}
*/
var _store = function (name, content) {
try {
localStorage.setItem(name, content);
} catch (e) {}
};
/**
* See if the resource is in the cache, if so - return it. This
* will optimize the application as all templates don't need to
* be fetched on every visit
*
* @param name {String} The name (url) of the resource
* @returns {Mixed} Either the cached resource (as string) or 'false' if not present
*/
var _retrieve = function (name) {
var cached = false;
try {
if ((cached = localStorage.getItem(name)) !== null && typeof cached === 'string') {
return cached;
}
} catch (e) {}
return cached;
};
return {
/**
* Should the next resource be cachable? Either a JSON
* webservice call or a XSLT template resource
*/
cachable: true,
/**
* Helper to see if the client is a relatively modern
* browser (IE8+) or is using fallback libraries
*
* @returns {Boolean}
*/
isSupported: function () {
return (window.localStorage && window.JSON);
},
/**
* Pre fetch either a XSLT template from resource
* or JSON data from service and store it in cache.
* This way loading content later will be much faster.
*
* @param resources {Array|String} The service or template URI(s)
* @returns {Void}
*/
prefetch: function (resources) {
if (typeof resources === 'string') {
resources = [resources];
}
for (var i = 0; i < resources.length; i++) {
(function (resource) {
_request(resource, function (response) {
_store(resource, response);
});
})(resources[i]);
}
},
/**
* Is the specified resource cached?
*
* @param resource {String} The service or template URI
* @returns {Boolean}
*/
isCached: function (resource) {
return _retrieve(resource) !== false;
},
/**
* Parse the specified JSON object with a XSLT template
* from the specified resource
*
* @param json {Object} A JSON object
* @param template {String} An URI to the XSLT template
* @param callback {Function} Called when done, with the generated document
* @returns {Void}
*/
parse: function (json, template, callback) {
/* If we have any parse events, call them to see
if we should proceed with the parsing */
if (!!_events['parse'] && _events['parse'].length > 0) {
var shouldParse = true;
_events['parse'].forEach(function (fn) {
if (!fn.call(this, json, template)) shouldParse = false;
}, this);
if (!shouldParse) {
return;
}
}
var xml = _xmlFromJSON(json),
cached = false;
if (this.cachable && (cached = _retrieve(template)) !== false && cached != null) {
var xmlDocument = _xmlFromString(xml),
xslDocument = _xslFromString(cached);
_parse(xmlDocument, xslDocument, callback);
} else {
var me = this;
_request(template, function (xsl) {
if (me.cachable) {
_store(template, xsl);
}
var xmlDocument = _xmlFromString(xml),
xslDocument = _xslFromString(xsl);
_parse(xmlDocument, xslDocument, callback);
});
}
},
/**
* Load both JSON and XSLT template from resources
*
* @param service {String} An URI to the JSON webservice
* @param template {String} An URI to the XSLT template
* @param callback {Function} Called when done, with the generated document
* @returns {Void}
*/
load: function (service, template, callback) {
var cached = false,
me = this;
if (this.cachable && (cached = _retrieve(service)) !== false && cached != null) {
me.parse(JSON.parse(cached), template, callback);
} else {
var me = this;
_request(service, function (json) {
if (me.cachable) {
_store(service, json);
}
me.parse(JSON.parse(json), template, callback);
});
}
},
/**
* Clear the cache for the specified resource(s)
*
* @param name {String|Array} An URI for a XSLT template, or a list of multiple URIs
* @returns {Void}
*/
clear: function (name) {
try {
if (Object.prototype.toString.call(name) === '[object Array]') {
for (var i = 0; i < name.length; i++) {
localStorage.removeItem(name[i]);
}
} else {
localStorage.removeItem(name);
}
} catch (e) {}
},
/**
* Event registration, adds a callback for a supported event
*
* @param event {String} An event name
* @param callback {Function} A callback for the event
* @returns {Void}
*/
on: function (event, callback) {
if (!!_events[event]) {
_events[event].push(callback);
}
}
};
}();
/**
* Add Stapling to the global namespace
*/
window.Stapling = Stapling;
})(window, document);