@@ -16,18 +16,31 @@ const DelegateFocusMixinImplementation = (superclass) =>
1616 */
1717 autofocus : {
1818 type : Boolean
19+ } ,
20+
21+ /**
22+ * A reference to the focusable element controlled by the mixin.
23+ * It can be an input, textarea, button or any element with tabindex > -1.
24+ *
25+ * Any component implementing this mixin is expected to provide it
26+ * by using `this._setFocusElement(input)` Polymer API.
27+ *
28+ * @protected
29+ * @type {!HTMLElement }
30+ */
31+ focusElement : {
32+ type : Object ,
33+ readOnly : true ,
34+ observer : '_focusElementChanged'
1935 }
2036 } ;
2137 }
2238
23- /**
24- * Any element extending this mixin is required to implement this getter.
25- * It returns the actual focusable element in the component.
26- * @return {Element | null | undefined }
27- */
28- get focusElement ( ) {
29- console . warn ( `Please implement the 'focusElement' property in <${ this . localName } >` ) ;
30- return null ;
39+ constructor ( ) {
40+ super ( ) ;
41+
42+ this . _boundOnBlur = this . _onBlur . bind ( this ) ;
43+ this . _boundOnFocus = this . _onFocus . bind ( this ) ;
3144 }
3245
3346 /** @protected */
@@ -65,10 +78,62 @@ const DelegateFocusMixinImplementation = (superclass) =>
6578 }
6679 }
6780
81+ /** @protected */
82+ _focusElementChanged ( element , oldElement ) {
83+ if ( element ) {
84+ this . _addFocusListeners ( element ) ;
85+ } else if ( oldElement ) {
86+ this . _removeFocusListeners ( oldElement ) ;
87+ }
88+ }
89+
90+ /**
91+ * @param {HTMLElement } element
92+ * @protected
93+ */
94+ _addFocusListeners ( element ) {
95+ element . addEventListener ( 'blur' , this . _boundOnBlur ) ;
96+ element . addEventListener ( 'focus' , this . _boundOnFocus ) ;
97+ }
98+
99+ /**
100+ * @param {HTMLElement } element
101+ * @protected
102+ */
103+ _removeFocusListeners ( element ) {
104+ element . removeEventListener ( 'blur' , this . _boundOnBlur ) ;
105+ element . removeEventListener ( 'focus' , this . _boundOnFocus ) ;
106+ }
107+
108+ /**
109+ * Focus event does not bubble, so we dispatch it manually
110+ * on the host element to support adding focus listeners
111+ * when the focusable element is placed in light DOM.
112+ * @param {FocusEvent } event
113+ * @protected
114+ */
115+ _onFocus ( event ) {
116+ event . stopPropagation ( ) ;
117+ this . dispatchEvent ( new Event ( 'focus' ) ) ;
118+ }
119+
120+ /**
121+ * Blur event does not bubble, so we dispatch it manually
122+ * on the host element to support adding blur listeners
123+ * when the focusable element is placed in light DOM.
124+ * @param {FocusEvent } event
125+ * @protected
126+ */
127+ _onBlur ( event ) {
128+ event . stopPropagation ( ) ;
129+ this . dispatchEvent ( new Event ( 'blur' ) ) ;
130+ }
131+
68132 /**
69133 * @param {Event } event
70134 * @return {boolean }
71135 * @protected
136+ * @override
72137 */
73138 _shouldSetFocus ( event ) {
74139 return event . target === this . focusElement ;
0 commit comments