]> cat aescling's git repositories - mastodon.git/commitdiff
[Glitch] Trap tab in modals
authorThibG <thib@sitedethib.com>
Tue, 6 Aug 2019 09:59:28 +0000 (11:59 +0200)
committerThibaut Girka <thib@sitedethib.com>
Tue, 6 Aug 2019 13:09:30 +0000 (15:09 +0200)
Port 5c73746b695e5bc540b41f5ae1406eac6220886e to glitch-soc

Signed-off-by: Thibaut Girka <thib@sitedethib.com>
app/javascript/flavours/glitch/components/modal_root.js

index 4e8648b497ac5acdd3d53590f68d7d22bb67bdcf..fd0af9f6ee818e19292dd5649fdb38e499768aad 100644 (file)
@@ -26,8 +26,30 @@ export default class ModalRoot extends React.PureComponent {
     }
   }
 
+  handleKeyDown = (e) => {
+    if (e.key === 'Tab') {
+      const focusable = Array.from(this.node.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((x) => window.getComputedStyle(x).display !== 'none');
+      const index = focusable.indexOf(e.target);
+
+      let element;
+
+      if (e.shiftKey) {
+        element = focusable[index - 1] || focusable[focusable.length - 1];
+      } else {
+        element = focusable[index + 1] || focusable[0];
+      }
+
+      if (element) {
+        element.focus();
+        e.stopPropagation();
+        e.preventDefault();
+      }
+    }
+  }
+
   componentDidMount () {
     window.addEventListener('keyup', this.handleKeyUp, false);
+    window.addEventListener('keydown', this.handleKeyDown, false);
     this.history = this.context.router ? this.context.router.history : createHistory();
   }
 
@@ -60,6 +82,7 @@ export default class ModalRoot extends React.PureComponent {
 
   componentWillUnmount () {
     window.removeEventListener('keyup', this.handleKeyUp);
+    window.removeEventListener('keydown', this.handleKeyDown);
   }
 
   handleModalClose () {