Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useElementSize): support box sizing #2143

Merged
merged 5 commits into from Sep 5, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/core/useElementSize/demo.vue
Expand Up @@ -4,7 +4,9 @@ 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
16 changes: 14 additions & 2 deletions packages/core/useElementSize/index.ts
Expand Up @@ -22,14 +22,26 @@ 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,
)
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