| 1 |
import getBoundaries from '../utils/getBoundaries'; |
| 2 |
|
| 3 |
function getArea({ width, height }) { |
| 4 |
return width * height; |
| 5 |
} |
| 6 |
|
| 7 |
/** |
| 8 |
* Utility used to transform the `auto` placement to the placement with more |
| 9 |
* available space. |
| 10 |
* @method |
| 11 |
* @memberof Popper.Utils |
| 12 |
* @argument {Object} data - The data object generated by update method |
| 13 |
* @argument {Object} options - Modifiers configuration and options |
| 14 |
* @returns {Object} The data object, properly modified |
| 15 |
*/ |
| 16 |
export default function computeAutoPlacement( |
| 17 |
placement, |
| 18 |
refRect, |
| 19 |
popper, |
| 20 |
reference, |
| 21 |
boundariesElement, |
| 22 |
padding = 0 |
| 23 |
) { |
| 24 |
if (placement.indexOf('auto') === -1) { |
| 25 |
return placement; |
| 26 |
} |
| 27 |
|
| 28 |
const boundaries = getBoundaries( |
| 29 |
popper, |
| 30 |
reference, |
| 31 |
padding, |
| 32 |
boundariesElement |
| 33 |
); |
| 34 |
|
| 35 |
const rects = { |
| 36 |
top: { |
| 37 |
width: boundaries.width, |
| 38 |
height: refRect.top - boundaries.top, |
| 39 |
}, |
| 40 |
right: { |
| 41 |
width: boundaries.right - refRect.right, |
| 42 |
height: boundaries.height, |
| 43 |
}, |
| 44 |
bottom: { |
| 45 |
width: boundaries.width, |
| 46 |
height: boundaries.bottom - refRect.bottom, |
| 47 |
}, |
| 48 |
left: { |
| 49 |
width: refRect.left - boundaries.left, |
| 50 |
height: boundaries.height, |
| 51 |
}, |
| 52 |
}; |
| 53 |
|
| 54 |
const sortedAreas = Object.keys(rects) |
| 55 |
.map(key => ({ |
| 56 |
key, |
| 57 |
...rects[key], |
| 58 |
area: getArea(rects[key]), |
| 59 |
})) |
| 60 |
.sort((a, b) => b.area - a.area); |
| 61 |
|
| 62 |
const filteredAreas = sortedAreas.filter( |
| 63 |
({ width, height }) => |
| 64 |
width >= popper.clientWidth && height >= popper.clientHeight |
| 65 |
); |
| 66 |
|
| 67 |
const computedPlacement = filteredAreas.length > 0 |
| 68 |
? filteredAreas[0].key |
| 69 |
: sortedAreas[0].key; |
| 70 |
|
| 71 |
const variation = placement.split('-')[1]; |
| 72 |
|
| 73 |
return computedPlacement + (variation ? `-${variation}` : ''); |
| 74 |
} |