focus.js.uncompressed.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. define("dijit/focus", [
  2. "dojo/aspect",
  3. "dojo/_base/declare", // declare
  4. "dojo/dom", // domAttr.get dom.isDescendant
  5. "dojo/dom-attr", // domAttr.get dom.isDescendant
  6. "dojo/dom-construct", // connect to domConstruct.empty, domConstruct.destroy
  7. "dojo/Evented",
  8. "dojo/_base/lang", // lang.hitch
  9. "dojo/on",
  10. "dojo/ready",
  11. "dojo/sniff", // has("ie")
  12. "dojo/Stateful",
  13. "dojo/_base/unload", // unload.addOnWindowUnload
  14. "dojo/_base/window", // win.body
  15. "dojo/window", // winUtils.get
  16. "./a11y", // a11y.isTabNavigable
  17. "./registry", // registry.byId
  18. "./main" // to set dijit.focus
  19. ], function(aspect, declare, dom, domAttr, domConstruct, Evented, lang, on, ready, has, Stateful, unload, win, winUtils,
  20. a11y, registry, dijit){
  21. // module:
  22. // dijit/focus
  23. var FocusManager = declare([Stateful, Evented], {
  24. // summary:
  25. // Tracks the currently focused node, and which widgets are currently "active".
  26. // Access via require(["dijit/focus"], function(focus){ ... }).
  27. //
  28. // A widget is considered active if it or a descendant widget has focus,
  29. // or if a non-focusable node of this widget or a descendant was recently clicked.
  30. //
  31. // Call focus.watch("curNode", callback) to track the current focused DOMNode,
  32. // or focus.watch("activeStack", callback) to track the currently focused stack of widgets.
  33. //
  34. // Call focus.on("widget-blur", func) or focus.on("widget-focus", ...) to monitor when
  35. // when widgets become active/inactive
  36. //
  37. // Finally, focus(node) will focus a node, suppressing errors if the node doesn't exist.
  38. // curNode: DomNode
  39. // Currently focused item on screen
  40. curNode: null,
  41. // activeStack: dijit/_WidgetBase[]
  42. // List of currently active widgets (focused widget and it's ancestors)
  43. activeStack: [],
  44. constructor: function(){
  45. // Don't leave curNode/prevNode pointing to bogus elements
  46. var check = lang.hitch(this, function(node){
  47. if(dom.isDescendant(this.curNode, node)){
  48. this.set("curNode", null);
  49. }
  50. if(dom.isDescendant(this.prevNode, node)){
  51. this.set("prevNode", null);
  52. }
  53. });
  54. aspect.before(domConstruct, "empty", check);
  55. aspect.before(domConstruct, "destroy", check);
  56. },
  57. registerIframe: function(/*DomNode*/ iframe){
  58. // summary:
  59. // Registers listeners on the specified iframe so that any click
  60. // or focus event on that iframe (or anything in it) is reported
  61. // as a focus/click event on the `<iframe>` itself.
  62. // description:
  63. // Currently only used by editor.
  64. // returns:
  65. // Handle with remove() method to deregister.
  66. return this.registerWin(iframe.contentWindow, iframe);
  67. },
  68. registerWin: function(/*Window?*/targetWindow, /*DomNode?*/ effectiveNode){
  69. // summary:
  70. // Registers listeners on the specified window (either the main
  71. // window or an iframe's window) to detect when the user has clicked somewhere
  72. // or focused somewhere.
  73. // description:
  74. // Users should call registerIframe() instead of this method.
  75. // targetWindow:
  76. // If specified this is the window associated with the iframe,
  77. // i.e. iframe.contentWindow.
  78. // effectiveNode:
  79. // If specified, report any focus events inside targetWindow as
  80. // an event on effectiveNode, rather than on evt.target.
  81. // returns:
  82. // Handle with remove() method to deregister.
  83. // TODO: make this function private in 2.0; Editor/users should call registerIframe(),
  84. var _this = this;
  85. var mousedownListener = function(evt){
  86. _this._justMouseDowned = true;
  87. setTimeout(function(){ _this._justMouseDowned = false; }, 0);
  88. // workaround weird IE bug where the click is on an orphaned node
  89. // (first time clicking a Select/DropDownButton inside a TooltipDialog)
  90. if(has("ie") && evt && evt.srcElement && evt.srcElement.parentNode == null){
  91. return;
  92. }
  93. _this._onTouchNode(effectiveNode || evt.target || evt.srcElement, "mouse");
  94. };
  95. // Listen for blur and focus events on targetWindow's document.
  96. // Using attachEvent()/addEventListener() rather than on() to try to catch mouseDown events even
  97. // if other code calls evt.stopPropagation(). But rethink for 2.0 since that doesn't work for attachEvent(),
  98. // which watches events at the bubbling phase rather than capturing phase, like addEventListener(..., false).
  99. // Connect to <html> (rather than document) on IE to avoid memory leaks, but document on other browsers because
  100. // (at least for FF) the focus event doesn't fire on <html> or <body>.
  101. var doc = has("ie") ? targetWindow.document.documentElement : targetWindow.document;
  102. if(doc){
  103. if(has("ie")){
  104. targetWindow.document.body.attachEvent('onmousedown', mousedownListener);
  105. var focusinListener = function(evt){
  106. // IE reports that nodes like <body> have gotten focus, even though they have tabIndex=-1,
  107. // ignore those events
  108. var tag = evt.srcElement.tagName.toLowerCase();
  109. if(tag == "#document" || tag == "body"){ return; }
  110. // Previous code called _onTouchNode() for any activate event on a non-focusable node. Can
  111. // probably just ignore such an event as it will be handled by onmousedown handler above, but
  112. // leaving the code for now.
  113. if(a11y.isTabNavigable(evt.srcElement)){
  114. _this._onFocusNode(effectiveNode || evt.srcElement);
  115. }else{
  116. _this._onTouchNode(effectiveNode || evt.srcElement);
  117. }
  118. };
  119. doc.attachEvent('onfocusin', focusinListener);
  120. var focusoutListener = function(evt){
  121. _this._onBlurNode(effectiveNode || evt.srcElement);
  122. };
  123. doc.attachEvent('onfocusout', focusoutListener);
  124. return {
  125. remove: function(){
  126. targetWindow.document.detachEvent('onmousedown', mousedownListener);
  127. doc.detachEvent('onfocusin', focusinListener);
  128. doc.detachEvent('onfocusout', focusoutListener);
  129. doc = null; // prevent memory leak (apparent circular reference via closure)
  130. }
  131. };
  132. }else{
  133. doc.body.addEventListener('mousedown', mousedownListener, true);
  134. doc.body.addEventListener('touchstart', mousedownListener, true);
  135. var focusListener = function(evt){
  136. _this._onFocusNode(effectiveNode || evt.target);
  137. };
  138. doc.addEventListener('focus', focusListener, true);
  139. var blurListener = function(evt){
  140. _this._onBlurNode(effectiveNode || evt.target);
  141. };
  142. doc.addEventListener('blur', blurListener, true);
  143. return {
  144. remove: function(){
  145. doc.body.removeEventListener('mousedown', mousedownListener, true);
  146. doc.body.removeEventListener('touchstart', mousedownListener, true);
  147. doc.removeEventListener('focus', focusListener, true);
  148. doc.removeEventListener('blur', blurListener, true);
  149. doc = null; // prevent memory leak (apparent circular reference via closure)
  150. }
  151. };
  152. }
  153. }
  154. },
  155. _onBlurNode: function(/*DomNode*/ node){
  156. // summary:
  157. // Called when focus leaves a node.
  158. // Usually ignored, _unless_ it *isn't* followed by touching another node,
  159. // which indicates that we tabbed off the last field on the page,
  160. // in which case every widget is marked inactive
  161. // If the blur event isn't followed by a focus event, it means the user clicked on something unfocusable,
  162. // so clear focus.
  163. if(this._clearFocusTimer){
  164. clearTimeout(this._clearFocusTimer);
  165. }
  166. this._clearFocusTimer = setTimeout(lang.hitch(this, function(){
  167. this.set("prevNode", this.curNode);
  168. this.set("curNode", null);
  169. }), 0);
  170. if(this._justMouseDowned){
  171. // the mouse down caused a new widget to be marked as active; this blur event
  172. // is coming late, so ignore it.
  173. return;
  174. }
  175. // If the blur event isn't followed by a focus or touch event then mark all widgets as inactive.
  176. if(this._clearActiveWidgetsTimer){
  177. clearTimeout(this._clearActiveWidgetsTimer);
  178. }
  179. this._clearActiveWidgetsTimer = setTimeout(lang.hitch(this, function(){
  180. delete this._clearActiveWidgetsTimer;
  181. this._setStack([]);
  182. }), 0);
  183. },
  184. _onTouchNode: function(/*DomNode*/ node, /*String*/ by){
  185. // summary:
  186. // Callback when node is focused or mouse-downed
  187. // node:
  188. // The node that was touched.
  189. // by:
  190. // "mouse" if the focus/touch was caused by a mouse down event
  191. // ignore the recent blurNode event
  192. if(this._clearActiveWidgetsTimer){
  193. clearTimeout(this._clearActiveWidgetsTimer);
  194. delete this._clearActiveWidgetsTimer;
  195. }
  196. // compute stack of active widgets (ex: ComboButton --> Menu --> MenuItem)
  197. var newStack=[];
  198. try{
  199. while(node){
  200. var popupParent = domAttr.get(node, "dijitPopupParent");
  201. if(popupParent){
  202. node=registry.byId(popupParent).domNode;
  203. }else if(node.tagName && node.tagName.toLowerCase() == "body"){
  204. // is this the root of the document or just the root of an iframe?
  205. if(node === win.body()){
  206. // node is the root of the main document
  207. break;
  208. }
  209. // otherwise, find the iframe this node refers to (can't access it via parentNode,
  210. // need to do this trick instead). window.frameElement is supported in IE/FF/Webkit
  211. node=winUtils.get(node.ownerDocument).frameElement;
  212. }else{
  213. // if this node is the root node of a widget, then add widget id to stack,
  214. // except ignore clicks on disabled widgets (actually focusing a disabled widget still works,
  215. // to support MenuItem)
  216. var id = node.getAttribute && node.getAttribute("widgetId"),
  217. widget = id && registry.byId(id);
  218. if(widget && !(by == "mouse" && widget.get("disabled"))){
  219. newStack.unshift(id);
  220. }
  221. node=node.parentNode;
  222. }
  223. }
  224. }catch(e){ /* squelch */ }
  225. this._setStack(newStack, by);
  226. },
  227. _onFocusNode: function(/*DomNode*/ node){
  228. // summary:
  229. // Callback when node is focused
  230. if(!node){
  231. return;
  232. }
  233. if(node.nodeType == 9){
  234. // Ignore focus events on the document itself. This is here so that
  235. // (for example) clicking the up/down arrows of a spinner
  236. // (which don't get focus) won't cause that widget to blur. (FF issue)
  237. return;
  238. }
  239. // There was probably a blur event right before this event, but since we have a new focus, don't
  240. // do anything with the blur
  241. if(this._clearFocusTimer){
  242. clearTimeout(this._clearFocusTimer);
  243. delete this._clearFocusTimer;
  244. }
  245. this._onTouchNode(node);
  246. if(node == this.curNode){ return; }
  247. this.set("prevNode", this.curNode);
  248. this.set("curNode", node);
  249. },
  250. _setStack: function(/*String[]*/ newStack, /*String*/ by){
  251. // summary:
  252. // The stack of active widgets has changed. Send out appropriate events and records new stack.
  253. // newStack:
  254. // array of widget id's, starting from the top (outermost) widget
  255. // by:
  256. // "mouse" if the focus/touch was caused by a mouse down event
  257. var oldStack = this.activeStack;
  258. this.set("activeStack", newStack);
  259. // compare old stack to new stack to see how many elements they have in common
  260. for(var nCommon=0; nCommon<Math.min(oldStack.length, newStack.length); nCommon++){
  261. if(oldStack[nCommon] != newStack[nCommon]){
  262. break;
  263. }
  264. }
  265. var widget;
  266. // for all elements that have gone out of focus, set focused=false
  267. for(var i=oldStack.length-1; i>=nCommon; i--){
  268. widget = registry.byId(oldStack[i]);
  269. if(widget){
  270. widget._hasBeenBlurred = true; // TODO: used by form widgets, should be moved there
  271. widget.set("focused", false);
  272. if(widget._focusManager == this){
  273. widget._onBlur(by);
  274. }
  275. this.emit("widget-blur", widget, by);
  276. }
  277. }
  278. // for all element that have come into focus, set focused=true
  279. for(i=nCommon; i<newStack.length; i++){
  280. widget = registry.byId(newStack[i]);
  281. if(widget){
  282. widget.set("focused", true);
  283. if(widget._focusManager == this){
  284. widget._onFocus(by);
  285. }
  286. this.emit("widget-focus", widget, by);
  287. }
  288. }
  289. },
  290. focus: function(node){
  291. // summary:
  292. // Focus the specified node, suppressing errors if they occur
  293. if(node){
  294. try{ node.focus(); }catch(e){/*quiet*/}
  295. }
  296. }
  297. });
  298. var singleton = new FocusManager();
  299. // register top window and all the iframes it contains
  300. ready(function(){
  301. var handle = singleton.registerWin(winUtils.get(win.doc));
  302. if(has("ie")){
  303. unload.addOnWindowUnload(function(){
  304. if(handle){ // because this gets called twice when doh.robot is running
  305. handle.remove();
  306. handle = null;
  307. }
  308. });
  309. }
  310. });
  311. // Setup dijit.focus as a pointer to the singleton but also (for backwards compatibility)
  312. // as a function to set focus. Remove for 2.0.
  313. dijit.focus = function(node){
  314. singleton.focus(node); // indirection here allows dijit/_base/focus.js to override behavior
  315. };
  316. for(var attr in singleton){
  317. if(!/^_/.test(attr)){
  318. dijit.focus[attr] = typeof singleton[attr] == "function" ? lang.hitch(singleton, attr) : singleton[attr];
  319. }
  320. }
  321. singleton.watch(function(attr, oldVal, newVal){
  322. dijit.focus[attr] = newVal;
  323. });
  324. return singleton;
  325. });