fix(editor): prevent eyedropper preview from overflowing viewport (#11722)

* fix(editor): prevent eyedropper preview from overflowing viewport

* generalize

---------

Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
This commit is contained in:
samirananddwelle authored and GitHub committed 2026-07-21 22:07:15 +00:00
1 parent 5cf547650b
commit 53732f08f4
12 files changed
+314 -53

No files matched your search

@@ -10,10 +10,9 @@
position: relative;
border-radius: 4px;
box-shadow: 0 3px 10px color.adjust(#000, $alpha: -0.8);
padding: 0;
list-style: none;
user-select: none;
margin: -0.25rem 0 0 0.125rem;
margin: 0;
padding: 0.5rem 0;
background-color: var(--popup-secondary-bg-color);
border: 1px solid var(--button-gray-3);
@@ -60,8 +60,6 @@ export const ContextMenu = React.memo(
top={top}
left={left}
fitInViewport={true}
offsetLeft={appState.offsetLeft}
offsetTop={appState.offsetTop}
viewportWidth={appState.width}
viewportHeight={appState.height}
className="context-menu-popover"
+13 -12
View File
@@ -6,6 +6,7 @@ import { ARROW_TYPE, EVENT } from "@excalidraw/common";
import { atom, useAtom } from "../editor-jotai";
import { useApp, useExcalidrawContainer } from "./App";
import { positionElementBesideCursor } from "./positionElementBesideCursor";
import {
LineIcon,
sharpArrowIcon,
@@ -22,7 +23,7 @@ const CURSOR_HINT_DURATION = 700;
/** fade-out duration (keep in sync with CursorHint.scss) */
const CURSOR_HINT_FADE_DURATION = 100;
/** distance from the pointer so the hint isn't covered by the cursor */
const CURSOR_HINT_OFFSET = 16;
const CURSOR_HINT_GAP = 16;
/**
* While a recently shown hint is still fresh in memory, tool-switch hints
@@ -126,17 +127,17 @@ export const CursorHint = () => {
if (!element) {
return;
}
const rect = container.getBoundingClientRect();
let x = clientX - rect.left + CURSOR_HINT_OFFSET;
let y = clientY - rect.top + CURSOR_HINT_OFFSET;
// flip to the other side of the pointer when overflowing the container
if (x + element.offsetWidth > rect.width) {
x = clientX - rect.left - CURSOR_HINT_OFFSET - element.offsetWidth;
}
if (y + element.offsetHeight > rect.height) {
y = clientY - rect.top - CURSOR_HINT_OFFSET - element.offsetHeight;
}
element.style.transform = `translate(${x}px, ${y}px)`;
const { left, top } = positionElementBesideCursor({
cursor: { x: clientX, y: clientY },
element: {
width: element.offsetWidth,
height: element.offsetHeight,
},
container: container.getBoundingClientRect(),
gap: CURSOR_HINT_GAP,
});
element.style.transform = `translate(${left}px, ${top}px)`;
};
updatePosition(app.viewport.lastPosition.x, app.viewport.lastPosition.y);
@@ -2,6 +2,8 @@
.excalidraw-eye-dropper-container,
.excalidraw-eye-dropper-backdrop {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: var(--zIndex-eyeDropperBackdrop);
@@ -20,7 +22,7 @@
pointer-events: none;
width: 3rem;
height: 3rem;
position: fixed;
position: absolute;
z-index: var(--zIndex-eyeDropperPreview);
border-radius: 1rem;
border: 1px solid var(--default-border-color);
+13 -3
View File
@@ -13,6 +13,7 @@ import { useStable } from "../hooks/useStable";
import { getSelectedElements } from "../scene";
import { useApp, useExcalidrawContainer, useExcalidrawElements } from "./App";
import { positionElementBesideCursor } from "./positionElementBesideCursor";
import "./EyeDropper.scss";
@@ -102,9 +103,18 @@ export const EyeDropper: React.FC<{
clientY: number;
altKey: boolean;
}) => {
// FIXME swap offset when the preview gets outside viewport
colorPreviewDiv.style.top = `${clientY + 20}px`;
colorPreviewDiv.style.left = `${clientX + 20}px`;
const { top, left } = positionElementBesideCursor({
cursor: { x: clientX, y: clientY },
element: {
width: colorPreviewDiv.offsetWidth,
height: colorPreviewDiv.offsetHeight,
},
container: eyeDropperContainer.getBoundingClientRect(),
gap: 20,
});
colorPreviewDiv.style.top = `${top}px`;
colorPreviewDiv.style.left = `${left}px`;
const currentColor = getCurrentColor({ clientX, clientY });
@@ -2,7 +2,6 @@
.popover {
position: absolute;
z-index: 10;
padding: 5px 0 5px;
outline: none;
}
}
@@ -0,0 +1,75 @@
import React from "react";
import { render } from "@testing-library/react";
import { vi } from "vitest";
import { Popover } from "./Popover";
const mockPopoverDimensions = (width: number, height: number) => {
const getBoundingClientRect = vi
.spyOn(HTMLDivElement.prototype, "getBoundingClientRect")
.mockReturnValue({
left: 0,
top: 0,
right: width,
bottom: height,
width,
height,
x: 0,
y: 0,
toJSON: () => {},
});
return () => {
getBoundingClientRect.mockRestore();
};
};
describe("Popover", () => {
it("shifts overflowing content within its positioning container", () => {
const restoreDimensions = mockPopoverDimensions(100, 80);
try {
const { container } = render(
<Popover
left={180}
top={180}
fitInViewport={true}
viewportWidth={200}
viewportHeight={200}
/>,
);
const popover = container.querySelector<HTMLDivElement>(".popover")!;
expect(popover.style.left).toBe("90px");
expect(popover.style.top).toBe("110px");
} finally {
restoreDimensions();
}
});
it("resizes oversized content within the container gap", () => {
const restoreDimensions = mockPopoverDimensions(250, 250);
try {
const { container } = render(
<Popover
left={180}
top={180}
fitInViewport={true}
viewportWidth={200}
viewportHeight={200}
/>,
);
const popover = container.querySelector<HTMLDivElement>(".popover")!;
expect(popover.style.width).toBe("180px");
expect(popover.style.height).toBe("180px");
expect(popover.style.left).toBe("10px");
expect(popover.style.top).toBe("10px");
expect(popover.style.overflowX).toBe("scroll");
expect(popover.style.overflowY).toBe("scroll");
} finally {
restoreDimensions();
}
});
});
+27 -29
View File
@@ -3,18 +3,20 @@ import { unstable_batchedUpdates } from "react-dom";
import { KEYS, queryFocusableElements } from "@excalidraw/common";
import { clamp } from "@excalidraw/math";
import clsx from "clsx";
import "./Popover.scss";
const POPOVER_CONTAINER_GAP = 10;
type Props = {
top?: number;
left?: number;
children?: React.ReactNode;
onCloseRequest?(event: PointerEvent): void;
fitInViewport?: boolean;
offsetLeft?: number;
offsetTop?: number;
viewportWidth?: number;
viewportHeight?: number;
className?: string;
@@ -26,8 +28,6 @@ export const Popover = ({
top,
onCloseRequest,
fitInViewport = false,
offsetLeft = 0,
offsetTop = 0,
viewportWidth = window.innerWidth,
viewportHeight = window.innerHeight,
className,
@@ -92,8 +92,8 @@ export const Popover = ({
// ensure the popover doesn't overflow the viewport
useLayoutEffect(() => {
if (fitInViewport && popoverRef.current && top != null && left != null) {
const container = popoverRef.current;
const { width, height } = container.getBoundingClientRect();
const element = popoverRef.current;
const { width, height } = element.getBoundingClientRect();
// hack for StrictMode so this effect only runs once for
// the same top/left position, otherwise
@@ -107,35 +107,33 @@ export const Popover = ({
}
lastInitializedPosRef.current = { top, left };
if (width >= viewportWidth) {
container.style.width = `${viewportWidth}px`;
container.style.left = "0px";
container.style.overflowX = "scroll";
} else if (left + width - offsetLeft > viewportWidth) {
container.style.left = `${viewportWidth - width - 10}px`;
const maxWidth = Math.max(0, viewportWidth - POPOVER_CONTAINER_GAP * 2);
if (width >= maxWidth) {
element.style.width = `${maxWidth}px`;
element.style.left = `${POPOVER_CONTAINER_GAP}px`;
element.style.overflowX = "scroll";
} else {
container.style.left = `${left}px`;
element.style.left = `${clamp(
left,
POPOVER_CONTAINER_GAP,
viewportWidth - POPOVER_CONTAINER_GAP - width,
)}px`;
}
if (height >= viewportHeight) {
container.style.height = `${viewportHeight - 20}px`;
container.style.top = "10px";
container.style.overflowY = "scroll";
} else if (top + height - offsetTop > viewportHeight) {
container.style.top = `${viewportHeight - height}px`;
const maxHeight = Math.max(0, viewportHeight - POPOVER_CONTAINER_GAP * 2);
if (height >= maxHeight) {
element.style.height = `${maxHeight}px`;
element.style.top = `${POPOVER_CONTAINER_GAP}px`;
element.style.overflowY = "scroll";
} else {
container.style.top = `${top}px`;
element.style.top = `${clamp(
top,
POPOVER_CONTAINER_GAP,
viewportHeight - POPOVER_CONTAINER_GAP - height,
)}px`;
}
}
}, [
top,
left,
fitInViewport,
viewportWidth,
viewportHeight,
offsetLeft,
offsetTop,
]);
}, [top, left, fitInViewport, viewportWidth, viewportHeight]);
useEffect(() => {
if (onCloseRequest) {
@@ -0,0 +1,59 @@
import { positionElementBesideCursor } from "./positionElementBesideCursor";
const element = {
width: 48,
height: 48,
};
const container = {
left: 100,
top: 50,
width: 400,
height: 300,
};
describe("positionElementBesideCursor", () => {
it("positions the element after the cursor when it fits", () => {
expect(
positionElementBesideCursor({
cursor: { x: 200, y: 100 },
element,
container,
gap: 20,
}),
).toEqual({ left: 120, top: 70 });
});
it("flips an overflowing element to the other side of the cursor", () => {
expect(
positionElementBesideCursor({
cursor: { x: 480, y: 330 },
element,
container,
gap: 20,
}),
).toEqual({ left: 312, top: 212 });
});
it("keeps a flipped element within the container", () => {
expect(
positionElementBesideCursor({
cursor: { x: 160, y: 90 },
element,
container: { left: 100, top: 50, width: 100, height: 80 },
gap: 20,
}),
).toEqual({ left: 0, top: 0 });
});
it("pins an oversized element to the container origin", () => {
expect(
positionElementBesideCursor({
cursor: { x: 130, y: 80 },
element,
container: { left: 100, top: 50, width: 40, height: 40 },
gap: 0,
}),
).toEqual({ left: 0, top: 0 });
});
});
@@ -0,0 +1,65 @@
import { clamp } from "@excalidraw/math";
const positionAxis = ({
cursorPosition,
elementSize,
containerSize,
gap,
}: {
cursorPosition: number;
elementSize: number;
containerSize: number;
gap: number;
}) => {
// flip to the other side of the cursor when overflowing the container
const position =
cursorPosition + gap + elementSize > containerSize
? cursorPosition - gap - elementSize
: cursorPosition + gap;
// If the element does not fit on either side, keep as much of it within the
// container as possible.
return clamp(position, 0, Math.max(0, containerSize - elementSize));
};
/**
* Positions an element beside a cursor within a container, flipping the
* element to the other side of the cursor when it would overflow the
* container, resolved independently on each axis.
*
* Takes the cursor in client (viewport) coordinates and returns
* container-local coordinates.
*/
export const positionElementBesideCursor = ({
cursor,
element,
container,
gap,
}: {
/** client (viewport) coordinates */
cursor: {
x: number;
y: number;
};
element: {
width: number;
height: number;
};
/** the container's bounding client rect */
container: Pick<DOMRect, "left" | "top" | "width" | "height">;
/** distance between the cursor and the positioned element */
gap: number;
}) => ({
left: positionAxis({
cursorPosition: cursor.x - container.left,
elementSize: element.width,
containerSize: container.width,
gap,
}),
top: positionAxis({
cursorPosition: cursor.y - container.top,
elementSize: element.height,
containerSize: container.height,
gap,
}),
});
@@ -193,7 +193,12 @@ describe("cursor hint", () => {
});
it("tracks pointer position while visible", () => {
mockBoundingClientRect({ width: 1920, height: 1080 });
mockBoundingClientRect({
left: 100,
top: 50,
width: 1920,
height: 1080,
});
try {
UI.clickTool("arrow");
@@ -201,8 +206,8 @@ describe("cursor hint", () => {
fireEvent.pointerMove(window, { clientX: 200, clientY: 100 });
// 16px offset from the pointer
expect(getCursorHint()!.style.transform).toBe("translate(216px, 116px)");
// container-relative position, 16px offset from the pointer
expect(getCursorHint()!.style.transform).toBe("translate(116px, 66px)");
} finally {
restoreOriginalGetBoundingClientRect();
}
@@ -0,0 +1,50 @@
import React from "react";
import { Excalidraw } from "../index";
import { Keyboard } from "./helpers/ui";
import { fireEvent, GlobalTestState, render, waitFor } from "./test-utils";
describe("eye dropper", () => {
it("keeps the color preview within the editor container", async () => {
await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
Keyboard.keyPress("i");
const preview = await waitFor(() => {
const element =
GlobalTestState.renderResult.container.querySelector<HTMLDivElement>(
".excalidraw-eye-dropper-preview",
);
expect(element).not.toBeNull();
return element!;
});
const eyeDropperContainer =
GlobalTestState.renderResult.container.querySelector<HTMLDivElement>(
".excalidraw-eye-dropper-backdrop",
)!;
eyeDropperContainer.getBoundingClientRect = () => ({
left: 100,
top: 50,
right: 500,
bottom: 350,
width: 400,
height: 300,
x: 100,
y: 50,
toJSON: () => {},
});
Object.defineProperties(preview, {
offsetWidth: { configurable: true, value: 48 },
offsetHeight: { configurable: true, value: 48 },
});
// This position fits within the viewport, but not within the editor.
fireEvent.pointerMove(window, { clientX: 480, clientY: 330 });
expect(preview.style.left).toBe("312px");
expect(preview.style.top).toBe("212px");
});
});