2020-07-28 00:32:04 +08:00
|
|
|
import ResizeObserver from 'resize-observer-polyfill'
|
|
|
|
import isServer from './isServer'
|
|
|
|
|
2021-08-24 13:36:48 +08:00
|
|
|
import type { CustomizedHTMLElement } from './types'
|
|
|
|
|
2020-08-23 10:35:36 +08:00
|
|
|
export type ResizableElement = CustomizedHTMLElement<{
|
2020-08-02 21:29:35 +08:00
|
|
|
__resizeListeners__: Array<(...args: unknown[]) => unknown>
|
|
|
|
__ro__: ResizeObserver
|
2020-07-28 00:32:04 +08:00
|
|
|
}>;
|
|
|
|
|
|
|
|
/* istanbul ignore next */
|
|
|
|
const resizeHandler = function(entries: ResizeObserverEntry[]) {
|
|
|
|
for (const entry of entries) {
|
|
|
|
const listeners =
|
|
|
|
(entry.target as ResizableElement).__resizeListeners__ || []
|
|
|
|
if (listeners.length) {
|
|
|
|
listeners.forEach(fn => {
|
|
|
|
fn()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/* istanbul ignore next */
|
|
|
|
export const addResizeListener = function(
|
|
|
|
element: ResizableElement,
|
2020-07-29 15:09:29 +08:00
|
|
|
fn: (...args: unknown[]) => unknown,
|
|
|
|
): void {
|
2020-10-30 23:26:33 +08:00
|
|
|
if (isServer || !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)
|
|
|
|
}
|
|
|
|
|
|
|
|
/* istanbul ignore next */
|
|
|
|
export const removeResizeListener = function(
|
|
|
|
element: ResizableElement,
|
2020-07-29 15:09:29 +08:00
|
|
|
fn: (...args: unknown[]) => unknown,
|
|
|
|
): void {
|
2020-07-28 00:32:04 +08:00
|
|
|
if (!element || !element.__resizeListeners__) return
|
|
|
|
element.__resizeListeners__.splice(
|
|
|
|
element.__resizeListeners__.indexOf(fn),
|
|
|
|
1,
|
|
|
|
)
|
|
|
|
if (!element.__resizeListeners__.length) {
|
|
|
|
element.__ro__.disconnect()
|
|
|
|
}
|
|
|
|
}
|