4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-FocusManager'>/**
19 </span> * @class Ext.FocusManager
21 The FocusManager is responsible for globally:
23 1. Managing component focus
24 2. Providing basic keyboard navigation
25 3. (optional) Provide a visual cue for focused components, in the form of a focus ring/frame.
27 To activate the FocusManager, simply call {@link #enable `Ext.FocusManager.enable();`}. In turn, you may
28 deactivate the FocusManager by subsequently calling {@link #disable `Ext.FocusManager.disable();`}. The
29 FocusManager is disabled by default.
31 To enable the optional focus frame, pass `true` or `{focusFrame: true}` to {@link #enable}.
33 Another feature of the FocusManager is to provide basic keyboard focus navigation scoped to any {@link Ext.container.Container}
34 that would like to have navigation between its child {@link Ext.Component}'s. The {@link Ext.container.Container} can simply
35 call {@link #subscribe Ext.FocusManager.subscribe} to take advantage of this feature, and can at any time call
36 {@link #unsubscribe Ext.FocusManager.unsubscribe} to turn the navigation off.
40 * @author Jarred Nicholls <jarred@sencha.com>
41 * @docauthor Jarred Nicholls <jarred@sencha.com>
43 Ext.define('Ext.FocusManager', {
45 alternateClassName: 'Ext.FocusMgr',
48 observable: 'Ext.util.Observable'
52 'Ext.ComponentManager',
58 <span id='Ext-FocusManager-property-enabled'> /**
59 </span> * @property {Boolean} enabled
60 * Whether or not the FocusManager is currently enabled
64 <span id='Ext-FocusManager-property-focusedCmp'> /**
65 </span> * @property {Ext.Component} focusedCmp
66 * The currently focused component. Defaults to `undefined`.
70 focusElementCls: Ext.baseCSSPrefix + 'focus-element',
72 focusFrameCls: Ext.baseCSSPrefix + 'focus-frame',
74 <span id='Ext-FocusManager-property-whitelist'> /**
75 </span> * @property {Array} whitelist
76 * A list of xtypes that should ignore certain navigation input keys and
77 * allow for the default browser event/behavior. These input keys include:
86 * The FocusManager will not attempt to navigate when a component is an xtype (or descendents thereof)
87 * that belongs to this whitelist. E.g., an {@link Ext.form.field.Text} should allow
88 * the user to move the input cursor left and right, and to delete characters, etc.
90 * This whitelist currently defaults to `['textfield']`.
110 constructor: function() {
112 CQ = Ext.ComponentQuery;
115 <span id='Ext-FocusManager-event-beforecomponentfocus'> /**
116 </span> * @event beforecomponentfocus
117 * Fires before a component becomes focused. Return `false` to prevent
118 * the component from gaining focus.
119 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
120 * @param {Ext.Component} cmp The component that is being focused
121 * @param {Ext.Component} previousCmp The component that was previously focused,
122 * or `undefined` if there was no previously focused component.
125 'beforecomponentfocus',
127 <span id='Ext-FocusManager-event-componentfocus'> /**
128 </span> * @event componentfocus
129 * Fires after a component becomes focused.
130 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
131 * @param {Ext.Component} cmp The component that has been focused
132 * @param {Ext.Component} previousCmp The component that was previously focused,
133 * or `undefined` if there was no previously focused component.
138 <span id='Ext-FocusManager-event-disable'> /**
139 </span> * @event disable
140 * Fires when the FocusManager is disabled
141 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
145 <span id='Ext-FocusManager-event-enable'> /**
146 </span> * @event enable
147 * Fires when the FocusManager is enabled
148 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
153 // Setup KeyNav that's bound to document to catch all
154 // unhandled/bubbled key events for navigation
155 me.keyNav = Ext.create('Ext.util.KeyNav', Ext.getDoc(), {
159 backspace: me.focusLast,
160 enter: me.navigateIn,
162 tab: me.navigateSiblings
164 //space: me.navigateIn,
166 //left: me.navigateSiblings,
167 //right: me.navigateSiblings,
168 //down: me.navigateSiblings,
169 //up: me.navigateSiblings
173 me.subscribers = Ext.create('Ext.util.HashMap');
176 // Setup some ComponentQuery pseudos
177 Ext.apply(CQ.pseudos, {
178 focusable: function(cmps) {
179 var len = cmps.length,
184 isFocusable = function(x) {
185 return x && x.focusable !== false && CQ.is(x, '[rendered]:not([destroying]):not([isDestroyed]):not([disabled]){isVisible(true)}{el && c.el.dom && c.el.isVisible()}');
188 for (; i < len; i++) {
190 if (isFocusable(c)) {
198 nextFocus: function(cmps, idx, step) {
200 idx = parseInt(idx, 10);
202 var len = cmps.length,
206 for (; i != idx; i += step) {
209 } else if (i < 0) {
214 if (CQ.is(c, ':focusable')) {
216 } else if (c.placeholder && CQ.is(c.placeholder, ':focusable')) {
217 return [c.placeholder];
224 prevFocus: function(cmps, idx) {
225 return this.nextFocus(cmps, idx, -1);
228 root: function(cmps) {
229 var len = cmps.length,
234 for (; i < len; i++) {
246 <span id='Ext-FocusManager-method-addXTypeToWhitelist'> /**
247 </span> * Adds the specified xtype to the {@link #whitelist}.
248 * @param {String/Array} xtype Adds the xtype(s) to the {@link #whitelist}.
250 addXTypeToWhitelist: function(xtype) {
253 if (Ext.isArray(xtype)) {
254 Ext.Array.forEach(xtype, me.addXTypeToWhitelist, me);
258 if (!Ext.Array.contains(me.whitelist, xtype)) {
259 me.whitelist.push(xtype);
263 clearComponent: function(cmp) {
264 clearTimeout(this.cmpFocusDelay);
265 if (!cmp.isDestroyed) {
270 <span id='Ext-FocusManager-method-disable'> /**
271 </span> * Disables the FocusManager by turning of all automatic focus management and keyboard navigation
273 disable: function() {
283 Ext.ComponentManager.all.un('add', me.onComponentCreated, me);
287 // Stop handling key navigation
290 // disable focus for all components
291 me.setFocusAll(false);
293 me.fireEvent('disable', me);
296 <span id='Ext-FocusManager-method-enable'> /**
297 </span> * Enables the FocusManager by turning on all automatic focus management and keyboard navigation
298 * @param {Boolean/Object} options Either `true`/`false` to turn on the focus frame, or an object of the following options:
299 - focusFrame : Boolean
300 `true` to show the focus frame around a component when it is focused. Defaults to `false`.
303 enable: function(options) {
306 if (options === true) {
307 options = { focusFrame: true };
309 me.options = options = options || {};
315 // Handle components that are newly added after we are enabled
316 Ext.ComponentManager.all.on('add', me.onComponentCreated, me);
320 // Start handling key navigation
323 // enable focus for all components
324 me.setFocusAll(true, options);
326 // Finally, let's focus our global focus el so we start fresh
328 delete me.focusedCmp;
331 me.fireEvent('enable', me);
334 focusLast: function(e) {
337 if (me.isWhitelisted(me.focusedCmp)) {
341 // Go back to last focused item
342 if (me.previousFocusedCmp) {
343 me.previousFocusedCmp.focus();
347 getRootComponents: function() {
349 CQ = Ext.ComponentQuery,
350 inline = CQ.query(':focusable:root:not([floating])'),
351 floating = CQ.query(':focusable:root[floating]');
353 // Floating items should go to the top of our root stack, and be ordered
354 // by their z-index (highest first)
355 floating.sort(function(a, b) {
356 return a.el.getZIndex() > b.el.getZIndex();
359 return floating.concat(inline);
362 initDOM: function(options) {
365 cls = me.focusFrameCls;
368 Ext.onReady(me.initDOM, me);
372 // Create global focus element
374 me.focusEl = Ext.getBody().createChild({
376 cls: me.focusElementCls,
381 // Create global focus frame
382 if (!me.focusFrame && options.focusFrame) {
383 me.focusFrame = Ext.getBody().createChild({
386 { cls: cls + '-top' },
387 { cls: cls + '-bottom' },
388 { cls: cls + '-left' },
389 { cls: cls + '-right' }
391 style: 'top: -100px; left: -100px;'
393 me.focusFrame.setVisibilityMode(Ext.core.Element.DISPLAY);
394 me.focusFrameWidth = me.focusFrame.child('.' + cls + '-top').getHeight();
395 me.focusFrame.hide().setLeftTop(0, 0);
399 isWhitelisted: function(cmp) {
400 return cmp && Ext.Array.some(this.whitelist, function(x) {
401 return cmp.isXType(x);
405 navigateIn: function(e) {
407 focusedCmp = me.focusedCmp,
412 // No focus yet, so focus the first root cmp on the page
413 rootCmps = me.getRootComponents();
414 if (rootCmps.length) {
418 // Drill into child ref items of the focused cmp, if applicable.
419 // This works for any Component with a getRefItems implementation.
420 firstChild = Ext.ComponentQuery.query('>:focusable', focusedCmp)[0];
424 // Let's try to fire a click event, as if it came from the mouse
425 if (Ext.isFunction(focusedCmp.onClick)) {
427 focusedCmp.onClick(e);
434 navigateOut: function(e) {
438 if (!me.focusedCmp || !(parent = me.focusedCmp.up(':focusable'))) {
446 navigateSiblings: function(e, source, parent) {
450 EO = Ext.EventObject,
451 goBack = e.shiftKey || key == EO.LEFT || key == EO.UP,
452 checkWhitelist = key == EO.LEFT || key == EO.RIGHT || key == EO.UP || key == EO.DOWN,
453 nextSelector = goBack ? 'prev' : 'next',
454 idx, next, focusedCmp;
456 focusedCmp = (src.focusedCmp && src.focusedCmp.comp) || src.focusedCmp;
457 if (!focusedCmp && !parent) {
461 if (checkWhitelist && me.isWhitelisted(focusedCmp)) {
465 parent = parent || focusedCmp.up();
467 idx = focusedCmp ? Ext.Array.indexOf(parent.getRefItems(), focusedCmp) : -1;
468 next = Ext.ComponentQuery.query('>:' + nextSelector + 'Focus(' + idx + ')', parent)[0];
469 if (next && focusedCmp !== next) {
476 onComponentBlur: function(cmp, e) {
479 if (me.focusedCmp === cmp) {
480 me.previousFocusedCmp = cmp;
481 delete me.focusedCmp;
485 me.focusFrame.hide();
489 onComponentCreated: function(hash, id, cmp) {
490 this.setFocus(cmp, true, this.options);
493 onComponentDestroy: function(cmp) {
494 this.setFocus(cmp, false);
497 onComponentFocus: function(cmp, e) {
499 chain = me.focusChain;
501 if (!Ext.ComponentQuery.is(cmp, ':focusable')) {
502 me.clearComponent(cmp);
504 // Check our focus chain, so we don't run into a never ending recursion
505 // If we've attempted (unsuccessfully) to focus this component before,
506 // then we're caught in a loop of child->parent->...->child and we
507 // need to cut the loop off rather than feed into it.
512 // Try to focus the parent instead
513 var parent = cmp.up();
515 // Add component to our focus chain to detect infinite focus loop
516 // before we fire off an attempt to focus our parent.
517 // See the comments above.
518 chain[cmp.id] = true;
525 // Clear our focus chain when we have a focusable component
528 // Defer focusing for 90ms so components can do a layout/positioning
529 // and give us an ability to buffer focuses
530 clearTimeout(me.cmpFocusDelay);
531 if (arguments.length !== 2) {
532 me.cmpFocusDelay = Ext.defer(me.onComponentFocus, 90, me, [cmp, e]);
536 if (me.fireEvent('beforecomponentfocus', me, cmp, me.previousFocusedCmp) === false) {
537 me.clearComponent(cmp);
543 // If we have a focus frame, show it around the focused component
544 if (me.shouldShowFocusFrame(cmp)) {
545 var cls = '.' + me.focusFrameCls + '-',
547 fw = me.focusFrameWidth,
548 box = cmp.el.getPageBox(),
550 // Size the focus frame's t/b/l/r according to the box
551 // This leaves a hole in the middle of the frame so user
552 // interaction w/ the mouse can continue
557 ft = ff.child(cls + 'top'),
558 fb = ff.child(cls + 'bottom'),
559 fl = ff.child(cls + 'left'),
560 fr = ff.child(cls + 'right');
562 ft.setWidth(bw - 2).setLeftTop(bl + 1, bt);
563 fb.setWidth(bw - 2).setLeftTop(bl + 1, bt + bh - fw);
564 fl.setHeight(bh - 2).setLeftTop(bl, bt + 1);
565 fr.setHeight(bh - 2).setLeftTop(bl + bw - fw, bt + 1);
570 me.fireEvent('componentfocus', me, cmp, me.previousFocusedCmp);
573 onComponentHide: function(cmp) {
575 CQ = Ext.ComponentQuery,
581 focusedCmp = CQ.query('[id=' + me.focusedCmp.id + ']', cmp)[0];
582 cmpHadFocus = me.focusedCmp.id === cmp.id || focusedCmp;
585 me.clearComponent(focusedCmp);
589 me.clearComponent(cmp);
592 parent = CQ.query('^:focusable', cmp)[0];
599 removeDOM: function() {
602 // If we are still enabled globally, or there are still subscribers
603 // then we will halt here, since our DOM stuff is still being used
604 if (me.enabled || me.subscribers.length) {
613 delete me.focusFrame;
614 delete me.focusFrameWidth;
617 <span id='Ext-FocusManager-method-removeXTypeFromWhitelist'> /**
618 </span> * Removes the specified xtype from the {@link #whitelist}.
619 * @param {String/Array} xtype Removes the xtype(s) from the {@link #whitelist}.
621 removeXTypeFromWhitelist: function(xtype) {
624 if (Ext.isArray(xtype)) {
625 Ext.Array.forEach(xtype, me.removeXTypeFromWhitelist, me);
629 Ext.Array.remove(me.whitelist, xtype);
632 setFocus: function(cmp, focusable, options) {
636 needsTabIndex = function(n) {
637 return !Ext.Array.contains(me.tabIndexWhitelist, n.tagName.toLowerCase())
638 && n.tabIndex <= 0;
641 options = options || {};
643 // Come back and do this after the component is rendered
645 cmp.on('afterrender', Ext.pass(me.setFocus, arguments, me), me, { single: true });
649 el = cmp.getFocusEl();
652 // Decorate the component's focus el for focus-ability
653 if ((focusable && !me.focusData[cmp.id]) || (!focusable && me.focusData[cmp.id])) {
656 focusFrame: options.focusFrame
659 // Only set -1 tabIndex if we need it
660 // inputs, buttons, and anchor tags do not need it,
661 // and neither does any DOM that has it set already
662 // programmatically or in markup.
663 if (needsTabIndex(dom)) {
664 data.tabIndex = dom.tabIndex;
669 focus: data.focusFn = Ext.bind(me.onComponentFocus, me, [cmp], 0),
670 blur: data.blurFn = Ext.bind(me.onComponentBlur, me, [cmp], 0),
674 hide: me.onComponentHide,
675 close: me.onComponentHide,
676 beforedestroy: me.onComponentDestroy,
680 me.focusData[cmp.id] = data;
682 data = me.focusData[cmp.id];
683 if ('tabIndex' in data) {
684 dom.tabIndex = data.tabIndex;
686 el.un('focus', data.focusFn, me);
687 el.un('blur', data.blurFn, me);
688 cmp.un('hide', me.onComponentHide, me);
689 cmp.un('close', me.onComponentHide, me);
690 cmp.un('beforedestroy', me.onComponentDestroy, me);
692 delete me.focusData[cmp.id];
697 setFocusAll: function(focusable, options) {
699 cmps = Ext.ComponentManager.all.getArray(),
704 for (; i < len; i++) {
705 me.setFocus(cmps[i], focusable, options);
709 setupSubscriberKeys: function(container, keys) {
711 el = container.getFocusEl(),
714 backspace: me.focusLast,
715 enter: me.navigateIn,
720 navSiblings = function(e) {
721 if (me.focusedCmp === container) {
722 // Root the sibling navigation to this container, so that we
723 // can automatically dive into the container, rather than forcing
724 // the user to hit the enter key to dive in.
725 return me.navigateSiblings(e, me, container);
727 return me.navigateSiblings(e);
731 Ext.iterate(keys, function(key, cb) {
732 handlers[key] = function(e) {
733 var ret = navSiblings(e);
735 if (Ext.isFunction(cb) && cb.call(scope || container, e, ret) === true) {
743 return Ext.create('Ext.util.KeyNav', el, handlers);
746 shouldShowFocusFrame: function(cmp) {
748 opts = me.options || {};
750 if (!me.focusFrame || !cmp) {
755 if (opts.focusFrame) {
759 if (me.focusData[cmp.id].focusFrame) {
766 <span id='Ext-FocusManager-method-subscribe'> /**
767 </span> * Subscribes an {@link Ext.container.Container} to provide basic keyboard focus navigation between its child {@link Ext.Component}'s.
768 * @param {Ext.container.Container} container A reference to the {@link Ext.container.Container} on which to enable keyboard functionality and focus management.
769 * @param {Boolean/Object} options An object of the following options:
770 - keys : Array/Object
771 An array containing the string names of navigation keys to be supported. The allowed values are:
778 Or, an object containing those key names as keys with `true` or a callback function as their value. A scope may also be passed. E.g.:
781 left: this.onLeftKey,
782 right: this.onRightKey,
786 - focusFrame : Boolean (optional)
787 `true` to show the focus frame around a component when it is focused. Defaults to `false`.
790 subscribe: function(container, options) {
794 subs = me.subscribers,
796 // Recursively add focus ability as long as a descendent container isn't
797 // itself subscribed to the FocusManager, or else we'd have unwanted side
798 // effects for subscribing a descendent container twice.
799 safeSetFocus = function(cmp) {
800 if (cmp.isContainer && !subs.containsKey(cmp.id)) {
801 EA.forEach(cmp.query('>'), safeSetFocus);
802 me.setFocus(cmp, true, options);
803 cmp.on('add', data.onAdd, me);
804 } else if (!cmp.isContainer) {
805 me.setFocus(cmp, true, options);
809 // We only accept containers
810 if (!container || !container.isContainer) {
814 if (!container.rendered) {
815 container.on('afterrender', Ext.pass(me.subscribe, arguments, me), me, { single: true });
819 // Init the DOM, incase this is the first time it will be used
822 // Create key navigation for subscriber based on keys option
823 data.keyNav = me.setupSubscriberKeys(container, options.keys);
825 // We need to keep track of components being added to our subscriber
826 // and any containers nested deeply within it (omg), so let's do that.
827 // Components that are removed are globally handled.
828 // Also keep track of destruction of our container for auto-unsubscribe.
829 data.onAdd = function(ct, cmp, idx) {
832 container.on('beforedestroy', me.unsubscribe, me);
834 // Now we setup focusing abilities for the container and all its components
835 safeSetFocus(container);
837 // Add to our subscribers list
838 subs.add(container.id, data);
841 <span id='Ext-FocusManager-method-unsubscribe'> /**
842 </span> * Unsubscribes an {@link Ext.container.Container} from keyboard focus management.
843 * @param {Ext.container.Container} container A reference to the {@link Ext.container.Container} to unsubscribe from the FocusManager.
846 unsubscribe: function(container) {
849 subs = me.subscribers,
852 // Recursively remove focus ability as long as a descendent container isn't
853 // itself subscribed to the FocusManager, or else we'd have unwanted side
854 // effects for unsubscribing an ancestor container.
855 safeSetFocus = function(cmp) {
856 if (cmp.isContainer && !subs.containsKey(cmp.id)) {
857 EA.forEach(cmp.query('>'), safeSetFocus);
858 me.setFocus(cmp, false);
859 cmp.un('add', data.onAdd, me);
860 } else if (!cmp.isContainer) {
861 me.setFocus(cmp, false);
865 if (!container || !subs.containsKey(container.id)) {
869 data = subs.get(container.id);
870 data.keyNav.destroy();
871 container.un('beforedestroy', me.unsubscribe, me);
872 subs.removeAtKey(container.id);
873 safeSetFocus(container);