Virtual whiteboard for sketching hand-drawn like diagrams
fix(editor): pan the canvas to follow the caret instead of shifting the UI (#12175)
David Luzarf3d99c42e905
diff --git a/packages/common/src/constants.ts b/packages/common/src/constants.tsindex 63b5756c91..594fc3c791 100644--- a/packages/common/src/constants.ts+++ b/packages/common/src/constants.ts@@ -22,6 +22,9 @@ export const APP_NAME = "Excalidraw";// don't unintentionally create text elements that are wrapped to a few chars// (happens a lot with fast clicks with the text tool)export const TEXT_AUTOWRAP_THRESHOLD = 36; // px+// room left at each side of the visible canvas when a text stops growing at+// its width, or is brought into view once it wraps+export const TEXT_VIEWPORT_PADDING = 20; // pxexport const DRAGGING_THRESHOLD = 10; // pxexport const MINIMUM_ARROW_SIZE = 20; // pxexport const LINE_CONFIRM_THRESHOLD = 8; // pxdiff --git a/packages/element/src/newElement.ts b/packages/element/src/newElement.tsindex e342abdc9d..02026067e1 100644--- a/packages/element/src/newElement.ts+++ b/packages/element/src/newElement.ts@@ -394,6 +394,8 @@ const getAdjustedDimensions = (element: ExcalidrawTextElement,elementsMap: ElementsMap,nextText: string,+ /** the width the text is to take regardless of its content */+ nextFixedWidth?: number,): {x: number;y: number;@@ -407,7 +409,9 @@ const getAdjustedDimensions = ();// wrapped text- if (!element.autoResize) {+ if (nextFixedWidth !== undefined) {+ nextWidth = nextFixedWidth;+ } else if (!element.autoResize) {nextWidth = element.width;}@@ -531,10 +535,38 @@ export const refreshTextDimensions = (container: ExcalidrawTextContainer | null,elementsMap: ElementsMap,text = textElement.text,+ /**+ * For a free text that grows with its content (`autoResize`): the widest+ * it may grow to. Crossing it, the text stops growing and wraps at this+ * width from then on (`autoResize: false`), anchored as its growth was. A+ * text that is already wider keeps growing.+ */+ maxWidth?: number,) => {if (textElement.isDeleted) {return;}+ if (+ maxWidth !== undefined &&+ !container &&+ textElement.autoResize &&+ textElement.width <= maxWidth+ ) {+ const font = getFontString(textElement);+ if (measureText(text, font, textElement.lineHeight).width > maxWidth) {+ const wrappedText = wrapText(text, font, maxWidth);+ return {+ text: wrappedText,+ autoResize: false,+ ...getAdjustedDimensions(+ textElement,+ elementsMap,+ wrappedText,+ maxWidth,+ ),+ };+ }+ }if (container || !textElement.autoResize) {text = wrapText(text,diff --git a/packages/element/tests/__snapshots__/linearElementEditor.test.tsx.snap b/packages/element/tests/__snapshots__/linearElementEditor.test.tsx.snapindex 3ee60ba8e8..ba8818591d 100644--- a/packages/element/tests/__snapshots__/linearElementEditor.test.tsx.snap+++ b/packages/element/tests/__snapshots__/linearElementEditor.test.tsx.snap@@ -17,7 +17,7 @@ exports[`Test Linear Elements > Test bound text element > should match styles foclass="excalidraw-wysiwyg"data-type="wysiwyg"dir="auto"- style="position: absolute; display: inline-block; min-height: 1em; backface-visibility: hidden; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 26.25px; left: 35px; top: 7.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; max-height: 992.5px; font: Emoji 20px 20px; line-height: 1.25; font-family: Excalifont, Xiaolai, sans-serif, Segoe UI Emoji;"+ style="position: absolute; display: inline-block; min-height: 1em; backface-visibility: hidden; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 26.25px; left: 35px; top: 7.5px; transform-origin: 5px 12.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; font: Emoji 20px 20px; line-height: 1.25; font-family: Excalifont, Xiaolai, sans-serif, Segoe UI Emoji;"tabindex="0"wrap="off"/>diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex 57dd82dbca..87db242929 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -109,6 +109,7 @@ import {isSelectionLikeTool,oneOf,getStrokeWidthByKey,+ TEXT_VIEWPORT_PADDING,} from "@excalidraw/common";import {@@ -416,6 +417,7 @@ import { Renderer } from "../scene/Renderer";import {type SetViewportOptions,getViewportForZoomWithScrollConstraints,+ scrollBoundsIntoView,} from "../viewport";import { ElementCanvasButtons } from "../components/ElementCanvasButtons";import { LaserTrails } from "../laserTrails";@@ -5057,8 +5059,12 @@ class App extends React.Component<AppProps, AppState> {});const lineHeight = getLineHeight(textElementProps.fontFamily);const [x1, , x2] = getVisibleSceneBounds(this.state);- // long texts should not go beyond 800 pixels in width nor should it go below 200 px- const maxTextWidth = Math.max(Math.min((x2 - x1) * 0.5, 800), 200);+ // long texts should not go beyond 800 pixels in width nor should it go+ // below 200 px — nor, whatever those make of it, outgrow the view+ const maxTextWidth = Math.min(+ Math.max(Math.min((x2 - x1) * 0.5, 800), 200),+ this.getMaxTextWidth(),+ );const LINE_GAP = 10;let currentY = y;@@ -5126,6 +5132,17 @@ class App extends React.Component<AppProps, AppState> {this.state,),});+ // wrapped to fit the view: make sure all of it is in view, too+ if (textElements.some((element) => !element.autoResize)) {+ const scroll = scrollBoundsIntoView({+ bounds: getCommonBounds(textElements),+ appState: this.state,+ offsets: this.getTextViewportOffsets(),+ });+ if (scroll) {+ this.viewport.translate(scroll);+ }+ }if (!isPlainPaste &&@@ -6392,6 +6409,33 @@ class App extends React.Component<AppProps, AppState> {gesture.initialScale = null;});+ /**+ * The part of the canvas a typed or pasted text is kept within, as offsets+ * from its edges (screen px): all of it but the sidebar, less some room+ * at each side.+ */+ private getTextViewportOffsets = () => {+ const { left, right } = this.viewport.getSidebarInsets();+ const padding = TEXT_VIEWPORT_PADDING;+ return {+ top: padding,+ right: right + padding,+ bottom: padding,+ left: left + padding,+ };+ };++ /**+ * The widest a text may grow to as it's typed or pasted, in scene units:+ * the width of the part of the canvas it's kept within, so that a text+ * never outgrows the view.+ */+ private getMaxTextWidth = () => {+ const { left, right } = this.getTextViewportOffsets();+ const width = this.state.width - left - right;+ return width > 0 ? width / this.state.zoom.value : Infinity;+ };+private handleTextWysiwyg(element: NonDeleted<ExcalidrawTextElement>,{@@ -6426,6 +6470,8 @@ class App extends React.Component<AppProps, AppState> {originalText: nextOriginalText,}): null;+ // a free text stops growing at the view's width and wraps from there+ const maxWidth = this.getMaxTextWidth();this.scene.replaceAllElements([// Not sure why we include deleted elements as well hence using deleted elements map@@ -6448,6 +6494,7 @@ class App extends React.Component<AppProps, AppState> {getContainerElement(_element, elementsMap),elementsMap,nextOriginalText,+ maxWidth,)),});}@@ -6455,6 +6502,32 @@ class App extends React.Component<AppProps, AppState> {}),]);+ const updatedTextElement = this.scene.getNonDeletedElement(+ latestTextElement.id,+ );+ if (+ latestTextElement.autoResize &&+ updatedTextElement &&+ isTextElement(updatedTextElement) &&+ !updatedTextElement.autoResize+ ) {+ // it just started wrapping at the view's width: bring all of it into+ // view (right edge off the view's by the same room as the width+ // left) — vertically only if it fits; the caret follows the rest+ const scroll = scrollBoundsIntoView({+ bounds: getElementBounds(+ updatedTextElement,+ this.scene.getNonDeletedElementsMap(),+ ),+ appState: this.state,+ offsets: this.getTextViewportOffsets(),+ tooLarge: "leave",+ });+ if (scroll) {+ this.viewport.translate(scroll);+ }+ }+if (stickyContainer) {// the note may have grown or shrunk — arrows bound to it must followconst latestContainer = this.scene.getNonDeletedElement(diff --git a/packages/excalidraw/components/App.viewport.ts b/packages/excalidraw/components/App.viewport.tsindex 301056e70f..4dc2214188 100644--- a/packages/excalidraw/components/App.viewport.ts+++ b/packages/excalidraw/components/App.viewport.ts@@ -468,6 +468,41 @@ export class AppViewport {this.uiLastMeasured.delete(name);};+ /**+ * The side a rendered side UI (`data-viewport-ui="side"`) docks to, and+ * how far it reaches into the canvas from it, in screen px.+ */+ private measureSide = (node: HTMLElement, containerRect: DOMRect) => {+ const domRect = node.getBoundingClientRect();+ const left = domRect.left - containerRect.left;+ const right = domRect.right - containerRect.left;+ return left + domRect.width / 2 < this.app.state.width / 2+ ? { side: "left" as const, offset: right }+ : { side: "right" as const, offset: this.app.state.width - left };+ };++ /**+ * How far the sidebar reaches into the canvas, in screen px, from the+ * right or (RTL) the left: the part of the canvas it covers. Zero when+ * it's closed — or on phones, where it's an overlay that doesn't count as+ * viewport UI.+ */+ getSidebarInsets = () => {+ const insets = { left: 0, right: 0 };+ const container = this.dependencies.getContainer();+ const sidebar = container?.querySelector<HTMLElement>(+ '[data-viewport-ui="side"][data-viewport-ui-name="sidebar"]',+ );+ if (container && sidebar) {+ const { side, offset } = this.measureSide(+ sidebar,+ container.getBoundingClientRect(),+ );+ insets[side] = Math.max(0, offset);+ }+ return insets;+ };+/*** Resolves user-supplied viewport offsets into concrete per-side pixel* values. Static sides take precedence over UI-derived sides.@@ -532,10 +567,10 @@ export class AppViewport {);break;case "side": {- const [side, offset] =- rect.left + rect.width / 2 < this.app.state.width / 2- ? (["left", rect.right] as const)- : (["right", this.app.state.width - rect.left] as const);+ const { side, offset } = this.measureSide(+ node,+ excalidrawContainerRect,+ );measuredOffsets[side] = Math.max(measuredOffsets[side], offset);diff --git a/packages/excalidraw/css/styles.scss b/packages/excalidraw/css/styles.scssindex 846c008f27..4e68554993 100644--- a/packages/excalidraw/css/styles.scss+++ b/packages/excalidraw/css/styles.scss@@ -130,6 +130,23 @@ body.excalidraw-cursor-resize * {position: absolute;}+ // The text editor's box: the canvas area, clipped, and kept off a docked+ // sidebar (see textWysiwyg). A caret outside it is revealed by scrolling+ // this box, which the text editor turns into a canvas pan.+ .excalidraw-textEditorContainer {+ position: absolute;+ top: 0;+ right: 0;+ bottom: 0;+ left: 0;+ overflow: hidden;+ pointer-events: none;++ > textarea {+ pointer-events: auto;+ }+ }+&__embeddable {width: 100%;height: 100%;diff --git a/packages/excalidraw/tests/clipboard.test.tsx b/packages/excalidraw/tests/clipboard.test.tsxindex 9520810583..24e4ea89c5 100644--- a/packages/excalidraw/tests/clipboard.test.tsx+++ b/packages/excalidraw/tests/clipboard.test.tsx@@ -3,10 +3,17 @@ import { vi } from "vitest";import { getLineHeightInPx } from "@excalidraw/element";-import { KEYS, arrayToMap, getLineHeight } from "@excalidraw/common";+import {+ KEYS,+ TEXT_VIEWPORT_PADDING,+ arrayToMap,+ getLineHeight,+} from "@excalidraw/common";import { getElementBounds } from "@excalidraw/element";+import type { ExcalidrawTextElement } from "@excalidraw/element/types";+import { createPasteEvent, serializeAsClipboardJSON } from "../clipboard";import { Excalidraw } from "../index";@@ -203,6 +210,56 @@ describe("paste text as a single element", () => {expect(h.elements.length).toEqual(1);});});+ it("should not make a pasted text wider than the view", async () => {+ API.setAppState({+ width: 1000,+ zoom: { value: 8 as NormalizedZoomValue },+ });+ // the view at 800%, less some room at each side: under the 200px a+ // pasted text otherwise wraps at, at the least+ const maxWidth = (1000 - 2 * TEXT_VIEWPORT_PADDING) / 8;+ expect(maxWidth).toBeLessThan(200);++ pasteWithCtrlCmdShiftV(+ "Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",+ );+ await waitFor(() => {+ expect(h.elements.length).toEqual(1);+ });+ const text = h.elements[0] as ExcalidrawTextElement;+ expect(text.autoResize).toBe(false);+ expect(text.width).toBeLessThanOrEqual(maxWidth);+ });+ it("should bring a pasted text that wraps into view", async () => {+ API.setAppState({ width: 1000, height: 800 });+ // pasted at the pointer, near the bottom-right corner+ h.app.viewport.lastPosition.x = 950;+ h.app.viewport.lastPosition.y = 780;++ pasteWithCtrlCmdShiftV(+ "Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams! Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",+ );+ await waitFor(() => {+ expect(h.elements.length).toEqual(1);+ });+ const text = h.elements[0] as ExcalidrawTextElement;+ expect(text.autoResize).toBe(false);+ // all of it within the view, with room at each side+ const { scrollX, scrollY } = h.state;+ const zoom = h.state.zoom.value;+ expect((text.x + scrollX) * zoom).toBeGreaterThanOrEqual(+ TEXT_VIEWPORT_PADDING - 0.01,+ );+ expect((text.x + text.width + scrollX) * zoom).toBeLessThanOrEqual(+ 1000 - TEXT_VIEWPORT_PADDING + 0.01,+ );+ expect((text.y + scrollY) * zoom).toBeGreaterThanOrEqual(+ TEXT_VIEWPORT_PADDING - 0.01,+ );+ expect((text.y + text.height + scrollY) * zoom).toBeLessThanOrEqual(+ 800 - TEXT_VIEWPORT_PADDING + 0.01,+ );+ });it("should not create any element when only new lines in clipboard", async () => {const text = "\n\n\n\n";pasteWithCtrlCmdShiftV(text);diff --git a/packages/excalidraw/tests/viewport.test.ts b/packages/excalidraw/tests/viewport.test.tsnew file mode 100644index 0000000000..c8e68b5ad4--- /dev/null+++ b/packages/excalidraw/tests/viewport.test.ts@@ -0,0 +1,76 @@+import { scrollBoundsIntoView } from "../viewport";++import type { NormalizedZoomValue } from "../types";++const appState = (zoom = 1) => ({+ scrollX: 0,+ scrollY: 0,+ zoom: { value: zoom as NormalizedZoomValue },+ width: 1000,+ height: 800,+});++describe("scrollBoundsIntoView", () => {+ it("should leave bounds that are in view already", () => {+ expect(+ scrollBoundsIntoView({+ bounds: [100, 100, 200, 200],+ appState: appState(),+ }),+ ).toBe(null);+ });++ it("should bring bounds past an edge in by the least movement", () => {+ // 50px past the right edge, 30px above the top+ expect(+ scrollBoundsIntoView({+ bounds: [900, -30, 1050, 100],+ appState: appState(),+ }),+ ).toEqual({ scrollX: -50, scrollY: 30 });+ });++ it("should keep the offsets clear", () => {+ // a 320px sidebar on the right+ expect(+ scrollBoundsIntoView({+ bounds: [900, 100, 1000, 200],+ appState: appState(),+ offsets: { right: 320 },+ }),+ ).toEqual({ scrollX: -320, scrollY: 0 });+ });++ it("should measure in screen px at any zoom", () => {+ // at 200%, [450, 550] is at [900, 1100] on screen: 100px past the edge,+ // i.e. 50 scene units+ expect(+ scrollBoundsIntoView({+ bounds: [450, 100, 550, 150],+ appState: appState(2),+ }),+ ).toEqual({ scrollX: -50, scrollY: 0 });+ });++ it("should bring in the start of bounds that don't fit, or leave that axis", () => {+ // taller than the view+ const bounds = [100, 500, 200, 2000] as const;+ expect(scrollBoundsIntoView({ bounds, appState: appState() })).toEqual({+ scrollX: 0,+ scrollY: -500,+ });+ expect(+ scrollBoundsIntoView({ bounds, appState: appState(), tooLarge: "leave" }),+ ).toBe(null);+ });++ it("should do nothing when the offsets leave no room", () => {+ expect(+ scrollBoundsIntoView({+ bounds: [900, 0, 1100, 10],+ appState: appState(),+ offsets: { left: 600, right: 600 },+ }),+ ).toBe(null);+ });+});diff --git a/packages/excalidraw/viewport.ts b/packages/excalidraw/viewport.tsindex e6abf78de3..df7b175f9d 100644--- a/packages/excalidraw/viewport.ts+++ b/packages/excalidraw/viewport.ts@@ -423,6 +423,63 @@ export const centerScrollOn = ({};};+/**+ * The scroll that brings `bounds` into the viewport — less `offsets` (screen+ * px: UI covering its edges, room to leave) — by the least movement, keeping+ * the zoom; `null` when they're in view already. Along an axis where they+ * don't fit, their start (left / top) is brought in instead, or, with+ * `tooLarge: "leave"`, that axis keeps its scroll.+ */+export const scrollBoundsIntoView = ({+ bounds: [x1, y1, x2, y2],+ appState: { scrollX, scrollY, zoom, width, height },+ offsets,+ tooLarge = "alignStart",+}: {+ bounds: Bounds;+ appState: Pick<AppState, "scrollX" | "scrollY" | "zoom" | "width" | "height">;+ offsets?: Offsets;+ tooLarge?: "alignStart" | "leave";+}): Pick<AppState, "scrollX" | "scrollY"> | null => {+ const viewLeft = offsets?.left ?? 0;+ const viewRight = width - (offsets?.right ?? 0);+ const viewTop = offsets?.top ?? 0;+ const viewBottom = height - (offsets?.bottom ?? 0);+ if (viewRight <= viewLeft || viewBottom <= viewTop) {+ return null;+ }+ // how far (screen px) to move a span to bring it within [start, end]+ const shift = (+ spanStart: number,+ spanEnd: number,+ scroll: number,+ start: number,+ end: number,+ ) => {+ const screenStart = (spanStart + scroll) * zoom.value;+ const screenEnd = (spanEnd + scroll) * zoom.value;+ if (screenEnd - screenStart > end - start) {+ return tooLarge === "alignStart" ? start - screenStart : 0;+ }+ if (screenEnd > end) {+ return end - screenEnd;+ }+ if (screenStart < start) {+ return start - screenStart;+ }+ return 0;+ };+ const dx = shift(x1, x2, scrollX, viewLeft, viewRight);+ const dy = shift(y1, y2, scrollY, viewTop, viewBottom);+ if (!dx && !dy) {+ return null;+ }+ return {+ scrollX: scrollX + dx / zoom.value,+ scrollY: scrollY + dy / zoom.value,+ };+};+export const getScrollToContentState = (elements: readonly ExcalidrawElement[],appState: AppState,diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsxindex a411497d0c..27305e8ab4 100644--- a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx+++ b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx@@ -17,6 +17,7 @@ import {THEME,VERTICAL_ALIGN,applyDarkModeFilter,+ TEXT_VIEWPORT_PADDING,} from "@excalidraw/common";import type {@@ -45,6 +46,8 @@ import {import { actionBindText } from "../actions";import { actionTextAutoResize } from "../actions/actionTextAutoResize";+import { CARET_FOLLOW_PADDING } from "./textWysiwyg";+const { h } = window;unmountComponent();@@ -763,6 +766,29 @@ describe("textWysiwyg", () => {describe("Test container-unbound text", () => {const { h } = window;const dimensions = { height: 400, width: 800 };+ const domRect = (left: number, width: number) => () =>+ ({+ x: left,+ y: 0,+ left,+ top: 0,+ width,+ height: 400,+ right: left + width,+ bottom: 400,+ toJSON: () => {},+ } as DOMRect);+ const dockSidebar = (left: number, width: number) => {+ const root = textarea.closest<HTMLElement>(".excalidraw")!;+ root.getBoundingClientRect = domRect(0, 800);+ const sidebar = document.createElement("div");+ sidebar.className = "sidebar sidebar--docked";+ sidebar.dataset.viewportUi = "side";+ sidebar.dataset.viewportUiName = "sidebar";+ sidebar.getBoundingClientRect = domRect(left, width);+ root.appendChild(sidebar);+ return sidebar;+ };let textarea: HTMLTextAreaElement;let textElement: ExcalidrawTextElement;@@ -963,19 +989,223 @@ describe("textWysiwyg", () => {expect(h.state.zoom.value).toBe(1);});- it("text should never go beyond max width", async () => {- UI.clickTool("text");- mouse.click(0, 0);+ it("should not cut the editor off at the viewport's edges", async () => {+ Keyboard.exitTextEditor(textarea);+ // already wider than the 800x400 viewport: such a text keeps growing+ const line =+ "Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!";+ const wide = API.createElement({ type: "text", text: line, width: 1000 });+ API.setElements([wide]);+ API.setSelectedElements([wide]);+ Keyboard.keyPress(KEYS.ENTER);+ textarea = await getTextEditor();+ // and taller, too+ updateTextEditor(textarea, `${line}${"\nline".repeat(20)}`);++ // the editor box is the text's: a caret past an edge pans the canvas+ // (see below) instead of scrolling inside a box cut to the viewport+ const text = h.elements[0] as ExcalidrawTextElement;+ expect(text.autoResize).toBe(true);+ expect(text.width).toBe(1000);+ expect(text.height).toBeGreaterThan(400);+ expect(textarea.style.width).toBe(`${text.width}px`);+ expect(parseFloat(textarea.style.height)).toBeCloseTo(text.height * 1.05);+ expect(textarea.style.maxHeight).toBe("");+ Keyboard.exitTextEditor(textarea);+ });++ it("should stop a growing text at the view's width and wrap it from there", () => {+ // the 800px wide view, less some room at each side+ const maxWidth = 800 - 2 * TEXT_VIEWPORT_PADDING;+ const line =+ "Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!";+ updateTextEditor(textarea, line);+ let text = h.elements[0] as ExcalidrawTextElement;+ expect(text.autoResize).toBe(false);+ expect(text.width).toBe(maxWidth);+ expect(text.originalText).toBe(line);+ expect(text.text).toContain("\n");+ // the editor wraps along+ expect(textarea.style.whiteSpace).toBe("pre-wrap");+ expect(textarea.style.width).toBe(`${maxWidth}px`);++ // typing on wraps further; the width stays+ const { height } = text;+ updateTextEditor(textarea, `${line} ${line}`);+ text = h.elements[0] as ExcalidrawTextElement;+ expect(text.width).toBe(maxWidth);+ expect(text.height).toBeGreaterThan(height);+ });++ it("should stop a growing text at a width that follows the zoom and a docked sidebar", () => {+ const sidebar = dockSidebar(500, 300);+ API.setAppState({ zoom: { value: 2 as typeof h.state.zoom.value } });++ updateTextEditor(+ textarea,+ "Excalidraw is an opensource virtual collaborative whiteboard",+ );+ // the canvas left of the sidebar, less the room, in scene units+ expect(h.elements[0].width).toBe(+ (800 - 300 - 2 * TEXT_VIEWPORT_PADDING) / 2,+ );+ sidebar.remove();+ });++ it("should bring a text that starts wrapping into view, with room at its right edge", async () => {+ Keyboard.exitTextEditor(textarea);+ UI.clickTool("text");+ mouse.clickAt(300, 100);textarea = await getTextEditor();+ const { scrollY } = h.state;+ // starts at 300px: it would stop growing well past the right edgeupdateTextEditor(textarea,"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",);++ const text = h.app.scene.getElement(+ h.state.editingTextElement!.id,+ ) as ExcalidrawTextElement;+ expect(text.autoResize).toBe(false);+ // as wide as the view less the room at each side, it now fills that+ const zoom = h.state.zoom.value;+ expect((text.x + h.state.scrollX) * zoom).toBeCloseTo(+ TEXT_VIEWPORT_PADDING,+ );+ expect((text.x + text.width + h.state.scrollX) * zoom).toBeCloseTo(+ 800 - TEXT_VIEWPORT_PADDING,+ );+ // it fitted vertically already+ expect(h.state.scrollY).toBe(scrollY);+ // and the editor moved along+ expect(parseFloat(textarea.style.left)).toBeCloseTo(+ TEXT_VIEWPORT_PADDING,+ );+ });++ it("should leave the vertical to the caret when a text that starts wrapping is taller than the view", async () => {Keyboard.exitTextEditor(textarea);+ UI.clickTool("text");+ mouse.clickAt(300, 100);+ textarea = await getTextEditor();+ const { scrollY } = h.state;+ updateTextEditor(+ textarea,+ `${"line\n".repeat(+ 20,+ )}Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!`,+ );++ const text = h.app.scene.getElement(+ h.state.editingTextElement!.id,+ ) as ExcalidrawTextElement;+ expect(text.autoResize).toBe(false);+ expect(text.height).toBeGreaterThan(400);+ // brought in horizontally…+ expect(+ (text.x + text.width + h.state.scrollX) * h.state.zoom.value,+ ).toBeCloseTo(800 - TEXT_VIEWPORT_PADDING);+ // …but not vertically: all of it can't be, and the caret is followed+ // as usual+ expect(h.state.scrollY).toBe(scrollY);+ });++ it("should keep a right-aligned text's right edge where it stops growing", () => {+ API.updateElement(h.elements[0] as ExcalidrawTextElement, {+ textAlign: "right",+ });+ updateTextEditor(textarea, "short");+ const { x, width } = h.elements[0];+ expect((h.elements[0] as ExcalidrawTextElement).textAlign).toBe("right");- expect(textarea.style.width).toBe("792px");- expect(h.elements[0].width).toBe(1000);+ updateTextEditor(+ textarea,+ "Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",+ );+ const text = h.elements[0] as ExcalidrawTextElement;+ expect(text.autoResize).toBe(false);+ expect(text.x + text.width).toBeCloseTo(x + width);+ });++ it("should pan the canvas instead of scrolling the editor to reveal the caret", () => {+ API.setAppState({ zoom: { value: 2 as typeof h.state.zoom.value } });+ const editorBox = textarea.parentElement!;+ const root = textarea.closest<HTMLElement>(".excalidraw")!;+ const { scrollX, scrollY } = h.state;+ const editorTop = parseFloat(textarea.style.top);++ // what the browser does to reveal a caret below and right of the+ // editor's box (the canvas area)+ editorBox.scrollTop = 120;+ editorBox.scrollLeft = 40;+ fireEvent.scroll(editorBox);++ // the box is put back, and the canvas pans by the same screen+ // distance plus room to spare+ expect(editorBox.scrollTop).toBe(0);+ expect(editorBox.scrollLeft).toBe(0);+ expect(h.state.scrollX).toBe(scrollX - (40 + CARET_FOLLOW_PADDING) / 2);+ expect(h.state.scrollY).toBe(scrollY - (120 + CARET_FOLLOW_PADDING) / 2);+ // with the editor on it+ expect(parseFloat(textarea.style.top)).toBe(+ editorTop - (120 + CARET_FOLLOW_PADDING),+ );+ // the reveal never reaches the root+ expect(root.scrollTop).toBe(0);++ // a reveal along one axis pans along that axis only+ const scrolledX = h.state.scrollX;+ editorBox.scrollTop = 30;+ fireEvent.scroll(editorBox);+ expect(h.state.scrollX).toBe(scrolledX);+ expect(h.state.scrollY).toBe(+ scrollY -+ (120 + CARET_FOLLOW_PADDING) / 2 -+ (30 + CARET_FOLLOW_PADDING) / 2,+ );++ // with no text being edited, the box is left alone+ const lastScrollY = h.state.scrollY;+ Keyboard.exitTextEditor(textarea);+ editorBox.scrollTop = 50;+ fireEvent.scroll(editorBox);+ expect(editorBox.scrollTop).toBe(50);+ expect(h.state.scrollY).toBe(lastScrollY);+ editorBox.scrollTop = 0;+ });++ it("should keep the editor's box off a docked sidebar", () => {+ const editorBox = textarea.parentElement!;+ const sidebar = dockSidebar(500, 300);+ const editorLeft = parseFloat(textarea.style.left);++ // docked on the right: the box ends where the sidebar starts, so a+ // caret behind the sidebar is outside it (and revealed by a pan)+ updateTextEditor(textarea, "Hello");+ expect(editorBox.style.right).toBe("300px");+ expect(editorBox.style.left).toBe("0px");+ expect(parseFloat(textarea.style.left)).toBe(editorLeft);++ // docked on the left (RTL): the box starts where the sidebar ends, and+ // the editor keeps its place on the canvas+ sidebar.getBoundingClientRect = domRect(0, 300);+ updateTextEditor(textarea, "Hello!");+ expect(editorBox.style.left).toBe("300px");+ expect(editorBox.style.right).toBe("0px");+ expect(parseFloat(textarea.style.left)).toBe(editorLeft - 300);++ // not docked: the whole canvas+ sidebar.remove();+ updateTextEditor(textarea, "Hello");+ expect(editorBox.style.left).toBe("0px");+ expect(editorBox.style.right).toBe("0px");++ // the insets go with the editor+ Keyboard.exitTextEditor(textarea);+ expect(editorBox.style.left).toBe("");+ expect(editorBox.style.right).toBe("");});});diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.tsxindex 569318c153..807eb52fe7 100644--- a/packages/excalidraw/wysiwyg/textWysiwyg.tsx+++ b/packages/excalidraw/wysiwyg/textWysiwyg.tsx@@ -77,24 +77,29 @@ import type { ParsedDataTranferList } from "../clipboard";import type App from "../components/App";import type { AppState } from "../types";+/**+ * How much further than the browser's caret reveal the canvas pans, in+ * screen px: text typed past the viewport's edge comes back with this much+ * room to spare, instead of flush against the edge.+ */+export const CARET_FOLLOW_PADDING = 5;++/**+ * The editor is scaled and rotated about the text's center (its transform+ * origin), as the canvas draws the text. The zoom puts that center at half+ * the *scaled* size from the box's top-left, while the origin sits at half+ * the unscaled size — the translate makes up the difference.+ */const getTransform = (width: number,height: number,angle: number,appState: AppState,- maxWidth: number,- maxHeight: number,) => {const { zoom } = appState;const degree = (180 * angle) / Math.PI;- let translateX = (width * (zoom.value - 1)) / 2;- let translateY = (height * (zoom.value - 1)) / 2;- if (width > maxWidth && zoom.value !== 1) {- translateX = (maxWidth * (zoom.value - 1)) / 2;- }- if (height > maxHeight && zoom.value !== 1) {- translateY = (maxHeight * (zoom.value - 1)) / 2;- }+ const translateX = (width * (zoom.value - 1)) / 2;+ const translateY = (height * (zoom.value - 1)) / 2;return `translate(${translateX}px, ${translateY}px) scale(${zoom.value}) rotate(${degree}deg)`;};@@ -232,6 +237,28 @@ export const textWysiwyg = ({}): SubmitHandler => {const ownerDocument = excalidrawContainer?.ownerDocument ?? document;const ownerWindow = ownerDocument.defaultView ?? window;+ // the editor's box: the part of the canvas a caret is revealed into (see+ // onEditorBoxScroll)+ const editorBox =+ excalidrawContainer?.querySelector<HTMLDivElement>(+ ".excalidraw-textEditorContainer",+ ) ?? null;++ /**+ * Keeps the editor's box off the sidebar, so a caret behind the sidebar+ * is outside the box and gets revealed like one past the viewport's edge.+ * Returns the box's left inset, which the editor's position is relative+ * to.+ */+ const updateEditorBoxInsets = () => {+ if (!editorBox) {+ return 0;+ }+ const { left, right } = app.viewport.getSidebarInsets();+ editorBox.style.left = `${left}px`;+ editorBox.style.right = `${right}px`;+ return left;+ };let currentTextLayout: {angle: Radians;font: ReturnType<typeof getFontString>;@@ -292,7 +319,6 @@ export const textWysiwyg = ({// what is going to be used for unbounded textlet height = updatedTextElement.height;- let maxWidth = updatedTextElement.width;let maxHeight = updatedTextElement.height;if (container && updatedTextElement.containerId) {@@ -306,7 +332,6 @@ export const textWysiwyg = ({coordX = boundTextCoords.x;coordY = boundTextCoords.y;}- maxWidth = getBoundTextMaxWidth(container, updatedTextElement);maxHeight = getBoundTextMaxHeight(container,updatedTextElement as ExcalidrawTextElementWithContainer,@@ -383,11 +408,12 @@ export const textWysiwyg = ({}}const [viewportX, viewportY] = getViewportCoords(coordX, coordY);+ const angle = getTextElementAngle(updatedTextElement, container);- if (!container) {- maxWidth = (appState.width - 8 - viewportX) / appState.zoom.value;- width = Math.min(width, maxWidth);- } else {+ // The editor box is the text's, never cut to the viewport: a caret past+ // the viewport's edge is revealed by panning the canvas (see+ // onEditorBoxScroll), and the editor stays on its text.+ if (container) {width += 0.5;}@@ -395,26 +421,36 @@ export const textWysiwyg = ({height *= 1.05;const font = getFontString(updatedTextElement);- const angle = getTextElementAngle(updatedTextElement, container);+ const editorBoxLeft = updateEditorBoxInsets();++ // a free text that stopped growing at the viewport's width (see+ // App.getMaxTextWidth) wraps from then on, and so does its editor+ if (+ !updatedTextElement.autoResize &&+ editable.style.whiteSpace !== "pre-wrap"+ ) {+ editable.style.whiteSpace = "pre-wrap";+ editable.style.wordBreak = "break-word";+ }- // Make sure text editor height doesn't go beyond viewport- const editorMaxHeight =- (appState.height - viewportY) / appState.zoom.value;Object.assign(editable.style, {font,// must be defined *after* font ¯\_(ツ)_/¯lineHeight: updatedTextElement.lineHeight,width: `${width}px`,height: `${height}px`,- left: `${viewportX}px`,+ left: `${viewportX - editorBoxLeft}px`,top: `${viewportY}px`,+ // about the text's center, whatever size the box itself ends up+ // (the 5% buffer) — see getTransform+ transformOrigin: `${updatedTextElement.width / 2}px ${+ updatedTextElement.height / 2+ }px`,transform: getTransform(- width,- height,+ updatedTextElement.width,+ updatedTextElement.height,angle,appState,- maxWidth,- editorMaxHeight,),textAlign,verticalAlign,@@ -423,7 +459,6 @@ export const textWysiwyg = ({appState.theme === THEME.DARK,),opacity: updatedTextElement.opacity / 100,- maxHeight: `${editorMaxHeight}px`,});currentTextLayout = {angle: angle as Radians,@@ -890,6 +925,9 @@ export const textWysiwyg = ({unbindUpdate();unsubOnChange();unbindOnScroll();+ editorBox?.removeEventListener("scroll", onEditorBoxScroll);+ editorBox?.style.removeProperty("left");+ editorBox?.style.removeProperty("right");editable.remove();};@@ -922,9 +960,12 @@ export const textWysiwyg = ({return;}- // Otherwise, re-enable submit on blur and refocus the editor.+ // Otherwise, re-enable submit on blur and refocus the editor. Never+ // let the focus scroll the container: for a box reaching past the+ // viewport, revealing the caret the textarea has until the click's is+ // placed (the end of the value) would pan the canvas there.editable.onblur = handleSubmit;- editable.focus();+ editable.focus({ preventScroll: true });if (pendingInitialSelection) {editable.setSelectionRange(pendingInitialSelection.start,@@ -1011,7 +1052,7 @@ export const textWysiwyg = ({".properties-content",);if (!isPopupOpened) {- editable.focus();+ editable.focus({ preventScroll: true });}});@@ -1019,6 +1060,37 @@ export const textWysiwyg = ({updateWysiwygStyle();});+ // The browser reveals an out-of-view caret by scrolling the nearest scroll+ // container: the editor's box, which clips it to the canvas area (off a+ // sidebar too, see updateEditorBoxInsets). Scrolled, the editor+ // would leave its text on the canvas; hand the offset to the canvas+ // instead, plus some room to spare, and put the box back: the canvas+ // follows the caret. Scroll events fire before the frame is painted, so+ // the box's shift is never seen, and the reveal never gets past the box —+ // to the editor root, whose overflow a host may override, or to a page+ // around an embedded editor. (A `scroll-padding` can't give the room: the+ // reveal only scrolls as far as the editor reaches, which ends at the+ // text.)+ const onEditorBoxScroll = () => {+ if (!editorBox) {+ return;+ }+ const { scrollLeft, scrollTop } = editorBox;+ if (!scrollLeft && !scrollTop) {+ return;+ }+ editorBox.scrollLeft = 0;+ editorBox.scrollTop = 0;+ // the box only scrolls right and down (it can't go below 0)+ const panX = scrollLeft && scrollLeft + CARET_FOLLOW_PADDING;+ const panY = scrollTop && scrollTop + CARET_FOLLOW_PADDING;+ app.viewport.translate((state) => ({+ scrollX: state.scrollX - panX / state.zoom.value,+ scrollY: state.scrollY - panY / state.zoom.value,+ }));+ };+ editorBox?.addEventListener("scroll", onEditorBoxScroll);+// ---------------------------------------------------------------------------let isDestroyed = false;@@ -1052,9 +1124,7 @@ export const textWysiwyg = ({});});ownerWindow.addEventListener("beforeunload", handleSubmit);- excalidrawContainer- ?.querySelector(".excalidraw-textEditorContainer")!- .appendChild(editable);+ editorBox!.appendChild(editable);return handleSubmit;};