@clayui/shared
Version:
ClayShared component
30 lines (29 loc) • 897 B
JavaScript
/**
* SPDX-FileCopyrightText: © 2021 Liferay, Inc. <https://liferay.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
const rectAttrs = ['bottom', 'height', 'left', 'right', 'top', 'width'];
const rectChanged = function () {
let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return rectAttrs.some(prop => a[prop] !== b[prop]);
};
let rafId;
const run = (node, state) => {
const newRect = node.getBoundingClientRect();
if (rectChanged(newRect, state.rect)) {
state.rect = newRect;
state.callback(state.rect);
}
rafId = window.requestAnimationFrame(() => run(node, state));
};
export const observeRect = (node, callback) => {
run(node, {
callback,
hasRectChanged: false,
rect: undefined
});
return () => {
cancelAnimationFrame(rafId);
};
};