From eaa7fa32a6645ae9da57eda548e838d0e2a024a1 Mon Sep 17 00:00:00 2001 From: David Luzar <5153846+dwelle@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:24:56 +0100 Subject: [PATCH] feat(editor): paste multiline text as a single element, with a toast to split it into lines (#12712) * fix(editor): stack text pasted as separate lines without overlap, as the text is aligned Each line was centered on a running y advanced by the previous line's height, so a line wrapping to more rows than the one above overlapped it. Lines now stack top to bottom, half a line height apart (blank lines no longer add room), and take the current text align: the block is centered at the pointer and its lines aligned in it. * fix(editor): don't restart the toast's timer on each render Its onClose is a new function on each LayerUI render, and the timer depended on it: every render cleared the timer and started a full-length one, so a toast stayed for as long as the UI kept re-rendering. The timer now restarts only when the toast shows something else. * feat(editor): paste multiline text as a single element, splitting it into lines from a toast Ctrl/Cmd+V of a text with more lines pasted an element per line. It's one text element now, and a toast offers to split it: each non-blank line an element of its own, in place of the pasted one (wrapped and aligned as in it, half a line height apart), as one step to undo. The toast takes an optional action for that: a link-like button after its message. * fix(editor): give a toast shown again its full duration Since the timer no longer restarts on a render, the same plain toast shown again within its duration got only what was left of the first one's. The toast takes a timerKey (LayerUI passes the toast object), so that another toast restarts the timer, and a re-render still doesn't. * fix(editor): split a pasted text into lines as it's laid out, in its place Review fixes for splitting a pasted text from the toast: - the lines keep their indentation and the rows they were wrapped to (wrapping a line anew at the text's measured width could break a long word elsewhere) - a line moved out of the frame by the gaps is taken out of it - the lines take the text's place in the layer order, and arrows bound to the text are let go of - the focus is back in the editor after the toast's button is gone, so that the next paste isn't ignored - a later paste retires the offer to split the text pasted before --- .../excalidraw/components/App.clipboard.ts | 271 ++++++++++++----- packages/excalidraw/components/LayerUI.tsx | 2 + packages/excalidraw/components/Toast.scss | 17 ++ packages/excalidraw/components/Toast.test.tsx | 54 ++++ packages/excalidraw/components/Toast.tsx | 41 ++- packages/excalidraw/locales/en.json | 3 +- packages/excalidraw/tests/clipboard.test.tsx | 278 ++++++++++++++---- packages/excalidraw/types.ts | 2 + 8 files changed, 517 insertions(+), 151 deletions(-) create mode 100644 packages/excalidraw/components/Toast.test.tsx diff --git a/packages/excalidraw/components/App.clipboard.ts b/packages/excalidraw/components/App.clipboard.ts index 3b09d50330..4af38c87af 100644 --- a/packages/excalidraw/components/App.clipboard.ts +++ b/packages/excalidraw/components/App.clipboard.ts @@ -1,7 +1,6 @@ import { flushSync } from "react-dom"; import { - DEFAULT_TEXT_ALIGN, DEFAULT_VERTICAL_ALIGN, getFontString, getLineHeight, @@ -14,9 +13,12 @@ import { import { convertToExcalidrawElements, embeddableURLValidator, + fixBindingsAfterDeletion, getCommonBounds, getEmbedLink, getLineHeightInPx, + getTextAnchorRatios, + isTextElement, makeNextSelectedElementIds, maybeParseEmbedSrc, measureText, @@ -44,7 +46,6 @@ import { MERMAID_TO_EXCALIDRAW_CONFIG, } from "../mermaid"; import { withBatchedUpdates } from "../reactUtils"; -import { getShortcutKey } from "../shortcut"; import { scrollBoundsIntoView } from "../viewport"; import type React from "react"; @@ -55,11 +56,10 @@ import type { PastedMixedContent, } from "../clipboard"; import type App from "./App"; -import type { Offsets } from "../types"; +import type { AppState, Offsets } from "../types"; let IS_PLAIN_PASTE = false; let IS_PLAIN_PASTE_TIMER = 0; -let PLAIN_PASTE_TOAST_SHOWN = false; type AppClipboardDependencies = { getContainer: () => HTMLDivElement | null; @@ -74,6 +74,9 @@ type AppClipboardDependencies = { * as a library item or a drop does. */ export class AppClipboard { + /** the toast offering to split the text pasted last, while it's offered */ + private splitToast: AppState["toast"] = null; + constructor( private app: App, private dependencies: AppClipboardDependencies, @@ -357,6 +360,12 @@ export class AppClipboard { const data = await parseClipboard(dataTransferList, isPlainPaste); + // the offer to split the text pasted before is for the last paste only + if (this.splitToast && this.app.state.toast === this.splitToast) { + this.app.setToast(null); + } + this.splitToast = null; + if (this.app.props.onPaste) { try { if ((await this.app.props.onPaste(data, event)) === false) { @@ -453,7 +462,7 @@ export class AppClipboard { text, fontSize: this.app.state.currentItemFontSize, fontFamily: this.app.state.currentItemFontFamily, - textAlign: DEFAULT_TEXT_ALIGN, + textAlign: this.app.state.currentItemTextAlign, verticalAlign: DEFAULT_VERTICAL_ALIGN, locked: false, }; @@ -462,74 +471,52 @@ export class AppClipboard { fontFamily: textElementProps.fontFamily, }); const lineHeight = getLineHeight(textElementProps.fontFamily); - const LINE_GAP = 10; - const lines = isPlainPaste ? [text] : text.split("\n"); + // one element, centered at the pointer (lines it has can be split into + // elements of their own after, from the toast) const createTextElements = (maxTextWidth: number) => { - let currentY = y; - return lines.reduce((acc: ExcalidrawTextElement[], line, idx) => { - const originalText = normalizeText(line).trim(); - if (originalText.length) { - const topLayerFrame = this.app.getTopLayerFrameAtSceneCoords({ - x, - y: currentY, - }); - - let metrics = measureText( + const originalText = normalizeText(text).trim(); + if (!originalText.length) { + return []; + } + const wraps = + measureText( + originalText, + fontString, + lineHeight, + this.app.renderEnvironment, + ).width > maxTextWidth; + const wrappedText = wraps + ? wrapText( originalText, fontString, - lineHeight, + maxTextWidth, this.app.renderEnvironment, - ); - const isTextUnwrapped = metrics.width > maxTextWidth; - - const text = isTextUnwrapped - ? wrapText( - originalText, - fontString, - maxTextWidth, - this.app.renderEnvironment, - ) - : originalText; - - metrics = isTextUnwrapped - ? measureText( - text, - fontString, - lineHeight, - this.app.renderEnvironment, - ) - : metrics; - - const startX = x - metrics.width / 2; - const startY = currentY - metrics.height / 2; - - const element = newTextElement({ - ...textElementProps, - x: startX, - y: startY, - text, - originalText, - lineHeight, - autoResize: !isTextUnwrapped, - frameId: topLayerFrame ? topLayerFrame.id : null, - renderEnvironment: this.app.renderEnvironment, - }); - acc.push(element); - currentY += element.height + LINE_GAP; - } else { - const prevLine = lines[idx - 1]?.trim(); - // add paragraph only if previous line was not empty, IOW don't add - // more than one empty line - if (prevLine) { - currentY += - getLineHeightInPx(textElementProps.fontSize, lineHeight) + - LINE_GAP; - } - } - - return acc; - }, []); + ) + : originalText; + const metrics = measureText( + wrappedText, + fontString, + lineHeight, + this.app.renderEnvironment, + ); + const topLayerFrame = this.app.getTopLayerFrameAtSceneCoords({ x, y }); + // a text's placed at its anchor: its left edge, center or right edge, + // as it's aligned + const { x: anchorRatio } = getTextAnchorRatios(textElementProps); + return [ + newTextElement({ + ...textElementProps, + x: x + metrics.width * (anchorRatio - 0.5), + y: y - metrics.height / 2, + text: wrappedText, + originalText, + lineHeight, + autoResize: !wraps, + frameId: topLayerFrame ? topLayerFrame.id : null, + renderEnvironment: this.app.renderEnvironment, + }), + ]; }; // long texts wrap as a typed one does; wrapped to fit the view, all of @@ -626,19 +613,141 @@ export class AppClipboard { this.app.store.scheduleCapture(); this.app.setState({ selectedElementIds: getSelectedElementIds() }); - if ( - !isPlainPaste && - textElements.length > 1 && - PLAIN_PASTE_TOAST_SHOWN === false && - this.app.editorInterface.formFactor !== "phone" - ) { - this.app.setToast({ - message: t("toast.pasteAsSingleElement", { - shortcut: getShortcutKey("CtrlOrCmd+Shift+V"), - }), - duration: 5000, - }); - PLAIN_PASTE_TOAST_SHOWN = true; + const [textElement] = textElements; + if (!isPlainPaste && getTextLines(textElement).length > 1) { + this.splitToast = { + message: t("toast.pastedAsSingleText"), + action: { + label: t("toast.splitIntoTextElements"), + onClick: () => { + this.splitTextIntoLines(textElement.id); + // the button's gone with the toast, and the focus with it + this.app.focusContainer(); + }, + }, + duration: 8000, + }; + this.app.setToast(this.splitToast); } } + + /** + * Splits a text into an element per line (blank lines dropped), as laid + * out in it: each line where it was across, indented and wrapped as it + * was, and stacked top to bottom from its top, half a line height apart. + * In its place in the layer order, too. One step to undo. + */ + private splitTextIntoLines(elementId: ExcalidrawTextElement["id"]) { + const element = this.app.scene.getElement(elementId); + if ( + !element || + element.isDeleted || + !isTextElement(element) || + element.containerId + ) { + return; + } + const lines = getTextLines(element); + if (lines.length < 2) { + return; + } + + const fontString = getFontString(element); + const { lineHeight } = element; + const lineGap = getLineHeightInPx(element.fontSize, lineHeight) / 2; + // a text's placed at its anchor: its left edge, center or right edge, + // as it's aligned (and its top, middle or bottom) + const anchorRatios = getTextAnchorRatios(element); + const anchorX = element.x + element.width * anchorRatios.x; + let currentY = element.y; + const textElements = lines.map(({ originalText, text }) => { + const { width, height } = measureText( + text, + fontString, + lineHeight, + this.app.renderEnvironment, + ); + // moved down by the gaps, a line may've left the frame: each is in + // the one at its center, as a pasted text is + const topLayerFrame = this.app.getTopLayerFrameAtSceneCoords({ + x: anchorX + width * (0.5 - anchorRatios.x), + y: currentY + height / 2, + }); + const textElement = newTextElement({ + x: anchorX, + y: currentY + height * anchorRatios.y, + text, + originalText, + autoResize: !text.includes("\n"), + fontSize: element.fontSize, + fontFamily: element.fontFamily, + textAlign: element.textAlign, + verticalAlign: element.verticalAlign, + lineHeight, + strokeColor: element.strokeColor, + backgroundColor: element.backgroundColor, + fillStyle: element.fillStyle, + strokeWidth: element.strokeWidth, + strokeStyle: element.strokeStyle, + roughness: element.roughness, + roundness: element.roundness, + opacity: element.opacity, + groupIds: element.groupIds, + frameId: topLayerFrame ? topLayerFrame.id : null, + locked: element.locked, + renderEnvironment: this.app.renderEnvironment, + }); + currentY += height + lineGap; + return textElement; + }); + + // arrows bound to the text are let go of + fixBindingsAfterDeletion(this.app.scene.getNonDeletedElements(), [element]); + this.app.scene.mutateElement(element, { isDeleted: true }); + // the lines take the text's place in the layer order — but for those + // now in another frame, which join its children + const [inPlace, inOtherFrame] = textElements.reduce( + (acc: [ExcalidrawTextElement[], ExcalidrawTextElement[]], line) => { + acc[ + line.frameId === null || line.frameId === element.frameId ? 0 : 1 + ].push(line); + return acc; + }, + [[], []], + ); + this.app.scene.insertElementsAtIndex( + inPlace, + this.app.scene.getElementIndex(element.id), + ); + this.app.insertNewElements(inOtherFrame); + this.app.store.scheduleCapture(); + this.app.setState({ + selectedElementIds: makeNextSelectedElementIds( + Object.fromEntries(textElements.map((el) => [el.id, true])), + this.app.state, + ), + }); + } } + +/** + * A text's lines (blank ones dropped), each as it's wrapped in the text: + * the rows it takes there are told by what's in them, as wrapping drops + * nothing but whitespace. Wrapping a line anew may break it elsewhere (the + * text's width is what its rows measure, not what they were wrapped to). + */ +const getTextLines = (element: ExcalidrawTextElement) => { + const getLength = (text: string) => text.replace(/\s/g, "").length; + const rows = element.text.split("\n"); + let rowIndex = 0; + return element.originalText.split("\n").flatMap((line) => { + const length = getLength(line); + let text = rows[rowIndex++] ?? ""; + while (rowIndex < rows.length && getLength(text) < length) { + text += `\n${rows[rowIndex++]}`; + } + return length + ? [{ originalText: line.trimEnd(), text: text.trimEnd() }] + : []; + }); +}; diff --git a/packages/excalidraw/components/LayerUI.tsx b/packages/excalidraw/components/LayerUI.tsx index f6efe133aa..f3ce2ec58a 100644 --- a/packages/excalidraw/components/LayerUI.tsx +++ b/packages/excalidraw/components/LayerUI.tsx @@ -694,6 +694,8 @@ const LayerUI = ({ onClose={() => setAppState({ toast: null })} duration={appState.toast.duration} closable={appState.toast.closable} + action={appState.toast.action} + timerKey={appState.toast} /> )} {!appState.toast && diff --git a/packages/excalidraw/components/Toast.scss b/packages/excalidraw/components/Toast.scss index 89ffc2ade5..5584a52b66 100644 --- a/packages/excalidraw/components/Toast.scss +++ b/packages/excalidraw/components/Toast.scss @@ -25,6 +25,23 @@ white-space: pre-wrap; } + .Toast__action { + all: unset; + color: var(--color-primary); + font-weight: 600; + cursor: pointer; + pointer-events: auto; + + &:hover { + text-decoration: underline; + } + + &:focus-visible { + outline: 1px solid var(--color-primary); + border-radius: 2px; + } + } + .Toast__progress-bar { margin-top: 0.35rem; width: 100%; diff --git a/packages/excalidraw/components/Toast.test.tsx b/packages/excalidraw/components/Toast.test.tsx new file mode 100644 index 0000000000..81078d973c --- /dev/null +++ b/packages/excalidraw/components/Toast.test.tsx @@ -0,0 +1,54 @@ +import React from "react"; +import { act, render } from "@testing-library/react"; +import { vi } from "vitest"; + +import { Excalidraw } from "../index"; +import { render as renderApp } from "../tests/test-utils"; + +import { Toast } from "./Toast"; + +describe("Toast", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("should close after its duration, however often its host re-renders it", () => { + vi.useFakeTimers(); + const onClose = vi.fn(); + // a new onClose each render, as a host's inline one is + const renderToast = () => ( + onClose()} /> + ); + const { rerender } = render(renderToast()); + for (let elapsed = 0; elapsed < 1000; elapsed += 250) { + expect(onClose).not.toHaveBeenCalled(); + rerender(renderToast()); + act(() => { + vi.advanceTimersByTime(250); + }); + } + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it("should give a toast shown again its full duration", async () => { + await renderApp(); + vi.useFakeTimers(); + const showToast = () => + act(() => { + window.h.app.setToast({ message: "hello", duration: 1000 }); + }); + const advanceTimersByTime = (ms: number) => + act(() => { + vi.advanceTimersByTime(ms); + }); + + showToast(); + advanceTimersByTime(900); + // the same message, but another toast + showToast(); + advanceTimersByTime(900); + expect(window.h.state.toast).not.toBe(null); + advanceTimersByTime(100); + expect(window.h.state.toast).toBe(null); + }); +}); diff --git a/packages/excalidraw/components/Toast.tsx b/packages/excalidraw/components/Toast.tsx index 7c1208197f..4e7f7d4bbb 100644 --- a/packages/excalidraw/components/Toast.tsx +++ b/packages/excalidraw/components/Toast.tsx @@ -1,5 +1,7 @@ import { useCallback, useEffect, useRef } from "react"; +import { useStableCallback } from "../hooks/useStableCallback"; + import { CloseIcon } from "./icons"; import { IconButton } from "./IconButton"; @@ -26,22 +28,36 @@ const ToastComponent = ({ closable = false, // To prevent autoclose, pass duration as Infinity duration = DEFAULT_TOAST_TIMEOUT, + action, + timerKey, style, }: { message: ReactNode; onClose: () => void; closable?: boolean; duration?: number; + /** a link-like button after the message; it closes the toast, too */ + action?: { label: string; onClick: () => void }; + /** + * What the toast is shown for (its host's toast object, say): shown for + * something else, even if with the same message, it's given its full + * duration again. + */ + timerKey?: unknown; style?: CSSProperties; }) => { const timerRef = useRef(0); const shouldAutoClose = duration !== Infinity; + // the host's onClose is likely a new function each render: the timer's + // restarted only for another toast (`timerKey`, or its message), not on a + // render + const stableOnClose = useStableCallback(onClose); const scheduleTimeout = useCallback(() => { if (!shouldAutoClose) { return; } - timerRef.current = window.setTimeout(() => onClose(), duration); - }, [onClose, duration, shouldAutoClose]); + timerRef.current = window.setTimeout(() => stableOnClose(), duration); + }, [stableOnClose, duration, shouldAutoClose]); useEffect(() => { if (!shouldAutoClose) { @@ -49,7 +65,7 @@ const ToastComponent = ({ } scheduleTimeout(); return () => clearTimeout(timerRef.current); - }, [scheduleTimeout, message, duration, shouldAutoClose]); + }, [scheduleTimeout, message, timerKey, duration, shouldAutoClose]); const onMouseEnter = shouldAutoClose ? () => clearTimeout(timerRef?.current) @@ -63,7 +79,24 @@ const ToastComponent = ({ onMouseLeave={onMouseLeave} style={style} > -
{message}
+
+ {message} + {action && ( + <> + {" "} + + + )} +
{closable && ( { }); }); -describe("paste text as single lines", () => { - it("should create an element for each line when copying with Ctrl/Cmd+V", async () => { - const text = "sajgfakfn\naaksfnknas\nakefnkasf"; - pasteWithCtrlCmdV(text); - await waitFor(() => { - expect(h.elements.length).toEqual(text.split("\n").length); - }); +/** + * pastes a text with Ctrl/Cmd+V, and splits it from the toast (the pasted + * text, then the lines it's split into, are what's selected) + */ +const pasteAndSplit = async ( + text: string, + beforeSplit?: (pasted: ExcalidrawTextElement) => void, +) => { + pasteWithCtrlCmdV(text); + const button = await waitFor(() => { + const button = document.querySelector(".Toast__action"); + expect(button).not.toBe(null); + return button!; }); + const pasted = API.getSelectedElement() as ExcalidrawTextElement; + beforeSplit?.(pasted); + // as a click does + button.focus(); + fireEvent.click(button); + return { + pasted, + texts: API.getSelectedElements() as ExcalidrawTextElement[], + }; +}; - it("should ignore empty lines when creating an element for each line", async () => { - const text = "\n\nsajgfakfn\n\n\naaksfnknas\n\nakefnkasf\n\n\n"; - pasteWithCtrlCmdV(text); - await waitFor(() => { - expect(h.elements.length).toEqual(3); - }); +describe("paste multiline text", () => { + it("should paste a single element, and offer to split it into an element per line", async () => { + const text = "sajgfakfn\n\n aaksfnknas\nakefnkasf\n"; + const { pasted, texts } = await pasteAndSplit(text); + expect(pasted.originalText).toBe(text.trim()); + + // blank lines dropped (the indentation kept), in place of the pasted + // text, selected + expect(texts.map((text) => text.originalText)).toEqual([ + "sajgfakfn", + " aaksfnknas", + "akefnkasf", + ]); + expect(h.elements.find((el) => el.id === pasted.id)?.isDeleted).toBe(true); + expect(texts[0].x).toBeCloseTo(pasted.x); + expect(texts[0].y).toBeCloseTo(pasted.y); + expect(Object.keys(h.state.selectedElementIds).sort()).toEqual( + texts.map((text) => text.id).sort(), + ); + expect(h.state.toast).toBe(null); + // the button's gone, the focus is back in the editor (to paste again) + expect(document.activeElement).toBe( + document.querySelector(".excalidraw-container"), + ); + + // one step to undo + Keyboard.undo(); + expect( + h.elements.filter((element) => !element.isDeleted).map((el) => el.id), + ).toEqual([pasted.id]); }); it("should not create any element if clipboard has only new lines", async () => { @@ -160,58 +204,167 @@ describe("paste text as single lines", () => { }); }); - it("should space items correctly", async () => { - const elementsMap = arrayToMap(h.elements); - - const text = "hkhkjhki\njgkjhffjh\njgkjhffjh"; - const lineHeightPx = - getLineHeightInPx( - h.app.state.currentItemFontSize, - getLineHeight(h.state.currentItemFontFamily), - ) + - 10 / h.app.state.zoom.value; + it("should space the split lines by half a line height, ignoring blank lines", async () => { + const lineHeightPx = getLineHeightInPx( + h.app.state.currentItemFontSize, + getLineHeight(h.state.currentItemFontFamily), + ); mouse.moveTo(100, 100); - pasteWithCtrlCmdV(text); - await waitFor(async () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [fx, firstElY] = getElementBounds(h.elements[0], elementsMap); - for (let i = 1; i < h.elements.length; i++) { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [fx, elY] = getElementBounds(h.elements[i], elementsMap); - expect(elY).toEqual(firstElY + lineHeightPx * i); - } - }); + const { texts } = await pasteAndSplit("hkhkjhki\njgkjhffjh\n\n\njgkjhffjh"); + expect(texts.length).toBe(3); + for (let i = 1; i < texts.length; i++) { + expect(texts[i].y).toBeCloseTo(texts[0].y + lineHeightPx * 1.5 * i); + } }); - it("should leave a space for blank new lines", async () => { - const elementsMap = arrayToMap(h.elements); - const text = "hkhkjhki\n\njgkjhffjh"; - const lineHeightPx = - getLineHeightInPx( - h.app.state.currentItemFontSize, - getLineHeight(h.state.currentItemFontFamily), - ) + - 10 / h.app.state.zoom.value; - mouse.moveTo(100, 100); - pasteWithCtrlCmdV(text); + it("should align the split lines as the text is", async () => { + for (const textAlign of ["left", "center", "right"] as const) { + API.updateScene({ elements: [] }); + API.setAppState({ currentItemTextAlign: textAlign }); + const { pasted, texts } = await pasteAndSplit("short\nmuch longer line"); + const [short, long] = texts; + expect(pasted.textAlign).toBe(textAlign); + expect(short.textAlign).toBe(textAlign); + expect(long.textAlign).toBe(textAlign); + expect(short.width).toBeLessThan(long.width); + const getEdge = (text: ExcalidrawTextElement) => + textAlign === "left" + ? text.x + : textAlign === "right" + ? text.x + text.width + : text.x + text.width / 2; + expect(getEdge(short)).toBeCloseTo(getEdge(pasted)); + expect(getEdge(long)).toBeCloseTo(getEdge(pasted)); + } + }); - await waitFor(async () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [fx, firstElY] = getElementBounds(h.elements[0], elementsMap); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [lx, lastElY] = getElementBounds(h.elements[1], elementsMap); - expect(lastElY).toEqual(firstElY + lineHeightPx * 2); + it("should stack split lines that wrap to different heights without overlap", async () => { + API.setAppState({ + width: 1000, + zoom: { value: 8 as NormalizedZoomValue }, }); + const long = + "Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!"; + const { pasted, texts } = await pasteAndSplit( + `short\n${long}\n${long} ${long}\nshort`, + ); + expect(pasted.autoResize).toBe(false); + // wrapped as they were in the pasted text + expect(texts.map((text) => text.text).join("\n")).toBe(pasted.text); + expect(texts.map((text) => text.autoResize)).toEqual([ + true, + false, + false, + true, + ]); + expect(texts[2].height).toBeGreaterThan(texts[1].height); + const lineGap = + getLineHeightInPx(texts[0].fontSize, texts[0].lineHeight) / 2; + for (let i = 1; i < texts.length; i++) { + expect(texts[i].y).toBeCloseTo( + texts[i - 1].y + texts[i - 1].height + lineGap, + ); + } + }); + + it("should keep the split lines wrapped as they were, not wrap them anew", async () => { + // kerning: a row is narrower than its characters are, one by one — as + // a long word is measured when it's broken up + setCustomTextMetricsProvider({ + getLineWidth: (text) => text.length * 10 - Math.max(0, text.length - 1), + }); + try { + API.setAppState({ + width: 1000, + zoom: { value: 8 as NormalizedZoomValue }, + }); + const { pasted, texts } = await pasteAndSplit( + "abcdefghijklmnopqrstuvwx\nshort", + ); + // the word's broken up into rows that, measured one character at a + // time, wouldn't fit the width the text ends up with + const rows = pasted.text.split("\n"); + expect(rows.length).toBeGreaterThan(2); + expect(rows[0].length * 10).toBeGreaterThan(pasted.width); + expect(texts.map((text) => text.text).join("\n")).toBe(pasted.text); + } finally { + setCustomTextMetricsProvider(undefined); + } + }); + + it("should take a split line that's left the frame out of it", async () => { + const frame = API.createElement({ + type: "frame", + x: 200, + y: 240, + width: 200, + height: 120, + }); + API.setElements([frame]); + // four lines fit the frame, not so half a line height apart + h.app.viewport.lastPosition.x = 300; + h.app.viewport.lastPosition.y = 300; + const { pasted, texts } = await pasteAndSplit("a\nb\nc\nd"); + expect(pasted.frameId).toBe(frame.id); + expect(texts.map((text) => text.frameId)).toEqual([ + frame.id, + frame.id, + frame.id, + null, + ]); + }); + + it("should put the split lines in the text's place in the layer order, and let go of arrows bound to it", async () => { + const rectangle = API.createElement({ type: "rectangle" }); + const arrow = API.createElement({ type: "arrow" }); + const { texts } = await pasteAndSplit("a\nb", (pasted) => { + API.setElements([ + { + ...pasted, + boundElements: [{ id: arrow.id, type: "arrow" }], + }, + rectangle, + { + ...arrow, + startBinding: { + elementId: pasted.id, + fixedPoint: [0.5, 0.5], + mode: "orbit", + }, + }, + ]); + }); + expect( + h.elements.filter((element) => !element.isDeleted).map((el) => el.id), + ).toEqual([...texts.map((text) => text.id), rectangle.id, arrow.id]); + expect( + (h.elements.find((el) => el.id === arrow.id) as ExcalidrawArrowElement) + .startBinding, + ).toBe(null); + }); + + it("should offer to split the text pasted last only", async () => { + pasteWithCtrlCmdV("a\nb"); + await waitFor(() => { + expect(h.state.toast).not.toBe(null); + }); + // no offer for this one: the one for the text before is gone + pasteWithCtrlCmdShiftV("c\nd"); + await waitFor(() => { + expect(h.elements.length).toBe(2); + }); + expect(h.state.toast).toBe(null); }); }); describe("paste text as a single element", () => { - it("should create single text element when copying text with Ctrl/Cmd+Shift+V", async () => { + it("should create single text element when copying text with Ctrl/Cmd+Shift+V, not offering to split it", async () => { const text = "sajgfakfn\naaksfnknas\nakefnkasf"; pasteWithCtrlCmdShiftV(text); await waitFor(() => { expect(h.elements.length).toEqual(1); }); + expect(h.state.toast).toBe(null); }); it("should not make a pasted text wider than the view", async () => { API.setAppState({ @@ -827,13 +980,9 @@ describe("clipboard - pasting mermaid definition", () => { const text = "flowchart TD xx\nA"; pasteWithCtrlCmdV(text); await waitFor(() => { - expect(h.elements.length).toEqual(2); - expect(h.elements).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: "text", text: "flowchart TD xx" }), - expect.objectContaining({ type: "text", text: "A" }), - ]), - ); + expect(h.elements).toEqual([ + expect.objectContaining({ type: "text", text: "flowchart TD xx\nA" }), + ]); }); }); }); @@ -938,8 +1087,7 @@ describe("paste routing", () => { ); await waitFor(() => { expect(h.elements.map((element) => (element as any).text)).toEqual([ - "hello", - "world", + "hello\n\nworld", ]); }); }); diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts index 2bda19f3fc..2d2842bc67 100644 --- a/packages/excalidraw/types.ts +++ b/packages/excalidraw/types.ts @@ -515,6 +515,8 @@ export interface AppState { message: React.ReactNode; closable?: boolean; duration?: number; + /** a link-like button after the message; it closes the toast, too */ + action?: { label: string; onClick: () => void }; } | null; zenModeEnabled: boolean; minimapEnabled: boolean;