4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../resources/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 `Ext.FocusManager.enable();`. In turn, you may
28 deactivate the FocusManager by subsequently calling `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.
39 * @author Jarred Nicholls <jarred@sencha.com>
40 * @docauthor Jarred Nicholls <jarred@sencha.com>
42 Ext.define('Ext.FocusManager', {
44 alternateClassName: 'Ext.FocusMgr',
47 observable: 'Ext.util.Observable'
51 'Ext.ComponentManager',
57 <span id='Ext-FocusManager-property-enabled'> /**
58 </span> * @property {Boolean} enabled
59 * Whether or not the FocusManager is currently enabled
63 <span id='Ext-FocusManager-property-focusedCmp'> /**
64 </span> * @property {Ext.Component} focusedCmp
65 * The currently focused component. Defaults to `undefined`.
68 focusElementCls: Ext.baseCSSPrefix + 'focus-element',
70 focusFrameCls: Ext.baseCSSPrefix + 'focus-frame',
72 <span id='Ext-FocusManager-property-whitelist'> /**
73 </span> * @property {String[]} whitelist
74 * A list of xtypes that should ignore certain navigation input keys and
75 * allow for the default browser event/behavior. These input keys include:
84 * The FocusManager will not attempt to navigate when a component is an xtype (or descendents thereof)
85 * that belongs to this whitelist. E.g., an {@link Ext.form.field.Text} should allow
86 * the user to move the input cursor left and right, and to delete characters, etc.
105 constructor: function() {
107 CQ = Ext.ComponentQuery;
110 <span id='Ext-FocusManager-event-beforecomponentfocus'> /**
111 </span> * @event beforecomponentfocus
112 * Fires before a component becomes focused. Return `false` to prevent
113 * the component from gaining focus.
114 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
115 * @param {Ext.Component} cmp The component that is being focused
116 * @param {Ext.Component} previousCmp The component that was previously focused,
117 * or `undefined` if there was no previously focused component.
119 'beforecomponentfocus',
121 <span id='Ext-FocusManager-event-componentfocus'> /**
122 </span> * @event componentfocus
123 * Fires after a component becomes focused.
124 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
125 * @param {Ext.Component} cmp The component that has been focused
126 * @param {Ext.Component} previousCmp The component that was previously focused,
127 * or `undefined` if there was no previously focused component.
131 <span id='Ext-FocusManager-event-disable'> /**
132 </span> * @event disable
133 * Fires when the FocusManager is disabled
134 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
138 <span id='Ext-FocusManager-event-enable'> /**
139 </span> * @event enable
140 * Fires when the FocusManager is enabled
141 * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
146 // Setup KeyNav that's bound to document to catch all
147 // unhandled/bubbled key events for navigation
148 me.keyNav = Ext.create('Ext.util.KeyNav', Ext.getDoc(), {
152 backspace: me.focusLast,
153 enter: me.navigateIn,
155 tab: me.navigateSiblings
157 //space: me.navigateIn,
159 //left: me.navigateSiblings,
160 //right: me.navigateSiblings,
161 //down: me.navigateSiblings,
162 //up: me.navigateSiblings
166 me.subscribers = Ext.create('Ext.util.HashMap');
169 // Setup some ComponentQuery pseudos
170 Ext.apply(CQ.pseudos, {
171 focusable: function(cmps) {
172 var len = cmps.length,
177 isFocusable = function(x) {
178 return x && x.focusable !== false && CQ.is(x, '[rendered]:not([destroying]):not([isDestroyed]):not([disabled]){isVisible(true)}{el && c.el.dom && c.el.isVisible()}');
181 for (; i < len; i++) {
183 if (isFocusable(c)) {
191 nextFocus: function(cmps, idx, step) {
193 idx = parseInt(idx, 10);
195 var len = cmps.length,
199 for (; i != idx; i += step) {
202 } else if (i < 0) {
207 if (CQ.is(c, ':focusable')) {
209 } else if (c.placeholder && CQ.is(c.placeholder, ':focusable')) {
210 return [c.placeholder];
217 prevFocus: function(cmps, idx) {
218 return this.nextFocus(cmps, idx, -1);
221 root: function(cmps) {
222 var len = cmps.length,
227 for (; i < len; i++) {
239 <span id='Ext-FocusManager-method-addXTypeToWhitelist'> /**
240 </span> * Adds the specified xtype to the {@link #whitelist}.
241 * @param {String/String[]} xtype Adds the xtype(s) to the {@link #whitelist}.
243 addXTypeToWhitelist: function(xtype) {
246 if (Ext.isArray(xtype)) {
247 Ext.Array.forEach(xtype, me.addXTypeToWhitelist, me);
251 if (!Ext.Array.contains(me.whitelist, xtype)) {
252 me.whitelist.push(xtype);
256 clearComponent: function(cmp) {
257 clearTimeout(this.cmpFocusDelay);
258 if (!cmp.isDestroyed) {
263 <span id='Ext-FocusManager-method-disable'> /**
264 </span> * Disables the FocusManager by turning of all automatic focus management and keyboard navigation
266 disable: function() {
276 Ext.ComponentManager.all.un('add', me.onComponentCreated, me);
280 // Stop handling key navigation
283 // disable focus for all components
284 me.setFocusAll(false);
286 me.fireEvent('disable', me);
289 <span id='Ext-FocusManager-method-enable'> /**
290 </span> * Enables the FocusManager by turning on all automatic focus management and keyboard navigation
291 * @param {Boolean/Object} options Either `true`/`false` to turn on the focus frame, or an object of the following options:
292 - focusFrame : Boolean
293 `true` to show the focus frame around a component when it is focused. Defaults to `false`.
296 enable: function(options) {
299 if (options === true) {
300 options = { focusFrame: true };
302 me.options = options = options || {};
308 // Handle components that are newly added after we are enabled
309 Ext.ComponentManager.all.on('add', me.onComponentCreated, me);
313 // Start handling key navigation
316 // enable focus for all components
317 me.setFocusAll(true, options);
319 // Finally, let's focus our global focus el so we start fresh
321 delete me.focusedCmp;
324 me.fireEvent('enable', me);
327 focusLast: function(e) {
330 if (me.isWhitelisted(me.focusedCmp)) {
334 // Go back to last focused item
335 if (me.previousFocusedCmp) {
336 me.previousFocusedCmp.focus();
340 getRootComponents: function() {
342 CQ = Ext.ComponentQuery,
343 inline = CQ.query(':focusable:root:not([floating])'),
344 floating = CQ.query(':focusable:root[floating]');
346 // Floating items should go to the top of our root stack, and be ordered
347 // by their z-index (highest first)
348 floating.sort(function(a, b) {
349 return a.el.getZIndex() > b.el.getZIndex();
352 return floating.concat(inline);
355 initDOM: function(options) {
358 cls = me.focusFrameCls;
361 Ext.onReady(me.initDOM, me);
365 // Create global focus element
367 me.focusEl = Ext.getBody().createChild({
369 cls: me.focusElementCls,
374 // Create global focus frame
375 if (!me.focusFrame && options.focusFrame) {
376 me.focusFrame = Ext.getBody().createChild({
379 { cls: cls + '-top' },
380 { cls: cls + '-bottom' },
381 { cls: cls + '-left' },
382 { cls: cls + '-right' }
384 style: 'top: -100px; left: -100px;'
386 me.focusFrame.setVisibilityMode(Ext.Element.DISPLAY);
387 me.focusFrameWidth = 2;
388 me.focusFrame.hide().setLeftTop(0, 0);
392 isWhitelisted: function(cmp) {
393 return cmp && Ext.Array.some(this.whitelist, function(x) {
394 return cmp.isXType(x);
398 navigateIn: function(e) {
400 focusedCmp = me.focusedCmp,
405 // No focus yet, so focus the first root cmp on the page
406 rootCmps = me.getRootComponents();
407 if (rootCmps.length) {
411 // Drill into child ref items of the focused cmp, if applicable.
412 // This works for any Component with a getRefItems implementation.
413 firstChild = Ext.ComponentQuery.query('>:focusable', focusedCmp)[0];
417 // Let's try to fire a click event, as if it came from the mouse
418 if (Ext.isFunction(focusedCmp.onClick)) {
420 focusedCmp.onClick(e);
427 navigateOut: function(e) {
431 if (!me.focusedCmp || !(parent = me.focusedCmp.up(':focusable'))) {
437 // In some browsers (Chrome) FocusManager can handle this before other
438 // handlers. Ext Windows have their own Esc key handling, so we need to
439 // return true here to allow the event to bubble.
443 navigateSiblings: function(e, source, parent) {
447 EO = Ext.EventObject,
448 goBack = e.shiftKey || key == EO.LEFT || key == EO.UP,
449 checkWhitelist = key == EO.LEFT || key == EO.RIGHT || key == EO.UP || key == EO.DOWN,
450 nextSelector = goBack ? 'prev' : 'next',
451 idx, next, focusedCmp;
453 focusedCmp = (src.focusedCmp && src.focusedCmp.comp) || src.focusedCmp;
454 if (!focusedCmp && !parent) {
458 if (checkWhitelist && me.isWhitelisted(focusedCmp)) {
462 parent = parent || focusedCmp.up();
464 idx = focusedCmp ? Ext.Array.indexOf(parent.getRefItems(), focusedCmp) : -1;
465 next = Ext.ComponentQuery.query('>:' + nextSelector + 'Focus(' + idx + ')', parent)[0];
466 if (next && focusedCmp !== next) {
473 onComponentBlur: function(cmp, e) {
476 if (me.focusedCmp === cmp) {
477 me.previousFocusedCmp = cmp;
478 delete me.focusedCmp;
482 me.focusFrame.hide();
486 onComponentCreated: function(hash, id, cmp) {
487 this.setFocus(cmp, true, this.options);
490 onComponentDestroy: function(cmp) {
491 this.setFocus(cmp, false);
494 onComponentFocus: function(cmp, e) {
496 chain = me.focusChain;
498 if (!Ext.ComponentQuery.is(cmp, ':focusable')) {
499 me.clearComponent(cmp);
501 // Check our focus chain, so we don't run into a never ending recursion
502 // If we've attempted (unsuccessfully) to focus this component before,
503 // then we're caught in a loop of child->parent->...->child and we
504 // need to cut the loop off rather than feed into it.
509 // Try to focus the parent instead
510 var parent = cmp.up();
512 // Add component to our focus chain to detect infinite focus loop
513 // before we fire off an attempt to focus our parent.
514 // See the comments above.
515 chain[cmp.id] = true;
522 // Clear our focus chain when we have a focusable component
525 // Defer focusing for 90ms so components can do a layout/positioning
526 // and give us an ability to buffer focuses
527 clearTimeout(me.cmpFocusDelay);
528 if (arguments.length !== 2) {
529 me.cmpFocusDelay = Ext.defer(me.onComponentFocus, 90, me, [cmp, e]);
533 if (me.fireEvent('beforecomponentfocus', me, cmp, me.previousFocusedCmp) === false) {
534 me.clearComponent(cmp);
540 // If we have a focus frame, show it around the focused component
541 if (me.shouldShowFocusFrame(cmp)) {
542 var cls = '.' + me.focusFrameCls + '-',
544 fw = me.focusFrameWidth,
545 box = cmp.el.getPageBox(),
547 // Size the focus frame's t/b/l/r according to the box
548 // This leaves a hole in the middle of the frame so user
549 // interaction w/ the mouse can continue
554 ft = ff.child(cls + 'top'),
555 fb = ff.child(cls + 'bottom'),
556 fl = ff.child(cls + 'left'),
557 fr = ff.child(cls + 'right');
559 ft.setWidth(bw).setLeftTop(bl, bt);
560 fb.setWidth(bw).setLeftTop(bl, bt + bh - fw);
561 fl.setHeight(bh - fw - fw).setLeftTop(bl, bt + fw);
562 fr.setHeight(bh - fw - fw).setLeftTop(bl + bw - fw, bt + fw);
567 me.fireEvent('componentfocus', me, cmp, me.previousFocusedCmp);
570 onComponentHide: function(cmp) {
572 CQ = Ext.ComponentQuery,
578 focusedCmp = CQ.query('[id=' + me.focusedCmp.id + ']', cmp)[0];
579 cmpHadFocus = me.focusedCmp.id === cmp.id || focusedCmp;
582 me.clearComponent(focusedCmp);
586 me.clearComponent(cmp);
589 parent = CQ.query('^:focusable', cmp)[0];
596 removeDOM: function() {
599 // If we are still enabled globally, or there are still subscribers
600 // then we will halt here, since our DOM stuff is still being used
601 if (me.enabled || me.subscribers.length) {
610 delete me.focusFrame;
611 delete me.focusFrameWidth;
614 <span id='Ext-FocusManager-method-removeXTypeFromWhitelist'> /**
615 </span> * Removes the specified xtype from the {@link #whitelist}.
616 * @param {String/String[]} xtype Removes the xtype(s) from the {@link #whitelist}.
618 removeXTypeFromWhitelist: function(xtype) {
621 if (Ext.isArray(xtype)) {
622 Ext.Array.forEach(xtype, me.removeXTypeFromWhitelist, me);
626 Ext.Array.remove(me.whitelist, xtype);
629 setFocus: function(cmp, focusable, options) {
633 needsTabIndex = function(n) {
634 return !Ext.Array.contains(me.tabIndexWhitelist, n.tagName.toLowerCase())
635 && n.tabIndex <= 0;
638 options = options || {};
640 // Come back and do this after the component is rendered
642 cmp.on('afterrender', Ext.pass(me.setFocus, arguments, me), me, { single: true });
646 el = cmp.getFocusEl();
649 // Decorate the component's focus el for focus-ability
650 if ((focusable && !me.focusData[cmp.id]) || (!focusable && me.focusData[cmp.id])) {
653 focusFrame: options.focusFrame
656 // Only set -1 tabIndex if we need it
657 // inputs, buttons, and anchor tags do not need it,
658 // and neither does any DOM that has it set already
659 // programmatically or in markup.
660 if (needsTabIndex(dom)) {
661 data.tabIndex = dom.tabIndex;
666 focus: data.focusFn = Ext.bind(me.onComponentFocus, me, [cmp], 0),
667 blur: data.blurFn = Ext.bind(me.onComponentBlur, me, [cmp], 0),
671 hide: me.onComponentHide,
672 close: me.onComponentHide,
673 beforedestroy: me.onComponentDestroy,
677 me.focusData[cmp.id] = data;
679 data = me.focusData[cmp.id];
680 if ('tabIndex' in data) {
681 dom.tabIndex = data.tabIndex;
683 el.un('focus', data.focusFn, me);
684 el.un('blur', data.blurFn, me);
685 cmp.un('hide', me.onComponentHide, me);
686 cmp.un('close', me.onComponentHide, me);
687 cmp.un('beforedestroy', me.onComponentDestroy, me);
689 delete me.focusData[cmp.id];
694 setFocusAll: function(focusable, options) {
696 cmps = Ext.ComponentManager.all.getArray(),
701 for (; i < len; i++) {
702 me.setFocus(cmps[i], focusable, options);
706 setupSubscriberKeys: function(container, keys) {
708 el = container.getFocusEl(),
711 backspace: me.focusLast,
712 enter: me.navigateIn,
717 navSiblings = function(e) {
718 if (me.focusedCmp === container) {
719 // Root the sibling navigation to this container, so that we
720 // can automatically dive into the container, rather than forcing
721 // the user to hit the enter key to dive in.
722 return me.navigateSiblings(e, me, container);
724 return me.navigateSiblings(e);
728 Ext.iterate(keys, function(key, cb) {
729 handlers[key] = function(e) {
730 var ret = navSiblings(e);
732 if (Ext.isFunction(cb) && cb.call(scope || container, e, ret) === true) {
740 return Ext.create('Ext.util.KeyNav', el, handlers);
743 shouldShowFocusFrame: function(cmp) {
745 opts = me.options || {};
747 if (!me.focusFrame || !cmp) {
752 if (opts.focusFrame) {
756 if (me.focusData[cmp.id].focusFrame) {
763 <span id='Ext-FocusManager-method-subscribe'> /**
764 </span> * Subscribes an {@link Ext.container.Container} to provide basic keyboard focus navigation between its child {@link Ext.Component}'s.
765 * @param {Ext.container.Container} container A reference to the {@link Ext.container.Container} on which to enable keyboard functionality and focus management.
766 * @param {Boolean/Object} options An object of the following options
767 * @param {Array/Object} options.keys
768 * An array containing the string names of navigation keys to be supported. The allowed values are:
775 * 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.:
778 * left: this.onLeftKey,
779 * right: this.onRightKey,
783 * @param {Boolean} options.focusFrame
784 * `true` to show the focus frame around a component when it is focused. Defaults to `false`.
786 subscribe: function(container, options) {
790 subs = me.subscribers,
792 // Recursively add focus ability as long as a descendent container isn't
793 // itself subscribed to the FocusManager, or else we'd have unwanted side
794 // effects for subscribing a descendent container twice.
795 safeSetFocus = function(cmp) {
796 if (cmp.isContainer && !subs.containsKey(cmp.id)) {
797 EA.forEach(cmp.query('>'), safeSetFocus);
798 me.setFocus(cmp, true, options);
799 cmp.on('add', data.onAdd, me);
800 } else if (!cmp.isContainer) {
801 me.setFocus(cmp, true, options);
805 // We only accept containers
806 if (!container || !container.isContainer) {
810 if (!container.rendered) {
811 container.on('afterrender', Ext.pass(me.subscribe, arguments, me), me, { single: true });
815 // Init the DOM, incase this is the first time it will be used
818 // Create key navigation for subscriber based on keys option
819 data.keyNav = me.setupSubscriberKeys(container, options.keys);
821 // We need to keep track of components being added to our subscriber
822 // and any containers nested deeply within it (omg), so let's do that.
823 // Components that are removed are globally handled.
824 // Also keep track of destruction of our container for auto-unsubscribe.
825 data.onAdd = function(ct, cmp, idx) {
828 container.on('beforedestroy', me.unsubscribe, me);
830 // Now we setup focusing abilities for the container and all its components
831 safeSetFocus(container);
833 // Add to our subscribers list
834 subs.add(container.id, data);
837 <span id='Ext-FocusManager-method-unsubscribe'> /**
838 </span> * Unsubscribes an {@link Ext.container.Container} from keyboard focus management.
839 * @param {Ext.container.Container} container A reference to the {@link Ext.container.Container} to unsubscribe from the FocusManager.
841 unsubscribe: function(container) {
844 subs = me.subscribers,
847 // Recursively remove focus ability as long as a descendent container isn't
848 // itself subscribed to the FocusManager, or else we'd have unwanted side
849 // effects for unsubscribing an ancestor container.
850 safeSetFocus = function(cmp) {
851 if (cmp.isContainer && !subs.containsKey(cmp.id)) {
852 EA.forEach(cmp.query('>'), safeSetFocus);
853 me.setFocus(cmp, false);
854 cmp.un('add', data.onAdd, me);
855 } else if (!cmp.isContainer) {
856 me.setFocus(cmp, false);
860 if (!container || !subs.containsKey(container.id)) {
864 data = subs.get(container.id);
865 data.keyNav.destroy();
866 container.un('beforedestroy', me.unsubscribe, me);
867 subs.removeAtKey(container.id);
868 safeSetFocus(container);