fix(editor): pan the canvas to follow the caret instead of shifting the UI (#12175)

* fix(editor): keep the text editor flush with the canvas when a click places the caret in a tall text

Editing a text that reaches past the viewport with the text tool (a click
places the caret) scrolled the editor's content: the textarea is clamped to
the viewport, focus() reveals the caret — which sits at the end of the value
until the initial selection is applied — and the deferred refocus after the
pointerdown's blur did that on an unfocused textarea, so the text moved up by
the overflow while the box stayed put. The selection tool's single-click edit
starts on pointerup, with no blur, so it never refocused and looked fine.

After placing the initial caret — inside the visible box by construction —
the textarea's own scroll goes back to zero.

Verified in the browser on a 49-line text hanging 250px below the viewport at
90% zoom: internal scroll was 278px, now 0, for the text tool with the
mousedown blur; the selection-tool path stays at 0. jsdom textareas don't
scroll, so there is no unit test for it.

Claude Fable 5.1, high effort

* fix(editor): place the editor of a rotated text where the text is

The editor's textarea was scaled and rotated about its own box's center,
while the canvas rotates a text about the text's center. The two only agree
when the box is the text's size — and it isn't once the box is clamped to
the viewport (a tall text reaching past it) or, slightly, through the 5%
height buffer. A rotated text scrolled partly off the viewport got its
editor displaced by the rotated pivot offset (36px for a 49-line text at
-18° and 130% zoom), and the clamp — a cut along the box's own edges —
removed lines that were still on screen on the side the rotation lifted.

Now the transform origin is the text's center whatever the box's size, with
the translate derived from the text's dimensions, so the editor lands on the
text in every case; the viewport clamps (right and bottom) apply only to an
unrotated box, whose edges are the viewport's, and a rotated box is left
whole. Since an unclamped box can reach past the viewport, both focus()
calls pass preventScroll so revealing the caret can never scroll the
container — the app owns scrolling.

Verified in the browser: all four corners of the rotated editor coincide
with the text's (they were off by up to 36px), typing at the off-screen end
leaves the container unscrolled, and the unrotated case is unchanged — still
clamped to the viewport bottom, top-left in place, no internal scroll on a
click caret, select-all on Enter.

Also updates the linear-editor style snapshot for the editor's explicit
transform origin.

Claude Fable 5.1, high effort
Claude Opus 5.5 (1M), xhigh effort (moved the snapshot update in)

* fix(editor): never let the browser scroll the editor container to reveal a caret

The root container is `overflow: hidden`, which still makes it a scroll
container the browser scrolls programmatically. Typing in a text editor
whose box reaches past the viewport — a rotated text's editor cannot be
clamped to the viewport without losing lines still on screen — made the
browser reveal the caret by scrolling the container, pushing the whole UI
out: two new lines below the viewport moved the toolbar up by 416px.

`overflow: clip` clips exactly like `hidden` but is not a scroll container,
so there is nothing for the caret reveal (or a focus) to scroll; `hidden`
stays as the fallback where `clip` is unknown. The editor never scrolled
this box itself.

Verified in the browser with real key input on a rotated 49-line text
hanging below the viewport at 130% zoom: the container stays at 0 and the
toolbar in place through new lines and characters typed past the viewport.

Claude Fable 5.1, high effort

* fix(editor): the canvas follows the caret instead of the page scrolling to reveal it

With the editor root at `overflow: clip` (previous commit), the browser's
caret reveal skips the root, since it is no longer a scroll container. Full
page, nothing moves, but the caret stays out of view. Embedded in a page
that scrolls (directly, or in a same-origin iframe), the reveal scrolls that
host page instead: 434px for a rotated text reaching past the editor's
bottom edge, 345px for a text scrolled below it while edited. Only a
cross-origin iframe stops it.

The root goes back to `overflow: hidden`, so it absorbs the reveal again.
While a text is being edited, the text editor hands any scroll of the root
to the canvas (`viewport.translate` by the same screen distance) and resets
the root. Scroll events fire before the frame is painted, so the root's
shift is never seen. Nothing moves, host page included, and the canvas pans
just far enough to bring the caret into view. The reveal is the browser's,
so this covers everything that moves the caret: typing, Enter, arrow keys,
paste, IME, and drag-selecting past the edge.

Measured with real key input in Chromium, full page and in a same-origin
iframe embed: host page and root unmoved, canvas panned 444px / 330-355px,
caret visible, the editor still on its text. Outside text editing, a root
scroll is left as it was.

Test: a root scroll while editing is reset and pans the canvas (at 200%
zoom, both axes) with the editor on it; with no text being edited, the root
is left alone.

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): never cut the text editor to the viewport; the canvas follows the caret for every text

