Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81159 views
1
/**
2
* Copyright 2013-2014, Facebook, Inc.
3
* All rights reserved.
4
*
5
* This source code is licensed under the BSD-style license found in the
6
* LICENSE file in the root directory of this source tree. An additional grant
7
* of patent rights can be found in the PATENTS file in the same directory.
8
*
9
* @providesModule setInnerHTML
10
*/
11
12
"use strict";
13
14
var ExecutionEnvironment = require('ExecutionEnvironment');
15
16
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
17
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
18
19
/**
20
* Set the innerHTML property of a node, ensuring that whitespace is preserved
21
* even in IE8.
22
*
23
* @param {DOMElement} node
24
* @param {string} html
25
* @internal
26
*/
27
var setInnerHTML = function(node, html) {
28
node.innerHTML = html;
29
};
30
31
if (ExecutionEnvironment.canUseDOM) {
32
// IE8: When updating a just created node with innerHTML only leading
33
// whitespace is removed. When updating an existing node with innerHTML
34
// whitespace in root TextNodes is also collapsed.
35
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
36
37
// Feature detection; only IE8 is known to behave improperly like this.
38
var testElement = document.createElement('div');
39
testElement.innerHTML = ' ';
40
if (testElement.innerHTML === '') {
41
setInnerHTML = function(node, html) {
42
// Magic theory: IE8 supposedly differentiates between added and updated
43
// nodes when processing innerHTML, innerHTML on updated nodes suffers
44
// from worse whitespace behavior. Re-adding a node like this triggers
45
// the initial and more favorable whitespace behavior.
46
// TODO: What to do on a detached node?
47
if (node.parentNode) {
48
node.parentNode.replaceChild(node, node);
49
}
50
51
// We also implement a workaround for non-visible tags disappearing into
52
// thin air on IE8, this only happens if there is no visible text
53
// in-front of the non-visible tags. Piggyback on the whitespace fix
54
// and simply check if any non-visible tags appear in the source.
55
if (WHITESPACE_TEST.test(html) ||
56
html[0] === '<' && NONVISIBLE_TEST.test(html)) {
57
// Recover leading whitespace by temporarily prepending any character.
58
// \uFEFF has the potential advantage of being zero-width/invisible.
59
node.innerHTML = '\uFEFF' + html;
60
61
// deleteData leaves an empty `TextNode` which offsets the index of all
62
// children. Definitely want to avoid this.
63
var textNode = node.firstChild;
64
if (textNode.data.length === 1) {
65
node.removeChild(textNode);
66
} else {
67
textNode.deleteData(0, 1);
68
}
69
} else {
70
node.innerHTML = html;
71
}
72
};
73
}
74
}
75
76
module.exports = setInnerHTML;
77
78