From f452481cbffe6b7f9de87fc6867a83d8a8d02936 Mon Sep 17 00:00:00 2001 From: Andrew Duthie Date: Mon, 24 Jul 2017 12:00:42 -0400 Subject: [PATCH] Refactor inert to explicitly disable fields --- components/inert/index.js | 92 +++++---------------------------------- 1 file changed, 12 insertions(+), 80 deletions(-) diff --git a/components/inert/index.js b/components/inert/index.js index 81fd860cec9800..751cc028af0869 100644 --- a/components/inert/index.js +++ b/components/inert/index.js @@ -3,93 +3,25 @@ */ import { Component } from 'element'; -const focusable = [ - 'INPUT', - 'SELECT', - 'TEXTAREA', - 'BUTTON', - 'OBJECT', -]; - -function isFocusable( node ) { - if ( node.tabIndex < 0 ) { - return false; - } else if ( -1 !== focusable.indexOf( node.nodeName ) ) { - return ! node.disabled; - } else if ( 'A' === node.nodeName || 'AREA' === node.nodeName ) { - return node.hasAttribute( 'href' ); - } - - return node.tabIndex >= 0; -} - -function getNextFocusable( node, siblingDirection ) { - let parent = node.parentNode; - - let childDirection; - if ( 'nextSibling' === siblingDirection ) { - childDirection = 'firstChild'; - } else { - childDirection = 'lastChild'; - } - - do { - while ( node[ siblingDirection ] ) { - if ( isFocusable( node[ siblingDirection ] ) ) { - return node[ siblingDirection ]; - } - - node = node[ siblingDirection ]; - } - - node = parent[ siblingDirection ]; - if ( node ) { - while ( node[ childDirection ] ) { - node = node[ childDirection ]; - } - } else { - node = parent; - } - - if ( isFocusable( node ) ) { - return node; - } - - parent = node.parentNode; - } while ( parent ); -} - class Inert extends Component { - constructor() { - super( ...arguments ); - - this.onKeyPress = this.onKeyPress.bind( this ); - } - componentDidMount() { - document.addEventListener( 'keydown', this.onKeyPress ); + this.disableFields(); } - componentWillUnmount() { - document.removeEventListener( 'keydown', this.onKeyPress ); + componentDidUpdate() { + this.disableFields(); } - onKeyPress( event ) { - if ( event.which !== 9 ) { - return; - } - - const testDirection = event.shiftKey ? 'nextSibling' : 'previousSibling'; - if ( event.target !== getNextFocusable( this.node, testDirection ) ) { - return; - } + disableFields() { + const focusables = this.node.querySelectorAll( 'input,select,textarea,button,object,a,area' ); + Array.prototype.forEach.call( focusables, ( node ) => { + node.tabIndex = -1; + } ); - const nextDirection = event.shiftKey ? 'previousSibling' : 'nextSibling'; - const nextFocusable = getNextFocusable( this.node, nextDirection ); - if ( nextFocusable ) { - nextFocusable.focus(); - event.preventDefault(); - } + const editables = this.node.querySelectorAll( '[contenteditable]' ); + Array.prototype.forEach.call( editables, ( node ) => { + node.removeAttribute( 'contenteditable' ); + } ); } render() {