The editor of an unrotated text was cut to the viewport's right and bottom
edges (the width of unbound text, plus a max-height), so a caret past an
edge was revealed by scrolling the textarea's content inside the cut box.
The canvas stood still, and the editor's text left its place on the canvas
while typing. Rotated texts were already left whole, and their caret reveal
panned the canvas (previous commit).

Now no editor box is cut: rotated or not, it is the text's own box, and a
caret past the viewport's edge is revealed by panning the canvas. Typing
past the bottom edge, or a long line past the right edge, moves the view
along; the editor stays on its text.

What only existed for the cut goes with it: the `maxWidth` bookkeeping, and
the reset of the textarea's internal scroll after placing a click's caret
(a whole box never scrolls inside).

Measured with real input in Chromium: 455px vertical pan for a 30-line text
crossing the bottom edge, 454px horizontal pan for a line crossing the right
edge, root and textarea unscrolled, editor on its text. A text-tool click on
line 3 of a text taller than the viewport places the caret there without any
pan or internal scroll.

Tests: the max-width test now checks the editor isn't cut at either edge
(it fails with the cut in place); the linear-editor style snapshot loses its
max-height.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): leave room past the caret when the canvas follows it

The browser reveals a caret only as far as it has to, so text typed past
the viewport's edge came into view flush against the edge. The canvas now
pans a further CARET_FOLLOW_PADDING (5 screen px) along the axis it
follows, so the caret keeps a little room from the edge while the view
follows it.

Not done with the root's `scroll-padding`: the browser honors it only as
far as it can scroll, and the editor box ends at the text (5% below it,
nothing past a line's end). Measured in Chromium: `scroll-padding: 80px`
left 39px below the caret and none to its right.

Measured with real input: once the caret reaches the edge, every new line
or character pans the canvas and the caret stays 4-5px from the edge, both
typing down and along a long line.

Test: the pan includes the padding, and a reveal along one axis pans along
that axis only.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): the canvas follows a caret behind a docked sidebar; the reveal stays in the editor's box

A caret that went behind a docked sidebar stayed hidden: it was still
inside the editor root, so the browser had nothing to reveal and the canvas
never followed.

The text editor's container (`.excalidraw-textEditorContainer`) is now the
box a caret is revealed into: the canvas area, clipped, and inset off a
docked sidebar (measured from `.sidebar--docked` on every editor update, on
the right or the left for RTL; the editor's position is relative to the
box). A caret past its edge, or behind the sidebar, is revealed by
scrolling the box, which the text editor turns into a canvas pan (+
padding) and resets, as it did for the root before.

The reveal now never gets past the box, so the editor root is back to
master's CSS, and what a host does to the root's overflow no longer
matters: with the root forced to `overflow: visible` (as Excalidraw+ does,
inside a wrapper that resets its own scroll), the canvas follows the same
way and the wrapper never scrolls.

Measured with real input in Chromium, full page, with the root forced to
`visible`, in the Excalidraw+ arrangement, and in a same-origin iframe
embed: nothing scrolled (host page, root, box), the canvas panned 449 /
360 / 580px for texts past the bottom edge, and for a line typed in behind
the docked sidebar it panned 120px, leaving the caret 5px left of the
sidebar. Clicks inside the editor still place the caret; clicks on the
canvas still end editing.

Tests: the pan test scrolls the editor's box; a new test covers the insets
for a sidebar docked on either side, and their removal with the editor.

Claude Opus 5.5 (1M), xhigh effort

* refactor(editor): measure the sidebar through the viewport UI markers

