forked from emberjs/ember.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender_buffer.js
600 lines (491 loc) · 16.1 KB
/
render_buffer.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
/**
@module ember
@submodule ember-views
*/
import jQuery from "ember-views/system/jquery";
import Ember from "ember-metal/core";
import create from 'ember-metal/platform/create';
import environment from "ember-metal/environment";
import { normalizeProperty } from "morph/dom-helper/prop";
// The HTML spec allows for "omitted start tags". These tags are optional
// when their intended child is the first thing in the parent tag. For
// example, this is a tbody start tag:
//
// <table>
// <tbody>
// <tr>
//
// The tbody may be omitted, and the browser will accept and render:
//
// <table>
// <tr>
//
// However, the omitted start tag will still be added to the DOM. Here
// we test the string and context to see if the browser is about to
// perform this cleanup, but with a special allowance for disregarding
// <script tags. This disregarding of <script being the first child item
// may bend the official spec a bit, and is only needed for Handlebars
// templates.
//
// http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
// describes which tags are omittable. The spec for tbody and colgroup
// explains this behavior:
//
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-tbody-element
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-colgroup-element
//
var omittedStartTagChildren;
var omittedStartTagChildTest = /(?:<script)*.*?<([\w:]+)/i;
function detectOmittedStartTag(dom, string, contextualElement) {
omittedStartTagChildren = omittedStartTagChildren || {
tr: dom.createElement('tbody'),
col: dom.createElement('colgroup')
};
// Omitted start tags are only inside table tags.
if (contextualElement.tagName === 'TABLE') {
var omittedStartTagChildMatch = omittedStartTagChildTest.exec(string);
if (omittedStartTagChildMatch) {
// It is already asserted that the contextual element is a table
// and not the proper start tag. Just look up the start tag.
return omittedStartTagChildren[omittedStartTagChildMatch[1].toLowerCase()];
}
}
}
function ClassSet() {
this.seen = create(null);
this.list = [];
}
ClassSet.prototype = {
add: function(string) {
if (this.seen[string] === true) { return; }
this.seen[string] = true;
this.list.push(string);
}
};
var BAD_TAG_NAME_TEST_REGEXP = /[^a-zA-Z0-9\-]/;
var BAD_TAG_NAME_REPLACE_REGEXP = /[^a-zA-Z0-9\-]/g;
function stripTagName(tagName) {
if (!tagName) {
return tagName;
}
if (!BAD_TAG_NAME_TEST_REGEXP.test(tagName)) {
return tagName;
}
return tagName.replace(BAD_TAG_NAME_REPLACE_REGEXP, '');
}
var BAD_CHARS_REGEXP = /&(?!\w+;)|[<>"'`]/g;
var POSSIBLE_CHARS_REGEXP = /[&<>"'`]/;
function escapeAttribute(value) {
// Stolen shamelessly from Handlebars
var escape = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
};
var escapeChar = function(chr) {
return escape[chr] || "&";
};
var string = value.toString();
if (!POSSIBLE_CHARS_REGEXP.test(string)) { return string; }
return string.replace(BAD_CHARS_REGEXP, escapeChar);
}
// IE 6/7 have bugs around setting names on inputs during creation.
// From http://msdn.microsoft.com/en-us/library/ie/ms536389(v=vs.85).aspx:
// "To include the NAME attribute at run time on objects created with the createElement method, use the eTag."
var canSetNameOnInputs = (function() {
if (!environment.hasDOM) { return false; }
var div = document.createElement('div');
var el = document.createElement('input');
el.setAttribute('name', 'foo');
div.appendChild(el);
return !!div.innerHTML.match('foo');
})();
/**
`Ember.RenderBuffer` gathers information regarding the view and generates the
final representation. `Ember.RenderBuffer` will generate HTML which can be pushed
to the DOM.
```javascript
var buffer = new Ember.RenderBuffer('div', contextualElement);
```
@method renderBuffer
@namespace Ember
@param {String} tagName tag name (such as 'div' or 'p') used for the buffer
*/
var RenderBuffer = function(domHelper) {
this.buffer = null;
this.childViews = [];
Ember.assert("RenderBuffer requires a DOM helper to be passed to its constructor.", !!domHelper);
this.dom = domHelper;
};
RenderBuffer.prototype = {
reset: function(tagName, contextualElement) {
this.tagName = tagName;
this.buffer = null;
this._element = null;
this._outerContextualElement = contextualElement;
this.elementClasses = null;
this.elementId = null;
this.elementAttributes = null;
this.elementProperties = null;
this.elementTag = null;
this.elementStyle = null;
this.childViews.length = 0;
},
// The root view's element
_element: null,
// The root view's contextualElement
_outerContextualElement: null,
/**
An internal set used to de-dupe class names when `addClass()` is
used. After each call to `addClass()`, the `classes` property
will be updated.
@private
@property elementClasses
@type Array
@default null
*/
elementClasses: null,
/**
Array of class names which will be applied in the class attribute.
You can use `setClasses()` to set this property directly. If you
use `addClass()`, it will be maintained for you.
@property classes
@type Array
@default null
*/
classes: null,
/**
The id in of the element, to be applied in the id attribute.
You should not set this property yourself, rather, you should use
the `id()` method of `Ember.RenderBuffer`.
@property elementId
@type String
@default null
*/
elementId: null,
/**
A hash keyed on the name of the attribute and whose value will be
applied to that attribute. For example, if you wanted to apply a
`data-view="Foo.bar"` property to an element, you would set the
elementAttributes hash to `{'data-view':'Foo.bar'}`.
You should not maintain this hash yourself, rather, you should use
the `attr()` method of `Ember.RenderBuffer`.
@property elementAttributes
@type Hash
@default {}
*/
elementAttributes: null,
/**
A hash keyed on the name of the properties and whose value will be
applied to that property. For example, if you wanted to apply a
`checked=true` property to an element, you would set the
elementProperties hash to `{'checked':true}`.
You should not maintain this hash yourself, rather, you should use
the `prop()` method of `Ember.RenderBuffer`.
@property elementProperties
@type Hash
@default {}
*/
elementProperties: null,
/**
The tagname of the element an instance of `Ember.RenderBuffer` represents.
Usually, this gets set as the first parameter to `Ember.RenderBuffer`. For
example, if you wanted to create a `p` tag, then you would call
```javascript
Ember.RenderBuffer('p', contextualElement)
```
@property elementTag
@type String
@default null
*/
elementTag: null,
/**
A hash keyed on the name of the style attribute and whose value will
be applied to that attribute. For example, if you wanted to apply a
`background-color:black;` style to an element, you would set the
elementStyle hash to `{'background-color':'black'}`.
You should not maintain this hash yourself, rather, you should use
the `style()` method of `Ember.RenderBuffer`.
@property elementStyle
@type Hash
@default {}
*/
elementStyle: null,
pushChildView: function (view) {
var index = this.childViews.length;
this.childViews[index] = view;
this.push("<script id='morph-"+index+"' type='text/x-placeholder'>\x3C/script>");
},
hydrateMorphs: function (contextualElement) {
var childViews = this.childViews;
var el = this._element;
for (var i=0,l=childViews.length; i<l; i++) {
var childView = childViews[i];
var ref = el.querySelector('#morph-'+i);
Ember.assert('An error occurred while setting up template bindings. Please check ' +
(childView && childView._parentView && childView._parentView._debugTemplateName ?
'"' + childView._parentView._debugTemplateName + '" template ' :
''
) + 'for invalid markup or bindings within HTML comments.',
ref);
var parent = ref.parentNode;
childView._morph = this.dom.insertMorphBefore(
parent,
ref,
parent.nodeType === 1 ? parent : contextualElement
);
parent.removeChild(ref);
}
},
/**
Adds a string of HTML to the `RenderBuffer`.
@method push
@param {String} string HTML to push into the buffer
@chainable
*/
push: function(content) {
if (typeof content === 'string') {
if (this.buffer === null) {
this.buffer = '';
}
Ember.assert("A string cannot be pushed into the buffer after a fragment", !this.buffer.nodeType);
this.buffer += content;
} else {
Ember.assert("A fragment cannot be pushed into a buffer that contains content", !this.buffer);
this.buffer = content;
}
return this;
},
/**
Adds a class to the buffer, which will be rendered to the class attribute.
@method addClass
@param {String} className Class name to add to the buffer
@chainable
*/
addClass: function(className) {
// lazily create elementClasses
this.elementClasses = (this.elementClasses || new ClassSet());
this.elementClasses.add(className);
this.classes = this.elementClasses.list;
return this;
},
setClasses: function(classNames) {
this.elementClasses = null;
var len = classNames.length;
var i;
for (i = 0; i < len; i++) {
this.addClass(classNames[i]);
}
},
/**
Sets the elementID to be used for the element.
@method id
@param {String} id
@chainable
*/
id: function(id) {
this.elementId = id;
return this;
},
// duck type attribute functionality like jQuery so a render buffer
// can be used like a jQuery object in attribute binding scenarios.
/**
Adds an attribute which will be rendered to the element.
@method attr
@param {String} name The name of the attribute
@param {String} value The value to add to the attribute
@chainable
@return {Ember.RenderBuffer|String} this or the current attribute value
*/
attr: function(name, value) {
var attributes = this.elementAttributes = (this.elementAttributes || {});
if (arguments.length === 1) {
return attributes[name];
} else {
attributes[name] = value;
}
return this;
},
/**
Remove an attribute from the list of attributes to render.
@method removeAttr
@param {String} name The name of the attribute
@chainable
*/
removeAttr: function(name) {
var attributes = this.elementAttributes;
if (attributes) { delete attributes[name]; }
return this;
},
/**
Adds a property which will be rendered to the element.
@method prop
@param {String} name The name of the property
@param {String} value The value to add to the property
@chainable
@return {Ember.RenderBuffer|String} this or the current property value
*/
prop: function(name, value) {
var properties = this.elementProperties = (this.elementProperties || {});
if (arguments.length === 1) {
return properties[name];
} else {
properties[name] = value;
}
return this;
},
/**
Remove an property from the list of properties to render.
@method removeProp
@param {String} name The name of the property
@chainable
*/
removeProp: function(name) {
var properties = this.elementProperties;
if (properties) { delete properties[name]; }
return this;
},
/**
Adds a style to the style attribute which will be rendered to the element.
@method style
@param {String} name Name of the style
@param {String} value
@chainable
*/
style: function(name, value) {
this.elementStyle = (this.elementStyle || {});
this.elementStyle[name] = value;
return this;
},
generateElement: function() {
var tagName = this.tagName;
var id = this.elementId;
var classes = this.classes;
var attrs = this.elementAttributes;
var props = this.elementProperties;
var style = this.elementStyle;
var styleBuffer = '';
var attr, prop, tagString;
if (attrs && attrs.name && !canSetNameOnInputs) {
// IE allows passing a tag to createElement. See note on `canSetNameOnInputs` above as well.
tagString = '<'+stripTagName(tagName)+' name="'+escapeAttribute(attrs.name)+'">';
} else {
tagString = tagName;
}
var element = this.dom.createElement(tagString, this.outerContextualElement());
if (id) {
this.dom.setAttribute(element, 'id', id);
this.elementId = null;
}
if (classes) {
this.dom.setAttribute(element, 'class', classes.join(' '));
this.classes = null;
this.elementClasses = null;
}
if (style) {
for (prop in style) {
styleBuffer += (prop + ':' + style[prop] + ';');
}
this.dom.setAttribute(element, 'style', styleBuffer);
this.elementStyle = null;
}
if (attrs) {
for (attr in attrs) {
this.dom.setAttribute(element, attr, attrs[attr]);
}
this.elementAttributes = null;
}
if (props) {
for (prop in props) {
var normalizedCase = normalizeProperty(element, prop.toLowerCase()) || prop;
this.dom.setPropertyStrict(element, normalizedCase, props[prop]);
}
this.elementProperties = null;
}
this._element = element;
},
/**
@method element
@return {DOMElement} The element corresponding to the generated HTML
of this buffer
*/
element: function() {
var content = this.innerContent();
// No content means a text node buffer, with the content
// in _element. Ember._BoundView is an example.
if (content === null) {
return this._element;
}
var contextualElement = this.innerContextualElement(content);
this.dom.detectNamespace(contextualElement);
if (!this._element) {
this._element = this.dom.createDocumentFragment();
}
if (content.nodeType) {
this._element.appendChild(content);
} else {
var nodes;
nodes = this.dom.parseHTML(content, contextualElement);
while (nodes[0]) {
this._element.appendChild(nodes[0]);
}
}
// This should only happen with legacy string buffers
if (this.childViews.length > 0) {
this.hydrateMorphs(contextualElement);
}
return this._element;
},
/**
Generates the HTML content for this buffer.
@method string
@return {String} The generated HTML
*/
string: function() {
if (this._element) {
// Firefox versions < 11 do not have support for element.outerHTML.
var thisElement = this.element();
var outerHTML = thisElement.outerHTML;
if (typeof outerHTML === 'undefined') {
return jQuery('<div/>').append(thisElement).html();
}
return outerHTML;
} else {
return this.innerString();
}
},
outerContextualElement: function() {
if (this._outerContextualElement === undefined) {
Ember.deprecate("The render buffer expects an outer contextualElement to exist." +
" This ensures DOM that requires context is correctly generated (tr, SVG tags)." +
" Defaulting to document.body, but this will be removed in the future");
this.outerContextualElement = document.body;
}
return this._outerContextualElement;
},
innerContextualElement: function(html) {
var innerContextualElement;
if (this._element && this._element.nodeType === 1) {
innerContextualElement = this._element;
} else {
innerContextualElement = this.outerContextualElement();
}
var omittedStartTag;
if (html) {
omittedStartTag = detectOmittedStartTag(this.dom, html, innerContextualElement);
}
return omittedStartTag || innerContextualElement;
},
innerString: function() {
var content = this.innerContent();
if (content && !content.nodeType) {
return content;
}
},
innerContent: function() {
return this.buffer;
}
};
export default RenderBuffer;