2021-12-12 23:28:03 +08:00
|
|
|
import { isClient } from '@vueuse/core'
|
2020-07-28 00:32:04 +08:00
|
|
|
|
2022-02-11 11:03:15 +08:00
|
|
|
import type { HTMLElementCustomized } from '../typescript'
|
2021-08-24 13:36:48 +08:00
|
|
|
|
2022-02-09 16:59:08 +08:00
|
|
|
export type ResizableElement = HTMLElementCustomized<{
|
2021-09-13 12:02:18 +08:00
|
|
|
__resizeListeners__?: Array<(...args: unknown[]) => unknown>
|
|
|
|
__ro__?: ResizeObserver
|
2021-09-04 19:29:28 +08:00
|
|
|
}>
|
2020-07-28 00:32:04 +08:00
|
|
|
|
2021-09-04 19:29:28 +08:00
|
|
|
const resizeHandler = function (entries: ResizeObserverEntry[]) {
|
2020-07-28 00:32:04 +08:00
|
|
|
for (const entry of entries) {
|
|
|
|
const listeners =
|
|
|
|
(entry.target as ResizableElement).__resizeListeners__ || []
|
|
|
|
if (listeners.length) {
|
2021-09-04 19:29:28 +08:00
|
|
|
listeners.forEach((fn) => {
|
2020-07-28 00:32:04 +08:00
|
|
|
fn()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-11 11:03:15 +08:00
|
|
|
/** @deprecated use `useResizeObserver` or `useElementSize` in vueuse */
|
2021-09-04 19:29:28 +08:00
|
|
|
export const addResizeListener = function (
|
2020-07-28 00:32:04 +08:00
|
|
|
element: ResizableElement,
|
2021-09-04 19:29:28 +08:00
|
|
|
fn: (...args: unknown[]) => unknown
|
2020-07-29 15:09:29 +08:00
|
|
|
): void {
|
2021-12-12 23:28:03 +08:00
|
|
|
if (!isClient || !element) return
|
2020-07-28 00:32:04 +08:00
|
|
|
if (!element.__resizeListeners__) {
|
|
|
|
element.__resizeListeners__ = []
|
|
|
|
element.__ro__ = new ResizeObserver(resizeHandler)
|
|
|
|
element.__ro__.observe(element)
|
|
|
|
}
|
|
|
|
element.__resizeListeners__.push(fn)
|
|
|
|
}
|
|
|
|
|
2022-02-11 11:03:15 +08:00
|
|
|
/** @deprecated use `useResizeObserver` or `useElementSize` in vueuse */
|
2021-09-04 19:29:28 +08:00
|
|
|
export const removeResizeListener = function (
|
2020-07-28 00:32:04 +08:00
|
|
|
element: ResizableElement,
|
2021-09-04 19:29:28 +08:00
|
|
|
fn: (...args: unknown[]) => unknown
|
2020-07-29 15:09:29 +08:00
|
|
|
): void {
|
2020-07-28 00:32:04 +08:00
|
|
|
if (!element || !element.__resizeListeners__) return
|
2021-09-04 19:29:28 +08:00
|
|
|
element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1)
|
2020-07-28 00:32:04 +08:00
|
|
|
if (!element.__resizeListeners__.length) {
|
2021-09-13 12:02:18 +08:00
|
|
|
element.__ro__?.disconnect()
|
2020-07-28 00:32:04 +08:00
|
|
|
}
|
|
|
|
}
|