Skip to content

Commit

Permalink
[editor] fix editor focus
Browse files Browse the repository at this point in the history
  • Loading branch information
ananthakumaran committed Feb 1, 2024
1 parent 0d4b88b commit 29a77e2
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
18 changes: 18 additions & 0 deletions src/lib/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,21 @@ export function updateContent(editor: EditorView, content: string) {
const newColumn = Math.min(newLine.from + column, newLine.to);
editor.dispatch({ selection: { anchor: newColumn, head: newColumn } });
}

export function focus(editor: EditorView, retry = 5) {
if (!editor.hasFocus) {
editor.focus();
if (!editor.hasFocus && retry > 0) {
setTimeout(
() => {
try {
focus(editor, retry - 1);
} catch (e) {
// ignore
}
},
(5 - retry) * 100 + 100
);
}
}
}
13 changes: 9 additions & 4 deletions src/routes/(app)/ledger/editor/[slug]/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
<script lang="ts">
import { createEditor, editorState, moveToEnd, moveToLine, updateContent } from "$lib/editor";
import {
createEditor,
editorState,
focus,
moveToEnd,
moveToLine,
updateContent
} from "$lib/editor";
import { insertTab } from "@codemirror/commands";
import { ajax, buildDirectoryTree, type LedgerFile } from "$lib/utils";
import { redo, undo } from "@codemirror/commands";
Expand Down Expand Up @@ -164,10 +171,8 @@
}
});
if (lineNumber > 0) {
if (!editor.hasFocus) {
editor.focus();
}
moveToLine(editor, lineNumber, true);
focus(editor);
lineNumber = 0;
} else {
moveToEnd(editor);
Expand Down
6 changes: 2 additions & 4 deletions src/routes/(app)/more/sheets/[slug]/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts">
import { createEditor, sheetEditorState } from "$lib/sheet";
import { moveToLine, updateContent } from "$lib/editor";
import { focus, moveToLine, updateContent } from "$lib/editor";
import {
ajax,
buildDirectoryTree,
Expand Down Expand Up @@ -157,10 +157,8 @@
}
});
if (lineNumber > 0) {
if (!editor.hasFocus) {
editor.focus();
}
moveToLine(editor, lineNumber, true);
focus(editor);
lineNumber = 0;
}
}
Expand Down

0 comments on commit 29a77e2

Please sign in to comment.