From 982f5717f7e2e26f3d0e9c3045b4b315d5558f6b Mon Sep 17 00:00:00 2001
From: Louis Capitanchik <contact@louiscap.co>
Date: Wed, 3 Aug 2022 01:30:53 +0100
Subject: [PATCH] Autofocus canvas in web after init

---
 build/web/autofocus.js            | 31 +++++++++++++++++++++++++++++++
 game_core/index.html              |  2 ++
 game_core/src/assets/resources.rs |  6 +++---
 3 files changed, 36 insertions(+), 3 deletions(-)
 create mode 100644 build/web/autofocus.js

diff --git a/build/web/autofocus.js b/build/web/autofocus.js
new file mode 100644
index 0000000..bd59c50
--- /dev/null
+++ b/build/web/autofocus.js
@@ -0,0 +1,31 @@
+document.addEventListener('DOMContentLoaded', function() {
+	if ('MutationObserver' in window) {
+		const config = {
+			attributes: false,
+			childList: true,
+			subtree: false,
+		}
+
+		function onElementAdded(mutationsList, observer) {
+			for (const mutation of mutationsList) {
+				if (mutation.type === 'childList') {
+					if (mutation.addedNodes.length > 0) {
+						for (const node of mutation.addedNodes) {
+							if (node.nodeName.toLowerCase() === 'canvas') {
+								node.focus();
+								if (window.focusHandler) {
+									window.focusHandler.disconnect()
+									delete window.focusHandler
+								}
+								return
+							}
+						}
+					}
+				}
+			}
+		}
+
+		window.focusHandler = new MutationObserver(onElementAdded)
+		window.focusHandler.observe(document.body, config)
+	}
+})
diff --git a/game_core/index.html b/game_core/index.html
index 7e303d2..ea8e997 100644
--- a/game_core/index.html
+++ b/game_core/index.html
@@ -103,5 +103,7 @@
 </main>
 
 <link data-trunk rel="inline" href="../build/web/audio.js"/>
+<link data-trunk rel="inline" href="../build/web/autofocus.js"/>
+
 </body>
 </html>
\ No newline at end of file
diff --git a/game_core/src/assets/resources.rs b/game_core/src/assets/resources.rs
index d7e078c..fb22eab 100644
--- a/game_core/src/assets/resources.rs
+++ b/game_core/src/assets/resources.rs
@@ -33,9 +33,9 @@ impl SpriteSheetConfig {
 
 #[derive(Default)]
 pub struct AssetHandles {
-	pub(crate) images: HashMap<String, Handle<Image>>,
-	pub(crate) atlas: HashMap<String, Handle<TextureAtlas>>,
-	pub(crate) sounds: HashMap<String, Handle<AudioSource>>,
+	pub images: HashMap<String, Handle<Image>>,
+	pub atlas: HashMap<String, Handle<TextureAtlas>>,
+	pub sounds: HashMap<String, Handle<AudioSource>>,
 }
 
 impl SuppliesAudio for AssetHandles {
-- 
GitLab