UNPKG

1.87 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 *
9 * @emails oncall+draft_js
10 */
11'use strict';
12
13var getRangeClientRects = require("./getRangeClientRects");
14
15/**
16 * Like range.getBoundingClientRect() but normalizes for browser bugs.
17 */
18function getRangeBoundingClientRect(range) {
19 // "Return a DOMRect object describing the smallest rectangle that includes
20 // the first rectangle in list and all of the remaining rectangles of which
21 // the height or width is not zero."
22 // http://www.w3.org/TR/cssom-view/#dom-range-getboundingclientrect
23 var rects = getRangeClientRects(range);
24 var top = 0;
25 var right = 0;
26 var bottom = 0;
27 var left = 0;
28
29 if (rects.length) {
30 // If the first rectangle has 0 width, we use the second, this is needed
31 // because Chrome renders a 0 width rectangle when the selection contains
32 // a line break.
33 if (rects.length > 1 && rects[0].width === 0) {
34 var _rects$ = rects[1];
35 top = _rects$.top;
36 right = _rects$.right;
37 bottom = _rects$.bottom;
38 left = _rects$.left;
39 } else {
40 var _rects$2 = rects[0];
41 top = _rects$2.top;
42 right = _rects$2.right;
43 bottom = _rects$2.bottom;
44 left = _rects$2.left;
45 }
46
47 for (var ii = 1; ii < rects.length; ii++) {
48 var rect = rects[ii];
49
50 if (rect.height !== 0 && rect.width !== 0) {
51 top = Math.min(top, rect.top);
52 right = Math.max(right, rect.right);
53 bottom = Math.max(bottom, rect.bottom);
54 left = Math.min(left, rect.left);
55 }
56 }
57 }
58
59 return {
60 top: top,
61 right: right,
62 bottom: bottom,
63 left: left,
64 width: right - left,
65 height: bottom - top
66 };
67}
68
69module.exports = getRangeBoundingClientRect;
\No newline at end of file