| 1 |
/** |
| 2 |
* Pick mini-inserter `position` before mount. Core's size middleware clamps to |
| 3 |
* the initial side and blocks flip, so decide top vs bottom from the anchor rect. |
| 4 |
*/ |
| 5 |
|
| 6 |
/** Popover's own viewport inset, `OVERFLOW_PADDING` in @wordpress/components. */ |
| 7 |
const OVERFLOW_PADDING = 8; |
| 8 |
|
| 9 |
/** Comfortable height below the anchor before preferring top. */ |
| 10 |
const COMFORTABLE_HEIGHT = 520; |
| 11 |
|
| 12 |
/** |
| 13 |
* Element rect in main-document viewport coords (adds iframe offset when needed). |
| 14 |
* |
| 15 |
* @param {?Element} element |
| 16 |
* @return {?Object} `{ top, bottom, left, right, width, height }`, or null. |
| 17 |
*/ |
| 18 |
export const mainDocumentRect = ( element ) => { |
| 19 |
if ( ! element ) return null; |
| 20 |
|
| 21 |
const rect = element.getBoundingClientRect(); |
| 22 |
const frame = element.ownerDocument?.defaultView?.frameElement; |
| 23 |
if ( ! frame ) { |
| 24 |
return rect; |
| 25 |
} |
| 26 |
|
| 27 |
const frameRect = frame.getBoundingClientRect(); |
| 28 |
return { |
| 29 |
top: rect.top + frameRect.top, |
| 30 |
bottom: rect.bottom + frameRect.top, |
| 31 |
left: rect.left + frameRect.left, |
| 32 |
right: rect.right + frameRect.left, |
| 33 |
width: rect.width, |
| 34 |
height: rect.height, |
| 35 |
}; |
| 36 |
}; |
| 37 |
|
| 38 |
/** |
| 39 |
* `'top center'` when below is short and above is larger; else `'bottom center'`. |
| 40 |
* |
| 41 |
* @param {?Object} rect Anchor rect in main-document viewport coordinates. |
| 42 |
* @return {string} |
| 43 |
*/ |
| 44 |
export const resolveMiniInserterPosition = ( rect ) => { |
| 45 |
if ( ! rect ) return 'bottom center'; |
| 46 |
|
| 47 |
const below = window.innerHeight - rect.bottom - OVERFLOW_PADDING; |
| 48 |
const above = rect.top - OVERFLOW_PADDING; |
| 49 |
|
| 50 |
return below < Math.min( COMFORTABLE_HEIGHT, above ) ? 'top center' : 'bottom center'; |
| 51 |
}; |
| 52 |
|
| 53 |
/** |
| 54 |
* `resolveMiniInserterPosition` straight from the anchor element. |
| 55 |
* |
| 56 |
* @param {?Element} element |
| 57 |
* @return {string} `'top center'` or `'bottom center'`. |
| 58 |
*/ |
| 59 |
export const resolveMiniInserterPositionFor = ( element ) => |
| 60 |
resolveMiniInserterPosition( mainDocumentRect( element ) ); |
| 61 |
|