react / react-0.13.3 / examples / basic-commonjs / node_modules / reactify / node_modules / react-tools / src / vendor / core / createNodesFromMarkup.js
81158 views/**1* Copyright 2013-2014, Facebook, Inc.2* All rights reserved.3*4* This source code is licensed under the BSD-style license found in the5* LICENSE file in the root directory of this source tree. An additional grant6* of patent rights can be found in the PATENTS file in the same directory.7*8* @providesModule createNodesFromMarkup9* @typechecks10*/1112/*jslint evil: true, sub: true */1314var ExecutionEnvironment = require('ExecutionEnvironment');1516var createArrayFrom = require('createArrayFrom');17var getMarkupWrap = require('getMarkupWrap');18var invariant = require('invariant');1920/**21* Dummy container used to render all markup.22*/23var dummyNode =24ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;2526/**27* Pattern used by `getNodeName`.28*/29var nodeNamePattern = /^\s*<(\w+)/;3031/**32* Extracts the `nodeName` of the first element in a string of markup.33*34* @param {string} markup String of markup.35* @return {?string} Node name of the supplied markup.36*/37function getNodeName(markup) {38var nodeNameMatch = markup.match(nodeNamePattern);39return nodeNameMatch && nodeNameMatch[1].toLowerCase();40}4142/**43* Creates an array containing the nodes rendered from the supplied markup. The44* optionally supplied `handleScript` function will be invoked once for each45* <script> element that is rendered. If no `handleScript` function is supplied,46* an exception is thrown if any <script> elements are rendered.47*48* @param {string} markup A string of valid HTML markup.49* @param {?function} handleScript Invoked once for each rendered <script>.50* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.51*/52function createNodesFromMarkup(markup, handleScript) {53var node = dummyNode;54invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized');55var nodeName = getNodeName(markup);5657var wrap = nodeName && getMarkupWrap(nodeName);58if (wrap) {59node.innerHTML = wrap[1] + markup + wrap[2];6061var wrapDepth = wrap[0];62while (wrapDepth--) {63node = node.lastChild;64}65} else {66node.innerHTML = markup;67}6869var scripts = node.getElementsByTagName('script');70if (scripts.length) {71invariant(72handleScript,73'createNodesFromMarkup(...): Unexpected <script> element rendered.'74);75createArrayFrom(scripts).forEach(handleScript);76}7778var nodes = createArrayFrom(node.childNodes);79while (node.lastChild) {80node.removeChild(node.lastChild);81}82return nodes;83}8485module.exports = createNodesFromMarkup;868788