Skip to content

regain focus when it gets lost by mistake #161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions src/routes/tutorial/[slug]/Editor.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<script>
import { dev } from '$app/environment';
import { monaco } from '$lib/client/monaco/monaco.js';
import { createEventDispatcher, onMount } from 'svelte';

/**
Expand Down Expand Up @@ -36,6 +35,13 @@
let w = 0;
let h = 0;

/**
* The iframe sometimes takes focus control in ways we can't prevent
* while the editor is focussed. Refocus the editor in these cases.
* This boolean tracks whether or not the editor should be refocused.
*/
let preserve_focus = true;

onMount(() => {
let destroyed = false;

Expand Down Expand Up @@ -234,8 +240,37 @@
}
</script>

<svelte:window
on:pointerdown={(e) => {
if (!container.contains(/** @type {HTMLElement} */ (e.target))) {
preserve_focus = false;
}
}}
/>

<div bind:clientWidth={w} bind:clientHeight={h}>
<div bind:this={container} />
<div
bind:this={container}
on:keydown={(e) => {
if (e.key === 'Tab') {
preserve_focus = false;

setTimeout(() => {
preserve_focus = true;
}, 0);
}
}}
on:focusin={() => {
preserve_focus = true;
}}
on:focusout={() => {
if (preserve_focus) {
setTimeout(() => {
instance?.editor.focus();
}, 0);
}
}}
/>
</div>

<style>
Expand Down