Virtual whiteboard for sketching hand-drawn like diagrams
fix(editor): prevent eyedropper preview from overflowing viewport (#11722)
samiran53732f08f430
diff --git a/packages/excalidraw/components/ContextMenu.scss b/packages/excalidraw/components/ContextMenu.scssindex 369d8f3d8e..247a5fd166 100644--- a/packages/excalidraw/components/ContextMenu.scss+++ b/packages/excalidraw/components/ContextMenu.scss@@ -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);diff --git a/packages/excalidraw/components/ContextMenu.tsx b/packages/excalidraw/components/ContextMenu.tsxindex 4cef2bb177..f3a54bf675 100644--- a/packages/excalidraw/components/ContextMenu.tsx+++ b/packages/excalidraw/components/ContextMenu.tsx@@ -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"diff --git a/packages/excalidraw/components/CursorHint.tsx b/packages/excalidraw/components/CursorHint.tsxindex 9f6a2b775c..44a527f85e 100644--- a/packages/excalidraw/components/CursorHint.tsx+++ b/packages/excalidraw/components/CursorHint.tsx@@ -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);diff --git a/packages/excalidraw/components/EyeDropper.scss b/packages/excalidraw/components/EyeDropper.scssindex da706b4160..d597e16567 100644--- a/packages/excalidraw/components/EyeDropper.scss+++ b/packages/excalidraw/components/EyeDropper.scss@@ -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);diff --git a/packages/excalidraw/components/EyeDropper.tsx b/packages/excalidraw/components/EyeDropper.tsxindex 654de4af2a..aea5f93cf6 100644--- a/packages/excalidraw/components/EyeDropper.tsx+++ b/packages/excalidraw/components/EyeDropper.tsx@@ -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 });diff --git a/packages/excalidraw/components/Popover.scss b/packages/excalidraw/components/Popover.scssindex 9458b50261..1faccea72f 100644--- a/packages/excalidraw/components/Popover.scss+++ b/packages/excalidraw/components/Popover.scss@@ -2,7 +2,6 @@.popover {position: absolute;z-index: 10;- padding: 5px 0 5px;outline: none;}}diff --git a/packages/excalidraw/components/Popover.test.tsx b/packages/excalidraw/components/Popover.test.tsxnew file mode 100644index 0000000000..6ebb02ef3e--- /dev/null+++ b/packages/excalidraw/components/Popover.test.tsx@@ -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();+ }+ });+});diff --git a/packages/excalidraw/components/Popover.tsx b/packages/excalidraw/components/Popover.tsxindex d8ee76aa62..c91a0ff184 100644--- a/packages/excalidraw/components/Popover.tsx+++ b/packages/excalidraw/components/Popover.tsx@@ -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 viewportuseLayoutEffect(() => {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) {diff --git a/packages/excalidraw/components/positionElementBesideCursor.test.ts b/packages/excalidraw/components/positionElementBesideCursor.test.tsnew file mode 100644index 0000000000..d695b71efe--- /dev/null+++ b/packages/excalidraw/components/positionElementBesideCursor.test.ts@@ -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 });+ });+});diff --git a/packages/excalidraw/components/positionElementBesideCursor.ts b/packages/excalidraw/components/positionElementBesideCursor.tsnew file mode 100644index 0000000000..aa48445fe0--- /dev/null+++ b/packages/excalidraw/components/positionElementBesideCursor.ts@@ -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,+ }),+});diff --git a/packages/excalidraw/tests/cursorHint.test.tsx b/packages/excalidraw/tests/cursorHint.test.tsxindex e952a6bade..86daea39b5 100644--- a/packages/excalidraw/tests/cursorHint.test.tsx+++ b/packages/excalidraw/tests/cursorHint.test.tsx@@ -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();}diff --git a/packages/excalidraw/tests/eyeDropper.test.tsx b/packages/excalidraw/tests/eyeDropper.test.tsxnew file mode 100644index 0000000000..24a38f61ab--- /dev/null+++ b/packages/excalidraw/tests/eyeDropper.test.tsx@@ -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");+ });+});