diff --git a/ts/editor/MathjaxHandleEditor.svelte b/ts/editor/MathjaxHandleEditor.svelte
index fc996d89e..ccbaae500 100644
--- a/ts/editor/MathjaxHandleEditor.svelte
+++ b/ts/editor/MathjaxHandleEditor.svelte
@@ -46,12 +46,12 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
+
diff --git a/ts/editor/editing-area.ts b/ts/editor/editing-area.ts
index 01a167d14..c2d36cd30 100644
--- a/ts/editor/editing-area.ts
+++ b/ts/editor/editing-area.ts
@@ -16,7 +16,7 @@ import type { Codable } from "./codable";
import { updateActiveButtons } from "./toolbar";
import { bridgeCommand } from "./lib";
import { onInput, onKey, onKeyUp } from "./input-handlers";
-import { onFocus, onBlur } from "./focus-handlers";
+import { deferFocusDown, saveFieldIfFieldChanged } from "./focus-handlers";
import { nightModeKey } from "components/context-keys";
import { decoratedComponents } from "editable/decorated";
@@ -202,13 +202,12 @@ export class EditingArea extends HTMLDivElement {
this.activeInput.surroundSelection(before, after);
}
- onFocus(event: FocusEvent): void {
- onFocus(event);
+ onFocus(): void {
+ deferFocusDown(this);
}
onBlur(event: FocusEvent): void {
- this.resetHandles();
- onBlur(event);
+ saveFieldIfFieldChanged(this, event.relatedTarget as Element);
}
onEnter(event: KeyboardEvent): void {
diff --git a/ts/editor/focus-handlers.ts b/ts/editor/focus-handlers.ts
index 11c317ead..109dfbdfb 100644
--- a/ts/editor/focus-handlers.ts
+++ b/ts/editor/focus-handlers.ts
@@ -12,19 +12,30 @@ import { saveField } from "./change-timer";
import { bridgeCommand } from "./lib";
import { getCurrentField } from "./helpers";
-export function onFocus(evt: FocusEvent): void {
- const currentField = evt.currentTarget as EditingArea;
- currentField.focus();
- currentField.caretToEnd();
+export function deferFocusDown(editingArea: EditingArea): void {
+ editingArea.focus();
+ editingArea.caretToEnd();
- bridgeCommand(`focus:${currentField.ord}`);
+ if (editingArea.getSelection().anchorNode === null) {
+ // selection is not inside editable after focusing
+ editingArea.caretToEnd();
+ }
+
+ bridgeCommand(`focus:${editingArea.ord}`);
fieldFocused.set(true);
}
-export function onBlur(evt: FocusEvent): void {
- const previousFocus = evt.currentTarget as EditingArea;
- const currentFieldUnchanged = previousFocus === getCurrentField();
+export function saveFieldIfFieldChanged(
+ editingArea: EditingArea,
+ focusTo: Element | null
+): void {
+ const fieldChanged =
+ editingArea !== getCurrentField() && !editingArea.contains(focusTo);
- saveField(previousFocus, currentFieldUnchanged ? "key" : "blur");
+ saveField(editingArea, fieldChanged ? "blur" : "key");
fieldFocused.set(false);
+
+ if (fieldChanged) {
+ editingArea.resetHandles();
+ }
}