Skip to content

Commit eab1cca

Browse files
[fix] regain focus when it gets lost by mistake (#161)
closes #150 Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
1 parent a135717 commit eab1cca

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

src/routes/tutorial/[slug]/Editor.svelte

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
<script>
22
import { dev } from '$app/environment';
3-
import { monaco } from '$lib/client/monaco/monaco.js';
43
import { createEventDispatcher, onMount } from 'svelte';
54
65
/**
@@ -36,6 +35,13 @@
3635
let w = 0;
3736
let h = 0;
3837
38+
/**
39+
* The iframe sometimes takes focus control in ways we can't prevent
40+
* while the editor is focussed. Refocus the editor in these cases.
41+
* This boolean tracks whether or not the editor should be refocused.
42+
*/
43+
let preserve_focus = true;
44+
3945
onMount(() => {
4046
let destroyed = false;
4147
@@ -234,8 +240,37 @@
234240
}
235241
</script>
236242
243+
<svelte:window
244+
on:pointerdown={(e) => {
245+
if (!container.contains(/** @type {HTMLElement} */ (e.target))) {
246+
preserve_focus = false;
247+
}
248+
}}
249+
/>
250+
237251
<div bind:clientWidth={w} bind:clientHeight={h}>
238-
<div bind:this={container} />
252+
<div
253+
bind:this={container}
254+
on:keydown={(e) => {
255+
if (e.key === 'Tab') {
256+
preserve_focus = false;
257+
258+
setTimeout(() => {
259+
preserve_focus = true;
260+
}, 0);
261+
}
262+
}}
263+
on:focusin={() => {
264+
preserve_focus = true;
265+
}}
266+
on:focusout={() => {
267+
if (preserve_focus) {
268+
setTimeout(() => {
269+
instance?.editor.focus();
270+
}, 0);
271+
}
272+
}}
273+
/>
239274
</div>
240275
241276
<style>

0 commit comments

Comments
 (0)