The text editor's box was kept off a docked sidebar by querying the
`.sidebar--docked` class and measuring it inline in textWysiwyg. How far
viewport UI reaches into the canvas is AppViewport's concern:
`getOffsets` measures every UI marked `data-viewport-ui`, and the sidebar
is marked (`side` / `sidebar`, except on phones, where it's an overlay).

AppViewport gains `getSidebarInsets()`, which measures just the sidebar
through those markers, with a `measureSide()` that `getOffsets` now shares.
The text editor asks the viewport for the insets. An open sidebar that
isn't docked covers the canvas the same way and now counts too; it closes
when the canvas is clicked to start a text, so this rarely matters.

`getOffsets` isn't used for the box: it gives one band per side for all
marked UI, so the top toolbar and the styles panel (open while a text is
edited) would pan the canvas as soon as one typed below them.

Test: the docked-sidebar test's fake sidebar carries the markers.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): a text stops growing at the view's width, and is brought into view when it wraps

Closes #8855. Typing a long line grew a free text past the view's edge.
The canvas followed the caret, so the start of the text went out of view
on the other side, and the box had to be resized by hand afterwards.

A free text that grows with its content (`autoResize`) now stops at the
view's width: the canvas minus the sidebar, less TEXT_VIEWPORT_PADDING
(20px, in @excalidraw/common) at each side, in scene units, so it follows
the zoom. On the keystroke that would cross it, the text becomes fixed
width at exactly that width and wraps from then on (`autoResize: false`),
anchored the way it grew, so a right-aligned or centered text keeps its
edge or center. The editor switches to wrapping with it. A text that is
already wider keeps growing; nothing shrinks. The rule is an optional
`maxWidth` on `refreshTextDimensions`, which the editor's per-keystroke
update passes.

When a text starts wrapping in the editor, while typed or pasted into it,
it is scrolled into view with the same room at the edges. Being exactly
the padded view's width, it then fills it. That happens horizontally
always, and vertically only if all of it fits; a taller text leaves the
vertical to the caret-follow, so the view doesn't jump away from the caret.

Pasting onto the canvas keeps its wrap width (half the view, 200-800),
capped by the same limit, so that the 200 minimum can't outgrow a narrow
or zoomed-in view. A paste that wrapped is scrolled fully into view; if
it is taller than the view, its top is brought in.

Scrolling into view is computed by a pure `scrollBoundsIntoView` in
viewport.ts, next to `centerScrollOn` and `constrainScrollState`. It moves
by the least amount, keeps the zoom, takes the usable area as `Offsets`,
and returns null when nothing needs to move. The move itself goes through
`viewport.translate`, as a user pan does: it respects scroll locks, yields
to a host's pending locked navigation, and stops following a
collaborator. No move, no translate.

Measured with real input in Chromium on a 2560px view: typing
character by character at 400% from 100px in, and a sentence inserted at
once, both end as a wrapped text from 20 to 2540; with the docked sidebar
the limit is 2226 (2560 - 294 - 40) and the text sits 20px left of it; a
paste near the bottom-right corner ends 20px inside the right and bottom
edges. Nothing scrolled the page or the editor box.

Tests: the text stops and wraps at the view's width, and keeps that width;
the limit follows the zoom and a docked sidebar; a right-aligned text keeps
its right edge; a text already wider keeps growing (the not-cut-off test,
reworked); starting to wrap scrolls it into view with room at its right
edge, but not vertically when it's taller than the view; a paste isn't
wider than the view at 800% and, wrapped, ends fully in view;
`scrollBoundsIntoView` unit tests.

Claude Opus 5.5 (1M), xhigh effort
This commit is contained in:
David Luzar authored and GitHub committed 2026-09-26 23:00:28 +02:00
1 parent c10499eebb
commit f3d99c42e9
11 files changed
+698 -48

No files matched your search

+3
View File
@@ -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; // px
export const DRAGGING_THRESHOLD = 10; // px
export const MINIMUM_ARROW_SIZE = 20; // px
export const LINE_CONFIRM_THRESHOLD = 8; // px
+33 -1
View File
@@ -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,
@@ -17,7 +17,7 @@ exports[`Test Linear Elements > Test bound text element > should match styles fo
class="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"
/>
+75 -2
View File
@@ -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 follow
const latestContainer = this.scene.getNonDeletedElement(
+39 -4
View File
@@ -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);
+17
View File
@@ -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%;
+58 -1
View File
@@ -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);
@@ -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);
});
});
+57
View File
@@ -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,
@@ -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 edge
updateTextEditor(
textarea,
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
);
Keyboard.exitTextEditor(textarea);
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
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");
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("");
});
});
+102 -32
View File
@@ -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 text
let 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;
};