Skip to content

Commit

Permalink
feat(useElementSize): support box sizing (#2143)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
vaakian and antfu committed Sep 5, 2022
1 parent fbc8959 commit 3c642b7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
8 changes: 7 additions & 1 deletion packages/core/useElementSize/demo.vue
Expand Up @@ -4,7 +4,13 @@ import { stringify } from '@vueuse/docs-utils'
import { useElementSize } from '@vueuse/core'
const el = ref(null)
const size = reactive(useElementSize(el))
const size = reactive(
useElementSize(
el,
{ width: 0, height: 0 },
{ box: 'border-box' },
),
)
const text = stringify(size)
</script>

Expand Down
31 changes: 25 additions & 6 deletions packages/core/useElementSize/index.ts
Expand Up @@ -22,21 +22,40 @@ export function useElementSize(
initialSize: ElementSize = { width: 0, height: 0 },
options: UseResizeObserverOptions = {},
) {
const { box = 'content-box' } = options
const width = ref(initialSize.width)
const height = ref(initialSize.height)

useResizeObserver(
target,
([entry]) => {
width.value = entry.contentRect.width
height.value = entry.contentRect.height
const boxSize = box === 'border-box'
? entry.borderBoxSize
: box === 'content-box'
? entry.contentBoxSize
: entry.devicePixelContentBoxSize

if (boxSize) {
width.value = boxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0)
height.value = boxSize.reduce((acc, { blockSize }) => acc + blockSize, 0)
}
else {
// fallback
width.value = entry.contentRect.width
height.value = entry.contentRect.height
}
},
options,
)
watch(() => unrefElement(target), (ele) => {
width.value = ele ? initialSize.width : 0
height.value = ele ? initialSize.height : 0
})

watch(
() => unrefElement(target),
(ele) => {
width.value = ele ? initialSize.width : 0
height.value = ele ? initialSize.height : 0
},
)

return {
width,
height,
Expand Down
4 changes: 2 additions & 2 deletions packages/core/useResizeObserver/index.ts
Expand Up @@ -24,11 +24,11 @@ export type ResizeObserverCallback = (entries: ReadonlyArray<ResizeObserverEntry
export interface UseResizeObserverOptions extends ConfigurableWindow {
/**
* Sets which box model the observer will observe changes to. Possible values
* are `content-box` (the default), and `border-box`.
* are `content-box` (the default), `border-box` and `device-pixel-content-box`.
*
* @default 'content-box'
*/
box?: 'content-box' | 'border-box'
box?: ResizeObserverBoxOptions
}

declare class ResizeObserver {
Expand Down

0 comments on commit 3c642b7

Please sign in to comment.