All files / src/core/dom getBoundingClientRect.ts

71.42% Statements 5/7
0% Branches 0/2
50% Functions 2/4
71.42% Lines 5/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33  1x 1x                 1x 1x                                     1x  
import { MPDOMRect, MPElement } from '../../types'
 
/**
 * 获取指定元素的大小及其相对于视口的位置
 *
 * @export
 * @param {MPElement} element
 * @return {*}  {(Promise<MPDOMRect | MPDOMRect[]>)}
 */
export function getBoundingClientRect (element: MPElement): Promise<MPDOMRect | MPDOMRect[]> {
  return new Promise((resolve) => {
    element?.fields({
      rect: true,
      size: true,
      properties: ['scrollX', 'scrollY'],
    }).exec((rects) => {
      resolve(
        Array.isArray(rects)
          ? rects.map((rect) => ({
            ...rect,
            x: rect.left,
            y: rect.top,
          } as MPDOMRect))
          : {
            ...rects,
            x: rects.left,
            y: rects.top,
          } as MPDOMRect
      )
    })
  })
}