nice-ui
Version:
React design system, components, and utilities
84 lines (83 loc) • 3.06 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MoveToViewport = void 0;
const React = require("react");
class MovementState {
constructor(gap = 4, vertical = false) {
this.gap = gap;
this.vertical = vertical;
this.div = null;
this.dx = 0;
this.dy = 0;
this.move = () => {
const { div } = this;
if (!div)
return;
const rect = div.getBoundingClientRect();
const { x, y, width, height } = rect;
if (!width || !height)
return;
const leftSpace = x - this.gap;
if (leftSpace < 0) {
this.dx += -leftSpace;
}
else if (leftSpace > 0) {
if (this.dx > 0)
this.dx = Math.max(0, this.dx - leftSpace);
else {
const rightSpace = window.innerWidth - x - width - this.gap;
if (rightSpace < 0)
this.dx += rightSpace;
else if (rightSpace > 0) {
if (this.dx < 0)
this.dx = Math.min(0, this.dx + rightSpace);
}
}
}
if (this.vertical) {
const topSpace = y - this.gap;
if (topSpace < 0) {
this.dy += -topSpace;
}
else if (topSpace > 0) {
if (this.dy > 0)
this.dy = Math.max(0, this.dy - topSpace);
else {
const bottomSpace = window.innerHeight - y - height - this.gap;
if (bottomSpace < 0)
this.dy += bottomSpace;
else if (bottomSpace > 0) {
if (this.dy < 0)
this.dy = Math.min(0, this.dy + bottomSpace);
}
}
}
}
const style = div.style;
style.left = this.dx + 'px';
if (this.vertical)
style.top = this.dy + 'px';
};
this.start = () => {
window.addEventListener('resize', this.move);
const timer = setTimeout(this.move, 25);
return () => {
window.removeEventListener('resize', this.move);
clearTimeout(timer);
};
};
this.ref = (div) => {
this.div = div;
this.move();
};
}
}
/**
* Moves the contents into the viewport if it is rendered outside of it.
*/
const MoveToViewport = ({ gap, vertical, children, ...attr }) => {
const state = React.useMemo(() => new MovementState(gap, vertical), [gap, vertical]);
React.useEffect(state.start, [state]);
return (React.createElement("span", { ref: state.ref, style: { position: 'relative' }, ...attr }, children));
};
exports.MoveToViewport = MoveToViewport;