FIX: attempts to make autofocus more resilient in modals (#10680)

FIX: attempts to make autofocus more resilient in modals (#10680)

The current situation could cause a transition on the button to end after/during modal has shown and causing the button to get focus again. Browsers would then refuse to switch focus.

This is a kinda convulted solution, but it’s a general purpose solution which doesn’t involve changing anything in plugins/themes or core templates.

diff --git a/app/assets/javascripts/discourse/app/components/d-modal.js b/app/assets/javascripts/discourse/app/components/d-modal.js
index 3b33542..63e9e75 100644
--- a/app/assets/javascripts/discourse/app/components/d-modal.js
+++ b/app/assets/javascripts/discourse/app/components/d-modal.js
@@ -1,3 +1,4 @@
+import afterTransition from "discourse/lib/after-transition";
 import I18n from "I18n";
 import { next } from "@ember/runloop";
 import { on } from "discourse-common/utils/decorators";
@@ -116,5 +117,15 @@ export default Component.extend({
     } else {
       this.set("dismissable", true);
     }
+
+    if (this.element) {
+      const autofocusInputs = this.element.querySelectorAll(
+        ".modal-body input[autofocus]"
+      );
+
+      if (autofocusInputs.length) {
+        afterTransition(() => autofocusInputs[0].focus());
+      }
+    }
   },
 });
diff --git a/app/assets/javascripts/discourse/app/controllers/insert-hyperlink.js b/app/assets/javascripts/discourse/app/controllers/insert-hyperlink.js
index e560031..d3821b2 100644
--- a/app/assets/javascripts/discourse/app/controllers/insert-hyperlink.js
+++ b/app/assets/javascripts/discourse/app/controllers/insert-hyperlink.js
@@ -26,8 +26,6 @@ export default Controller.extend(ModalFunctionality, {
       element
         .closest(".modal-inner-container")
         .addEventListener("mousedown", this.mouseDown);
-
-      document.activeElement.blur();
     });
   },
 

GitHub sha: 4af48f79

1 Like

This commit appears in #10680 which was merged by jjaffeux.