Skip to content

Commit 4e49c17

Browse files
committed
Fix window getting outside viewport when resized
1 parent e6cd022 commit 4e49c17

1 file changed

Lines changed: 23 additions & 5 deletions

File tree

‎app/components/Window.tsx‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ const Window: React.FC<WindowProps> = ({
2121
zIndex,
2222
onFocus,
2323
}) => {
24-
/* State */
2524
const [position, setPosition] = useState({ x: 0, y: 0 });
2625
const [isDragging, setIsDragging] = useState(false);
2726
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
@@ -36,6 +35,29 @@ const Window: React.FC<WindowProps> = ({
3635
}
3736
}, [isPositioned]);
3837

38+
// Constrain window position on viewport resize
39+
useEffect(() => {
40+
const handleResize = () => {
41+
if (!windowRef.current || !isPositioned) return;
42+
43+
const rect = windowRef.current.getBoundingClientRect();
44+
45+
// Allow 50% of the window to be off-screen on left/right/bottom
46+
const minX = -rect.width / 2;
47+
const maxX = window.innerWidth - (rect.width / 2);
48+
const maxY = window.innerHeight - (rect.height / 2);
49+
const minY = 0;
50+
51+
setPosition(prev => ({
52+
x: Math.max(minX, Math.min(prev.x, maxX)),
53+
y: Math.max(minY, Math.min(prev.y, maxY)),
54+
}));
55+
};
56+
57+
window.addEventListener('resize', handleResize);
58+
return () => window.removeEventListener('resize', handleResize);
59+
}, [isPositioned]);
60+
3961
useEffect(() => {
4062
const handleMouseMove = (e: MouseEvent) => {
4163
if (isDragging && windowRef.current) {
@@ -49,8 +71,6 @@ const Window: React.FC<WindowProps> = ({
4971
const minX = -rect.width / 2;
5072
const maxX = window.innerWidth - (rect.width / 2);
5173
const maxY = window.innerHeight - (rect.height / 2);
52-
53-
// Strict top boundary (cannot go above 0)
5474
const minY = 0;
5575

5676
newX = Math.max(minX, Math.min(newX, maxX));
@@ -76,8 +96,6 @@ const Window: React.FC<WindowProps> = ({
7696
const minX = -rect.width / 2;
7797
const maxX = window.innerWidth - (rect.width / 2);
7898
const maxY = window.innerHeight - (rect.height / 2);
79-
80-
// Strict top boundary (cannot go above 0)
8199
const minY = 0;
82100

83101
newX = Math.max(minX, Math.min(newX, maxX));

0 commit comments

Comments
 (0)