mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-11-20 21:23:22 +03:00
feat(editor): keep editing text when the window loses focus (#12675)
Co-authored-by: Márk Tolmács <14922478+mtolmacs@users.noreply.github.com> Co-authored-by: sahargavriely <63425950+sahargavriely@users.noreply.github.com> * feat(editor): keep editing text when the window loses focus The text editor submitted on any blur, the window's included: switching to another tab or app and back ended the edit. - submit only when the focus moves elsewhere in the document - until the user types, and while the window is away, the editor shows the scene's text, so a change made in another tab or by a collaborator is there to go on from - the editor closes when its element is deleted or removed from outside - collab: a text being edited takes newer remote copies. Its editor holds the draft and writes it on top, so the clients end up on the same text - excalidraw-app: the tab sync no longer ends a text edit * fix(editor): keep the text editor open when the update that removed its element brings it back The editor closes when its element is gone from the scene, deferred to after the update. A reset followed by a load of the same scene removes and restores the element in one go, and the deferred close then wrote the draft over the restored text.
This commit is contained in:
1 parent
d732d4f3d5
commit
894589f399
7 files changed
+377
-19
No files matched your search
@@ -610,6 +610,13 @@ const ExcalidrawWrapper = () => {
|
||||
setLangCode(getPreferredLanguage());
|
||||
excalidrawAPI.updateScene({
|
||||
...localDataState,
|
||||
// a text edit goes on through the sync: its editor takes the
|
||||
// synced text, or closes if the text is gone
|
||||
appState: localDataState.appState && {
|
||||
...localDataState.appState,
|
||||
editingTextElement:
|
||||
excalidrawAPI.getAppState().editingTextElement,
|
||||
},
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
LibraryIndexedDBAdapter.load().then((data) => {
|
||||
|
||||
@@ -221,7 +221,12 @@ export class AppText {
|
||||
const latestTextElement =
|
||||
this.app.scene.getElement<ExcalidrawTextElement>(element.id);
|
||||
|
||||
if (!latestTextElement || !isTextElement(latestTextElement)) {
|
||||
if (
|
||||
!latestTextElement ||
|
||||
!isTextElement(latestTextElement) ||
|
||||
// deleted from under the edit: the submit doesn't bring it back
|
||||
latestTextElement.isDeleted
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,9 +27,11 @@ export const shouldDiscardRemoteElement = (
|
||||
): boolean => {
|
||||
if (
|
||||
local &&
|
||||
// local element is being edited
|
||||
(local.id === localAppState.editingTextElement?.id ||
|
||||
local.id === localAppState.resizingElement?.id ||
|
||||
// local element is being edited. (Not a text in its editor: the editor
|
||||
// holds the draft, and writes it on top of whatever the scene has by
|
||||
// then, so the newest write wins on every client. Discarded, a remote
|
||||
// copy isn't sent again, and the clients end up on different texts.)
|
||||
(local.id === localAppState.resizingElement?.id ||
|
||||
local.id === localAppState.newElement?.id ||
|
||||
// local element is newer
|
||||
local.version > remote.version ||
|
||||
|
||||
@@ -304,6 +304,20 @@ describe("elements reconciliation", () => {
|
||||
test(["C", "A", "B"], ["C", "B", "D"], ["C:R", "A:L", "B:R", "D:R"]);
|
||||
});
|
||||
|
||||
it("takes a newer remote copy of the text being edited", () => {
|
||||
// the editor holds the draft and writes it on top (see textWysiwyg):
|
||||
// discarded here, the copy isn't sent again and the clients diverge
|
||||
const [local] = idsToElements(["A:1"]);
|
||||
const [remote] = idsToElements(["A:2"]);
|
||||
const reconciled = reconcileElements(
|
||||
[local] as OrderedExcalidrawElement[],
|
||||
[remote] as RemoteExcalidrawElement[],
|
||||
{ editingTextElement: local } as unknown as AppState,
|
||||
);
|
||||
expect(reconciled).toEqual([remote]);
|
||||
expect(reconciled[0]).not.toBe(local);
|
||||
});
|
||||
|
||||
it("test identical elements reconciliation", () => {
|
||||
const testIdentical = (
|
||||
local: ElementLike[],
|
||||
|
||||
@@ -907,8 +907,8 @@ describe("sticky notes", () => {
|
||||
// a click on empty canvas blurs the editor (submitting it), then its
|
||||
// pointer-up records — which used to leave the empty label's deletion
|
||||
// as a second, invisible entry. The wysiwyg's own outside-pointerdown
|
||||
// submit is disabled under vitest, so the blur is fired explicitly.
|
||||
fireEvent.blur(editor);
|
||||
// submit is disabled under vitest, so the editor is blurred explicitly.
|
||||
act(() => editor.blur());
|
||||
mouse.downAt(900, 800);
|
||||
mouse.up();
|
||||
|
||||
@@ -930,7 +930,7 @@ describe("sticky notes", () => {
|
||||
});
|
||||
expect(h.state.editingTextElement).not.toBeNull();
|
||||
|
||||
fireEvent.blur(editor);
|
||||
act(() => editor.blur());
|
||||
mouse.downAt(900, 800);
|
||||
mouse.up();
|
||||
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { newElementWith } from "@excalidraw/element";
|
||||
|
||||
import { CaptureUpdateAction } from "@excalidraw/element";
|
||||
|
||||
import type { ExcalidrawTextElement } from "@excalidraw/element/types";
|
||||
|
||||
import { reconcileElements } from "../data/reconcile";
|
||||
import { Excalidraw } from "../index";
|
||||
import { API } from "../tests/helpers/api";
|
||||
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
|
||||
import { getTextEditor, updateTextEditor } from "../tests/queries/dom";
|
||||
import { act, fireEvent, render, unmountComponent } from "../tests/test-utils";
|
||||
|
||||
import type { RemoteExcalidrawElement } from "../data/reconcile";
|
||||
|
||||
const { h } = window;
|
||||
const mouse = new Pointer("mouse");
|
||||
|
||||
const getText = (id: string) =>
|
||||
h.app.scene.getElement(id) as ExcalidrawTextElement;
|
||||
|
||||
describe("text editor & the world outside it", () => {
|
||||
let text: ExcalidrawTextElement;
|
||||
let editor: HTMLTextAreaElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
unmountComponent();
|
||||
await render(<Excalidraw handleKeyboardGlobally={true} />);
|
||||
text = API.createElement({ type: "text", text: "hello", x: 100, y: 100 });
|
||||
API.setElements([text]);
|
||||
mouse.doubleClickAt(text.x + 5, text.y + 5);
|
||||
editor = await getTextEditor();
|
||||
// the editor binds its blur handler (and takes focus) in a timeout
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(document.activeElement).toBe(editor);
|
||||
});
|
||||
|
||||
it("keeps the edit when the window loses focus", () => {
|
||||
updateTextEditor(editor, "hello wor");
|
||||
// the window going away blurs the textarea, which stays the active element
|
||||
fireEvent.blur(editor);
|
||||
fireEvent.blur(window);
|
||||
expect(h.state.editingTextElement?.id).toBe(text.id);
|
||||
expect(document.querySelector("textarea")).toBe(editor);
|
||||
|
||||
updateTextEditor(editor, "hello world");
|
||||
expect(getText(text.id).originalText).toBe("hello world");
|
||||
});
|
||||
|
||||
it("submits when the focus moves elsewhere in the document", () => {
|
||||
updateTextEditor(editor, "hello world");
|
||||
act(() => editor.blur());
|
||||
expect(h.state.editingTextElement).toBeNull();
|
||||
expect(document.querySelector("textarea")).toBeNull();
|
||||
expect(getText(text.id).originalText).toBe("hello world");
|
||||
});
|
||||
|
||||
it("takes a change of the text from outside, and edits go on from it", () => {
|
||||
updateTextEditor(editor, "hello wor");
|
||||
editor.setSelectionRange(2, 2);
|
||||
// the window goes away
|
||||
fireEvent.blur(editor);
|
||||
|
||||
// another tab's sync: the scene replaced, the edit kept
|
||||
API.updateScene({
|
||||
elements: [
|
||||
newElementWith(getText(text.id), { originalText: "hello world, B" }),
|
||||
],
|
||||
appState: { editingTextElement: h.state.editingTextElement },
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
expect(editor.value).toBe("hello world, B");
|
||||
expect(editor.selectionStart).toBe(2);
|
||||
expect(h.state.editingTextElement?.id).toBe(text.id);
|
||||
|
||||
updateTextEditor(editor, "hello world, B!");
|
||||
Keyboard.exitTextEditor(editor);
|
||||
expect(getText(text.id).originalText).toBe("hello world, B!");
|
||||
expect(getText(text.id).text).toBe("hello world, B!");
|
||||
|
||||
// one undo entry, back to what the outside brought
|
||||
Keyboard.undo();
|
||||
expect(getText(text.id).originalText).toBe("hello world, B");
|
||||
});
|
||||
|
||||
// When the editor shows a collaborator's edits of the text being edited,
|
||||
// as they come in:
|
||||
// - before the first keystroke, and while the window is away: yes
|
||||
// - from the first keystroke until the submit or the window going away:
|
||||
// no, the text is the user's draft
|
||||
describe("a collaborator editing the same text", () => {
|
||||
/** a collaborator's keystroke, the way it reaches the scene in a room */
|
||||
const remoteEdit = (originalText: string) => {
|
||||
const remote = newElementWith(getText(text.id), {
|
||||
originalText,
|
||||
text: originalText,
|
||||
});
|
||||
API.updateScene({
|
||||
elements: reconcileElements(
|
||||
h.app.scene.getElementsIncludingDeleted(),
|
||||
[remote] as RemoteExcalidrawElement[],
|
||||
h.state,
|
||||
),
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
return remote;
|
||||
};
|
||||
|
||||
it("shows their edits until the first keystroke", () => {
|
||||
remoteEdit("hello B");
|
||||
expect(editor.value).toBe("hello B");
|
||||
remoteEdit("hello BB");
|
||||
expect(editor.value).toBe("hello BB");
|
||||
});
|
||||
|
||||
it("keeps the draft while typing, and the submit writes it on top", () => {
|
||||
updateTextEditor(editor, "hello A");
|
||||
const remote = remoteEdit("hello B");
|
||||
// the scene has their text, the editor the draft
|
||||
expect(getText(text.id).originalText).toBe("hello B");
|
||||
expect(editor.value).toBe("hello A");
|
||||
|
||||
Keyboard.exitTextEditor(editor);
|
||||
expect(getText(text.id).originalText).toBe("hello A");
|
||||
// (newer than theirs: it wins on their client too)
|
||||
expect(getText(text.id).version).toBeGreaterThan(remote.version);
|
||||
});
|
||||
|
||||
it("shows their edits while the window is away, until the next keystroke", () => {
|
||||
updateTextEditor(editor, "hello A");
|
||||
fireEvent.blur(editor);
|
||||
fireEvent.blur(window);
|
||||
|
||||
remoteEdit("hello AB");
|
||||
expect(editor.value).toBe("hello AB");
|
||||
remoteEdit("hello ABB");
|
||||
expect(editor.value).toBe("hello ABB");
|
||||
|
||||
// back, and typing on from their text
|
||||
fireEvent.focus(window);
|
||||
fireEvent.focus(editor);
|
||||
updateTextEditor(editor, "hello ABBA");
|
||||
remoteEdit("hello ABBB");
|
||||
expect(editor.value).toBe("hello ABBA");
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves the textarea alone on its own input and unrelated updates", () => {
|
||||
const values: string[] = [];
|
||||
const descriptor = Object.getOwnPropertyDescriptor(
|
||||
HTMLTextAreaElement.prototype,
|
||||
"value",
|
||||
)!;
|
||||
Object.defineProperty(editor, "value", {
|
||||
get: () => descriptor.get!.call(editor),
|
||||
set: (value: string) => {
|
||||
values.push(value);
|
||||
descriptor.set!.call(editor, value);
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
// own input (the helper's own write goes around this setter)
|
||||
updateTextEditor(editor, "hello\n there");
|
||||
expect(values).toEqual([]);
|
||||
// an unrelated element changing (a collaborator's, say)
|
||||
const rect = API.createElement({ type: "rectangle", x: 500, y: 500 });
|
||||
API.updateScene({
|
||||
elements: [...h.elements, rect],
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
API.updateScene({
|
||||
elements: h.elements.map((element) =>
|
||||
element.id === rect.id ? newElementWith(element, { x: 600 }) : element,
|
||||
),
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
expect(values).toEqual([]);
|
||||
expect(editor.value).toBe("hello\n there");
|
||||
});
|
||||
|
||||
it("closes when the element is deleted from outside, which stays deleted", async () => {
|
||||
updateTextEditor(editor, "hello wor");
|
||||
API.updateScene({
|
||||
elements: [newElementWith(getText(text.id), { isDeleted: true })],
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
await act(async () => {});
|
||||
expect(document.querySelector("textarea")).toBeNull();
|
||||
expect(h.state.editingTextElement).toBeNull();
|
||||
expect(h.app.text.textWysiwygSubmitHandler).toBeNull();
|
||||
expect(getText(text.id).isDeleted).toBe(true);
|
||||
});
|
||||
|
||||
it("closes when the element is removed from outside", async () => {
|
||||
API.updateScene({
|
||||
elements: [],
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
await act(async () => {});
|
||||
expect(document.querySelector("textarea")).toBeNull();
|
||||
expect(h.state.editingTextElement).toBeNull();
|
||||
expect(h.app.text.textWysiwygSubmitHandler).toBeNull();
|
||||
expect(h.elements).toEqual([]);
|
||||
});
|
||||
|
||||
it("stays open when the update that removed the element brings it back", async () => {
|
||||
updateTextEditor(editor, "draft");
|
||||
const restored = newElementWith(getText(text.id), {
|
||||
originalText: "restored",
|
||||
text: "restored",
|
||||
});
|
||||
// a host's reset followed by a load of the same scene
|
||||
act(() => {
|
||||
h.app.updateScene({
|
||||
elements: [],
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
h.app.updateScene({
|
||||
elements: [restored],
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
});
|
||||
await act(async () => {});
|
||||
// not closed, so nothing wrote the draft over the restored text
|
||||
expect(document.querySelector("textarea")).toBe(editor);
|
||||
expect(getText(text.id).originalText).toBe("restored");
|
||||
});
|
||||
|
||||
it("keeps a label's container in step with a change from outside", async () => {
|
||||
Keyboard.exitTextEditor(editor);
|
||||
const container = UI.createElement("rectangle", {
|
||||
x: 300,
|
||||
y: 300,
|
||||
width: 120,
|
||||
height: 60,
|
||||
});
|
||||
mouse.doubleClickAt(360, 330);
|
||||
editor = await getTextEditor();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
updateTextEditor(editor, "label");
|
||||
const label = h.elements.find(
|
||||
(element) => "containerId" in element && element.containerId,
|
||||
) as ExcalidrawTextElement;
|
||||
expect(label.containerId).toBe(container.id);
|
||||
fireEvent.blur(editor);
|
||||
|
||||
API.updateScene({
|
||||
elements: h.elements.map((element) =>
|
||||
element.id === label.id
|
||||
? newElementWith(element as ExcalidrawTextElement, {
|
||||
originalText: "label from B",
|
||||
text: "label from B",
|
||||
})
|
||||
: element,
|
||||
),
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
expect(editor.value).toBe("label from B");
|
||||
updateTextEditor(editor, "label from B!");
|
||||
Keyboard.exitTextEditor(editor);
|
||||
expect(getText(label.id).originalText).toBe("label from B!");
|
||||
expect(
|
||||
h.app.scene.getElement(container.id)!.boundElements?.map(({ id }) => id),
|
||||
).toEqual([label.id]);
|
||||
Keyboard.undo();
|
||||
Keyboard.redo();
|
||||
expect(getText(label.id).originalText).toBe("label from B!");
|
||||
});
|
||||
});
|
||||
@@ -944,6 +944,7 @@ export const textWysiwyg = ({
|
||||
};
|
||||
|
||||
editable.oninput = () => {
|
||||
followsScene = false;
|
||||
const normalized = normalizeText(editable.value);
|
||||
if (editable.value !== normalized) {
|
||||
const selectionStart = editable.selectionStart;
|
||||
@@ -1155,18 +1156,20 @@ export const textWysiwyg = ({
|
||||
// it'd get stuck in an infinite loop of blur→onSubmit after we re-focus the
|
||||
// wysiwyg on update
|
||||
cleanup();
|
||||
const updateElement = app.scene.getElement(
|
||||
const updateElement = app.scene.getElement<ExcalidrawTextElement>(
|
||||
element.id,
|
||||
) as ExcalidrawTextElement;
|
||||
if (!updateElement) {
|
||||
return;
|
||||
}
|
||||
const container = getContainerElement(
|
||||
updateElement,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
// gone from the scene (see the scene update handler below): the edit
|
||||
// still ends, and nothing is written
|
||||
const container =
|
||||
updateElement && !updateElement.isDeleted
|
||||
? getContainerElement(
|
||||
updateElement,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
)
|
||||
: null;
|
||||
|
||||
if (container) {
|
||||
if (updateElement && container) {
|
||||
if (editable.value.trim()) {
|
||||
const boundTextElementId = getBoundTextElementId(container);
|
||||
if (!boundTextElementId || boundTextElementId !== element.id) {
|
||||
@@ -1205,6 +1208,29 @@ export const textWysiwyg = ({
|
||||
});
|
||||
};
|
||||
|
||||
// The textarea also blurs when the window does (switching tabs or apps).
|
||||
// It stays the document's active element then, and gets the focus back
|
||||
// with the window: the edit goes on. Only a focus that moved elsewhere in
|
||||
// the document submits.
|
||||
const handleBlur = () => {
|
||||
if (ownerDocument.activeElement !== editable) {
|
||||
handleSubmit();
|
||||
return;
|
||||
}
|
||||
// nobody is typing while the window is away
|
||||
followsScene = true;
|
||||
};
|
||||
|
||||
// The window lost focus while submit was disabled for a press (see
|
||||
// temporarilyDisableSubmit), whose pointerup may never come: the press is
|
||||
// over, and submit on blur is back.
|
||||
const onWindowBlur = () => {
|
||||
ownerWindow.removeEventListener("blur", onWindowBlur);
|
||||
ownerWindow.removeEventListener("pointerup", bindBlurEvent);
|
||||
editable.onblur = handleBlur;
|
||||
handleBlur();
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
// (the canvas takes the editor's place under the pointer, with the
|
||||
// cursor given to it for around the editor: see the pointermove below)
|
||||
@@ -1224,7 +1250,7 @@ export const textWysiwyg = ({
|
||||
capture: true,
|
||||
});
|
||||
ownerWindow.removeEventListener("pointerup", bindBlurEvent);
|
||||
ownerWindow.removeEventListener("blur", handleSubmit);
|
||||
ownerWindow.removeEventListener("blur", onWindowBlur);
|
||||
ownerWindow.removeEventListener("beforeunload", handleSubmit);
|
||||
unbindUpdate();
|
||||
unsubOnChange();
|
||||
@@ -1268,7 +1294,7 @@ export const textWysiwyg = ({
|
||||
// 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.onblur = handleBlur;
|
||||
editable.focus({ preventScroll: true });
|
||||
if (pendingInitialSelection) {
|
||||
editable.setSelectionRange(
|
||||
@@ -1285,7 +1311,7 @@ export const textWysiwyg = ({
|
||||
ownerWindow.addEventListener("pointerup", bindBlurEvent);
|
||||
// handle edge-case where pointerup doesn't fire e.g. due to user
|
||||
// alt-tabbing away
|
||||
ownerWindow.addEventListener("blur", handleSubmit);
|
||||
ownerWindow.addEventListener("blur", onWindowBlur);
|
||||
};
|
||||
|
||||
// prevent blur when changing properties from the menu
|
||||
@@ -1402,6 +1428,34 @@ export const textWysiwyg = ({
|
||||
|
||||
// handle updates of textElement properties of editing element
|
||||
const unbindUpdate = app.scene.onUpdate(() => {
|
||||
const latestElement = app.scene.getElement(element.id);
|
||||
if (!latestElement || latestElement.isDeleted) {
|
||||
// the element went away under the edit (another tab's sync, a host's
|
||||
// update): so does the editor. After the update that's under way, and
|
||||
// unless that brought it back (a reset followed by a load).
|
||||
queueMicrotask(() => {
|
||||
const currentElement = app.scene.getElement(element.id);
|
||||
if (!currentElement || currentElement.isDeleted) {
|
||||
handleSubmit();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Until the user types, the editor shows the scene's text: a change
|
||||
// from outside (another tab's sync, a collaborator's edit, a host's
|
||||
// update) is taken. Setting the value fires no input event: nothing is
|
||||
// written back.
|
||||
if (followsScene && isTextElement(latestElement)) {
|
||||
const nextValue = normalizeText(latestElement.originalText);
|
||||
if (nextValue !== editable.value) {
|
||||
const { selectionStart, selectionEnd } = editable;
|
||||
editable.value = nextValue;
|
||||
editable.setSelectionRange(
|
||||
Math.min(selectionStart, nextValue.length),
|
||||
Math.min(selectionEnd, nextValue.length),
|
||||
);
|
||||
}
|
||||
}
|
||||
updateWysiwygStyle();
|
||||
const isPopupOpened = !!ownerDocument.activeElement?.closest(
|
||||
".properties-content",
|
||||
@@ -1449,6 +1503,12 @@ export const textWysiwyg = ({
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let isDestroyed = false;
|
||||
// Whether the editor takes the scene's text when it changes from outside
|
||||
// (see the scene update handler). Typing makes the text the user's draft,
|
||||
// which is theirs until submitted: a collaborator typing into the same
|
||||
// text doesn't change it under them. The window going away gives it back
|
||||
// to the scene.
|
||||
let followsScene = true;
|
||||
|
||||
if (autoSelect && !pendingInitialSelection) {
|
||||
// select on init (focusing is done separately inside the bindBlurEvent()
|
||||
|
||||
Reference in new issue
Block a user