Skip to content

Commit

Permalink
fix(useElementSize): fix incorrect element size on SVG (#2661)
Browse files Browse the repository at this point in the history
Co-authored-by: wheat <jacobrclevenger@gmail.com>
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
3 people committed Jan 29, 2023
1 parent 54f4e72 commit 902b3cc
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions packages/core/useElementSize/index.ts
@@ -1,8 +1,9 @@
import { ref, watch } from 'vue-demi'
import { computed, ref, watch } from 'vue-demi'
import type { MaybeComputedElementRef } from '../unrefElement'
import type { UseResizeObserverOptions } from '../useResizeObserver'
import { useResizeObserver } from '../useResizeObserver'
import { unrefElement } from '../unrefElement'
import { defaultWindow } from '../_configurable'

export interface ElementSize {
width: number
Expand All @@ -22,7 +23,8 @@ export function useElementSize(
initialSize: ElementSize = { width: 0, height: 0 },
options: UseResizeObserverOptions = {},
) {
const { box = 'content-box' } = options
const { window = defaultWindow, box = 'content-box' } = options
const isSVG = computed(() => unrefElement(target)?.namespaceURI?.includes('svg'))
const width = ref(initialSize.width)
const height = ref(initialSize.height)

Expand All @@ -35,15 +37,25 @@ export function useElementSize(
? entry.contentBoxSize
: entry.devicePixelContentBoxSize

if (boxSize) {
const formatBoxSize = Array.isArray(boxSize) ? boxSize : [boxSize]
width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0)
height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0)
if (window && isSVG.value) {
const $elem = unrefElement(target)
if ($elem) {
const styles = window.getComputedStyle($elem)
width.value = parseFloat(styles.width)
height.value = parseFloat(styles.height)
}
}
else {
// fallback
width.value = entry.contentRect.width
height.value = entry.contentRect.height
if (boxSize) {
const formatBoxSize = Array.isArray(boxSize) ? boxSize : [boxSize]
width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0)
height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0)
}
else {
// fallback
width.value = entry.contentRect.width
height.value = entry.contentRect.height
}
}
},
options,
Expand Down

0 comments on commit 902b3cc

Please sign in to comment.