-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDOMBuilder.js
More file actions
604 lines (559 loc) · 20.7 KB
/
DOMBuilder.js
File metadata and controls
604 lines (559 loc) · 20.7 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
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
var ak = require('util').ak;
/**
* Provides utility methods for creating DOM elements in a more declarative
* manner.
* <p>
* <strong>Usage</strong>
* <p>
* Use <code>DOMBuilder.apply()</code> to add DOM creation functions to a given
* context object. A function will be added for each HTML tag, with its name
* being the tag name in upper case. If you don't pass in a context object, one
* will be created for you. For example, the following code:
* <pre><code>var html = DOMBuilder.apply();
* var article =
* html.DIV({"class": "article"},
* html.H2("Article title"),
* html.P("Paragraph one"),
* html.P("Paragraph two")
* );</code></pre>
* <p>
* Will produce a DOM element corresponding to the following HTML:
* <pre><code><div class="article">
* <h2>Article title</h2>
* <p>Paragraph one</p>
* <p>Paragraph two</p>
* </div></code></pre>
* <p>
* General usage of DOM creation functions is that an object specifying
* attributes for the element is passed as the first argument and child elements
* are passed as further arguments. The attribute object is optional and, for
* the sake of flexibility, children may also be passed in an
* <code>Array</code>.
* <p>
* For convenience, you may want to create the utility methods in the global
* scope, which is done like so:
* <pre><code>DOMBuilder.apply(window);</code></pre>
* <p>
* Event handlers can be specified as you would expect - supply an event name
* (including the <code>"on"</code> prefix) as one of the element's attributes
* and an event handling function as the corresponding value. DOMBuilder will
* also ensure the element the event handler is registered on will be accessible
* cross-browser using the <code>this</code> keyword when the event handling
* function is executed.
* <p>
* For example, the following will create a text input which displays a default
* value, clearing it when the input is focused and restoring the default if the
* input is left blank:
* <pre><code>var defaultInput =
* INPUT({type: "text", name: "test",
* value: "Type Here!", defaultValue: "Type Here!",
* onfocus: function()
* {
* if (this.value == this.defaultValue)
* {
* this.value = "";
* }
* },
* onblur: function()
* {
* if (this.value == "")
* {
* this.value = this.defaultValue;
* }
* }});</code></pre>
*
* @class
* @static
* @author Jonathan Buchanan
*/
var DOMBuilder = exports.DOMBuilder = (function()
{
function conditionalEscape(html)
{
if (html instanceof ak.template.Wrap)
{
return ""+html;
}
// Ensure the value we're trying to escape is coerced to a String
return ak.escapeHTML(""+html);
}
/**
* A quick lookup for names of empty tags.
*/
var emptyTags = (function()
{
var lookup = {};
var tags = ["br", "col", "hr", "input", "img", "link", "param"];
for (var i = 0, l = tags.length; i < l; i++)
{
lookup[tags[i]] = true;
}
return lookup;
})();
/**
* Marks a string as safe - this method will be exposed as
* DOMBUilder.markSafe for end users.
*/
function markSafe(value)
{
return ak.safe(value);
}
/**
* Determines if a string is safe - this method will be exposed as
* DOMBuilder.isSafe to end users so they don't have to know about the
* implementation details of escaping.
*/
function isSafe(value)
{
return value instanceof ak.template.Wrap && value.safe;
}
/**
* Encapsulates logic for creating an HTML/XHTML representation of a tag
* structure.
*/
function Tag(tagName, attributes, children)
{
this.tagName = tagName;
this.attributes = attributes || {};
this.children = children || [];
}
Tag.prototype =
{
appendChild: function(child)
{
this.children.push(child);
},
toString: function()
{
// Opening tag
var parts = ["<" + this.tagName];
for (var attr in this.attributes)
{
if (this.attributes.hasOwnProperty(attr))
{
parts.push(" " + attr.toLowerCase() + "=\"" + conditionalEscape(this.attributes[attr]) + "\"");
}
}
parts.push(">");
if (typeof emptyTags[this.tagName] != "undefined")
{
if (o.mode == "XHTML")
{
parts.splice(parts.length - 1, 1, " />");
}
return parts.join("");
}
// Contents
for (var i = 0, l = this.children.length; i < l; i++)
{
var child = this.children[i];
if (child instanceof Tag || child instanceof ak.template.Wrap)
{
parts.push(child.toString());
}
else if (child == "\u00A0")
{
// Special case to convert these back to entities,
parts.push(" ");
}
else
{
// Coerce to string and escape
parts.push(escapeHTML(""+child));
}
}
// Closing tag
parts.push("</" + this.tagName + ">");
return parts.join("");
}
};
Tag.prototype.toString.safe = true;
var o =
/** @scope DOMBuilder */
{
/**
* Determines which mode the createElement function will operate in.
* Supported values are:
* <dl>
* <dt>DOM</dt><dd>Create DOM Elements</dd>
* <dt>HTML</dt><dd>Create HTML Strings</dd>
* <dt>XHTML</dt><dd>Create XHTML Strings</dd>
* </dl>
*/
mode: "HTML",
/**
* Adds element creation functions to a given context object, or to a
* new object if no context object was given.
* <p>
* An <code>NBSP</code> property corresponding to the Unicode character
* for a non-breaking space is also added to the context object, for
* convenience.
*
* @param {Object} [context] a context object to which element creation
* functions should be added.
*
* @return the context object to which element creation functions were
* added.
*/
apply: function(context)
{
context = context || {};
var tagNames = ["a", "abbr", "acronym", "address", "bdo",
"blockquote", "br", "button", "caption", "cite", "code", "col",
"colgroup", "dd", "del", "dfn", "div", "dl", "dt", "em",
"fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6", "hr",
"img", "input", "ins", "kbd", "label", "legend", "li", "link",
"object", "ol", "optgroup", "option", "p", "param", "pre",
"samp", "script", "select", "span", "strong", "style", "table",
"tbody", "td", "textarea", "tfoot", "th", "thead", "tr", "ul",
"var"];
for (var i = 0, tagName; tagName = tagNames[i]; i++)
{
context[tagName.toUpperCase()] = this.createElementFunction(tagName);
}
context.NBSP = "\u00A0";
return context;
},
/**
* Creates a function which, when called, uses DOMBuilder to create a
* DOM element with the given tagName.
* <p>
* See <code>DOMBuilder.createElementFromArguments</code> for the input
* argument formats supported by the resulting function.
*
* @param {String} tagName an HTML tag name.
*
* @return {Function} an element creation function.
*/
createElementFunction: function(tagName)
{
return function()
{
if (arguments.length == 0 && this.mode == "DOM")
{
return document.createElement(tagName);
}
else
{
return DOMBuilder.createElementFromArguments(tagName,
arguments);
}
};
},
/**
* Normalises a list of arguments in order to create a new DOM element
* using <code>DOMBuilder.createElement</code>.
* <p>
* Supported argument formats are:
* <ol>
* <li>
* <code>attributes, child1, ...</code> - an attributes object
* followed by an arbitrary number of children.
* </li>
* <li>
* <code>attributes, [child1, ...]</code> - an attributes object and
* an <code>Array</code> of children.
* </li>
* <li>
* <code>child1, ...</code> - an arbitrary number of children.
* </li>
* <li>
* <code>[child1, ...]</code> - an <code>Array</code> of children.
* </li>
* </ol>
* <p>
* The official store policy on passing invalid argument lists is "You
* Break It, You Get To Keep The Pieces."
*
* @param {String} tagName an HTML tag name.
* @param {Array} args a list of arguments, which may not be empty.
*
* @return a DOM element.
*/
createElementFromArguments: function(tagName, args)
{
var attributes;
var children;
// List of children
if (args.length == 1 &&
args[0] instanceof Array)
{
children = args[0];
}
// Attributes and list of children
else if (args.length == 2 &&
args[0] && args[0].constructor == Object &&
args[1] instanceof Array)
{
attributes = args[0];
children = args[1];
}
// If the first argument is not an attribute object but is a
// valid child, assume all arguments are children.
else if (args[0] && (args[0].nodeName ||
typeof args[0] == "string" ||
typeof args[0] == "number" ||
args[0] instanceof Tag ||
args[0] instanceof ak.template.Wrap))
{
children = args;
}
// Default - assume the first argument is an attributes object
// and all remaining arguments are children.
else
{
attributes = args[0];
children = Array.prototype.slice.call(args, 1);
}
return this.createElement(tagName, attributes, children);
},
/**
* Creates a DOM element with the given tag name and optionally,
* attributes and children.
* <p>
* If the <code>attributes</code> argument is given, any properties of
* the attributes object which have names starting with "on" and which
* have a <code>Function</code> as their value will be assigned as event
* listeners on the new element. It is assumed that a valid event name
* is set as the attribute name in this case.
* <p>
* If the <code>children</code> argument is given, its contents will be
* added to the new element. Strings or Numbers will be added as text
* nodes. It is assumed that any child passed which is not a String or
* Number will be a DOM node.
*
* @param {String} tagName an HTML tag name.
* @param {Object} [attributes] an object whose properties specify
* attributes of the new element.
* @param {Array} [children] a list of child contents, made up of mixed
* Strings, Numbers or DOM elements.
*
* @return a DOM element.
*/
createElement: function(tagName, attributes, children)
{
attributes = attributes || {};
children = children || [];
if (this.mode != "DOM")
{
return new Tag(tagName, attributes, children);
}
var element = document.createElement(tagName);
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
var value = attributes[attr];
var valueType = typeof value;
if (valueType == "function" &&
attr.toLowerCase().indexOf("on") == 0)
{
// Trust the user with the event name
this.addEvent(element,
attr.substr(2),
value);
}
else
{
if (valueType != "boolean" || value === true)
{
element.setAttribute(attr, value);
}
}
}
}
for (var i = 0, l = children.length; i < l; i++)
{
var child = children[i];
var childType = typeof child;
if (childType == "string" || childType == "number")
{
element.appendChild(document.createTextNode(child));
}
else
{
// Trust the user to pass DOM elements
element.appendChild(child);
}
}
return element;
},
/**
* Utility method for adding event handlers
*
* @param element a DOM element.
* @param {String} eventName an event name, without the
* <code>"on"</code> prefix.
* @param {Function} handler an event handling function.
*/
addEvent: function(element, eventName, handler)
{
return element.addEventListener(eventName, handler, false);
},
/**
* Utility method for removing event handlers added using DOMBuilder.
*
* @param element a DOM element.
* @param {String} eventName an event name, without the
* <code>"on"</code> prefix.
* @param {Function} handler an event handling function.
*/
removeEvent: function(element, eventName, handler)
{
element.removeEventListener(eventName, handler, false);
}
};
// Detect IE and modify DOMBuilder as required
if (/*@cc_on @*//*@if (@_win32)!/*@end @*/false)
{
/**
* Translations for attribute names which IE would otherwise choke on.
*/
o.ATTR_TRANSLATIONS =
{
"class": "className",
"for": "htmlFor"
};
/**
* Deals with special cases related to setting attributes in IE.
*
* @param element a DOM element.
* @param {String} attr an attribute name.
* @param {String} value a value for the attribute.
*/
o.setAttribute = function(element, attr, value)
{
if (this.ATTR_TRANSLATIONS.hasOwnProperty(attr))
{
element[this.ATTR_TRANSLATIONS[attr]] = value;
}
else if (attr == "style")
{
element.style.cssText = value;
}
else
{
if (typeof value != "boolean" || value === true)
{
element.setAttribute(attr, value);
}
}
};
/**
* Adds an event handler to a DOM element in IE.
* <p>
* This function is taken from http://fn-js.info/snippets/addevent
*
* @param element a DOM element.
* @param {String} eventName an event name, without the
* <code>"on"</code> prefix.
* @param {Function} handler an event handling function.
*/
o.addEvent = function(element, eventName, handler)
{
// This is to work around a bug in IE whereby the current element
// doesn't get passed as context.
// We pass it via closure instead and set it as the context using
// call().
// This needs to be stored for removeEvent().
// We also store the original wrapped function as a property, _w.
((element._evts = element._evts || [])[element._evts.length]
= function(e) { return handler.call(element, e); })._w = handler;
return element.attachEvent("on" + eventName,
element._evts[element._evts.length - 1]);
};
/**
* Removes an event handler from a DOM element in IE.
* <p>
* This function is taken from http://fn-js.info/snippets/addevent
*
* @param element a DOM element.
* @param {String} eventName an event name, without the
* <code>"on"</code> prefix.
* @param {Function} handler an event handling function.
*/
o.removeEvent = function(element, eventName, handler)
{
for (var evts = el._evts || [], i = evts.length; i--; )
if (evts[i]._w === f)
el.detachEvent("on" + eventName, evts.splice(i, 1)[0]);
};
// This is a lot of copying and pasting - it's that or splitting out all
// the common parts into needless function calls just because IE exists.
o.createElement = function(tagName, attributes, children)
{
attributes = attributes || {};
children = children || [];
if (this.mode != "DOM")
{
return new Tag(tagName, attributes, children);
}
// See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
if (attributes.hasOwnProperty("name") ||
attributes.hasOwnProperty("checked") ||
attributes.hasOwnProperty("multiple"))
{
var tagParts = ["<" + tagName];
if (attributes.hasOwnProperty("name"))
{
tagParts[tagParts.length] =
' name="' + attributes.name + '"';
}
if (attributes.hasOwnProperty("checked") &&
"" + attributes.checked == "true")
{
tagParts[tagParts.length] = " checked";
}
if (attributes.hasOwnProperty("multiple") &&
"" + attributes.multiple == "true")
{
tagParts[tagParts.length] = " multiple";
}
tagParts[tagParts.length] = ">";
var element =
document.createElement(tagParts.join(""));
}
else
{
var element = document.createElement(tagName);
}
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
if (typeof attributes[attr] == "function" &&
attr.toLowerCase().indexOf("on") == 0)
{
// Trust the user with the event name
this.addEvent(element,
attr.substr(2),
attributes[attr]);
}
else
{
this.setAttribute(element, attr, attributes[attr]);
}
}
}
for (var i = 0, l = children.length; i < l; i++)
{
var child = children[i];
var childType = typeof child;
if (childType == "string" || childType == "number")
{
element.appendChild(document.createTextNode(child));
}
else
{
// Trust the user to pass DOM elements
element.appendChild(child);
}
}
return element;
};
}
// Expose escaping-related utility functions
o.isSafe = isSafe;
o.markSafe = markSafe;
return o;
})();