react / react-0.13.3 / examples / basic-commonjs / node_modules / reactify / node_modules / react-tools / src / browser / ui / dom / getNodeForCharacterOffset.js
81159 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 getNodeForCharacterOffset9*/1011"use strict";1213/**14* Given any node return the first leaf node without children.15*16* @param {DOMElement|DOMTextNode} node17* @return {DOMElement|DOMTextNode}18*/19function getLeafNode(node) {20while (node && node.firstChild) {21node = node.firstChild;22}23return node;24}2526/**27* Get the next sibling within a container. This will walk up the28* DOM if a node's siblings have been exhausted.29*30* @param {DOMElement|DOMTextNode} node31* @return {?DOMElement|DOMTextNode}32*/33function getSiblingNode(node) {34while (node) {35if (node.nextSibling) {36return node.nextSibling;37}38node = node.parentNode;39}40}4142/**43* Get object describing the nodes which contain characters at offset.44*45* @param {DOMElement|DOMTextNode} root46* @param {number} offset47* @return {?object}48*/49function getNodeForCharacterOffset(root, offset) {50var node = getLeafNode(root);51var nodeStart = 0;52var nodeEnd = 0;5354while (node) {55if (node.nodeType == 3) {56nodeEnd = nodeStart + node.textContent.length;5758if (nodeStart <= offset && nodeEnd >= offset) {59return {60node: node,61offset: offset - nodeStart62};63}6465nodeStart = nodeEnd;66}6768node = getLeafNode(getSiblingNode(node));69}70}7172module.exports = getNodeForCharacterOffset;737475