2 Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved.
3 Available via Academic Free License >= 2.1 OR the modified BSD license.
4 see: http://dojotoolkit.org/license for details
8 This is an optimized version of Dojo, built for deployment and not for
9 development. To get sources and documentation, please visit:
11 http://dojotoolkit.org
14 dojo
.provide("tt-rss-layer");
15 if(!dojo
._hasResource
["dojo.date.stamp"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
16 dojo
._hasResource
["dojo.date.stamp"] = true;
17 dojo
.provide("dojo.date.stamp");
19 // Methods to convert dates to or from a wire (string) format using well-known conventions
21 dojo
.date
.stamp
.fromISOString = function(/*String*/formattedString
, /*Number?*/defaultTime
){
23 // Returns a Date object given a string formatted according to a subset of the ISO-8601 standard.
26 // Accepts a string formatted according to a profile of ISO8601 as defined by
27 // [RFC3339](http://www.ietf.org/rfc/rfc3339.txt), except that partial input is allowed.
28 // Can also process dates as specified [by the W3C](http://www.w3.org/TR/NOTE-datetime)
29 // The following combinations are valid:
35 // * times only, with an optional time zone appended
39 // * and "datetimes" which could be any combination of the above
41 // timezones may be specified as Z (for UTC) or +/- followed by a time expression HH:mm
42 // Assumes the local time zone if not specified. Does not validate. Improperly formatted
43 // input may return null. Arguments which are out of bounds will be handled
44 // by the Date constructor (e.g. January 32nd typically gets resolved to February 1st)
45 // Only years between 100 and 9999 are supported.
48 // A string such as 2005-06-30T08:05:00-07:00 or 2005-06-30 or T08:05:00
51 // Used for defaults for fields omitted in the formattedString.
52 // Uses 1970-01-01T00:00:00.0Z by default.
54 if(!dojo
.date
.stamp
._isoRegExp
){
55 dojo
.date
.stamp
._isoRegExp
=
56 //TODO: could be more restrictive and check for 00-59, etc.
57 /^(?:(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(.\d+)?)?((?:[+-](\d{2}):(\d{2}))|Z)?)?$/;
60 var match
= dojo
.date
.stamp
._isoRegExp
.exec(formattedString
),
65 if(match
[1]){match
[1]--;} // Javascript Date months are 0-based
66 if(match
[6]){match
[6] *= 1000;} // Javascript Date expects fractional seconds as milliseconds
69 // mix in defaultTime. Relatively expensive, so use || operators for the fast path of defaultTime === 0
70 defaultTime
= new Date(defaultTime
);
71 dojo
.forEach(dojo
.map(["FullYear", "Month", "Date", "Hours", "Minutes", "Seconds", "Milliseconds"], function(prop
){
72 return defaultTime
["get" + prop
]();
73 }), function(value
, index
){
74 match
[index
] = match
[index
] || value
;
77 result
= new Date(match
[0]||1970, match
[1]||0, match
[2]||1, match
[3]||0, match
[4]||0, match
[5]||0, match
[6]||0); //TODO: UTC defaults
79 result
.setFullYear(match
[0] || 1970);
83 zoneSign
= match
[7] && match
[7].charAt(0);
85 offset
= ((match
[8] || 0) * 60) + (Number(match
[9]) || 0);
86 if(zoneSign
!= '-'){ offset
*= -1; }
89 offset
-= result
.getTimezoneOffset();
92 result
.setTime(result
.getTime() + offset
* 60000);
96 return result
; // Date or null
100 dojo.date.stamp.__Options = function(){
102 // "date" or "time" for partial formatting of the Date object.
103 // Both date and time will be formatted by default.
105 // if true, UTC/GMT is used for a timezone
106 // milliseconds: Boolean
107 // if true, output milliseconds
108 this.selector = selector;
110 this.milliseconds = milliseconds;
114 dojo
.date
.stamp
.toISOString = function(/*Date*/dateObject
, /*dojo.date.stamp.__Options?*/options
){
116 // Format a Date object as a string according a subset of the ISO-8601 standard
119 // When options.selector is omitted, output follows [RFC3339](http://www.ietf.org/rfc/rfc3339.txt)
120 // The local time zone is included as an offset from GMT, except when selector=='time' (time without a date)
121 // Does not check bounds. Only years between 100 and 9999 are supported.
126 var _ = function(n
){ return (n
< 10) ? "0" + n
: n
; };
127 options
= options
|| {};
128 var formattedDate
= [],
129 getter
= options
.zulu
? "getUTC" : "get",
131 if(options
.selector
!= "time"){
132 var year
= dateObject
[getter
+"FullYear"]();
133 date
= ["0000".substr((year
+"").length
)+year
, _(dateObject
[getter
+"Month"]()+1), _(dateObject
[getter
+"Date"]())].join('-');
135 formattedDate
.push(date
);
136 if(options
.selector
!= "date"){
137 var time
= [_(dateObject
[getter
+"Hours"]()), _(dateObject
[getter
+"Minutes"]()), _(dateObject
[getter
+"Seconds"]())].join(':');
138 var millis
= dateObject
[getter
+"Milliseconds"]();
139 if(options
.milliseconds
){
140 time
+= "."+ (millis
< 100 ? "0" : "") + _(millis
);
144 }else if(options
.selector
!= "time"){
145 var timezoneOffset
= dateObject
.getTimezoneOffset();
146 var absOffset
= Math
.abs(timezoneOffset
);
147 time
+= (timezoneOffset
> 0 ? "-" : "+") +
148 _(Math
.floor(absOffset
/60)) + ":" + _(absOffset
%60);
150 formattedDate
.push(time
);
152 return formattedDate
.join('T'); // String
157 if(!dojo
._hasResource
["dojo.parser"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
158 dojo
._hasResource
["dojo.parser"] = true;
159 dojo
.provide("dojo.parser");
162 new Date("X"); // workaround for #11279, new Date("") == NaN
164 dojo
.parser
= new function(){
165 // summary: The Dom/Widget parsing package
168 this._attrName
= d
._scopeName
+ "Type";
169 this._query
= "[" + this._attrName
+ "]";
171 function val2type(/*Object*/ value
){
173 // Returns name of type of given value.
175 if(d
.isString(value
)){ return "string"; }
176 if(typeof value
== "number"){ return "number"; }
177 if(typeof value
== "boolean"){ return "boolean"; }
178 if(d
.isFunction(value
)){ return "function"; }
179 if(d
.isArray(value
)){ return "array"; } // typeof [] == "object"
180 if(value
instanceof Date
) { return "date"; } // assume timestamp
181 if(value
instanceof d
._Url
){ return "url"; }
185 function str2obj(/*String*/ value
, /*String*/ type
){
187 // Convert given string value to given type
192 return value
.length
? Number(value
) : NaN
;
194 // for checked/disabled value might be "" or "checked". interpret as true.
195 return typeof value
== "boolean" ? value
: !(value
.toLowerCase()=="false");
197 if(d
.isFunction(value
)){
198 // IE gives us a function, even when we say something like onClick="foo"
199 // (in which case it gives us an invalid function "function(){ foo }").
200 // Therefore, convert to string
201 value
=value
.toString();
202 value
=d
.trim(value
.substring(value
.indexOf('{')+1, value
.length
-1));
205 if(value
=== "" || value
.search(/[^\w\.]+/i) != -1){
206 // The user has specified some text for a function like "return x+5"
207 return new Function(value
);
209 // The user has specified the name of a function like "myOnClick"
210 // or a single word function "return"
211 return d
.getObject(value
, false) || new Function(value
);
213 }catch(e
){ return new Function(); }
215 return value
? value
.split(/\s*,\s*/) : [];
218 case "": return new Date(""); // the NaN of dates
219 case "now": return new Date(); // current date
220 default: return d
.date
.stamp
.fromISOString(value
);
223 return d
.baseUrl
+ value
;
225 return d
.fromJson(value
);
229 var instanceClasses
= {
230 // map from fully qualified name (like "dijit.Button") to structure like
231 // { cls: dijit.Button, params: {label: "string", disabled: "boolean"} }
234 // Widgets like BorderContainer add properties to _Widget via dojo.extend().
235 // If BorderContainer is loaded after _Widget's parameter list has been cached,
236 // we need to refresh that parameter list (for _Widget and all widgets that extend _Widget).
237 dojo
.connect(dojo
, "extend", function(){
238 instanceClasses
= {};
241 function getClassInfo(/*String*/ className
){
243 // fully qualified name (like "dijit.form.Button")
247 // cls: dijit.Button,
248 // params: { label: "string", disabled: "boolean"}
251 if(!instanceClasses
[className
]){
252 // get pointer to widget class
253 var cls
= d
.getObject(className
);
254 if(!cls
){ return null; } // class not defined [yet]
256 var proto
= cls
.prototype;
258 // get table of parameter names & types
259 var params
= {}, dummyClass
= {};
260 for(var name
in proto
){
261 if(name
.charAt(0)=="_"){ continue; } // skip internal properties
262 if(name
in dummyClass
){ continue; } // skip "constructor" and "toString"
263 var defVal
= proto
[name
];
264 params
[name
]=val2type(defVal
);
267 instanceClasses
[className
] = { cls
: cls
, params
: params
};
269 return instanceClasses
[className
];
272 this._functionFromScript = function(script
){
275 var argsStr
= script
.getAttribute("args");
277 d
.forEach(argsStr
.split(/\s*,\s*/), function(part
, idx
){
278 preamble
+= "var "+part
+" = arguments["+idx
+"]; ";
281 var withStr
= script
.getAttribute("with");
282 if(withStr
&& withStr
.length
){
283 d
.forEach(withStr
.split(/\s*,\s*/), function(part
){
284 preamble
+= "with("+part
+"){";
288 return new Function(preamble
+script
.innerHTML
+suffix
);
291 this.instantiate = function(/* Array */nodes
, /* Object? */mixin
, /* Object? */args
){
293 // Takes array of nodes, and turns them into class instances and
294 // potentially calls a startup method to allow them to connect with
297 // Array of nodes or objects like
299 // | type: "dijit.form.Button",
301 // | scripts: [ ... ], // array of <script type="dojo/..."> children of node
302 // | inherited: { ... } // settings inherited from ancestors like dir, theme, etc.
305 // An object that will be mixed in with each node in the array.
306 // Values in the mixin will override values in the node, if they
309 // An object used to hold kwArgs for instantiation.
310 // Supports 'noStart' and inherited.
311 var thelist
= [], dp
= dojo
.parser
;
315 d
.forEach(nodes
, function(obj
){
318 // Get pointers to DOMNode, dojoType string, and clsInfo (metadata about the dojoType), etc.s
319 var node
, type
, clsInfo
, clazz
, scripts
;
321 // new format of nodes[] array, object w/lots of properties pre-computed for me
324 clsInfo
= obj
.clsInfo
|| (type
&& getClassInfo(type
));
325 clazz
= clsInfo
&& clsInfo
.cls
;
326 scripts
= obj
.scripts
;
328 // old (backwards compatible) format of nodes[] array, simple array of DOMNodes
330 type
= dp
._attrName
in mixin
? mixin
[dp
._attrName
] : node
.getAttribute(dp
._attrName
);
331 clsInfo
= type
&& getClassInfo(type
);
332 clazz
= clsInfo
&& clsInfo
.cls
;
333 scripts
= (clazz
&& (clazz
._noScript
|| clazz
.prototype._noScript
) ? [] :
334 d
.query("> script[type^='dojo/']", node
));
337 throw new Error("Could not load class '" + type
);
340 // Setup hash to hold parameter settings for this widget. Start with the parameter
341 // settings inherited from ancestors ("dir" and "lang").
342 // Inherited setting may later be overridden by explicit settings on node itself.
344 attributes
= node
.attributes
;
346 // settings for the document itself (or whatever subtree is being parsed)
347 dojo
.mixin(params
, args
.defaults
);
350 // settings from dir=rtl or lang=... on a node above this node
351 dojo
.mixin(params
, obj
.inherited
);
354 // read parameters (ie, attributes) specified on DOMNode
355 // clsInfo.params lists expected params like {"checked": "boolean", "n": "number"}
356 for(var name
in clsInfo
.params
){
357 var item
= name
in mixin
?{value
:mixin
[name
],specified
:true}:attributes
.getNamedItem(name
);
358 if(!item
|| (!item
.specified
&& (!dojo
.isIE
|| name
.toLowerCase()!="value"))){ continue; }
359 var value
= item
.value
;
360 // Deal with IE quirks for 'class' and 'style'
363 value
= "className" in mixin
?mixin
.className
:node
.className
;
366 value
= "style" in mixin
?mixin
.style
:(node
.style
&& node
.style
.cssText
); // FIXME: Opera?
368 var _type
= clsInfo
.params
[name
];
369 if(typeof value
== "string"){
370 params
[name
] = str2obj(value
, _type
);
372 params
[name
] = value
;
376 // Process <script type="dojo/*"> script tags
377 // <script type="dojo/method" event="foo"> tags are added to params, and passed to
378 // the widget on instantiation.
379 // <script type="dojo/method"> tags (with no event) are executed after instantiation
380 // <script type="dojo/connect" event="foo"> tags are dojo.connected after instantiation
381 // note: dojo/* script tags cannot exist in self closing widgets, like <input />
382 var connects
= [], // functions to connect after instantiation
383 calls
= []; // functions to call after instantiation
385 d
.forEach(scripts
, function(script
){
386 node
.removeChild(script
);
387 var event
= script
.getAttribute("event"),
388 type
= script
.getAttribute("type"),
389 nf
= d
.parser
._functionFromScript(script
);
391 if(type
== "dojo/connect"){
392 connects
.push({event
: event
, func
: nf
});
401 var markupFactory
= clazz
.markupFactory
|| clazz
.prototype && clazz
.prototype.markupFactory
;
402 // create the instance
403 var instance
= markupFactory
? markupFactory(params
, node
, clazz
) : new clazz(params
, node
);
404 thelist
.push(instance
);
406 // map it to the JS namespace if that makes sense
407 var jsname
= node
.getAttribute("jsId");
409 d
.setObject(jsname
, instance
);
412 // process connections and startup functions
413 d
.forEach(connects
, function(connect
){
414 d
.connect(instance
, connect
.event
, null, connect
.func
);
416 d
.forEach(calls
, function(func
){
421 // Call startup on each top level instance if it makes sense (as for
422 // widgets). Parent widgets will recursively call startup on their
423 // (non-top level) children
425 // TODO: for 2.0, when old instantiate() API is desupported, store parent-child
426 // relationships in the nodes[] array so that no getParent() call is needed.
427 // Note that will require a parse() call from ContentPane setting a param that the
428 // ContentPane is the parent widget (so that the parse doesn't call startup() on the
429 // ContentPane's children)
430 d
.forEach(thelist
, function(instance
){
431 if( !args
.noStart
&& instance
&&
433 !instance
._started
&&
434 (!instance
.getParent
|| !instance
.getParent())
443 this.parse = function(/*DomNode?*/ rootNode
, /* Object? */ args
){
445 // Scan the DOM for class instances, and instantiate them.
448 // Search specified node (or root node) recursively for class instances,
449 // and instantiate them Searches for
450 // dojoType="qualified.class.name"
452 // rootNode: DomNode?
453 // A default starting root node from which to start the parsing. Can be
454 // omitted, defaulting to the entire document. If omitted, the `args`
455 // object can be passed in this place. If the `args` object has a
456 // `rootNode` member, that is used.
459 // a kwArgs object passed along to instantiate()
461 // * noStart: Boolean?
462 // when set will prevent the parser from calling .startup()
463 // when locating the nodes.
464 // * rootNode: DomNode?
465 // identical to the function's `rootNode` argument, though
466 // allowed to be passed in via this `args object.
467 // * inherited: Object
468 // Hash possibly containing dir and lang settings to be applied to
469 // parsed widgets, unless there's another setting on a sub-node that overrides
473 // Parse all widgets on a page:
474 // | dojo.parser.parse();
477 // Parse all classes within the node with id="foo"
478 // | dojo.parser.parse(dojo.byId(foo));
481 // Parse all classes in a page, but do not call .startup() on any
483 // | dojo.parser.parse({ noStart: true })
486 // Parse all classes in a node, but do not call .startup()
487 // | dojo.parser.parse(someNode, { noStart:true });
489 // | dojo.parser.parse({ noStart:true, rootNode: someNode });
491 // determine the root node based on the passed arguments.
493 if(!args
&& rootNode
&& rootNode
.rootNode
){
495 root
= args
.rootNode
;
500 var attrName
= this._attrName
;
501 function scan(parent
, list
){
503 // Parent is an Object representing a DOMNode, with or without a dojoType specified.
504 // Scan parent's children looking for nodes with dojoType specified, storing in list[].
505 // If parent has a dojoType, also collects <script type=dojo/*> children and stores in parent.scripts[].
507 // Object representing the parent node, like
509 // | node: DomNode, // scan children of this node
510 // | inherited: {dir: "rtl"}, // dir/lang setting inherited from above node
512 // | // attributes only set if node has dojoType specified
513 // | scripts: [], // empty array, put <script type=dojo/*> in here
514 // | clsInfo: { cls: dijit.form.Button, ...}
517 // Output array of objects (same format as parent) representing nodes to be turned into widgets
519 // Effective dir and lang settings on parent node, either set directly or inherited from grandparent
520 var inherited
= dojo
.clone(parent
.inherited
);
521 dojo
.forEach(["dir", "lang"], function(name
){
522 var val
= parent
.node
.getAttribute(name
);
524 inherited
[name
] = val
;
528 // if parent is a widget, then search for <script type=dojo/*> tags and put them in scripts[].
529 var scripts
= parent
.scripts
;
531 // unless parent is a widget with the stopParser flag set, continue search for dojoType, recursively
532 var recurse
= !parent
.clsInfo
|| !parent
.clsInfo
.cls
.prototype.stopParser
;
534 // scan parent's children looking for dojoType and <script type=dojo/*>
535 for(var child
= parent
.node
.firstChild
; child
; child
= child
.nextSibling
){
536 if(child
.nodeType
== 1){
537 var type
= recurse
&& child
.getAttribute(attrName
);
539 // if dojoType specified, add to output array of nodes to instantiate
542 clsInfo
: getClassInfo(type
), // note: won't find classes declared via dojo.Declaration
544 scripts
: [], // <script> nodes that are parent's children
545 inherited
: inherited
// dir & lang attributes inherited from parent
549 // Recurse, collecting <script type="dojo/..."> children, and also looking for
550 // descendant nodes with dojoType specified (unless the widget has the stopParser flag),
552 }else if(scripts
&& child
.nodeName
.toLowerCase() == "script"){
553 // if <script type="dojo/...">, save in scripts[]
554 type
= child
.getAttribute("type");
555 if (type
&& /^dojo\//i.test(type
)) {
559 // Recurse, looking for grandchild nodes with dojoType specified
569 // Make list of all nodes on page w/dojoType specified
572 node
: root
? dojo
.byId(root
) : dojo
.body(),
573 inherited
: (args
&& args
.inherited
) || {
574 dir
: dojo
._isBodyLtr() ? "ltr" : "rtl"
578 // go build the object instances
579 return this.instantiate(list
, null, args
); // Array
583 //Register the parser callback. It should be the first callback
584 //after the a11y test.
587 var parseRunner = function(){
588 if(dojo
.config
.parseOnLoad
){
593 // FIXME: need to clobber cross-dependency!!
594 if(dojo
.exists("dijit.wai.onload") && (dijit
.wai
.onload
=== dojo
._loaders
[0])){
595 dojo
._loaders
.splice(1, 0, parseRunner
);
597 dojo
._loaders
.unshift(parseRunner
);
603 if(!dojo
._hasResource
["dojo.window"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
604 dojo
._hasResource
["dojo.window"] = true;
605 dojo
.provide("dojo.window");
607 dojo
.window
.getBox = function(){
609 // Returns the dimensions and scroll position of the viewable area of a browser window
611 var scrollRoot
= (dojo
.doc
.compatMode
== 'BackCompat') ? dojo
.body() : dojo
.doc
.documentElement
;
613 // get scroll position
614 var scroll
= dojo
._docScroll(); // scrollRoot.scrollTop/Left should work
615 return { w
: scrollRoot
.clientWidth
, h
: scrollRoot
.clientHeight
, l
: scroll
.x
, t
: scroll
.y
};
618 dojo
.window
.get = function(doc
){
620 // Get window object associated with document doc
622 // In some IE versions (at least 6.0), document.parentWindow does not return a
623 // reference to the real window object (maybe a copy), so we must fix it as well
624 // We use IE specific execScript to attach the real window reference to
625 // document._parentWindow for later use
626 if(dojo
.isIE
&& window
!== document
.parentWindow
){
628 In IE 6, only the variable "window" can be used to connect events (others
631 doc
.parentWindow
.execScript("document._parentWindow = window;", "Javascript");
632 //to prevent memory leak, unset it after use
633 //another possibility is to add an onUnload handler which seems overkill to me (liucougar)
634 var win
= doc
._parentWindow
;
635 doc
._parentWindow
= null;
636 return win
; // Window
639 return doc
.parentWindow
|| doc
.defaultView
; // Window
642 dojo
.window
.scrollIntoView = function(/*DomNode*/ node
, /*Object?*/ pos
){
644 // Scroll the passed node into view, if it is not already.
646 // don't rely on node.scrollIntoView working just because the function is there
648 try{ // catch unexpected/unrecreatable errors (#7808) since we can recover using a semi-acceptable native method
649 node
= dojo
.byId(node
);
650 var doc
= node
.ownerDocument
|| dojo
.doc
,
651 body
= doc
.body
|| dojo
.body(),
652 html
= doc
.documentElement
|| body
.parentNode
,
653 isIE
= dojo
.isIE
, isWK
= dojo
.isWebKit
;
654 // if an untested browser, then use the native method
655 if((!(dojo
.isMoz
|| isIE
|| isWK
|| dojo
.isOpera
) || node
== body
|| node
== html
) && (typeof node
.scrollIntoView
!= "undefined")){
656 node
.scrollIntoView(false); // short-circuit to native if possible
659 var backCompat
= doc
.compatMode
== 'BackCompat',
660 clientAreaRoot
= backCompat
? body
: html
,
661 scrollRoot
= isWK
? body
: clientAreaRoot
,
662 rootWidth
= clientAreaRoot
.clientWidth
,
663 rootHeight
= clientAreaRoot
.clientHeight
,
664 rtl
= !dojo
._isBodyLtr(),
665 nodePos
= pos
|| dojo
.position(node
),
666 el
= node
.parentNode
,
667 isFixed = function(el
){
668 return ((isIE
<= 6 || (isIE
&& backCompat
))? false : (dojo
.style(el
, 'position').toLowerCase() == "fixed"));
670 if(isFixed(node
)){ return; } // nothing to do
673 if(el
== body
){ el
= scrollRoot
; }
674 var elPos
= dojo
.position(el
),
675 fixedPos
= isFixed(el
);
677 if(el
== scrollRoot
){
678 elPos
.w
= rootWidth
; elPos
.h
= rootHeight
;
679 if(scrollRoot
== html
&& isIE
&& rtl
){ elPos
.x
+= scrollRoot
.offsetWidth
-elPos
.w
; } // IE workaround where scrollbar causes negative x
680 if(elPos
.x
< 0 || !isIE
){ elPos
.x
= 0; } // IE can have values > 0
681 if(elPos
.y
< 0 || !isIE
){ elPos
.y
= 0; }
683 var pb
= dojo
._getPadBorderExtents(el
);
684 elPos
.w
-= pb
.w
; elPos
.h
-= pb
.h
; elPos
.x
+= pb
.l
; elPos
.y
+= pb
.t
;
687 if(el
!= scrollRoot
){ // body, html sizes already have the scrollbar removed
688 var clientSize
= el
.clientWidth
,
689 scrollBarSize
= elPos
.w
- clientSize
;
690 if(clientSize
> 0 && scrollBarSize
> 0){
691 elPos
.w
= clientSize
;
692 if(isIE
&& rtl
){ elPos
.x
+= scrollBarSize
; }
694 clientSize
= el
.clientHeight
;
695 scrollBarSize
= elPos
.h
- clientSize
;
696 if(clientSize
> 0 && scrollBarSize
> 0){
697 elPos
.h
= clientSize
;
700 if(fixedPos
){ // bounded by viewport, not parents
702 elPos
.h
+= elPos
.y
; elPos
.y
= 0;
705 elPos
.w
+= elPos
.x
; elPos
.x
= 0;
707 if(elPos
.y
+ elPos
.h
> rootHeight
){
708 elPos
.h
= rootHeight
- elPos
.y
;
710 if(elPos
.x
+ elPos
.w
> rootWidth
){
711 elPos
.w
= rootWidth
- elPos
.x
;
714 // calculate overflow in all 4 directions
715 var l
= nodePos
.x
- elPos
.x
, // beyond left: < 0
716 t
= nodePos
.y
- Math
.max(elPos
.y
, 0), // beyond top: < 0
717 r
= l
+ nodePos
.w
- elPos
.w
, // beyond right: > 0
718 bot
= t
+ nodePos
.h
- elPos
.h
; // beyond bottom: > 0
720 var s
= Math
[l
< 0? "max" : "min"](l
, r
);
721 nodePos
.x
+= el
.scrollLeft
;
722 el
.scrollLeft
+= (isIE
>= 8 && !backCompat
&& rtl
)? -s
: s
;
723 nodePos
.x
-= el
.scrollLeft
;
726 nodePos
.y
+= el
.scrollTop
;
727 el
.scrollTop
+= Math
[t
< 0? "max" : "min"](t
, bot
);
728 nodePos
.y
-= el
.scrollTop
;
730 el
= (el
!= scrollRoot
) && !fixedPos
&& el
.parentNode
;
733 console
.error('scrollIntoView: ' + error
);
734 node
.scrollIntoView(false);
740 if(!dojo
._hasResource
["dijit._base.manager"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
741 dojo
._hasResource
["dijit._base.manager"] = true;
742 dojo
.provide("dijit._base.manager");
744 dojo
.declare("dijit.WidgetSet", null, {
746 // A set of widgets indexed by id. A default instance of this class is
747 // available as `dijit.registry`
750 // Create a small list of widgets:
751 // | var ws = new dijit.WidgetSet();
752 // | ws.add(dijit.byId("one"));
753 // | ws.add(dijit.byId("two"));
754 // | // destroy both:
755 // | ws.forEach(function(w){ w.destroy(); });
758 // Using dijit.registry:
759 // | dijit.registry.forEach(function(w){ /* do something */ });
761 constructor: function(){
766 add: function(/*dijit._Widget*/ widget
){
768 // Add a widget to this list. If a duplicate ID is detected, a error is thrown.
770 // widget: dijit._Widget
771 // Any dijit._Widget subclass.
772 if(this._hash
[widget
.id
]){
773 throw new Error("Tried to register widget with id==" + widget
.id
+ " but that id is already registered");
775 this._hash
[widget
.id
] = widget
;
779 remove: function(/*String*/ id
){
781 // Remove a widget from this WidgetSet. Does not destroy the widget; simply
782 // removes the reference.
784 delete this._hash
[id
];
789 forEach: function(/*Function*/ func
, /* Object? */thisObj
){
791 // Call specified function for each widget in this set.
794 // A callback function to run for each item. Is passed the widget, the index
795 // in the iteration, and the full hash, similar to `dojo.forEach`.
798 // An optional scope parameter
801 // Using the default `dijit.registry` instance:
802 // | dijit.registry.forEach(function(widget){
803 // | console.log(widget.declaredClass);
807 // Returns self, in order to allow for further chaining.
809 thisObj
= thisObj
|| dojo
.global
;
811 for(id
in this._hash
){
812 func
.call(thisObj
, this._hash
[id
], i
++, this._hash
);
814 return this; // dijit.WidgetSet
817 filter: function(/*Function*/ filter
, /* Object? */thisObj
){
819 // Filter down this WidgetSet to a smaller new WidgetSet
820 // Works the same as `dojo.filter` and `dojo.NodeList.filter`
823 // Callback function to test truthiness. Is passed the widget
824 // reference and the pseudo-index in the object.
827 // Option scope to use for the filter function.
830 // Arbitrary: select the odd widgets in this list
831 // | dijit.registry.filter(function(w, i){
832 // | return i % 2 == 0;
833 // | }).forEach(function(w){ /* odd ones */ });
835 thisObj
= thisObj
|| dojo
.global
;
836 var res
= new dijit
.WidgetSet(), i
= 0, id
;
837 for(id
in this._hash
){
838 var w
= this._hash
[id
];
839 if(filter
.call(thisObj
, w
, i
++, this._hash
)){
843 return res
; // dijit.WidgetSet
846 byId: function(/*String*/ id
){
848 // Find a widget in this list by it's id.
850 // Test if an id is in a particular WidgetSet
851 // | var ws = new dijit.WidgetSet();
852 // | ws.add(dijit.byId("bar"));
853 // | var t = ws.byId("bar") // returns a widget
854 // | var x = ws.byId("foo"); // returns undefined
856 return this._hash
[id
]; // dijit._Widget
859 byClass: function(/*String*/ cls
){
861 // Reduce this widgetset to a new WidgetSet of a particular `declaredClass`
864 // The Class to scan for. Full dot-notated string.
867 // Find all `dijit.TitlePane`s in a page:
868 // | dijit.registry.byClass("dijit.TitlePane").forEach(function(tp){ tp.close(); });
870 var res
= new dijit
.WidgetSet(), id
, widget
;
871 for(id
in this._hash
){
872 widget
= this._hash
[id
];
873 if(widget
.declaredClass
== cls
){
877 return res
; // dijit.WidgetSet
882 // Convert this WidgetSet into a true Array
885 // Work with the widget .domNodes in a real Array
886 // | dojo.map(dijit.registry.toArray(), function(w){ return w.domNode; });
889 for(var id
in this._hash
){
890 ar
.push(this._hash
[id
]);
892 return ar
; // dijit._Widget[]
895 map: function(/* Function */func
, /* Object? */thisObj
){
897 // Create a new Array from this WidgetSet, following the same rules as `dojo.map`
899 // | var nodes = dijit.registry.map(function(w){ return w.domNode; });
902 // A new array of the returned values.
903 return dojo
.map(this.toArray(), func
, thisObj
); // Array
906 every: function(func
, thisObj
){
908 // A synthetic clone of `dojo.every` acting explicitly on this WidgetSet
911 // A callback function run for every widget in this list. Exits loop
912 // when the first false return is encountered.
915 // Optional scope parameter to use for the callback
917 thisObj
= thisObj
|| dojo
.global
;
919 for(i
in this._hash
){
920 if(!func
.call(thisObj
, this._hash
[i
], x
++, this._hash
)){
921 return false; // Boolean
924 return true; // Boolean
927 some: function(func
, thisObj
){
929 // A synthetic clone of `dojo.some` acting explictly on this WidgetSet
932 // A callback function run for every widget in this list. Exits loop
933 // when the first true return is encountered.
936 // Optional scope parameter to use for the callback
938 thisObj
= thisObj
|| dojo
.global
;
940 for(i
in this._hash
){
941 if(func
.call(thisObj
, this._hash
[i
], x
++, this._hash
)){
942 return true; // Boolean
945 return false; // Boolean
955 // A list of widgets on a page.
957 // Is an instance of `dijit.WidgetSet`
960 dijit
.registry
= new dijit
.WidgetSet();
962 var hash
= dijit
.registry
._hash
,
964 hasAttr
= dojo
.hasAttr
,
967 dijit
.byId = function(/*String|dijit._Widget*/ id
){
969 // Returns a widget by it's id, or if passed a widget, no-op (like dojo.byId())
970 return typeof id
== "string" ? hash
[id
] : id
; // dijit._Widget
973 var _widgetTypeCtr
= {};
974 dijit
.getUniqueId = function(/*String*/widgetType
){
976 // Generates a unique id for a given widgetType
980 id
= widgetType
+ "_" +
981 (widgetType
in _widgetTypeCtr
?
982 ++_widgetTypeCtr
[widgetType
] : _widgetTypeCtr
[widgetType
] = 0);
984 return dijit
._scopeName
== "dijit" ? id
: dijit
._scopeName
+ "_" + id
; // String
987 dijit
.findWidgets = function(/*DomNode*/ root
){
989 // Search subtree under root returning widgets found.
990 // Doesn't search for nested widgets (ie, widgets inside other widgets).
994 function getChildrenHelper(root
){
995 for(var node
= root
.firstChild
; node
; node
= node
.nextSibling
){
996 if(node
.nodeType
== 1){
997 var widgetId
= node
.getAttribute("widgetId");
999 outAry
.push(hash
[widgetId
]);
1001 getChildrenHelper(node
);
1007 getChildrenHelper(root
);
1011 dijit
._destroyAll = function(){
1013 // Code to destroy all widgets and do other cleanup on page unload
1015 // Clean up focus manager lingering references to widgets and nodes
1016 dijit
._curFocus
= null;
1017 dijit
._prevFocus
= null;
1018 dijit
._activeStack
= [];
1020 // Destroy all the widgets, top down
1021 dojo
.forEach(dijit
.findWidgets(dojo
.body()), function(widget
){
1022 // Avoid double destroy of widgets like Menu that are attached to <body>
1023 // even though they are logically children of other widgets.
1024 if(!widget
._destroyed
){
1025 if(widget
.destroyRecursive
){
1026 widget
.destroyRecursive();
1027 }else if(widget
.destroy
){
1035 // Only run _destroyAll() for IE because we think it's only necessary in that case,
1036 // and because it causes problems on FF. See bug #3531 for details.
1037 dojo
.addOnWindowUnload(function(){
1038 dijit
._destroyAll();
1042 dijit
.byNode = function(/*DOMNode*/ node
){
1044 // Returns the widget corresponding to the given DOMNode
1045 return hash
[node
.getAttribute("widgetId")]; // dijit._Widget
1048 dijit
.getEnclosingWidget = function(/*DOMNode*/ node
){
1050 // Returns the widget whose DOM tree contains the specified DOMNode, or null if
1051 // the node is not contained within the DOM tree of any widget
1053 var id
= node
.getAttribute
&& node
.getAttribute("widgetId");
1057 node
= node
.parentNode
;
1062 var shown
= (dijit
._isElementShown = function(/*Element*/ elem
){
1063 var s
= style(elem
);
1064 return (s
.visibility
!= "hidden")
1065 && (s
.visibility
!= "collapsed")
1066 && (s
.display
!= "none")
1067 && (attr(elem
, "type") != "hidden");
1070 dijit
.hasDefaultTabStop = function(/*Element*/ elem
){
1072 // Tests if element is tab-navigable even without an explicit tabIndex setting
1074 // No explicit tabIndex setting, need to investigate node type
1075 switch(elem
.nodeName
.toLowerCase()){
1077 // An <a> w/out a tabindex is only navigable if it has an href
1078 return hasAttr(elem
, "href");
1085 // These are navigable by default
1088 // If it's an editor <iframe> then it's tab navigable.
1089 //TODO: feature detect "designMode" in elem.contentDocument?
1092 return elem
.contentDocument
.designMode
== "on";
1096 }else if(dojo
.isWebKit
){
1097 var doc
= elem
.contentDocument
,
1098 body
= doc
&& doc
.body
;
1099 return body
&& body
.contentEditable
== 'true';
1101 // contentWindow.document isn't accessible within IE7/8
1102 // if the iframe.src points to a foreign url and this
1103 // page contains an element, that could get focus
1105 doc
= elem
.contentWindow
.document
;
1106 body
= doc
&& doc
.body
;
1107 return body
&& body
.firstChild
&& body
.firstChild
.contentEditable
== 'true';
1113 return elem
.contentEditable
== 'true';
1117 var isTabNavigable
= (dijit
.isTabNavigable = function(/*Element*/ elem
){
1119 // Tests if an element is tab-navigable
1121 // TODO: convert (and rename method) to return effective tabIndex; will save time in _getTabNavigable()
1122 if(attr(elem
, "disabled")){
1124 }else if(hasAttr(elem
, "tabIndex")){
1125 // Explicit tab index setting
1126 return attr(elem
, "tabIndex") >= 0; // boolean
1128 // No explicit tabIndex setting, so depends on node type
1129 return dijit
.hasDefaultTabStop(elem
);
1133 dijit
._getTabNavigable = function(/*DOMNode*/ root
){
1135 // Finds descendants of the specified root node.
1138 // Finds the following descendants of the specified root node:
1139 // * the first tab-navigable element in document order
1140 // without a tabIndex or with tabIndex="0"
1141 // * the last tab-navigable element in document order
1142 // without a tabIndex or with tabIndex="0"
1143 // * the first element in document order with the lowest
1144 // positive tabIndex value
1145 // * the last element in document order with the highest
1146 // positive tabIndex value
1147 var first
, last
, lowest
, lowestTabindex
, highest
, highestTabindex
;
1148 var walkTree = function(/*DOMNode*/parent
){
1149 dojo
.query("> *", parent
).forEach(function(child
){
1150 // Skip hidden elements, and also non-HTML elements (those in custom namespaces) in IE,
1151 // since show() invokes getAttribute("type"), which crash on VML nodes in IE.
1152 if((dojo
.isIE
&& child
.scopeName
!=="HTML") || !shown(child
)){
1156 if(isTabNavigable(child
)){
1157 var tabindex
= attr(child
, "tabIndex");
1158 if(!hasAttr(child
, "tabIndex") || tabindex
== 0){
1159 if(!first
){ first
= child
; }
1161 }else if(tabindex
> 0){
1162 if(!lowest
|| tabindex
< lowestTabindex
){
1163 lowestTabindex
= tabindex
;
1166 if(!highest
|| tabindex
>= highestTabindex
){
1167 highestTabindex
= tabindex
;
1172 if(child
.nodeName
.toUpperCase() != 'SELECT'){
1177 if(shown(root
)){ walkTree(root
) }
1178 return { first
: first
, last
: last
, lowest
: lowest
, highest
: highest
};
1180 dijit
.getFirstInTabbingOrder = function(/*String|DOMNode*/ root
){
1182 // Finds the descendant of the specified root node
1183 // that is first in the tabbing order
1184 var elems
= dijit
._getTabNavigable(dojo
.byId(root
));
1185 return elems
.lowest
? elems
.lowest
: elems
.first
; // DomNode
1188 dijit
.getLastInTabbingOrder = function(/*String|DOMNode*/ root
){
1190 // Finds the descendant of the specified root node
1191 // that is last in the tabbing order
1192 var elems
= dijit
._getTabNavigable(dojo
.byId(root
));
1193 return elems
.last
? elems
.last
: elems
.highest
; // DomNode
1198 // defaultDuration: Integer
1199 // The default animation speed (in ms) to use for all Dijit
1200 // transitional animations, unless otherwise specified
1201 // on a per-instance basis. Defaults to 200, overrided by
1202 // `djConfig.defaultDuration`
1203 defaultDuration: 200
1207 dijit
.defaultDuration
= dojo
.config
["defaultDuration"] || 200;
1213 if(!dojo
._hasResource
["dijit._base.focus"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
1214 dojo
._hasResource
["dijit._base.focus"] = true;
1215 dojo
.provide("dijit._base.focus");
1218 // for dijit.isTabNavigable()
1221 // These functions are used to query or set the focus and selection.
1223 // Also, they trace when widgets become activated/deactivated,
1224 // so that the widget can fire _onFocus/_onBlur events.
1225 // "Active" here means something similar to "focused", but
1226 // "focus" isn't quite the right word because we keep track of
1227 // a whole stack of "active" widgets. Example: ComboButton --> Menu -->
1228 // MenuItem. The onBlur event for ComboButton doesn't fire due to focusing
1229 // on the Menu or a MenuItem, since they are considered part of the
1230 // ComboButton widget. It only happens when focus is shifted
1231 // somewhere completely different.
1234 // _curFocus: DomNode
1235 // Currently focused item on screen
1238 // _prevFocus: DomNode
1239 // Previously focused item on screen
1242 isCollapsed: function(){
1244 // Returns true if there is no text selected
1245 return dijit
.getBookmark().isCollapsed
;
1248 getBookmark: function(){
1250 // Retrieves a bookmark that can be used with moveToBookmark to return to the same range
1251 var bm
, rg
, tg
, sel
= dojo
.doc
.selection
, cf
= dijit
._curFocus
;
1253 if(dojo
.global
.getSelection
){
1254 //W3C Range API for selections.
1255 sel
= dojo
.global
.getSelection();
1257 if(sel
.isCollapsed
){
1258 tg
= cf
? cf
.tagName
: "";
1260 //Create a fake rangelike item to restore selections.
1261 tg
= tg
.toLowerCase();
1262 if(tg
== "textarea" ||
1263 (tg
== "input" && (!cf
.type
|| cf
.type
.toLowerCase() == "text"))){
1265 start
: cf
.selectionStart
,
1266 end
: cf
.selectionEnd
,
1270 return {isCollapsed
: (sel
.end
<= sel
.start
), mark
: sel
}; //Object.
1273 bm
= {isCollapsed
:true};
1275 rg
= sel
.getRangeAt(0);
1276 bm
= {isCollapsed
: false, mark
: rg
.cloneRange()};
1280 // If the current focus was a input of some sort and no selection, don't bother saving
1281 // a native bookmark. This is because it causes issues with dialog/page selection restore.
1282 // So, we need to create psuedo bookmarks to work with.
1283 tg
= cf
? cf
.tagName
: "";
1284 tg
= tg
.toLowerCase();
1285 if(cf
&& tg
&& (tg
== "button" || tg
== "textarea" || tg
== "input")){
1286 if(sel
.type
&& sel
.type
.toLowerCase() == "none"){
1292 rg
= sel
.createRange();
1294 isCollapsed
: rg
.text
&& rg
.text
.length
?false:true,
1304 //'IE' way for selections.
1306 // createRange() throws exception when dojo in iframe
1307 //and nothing selected, see #9632
1308 rg
= sel
.createRange();
1309 bm
.isCollapsed
= !(sel
.type
== 'Text' ? rg
.htmlText
.length
: rg
.length
);
1311 bm
.isCollapsed
= true;
1314 if(sel
.type
.toUpperCase() == 'CONTROL'){
1317 var i
=0,len
=rg
.length
;
1319 bm
.mark
.push(rg
.item(i
++));
1322 bm
.isCollapsed
= true;
1326 bm
.mark
= rg
.getBookmark();
1329 console
.warn("No idea how to store the current selection for this browser!");
1331 return bm
; // Object
1334 moveToBookmark: function(/*Object*/bookmark
){
1336 // Moves current selection to a bookmark
1338 // This should be a returned object from dijit.getBookmark()
1340 var _doc
= dojo
.doc
,
1341 mark
= bookmark
.mark
;
1343 if(dojo
.global
.getSelection
){
1344 //W3C Rangi API (FF, WebKit, Opera, etc)
1345 var sel
= dojo
.global
.getSelection();
1346 if(sel
&& sel
.removeAllRanges
){
1350 n
.selectionStart
= r
.start
;
1351 n
.selectionEnd
= r
.end
;
1353 sel
.removeAllRanges();
1357 console
.warn("No idea how to restore selection for this browser!");
1359 }else if(_doc
.selection
&& mark
){
1364 }else if(dojo
.isArray(mark
)){
1365 rg
= _doc
.body
.createControlRange();
1366 //rg.addElement does not have call/apply method, so can not call it directly
1367 //rg is not available in "range.addElement(item)", so can't use that either
1368 dojo
.forEach(mark
, function(n
){
1372 rg
= _doc
.body
.createTextRange();
1373 rg
.moveToBookmark(mark
);
1380 getFocus: function(/*Widget?*/ menu
, /*Window?*/ openedForWindow
){
1382 // Called as getFocus(), this returns an Object showing the current focus
1383 // and selected text.
1385 // Called as getFocus(widget), where widget is a (widget representing) a button
1386 // that was just pressed, it returns where focus was before that button
1387 // was pressed. (Pressing the button may have either shifted focus to the button,
1388 // or removed focus altogether.) In this case the selected text is not returned,
1389 // since it can't be accurately determined.
1391 // menu: dijit._Widget or {domNode: DomNode} structure
1392 // The button that was just pressed. If focus has disappeared or moved
1393 // to this button, returns the previous focus. In this case the bookmark
1394 // information is already lost, and null is returned.
1397 // iframe in which menu was opened
1400 // A handle to restore focus/selection, to be passed to `dijit.focus`
1401 var node
= !dijit
._curFocus
|| (menu
&& dojo
.isDescendant(dijit
._curFocus
, menu
.domNode
)) ? dijit
._prevFocus
: dijit
._curFocus
;
1404 bookmark
: (node
== dijit
._curFocus
) && dojo
.withGlobal(openedForWindow
|| dojo
.global
, dijit
.getBookmark
),
1405 openedForWindow
: openedForWindow
1409 focus: function(/*Object || DomNode */ handle
){
1411 // Sets the focused node and the selection according to argument.
1412 // To set focus to an iframe's content, pass in the iframe itself.
1414 // object returned by get(), or a DomNode
1416 if(!handle
){ return; }
1418 var node
= "node" in handle
? handle
.node
: handle
, // because handle is either DomNode or a composite object
1419 bookmark
= handle
.bookmark
,
1420 openedForWindow
= handle
.openedForWindow
,
1421 collapsed
= bookmark
? bookmark
.isCollapsed
: false;
1424 // Note that for iframe's we need to use the <iframe> to follow the parentNode chain,
1425 // but we need to set focus to iframe.contentWindow
1427 var focusNode
= (node
.tagName
.toLowerCase() == "iframe") ? node
.contentWindow
: node
;
1428 if(focusNode
&& focusNode
.focus
){
1430 // Gecko throws sometimes if setting focus is impossible,
1431 // node not displayed or something like that
1433 }catch(e
){/*quiet*/}
1435 dijit
._onFocusNode(node
);
1438 // set the selection
1439 // do not need to restore if current selection is not empty
1440 // (use keyboard to select a menu item) or if previous selection was collapsed
1441 // as it may cause focus shift (Esp in IE).
1442 if(bookmark
&& dojo
.withGlobal(openedForWindow
|| dojo
.global
, dijit
.isCollapsed
) && !collapsed
){
1443 if(openedForWindow
){
1444 openedForWindow
.focus();
1447 dojo
.withGlobal(openedForWindow
|| dojo
.global
, dijit
.moveToBookmark
, null, [bookmark
]);
1449 /*squelch IE internal error, see http://trac.dojotoolkit.org/ticket/1984 */
1454 // _activeStack: dijit._Widget[]
1455 // List of currently active widgets (focused widget and it's ancestors)
1458 registerIframe: function(/*DomNode*/ iframe
){
1460 // Registers listeners on the specified iframe so that any click
1461 // or focus event on that iframe (or anything in it) is reported
1462 // as a focus/click event on the <iframe> itself.
1464 // Currently only used by editor.
1466 // Handle to pass to unregisterIframe()
1467 return dijit
.registerWin(iframe
.contentWindow
, iframe
);
1470 unregisterIframe: function(/*Object*/ handle
){
1472 // Unregisters listeners on the specified iframe created by registerIframe.
1473 // After calling be sure to delete or null out the handle itself.
1475 // Handle returned by registerIframe()
1477 dijit
.unregisterWin(handle
);
1480 registerWin: function(/*Window?*/targetWindow
, /*DomNode?*/ effectiveNode
){
1482 // Registers listeners on the specified window (either the main
1483 // window or an iframe's window) to detect when the user has clicked somewhere
1484 // or focused somewhere.
1486 // Users should call registerIframe() instead of this method.
1488 // If specified this is the window associated with the iframe,
1489 // i.e. iframe.contentWindow.
1491 // If specified, report any focus events inside targetWindow as
1492 // an event on effectiveNode, rather than on evt.target.
1494 // Handle to pass to unregisterWin()
1496 // TODO: make this function private in 2.0; Editor/users should call registerIframe(),
1498 var mousedownListener = function(evt
){
1499 dijit
._justMouseDowned
= true;
1500 setTimeout(function(){ dijit
._justMouseDowned
= false; }, 0);
1502 // workaround weird IE bug where the click is on an orphaned node
1503 // (first time clicking a Select/DropDownButton inside a TooltipDialog)
1504 if(dojo
.isIE
&& evt
&& evt
.srcElement
&& evt
.srcElement
.parentNode
== null){
1508 dijit
._onTouchNode(effectiveNode
|| evt
.target
|| evt
.srcElement
, "mouse");
1510 //dojo.connect(targetWindow, "onscroll", ???);
1512 // Listen for blur and focus events on targetWindow's document.
1513 // IIRC, I'm using attachEvent() rather than dojo.connect() because focus/blur events don't bubble
1514 // through dojo.connect(), and also maybe to catch the focus events early, before onfocus handlers
1516 // Connect to <html> (rather than document) on IE to avoid memory leaks, but document on other browsers because
1517 // (at least for FF) the focus event doesn't fire on <html> or <body>.
1518 var doc
= dojo
.isIE
? targetWindow
.document
.documentElement
: targetWindow
.document
;
1521 doc
.attachEvent('onmousedown', mousedownListener
);
1522 var activateListener = function(evt
){
1523 // IE reports that nodes like <body> have gotten focus, even though they have tabIndex=-1,
1524 // Should consider those more like a mouse-click than a focus....
1525 if(evt
.srcElement
.tagName
.toLowerCase() != "#document" &&
1526 dijit
.isTabNavigable(evt
.srcElement
)){
1527 dijit
._onFocusNode(effectiveNode
|| evt
.srcElement
);
1529 dijit
._onTouchNode(effectiveNode
|| evt
.srcElement
);
1532 doc
.attachEvent('onactivate', activateListener
);
1533 var deactivateListener = function(evt
){
1534 dijit
._onBlurNode(effectiveNode
|| evt
.srcElement
);
1536 doc
.attachEvent('ondeactivate', deactivateListener
);
1539 doc
.detachEvent('onmousedown', mousedownListener
);
1540 doc
.detachEvent('onactivate', activateListener
);
1541 doc
.detachEvent('ondeactivate', deactivateListener
);
1542 doc
= null; // prevent memory leak (apparent circular reference via closure)
1545 doc
.addEventListener('mousedown', mousedownListener
, true);
1546 var focusListener = function(evt
){
1547 dijit
._onFocusNode(effectiveNode
|| evt
.target
);
1549 doc
.addEventListener('focus', focusListener
, true);
1550 var blurListener = function(evt
){
1551 dijit
._onBlurNode(effectiveNode
|| evt
.target
);
1553 doc
.addEventListener('blur', blurListener
, true);
1556 doc
.removeEventListener('mousedown', mousedownListener
, true);
1557 doc
.removeEventListener('focus', focusListener
, true);
1558 doc
.removeEventListener('blur', blurListener
, true);
1559 doc
= null; // prevent memory leak (apparent circular reference via closure)
1565 unregisterWin: function(/*Handle*/ handle
){
1567 // Unregisters listeners on the specified window (either the main
1568 // window or an iframe's window) according to handle returned from registerWin().
1569 // After calling be sure to delete or null out the handle itself.
1571 // Currently our handle is actually a function
1575 _onBlurNode: function(/*DomNode*/ node
){
1577 // Called when focus leaves a node.
1578 // Usually ignored, _unless_ it *isn't* follwed by touching another node,
1579 // which indicates that we tabbed off the last field on the page,
1580 // in which case every widget is marked inactive
1581 dijit
._prevFocus
= dijit
._curFocus
;
1582 dijit
._curFocus
= null;
1584 if(dijit
._justMouseDowned
){
1585 // the mouse down caused a new widget to be marked as active; this blur event
1586 // is coming late, so ignore it.
1590 // if the blur event isn't followed by a focus event then mark all widgets as inactive.
1591 if(dijit
._clearActiveWidgetsTimer
){
1592 clearTimeout(dijit
._clearActiveWidgetsTimer
);
1594 dijit
._clearActiveWidgetsTimer
= setTimeout(function(){
1595 delete dijit
._clearActiveWidgetsTimer
;
1596 dijit
._setStack([]);
1597 dijit
._prevFocus
= null;
1601 _onTouchNode: function(/*DomNode*/ node
, /*String*/ by
){
1603 // Callback when node is focused or mouse-downed
1605 // The node that was touched.
1607 // "mouse" if the focus/touch was caused by a mouse down event
1609 // ignore the recent blurNode event
1610 if(dijit
._clearActiveWidgetsTimer
){
1611 clearTimeout(dijit
._clearActiveWidgetsTimer
);
1612 delete dijit
._clearActiveWidgetsTimer
;
1615 // compute stack of active widgets (ex: ComboButton --> Menu --> MenuItem)
1619 var popupParent
= dojo
.attr(node
, "dijitPopupParent");
1621 node
=dijit
.byId(popupParent
).domNode
;
1622 }else if(node
.tagName
&& node
.tagName
.toLowerCase() == "body"){
1623 // is this the root of the document or just the root of an iframe?
1624 if(node
=== dojo
.body()){
1625 // node is the root of the main document
1628 // otherwise, find the iframe this node refers to (can't access it via parentNode,
1629 // need to do this trick instead). window.frameElement is supported in IE/FF/Webkit
1630 node
=dojo
.window
.get(node
.ownerDocument
).frameElement
;
1632 // if this node is the root node of a widget, then add widget id to stack,
1633 // except ignore clicks on disabled widgets (actually focusing a disabled widget still works,
1634 // to support MenuItem)
1635 var id
= node
.getAttribute
&& node
.getAttribute("widgetId"),
1636 widget
= id
&& dijit
.byId(id
);
1637 if(widget
&& !(by
== "mouse" && widget
.get("disabled"))){
1638 newStack
.unshift(id
);
1640 node
=node
.parentNode
;
1643 }catch(e
){ /* squelch */ }
1645 dijit
._setStack(newStack
, by
);
1648 _onFocusNode: function(/*DomNode*/ node
){
1650 // Callback when node is focused
1656 if(node
.nodeType
== 9){
1657 // Ignore focus events on the document itself. This is here so that
1658 // (for example) clicking the up/down arrows of a spinner
1659 // (which don't get focus) won't cause that widget to blur. (FF issue)
1663 dijit
._onTouchNode(node
);
1665 if(node
== dijit
._curFocus
){ return; }
1666 if(dijit
._curFocus
){
1667 dijit
._prevFocus
= dijit
._curFocus
;
1669 dijit
._curFocus
= node
;
1670 dojo
.publish("focusNode", [node
]);
1673 _setStack: function(/*String[]*/ newStack
, /*String*/ by
){
1675 // The stack of active widgets has changed. Send out appropriate events and records new stack.
1677 // array of widget id's, starting from the top (outermost) widget
1679 // "mouse" if the focus/touch was caused by a mouse down event
1681 var oldStack
= dijit
._activeStack
;
1682 dijit
._activeStack
= newStack
;
1684 // compare old stack to new stack to see how many elements they have in common
1685 for(var nCommon
=0; nCommon
<Math
.min(oldStack
.length
, newStack
.length
); nCommon
++){
1686 if(oldStack
[nCommon
] != newStack
[nCommon
]){
1692 // for all elements that have gone out of focus, send blur event
1693 for(var i
=oldStack
.length
-1; i
>=nCommon
; i
--){
1694 widget
= dijit
.byId(oldStack
[i
]);
1696 widget
._focused
= false;
1697 widget
._hasBeenBlurred
= true;
1701 dojo
.publish("widgetBlur", [widget
, by
]);
1705 // for all element that have come into focus, send focus event
1706 for(i
=nCommon
; i
<newStack
.length
; i
++){
1707 widget
= dijit
.byId(newStack
[i
]);
1709 widget
._focused
= true;
1710 if(widget
._onFocus
){
1711 widget
._onFocus(by
);
1713 dojo
.publish("widgetFocus", [widget
, by
]);
1719 // register top window and all the iframes it contains
1720 dojo
.addOnLoad(function(){
1721 var handle
= dijit
.registerWin(window
);
1723 dojo
.addOnWindowUnload(function(){
1724 dijit
.unregisterWin(handle
);
1732 if(!dojo
._hasResource
["dojo.AdapterRegistry"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
1733 dojo
._hasResource
["dojo.AdapterRegistry"] = true;
1734 dojo
.provide("dojo.AdapterRegistry");
1736 dojo
.AdapterRegistry = function(/*Boolean?*/ returnWrappers
){
1738 // A registry to make contextual calling/searching easier.
1740 // Objects of this class keep list of arrays in the form [name, check,
1741 // wrap, directReturn] that are used to determine what the contextual
1742 // result of a set of checked arguments is. All check/wrap functions
1743 // in this registry should be of the same arity.
1745 // | // create a new registry
1746 // | var reg = new dojo.AdapterRegistry();
1747 // | reg.register("handleString",
1750 // | // do something with the string here
1753 // | reg.register("handleArr",
1756 // | // do something with the array here
1760 // | // now we can pass reg.match() *either* an array or a string and
1761 // | // the value we pass will get handled by the right function
1762 // | reg.match("someValue"); // will call the first function
1763 // | reg.match(["someValue"]); // will call the second
1766 this.returnWrappers
= returnWrappers
|| false; // Boolean
1769 dojo
.extend(dojo
.AdapterRegistry
, {
1770 register: function(/*String*/ name
, /*Function*/ check
, /*Function*/ wrap
, /*Boolean?*/ directReturn
, /*Boolean?*/ override
){
1772 // register a check function to determine if the wrap function or
1773 // object gets selected
1775 // a way to identify this matcher.
1777 // a function that arguments are passed to from the adapter's
1778 // match() function. The check function should return true if the
1779 // given arguments are appropriate for the wrap function.
1781 // If directReturn is true, the value passed in for wrap will be
1782 // returned instead of being called. Alternately, the
1783 // AdapterRegistry can be set globally to "return not call" using
1784 // the returnWrappers property. Either way, this behavior allows
1785 // the registry to act as a "search" function instead of a
1786 // function interception library.
1788 // If override is given and true, the check function will be given
1789 // highest priority. Otherwise, it will be the lowest priority
1791 this.pairs
[((override
) ? "unshift" : "push")]([name
, check
, wrap
, directReturn
]);
1794 match: function(/* ... */){
1796 // Find an adapter for the given arguments. If no suitable adapter
1797 // is found, throws an exception. match() accepts any number of
1798 // arguments, all of which are passed to all matching functions
1799 // from the registered pairs.
1800 for(var i
= 0; i
< this.pairs
.length
; i
++){
1801 var pair
= this.pairs
[i
];
1802 if(pair
[1].apply(this, arguments
)){
1803 if((pair
[3])||(this.returnWrappers
)){
1806 return pair
[2].apply(this, arguments
);
1810 throw new Error("No match found");
1813 unregister: function(name
){
1814 // summary: Remove a named adapter from the registry
1816 // FIXME: this is kind of a dumb way to handle this. On a large
1817 // registry this will be slow-ish and we can use the name as a lookup
1818 // should we choose to trade memory for speed.
1819 for(var i
= 0; i
< this.pairs
.length
; i
++){
1820 var pair
= this.pairs
[i
];
1821 if(pair
[0] == name
){
1822 this.pairs
.splice(i
, 1);
1832 if(!dojo
._hasResource
["dijit._base.place"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
1833 dojo
._hasResource
["dijit._base.place"] = true;
1834 dojo
.provide("dijit._base.place");
1840 dijit
.getViewport = function(){
1842 // Returns the dimensions and scroll position of the viewable area of a browser window
1844 return dojo
.window
.getBox();
1848 dijit.__Position = function(){
1850 // horizontal coordinate in pixels, relative to document body
1852 // vertical coordinate in pixels, relative to document body
1860 dijit
.placeOnScreen = function(
1862 /* dijit.__Position */ pos
,
1863 /* String[] */ corners
,
1864 /* dijit.__Position? */ padding
){
1866 // Positions one of the node's corners at specified position
1867 // such that node is fully visible in viewport.
1869 // NOTE: node is assumed to be absolutely or relatively positioned.
1871 // Object like {x: 10, y: 20}
1873 // Array of Strings representing order to try corners in, like ["TR", "BL"].
1874 // Possible values are:
1875 // * "BL" - bottom left
1876 // * "BR" - bottom right
1877 // * "TL" - top left
1878 // * "TR" - top right
1880 // set padding to put some buffer around the element you want to position.
1882 // Try to place node's top right corner at (10,20).
1883 // If that makes node go (partially) off screen, then try placing
1884 // bottom left corner at (10,20).
1885 // | placeOnScreen(node, {x: 10, y: 20}, ["TR", "BL"])
1887 var choices
= dojo
.map(corners
, function(corner
){
1888 var c
= { corner
: corner
, pos
: {x
:pos
.x
,y
:pos
.y
} };
1890 c
.pos
.x
+= corner
.charAt(1) == 'L' ? padding
.x
: -padding
.x
;
1891 c
.pos
.y
+= corner
.charAt(0) == 'T' ? padding
.y
: -padding
.y
;
1896 return dijit
._place(node
, choices
);
1899 dijit
._place = function(/*DomNode*/ node
, /* Array */ choices
, /* Function */ layoutNode
){
1901 // Given a list of spots to put node, put it at the first spot where it fits,
1902 // of if it doesn't fit anywhere then the place with the least overflow
1904 // Array of elements like: {corner: 'TL', pos: {x: 10, y: 20} }
1905 // Above example says to put the top-left corner of the node at (10,20)
1906 // layoutNode: Function(node, aroundNodeCorner, nodeCorner)
1907 // for things like tooltip, they are displayed differently (and have different dimensions)
1908 // based on their orientation relative to the parent. This adjusts the popup based on orientation.
1910 // get {x: 10, y: 10, w: 100, h:100} type obj representing position of
1911 // viewport over document
1912 var view
= dojo
.window
.getBox();
1914 // This won't work if the node is inside a <div style="position: relative">,
1915 // so reattach it to dojo.doc.body. (Otherwise, the positioning will be wrong
1916 // and also it might get cutoff)
1917 if(!node
.parentNode
|| String(node
.parentNode
.tagName
).toLowerCase() != "body"){
1918 dojo
.body().appendChild(node
);
1922 dojo
.some(choices
, function(choice
){
1923 var corner
= choice
.corner
;
1924 var pos
= choice
.pos
;
1926 // configure node to be displayed in given position relative to button
1927 // (need to do this in order to get an accurate size for the node, because
1928 // a tooltips size changes based on position, due to triangle)
1930 layoutNode(node
, choice
.aroundCorner
, corner
);
1934 var style
= node
.style
;
1935 var oldDisplay
= style
.display
;
1936 var oldVis
= style
.visibility
;
1937 style
.visibility
= "hidden";
1939 var mb
= dojo
.marginBox(node
);
1940 style
.display
= oldDisplay
;
1941 style
.visibility
= oldVis
;
1943 // coordinates and size of node with specified corner placed at pos,
1944 // and clipped by viewport
1945 var startX
= Math
.max(view
.l
, corner
.charAt(1) == 'L' ? pos
.x
: (pos
.x
- mb
.w
)),
1946 startY
= Math
.max(view
.t
, corner
.charAt(0) == 'T' ? pos
.y
: (pos
.y
- mb
.h
)),
1947 endX
= Math
.min(view
.l
+ view
.w
, corner
.charAt(1) == 'L' ? (startX
+ mb
.w
) : pos
.x
),
1948 endY
= Math
.min(view
.t
+ view
.h
, corner
.charAt(0) == 'T' ? (startY
+ mb
.h
) : pos
.y
),
1949 width
= endX
- startX
,
1950 height
= endY
- startY
,
1951 overflow
= (mb
.w
- width
) + (mb
.h
- height
);
1953 if(best
== null || overflow
< best
.overflow
){
1956 aroundCorner
: choice
.aroundCorner
,
1967 node
.style
.left
= best
.x
+ "px";
1968 node
.style
.top
= best
.y
+ "px";
1969 if(best
.overflow
&& layoutNode
){
1970 layoutNode(node
, best
.aroundCorner
, best
.corner
);
1975 dijit
.placeOnScreenAroundNode = function(
1977 /* DomNode */ aroundNode
,
1978 /* Object */ aroundCorners
,
1979 /* Function? */ layoutNode
){
1982 // Position node adjacent or kitty-corner to aroundNode
1983 // such that it's fully visible in viewport.
1986 // Place node such that corner of node touches a corner of
1987 // aroundNode, and that node is fully visible.
1990 // Ordered list of pairs of corners to try matching up.
1991 // Each pair of corners is represented as a key/value in the hash,
1992 // where the key corresponds to the aroundNode's corner, and
1993 // the value corresponds to the node's corner:
1995 // | { aroundNodeCorner1: nodeCorner1, aroundNodeCorner2: nodeCorner2, ...}
1997 // The following strings are used to represent the four corners:
1998 // * "BL" - bottom left
1999 // * "BR" - bottom right
2000 // * "TL" - top left
2001 // * "TR" - top right
2003 // layoutNode: Function(node, aroundNodeCorner, nodeCorner)
2004 // For things like tooltip, they are displayed differently (and have different dimensions)
2005 // based on their orientation relative to the parent. This adjusts the popup based on orientation.
2008 // | dijit.placeOnScreenAroundNode(node, aroundNode, {'BL':'TL', 'TR':'BR'});
2009 // This will try to position node such that node's top-left corner is at the same position
2010 // as the bottom left corner of the aroundNode (ie, put node below
2011 // aroundNode, with left edges aligned). If that fails it will try to put
2012 // the bottom-right corner of node where the top right corner of aroundNode is
2013 // (ie, put node above aroundNode, with right edges aligned)
2016 // get coordinates of aroundNode
2017 aroundNode
= dojo
.byId(aroundNode
);
2018 var oldDisplay
= aroundNode
.style
.display
;
2019 aroundNode
.style
.display
="";
2020 // #3172: use the slightly tighter border box instead of marginBox
2021 var aroundNodePos
= dojo
.position(aroundNode
, true);
2022 aroundNode
.style
.display
=oldDisplay
;
2024 // place the node around the calculated rectangle
2025 return dijit
._placeOnScreenAroundRect(node
,
2026 aroundNodePos
.x
, aroundNodePos
.y
, aroundNodePos
.w
, aroundNodePos
.h
, // rectangle
2027 aroundCorners
, layoutNode
);
2031 dijit.__Rectangle = function(){
2033 // horizontal offset in pixels, relative to document body
2035 // vertical offset in pixels, relative to document body
2044 this.height = height;
2049 dijit
.placeOnScreenAroundRectangle = function(
2051 /* dijit.__Rectangle */ aroundRect
,
2052 /* Object */ aroundCorners
,
2053 /* Function */ layoutNode
){
2056 // Like dijit.placeOnScreenAroundNode(), except that the "around"
2057 // parameter is an arbitrary rectangle on the screen (x, y, width, height)
2058 // instead of a dom node.
2060 return dijit
._placeOnScreenAroundRect(node
,
2061 aroundRect
.x
, aroundRect
.y
, aroundRect
.width
, aroundRect
.height
, // rectangle
2062 aroundCorners
, layoutNode
);
2065 dijit
._placeOnScreenAroundRect = function(
2070 /* Number */ height
,
2071 /* Object */ aroundCorners
,
2072 /* Function */ layoutNode
){
2075 // Like dijit.placeOnScreenAroundNode(), except it accepts coordinates
2076 // of a rectangle to place node adjacent to.
2078 // TODO: combine with placeOnScreenAroundRectangle()
2080 // Generate list of possible positions for node
2082 for(var nodeCorner
in aroundCorners
){
2084 aroundCorner
: nodeCorner
,
2085 corner
: aroundCorners
[nodeCorner
],
2087 x
: x
+ (nodeCorner
.charAt(1) == 'L' ? 0 : width
),
2088 y
: y
+ (nodeCorner
.charAt(0) == 'T' ? 0 : height
)
2093 return dijit
._place(node
, choices
, layoutNode
);
2096 dijit
.placementRegistry
= new dojo
.AdapterRegistry();
2097 dijit
.placementRegistry
.register("node",
2099 return typeof x
== "object" &&
2100 typeof x
.offsetWidth
!= "undefined" && typeof x
.offsetHeight
!= "undefined";
2102 dijit
.placeOnScreenAroundNode
);
2103 dijit
.placementRegistry
.register("rect",
2105 return typeof x
== "object" &&
2106 "x" in x
&& "y" in x
&& "width" in x
&& "height" in x
;
2108 dijit
.placeOnScreenAroundRectangle
);
2110 dijit
.placeOnScreenAroundElement = function(
2112 /* Object */ aroundElement
,
2113 /* Object */ aroundCorners
,
2114 /* Function */ layoutNode
){
2117 // Like dijit.placeOnScreenAroundNode(), except it accepts an arbitrary object
2118 // for the "around" argument and finds a proper processor to place a node.
2120 return dijit
.placementRegistry
.match
.apply(dijit
.placementRegistry
, arguments
);
2123 dijit
.getPopupAroundAlignment = function(/*Array*/ position
, /*Boolean*/ leftToRight
){
2125 // Transforms the passed array of preferred positions into a format suitable for passing as the aroundCorners argument to dijit.placeOnScreenAroundElement.
2127 // position: String[]
2128 // This variable controls the position of the drop down.
2129 // It's an array of strings with the following values:
2131 // * before: places drop down to the left of the target node/widget, or to the right in
2132 // the case of RTL scripts like Hebrew and Arabic
2133 // * after: places drop down to the right of the target node/widget, or to the left in
2134 // the case of RTL scripts like Hebrew and Arabic
2135 // * above: drop down goes above target node
2136 // * below: drop down goes below target node
2138 // The list is positions is tried, in order, until a position is found where the drop down fits
2139 // within the viewport.
2141 // leftToRight: Boolean
2142 // Whether the popup will be displaying in leftToRight mode.
2145 dojo
.forEach(position
, function(pos
){
2148 align
[leftToRight
? "BR" : "BL"] = leftToRight
? "BL" : "BR";
2151 align
[leftToRight
? "BL" : "BR"] = leftToRight
? "BR" : "BL";
2154 // first try to align left borders, next try to align right borders (or reverse for RTL mode)
2155 align
[leftToRight
? "BL" : "BR"] = leftToRight
? "TL" : "TR";
2156 align
[leftToRight
? "BR" : "BL"] = leftToRight
? "TR" : "TL";
2160 // first try to align left borders, next try to align right borders (or reverse for RTL mode)
2161 align
[leftToRight
? "TL" : "TR"] = leftToRight
? "BL" : "BR";
2162 align
[leftToRight
? "TR" : "TL"] = leftToRight
? "BR" : "BL";
2171 if(!dojo
._hasResource
["dijit._base.window"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2172 dojo
._hasResource
["dijit._base.window"] = true;
2173 dojo
.provide("dijit._base.window");
2177 dijit
.getDocumentWindow = function(doc
){
2178 return dojo
.window
.get(doc
);
2183 if(!dojo
._hasResource
["dijit._base.popup"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2184 dojo
._hasResource
["dijit._base.popup"] = true;
2185 dojo
.provide("dijit._base.popup");
2192 dijit.popup.__OpenArgs = function(){
2194 // widget to display
2196 // the button etc. that is displaying this popup
2198 // DOM node (typically a button); place popup relative to this node. (Specify this *or* "x" and "y" parameters.)
2200 // Absolute horizontal position (in pixels) to place node at. (Specify this *or* "around" parameter.)
2202 // Absolute vertical position (in pixels) to place node at. (Specify this *or* "around" parameter.)
2203 // orient: Object|String
2204 // When the around parameter is specified, orient should be an
2205 // ordered list of tuples of the form (around-node-corner, popup-node-corner).
2206 // dijit.popup.open() tries to position the popup according to each tuple in the list, in order,
2207 // until the popup appears fully within the viewport.
2209 // The default value is {BL:'TL', TL:'BL'}, which represents a list of two tuples:
2212 // where BL means "bottom left" and "TL" means "top left".
2213 // So by default, it first tries putting the popup below the around node, left-aligning them,
2214 // and then tries to put it above the around node, still left-aligning them. Note that the
2215 // default is horizontally reversed when in RTL mode.
2217 // When an (x,y) position is specified rather than an around node, orient is either
2218 // "R" or "L". R (for right) means that it tries to put the popup to the right of the mouse,
2219 // specifically positioning the popup's top-right corner at the mouse position, and if that doesn't
2220 // fit in the viewport, then it tries, in order, the bottom-right corner, the top left corner,
2221 // and the top-right corner.
2222 // onCancel: Function
2223 // callback when user has canceled the popup by
2224 // 1. hitting ESC or
2225 // 2. by using the popup widget's proprietary cancel mechanism (like a cancel button in a dialog);
2226 // i.e. whenever popupWidget.onCancel() is called, args.onCancel is called
2227 // onClose: Function
2228 // callback whenever this popup is closed
2229 // onExecute: Function
2230 // callback when user "executed" on the popup/sub-popup by selecting a menu choice, etc. (top menu only)
2231 // padding: dijit.__Position
2232 // adding a buffer around the opening position. This is only useful when around is not set.
2234 this.parent = parent;
2235 this.around = around;
2238 this.orient = orient;
2239 this.onCancel = onCancel;
2240 this.onClose = onClose;
2241 this.onExecute = onExecute;
2242 this.padding = padding;
2248 // This singleton is used to show/hide widgets as popups.
2250 // _stack: dijit._Widget[]
2251 // Stack of currently popped up widgets.
2252 // (someone opened _stack[0], and then it opened _stack[1], etc.)
2255 // _beginZIndex: Number
2256 // Z-index of the first popup. (If first popup opens other
2257 // popups they get a higher z-index.)
2262 moveOffScreen: function(/*DomNode*/ node
){
2264 // Initialization for nodes that will be used as popups
2267 // Puts node inside a wrapper <div>, and
2268 // positions wrapper div off screen, but not display:none, so that
2269 // the widget doesn't appear in the page flow and/or cause a blank
2270 // area at the bottom of the viewport (making scrollbar longer), but
2271 // initialization of contained widgets works correctly
2273 var wrapper
= node
.parentNode
;
2275 // Create a wrapper widget for when this node (in the future) will be used as a popup.
2276 // This is done early because of IE bugs where creating/moving DOM nodes causes focus
2277 // to go wonky, see tests/robot/Toolbar.html to reproduce
2278 if(!wrapper
|| !dojo
.hasClass(wrapper
, "dijitPopup")){
2279 wrapper
= dojo
.create("div",{
2280 "class":"dijitPopup",
2282 visibility
:"hidden",
2286 dijit
.setWaiRole(wrapper
, "presentation");
2287 wrapper
.appendChild(node
);
2297 dojo
.style(wrapper
, {
2298 visibility
: "hidden",
2299 // prevent transient scrollbar causing misalign (#5776), and initial flash in upper left (#10111)
2304 getTopPopup: function(){
2306 // Compute the closest ancestor popup that's *not* a child of another popup.
2307 // Ex: For a TooltipDialog with a button that spawns a tree of menus, find the popup of the button.
2308 var stack
= this._stack
;
2309 for(var pi
=stack
.length
-1; pi
> 0 && stack
[pi
].parent
=== stack
[pi
-1].widget
; pi
--){
2310 /* do nothing, just trying to get right value for pi */
2315 open: function(/*dijit.popup.__OpenArgs*/ args
){
2317 // Popup the widget at the specified position
2320 // opening at the mouse position
2321 // | dijit.popup.open({popup: menuWidget, x: evt.pageX, y: evt.pageY});
2324 // opening the widget as a dropdown
2325 // | dijit.popup.open({parent: this, popup: menuWidget, around: this.domNode, onClose: function(){...}});
2327 // Note that whatever widget called dijit.popup.open() should also listen to its own _onBlur callback
2328 // (fired from _base/focus.js) to know that focus has moved somewhere else and thus the popup should be closed.
2330 var stack
= this._stack
,
2331 widget
= args
.popup
,
2332 orient
= args
.orient
|| (
2333 (args
.parent
? args
.parent
.isLeftToRight() : dojo
._isBodyLtr()) ?
2334 {'BL':'TL', 'BR':'TR', 'TL':'BL', 'TR':'BR'} :
2335 {'BR':'TR', 'BL':'TL', 'TR':'BR', 'TL':'BL'}
2337 around
= args
.around
,
2338 id
= (args
.around
&& args
.around
.id
) ? (args
.around
.id
+"_dropdown") : ("popup_"+this._idGen
++);
2341 // The wrapper may have already been created, but in case it wasn't, create here
2342 var wrapper
= widget
.domNode
.parentNode
;
2343 if(!wrapper
|| !dojo
.hasClass(wrapper
, "dijitPopup")){
2344 this.moveOffScreen(widget
.domNode
);
2345 wrapper
= widget
.domNode
.parentNode
;
2348 dojo
.attr(wrapper
, {
2351 zIndex
: this._beginZIndex
+ stack
.length
2353 "class": "dijitPopup " + (widget
.baseClass
|| widget
["class"] || "").split(" ")[0] +"Popup",
2354 dijitPopupParent
: args
.parent
? args
.parent
.id
: ""
2357 if(dojo
.isIE
|| dojo
.isMoz
){
2358 var iframe
= wrapper
.childNodes
[1];
2360 iframe
= new dijit
.BackgroundIframe(wrapper
);
2364 // position the wrapper node and make it visible
2366 dijit
.placeOnScreenAroundElement(wrapper
, around
, orient
, widget
.orient
? dojo
.hitch(widget
, "orient") : null) :
2367 dijit
.placeOnScreen(wrapper
, args
, orient
== 'R' ? ['TR','BR','TL','BL'] : ['TL','BL','TR','BR'], args
.padding
);
2369 wrapper
.style
.visibility
= "visible";
2370 widget
.domNode
.style
.visibility
= "visible"; // counteract effects from _HasDropDown
2374 // provide default escape and tab key handling
2375 // (this will work for any widget, not just menu)
2376 handlers
.push(dojo
.connect(wrapper
, "onkeypress", this, function(evt
){
2377 if(evt
.charOrCode
== dojo
.keys
.ESCAPE
&& args
.onCancel
){
2378 dojo
.stopEvent(evt
);
2380 }else if(evt
.charOrCode
=== dojo
.keys
.TAB
){
2381 dojo
.stopEvent(evt
);
2382 var topPopup
= this.getTopPopup();
2383 if(topPopup
&& topPopup
.onCancel
){
2384 topPopup
.onCancel();
2389 // watch for cancel/execute events on the popup and notify the caller
2390 // (for a menu, "execute" means clicking an item)
2391 if(widget
.onCancel
){
2392 handlers
.push(dojo
.connect(widget
, "onCancel", args
.onCancel
));
2395 handlers
.push(dojo
.connect(widget
, widget
.onExecute
? "onExecute" : "onChange", this, function(){
2396 var topPopup
= this.getTopPopup();
2397 if(topPopup
&& topPopup
.onExecute
){
2398 topPopup
.onExecute();
2406 parent
: args
.parent
,
2407 onExecute
: args
.onExecute
,
2408 onCancel
: args
.onCancel
,
2409 onClose
: args
.onClose
,
2414 // TODO: in 2.0 standardize onShow() (used by StackContainer) and onOpen() (used here)
2415 widget
.onOpen(best
);
2421 close: function(/*dijit._Widget*/ popup
){
2423 // Close specified popup and any popups that it parented
2425 var stack
= this._stack
;
2427 // Basically work backwards from the top of the stack closing popups
2428 // until we hit the specified popup, but IIRC there was some issue where closing
2429 // a popup would cause others to close too. Thus if we are trying to close B in [A,B,C]
2430 // closing C might close B indirectly and then the while() condition will run where stack==[A]...
2431 // so the while condition is constructed defensively.
2432 while(dojo
.some(stack
, function(elem
){return elem
.widget
== popup
;})){
2433 var top
= stack
.pop(),
2434 wrapper
= top
.wrapper
,
2435 iframe
= top
.iframe
,
2436 widget
= top
.widget
,
2437 onClose
= top
.onClose
;
2440 // TODO: in 2.0 standardize onHide() (used by StackContainer) and onClose() (used here)
2443 dojo
.forEach(top
.handlers
, dojo
.disconnect
);
2445 // Move the widget plus it's wrapper off screen, unless it has already been destroyed in above onClose() etc.
2446 if(widget
&& widget
.domNode
){
2447 this.moveOffScreen(widget
.domNode
);
2449 dojo
.destroy(wrapper
);
2459 dijit
._frames
= new function(){
2464 this.pop = function(){
2467 iframe
= queue
.pop();
2468 iframe
.style
.display
="";
2471 var burl
= dojo
.config
["dojoBlankHtmlUrl"] || (dojo
.moduleUrl("dojo", "resources/blank.html")+"") || "javascript:\"\"";
2472 var html
="<iframe src='" + burl
+ "'"
2473 + " style='position: absolute; left: 0px; top: 0px;"
2474 + "z-index: -1; filter:Alpha(Opacity=\"0\");'>";
2475 iframe
= dojo
.doc
.createElement(html
);
2477 iframe
= dojo
.create("iframe");
2478 iframe
.src
= 'javascript:""';
2479 iframe
.className
= "dijitBackgroundIframe";
2480 dojo
.style(iframe
, "opacity", 0.1);
2482 iframe
.tabIndex
= -1; // Magic to prevent iframe from getting focus on tab keypress - as style didnt work.
2483 dijit
.setWaiRole(iframe
,"presentation");
2488 this.push = function(iframe
){
2489 iframe
.style
.display
="none";
2495 dijit
.BackgroundIframe = function(/* DomNode */node
){
2497 // For IE/FF z-index schenanigans. id attribute is required.
2500 // new dijit.BackgroundIframe(node)
2501 // Makes a background iframe as a child of node, that fills
2502 // area (and position) of node
2504 if(!node
.id
){ throw new Error("no id"); }
2505 if(dojo
.isIE
|| dojo
.isMoz
){
2506 var iframe
= dijit
._frames
.pop();
2507 node
.appendChild(iframe
);
2510 this._conn
= dojo
.connect(node
, 'onresize', this, function(){
2514 dojo
.style(iframe
, {
2519 this.iframe
= iframe
;
2523 dojo
.extend(dijit
.BackgroundIframe
, {
2524 resize: function(node
){
2526 // resize the iframe so its the same size as node
2528 // this function is a no-op in all browsers except
2529 // IE6, which does not support 100% width/height
2530 // of absolute positioned iframes
2531 if(this.iframe
&& dojo
.isIE
<7){
2532 dojo
.style(this.iframe
, {
2533 width
: node
.offsetWidth
+ 'px',
2534 height
: node
.offsetHeight
+ 'px'
2538 destroy: function(){
2540 // destroy the iframe
2542 dojo
.disconnect(this._conn
);
2546 dijit
._frames
.push(this.iframe
);
2554 if(!dojo
._hasResource
["dijit._base.scroll"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2555 dojo
._hasResource
["dijit._base.scroll"] = true;
2556 dojo
.provide("dijit._base.scroll");
2560 dijit
.scrollIntoView = function(/*DomNode*/ node
, /*Object?*/ pos
){
2562 // Scroll the passed node into view, if it is not already.
2563 // Deprecated, use `dojo.window.scrollIntoView` instead.
2565 dojo
.window
.scrollIntoView(node
, pos
);
2570 if(!dojo
._hasResource
["dojo.uacss"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2571 dojo
._hasResource
["dojo.uacss"] = true;
2572 dojo
.provide("dojo.uacss");
2576 // Applies pre-set CSS classes to the top-level HTML node, based on:
2577 // - browser (ex: dj_ie)
2578 // - browser version (ex: dj_ie6)
2579 // - box model (ex: dj_contentBox)
2580 // - text direction (ex: dijitRtl)
2582 // In addition, browser, browser version, and box model are
2583 // combined with an RTL flag when browser text is RTL. ex: dj_ie-rtl.
2586 html
= d
.doc
.documentElement
,
2591 boxModel
= d
.boxModel
.replace(/-/,''),
2595 dj_ie6
: maj(ie
) == 6,
2596 dj_ie7
: maj(ie
) == 7,
2597 dj_ie8
: maj(ie
) == 8,
2598 dj_quirks
: d
.isQuirks
,
2599 dj_iequirks
: ie
&& d
.isQuirks
,
2601 // NOTE: Opera not supported by dijit
2604 dj_khtml
: d
.isKhtml
,
2606 dj_webkit
: d
.isWebKit
,
2607 dj_safari
: d
.isSafari
,
2608 dj_chrome
: d
.isChrome
,
2610 dj_gecko
: d
.isMozilla
,
2611 dj_ff3
: maj(ff
) == 3
2612 }; // no dojo unsupported browsers
2614 classes
["dj_" + boxModel
] = true;
2616 // apply browser, browser version, and box model class names
2618 for(var clz
in classes
){
2620 classStr
+= clz
+ " ";
2623 html
.className
= d
.trim(html
.className
+ " " + classStr
);
2625 // If RTL mode, then add dj_rtl flag plus repeat existing classes with -rtl extension.
2626 // We can't run the code below until the <body> tag has loaded (so we can check for dir=rtl).
2627 // Unshift() is to run sniff code before the parser.
2628 dojo
._loaders
.unshift(function(){
2629 if(!dojo
._isBodyLtr()){
2630 var rtlClassStr
= "dj_rtl dijitRtl " + classStr
.replace(/ /g
, "-rtl ")
2631 html
.className
= d
.trim(html
.className
+ " " + rtlClassStr
);
2638 if(!dojo
._hasResource
["dijit._base.sniff"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2639 dojo
._hasResource
["dijit._base.sniff"] = true;
2641 // Applies pre-set CSS classes to the top-level HTML node, see
2642 // `dojo.uacss` for details.
2644 // Simply doing a require on this module will
2645 // establish this CSS. Modified version of Morris' CSS hack.
2647 dojo
.provide("dijit._base.sniff");
2653 if(!dojo
._hasResource
["dijit._base.typematic"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2654 dojo
._hasResource
["dijit._base.typematic"] = true;
2655 dojo
.provide("dijit._base.typematic");
2659 // These functions are used to repetitively call a user specified callback
2660 // method when a specific key or mouse click over a specific DOM node is
2661 // held down for a specific amount of time.
2662 // Only 1 such event is allowed to occur on the browser page at 1 time.
2664 _fireEventAndReload: function(){
2666 this._callback(++this._count
, this._node
, this._evt
);
2668 // Schedule next event, timer is at most minDelay (default 10ms) to avoid
2669 // browser overload (particularly avoiding starving DOH robot so it never gets to send a mouseup)
2670 this._currentTimeout
= Math
.max(
2671 this._currentTimeout
< 0 ? this._initialDelay
:
2672 (this._subsequentDelay
> 1 ? this._subsequentDelay
: Math
.round(this._currentTimeout
* this._subsequentDelay
)),
2674 this._timer
= setTimeout(dojo
.hitch(this, "_fireEventAndReload"), this._currentTimeout
);
2677 trigger: function(/*Event*/ evt
, /*Object*/ _this
, /*DOMNode*/ node
, /*Function*/ callback
, /*Object*/ obj
, /*Number*/ subsequentDelay
, /*Number*/ initialDelay
, /*Number?*/ minDelay
){
2679 // Start a timed, repeating callback sequence.
2680 // If already started, the function call is ignored.
2681 // This method is not normally called by the user but can be
2682 // when the normal listener code is insufficient.
2684 // key or mouse event object to pass to the user callback
2686 // pointer to the user's widget space.
2688 // the DOM node object to pass the the callback function
2690 // function to call until the sequence is stopped called with 3 parameters:
2692 // integer representing number of repeated calls (0..n) with -1 indicating the iteration has stopped
2694 // the DOM node object passed in
2696 // key or mouse event object
2698 // user space object used to uniquely identify each typematic sequence
2699 // subsequentDelay (optional):
2700 // if > 1, the number of milliseconds until the 3->n events occur
2701 // or else the fractional time multiplier for the next event's delay, default=0.9
2702 // initialDelay (optional):
2703 // the number of milliseconds until the 2nd event occurs, default=500ms
2704 // minDelay (optional):
2705 // the maximum delay in milliseconds for event to fire, default=10ms
2706 if(obj
!= this._obj
){
2708 this._initialDelay
= initialDelay
|| 500;
2709 this._subsequentDelay
= subsequentDelay
|| 0.90;
2710 this._minDelay
= minDelay
|| 10;
2714 this._currentTimeout
= -1;
2716 this._callback
= dojo
.hitch(_this
, callback
);
2717 this._fireEventAndReload();
2718 this._evt
= dojo
.mixin({faux
: true}, evt
);
2724 // Stop an ongoing timed, repeating callback sequence.
2726 clearTimeout(this._timer
);
2730 this._callback(-1, this._node
, this._evt
);
2735 addKeyListener: function(/*DOMNode*/ node
, /*Object*/ keyObject
, /*Object*/ _this
, /*Function*/ callback
, /*Number*/ subsequentDelay
, /*Number*/ initialDelay
, /*Number?*/ minDelay
){
2737 // Start listening for a specific typematic key.
2738 // See also the trigger method for other parameters.
2740 // an object defining the key to listen for:
2742 // the printable character (string) or keyCode (number) to listen for.
2744 // (deprecated - use charOrCode) the keyCode (number) to listen for (implies charCode = 0).
2746 // (deprecated - use charOrCode) the charCode (number) to listen for.
2748 // desired ctrl key state to initiate the callback sequence:
2750 // - released (false)
2751 // - either (unspecified)
2753 // same as ctrlKey but for the alt key
2755 // same as ctrlKey but for the shift key
2757 // an array of dojo.connect handles
2758 if(keyObject
.keyCode
){
2759 keyObject
.charOrCode
= keyObject
.keyCode
;
2760 dojo
.deprecated("keyCode attribute parameter for dijit.typematic.addKeyListener is deprecated. Use charOrCode instead.", "", "2.0");
2761 }else if(keyObject
.charCode
){
2762 keyObject
.charOrCode
= String
.fromCharCode(keyObject
.charCode
);
2763 dojo
.deprecated("charCode attribute parameter for dijit.typematic.addKeyListener is deprecated. Use charOrCode instead.", "", "2.0");
2766 dojo
.connect(node
, "onkeypress", this, function(evt
){
2767 if(evt
.charOrCode
== keyObject
.charOrCode
&&
2768 (keyObject
.ctrlKey
=== undefined || keyObject
.ctrlKey
== evt
.ctrlKey
) &&
2769 (keyObject
.altKey
=== undefined || keyObject
.altKey
== evt
.altKey
) &&
2770 (keyObject
.metaKey
=== undefined || keyObject
.metaKey
== (evt
.metaKey
|| false)) && // IE doesn't even set metaKey
2771 (keyObject
.shiftKey
=== undefined || keyObject
.shiftKey
== evt
.shiftKey
)){
2772 dojo
.stopEvent(evt
);
2773 dijit
.typematic
.trigger(evt
, _this
, node
, callback
, keyObject
, subsequentDelay
, initialDelay
, minDelay
);
2774 }else if(dijit
.typematic
._obj
== keyObject
){
2775 dijit
.typematic
.stop();
2778 dojo
.connect(node
, "onkeyup", this, function(evt
){
2779 if(dijit
.typematic
._obj
== keyObject
){
2780 dijit
.typematic
.stop();
2786 addMouseListener: function(/*DOMNode*/ node
, /*Object*/ _this
, /*Function*/ callback
, /*Number*/ subsequentDelay
, /*Number*/ initialDelay
, /*Number?*/ minDelay
){
2788 // Start listening for a typematic mouse click.
2789 // See the trigger method for other parameters.
2791 // an array of dojo.connect handles
2792 var dc
= dojo
.connect
;
2794 dc(node
, "mousedown", this, function(evt
){
2795 dojo
.stopEvent(evt
);
2796 dijit
.typematic
.trigger(evt
, _this
, node
, callback
, node
, subsequentDelay
, initialDelay
, minDelay
);
2798 dc(node
, "mouseup", this, function(evt
){
2799 dojo
.stopEvent(evt
);
2800 dijit
.typematic
.stop();
2802 dc(node
, "mouseout", this, function(evt
){
2803 dojo
.stopEvent(evt
);
2804 dijit
.typematic
.stop();
2806 dc(node
, "mousemove", this, function(evt
){
2807 evt
.preventDefault();
2809 dc(node
, "dblclick", this, function(evt
){
2810 dojo
.stopEvent(evt
);
2812 dijit
.typematic
.trigger(evt
, _this
, node
, callback
, node
, subsequentDelay
, initialDelay
, minDelay
);
2813 setTimeout(dojo
.hitch(this, dijit
.typematic
.stop
), 50);
2819 addListener: function(/*Node*/ mouseNode
, /*Node*/ keyNode
, /*Object*/ keyObject
, /*Object*/ _this
, /*Function*/ callback
, /*Number*/ subsequentDelay
, /*Number*/ initialDelay
, /*Number?*/ minDelay
){
2821 // Start listening for a specific typematic key and mouseclick.
2822 // This is a thin wrapper to addKeyListener and addMouseListener.
2823 // See the addMouseListener and addKeyListener methods for other parameters.
2825 // the DOM node object to listen on for mouse events.
2827 // the DOM node object to listen on for key events.
2829 // an array of dojo.connect handles
2830 return this.addKeyListener(keyNode
, keyObject
, _this
, callback
, subsequentDelay
, initialDelay
, minDelay
).concat(
2831 this.addMouseListener(mouseNode
, _this
, callback
, subsequentDelay
, initialDelay
, minDelay
));
2837 if(!dojo
._hasResource
["dijit._base.wai"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2838 dojo
._hasResource
["dijit._base.wai"] = true;
2839 dojo
.provide("dijit._base.wai");
2844 // Detects if we are in high-contrast mode or not
2846 // This must be a named function and not an anonymous
2847 // function, so that the widget parsing code can make sure it
2848 // registers its onload function after this function.
2849 // DO NOT USE "this" within this function.
2851 // create div for testing if high contrast mode is on or images are turned off
2852 var div
= dojo
.create("div",{
2855 cssText
:'border: 1px solid;'
2856 + 'border-color:red green;'
2857 + 'position: absolute;'
2860 + 'background-image: url("' + (dojo
.config
.blankGif
|| dojo
.moduleUrl("dojo", "resources/blank.gif")) + '");'
2865 var cs
= dojo
.getComputedStyle(div
);
2867 var bkImg
= cs
.backgroundImage
;
2868 var needsA11y
= (cs
.borderTopColor
== cs
.borderRightColor
) || (bkImg
!= null && (bkImg
== "none" || bkImg
== "url(invalid-url:)" ));
2869 dojo
[needsA11y
? "addClass" : "removeClass"](dojo
.body(), "dijit_a11y");
2871 div
.outerHTML
= ""; // prevent mixed-content warning, see http://support.microsoft.com/kb/925014
2873 dojo
.body().removeChild(div
);
2879 // Test if computer is in high contrast mode.
2880 // Make sure the a11y test runs first, before widgets are instantiated.
2881 if(dojo
.isIE
|| dojo
.isMoz
){ // NOTE: checking in Safari messes things up
2882 dojo
._loaders
.unshift(dijit
.wai
.onload
);
2886 _XhtmlRoles
: /banner|contentinfo|definition|main|navigation|search|note|secondary|seealso/,
2888 hasWaiRole: function(/*Element*/ elem
, /*String*/ role
){
2890 // Determines if an element has a particular non-XHTML role.
2892 // True if elem has the specific non-XHTML role attribute and false if not.
2893 // For backwards compatibility if role parameter not provided,
2894 // returns true if has non XHTML role
2895 var waiRole
= this.getWaiRole(elem
);
2896 return role
? (waiRole
.indexOf(role
) > -1) : (waiRole
.length
> 0);
2899 getWaiRole: function(/*Element*/ elem
){
2901 // Gets the non-XHTML role for an element (which should be a wai role).
2903 // The non-XHTML role of elem or an empty string if elem
2904 // does not have a role.
2905 return dojo
.trim((dojo
.attr(elem
, "role") || "").replace(this._XhtmlRoles
,"").replace("wairole:",""));
2908 setWaiRole: function(/*Element*/ elem
, /*String*/ role
){
2910 // Sets the role on an element.
2912 // Replace existing role attribute with new role.
2913 // If elem already has an XHTML role, append this role to XHTML role
2914 // and remove other ARIA roles.
2916 var curRole
= dojo
.attr(elem
, "role") || "";
2917 if(!this._XhtmlRoles
.test(curRole
)){
2918 dojo
.attr(elem
, "role", role
);
2920 if((" "+ curRole
+" ").indexOf(" " + role
+ " ") < 0){
2921 var clearXhtml
= dojo
.trim(curRole
.replace(this._XhtmlRoles
, ""));
2922 var cleanRole
= dojo
.trim(curRole
.replace(clearXhtml
, ""));
2923 dojo
.attr(elem
, "role", cleanRole
+ (cleanRole
? ' ' : '') + role
);
2928 removeWaiRole: function(/*Element*/ elem
, /*String*/ role
){
2930 // Removes the specified non-XHTML role from an element.
2931 // Removes role attribute if no specific role provided (for backwards compat.)
2933 var roleValue
= dojo
.attr(elem
, "role");
2934 if(!roleValue
){ return; }
2936 var t
= dojo
.trim((" " + roleValue
+ " ").replace(" " + role
+ " ", " "));
2937 dojo
.attr(elem
, "role", t
);
2939 elem
.removeAttribute("role");
2943 hasWaiState: function(/*Element*/ elem
, /*String*/ state
){
2945 // Determines if an element has a given state.
2947 // Checks for an attribute called "aria-"+state.
2949 // true if elem has a value for the given state and
2950 // false if it does not.
2952 return elem
.hasAttribute
? elem
.hasAttribute("aria-"+state
) : !!elem
.getAttribute("aria-"+state
);
2955 getWaiState: function(/*Element*/ elem
, /*String*/ state
){
2957 // Gets the value of a state on an element.
2959 // Checks for an attribute called "aria-"+state.
2961 // The value of the requested state on elem
2962 // or an empty string if elem has no value for state.
2964 return elem
.getAttribute("aria-"+state
) || "";
2967 setWaiState: function(/*Element*/ elem
, /*String*/ state
, /*String*/ value
){
2969 // Sets a state on an element.
2971 // Sets an attribute called "aria-"+state.
2973 elem
.setAttribute("aria-"+state
, value
);
2976 removeWaiState: function(/*Element*/ elem
, /*String*/ state
){
2978 // Removes a state from an element.
2980 // Sets an attribute called "aria-"+state.
2982 elem
.removeAttribute("aria-"+state
);
2988 if(!dojo
._hasResource
["dijit._base"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2989 dojo
._hasResource
["dijit._base"] = true;
2990 dojo
.provide("dijit._base");
3004 if(!dojo
._hasResource
["dijit._Widget"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
3005 dojo
._hasResource
["dijit._Widget"] = true;
3006 dojo
.provide("dijit._Widget");
3008 dojo
.require( "dijit._base" );
3011 // This code is to assist deferring dojo.connect() calls in widgets (connecting to events on the widgets'
3012 // DOM nodes) until someone actually needs to monitor that event.
3013 dojo
.connect(dojo
, "_connect",
3014 function(/*dijit._Widget*/ widget
, /*String*/ event
){
3015 if(widget
&& dojo
.isFunction(widget
._onConnect
)){
3016 widget
._onConnect(event
);
3020 dijit
._connectOnUseEventHandler = function(/*Event*/ event
){};
3022 // Keep track of where the last keydown event was, to help avoid generating
3023 // spurious ondijitclick events when:
3024 // 1. focus is on a <button> or <a>
3025 // 2. user presses then releases the ENTER key
3026 // 3. onclick handler fires and shifts focus to another node, with an ondijitclick handler
3027 // 4. onkeyup event fires, causing the ondijitclick handler to fire
3028 dijit
._lastKeyDownNode
= null;
3031 var keydownCallback = function(evt
){
3032 dijit
._lastKeyDownNode
= evt
.srcElement
;
3034 dojo
.doc
.attachEvent('onkeydown', keydownCallback
);
3035 dojo
.addOnWindowUnload(function(){
3036 dojo
.doc
.detachEvent('onkeydown', keydownCallback
);
3040 dojo
.doc
.addEventListener('keydown', function(evt
){
3041 dijit
._lastKeyDownNode
= evt
.target
;
3047 var _attrReg
= {}, // cached results from getSetterAttributes
3048 getSetterAttributes = function(widget
){
3050 // Returns list of attributes with custom setters for specified widget
3051 var dc
= widget
.declaredClass
;
3055 proto
= widget
.constructor.prototype;
3056 for(var fxName
in proto
){
3057 if(dojo
.isFunction(proto
[fxName
]) && (attrs
= fxName
.match(/^_set([a-zA-Z]*)Attr$/)) && attrs
[1]){
3058 r
.push(attrs
[1].charAt(0).toLowerCase() + attrs
[1].substr(1));
3063 return _attrReg
[dc
] || []; // String[]
3066 dojo
.declare("dijit._Widget", null, {
3068 // Base class for all Dijit widgets.
3070 // id: [const] String
3071 // A unique, opaque ID string that can be assigned by users or by the
3072 // system. If the developer passes an ID which is known not to be
3073 // unique, the specified ID is ignored and the system-generated ID is
3077 // lang: [const] String
3078 // Rarely used. Overrides the default Dojo locale used to render this widget,
3079 // as defined by the [HTML LANG](http://www.w3.org/TR/html401/struct/dirlang.html#adef-lang) attribute.
3080 // Value must be among the list of locales specified during by the Dojo bootstrap,
3081 // formatted according to [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt) (like en-us).
3084 // dir: [const] String
3085 // Bi-directional support, as defined by the [HTML DIR](http://www.w3.org/TR/html401/struct/dirlang.html#adef-dir)
3086 // attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's
3087 // default direction.
3091 // HTML class attribute
3094 // style: String||Object
3095 // HTML style attributes as cssText string or name/value hash
3099 // HTML title attribute.
3101 // For form widgets this specifies a tooltip to display when hovering over
3102 // the widget (just like the native HTML title attribute).
3104 // For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer,
3105 // etc., it's used to specify the tab label, accordion pane title, etc.
3109 // When this widget's title attribute is used to for a tab label, accordion pane title, etc.,
3110 // this specifies the tooltip to appear when the mouse is hovered over that text.
3113 // baseClass: [protected] String
3114 // Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate
3118 // srcNodeRef: [readonly] DomNode
3119 // pointer to original DOM node
3122 // domNode: [readonly] DomNode
3123 // This is our visible representation of the widget! Other DOM
3124 // Nodes may by assigned to other properties, usually through the
3125 // template system's dojoAttachPoint syntax, but the domNode
3126 // property is the canonical "top level" node in widget UI.
3129 // containerNode: [readonly] DomNode
3130 // Designates where children of the source DOM node will be placed.
3131 // "Children" in this case refers to both DOM nodes and widgets.
3132 // For example, for myWidget:
3134 // | <div dojoType=myWidget>
3135 // | <b> here's a plain DOM node
3136 // | <span dojoType=subWidget>and a widget</span>
3137 // | <i> and another plain DOM node </i>
3140 // containerNode would point to:
3142 // | <b> here's a plain DOM node
3143 // | <span dojoType=subWidget>and a widget</span>
3144 // | <i> and another plain DOM node </i>
3146 // In templated widgets, "containerNode" is set via a
3147 // dojoAttachPoint assignment.
3149 // containerNode must be defined for any widget that accepts innerHTML
3150 // (like ContentPane or BorderContainer or even Button), and conversely
3151 // is null for widgets that don't, like TextBox.
3152 containerNode
: null,
3155 // _started: Boolean
3156 // startup() has completed.
3160 // attributeMap: [protected] Object
3161 // attributeMap sets up a "binding" between attributes (aka properties)
3162 // of the widget and the widget's DOM.
3163 // Changes to widget attributes listed in attributeMap will be
3164 // reflected into the DOM.
3166 // For example, calling attr('title', 'hello')
3167 // on a TitlePane will automatically cause the TitlePane's DOM to update
3168 // with the new title.
3170 // attributeMap is a hash where the key is an attribute of the widget,
3171 // and the value reflects a binding to a:
3173 // - DOM node attribute
3174 // | focus: {node: "focusNode", type: "attribute"}
3175 // Maps this.focus to this.focusNode.focus
3177 // - DOM node innerHTML
3178 // | title: { node: "titleNode", type: "innerHTML" }
3179 // Maps this.title to this.titleNode.innerHTML
3181 // - DOM node innerText
3182 // | title: { node: "titleNode", type: "innerText" }
3183 // Maps this.title to this.titleNode.innerText
3185 // - DOM node CSS class
3186 // | myClass: { node: "domNode", type: "class" }
3187 // Maps this.myClass to this.domNode.className
3189 // If the value is an array, then each element in the array matches one of the
3190 // formats of the above list.
3192 // There are also some shorthands for backwards compatibility:
3193 // - string --> { node: string, type: "attribute" }, for example:
3194 // | "focusNode" ---> { node: "focusNode", type: "attribute" }
3195 // - "" --> { node: "domNode", type: "attribute" }
3196 attributeMap
: {id
:"", dir
:"", lang
:"", "class":"", style
:"", title
:""},
3198 // _deferredConnects: [protected] Object
3199 // attributeMap addendum for event handlers that should be connected only on first use
3200 _deferredConnects
: {
3215 onClick
: dijit
._connectOnUseEventHandler
,
3217 onClick: function(event){
3219 // Connect to this function to receive notifications of mouse click events.
3226 onDblClick
: dijit
._connectOnUseEventHandler
,
3228 onDblClick: function(event){
3230 // Connect to this function to receive notifications of mouse double click events.
3237 onKeyDown
: dijit
._connectOnUseEventHandler
,
3239 onKeyDown: function(event){
3241 // Connect to this function to receive notifications of keys being pressed down.
3248 onKeyPress
: dijit
._connectOnUseEventHandler
,
3250 onKeyPress: function(event){
3252 // Connect to this function to receive notifications of printable keys being typed.
3259 onKeyUp
: dijit
._connectOnUseEventHandler
,
3261 onKeyUp: function(event){
3263 // Connect to this function to receive notifications of keys being released.
3270 onMouseDown
: dijit
._connectOnUseEventHandler
,
3272 onMouseDown: function(event){
3274 // Connect to this function to receive notifications of when the mouse button is pressed down.
3281 onMouseMove
: dijit
._connectOnUseEventHandler
,
3283 onMouseMove: function(event){
3285 // Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget.
3292 onMouseOut
: dijit
._connectOnUseEventHandler
,
3294 onMouseOut: function(event){
3296 // Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget.
3303 onMouseOver
: dijit
._connectOnUseEventHandler
,
3305 onMouseOver: function(event){
3307 // Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget.
3314 onMouseLeave
: dijit
._connectOnUseEventHandler
,
3316 onMouseLeave: function(event){
3318 // Connect to this function to receive notifications of when the mouse moves off of this widget.
3325 onMouseEnter
: dijit
._connectOnUseEventHandler
,
3327 onMouseEnter: function(event){
3329 // Connect to this function to receive notifications of when the mouse moves onto this widget.
3336 onMouseUp
: dijit
._connectOnUseEventHandler
,
3338 onMouseUp: function(event){
3340 // Connect to this function to receive notifications of when the mouse button is released.
3348 // Constants used in templates
3350 // _blankGif: [protected] String
3351 // Path to a blank 1x1 image.
3352 // Used by <img> nodes in templates that really get their image via CSS background-image.
3353 _blankGif
: (dojo
.config
.blankGif
|| dojo
.moduleUrl("dojo", "resources/blank.gif")).toString(),
3355 //////////// INITIALIZATION METHODS ///////////////////////////////////////
3357 postscript: function(/*Object?*/params
, /*DomNode|String*/srcNodeRef
){
3359 // Kicks off widget instantiation. See create() for details.
3362 this.create(params
, srcNodeRef
);
3365 create: function(/*Object?*/params
, /*DomNode|String?*/srcNodeRef
){
3367 // Kick off the life-cycle of a widget
3369 // Hash of initialization parameters for widget, including
3370 // scalar values (like title, duration etc.) and functions,
3371 // typically callbacks like onClick.
3373 // If a srcNodeRef (DOM node) is specified:
3374 // - use srcNodeRef.innerHTML as my contents
3375 // - if this is a behavioral widget then apply behavior
3376 // to that srcNodeRef
3377 // - otherwise, replace srcNodeRef with my generated DOM
3380 // Create calls a number of widget methods (postMixInProperties, buildRendering, postCreate,
3381 // etc.), some of which of you'll want to override. See http://docs.dojocampus.org/dijit/_Widget
3382 // for a discussion of the widget creation lifecycle.
3384 // Of course, adventurous developers could override create entirely, but this should
3385 // only be done as a last resort.
3389 // store pointer to original DOM tree
3390 this.srcNodeRef
= dojo
.byId(srcNodeRef
);
3392 // For garbage collection. An array of handles returned by Widget.connect()
3393 // Each handle returned from Widget.connect() is an array of handles from dojo.connect()
3394 this._connects
= [];
3396 // For garbage collection. An array of handles returned by Widget.subscribe()
3397 // The handle returned from Widget.subscribe() is the handle returned from dojo.subscribe()
3398 this._subscribes
= [];
3400 // To avoid double-connects, remove entries from _deferredConnects
3401 // that have been setup manually by a subclass (ex, by dojoAttachEvent).
3402 // If a subclass has redefined a callback (ex: onClick) then assume it's being
3403 // connected to manually.
3404 this._deferredConnects
= dojo
.clone(this._deferredConnects
);
3405 for(var attr
in this.attributeMap
){
3406 delete this._deferredConnects
[attr
]; // can't be in both attributeMap and _deferredConnects
3408 for(attr
in this._deferredConnects
){
3409 if(this[attr
] !== dijit
._connectOnUseEventHandler
){
3410 delete this._deferredConnects
[attr
]; // redefined, probably dojoAttachEvent exists
3414 //mixin our passed parameters
3415 if(this.srcNodeRef
&& (typeof this.srcNodeRef
.id
== "string")){ this.id
= this.srcNodeRef
.id
; }
3417 this.params
= params
;
3418 dojo
.mixin(this,params
);
3420 this.postMixInProperties();
3422 // generate an id for the widget if one wasn't specified
3423 // (be sure to do this before buildRendering() because that function might
3424 // expect the id to be there.)
3426 this.id
= dijit
.getUniqueId(this.declaredClass
.replace(/\./g,"_"));
3428 dijit
.registry
.add(this);
3430 this.buildRendering();
3433 // Copy attributes listed in attributeMap into the [newly created] DOM for the widget.
3434 this._applyAttributes();
3436 var source
= this.srcNodeRef
;
3437 if(source
&& source
.parentNode
){
3438 source
.parentNode
.replaceChild(this.domNode
, source
);
3441 // If the developer has specified a handler as a widget parameter
3442 // (ex: new Button({onClick: ...})
3443 // then naturally need to connect from DOM node to that handler immediately,
3444 for(attr
in this.params
){
3445 this._onConnect(attr
);
3450 this.domNode
.setAttribute("widgetId", this.id
);
3454 // If srcNodeRef has been processed and removed from the DOM (e.g. TemplatedWidget) then delete it to allow GC.
3455 if(this.srcNodeRef
&& !this.srcNodeRef
.parentNode
){
3456 delete this.srcNodeRef
;
3459 this._created
= true;
3462 _applyAttributes: function(){
3464 // Step during widget creation to copy all widget attributes to the
3465 // DOM as per attributeMap and _setXXXAttr functions.
3467 // Skips over blank/false attribute values, unless they were explicitly specified
3468 // as parameters to the widget, since those are the default anyway,
3469 // and setting tabIndex="" is different than not setting tabIndex at all.
3471 // It processes the attributes in the attribute map first, and then
3472 // it goes through and processes the attributes for the _setXXXAttr
3473 // functions that have been specified
3476 var condAttrApply = function(attr
, scope
){
3477 if((scope
.params
&& attr
in scope
.params
) || scope
[attr
]){
3478 scope
.set(attr
, scope
[attr
]);
3482 // Do the attributes in attributeMap
3483 for(var attr
in this.attributeMap
){
3484 condAttrApply(attr
, this);
3487 // And also any attributes with custom setters
3488 dojo
.forEach(getSetterAttributes(this), function(a
){
3489 if(!(a
in this.attributeMap
)){
3490 condAttrApply(a
, this);
3495 postMixInProperties: function(){
3497 // Called after the parameters to the widget have been read-in,
3498 // but before the widget template is instantiated. Especially
3499 // useful to set properties that are referenced in the widget
3505 buildRendering: function(){
3507 // Construct the UI for this widget, setting this.domNode
3509 // Most widgets will mixin `dijit._Templated`, which implements this
3513 this.domNode
= this.srcNodeRef
|| dojo
.create('div');
3516 postCreate: function(){
3518 // Processing after the DOM fragment is created
3520 // Called after the DOM fragment has been created, but not necessarily
3521 // added to the document. Do not include any operations which rely on
3522 // node dimensions or placement.
3526 // baseClass is a single class name or occasionally a space-separated list of names.
3527 // Add those classes to the DOMNod. If RTL mode then also add with Rtl suffix.
3529 var classes
= this.baseClass
.split(" ");
3530 if(!this.isLeftToRight()){
3531 classes
= classes
.concat( dojo
.map(classes
, function(name
){ return name
+"Rtl"; }));
3533 dojo
.addClass(this.domNode
, classes
);
3537 startup: function(){
3539 // Processing after the DOM fragment is added to the document
3541 // Called after a widget and its children have been created and added to the page,
3542 // and all related widgets have finished their create() cycle, up through postCreate().
3543 // This is useful for composite widgets that need to control or layout sub-widgets.
3544 // Many layout widgets can use this as a wiring phase.
3545 this._started
= true;
3548 //////////// DESTROY FUNCTIONS ////////////////////////////////
3550 destroyRecursive: function(/*Boolean?*/ preserveDom
){
3552 // Destroy this widget and its descendants
3554 // This is the generic "destructor" function that all widget users
3555 // should call to cleanly discard with a widget. Once a widget is
3556 // destroyed, it is removed from the manager object.
3558 // If true, this method will leave the original DOM structure
3559 // alone of descendant Widgets. Note: This will NOT work with
3560 // dijit._Templated widgets.
3562 this._beingDestroyed
= true;
3563 this.destroyDescendants(preserveDom
);
3564 this.destroy(preserveDom
);
3567 destroy: function(/*Boolean*/ preserveDom
){
3569 // Destroy this widget, but not its descendants.
3570 // This method will, however, destroy internal widgets such as those used within a template.
3571 // preserveDom: Boolean
3572 // If true, this method will leave the original DOM structure alone.
3573 // Note: This will not yet work with _Templated widgets
3575 this._beingDestroyed
= true;
3576 this.uninitialize();
3579 dun
= d
.unsubscribe
;
3580 dfe(this._connects
, function(array
){
3581 dfe(array
, d
.disconnect
);
3583 dfe(this._subscribes
, function(handle
){
3587 // destroy widgets created as part of template, etc.
3588 dfe(this._supportingWidgets
|| [], function(w
){
3589 if(w
.destroyRecursive
){
3590 w
.destroyRecursive();
3591 }else if(w
.destroy
){
3596 this.destroyRendering(preserveDom
);
3597 dijit
.registry
.remove(this.id
);
3598 this._destroyed
= true;
3601 destroyRendering: function(/*Boolean?*/ preserveDom
){
3603 // Destroys the DOM nodes associated with this widget
3605 // If true, this method will leave the original DOM structure alone
3606 // during tear-down. Note: this will not work with _Templated
3612 this.bgIframe
.destroy(preserveDom
);
3613 delete this.bgIframe
;
3618 dojo
.removeAttr(this.domNode
, "widgetId");
3620 dojo
.destroy(this.domNode
);
3622 delete this.domNode
;
3625 if(this.srcNodeRef
){
3627 dojo
.destroy(this.srcNodeRef
);
3629 delete this.srcNodeRef
;
3633 destroyDescendants: function(/*Boolean?*/ preserveDom
){
3635 // Recursively destroy the children of this widget and their
3638 // If true, the preserveDom attribute is passed to all descendant
3639 // widget's .destroy() method. Not for use with _Templated
3642 // get all direct descendants and destroy them recursively
3643 dojo
.forEach(this.getChildren(), function(widget
){
3644 if(widget
.destroyRecursive
){
3645 widget
.destroyRecursive(preserveDom
);
3651 uninitialize: function(){
3653 // Stub function. Override to implement custom widget tear-down
3660 ////////////////// MISCELLANEOUS METHODS ///////////////////
3662 onFocus: function(){
3664 // Called when the widget becomes "active" because
3665 // it or a widget inside of it either has focus, or has recently
3673 // Called when the widget stops being "active" because
3674 // focus moved to something outside of it, or the user
3675 // clicked somewhere outside of it, or the widget was
3681 _onFocus: function(e
){
3683 // This is where widgets do processing for when they are active,
3684 // such as changing CSS classes. See onFocus() for more details.
3690 _onBlur: function(){
3692 // This is where widgets do processing for when they stop being active,
3693 // such as changing CSS classes. See onBlur() for more details.
3699 _onConnect: function(/*String*/ event
){
3701 // Called when someone connects to one of my handlers.
3702 // "Turn on" that handler if it isn't active yet.
3704 // This is also called for every single initialization parameter
3705 // so need to do nothing for parameters like "id".
3708 if(event
in this._deferredConnects
){
3709 var mapNode
= this[this._deferredConnects
[event
] || 'domNode'];
3710 this.connect(mapNode
, event
.toLowerCase(), event
);
3711 delete this._deferredConnects
[event
];
3715 _setClassAttr: function(/*String*/ value
){
3717 // Custom setter for the CSS "class" attribute
3720 var mapNode
= this[this.attributeMap
["class"] || 'domNode'];
3721 dojo
.removeClass(mapNode
, this["class"])
3722 this["class"] = value
;
3723 dojo
.addClass(mapNode
, value
);
3726 _setStyleAttr: function(/*String||Object*/ value
){
3728 // Sets the style attribut of the widget according to value,
3729 // which is either a hash like {height: "5px", width: "3px"}
3730 // or a plain string
3732 // Determines which node to set the style on based on style setting
3737 var mapNode
= this[this.attributeMap
.style
|| 'domNode'];
3739 // Note: technically we should revert any style setting made in a previous call
3740 // to his method, but that's difficult to keep track of.
3742 if(dojo
.isObject(value
)){
3743 dojo
.style(mapNode
, value
);
3745 if(mapNode
.style
.cssText
){
3746 mapNode
.style
.cssText
+= "; " + value
;
3748 mapNode
.style
.cssText
= value
;
3755 setAttribute: function(/*String*/ attr
, /*anything*/ value
){
3757 // Deprecated. Use set() instead.
3760 dojo
.deprecated(this.declaredClass
+"::setAttribute(attr, value) is deprecated. Use set() instead.", "", "2.0");
3761 this.set(attr
, value
);
3764 _attrToDom: function(/*String*/ attr
, /*String*/ value
){
3766 // Reflect a widget attribute (title, tabIndex, duration etc.) to
3767 // the widget DOM, as specified in attributeMap.
3770 // Also sets this["attr"] to the new value.
3771 // Note some attributes like "type"
3772 // cannot be processed this way as they are not mutable.
3777 var commands
= this.attributeMap
[attr
];
3778 dojo
.forEach(dojo
.isArray(commands
) ? commands
: [commands
], function(command
){
3780 // Get target node and what we are doing to that node
3781 var mapNode
= this[command
.node
|| command
|| "domNode"]; // DOM node
3782 var type
= command
.type
|| "attribute"; // class, innerHTML, innerText, or attribute
3786 if(dojo
.isFunction(value
)){ // functions execute in the context of the widget
3787 value
= dojo
.hitch(this, value
);
3790 // Get the name of the DOM node attribute; usually it's the same
3791 // as the name of the attribute in the widget (attr), but can be overridden.
3792 // Also maps handler names to lowercase, like onSubmit --> onsubmit
3793 var attrName
= command
.attribute
? command
.attribute
:
3794 (/^on[A-Z][a-zA-Z]*$/.test(attr
) ? attr
.toLowerCase() : attr
);
3796 dojo
.attr(mapNode
, attrName
, value
);
3799 mapNode
.innerHTML
= "";
3800 mapNode
.appendChild(dojo
.doc
.createTextNode(value
));
3803 mapNode
.innerHTML
= value
;
3806 dojo
.removeClass(mapNode
, this[attr
]);
3807 dojo
.addClass(mapNode
, value
);
3814 attr: function(/*String|Object*/name
, /*Object?*/value
){
3816 // Set or get properties on a widget instance.
3818 // The property to get or set. If an object is passed here and not
3819 // a string, its keys are used as names of attributes to be set
3820 // and the value of the object as values to set in the widget.
3822 // Optional. If provided, attr() operates as a setter. If omitted,
3823 // the current value of the named property is returned.
3825 // This method is deprecated, use get() or set() directly.
3827 // Print deprecation warning but only once per calling function
3828 if(dojo
.config
.isDebug
){
3829 var alreadyCalledHash
= arguments
.callee
._ach
|| (arguments
.callee
._ach
= {}),
3830 caller
= (arguments
.callee
.caller
|| "unknown caller").toString();
3831 if(!alreadyCalledHash
[caller
]){
3832 dojo
.deprecated(this.declaredClass
+ "::attr() is deprecated. Use get() or set() instead, called from " +
3834 alreadyCalledHash
[caller
] = true;
3838 var args
= arguments
.length
;
3839 if(args
>= 2 || typeof name
=== "object"){ // setter
3840 return this.set.apply(this, arguments
);
3842 return this.get(name
);
3846 get: function(name
){
3848 // Get a property from a widget.
3850 // The property to get.
3852 // Get a named property from a widget. The property may
3853 // potentially be retrieved via a getter method. If no getter is defined, this
3854 // just retrieves the object's property.
3855 // For example, if the widget has a properties "foo"
3856 // and "bar" and a method named "_getFooAttr", calling:
3857 // | myWidget.get("foo");
3858 // would be equivalent to writing:
3859 // | widget._getFooAttr();
3861 // | myWidget.get("bar");
3862 // would be equivalent to writing:
3864 var names
= this._getAttrNames(name
);
3865 return this[names
.g
] ? this[names
.g
]() : this[name
];
3868 set: function(name
, value
){
3870 // Set a property on a widget
3872 // The property to set.
3874 // The value to set in the property.
3876 // Sets named properties on a widget which may potentially be handled by a
3877 // setter in the widget.
3878 // For example, if the widget has a properties "foo"
3879 // and "bar" and a method named "_setFooAttr", calling:
3880 // | myWidget.set("foo", "Howdy!");
3881 // would be equivalent to writing:
3882 // | widget._setFooAttr("Howdy!");
3884 // | myWidget.set("bar", 3);
3885 // would be equivalent to writing:
3886 // | widget.bar = 3;
3888 // set() may also be called with a hash of name/value pairs, ex:
3893 // This is equivalent to calling set(foo, "Howdy") and set(bar, 3)
3895 if(typeof name
=== "object"){
3897 this.set(x
, name
[x
]);
3901 var names
= this._getAttrNames(name
);
3903 // use the explicit setter
3904 var result
= this[names
.s
].apply(this, Array
.prototype.slice
.call(arguments
, 1));
3906 // if param is specified as DOM node attribute, copy it
3907 if(name
in this.attributeMap
){
3908 this._attrToDom(name
, value
);
3910 var oldValue
= this[name
];
3911 // FIXME: what about function assignments? Any way to connect() here?
3914 return result
|| this;
3917 _attrPairNames
: {}, // shared between all widgets
3918 _getAttrNames: function(name
){
3920 // Helper function for get() and set().
3921 // Caches attribute name values so we don't do the string ops every time.
3925 var apn
= this._attrPairNames
;
3926 if(apn
[name
]){ return apn
[name
]; }
3927 var uc
= name
.charAt(0).toUpperCase() + name
.substr(1);
3928 return (apn
[name
] = {
3930 s
: "_set"+uc
+"Attr",
3935 toString: function(){
3937 // Returns a string that represents the widget
3939 // When a widget is cast to a string, this method will be used to generate the
3940 // output. Currently, it does not implement any sort of reversible
3942 return '[Widget ' + this.declaredClass
+ ', ' + (this.id
|| 'NO ID') + ']'; // String
3945 getDescendants: function(){
3947 // Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode.
3948 // This method should generally be avoided as it returns widgets declared in templates, which are
3949 // supposed to be internal/hidden, but it's left here for back-compat reasons.
3951 return this.containerNode
? dojo
.query('[widgetId]', this.containerNode
).map(dijit
.byNode
) : []; // dijit._Widget[]
3954 getChildren: function(){
3956 // Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode.
3957 // Does not return nested widgets, nor widgets that are part of this widget's template.
3958 return this.containerNode
? dijit
.findWidgets(this.containerNode
) : []; // dijit._Widget[]
3961 // nodesWithKeyClick: [private] String[]
3962 // List of nodes that correctly handle click events via native browser support,
3963 // and don't need dijit's help
3964 nodesWithKeyClick
: ["input", "button"],
3967 /*Object|null*/ obj
,
3968 /*String|Function*/ event
,
3969 /*String|Function*/ method
){
3971 // Connects specified obj/event to specified method of this object
3972 // and registers for disconnect() on widget destroy.
3974 // Provide widget-specific analog to dojo.connect, except with the
3975 // implicit use of this widget as the target object.
3976 // This version of connect also provides a special "ondijitclick"
3977 // event which triggers on a click or space or enter keyup
3979 // A handle that can be passed to `disconnect` in order to disconnect before
3980 // the widget is destroyed.
3982 // | var btn = new dijit.form.Button();
3983 // | // when foo.bar() is called, call the listener we're going to
3984 // | // provide in the scope of btn
3985 // | btn.connect(foo, "bar", function(){
3986 // | console.debug(this.toString());
3994 if(event
== "ondijitclick"){
3995 // add key based click activation for unsupported nodes.
3996 // do all processing onkey up to prevent spurious clicks
3997 // for details see comments at top of this file where _lastKeyDownNode is defined
3998 if(dojo
.indexOf(this.nodesWithKeyClick
, obj
.nodeName
.toLowerCase()) == -1){ // is NOT input or button
3999 var m
= d
.hitch(this, method
);
4001 dc(obj
, "onkeydown", this, function(e
){
4002 //console.log(this.id + ": onkeydown, e.target = ", e.target, ", lastKeyDownNode was ", dijit._lastKeyDownNode, ", equality is ", (e.target === dijit._lastKeyDownNode));
4003 if((e
.keyCode
== d
.keys
.ENTER
|| e
.keyCode
== d
.keys
.SPACE
) &&
4004 !e
.ctrlKey
&& !e
.shiftKey
&& !e
.altKey
&& !e
.metaKey
){
4005 // needed on IE for when focus changes between keydown and keyup - otherwise dropdown menus do not work
4006 dijit
._lastKeyDownNode
= e
.target
;
4007 e
.preventDefault(); // stop event to prevent scrolling on space key in IE
4010 dc(obj
, "onkeyup", this, function(e
){
4011 //console.log(this.id + ": onkeyup, e.target = ", e.target, ", lastKeyDownNode was ", dijit._lastKeyDownNode, ", equality is ", (e.target === dijit._lastKeyDownNode));
4012 if( (e
.keyCode
== d
.keys
.ENTER
|| e
.keyCode
== d
.keys
.SPACE
) &&
4013 e
.target
=== dijit
._lastKeyDownNode
&&
4014 !e
.ctrlKey
&& !e
.shiftKey
&& !e
.altKey
&& !e
.metaKey
){
4015 //need reset here or have problems in FF when focus returns to trigger element after closing popup/alert
4016 dijit
._lastKeyDownNode
= null;
4024 handles
.push(dc(obj
, event
, this, method
));
4026 this._connects
.push(handles
);
4027 return handles
; // _Widget.Handle
4030 disconnect: function(/* _Widget.Handle */ handles
){
4032 // Disconnects handle created by `connect`.
4033 // Also removes handle from this widget's list of connects.
4036 for(var i
=0; i
<this._connects
.length
; i
++){
4037 if(this._connects
[i
] == handles
){
4038 dojo
.forEach(handles
, dojo
.disconnect
);
4039 this._connects
.splice(i
, 1);
4045 subscribe: function(
4047 /*String|Function*/ method
){
4049 // Subscribes to the specified topic and calls the specified method
4050 // of this object and registers for unsubscribe() on widget destroy.
4052 // Provide widget-specific analog to dojo.subscribe, except with the
4053 // implicit use of this widget as the target object.
4055 // | var btn = new dijit.form.Button();
4056 // | // when /my/topic is published, this button changes its label to
4057 // | // be the parameter of the topic.
4058 // | btn.subscribe("/my/topic", function(v){
4059 // | this.set("label", v);
4062 handle
= d
.subscribe(topic
, this, method
);
4064 // return handles for Any widget that may need them
4065 this._subscribes
.push(handle
);
4069 unsubscribe: function(/*Object*/ handle
){
4071 // Unsubscribes handle created by this.subscribe.
4072 // Also removes handle from this widget's list of subscriptions
4073 for(var i
=0; i
<this._subscribes
.length
; i
++){
4074 if(this._subscribes
[i
] == handle
){
4075 dojo
.unsubscribe(handle
);
4076 this._subscribes
.splice(i
, 1);
4082 isLeftToRight: function(){
4084 // Return this widget's explicit or implicit orientation (true for LTR, false for RTL)
4087 return this.dir
? (this.dir
== "ltr") : dojo
._isBodyLtr(); //Boolean
4090 isFocusable: function(){
4092 // Return true if this widget can currently be focused
4094 return this.focus
&& (dojo
.style(this.domNode
, "display") != "none");
4097 placeAt: function(/* String|DomNode|_Widget */reference
, /* String?|Int? */position
){
4099 // Place this widget's domNode reference somewhere in the DOM based
4100 // on standard dojo.place conventions, or passing a Widget reference that
4101 // contains and addChild member.
4104 // A convenience function provided in all _Widgets, providing a simple
4105 // shorthand mechanism to put an existing (or newly created) Widget
4106 // somewhere in the dom, and allow chaining.
4109 // The String id of a domNode, a domNode reference, or a reference to a Widget posessing
4110 // an addChild method.
4113 // If passed a string or domNode reference, the position argument
4114 // accepts a string just as dojo.place does, one of: "first", "last",
4115 // "before", or "after".
4117 // If passed a _Widget reference, and that widget reference has an ".addChild" method,
4118 // it will be called passing this widget instance into that method, supplying the optional
4119 // position index passed.
4123 // Provides a useful return of the newly created dijit._Widget instance so you
4124 // can "chain" this function by instantiating, placing, then saving the return value
4128 // | // create a Button with no srcNodeRef, and place it in the body:
4129 // | var button = new dijit.form.Button({ label:"click" }).placeAt(dojo.body());
4130 // | // now, 'button' is still the widget reference to the newly created button
4131 // | dojo.connect(button, "onClick", function(e){ console.log('click'); });
4134 // | // create a button out of a node with id="src" and append it to id="wrapper":
4135 // | var button = new dijit.form.Button({},"src").placeAt("wrapper");
4138 // | // place a new button as the first element of some div
4139 // | var button = new dijit.form.Button({ label:"click" }).placeAt("wrapper","first");
4142 // | // create a contentpane and add it to a TabContainer
4143 // | var tc = dijit.byId("myTabs");
4144 // | new dijit.layout.ContentPane({ href:"foo.html", title:"Wow!" }).placeAt(tc)
4146 if(reference
.declaredClass
&& reference
.addChild
){
4147 reference
.addChild(this, position
);
4149 dojo
.place(this.domNode
, reference
, position
);
4154 _onShow: function(){
4156 // Internal method called when this widget is made visible.
4157 // See `onShow` for details.
4163 // Called when this widget becomes the selected pane in a
4164 // `dijit.layout.TabContainer`, `dijit.layout.StackContainer`,
4165 // `dijit.layout.AccordionContainer`, etc.
4167 // Also called to indicate display of a `dijit.Dialog`, `dijit.TooltipDialog`, or `dijit.TitlePane`.
4174 // Called when another widget becomes the selected pane in a
4175 // `dijit.layout.TabContainer`, `dijit.layout.StackContainer`,
4176 // `dijit.layout.AccordionContainer`, etc.
4178 // Also called to indicate hide of a `dijit.Dialog`, `dijit.TooltipDialog`, or `dijit.TitlePane`.
4183 onClose: function(){
4185 // Called when this widget is being displayed as a popup (ex: a Calendar popped
4186 // up from a DateTextBox), and it is hidden.
4187 // This is called from the dijit.popup code, and should not be called directly.
4189 // Also used as a parameter for children of `dijit.layout.StackContainer` or subclasses.
4190 // Callback if a user tries to close the child. Child will be closed if this function returns true.
4194 return true; // Boolean
4202 if(!dojo
._hasResource
["dojo.string"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
4203 dojo
._hasResource
["dojo.string"] = true;
4204 dojo
.provide("dojo.string");
4208 // summary: String utilities for Dojo
4212 dojo
.string
.rep = function(/*String*/str
, /*Integer*/num
){
4214 // Efficiently replicate a string `n` times.
4216 // the string to replicate
4218 // number of times to replicate the string
4220 if(num
<= 0 || !str
){ return ""; }
4227 if(!(num
>>= 1)){ break; }
4230 return buf
.join(""); // String
4233 dojo
.string
.pad = function(/*String*/text
, /*Integer*/size
, /*String?*/ch
, /*Boolean?*/end
){
4235 // Pad a string to guarantee that it is at least `size` length by
4236 // filling with the character `ch` at either the start or end of the
4237 // string. Pads at the start, by default.
4239 // the string to pad
4241 // length to provide padding
4243 // character to pad, defaults to '0'
4245 // adds padding at the end if true, otherwise pads at start
4247 // | // Fill the string to length 10 with "+" characters on the right. Yields "Dojo++++++".
4248 // | dojo.string.pad("Dojo", 10, "+", true);
4253 var out
= String(text
),
4254 pad
= dojo
.string
.rep(ch
, Math
.ceil((size
- out
.length
) / ch
.length
));
4255 return end
? out
+ pad
: pad
+ out
; // String
4258 dojo
.string
.substitute = function( /*String*/ template
,
4259 /*Object|Array*/map
,
4260 /*Function?*/ transform
,
4261 /*Object?*/ thisObject
){
4263 // Performs parameterized substitutions on a string. Throws an
4264 // exception if any parameter is unmatched.
4266 // a string with expressions in the form `${key}` to be replaced or
4267 // `${key:format}` which specifies a format function. keys are case-sensitive.
4269 // hash to search for substitutions
4271 // a function to process all parameters before substitution takes
4272 // place, e.g. mylib.encodeXML
4274 // where to look for optional format function; default to the global
4277 // Substitutes two expressions in a string from an Array or Object
4278 // | // returns "File 'foo.html' is not found in directory '/temp'."
4279 // | // by providing substitution data in an Array
4280 // | dojo.string.substitute(
4281 // | "File '${0}' is not found in directory '${1}'.",
4282 // | ["foo.html","/temp"]
4285 // | // also returns "File 'foo.html' is not found in directory '/temp'."
4286 // | // but provides substitution data in an Object structure. Dotted
4287 // | // notation may be used to traverse the structure.
4288 // | dojo.string.substitute(
4289 // | "File '${name}' is not found in directory '${info.dir}'.",
4290 // | { name: "foo.html", info: { dir: "/temp" } }
4293 // Use a transform function to modify the values:
4294 // | // returns "file 'foo.html' is not found in directory '/temp'."
4295 // | dojo.string.substitute(
4296 // | "${0} is not found in ${1}.",
4297 // | ["foo.html","/temp"],
4299 // | // try to figure out the type
4300 // | var prefix = (str.charAt(0) == "/") ? "directory": "file";
4301 // | return prefix + " '" + str + "'";
4306 // | // returns "thinger -- howdy"
4307 // | dojo.string.substitute(
4308 // | "${0:postfix}", ["thinger"], null, {
4309 // | postfix: function(value, key){
4310 // | return value + " -- howdy";
4315 thisObject
= thisObject
|| dojo
.global
;
4316 transform
= transform
?
4317 dojo
.hitch(thisObject
, transform
) : function(v
){ return v
; };
4319 return template
.replace(/\$\{([^\s\:\}]+)(?:\:([^\s\:\}]+))?\}/g,
4320 function(match
, key
, format
){
4321 var value
= dojo
.getObject(key
, false, map
);
4323 value
= dojo
.getObject(format
, false, thisObject
).call(thisObject
, value
, key
);
4325 return transform(value
, key
).toString();
4330 dojo.string.trim = function(str){
4332 // Trims whitespace from both sides of the string
4334 // String to be trimmed
4336 // Returns the trimmed string
4338 // This version of trim() was taken from [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript).
4339 // The short yet performant version of this function is dojo.trim(),
4340 // which is part of Dojo base. Uses String.prototype.trim instead, if available.
4341 return ""; // String
4345 dojo
.string
.trim
= String
.prototype.trim
?
4346 dojo
.trim
: // aliasing to the native function
4348 str
= str
.replace(/^\s+/, '');
4349 for(var i
= str
.length
- 1; i
>= 0; i
--){
4350 if(/\S/.test(str
.charAt(i
))){
4351 str
= str
.substring(0, i
+ 1);
4360 if(!dojo
._hasResource
["dojo.cache"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
4361 dojo
._hasResource
["dojo.cache"] = true;
4362 dojo
.provide("dojo.cache");
4367 // A way to cache string content that is fetchable via `dojo.moduleUrl`.
4373 dojo
.cache = function(/*String||Object*/module
, /*String*/url
, /*String||Object?*/value
){
4375 // A getter and setter for storing the string content associated with the
4376 // module and url arguments.
4378 // module and url are used to call `dojo.moduleUrl()` to generate a module URL.
4379 // If value is specified, the cache value for the moduleUrl will be set to
4380 // that value. Otherwise, dojo.cache will fetch the moduleUrl and store it
4381 // in its internal cache and return that cached value for the URL. To clear
4382 // a cache value pass null for value. Since XMLHttpRequest (XHR) is used to fetch the
4383 // the URL contents, only modules on the same domain of the page can use this capability.
4384 // The build system can inline the cache values though, to allow for xdomain hosting.
4385 // module: String||Object
4386 // If a String, the module name to use for the base part of the URL, similar to module argument
4387 // to `dojo.moduleUrl`. If an Object, something that has a .toString() method that
4388 // generates a valid path for the cache item. For example, a dojo._Url object.
4390 // The rest of the path to append to the path derived from the module argument. If
4391 // module is an object, then this second argument should be the "value" argument instead.
4392 // value: String||Object?
4393 // If a String, the value to use in the cache for the module/url combination.
4394 // If an Object, it can have two properties: value and sanitize. The value property
4395 // should be the value to use in the cache, and sanitize can be set to true or false,
4396 // to indicate if XML declarations should be removed from the value and if the HTML
4397 // inside a body tag in the value should be extracted as the real value. The value argument
4398 // or the value property on the value argument are usually only used by the build system
4399 // as it inlines cache content.
4401 // To ask dojo.cache to fetch content and store it in the cache (the dojo["cache"] style
4402 // of call is used to avoid an issue with the build system erroneously trying to intern
4403 // this example. To get the build system to intern your dojo.cache calls, use the
4404 // "dojo.cache" style of call):
4405 // | //If template.html contains "<h1>Hello</h1>" that will be
4406 // | //the value for the text variable.
4407 // | var text = dojo["cache"]("my.module", "template.html");
4409 // To ask dojo.cache to fetch content and store it in the cache, and sanitize the input
4410 // (the dojo["cache"] style of call is used to avoid an issue with the build system
4411 // erroneously trying to intern this example. To get the build system to intern your
4412 // dojo.cache calls, use the "dojo.cache" style of call):
4413 // | //If template.html contains "<html><body><h1>Hello</h1></body></html>", the
4414 // | //text variable will contain just "<h1>Hello</h1>".
4415 // | var text = dojo["cache"]("my.module", "template.html", {sanitize: true});
4417 // Same example as previous, but demostrates how an object can be passed in as
4418 // the first argument, then the value argument can then be the second argument.
4419 // | //If template.html contains "<html><body><h1>Hello</h1></body></html>", the
4420 // | //text variable will contain just "<h1>Hello</h1>".
4421 // | var text = dojo["cache"](new dojo._Url("my/module/template.html"), {sanitize: true});
4423 //Module could be a string, or an object that has a toString() method
4424 //that will return a useful path. If it is an object, then the "url" argument
4425 //will actually be the value argument.
4426 if(typeof module
== "string"){
4427 var pathObj
= dojo
.moduleUrl(module
, url
);
4432 var key
= pathObj
.toString();
4435 if(value
!= undefined && !dojo
.isString(value
)){
4436 val
= ("value" in value
? value
.value
: undefined);
4439 var sanitize
= value
&& value
.sanitize
? true : false;
4441 if(typeof val
== "string"){
4442 //We have a string, set cache value
4443 val
= cache
[key
] = sanitize
? dojo
.cache
._sanitize(val
) : val
;
4444 }else if(val
=== null){
4445 //Remove cached value
4448 //Allow cache values to be empty strings. If key property does
4449 //not exist, fetch it.
4450 if(!(key
in cache
)){
4451 val
= dojo
._getText(key
);
4452 cache
[key
] = sanitize
? dojo
.cache
._sanitize(val
) : val
;
4456 return val
; //String
4459 dojo
.cache
._sanitize = function(/*String*/val
){
4461 // Strips <?xml ...?> declarations so that external SVG and XML
4462 // documents can be added to a document without worry. Also, if the string
4463 // is an HTML document, only the part inside the body tag is returned.
4465 // Copied from dijit._Templated._sanitizeTemplateString.
4467 val
= val
.replace(/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, "");
4468 var matches
= val
.match(/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im);
4475 return val
; //String
4481 if(!dojo
._hasResource
["dijit._Templated"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
4482 dojo
._hasResource
["dijit._Templated"] = true;
4483 dojo
.provide("dijit._Templated");
4490 dojo
.declare("dijit._Templated",
4494 // Mixin for widgets that are instantiated from a template
4496 // templateString: [protected] String
4497 // A string that represents the widget template. Pre-empts the
4498 // templatePath. In builds that have their strings "interned", the
4499 // templatePath is converted to an inline templateString, thereby
4500 // preventing a synchronous network call.
4502 // Use in conjunction with dojo.cache() to load from a file.
4503 templateString
: null,
4505 // templatePath: [protected deprecated] String
4506 // Path to template (HTML file) for this widget relative to dojo.baseUrl.
4507 // Deprecated: use templateString with dojo.cache() instead.
4510 // widgetsInTemplate: [protected] Boolean
4511 // Should we parse the template to find widgets that might be
4512 // declared in markup inside it? False by default.
4513 widgetsInTemplate
: false,
4515 // skipNodeCache: [protected] Boolean
4516 // If using a cached widget template node poses issues for a
4517 // particular widget class, it can set this property to ensure
4518 // that its template is always re-built from a string
4519 _skipNodeCache
: false,
4521 // _earlyTemplatedStartup: Boolean
4522 // A fallback to preserve the 1.0 - 1.3 behavior of children in
4523 // templates having their startup called before the parent widget
4524 // fires postCreate. Defaults to 'false', causing child widgets to
4525 // have their .startup() called immediately before a parent widget
4526 // .startup(), but always after the parent .postCreate(). Set to
4527 // 'true' to re-enable to previous, arguably broken, behavior.
4528 _earlyTemplatedStartup
: false,
4530 // _attachPoints: [private] String[]
4531 // List of widget attribute names associated with dojoAttachPoint=... in the
4532 // template, ex: ["containerNode", "labelNode"]
4537 constructor: function(){
4538 this._attachPoints
= [];
4541 _stringRepl: function(tmpl
){
4543 // Does substitution of ${foo} type properties in template string
4546 var className
= this.declaredClass
, _this
= this;
4547 // Cache contains a string because we need to do property replacement
4548 // do the property replacement
4549 return dojo
.string
.substitute(tmpl
, this, function(value
, key
){
4550 if(key
.charAt(0) == '!'){ value
= dojo
.getObject(key
.substr(1), false, _this
); }
4551 if(typeof value
== "undefined"){ throw new Error(className
+" template:"+key
); } // a debugging aide
4552 if(value
== null){ return ""; }
4554 // Substitution keys beginning with ! will skip the transform step,
4555 // in case a user wishes to insert unescaped markup, e.g. ${!foo}
4556 return key
.charAt(0) == "!" ? value
:
4557 // Safer substitution, see heading "Attribute values" in
4558 // http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2
4559 value
.toString().replace(/"/g,"""); //TODO
: add
&
? use encodeXML method
?
4564 buildRendering: function(){
4566 // Construct the UI for this widget from a template, setting this.domNode.
4570 // Lookup cached version of template, and download to cache if it
4571 // isn't there already. Returns either a DomNode or a string, depending on
4572 // whether or not the template contains ${foo} replacement parameters.
4573 var cached
= dijit
._Templated
.getCachedTemplate(this.templatePath
, this.templateString
, this._skipNodeCache
);
4576 if(dojo
.isString(cached
)){
4577 node
= dojo
._toDom(this._stringRepl(cached
));
4578 if(node
.nodeType
!= 1){
4579 // Flag common problems such as templates with multiple top level nodes (nodeType == 11)
4580 throw new Error("Invalid template: " + cached
);
4583 // if it's a node, all we have to do is clone it
4584 node
= cached
.cloneNode(true);
4587 this.domNode
= node
;
4589 // recurse through the node, looking for, and attaching to, our
4590 // attachment points and events, which should be defined on the template node.
4591 this._attachTemplateNodes(node
);
4593 if(this.widgetsInTemplate
){
4594 // Make sure dojoType is used for parsing widgets in template.
4595 // The dojo.parser.query could be changed from multiversion support.
4596 var parser
= dojo
.parser
, qry
, attr
;
4597 if(parser
._query
!= "[dojoType]"){
4598 qry
= parser
._query
;
4599 attr
= parser
._attrName
;
4600 parser
._query
= "[dojoType]";
4601 parser
._attrName
= "dojoType";
4604 // Store widgets that we need to start at a later point in time
4605 var cw
= (this._startupWidgets
= dojo
.parser
.parse(node
, {
4606 noStart
: !this._earlyTemplatedStartup
,
4607 inherited
: {dir
: this.dir
, lang
: this.lang
}
4610 // Restore the query.
4612 parser
._query
= qry
;
4613 parser
._attrName
= attr
;
4616 this._supportingWidgets
= dijit
.findWidgets(node
);
4618 this._attachTemplateNodes(cw
, function(n
,p
){
4623 this._fillContent(this.srcNodeRef
);
4626 _fillContent: function(/*DomNode*/ source
){
4628 // Relocate source contents to templated container node.
4629 // this.containerNode must be able to receive children, or exceptions will be thrown.
4632 var dest
= this.containerNode
;
4634 while(source
.hasChildNodes()){
4635 dest
.appendChild(source
.firstChild
);
4640 _attachTemplateNodes: function(rootNode
, getAttrFunc
){
4642 // Iterate through the template and attach functions and nodes accordingly.
4644 // Map widget properties and functions to the handlers specified in
4645 // the dom node and it's descendants. This function iterates over all
4646 // nodes and looks for these properties:
4647 // * dojoAttachPoint
4648 // * dojoAttachEvent
4651 // rootNode: DomNode|Array[Widgets]
4652 // the node to search for properties. All children will be searched.
4653 // getAttrFunc: Function?
4654 // a function which will be used to obtain property for a given
4659 getAttrFunc
= getAttrFunc
|| function(n
,p
){ return n
.getAttribute(p
); };
4661 var nodes
= dojo
.isArray(rootNode
) ? rootNode
: (rootNode
.all
|| rootNode
.getElementsByTagName("*"));
4662 var x
= dojo
.isArray(rootNode
) ? 0 : -1;
4663 for(; x
<nodes
.length
; x
++){
4664 var baseNode
= (x
== -1) ? rootNode
: nodes
[x
];
4665 if(this.widgetsInTemplate
&& getAttrFunc(baseNode
, "dojoType")){
4668 // Process dojoAttachPoint
4669 var attachPoint
= getAttrFunc(baseNode
, "dojoAttachPoint");
4671 var point
, points
= attachPoint
.split(/\s*,\s*/);
4672 while((point
= points
.shift())){
4673 if(dojo
.isArray(this[point
])){
4674 this[point
].push(baseNode
);
4676 this[point
]=baseNode
;
4678 this._attachPoints
.push(point
);
4682 // Process dojoAttachEvent
4683 var attachEvent
= getAttrFunc(baseNode
, "dojoAttachEvent");
4685 // NOTE: we want to support attributes that have the form
4686 // "domEvent: nativeEvent; ..."
4687 var event
, events
= attachEvent
.split(/\s*,\s*/);
4688 var trim
= dojo
.trim
;
4689 while((event
= events
.shift())){
4691 var thisFunc
= null;
4692 if(event
.indexOf(":") != -1){
4693 // oh, if only JS had tuple assignment
4694 var funcNameArr
= event
.split(":");
4695 event
= trim(funcNameArr
[0]);
4696 thisFunc
= trim(funcNameArr
[1]);
4698 event
= trim(event
);
4703 this.connect(baseNode
, event
, thisFunc
);
4708 // waiRole, waiState
4709 var role
= getAttrFunc(baseNode
, "waiRole");
4711 dijit
.setWaiRole(baseNode
, role
);
4713 var values
= getAttrFunc(baseNode
, "waiState");
4715 dojo
.forEach(values
.split(/\s*,\s*/), function(stateValue
){
4716 if(stateValue
.indexOf('-') != -1){
4717 var pair
= stateValue
.split('-');
4718 dijit
.setWaiState(baseNode
, pair
[0], pair
[1]);
4725 startup: function(){
4726 dojo
.forEach(this._startupWidgets
, function(w
){
4727 if(w
&& !w
._started
&& w
.startup
){
4731 this.inherited(arguments
);
4734 destroyRendering: function(){
4735 // Delete all attach points to prevent IE6 memory leaks.
4736 dojo
.forEach(this._attachPoints
, function(point
){
4739 this._attachPoints
= [];
4741 this.inherited(arguments
);
4746 // key is either templatePath or templateString; object is either string or DOM tree
4747 dijit
._Templated
._templateCache
= {};
4749 dijit
._Templated
.getCachedTemplate = function(templatePath
, templateString
, alwaysUseString
){
4751 // Static method to get a template based on the templatePath or
4752 // templateString key
4753 // templatePath: String||dojo.uri.Uri
4754 // The URL to get the template from.
4755 // templateString: String?
4756 // a string to use in lieu of fetching the template from a URL. Takes precedence
4757 // over templatePath
4759 // Either string (if there are ${} variables that need to be replaced) or just
4760 // a DOM tree (if the node can be cloned directly)
4762 // is it already cached?
4763 var tmplts
= dijit
._Templated
._templateCache
;
4764 var key
= templateString
|| templatePath
;
4765 var cached
= tmplts
[key
];
4768 // if the cached value is an innerHTML string (no ownerDocument) or a DOM tree created within the current document, then use the current cached value
4769 if(!cached
.ownerDocument
|| cached
.ownerDocument
== dojo
.doc
){
4770 // string or node of the same document
4773 }catch(e
){ /* squelch */ } // IE can throw an exception if cached.ownerDocument was reloaded
4774 dojo
.destroy(cached
);
4777 // If necessary, load template string from template path
4778 if(!templateString
){
4779 templateString
= dojo
.cache(templatePath
, {sanitize
: true});
4781 templateString
= dojo
.string
.trim(templateString
);
4783 if(alwaysUseString
|| templateString
.match(/\$\{([^\}]+)\}/g)){
4784 // there are variables in the template so all we can do is cache the string
4785 return (tmplts
[key
] = templateString
); //String
4787 // there are no variables in the template so we can cache the DOM tree
4788 var node
= dojo
._toDom(templateString
);
4789 if(node
.nodeType
!= 1){
4790 throw new Error("Invalid template: " + templateString
);
4792 return (tmplts
[key
] = node
); //Node
4797 dojo
.addOnWindowUnload(function(){
4798 var cache
= dijit
._Templated
._templateCache
;
4799 for(var key
in cache
){
4800 var value
= cache
[key
];
4801 if(typeof value
== "object"){ // value is either a string or a DOM node template
4802 dojo
.destroy(value
);
4809 // These arguments can be specified for widgets which are used in templates.
4810 // Since any widget can be specified as sub widgets in template, mix it
4811 // into the base widget class. (This is a hack, but it's effective.)
4812 dojo
.extend(dijit
._Widget
,{
4813 dojoAttachEvent
: "",
4814 dojoAttachPoint
: "",
4821 if(!dojo
._hasResource
["dijit._Container"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
4822 dojo
._hasResource
["dijit._Container"] = true;
4823 dojo
.provide("dijit._Container");
4825 dojo
.declare("dijit._Container",
4829 // Mixin for widgets that contain a set of widget children.
4831 // Use this mixin for widgets that needs to know about and
4832 // keep track of their widget children. Suitable for widgets like BorderContainer
4833 // and TabContainer which contain (only) a set of child widgets.
4835 // It's not suitable for widgets like ContentPane
4836 // which contains mixed HTML (plain DOM nodes in addition to widgets),
4837 // and where contained widgets are not necessarily directly below
4838 // this.containerNode. In that case calls like addChild(node, position)
4839 // wouldn't make sense.
4841 // isContainer: [protected] Boolean
4842 // Indicates that this widget acts as a "parent" to the descendant widgets.
4843 // When the parent is started it will call startup() on the child widgets.
4844 // See also `isLayoutContainer`.
4847 buildRendering: function(){
4848 this.inherited(arguments
);
4849 if(!this.containerNode
){
4850 // all widgets with descendants must set containerNode
4851 this.containerNode
= this.domNode
;
4855 addChild: function(/*dijit._Widget*/ widget
, /*int?*/ insertIndex
){
4857 // Makes the given widget a child of this widget.
4859 // Inserts specified child widget's dom node as a child of this widget's
4860 // container node, and possibly does other processing (such as layout).
4862 var refNode
= this.containerNode
;
4863 if(insertIndex
&& typeof insertIndex
== "number"){
4864 var children
= this.getChildren();
4865 if(children
&& children
.length
>= insertIndex
){
4866 refNode
= children
[insertIndex
-1].domNode
;
4867 insertIndex
= "after";
4870 dojo
.place(widget
.domNode
, refNode
, insertIndex
);
4872 // If I've been started but the child widget hasn't been started,
4873 // start it now. Make sure to do this after widget has been
4874 // inserted into the DOM tree, so it can see that it's being controlled by me,
4875 // so it doesn't try to size itself.
4876 if(this._started
&& !widget
._started
){
4881 removeChild: function(/*Widget or int*/ widget
){
4883 // Removes the passed widget instance from this widget but does
4884 // not destroy it. You can also pass in an integer indicating
4885 // the index within the container to remove
4887 if(typeof widget
== "number" && widget
> 0){
4888 widget
= this.getChildren()[widget
];
4892 var node
= widget
.domNode
;
4893 if(node
&& node
.parentNode
){
4894 node
.parentNode
.removeChild(node
); // detach but don't destroy
4899 hasChildren: function(){
4901 // Returns true if widget has children, i.e. if this.containerNode contains something.
4902 return this.getChildren().length
> 0; // Boolean
4905 destroyDescendants: function(/*Boolean*/ preserveDom
){
4907 // Destroys all the widgets inside this.containerNode,
4908 // but not this widget itself
4909 dojo
.forEach(this.getChildren(), function(child
){ child
.destroyRecursive(preserveDom
); });
4912 _getSiblingOfChild: function(/*dijit._Widget*/ child
, /*int*/ dir
){
4914 // Get the next or previous widget sibling of child
4916 // if 1, get the next sibling
4917 // if -1, get the previous sibling
4920 var node
= child
.domNode
,
4921 which
= (dir
>0 ? "nextSibling" : "previousSibling");
4924 }while(node
&& (node
.nodeType
!= 1 || !dijit
.byNode(node
)));
4925 return node
&& dijit
.byNode(node
); // dijit._Widget
4928 getIndexOfChild: function(/*dijit._Widget*/ child
){
4930 // Gets the index of the child in this container or -1 if not found
4931 return dojo
.indexOf(this.getChildren(), child
); // int
4934 startup: function(){
4936 // Called after all the widgets have been instantiated and their
4937 // dom nodes have been inserted somewhere under dojo.doc.body.
4939 // Widgets should override this method to do any initialization
4940 // dependent on other widgets existing, and then call
4941 // this superclass method to finish things off.
4943 // startup() in subclasses shouldn't do anything
4944 // size related because the size of the widget hasn't been set yet.
4946 if(this._started
){ return; }
4948 // Startup all children of this widget
4949 dojo
.forEach(this.getChildren(), function(child
){ child
.startup(); });
4951 this.inherited(arguments
);
4958 if(!dojo
._hasResource
["dijit._Contained"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
4959 dojo
._hasResource
["dijit._Contained"] = true;
4960 dojo
.provide("dijit._Contained");
4962 dojo
.declare("dijit._Contained",
4966 // Mixin for widgets that are children of a container widget
4969 // | // make a basic custom widget that knows about it's parents
4970 // | dojo.declare("my.customClass",[dijit._Widget,dijit._Contained],{});
4972 getParent: function(){
4974 // Returns the parent widget of this widget, assuming the parent
4975 // specifies isContainer
4976 var parent
= dijit
.getEnclosingWidget(this.domNode
.parentNode
);
4977 return parent
&& parent
.isContainer
? parent
: null;
4980 _getSibling: function(/*String*/ which
){
4982 // Returns next or previous sibling
4984 // Either "next" or "previous"
4987 var node
= this.domNode
;
4989 node
= node
[which
+"Sibling"];
4990 }while(node
&& node
.nodeType
!= 1);
4991 return node
&& dijit
.byNode(node
); // dijit._Widget
4994 getPreviousSibling: function(){
4996 // Returns null if this is the first child of the parent,
4997 // otherwise returns the next element sibling to the "left".
4999 return this._getSibling("previous"); // dijit._Widget
5002 getNextSibling: function(){
5004 // Returns null if this is the last child of the parent,
5005 // otherwise returns the next element sibling to the "right".
5007 return this._getSibling("next"); // dijit._Widget
5010 getIndexInParent: function(){
5012 // Returns the index of this widget within its container parent.
5013 // It returns -1 if the parent does not exist, or if the parent
5014 // is not a dijit._Container
5016 var p
= this.getParent();
5017 if(!p
|| !p
.getIndexOfChild
){
5020 return p
.getIndexOfChild(this); // int
5028 if(!dojo
._hasResource
["dijit.layout._LayoutWidget"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
5029 dojo
._hasResource
["dijit.layout._LayoutWidget"] = true;
5030 dojo
.provide("dijit.layout._LayoutWidget");
5036 dojo
.declare("dijit.layout._LayoutWidget",
5037 [dijit
._Widget
, dijit
._Container
, dijit
._Contained
],
5040 // Base class for a _Container widget which is responsible for laying out its children.
5041 // Widgets which mixin this code must define layout() to manage placement and sizing of the children.
5043 // baseClass: [protected extension] String
5044 // This class name is applied to the widget's domNode
5045 // and also may be used to generate names for sub nodes,
5046 // for example dijitTabContainer-content.
5047 baseClass
: "dijitLayoutContainer",
5049 // isLayoutContainer: [protected] Boolean
5050 // Indicates that this widget is going to call resize() on its
5051 // children widgets, setting their size, when they become visible.
5052 isLayoutContainer
: true,
5054 postCreate: function(){
5055 dojo
.addClass(this.domNode
, "dijitContainer");
5057 this.inherited(arguments
);
5060 startup: function(){
5062 // Called after all the widgets have been instantiated and their
5063 // dom nodes have been inserted somewhere under dojo.doc.body.
5065 // Widgets should override this method to do any initialization
5066 // dependent on other widgets existing, and then call
5067 // this superclass method to finish things off.
5069 // startup() in subclasses shouldn't do anything
5070 // size related because the size of the widget hasn't been set yet.
5072 if(this._started
){ return; }
5074 // Need to call inherited first - so that child widgets get started
5076 this.inherited(arguments
);
5078 // If I am a not being controlled by a parent layout widget...
5079 var parent
= this.getParent
&& this.getParent()
5080 if(!(parent
&& parent
.isLayoutContainer
)){
5081 // Do recursive sizing and layout of all my descendants
5082 // (passing in no argument to resize means that it has to glean the size itself)
5085 // Since my parent isn't a layout container, and my style *may be* width=height=100%
5086 // or something similar (either set directly or via a CSS class),
5087 // monitor when my size changes so that I can re-layout.
5088 // For browsers where I can't directly monitor when my size changes,
5089 // monitor when the viewport changes size, which *may* indicate a size change for me.
5090 this.connect(dojo
.isIE
? this.domNode
: dojo
.global
, 'onresize', function(){
5091 // Using function(){} closure to ensure no arguments to resize.
5097 resize: function(changeSize
, resultSize
){
5099 // Call this to resize a widget, or after its size has changed.
5101 // Change size mode:
5102 // When changeSize is specified, changes the marginBox of this widget
5103 // and forces it to relayout its contents accordingly.
5104 // changeSize may specify height, width, or both.
5106 // If resultSize is specified it indicates the size the widget will
5107 // become after changeSize has been applied.
5109 // Notification mode:
5110 // When changeSize is null, indicates that the caller has already changed
5111 // the size of the widget, or perhaps it changed because the browser
5112 // window was resized. Tells widget to relayout its contents accordingly.
5114 // If resultSize is also specified it indicates the size the widget has
5117 // In either mode, this method also:
5118 // 1. Sets this._borderBox and this._contentBox to the new size of
5119 // the widget. Queries the current domNode size if necessary.
5120 // 2. Calls layout() to resize contents (and maybe adjust child widgets).
5122 // changeSize: Object?
5123 // Sets the widget to this margin-box size and position.
5124 // May include any/all of the following properties:
5125 // | {w: int, h: int, l: int, t: int}
5127 // resultSize: Object?
5128 // The margin-box size of this widget after applying changeSize (if
5129 // changeSize is specified). If caller knows this size and
5130 // passes it in, we don't need to query the browser to get the size.
5131 // | {w: int, h: int}
5133 var node
= this.domNode
;
5135 // set margin box size, unless it wasn't specified, in which case use current size
5137 dojo
.marginBox(node
, changeSize
);
5139 // set offset of the node
5140 if(changeSize
.t
){ node
.style
.top
= changeSize
.t
+ "px"; }
5141 if(changeSize
.l
){ node
.style
.left
= changeSize
.l
+ "px"; }
5144 // If either height or width wasn't specified by the user, then query node for it.
5145 // But note that setting the margin box and then immediately querying dimensions may return
5146 // inaccurate results, so try not to depend on it.
5147 var mb
= resultSize
|| {};
5148 dojo
.mixin(mb
, changeSize
|| {}); // changeSize overrides resultSize
5149 if( !("h" in mb
) || !("w" in mb
) ){
5150 mb
= dojo
.mixin(dojo
.marginBox(node
), mb
); // just use dojo.marginBox() to fill in missing values
5153 // Compute and save the size of my border box and content box
5154 // (w/out calling dojo.contentBox() since that may fail if size was recently set)
5155 var cs
= dojo
.getComputedStyle(node
);
5156 var me
= dojo
._getMarginExtents(node
, cs
);
5157 var be
= dojo
._getBorderExtents(node
, cs
);
5158 var bb
= (this._borderBox
= {
5159 w
: mb
.w
- (me
.w
+ be
.w
),
5160 h
: mb
.h
- (me
.h
+ be
.h
)
5162 var pe
= dojo
._getPadExtents(node
, cs
);
5163 this._contentBox
= {
5164 l
: dojo
._toPixelValue(node
, cs
.paddingLeft
),
5165 t
: dojo
._toPixelValue(node
, cs
.paddingTop
),
5170 // Callback for widget to adjust size of its children
5176 // Widgets override this method to size and position their contents/children.
5177 // When this is called this._contentBox is guaranteed to be set (see resize()).
5179 // This is called after startup(), and also when the widget's size has been
5182 // protected extension
5185 _setupChild: function(/*dijit._Widget*/child
){
5187 // Common setup for initial children and children which are added after startup
5189 // protected extension
5191 dojo
.addClass(child
.domNode
, this.baseClass
+"-child");
5192 if(child
.baseClass
){
5193 dojo
.addClass(child
.domNode
, this.baseClass
+"-"+child
.baseClass
);
5197 addChild: function(/*dijit._Widget*/ child
, /*Integer?*/ insertIndex
){
5198 // Overrides _Container.addChild() to call _setupChild()
5199 this.inherited(arguments
);
5201 this._setupChild(child
);
5205 removeChild: function(/*dijit._Widget*/ child
){
5206 // Overrides _Container.removeChild() to remove class added by _setupChild()
5207 dojo
.removeClass(child
.domNode
, this.baseClass
+"-child");
5208 if(child
.baseClass
){
5209 dojo
.removeClass(child
.domNode
, this.baseClass
+"-"+child
.baseClass
);
5211 this.inherited(arguments
);
5216 dijit
.layout
.marginBox2contentBox = function(/*DomNode*/ node
, /*Object*/ mb
){
5218 // Given the margin-box size of a node, return its content box size.
5219 // Functions like dojo.contentBox() but is more reliable since it doesn't have
5220 // to wait for the browser to compute sizes.
5221 var cs
= dojo
.getComputedStyle(node
);
5222 var me
= dojo
._getMarginExtents(node
, cs
);
5223 var pb
= dojo
._getPadBorderExtents(node
, cs
);
5225 l
: dojo
._toPixelValue(node
, cs
.paddingLeft
),
5226 t
: dojo
._toPixelValue(node
, cs
.paddingTop
),
5227 w
: mb
.w
- (me
.w
+ pb
.w
),
5228 h
: mb
.h
- (me
.h
+ pb
.h
)
5233 var capitalize = function(word
){
5234 return word
.substring(0,1).toUpperCase() + word
.substring(1);
5237 var size = function(widget
, dim
){
5239 widget
.resize
? widget
.resize(dim
) : dojo
.marginBox(widget
.domNode
, dim
);
5241 // record child's size, but favor our own numbers when we have them.
5242 // the browser lies sometimes
5243 dojo
.mixin(widget
, dojo
.marginBox(widget
.domNode
));
5244 dojo
.mixin(widget
, dim
);
5247 dijit
.layout
.layoutChildren = function(/*DomNode*/ container
, /*Object*/ dim
, /*Object[]*/ children
){
5249 // Layout a bunch of child dom nodes within a parent dom node
5253 // {l, t, w, h} object specifying dimensions of container into which to place children
5255 // an array like [ {domNode: foo, layoutAlign: "bottom" }, {domNode: bar, layoutAlign: "client"} ]
5257 // copy dim because we are going to modify it
5258 dim
= dojo
.mixin({}, dim
);
5260 dojo
.addClass(container
, "dijitLayoutContainer");
5262 // Move "client" elements to the end of the array for layout. a11y dictates that the author
5263 // needs to be able to put them in the document in tab-order, but this algorithm requires that
5265 children
= dojo
.filter(children
, function(item
){ return item
.layoutAlign
!= "client"; })
5266 .concat(dojo
.filter(children
, function(item
){ return item
.layoutAlign
== "client"; }));
5268 // set positions/sizes
5269 dojo
.forEach(children
, function(child
){
5270 var elm
= child
.domNode
,
5271 pos
= child
.layoutAlign
;
5273 // set elem to upper left corner of unused space; may move it later
5274 var elmStyle
= elm
.style
;
5275 elmStyle
.left
= dim
.l
+"px";
5276 elmStyle
.top
= dim
.t
+"px";
5277 elmStyle
.bottom
= elmStyle
.right
= "auto";
5279 dojo
.addClass(elm
, "dijitAlign" + capitalize(pos
));
5281 // set size && adjust record of remaining space.
5282 // note that setting the width of a <div> may affect its height.
5283 if(pos
== "top" || pos
== "bottom"){
5284 size(child
, { w
: dim
.w
});
5289 elmStyle
.top
= dim
.t
+ dim
.h
+ "px";
5291 }else if(pos
== "left" || pos
== "right"){
5292 size(child
, { h
: dim
.h
});
5297 elmStyle
.left
= dim
.l
+ dim
.w
+ "px";
5299 }else if(pos
== "client"){
5309 if(!dojo
._hasResource
["dijit._CssStateMixin"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
5310 dojo
._hasResource
["dijit._CssStateMixin"] = true;
5311 dojo
.provide("dijit._CssStateMixin");
5314 dojo
.declare("dijit._CssStateMixin", [], {
5316 // Mixin for widgets to set CSS classes on the widget DOM nodes depending on hover/mouse press/focus
5317 // state changes, and also higher-level state changes such becoming disabled or selected.
5320 // By mixing this class into your widget, and setting the this.baseClass attribute, it will automatically
5321 // maintain CSS classes on the widget root node (this.domNode) depending on hover,
5322 // active, focus, etc. state. Ex: with a baseClass of dijitButton, it will apply the classes
5323 // dijitButtonHovered and dijitButtonActive, as the user moves the mouse over the widget and clicks it.
5325 // It also sets CSS like dijitButtonDisabled based on widget semantic state.
5327 // By setting the cssStateNodes attribute, a widget can also track events on subnodes (like buttons
5328 // within the widget).
5330 // cssStateNodes: [protected] Object
5331 // List of sub-nodes within the widget that need CSS classes applied on mouse hover/press and focus
5333 // Each entry in the hash is a an attachpoint names (like "upArrowButton") mapped to a CSS class names
5334 // (like "dijitUpArrowButton"). Example:
5336 // | "upArrowButton": "dijitUpArrowButton",
5337 // | "downArrowButton": "dijitDownArrowButton"
5339 // The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it
5343 postCreate: function(){
5344 this.inherited(arguments
);
5346 // Automatically monitor mouse events (essentially :hover and :active) on this.domNode
5347 dojo
.forEach(["onmouseenter", "onmouseleave", "onmousedown"], function(e
){
5348 this.connect(this.domNode
, e
, "_cssMouseEvent");
5351 // Monitoring changes to disabled, readonly, etc. state, and update CSS class of root node
5352 this.connect(this, "set", function(name
, value
){
5353 if(arguments
.length
>= 2 && {disabled
: true, readOnly
: true, checked
:true, selected
:true}[name
]){
5354 this._setStateClass();
5358 // The widget coming in/out of the focus change affects it's state
5359 dojo
.forEach(["_onFocus", "_onBlur"], function(ap
){
5360 this.connect(this, ap
, "_setStateClass");
5363 // Events on sub nodes within the widget
5364 for(var ap
in this.cssStateNodes
){
5365 this._trackMouseState(this[ap
], this.cssStateNodes
[ap
]);
5367 // Set state initially; there's probably no hover/active/focus state but widget might be
5368 // disabled/readonly so we want to set CSS classes for those conditions.
5369 this._setStateClass();
5372 _cssMouseEvent: function(/*Event*/ event
){
5374 // Sets _hovering and _active properties depending on mouse state,
5375 // then calls _setStateClass() to set appropriate CSS classes for this.domNode.
5380 case "mouseover": // generated on non-IE browsers even though we connected to mouseenter
5381 this._hovering
= true;
5382 this._active
= this._mouseDown
;
5386 case "mouseout": // generated on non-IE browsers even though we connected to mouseleave
5387 this._hovering
= false;
5388 this._active
= false;
5392 this._active
= true;
5393 this._mouseDown
= true;
5394 // Set a global event to handle mouseup, so it fires properly
5395 // even if the cursor leaves this.domNode before the mouse up event.
5396 // Alternately could set active=false on mouseout.
5397 var mouseUpConnector
= this.connect(dojo
.body(), "onmouseup", function(){
5398 this._active
= false;
5399 this._mouseDown
= false;
5400 this._setStateClass();
5401 this.disconnect(mouseUpConnector
);
5405 this._setStateClass();
5409 _setStateClass: function(){
5411 // Update the visual state of the widget by setting the css classes on this.domNode
5412 // (or this.stateNode if defined) by combining this.baseClass with
5413 // various suffixes that represent the current widget state(s).
5416 // In the case where a widget has multiple
5417 // states, it sets the class based on all possible
5418 // combinations. For example, an invalid form widget that is being hovered
5419 // will be "dijitInput dijitInputInvalid dijitInputHover dijitInputInvalidHover".
5421 // The widget may have one or more of the following states, determined
5422 // by this.state, this.checked, this.valid, and this.selected:
5423 // - Error - ValidationTextBox sets this.state to "Error" if the current input value is invalid
5424 // - Checked - ex: a checkmark or a ToggleButton in a checked state, will have this.checked==true
5425 // - Selected - ex: currently selected tab will have this.selected==true
5427 // In addition, it may have one or more of the following states,
5428 // based on this.disabled and flags set in _onMouse (this._active, this._hovering, this._focused):
5429 // - Disabled - if the widget is disabled
5430 // - Active - if the mouse (or space/enter key?) is being pressed down
5431 // - Focused - if the widget has focus
5432 // - Hover - if the mouse is over the widget
5434 // Compute new set of classes
5435 var newStateClasses
= this.baseClass
.split(" ");
5437 function multiply(modifier
){
5438 newStateClasses
= newStateClasses
.concat(dojo
.map(newStateClasses
, function(c
){ return c
+modifier
; }), "dijit"+modifier
);
5441 if(!this.isLeftToRight()){
5442 // For RTL mode we need to set an addition class like dijitTextBoxRtl.
5447 multiply("Checked");
5450 multiply(this.state
);
5453 multiply("Selected");
5457 multiply("Disabled");
5458 }else if(this.readOnly
){
5459 multiply("ReadOnly");
5463 }else if(this._hovering
){
5469 multiply("Focused");
5472 // Remove old state classes and add new ones.
5473 // For performance concerns we only write into domNode.className once.
5474 var tn
= this.stateNode
|| this.domNode
,
5475 classHash
= {}; // set of all classes (state and otherwise) for node
5477 dojo
.forEach(tn
.className
.split(" "), function(c
){ classHash
[c
] = true; });
5479 if("_stateClasses" in this){
5480 dojo
.forEach(this._stateClasses
, function(c
){ delete classHash
[c
]; });
5483 dojo
.forEach(newStateClasses
, function(c
){ classHash
[c
] = true; });
5485 var newClasses
= [];
5486 for(var c
in classHash
){
5489 tn
.className
= newClasses
.join(" ");
5491 this._stateClasses
= newStateClasses
;
5494 _trackMouseState: function(/*DomNode*/ node
, /*String*/ clazz
){
5496 // Track mouse/focus events on specified node and set CSS class on that node to indicate
5497 // current state. Usually not called directly, but via cssStateNodes attribute.
5499 // Given class=foo, will set the following CSS class on the node
5500 // - fooActive: if the user is currently pressing down the mouse button while over the node
5501 // - fooHover: if the user is hovering the mouse over the node, but not pressing down a button
5502 // - fooFocus: if the node is focused
5504 // Note that it won't set any classes if the widget is disabled.
5506 // Should be a sub-node of the widget, not the top node (this.domNode), since the top node
5507 // is handled specially and automatically just by mixing in this class.
5509 // CSS class name (ex: dijitSliderUpArrow).
5511 // Current state of node (initially false)
5512 // NB: setting specifically to false because dojo.toggleClass() needs true boolean as third arg
5513 var hovering
=false, active
=false, focused
=false;
5516 cn
= dojo
.hitch(this, "connect", node
);
5518 function setClass(){
5519 var disabled
= ("disabled" in self
&& self
.disabled
) || ("readonly" in self
&& self
.readonly
);
5520 dojo
.toggleClass(node
, clazz
+"Hover", hovering
&& !active
&& !disabled
);
5521 dojo
.toggleClass(node
, clazz
+"Active", active
&& !disabled
);
5522 dojo
.toggleClass(node
, clazz
+"Focused", focused
&& !disabled
);
5526 cn("onmouseenter", function(){
5530 cn("onmouseleave", function(){
5535 cn("onmousedown", function(){
5539 cn("onmouseup", function(){
5545 cn("onfocus", function(){
5549 cn("onblur", function(){
5554 // Just in case widget is enabled/disabled while it has focus/hover/active state.
5555 // Maybe this is overkill.
5556 this.connect(this, "set", function(name
, value
){
5557 if(name
== "disabled" || name
== "readOnly"){
5566 if(!dojo
._hasResource
["dijit.form._FormWidget"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
5567 dojo
._hasResource
["dijit.form._FormWidget"] = true;
5568 dojo
.provide("dijit.form._FormWidget");
5576 dojo
.declare("dijit.form._FormWidget", [dijit
._Widget
, dijit
._Templated
, dijit
._CssStateMixin
],
5579 // Base class for widgets corresponding to native HTML elements such as <checkbox> or <button>,
5580 // which can be children of a <form> node or a `dijit.form.Form` widget.
5583 // Represents a single HTML element.
5584 // All these widgets should have these attributes just like native HTML input elements.
5585 // You can set them during widget construction or afterwards, via `dijit._Widget.attr`.
5587 // They also share some common methods.
5590 // Name used when submitting form; same as "name" attribute or plain HTML elements
5594 // Corresponds to the native HTML <input> element's attribute.
5598 // Corresponds to the native HTML <input> element's attribute.
5602 // Corresponds to the native HTML <input> element's attribute.
5605 // tabIndex: Integer
5606 // Order fields are traversed when user hits the tab key
5609 // disabled: Boolean
5610 // Should this widget respond to user input?
5611 // In markup, this is specified as "disabled='disabled'", or just "disabled".
5614 // intermediateChanges: Boolean
5615 // Fires onChange for each value change or only on demand
5616 intermediateChanges
: false,
5618 // scrollOnFocus: Boolean
5619 // On focus, should this widget scroll into view?
5620 scrollOnFocus
: true,
5622 // These mixins assume that the focus node is an INPUT, as many but not all _FormWidgets are.
5623 attributeMap
: dojo
.delegate(dijit
._Widget
.prototype.attributeMap
, {
5626 tabIndex
: "focusNode",
5631 postMixInProperties: function(){
5632 // Setup name=foo string to be referenced from the template (but only if a name has been specified)
5633 // Unfortunately we can't use attributeMap to set the name due to IE limitations, see #8660
5634 // Regarding escaping, see heading "Attribute values" in
5635 // http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2
5636 this.nameAttrSetting
= this.name
? ('name="' + this.name
.replace(/'/g, """) + '"') : '';
5637 this.inherited(arguments);
5640 postCreate: function(){
5641 this.inherited(arguments);
5642 this.connect(this.domNode, "onmousedown
", "_onMouseDown
");
5645 _setDisabledAttr: function(/*Boolean*/ value){
5646 this.disabled = value;
5647 dojo.attr(this.focusNode, 'disabled', value);
5649 dojo.attr(this.valueNode, 'disabled', value);
5651 dijit.setWaiState(this.focusNode, "disabled
", value);
5654 // reset these, because after the domNode is disabled, we can no longer receive
5655 // mouse related events, see #4200
5656 this._hovering = false;
5657 this._active = false;
5659 // clear tab stop(s) on this widget's focusable node(s) (ComboBox has two focusable nodes)
5660 var attachPointNames = "tabIndex
" in this.attributeMap ? this.attributeMap.tabIndex : "focusNode
";
5661 dojo.forEach(dojo.isArray(attachPointNames) ? attachPointNames : [attachPointNames], function(attachPointName){
5662 var node = this[attachPointName];
5663 // complex code because tabIndex=-1 on a <div> doesn't work on FF
5664 if(dojo.isWebKit || dijit.hasDefaultTabStop(node)){ // see #11064 about webkit bug
5665 node.setAttribute('tabIndex', "-1");
5667 node.removeAttribute('tabIndex');
5671 this.focusNode.setAttribute('tabIndex', this.tabIndex);
5675 setDisabled: function(/*Boolean*/ disabled){
5677 // Deprecated. Use set('disabled', ...) instead.
5678 dojo.deprecated("setDisabled("+disabled+") is deprecated
. Use
set('disabled',"+disabled+") instead
.", "", "2.0");
5679 this.set('disabled', disabled);
5682 _onFocus: function(e){
5683 if(this.scrollOnFocus){
5684 dojo.window.scrollIntoView(this.domNode);
5686 this.inherited(arguments);
5689 isFocusable: function(){
5691 // Tells if this widget is focusable or not. Used internally by dijit.
5694 return !this.disabled && !this.readOnly && this.focusNode && (dojo.style(this.domNode, "display
") != "none
");
5699 // Put focus on this widget
5700 dijit.focus(this.focusNode);
5703 compare: function(/*anything*/val1, /*anything*/val2){
5705 // Compare 2 values (as returned by attr('value') for this widget).
5708 if(typeof val1 == "number
" && typeof val2 == "number
"){
5709 return (isNaN(val1) && isNaN(val2)) ? 0 : val1 - val2;
5710 }else if(val1 > val2){
5712 }else if(val1 < val2){
5719 onChange: function(newValue){
5721 // Callback when this widget's value is changed.
5726 // _onChangeActive: [private] Boolean
5727 // Indicates that changes to the value should call onChange() callback.
5728 // This is false during widget initialization, to avoid calling onChange()
5729 // when the initial value is set.
5730 _onChangeActive: false,
5732 _handleOnChange: function(/*anything*/ newValue, /* Boolean? */ priorityChange){
5734 // Called when the value of the widget is set. Calls onChange() if appropriate
5738 // For a slider, for example, dragging the slider is priorityChange==false,
5739 // but on mouse up, it's priorityChange==true. If intermediateChanges==true,
5740 // onChange is only called form priorityChange=true events.
5743 this._lastValue = newValue;
5744 if(this._lastValueReported == undefined && (priorityChange === null || !this._onChangeActive)){
5745 // this block executes not for a change, but during initialization,
5746 // and is used to store away the original value (or for ToggleButton, the original checked state)
5747 this._resetValue = this._lastValueReported = newValue;
5749 if((this.intermediateChanges || priorityChange || priorityChange === undefined) &&
5750 ((typeof newValue != typeof this._lastValueReported) ||
5751 this.compare(newValue, this._lastValueReported) != 0)){
5752 this._lastValueReported = newValue;
5753 if(this._onChangeActive){
5754 if(this._onChangeHandle){
5755 clearTimeout(this._onChangeHandle);
5757 // setTimout allows hidden value processing to run and
5758 // also the onChange handler can safely adjust focus, etc
5759 this._onChangeHandle = setTimeout(dojo.hitch(this,
5761 this._onChangeHandle = null;
5762 this.onChange(newValue);
5763 }), 0); // try to collapse multiple onChange's fired faster than can be processed
5769 // Overrides _Widget.create()
5770 this.inherited(arguments);
5771 this._onChangeActive = true;
5774 destroy: function(){
5775 if(this._onChangeHandle){ // destroy called before last onChange has fired
5776 clearTimeout(this._onChangeHandle);
5777 this.onChange(this._lastValueReported);
5779 this.inherited(arguments);
5782 setValue: function(/*String*/ value){
5784 // Deprecated. Use set('value', ...) instead.
5785 dojo.deprecated("dijit
.form
._FormWidget
:setValue("+value+") is deprecated
. Use
set('value',"+value+") instead
.", "", "2.0");
5786 this.set('value', value);
5789 getValue: function(){
5791 // Deprecated. Use get('value') instead.
5792 dojo.deprecated(this.declaredClass+"::getValue() is deprecated
. Use
get('value') instead
.", "", "2.0");
5793 return this.get('value');
5796 _onMouseDown: function(e){
5797 // If user clicks on the button, even if the mouse is released outside of it,
5798 // this button should get focus (to mimics native browser buttons).
5799 // This is also needed on chrome because otherwise buttons won't get focus at all,
5800 // which leads to bizarre focus restore on Dialog close etc.
5801 if(!e.ctrlKey && this.isFocusable()){ // !e.ctrlKey to ignore right-click on mac
5802 // Set a global event to handle mouseup, so it fires properly
5803 // even if the cursor leaves this.domNode before the mouse up event.
5804 var mouseUpConnector = this.connect(dojo.body(), "onmouseup
", function(){
5805 if (this.isFocusable()) {
5808 this.disconnect(mouseUpConnector);
5814 dojo.declare("dijit
.form
._FormValueWidget
", dijit.form._FormWidget,
5817 // Base class for widgets corresponding to native HTML elements such as <input> or <select> that have user changeable values.
5819 // Each _FormValueWidget represents a single input value, and has a (possibly hidden) <input> element,
5820 // to which it serializes it's input value, so that form submission (either normal submission or via FormBind?)
5821 // works as expected.
5823 // Don't attempt to mixin the 'type', 'name' attributes here programatically -- they must be declared
5824 // directly in the template as read by the parser in order to function. IE is known to specifically
5825 // require the 'name' attribute at element creation time. See #8484, #8660.
5826 // TODO: unclear what that {value: ""} is for; FormWidget.attributeMap copies value to focusNode,
5827 // so maybe {value: ""} is so the value *doesn't* get copied to focusNode?
5828 // Seems like we really want value removed from attributeMap altogether
5829 // (although there's no easy way to do that now)
5831 // readOnly: Boolean
5832 // Should this widget respond to user input?
5833 // In markup, this is specified as "readOnly
".
5834 // Similar to disabled except readOnly form values are submitted.
5837 attributeMap: dojo.delegate(dijit.form._FormWidget.prototype.attributeMap, {
5839 readOnly: "focusNode
"
5842 _setReadOnlyAttr: function(/*Boolean*/ value){
5843 this.readOnly = value;
5844 dojo.attr(this.focusNode, 'readOnly', value);
5845 dijit.setWaiState(this.focusNode, "readonly
", value);
5848 postCreate: function(){
5849 this.inherited(arguments);
5851 if(dojo.isIE){ // IE won't stop the event with keypress
5852 this.connect(this.focusNode || this.domNode, "onkeydown
", this._onKeyDown);
5854 // Update our reset value if it hasn't yet been set (because this.set()
5855 // is only called when there *is* a value)
5856 if(this._resetValue === undefined){
5857 this._resetValue = this.value;
5861 _setValueAttr: function(/*anything*/ newValue, /*Boolean, optional*/ priorityChange){
5863 // Hook so attr('value', value) works.
5865 // Sets the value of the widget.
5866 // If the value has changed, then fire onChange event, unless priorityChange
5867 // is specified as null (or false?)
5868 this.value = newValue;
5869 this._handleOnChange(newValue, priorityChange);
5872 _getValueAttr: function(){
5874 // Hook so attr('value') works.
5875 return this._lastValue;
5880 // Restore the value to the last value passed to onChange
5881 this._setValueAttr(this._lastValueReported, false);
5886 // Reset the widget's value to what it was at initialization time
5887 this._hasBeenBlurred = false;
5888 this._setValueAttr(this._resetValue, true);
5891 _onKeyDown: function(e){
5892 if(e.keyCode == dojo.keys.ESCAPE && !(e.ctrlKey || e.altKey || e.metaKey)){
5895 e.preventDefault(); // default behavior needs to be stopped here since keypress is too late
5896 te = document.createEventObject();
5897 te.keyCode = dojo.keys.ESCAPE;
5898 te.shiftKey = e.shiftKey;
5899 e.srcElement.fireEvent('onkeypress', te);
5904 _layoutHackIE7: function(){
5906 // Work around table sizing bugs on IE7 by forcing redraw
5908 if(dojo.isIE == 7){ // fix IE7 layout bug when the widget is scrolled out of sight
5909 var domNode = this.domNode;
5910 var parent = domNode.parentNode;
5911 var pingNode = domNode.firstChild || domNode; // target node most unlikely to have a custom filter
5912 var origFilter = pingNode.style.filter; // save custom filter, most likely nothing
5914 while(parent && parent.clientHeight == 0){ // search for parents that haven't rendered yet
5916 var disconnectHandle = _this.connect(parent, "onscroll
",
5918 _this.disconnect(disconnectHandle); // only call once
5919 pingNode.style.filter = (new Date()).getMilliseconds(); // set to anything that's unique
5920 setTimeout(function(){ pingNode.style.filter = origFilter }, 0); // restore custom filter, if any
5924 parent = parent.parentNode;
5932 if(!dojo._hasResource["dijit
.dijit
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
5933 dojo._hasResource["dijit
.dijit
"] = true;
5934 dojo.provide("dijit
.dijit
");
5939 // A roll-up for common dijit methods
5941 // A rollup file for the build system including the core and common
5945 // | <script type="text
/javascript" src="js/dojo/dijit/dijit.js
"></script>
5950 // All the stuff in _base (these are the function that are guaranteed available without an explicit dojo.require)
5953 // And some other stuff that we tend to pull in all the time anyway
5963 if(!dojo._hasResource["dojo
.fx
.Toggler
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
5964 dojo._hasResource["dojo
.fx
.Toggler
"] = true;
5965 dojo.provide("dojo
.fx
.Toggler
");
5967 dojo.declare("dojo
.fx
.Toggler
", null, {
5969 // A simple `dojo.Animation` toggler API.
5972 // class constructor for an animation toggler. It accepts a packed
5973 // set of arguments about what type of animation to use in each
5974 // direction, duration, etc. All available members are mixed into
5975 // these animations from the constructor (for example, `node`,
5976 // `showDuration`, `hideDuration`).
5979 // | var t = new dojo.fx.Toggler({
5980 // | node: "nodeId
",
5981 // | showDuration: 500,
5982 // | // hideDuration will default to "200"
5983 // | showFunc: dojo.fx.wipeIn,
5984 // | // hideFunc will default to "fadeOut
"
5986 // | t.show(100); // delay showing for 100ms
5987 // | // ...time passes...
5991 // the node to target for the showing and hiding animations
5994 // showFunc: Function
5995 // The function that returns the `dojo.Animation` to show the node
5996 showFunc: dojo.fadeIn,
5998 // hideFunc: Function
5999 // The function that returns the `dojo.Animation` to hide the node
6000 hideFunc: dojo.fadeOut,
6003 // Time in milliseconds to run the show Animation
6007 // Time in milliseconds to run the hide Animation
6010 // FIXME: need a policy for where the toggler should "be
" the next
6011 // time show/hide are called if we're stopped somewhere in the
6013 // FIXME: also would be nice to specify individual showArgs/hideArgs mixed into
6014 // each animation individually.
6015 // FIXME: also would be nice to have events from the animations exposed/bridged
6028 constructor: function(args){
6031 dojo.mixin(_t, args);
6032 _t.node = args.node;
6033 _t._showArgs = dojo.mixin({}, args);
6034 _t._showArgs.node = _t.node;
6035 _t._showArgs.duration = _t.showDuration;
6036 _t.showAnim = _t.showFunc(_t._showArgs);
6038 _t._hideArgs = dojo.mixin({}, args);
6039 _t._hideArgs.node = _t.node;
6040 _t._hideArgs.duration = _t.hideDuration;
6041 _t.hideAnim = _t.hideFunc(_t._hideArgs);
6043 dojo.connect(_t.showAnim, "beforeBegin
", dojo.hitch(_t.hideAnim, "stop
", true));
6044 dojo.connect(_t.hideAnim, "beforeBegin
", dojo.hitch(_t.showAnim, "stop
", true));
6047 show: function(delay){
6048 // summary: Toggle the node to showing
6050 // Ammount of time to stall playing the show animation
6051 return this.showAnim.play(delay || 0);
6054 hide: function(delay){
6055 // summary: Toggle the node to hidden
6057 // Ammount of time to stall playing the hide animation
6058 return this.hideAnim.play(delay || 0);
6064 if(!dojo._hasResource["dojo
.fx
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
6065 dojo._hasResource["dojo
.fx
"] = true;
6066 dojo.provide("dojo
.fx
");
6067 // FIXME: remove this back-compat require in 2.0
6070 // summary: Effects library on top of Base animations
6077 _fire: function(evt, args){
6079 this[evt].apply(this, args||[]);
6085 var _chain = function(animations){
6087 this._animations = animations||[];
6088 this._current = this._onAnimateCtx = this._onEndCtx = null;
6091 d.forEach(this._animations, function(a){
6092 this.duration += a.duration;
6093 if(a.delay){ this.duration += a.delay; }
6097 _onAnimate: function(){
6098 this._fire("onAnimate
", arguments);
6101 d.disconnect(this._onAnimateCtx);
6102 d.disconnect(this._onEndCtx);
6103 this._onAnimateCtx = this._onEndCtx = null;
6104 if(this._index + 1 == this._animations.length){
6105 this._fire("onEnd
");
6107 // switch animations
6108 this._current = this._animations[++this._index];
6109 this._onAnimateCtx = d.connect(this._current, "onAnimate
", this, "_onAnimate
");
6110 this._onEndCtx = d.connect(this._current, "onEnd
", this, "_onEnd
");
6111 this._current.play(0, true);
6114 play: function(/*int?*/ delay, /*Boolean?*/ gotoStart){
6115 if(!this._current){ this._current = this._animations[this._index = 0]; }
6116 if(!gotoStart && this._current.status() == "playing
"){ return this; }
6117 var beforeBegin = d.connect(this._current, "beforeBegin
", this, function(){
6118 this._fire("beforeBegin
");
6120 onBegin = d.connect(this._current, "onBegin
", this, function(arg){
6121 this._fire("onBegin
", arguments);
6123 onPlay = d.connect(this._current, "onPlay
", this, function(arg){
6124 this._fire("onPlay
", arguments);
6125 d.disconnect(beforeBegin);
6126 d.disconnect(onBegin);
6127 d.disconnect(onPlay);
6129 if(this._onAnimateCtx){
6130 d.disconnect(this._onAnimateCtx);
6132 this._onAnimateCtx = d.connect(this._current, "onAnimate
", this, "_onAnimate
");
6134 d.disconnect(this._onEndCtx);
6136 this._onEndCtx = d.connect(this._current, "onEnd
", this, "_onEnd
");
6137 this._current.play.apply(this._current, arguments);
6142 var e = d.connect(this._current, "onPause
", this, function(arg){
6143 this._fire("onPause
", arguments);
6146 this._current.pause();
6150 gotoPercent: function(/*Decimal*/percent, /*Boolean?*/ andPlay){
6152 var offset = this.duration * percent;
6153 this._current = null;
6154 d.some(this._animations, function(a){
6155 if(a.duration <= offset){
6159 offset -= a.duration;
6163 this._current.gotoPercent(offset / this._current.duration, andPlay);
6167 stop: function(/*boolean?*/ gotoEnd){
6170 for(; this._index + 1 < this._animations.length; ++this._index){
6171 this._animations[this._index].stop(true);
6173 this._current = this._animations[this._index];
6175 var e = d.connect(this._current, "onStop
", this, function(arg){
6176 this._fire("onStop
", arguments);
6179 this._current.stop();
6184 return this._current ? this._current.status() : "stopped
";
6186 destroy: function(){
6187 if(this._onAnimateCtx){ d.disconnect(this._onAnimateCtx); }
6188 if(this._onEndCtx){ d.disconnect(this._onEndCtx); }
6191 d.extend(_chain, _baseObj);
6193 dojo.fx.chain = function(/*dojo.Animation[]*/ animations){
6195 // Chain a list of `dojo.Animation`s to run in sequence
6198 // Return a `dojo.Animation` which will play all passed
6199 // `dojo.Animation` instances in sequence, firing its own
6200 // synthesized events simulating a single animation. (eg:
6201 // onEnd of this animation means the end of the chain,
6202 // not the individual animations within)
6205 // Once `node` is faded out, fade in `otherNode`
6206 // | dojo.fx.chain([
6207 // | dojo.fadeIn({ node:node }),
6208 // | dojo.fadeOut({ node:otherNode })
6211 return new _chain(animations) // dojo.Animation
6214 var _combine = function(animations){
6215 this._animations = animations||[];
6216 this._connects = [];
6220 d.forEach(animations, function(a){
6221 var duration = a.duration;
6222 if(a.delay){ duration += a.delay; }
6223 if(this.duration < duration){ this.duration = duration; }
6224 this._connects.push(d.connect(a, "onEnd
", this, "_onEnd
"));
6227 this._pseudoAnimation = new d.Animation({curve: [0, 1], duration: this.duration});
6229 d.forEach(["beforeBegin
", "onBegin
", "onPlay
", "onAnimate
", "onPause
", "onStop
", "onEnd
"],
6231 self._connects.push(d.connect(self._pseudoAnimation, evt,
6232 function(){ self._fire(evt, arguments); }
6237 d.extend(_combine, {
6238 _doAction: function(action, args){
6239 d.forEach(this._animations, function(a){
6240 a[action].apply(a, args);
6245 if(++this._finished > this._animations.length){
6246 this._fire("onEnd
");
6249 _call: function(action, args){
6250 var t = this._pseudoAnimation;
6251 t[action].apply(t, args);
6253 play: function(/*int?*/ delay, /*Boolean?*/ gotoStart){
6255 this._doAction("play
", arguments);
6256 this._call("play
", arguments);
6260 this._doAction("pause
", arguments);
6261 this._call("pause
", arguments);
6264 gotoPercent: function(/*Decimal*/percent, /*Boolean?*/ andPlay){
6265 var ms = this.duration * percent;
6266 d.forEach(this._animations, function(a){
6267 a.gotoPercent(a.duration < ms ? 1 : (ms / a.duration), andPlay);
6269 this._call("gotoPercent
", arguments);
6272 stop: function(/*boolean?*/ gotoEnd){
6273 this._doAction("stop
", arguments);
6274 this._call("stop
", arguments);
6278 return this._pseudoAnimation.status();
6280 destroy: function(){
6281 d.forEach(this._connects, dojo.disconnect);
6284 d.extend(_combine, _baseObj);
6286 dojo.fx.combine = function(/*dojo.Animation[]*/ animations){
6288 // Combine a list of `dojo.Animation`s to run in parallel
6291 // Combine an array of `dojo.Animation`s to run in parallel,
6292 // providing a new `dojo.Animation` instance encompasing each
6293 // animation, firing standard animation events.
6296 // Fade out `node` while fading in `otherNode` simultaneously
6297 // | dojo.fx.combine([
6298 // | dojo.fadeIn({ node:node }),
6299 // | dojo.fadeOut({ node:otherNode })
6303 // When the longest animation ends, execute a function:
6304 // | var anim = dojo.fx.combine([
6305 // | dojo.fadeIn({ node: n, duration:700 }),
6306 // | dojo.fadeOut({ node: otherNode, duration: 300 })
6308 // | dojo.connect(anim, "onEnd
", function(){
6309 // | // overall animation is done.
6311 // | anim.play(); // play the animation
6313 return new _combine(animations); // dojo.Animation
6316 dojo.fx.wipeIn = function(/*Object*/ args){
6318 // Expand a node to it's natural height.
6321 // Returns an animation that will expand the
6322 // node defined in 'args' object from it's current height to
6323 // it's natural height (with no scrollbar).
6324 // Node must have no margin/border/padding.
6327 // A hash-map of standard `dojo.Animation` constructor properties
6328 // (such as easing: node: duration: and so on)
6331 // | dojo.fx.wipeIn({
6334 var node = args.node = d.byId(args.node), s = node.style, o;
6336 var anim = d.animateProperty(d.mixin({
6339 // wrapped in functions so we wait till the last second to query (in case value has changed)
6341 // start at current [computed] height, but use 1px rather than 0
6342 // because 0 causes IE to display the whole panel
6344 s.overflow = "hidden
";
6345 if(s.visibility == "hidden
" || s.display == "none
"){
6351 var height = d.style(node, "height
");
6352 return Math.max(height, 1);
6356 return node.scrollHeight;
6362 d.connect(anim, "onEnd
", function(){
6367 return anim; // dojo.Animation
6370 dojo.fx.wipeOut = function(/*Object*/ args){
6372 // Shrink a node to nothing and hide it.
6375 // Returns an animation that will shrink node defined in "args
"
6376 // from it's current height to 1px, and then hide it.
6379 // A hash-map of standard `dojo.Animation` constructor properties
6380 // (such as easing: node: duration: and so on)
6383 // | dojo.fx.wipeOut({ node:"someId
" }).play()
6385 var node = args.node = d.byId(args.node), s = node.style, o;
6387 var anim = d.animateProperty(d.mixin({
6390 end: 1 // 0 causes IE to display the whole panel
6395 d.connect(anim, "beforeBegin
", function(){
6397 s.overflow = "hidden
";
6400 d.connect(anim, "onEnd
", function(){
6406 return anim; // dojo.Animation
6409 dojo.fx.slideTo = function(/*Object*/ args){
6411 // Slide a node to a new top/left position
6414 // Returns an animation that will slide "node
"
6415 // defined in args Object from its current position to
6416 // the position defined by (args.left, args.top).
6419 // A hash-map of standard `dojo.Animation` constructor properties
6420 // (such as easing: node: duration: and so on). Special args members
6421 // are `top` and `left`, which indicate the new position to slide to.
6424 // | dojo.fx.slideTo({ node: node, left:"40", top:"50", units:"px
" }).play()
6426 var node = args.node = d.byId(args.node),
6427 top = null, left = null;
6429 var init = (function(n){
6431 var cs = d.getComputedStyle(n);
6432 var pos = cs.position;
6433 top = (pos == 'absolute' ? n.offsetTop : parseInt(cs.top) || 0);
6434 left = (pos == 'absolute' ? n.offsetLeft : parseInt(cs.left) || 0);
6435 if(pos != 'absolute' && pos != 'relative'){
6436 var ret = d.position(n, true);
6439 n.style.position="absolute
";
6440 n.style.top=top+"px
";
6441 n.style.left=left+"px
";
6447 var anim = d.animateProperty(d.mixin({
6450 left: args.left || 0
6453 d.connect(anim, "beforeBegin
", anim, init);
6455 return anim; // dojo.Animation
6462 if(!dojo._hasResource["dojo
.NodeList
-fx
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
6463 dojo._hasResource["dojo
.NodeList
-fx
"] = true;
6464 dojo.provide("dojo
.NodeList
-fx
");
6468 dojo["NodeList
-fx
"] = {
6469 // summary: Adds dojo.fx animation support to dojo.query()
6473 dojo.extend(dojo.NodeList, {
6474 _anim: function(obj, method, args){
6476 var a = dojo.fx.combine(
6477 this.map(function(item){
6478 var tmpArgs = { node: item };
6479 dojo.mixin(tmpArgs, args);
6480 return obj[method](tmpArgs);
6483 return args.auto ? a.play() && this : a; // dojo.Animation|dojo.NodeList
6486 wipeIn: function(args){
6488 // wipe in all elements of this NodeList via `dojo.fx.wipeIn`
6491 // Additional dojo.Animation arguments to mix into this set with the addition of
6492 // an `auto` parameter.
6494 // returns: dojo.Animation|dojo.NodeList
6495 // A special args member `auto` can be passed to automatically play the animation.
6496 // If args.auto is present, the original dojo.NodeList will be returned for further
6497 // chaining. Otherwise the dojo.Animation instance is returned and must be .play()'ed
6500 // Fade in all tables with class "blah
":
6501 // | dojo.query("table
.blah
").wipeIn().play();
6504 // Utilizing `auto` to get the NodeList back:
6505 // | dojo.query(".titles
").wipeIn({ auto:true }).onclick(someFunction);
6507 return this._anim(dojo.fx, "wipeIn
", args); // dojo.Animation|dojo.NodeList
6510 wipeOut: function(args){
6512 // wipe out all elements of this NodeList via `dojo.fx.wipeOut`
6515 // Additional dojo.Animation arguments to mix into this set with the addition of
6516 // an `auto` parameter.
6518 // returns: dojo.Animation|dojo.NodeList
6519 // A special args member `auto` can be passed to automatically play the animation.
6520 // If args.auto is present, the original dojo.NodeList will be returned for further
6521 // chaining. Otherwise the dojo.Animation instance is returned and must be .play()'ed
6524 // Wipe out all tables with class "blah
":
6525 // | dojo.query("table
.blah
").wipeOut().play();
6526 return this._anim(dojo.fx, "wipeOut
", args); // dojo.Animation|dojo.NodeList
6529 slideTo: function(args){
6531 // slide all elements of the node list to the specified place via `dojo.fx.slideTo`
6534 // Additional dojo.Animation arguments to mix into this set with the addition of
6535 // an `auto` parameter.
6537 // returns: dojo.Animation|dojo.NodeList
6538 // A special args member `auto` can be passed to automatically play the animation.
6539 // If args.auto is present, the original dojo.NodeList will be returned for further
6540 // chaining. Otherwise the dojo.Animation instance is returned and must be .play()'ed
6543 // | Move all tables with class "blah
" to 300/300:
6544 // | dojo.query("table
.blah
").slideTo({
6548 return this._anim(dojo.fx, "slideTo
", args); // dojo.Animation|dojo.NodeList
6552 fadeIn: function(args){
6554 // fade in all elements of this NodeList via `dojo.fadeIn`
6557 // Additional dojo.Animation arguments to mix into this set with the addition of
6558 // an `auto` parameter.
6560 // returns: dojo.Animation|dojo.NodeList
6561 // A special args member `auto` can be passed to automatically play the animation.
6562 // If args.auto is present, the original dojo.NodeList will be returned for further
6563 // chaining. Otherwise the dojo.Animation instance is returned and must be .play()'ed
6566 // Fade in all tables with class "blah
":
6567 // | dojo.query("table
.blah
").fadeIn().play();
6568 return this._anim(dojo, "fadeIn
", args); // dojo.Animation|dojo.NodeList
6571 fadeOut: function(args){
6573 // fade out all elements of this NodeList via `dojo.fadeOut`
6576 // Additional dojo.Animation arguments to mix into this set with the addition of
6577 // an `auto` parameter.
6579 // returns: dojo.Animation|dojo.NodeList
6580 // A special args member `auto` can be passed to automatically play the animation.
6581 // If args.auto is present, the original dojo.NodeList will be returned for further
6582 // chaining. Otherwise the dojo.Animation instance is returned and must be .play()'ed
6585 // Fade out all elements with class "zork
":
6586 // | dojo.query(".zork
").fadeOut().play();
6588 // Fade them on a delay and do something at the end:
6589 // | var fo = dojo.query(".zork
").fadeOut();
6590 // | dojo.connect(fo, "onEnd
", function(){ /*...*/ });
6594 // | dojo.query("li
").fadeOut({ auto:true }).filter(filterFn).forEach(doit);
6596 return this._anim(dojo, "fadeOut
", args); // dojo.Animation|dojo.NodeList
6599 animateProperty: function(args){
6601 // Animate all elements of this NodeList across the properties specified.
6602 // syntax identical to `dojo.animateProperty`
6604 // returns: dojo.Animation|dojo.NodeList
6605 // A special args member `auto` can be passed to automatically play the animation.
6606 // If args.auto is present, the original dojo.NodeList will be returned for further
6607 // chaining. Otherwise the dojo.Animation instance is returned and must be .play()'ed
6610 // | dojo.query(".zork
").animateProperty({
6613 // | color: { start: "black
", end: "white
" },
6614 // | left: { end: 300 }
6619 // | dojo.query(".grue
").animateProperty({
6624 // | }).onclick(handler);
6625 return this._anim(dojo, "animateProperty
", args); // dojo.Animation|dojo.NodeList
6628 anim: function( /*Object*/ properties,
6629 /*Integer?*/ duration,
6630 /*Function?*/ easing,
6631 /*Function?*/ onEnd,
6632 /*Integer?*/ delay){
6634 // Animate one or more CSS properties for all nodes in this list.
6635 // The returned animation object will already be playing when it
6636 // is returned. See the docs for `dojo.anim` for full details.
6637 // properties: Object
6638 // the properties to animate. does NOT support the `auto` parameter like other
6639 // NodeList-fx methods.
6640 // duration: Integer?
6641 // Optional. The time to run the animations for
6642 // easing: Function?
6643 // Optional. The easing function to use.
6645 // A function to be called when the animation ends
6647 // how long to delay playing the returned animation
6649 // Another way to fade out:
6650 // | dojo.query(".thinger
").anim({ opacity: 0 });
6652 // animate all elements with the "thigner
" class to a width of 500
6653 // pixels over half a second
6654 // | dojo.query(".thinger
").anim({ width: 500 }, 700);
6655 var canim = dojo.fx.combine(
6656 this.map(function(item){
6657 return dojo.animateProperty({
6659 properties: properties,
6660 duration: duration||350,
6666 dojo.connect(canim, "onEnd
", onEnd);
6668 return canim.play(delay||0); // dojo.Animation
6674 if(!dojo._hasResource["dojo
.colors
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
6675 dojo._hasResource["dojo
.colors
"] = true;
6676 dojo.provide("dojo
.colors
");
6678 //TODO: this module appears to break naming conventions
6682 // summary: Color utilities
6687 // this is a standard conversion prescribed by the CSS3 Color Module
6688 var hue2rgb = function(m1, m2, h){
6692 if(h6 < 1){ return m1 + (m2 - m1) * h6; }
6693 if(2 * h < 1){ return m2; }
6694 if(3 * h < 2){ return m1 + (m2 - m1) * (2 / 3 - h) * 6; }
6698 dojo.colorFromRgb = function(/*String*/ color, /*dojo.Color?*/ obj){
6700 // get rgb(a) array from css-style color declarations
6702 // this function can handle all 4 CSS3 Color Module formats: rgb,
6703 // rgba, hsl, hsla, including rgb(a) with percentage values.
6704 var m = color.toLowerCase().match(/^(rgba?|hsla?)\(([\s\.\-,%0-9]+)\)/);
6706 var c = m[2].split(/\s*,\s*/), l = c.length, t = m[1], a;
6707 if((t == "rgb
" && l == 3) || (t == "rgba
" && l == 4)){
6709 if(r.charAt(r.length - 1) == "%"){
6710 // 3 rgb percentage values
6711 a = dojo.map(c, function(x){
6712 return parseFloat(x) * 2.56;
6714 if(l == 4){ a[3] = c[3]; }
6715 return dojo.colorFromArray(a, obj); // dojo.Color
6717 return dojo.colorFromArray(c, obj); // dojo.Color
6719 if((t == "hsl
" && l == 3) || (t == "hsla
" && l == 4)){
6720 // normalize hsl values
6721 var H = ((parseFloat(c[0]) % 360) + 360) % 360 / 360,
6722 S = parseFloat(c[1]) / 100,
6723 L = parseFloat(c[2]) / 100,
6724 // calculate rgb according to the algorithm
6725 // recommended by the CSS3 Color Module
6726 m2 = L <= 0.5 ? L * (S + 1) : L + S - L * S,
6729 hue2rgb(m1, m2, H + 1 / 3) * 256,
6730 hue2rgb(m1, m2, H) * 256,
6731 hue2rgb(m1, m2, H - 1 / 3) * 256,
6734 if(l == 4){ a[3] = c[3]; }
6735 return dojo.colorFromArray(a, obj); // dojo.Color
6738 return null; // dojo.Color
6741 var confine = function(c, low, high){
6743 // sanitize a color component by making sure it is a number,
6744 // and clamping it to valid values
6746 return isNaN(c) ? high : c < low ? low : c > high ? high : c; // Number
6749 dojo.Color.prototype.sanitize = function(){
6750 // summary: makes sure that the object has correct attributes
6752 t.r = Math.round(confine(t.r, 0, 255));
6753 t.g = Math.round(confine(t.g, 0, 255));
6754 t.b = Math.round(confine(t.b, 0, 255));
6755 t.a = confine(t.a, 0, 1);
6756 return this; // dojo.Color
6761 dojo.colors.makeGrey = function(/*Number*/ g, /*Number?*/ a){
6762 // summary: creates a greyscale color with an optional alpha
6763 return dojo.colorFromArray([g, g, g, a]);
6766 // mixin all CSS3 named colors not already in _base, along with SVG 1.0 variant spellings
6767 dojo.mixin(dojo.Color.named, {
6768 aliceblue: [240,248,255],
6769 antiquewhite: [250,235,215],
6770 aquamarine: [127,255,212],
6771 azure: [240,255,255],
6772 beige: [245,245,220],
6773 bisque: [255,228,196],
6774 blanchedalmond: [255,235,205],
6775 blueviolet: [138,43,226],
6777 burlywood: [222,184,135],
6778 cadetblue: [95,158,160],
6779 chartreuse: [127,255,0],
6780 chocolate: [210,105,30],
6781 coral: [255,127,80],
6782 cornflowerblue: [100,149,237],
6783 cornsilk: [255,248,220],
6784 crimson: [220,20,60],
6786 darkblue: [0,0,139],
6787 darkcyan: [0,139,139],
6788 darkgoldenrod: [184,134,11],
6789 darkgray: [169,169,169],
6790 darkgreen: [0,100,0],
6791 darkgrey: [169,169,169],
6792 darkkhaki: [189,183,107],
6793 darkmagenta: [139,0,139],
6794 darkolivegreen: [85,107,47],
6795 darkorange: [255,140,0],
6796 darkorchid: [153,50,204],
6798 darksalmon: [233,150,122],
6799 darkseagreen: [143,188,143],
6800 darkslateblue: [72,61,139],
6801 darkslategray: [47,79,79],
6802 darkslategrey: [47,79,79],
6803 darkturquoise: [0,206,209],
6804 darkviolet: [148,0,211],
6805 deeppink: [255,20,147],
6806 deepskyblue: [0,191,255],
6807 dimgray: [105,105,105],
6808 dimgrey: [105,105,105],
6809 dodgerblue: [30,144,255],
6810 firebrick: [178,34,34],
6811 floralwhite: [255,250,240],
6812 forestgreen: [34,139,34],
6813 gainsboro: [220,220,220],
6814 ghostwhite: [248,248,255],
6816 goldenrod: [218,165,32],
6817 greenyellow: [173,255,47],
6818 grey: [128,128,128],
6819 honeydew: [240,255,240],
6820 hotpink: [255,105,180],
6821 indianred: [205,92,92],
6823 ivory: [255,255,240],
6824 khaki: [240,230,140],
6825 lavender: [230,230,250],
6826 lavenderblush: [255,240,245],
6827 lawngreen: [124,252,0],
6828 lemonchiffon: [255,250,205],
6829 lightblue: [173,216,230],
6830 lightcoral: [240,128,128],
6831 lightcyan: [224,255,255],
6832 lightgoldenrodyellow: [250,250,210],
6833 lightgray: [211,211,211],
6834 lightgreen: [144,238,144],
6835 lightgrey: [211,211,211],
6836 lightpink: [255,182,193],
6837 lightsalmon: [255,160,122],
6838 lightseagreen: [32,178,170],
6839 lightskyblue: [135,206,250],
6840 lightslategray: [119,136,153],
6841 lightslategrey: [119,136,153],
6842 lightsteelblue: [176,196,222],
6843 lightyellow: [255,255,224],
6844 limegreen: [50,205,50],
6845 linen: [250,240,230],
6846 magenta: [255,0,255],
6847 mediumaquamarine: [102,205,170],
6848 mediumblue: [0,0,205],
6849 mediumorchid: [186,85,211],
6850 mediumpurple: [147,112,219],
6851 mediumseagreen: [60,179,113],
6852 mediumslateblue: [123,104,238],
6853 mediumspringgreen: [0,250,154],
6854 mediumturquoise: [72,209,204],
6855 mediumvioletred: [199,21,133],
6856 midnightblue: [25,25,112],
6857 mintcream: [245,255,250],
6858 mistyrose: [255,228,225],
6859 moccasin: [255,228,181],
6860 navajowhite: [255,222,173],
6861 oldlace: [253,245,230],
6862 olivedrab: [107,142,35],
6863 orange: [255,165,0],
6864 orangered: [255,69,0],
6865 orchid: [218,112,214],
6866 palegoldenrod: [238,232,170],
6867 palegreen: [152,251,152],
6868 paleturquoise: [175,238,238],
6869 palevioletred: [219,112,147],
6870 papayawhip: [255,239,213],
6871 peachpuff: [255,218,185],
6873 pink: [255,192,203],
6874 plum: [221,160,221],
6875 powderblue: [176,224,230],
6876 rosybrown: [188,143,143],
6877 royalblue: [65,105,225],
6878 saddlebrown: [139,69,19],
6879 salmon: [250,128,114],
6880 sandybrown: [244,164,96],
6881 seagreen: [46,139,87],
6882 seashell: [255,245,238],
6883 sienna: [160,82,45],
6884 skyblue: [135,206,235],
6885 slateblue: [106,90,205],
6886 slategray: [112,128,144],
6887 slategrey: [112,128,144],
6888 snow: [255,250,250],
6889 springgreen: [0,255,127],
6890 steelblue: [70,130,180],
6892 thistle: [216,191,216],
6893 tomato: [255,99,71],
6894 transparent: [0, 0, 0, 0],
6895 turquoise: [64,224,208],
6896 violet: [238,130,238],
6897 wheat: [245,222,179],
6898 whitesmoke: [245,245,245],
6899 yellowgreen: [154,205,50]
6904 if(!dojo._hasResource["dojo
.i18n
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
6905 dojo._hasResource["dojo
.i18n
"] = true;
6906 dojo.provide("dojo
.i18n
");
6910 // summary: Utility classes to enable loading of resources for internationalization (i18n)
6914 dojo.i18n.getLocalization = function(/*String*/packageName, /*String*/bundleName, /*String?*/locale){
6916 // Returns an Object containing the localization for a given resource
6917 // bundle in a package, matching the specified locale.
6919 // Returns a hash containing name/value pairs in its prototypesuch
6920 // that values can be easily overridden. Throws an exception if the
6921 // bundle is not found. Bundle must have already been loaded by
6922 // `dojo.requireLocalization()` or by a build optimization step. NOTE:
6923 // try not to call this method as part of an object property
6924 // definition (`var foo = { bar: dojo.i18n.getLocalization() }`). In
6925 // some loading situations, the bundle may not be available in time
6926 // for the object definition. Instead, call this method inside a
6927 // function that is run after all modules load or the page loads (like
6928 // in `dojo.addOnLoad()`), or in a widget lifecycle method.
6930 // package which is associated with this resource
6932 // the base filename of the resource bundle (without the ".js
" suffix)
6934 // the variant to load (optional). By default, the locale defined by
6935 // the host environment: dojo.locale
6937 locale = dojo.i18n.normalizeLocale(locale);
6939 // look for nearest locale match
6940 var elements = locale.split('-');
6941 var module = [packageName,"nls
",bundleName].join('.');
6942 var bundle = dojo._loadedModules[module];
6945 for(var i = elements.length; i > 0; i--){
6946 var loc = elements.slice(0, i).join('_');
6948 localization = bundle[loc];
6953 localization = bundle.ROOT;
6956 // make a singleton prototype so that the caller won't accidentally change the values globally
6958 var clazz = function(){};
6959 clazz.prototype = localization;
6960 return new clazz(); // Object
6964 throw new Error("Bundle not found
: " + bundleName + " in " + packageName+" , locale
=" + locale);
6967 dojo.i18n.normalizeLocale = function(/*String?*/locale){
6969 // Returns canonical form of locale, as used by Dojo.
6972 // All variants are case-insensitive and are separated by '-' as specified in [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt).
6973 // If no locale is specified, the dojo.locale is returned. dojo.locale is defined by
6974 // the user agent's locale unless overridden by djConfig.
6976 var result = locale ? locale.toLowerCase() : dojo.locale;
6977 if(result == "root
"){
6980 return result; // String
6983 dojo.i18n._requireLocalization = function(/*String*/moduleName, /*String*/bundleName, /*String?*/locale, /*String?*/availableFlatLocales){
6985 // See dojo.requireLocalization()
6987 // Called by the bootstrap, but factored out so that it is only
6988 // included in the build when needed.
6990 var targetLocale = dojo.i18n.normalizeLocale(locale);
6991 var bundlePackage = [moduleName, "nls
", bundleName].join(".");
6993 // When loading these resources, the packaging does not match what is
6994 // on disk. This is an implementation detail, as this is just a
6995 // private data structure to hold the loaded resources. e.g.
6996 // `tests/hello/nls/en-us/salutations.js` is loaded as the object
6997 // `tests.hello.nls.salutations.en_us={...}` The structure on disk is
6998 // intended to be most convenient for developers and translators, but
6999 // in memory it is more logical and efficient to store in a different
7000 // order. Locales cannot use dashes, since the resulting path will
7001 // not evaluate as valid JS, so we translate them to underscores.
7003 //Find the best-match locale to load if we have available flat locales.
7004 var bestLocale = "";
7005 if(availableFlatLocales){
7006 var flatLocales = availableFlatLocales.split(",");
7007 for(var i = 0; i < flatLocales.length; i++){
7008 //Locale must match from start of string.
7009 //Using ["indexOf
"] so customBase builds do not see
7010 //this as a dojo._base.array dependency.
7011 if(targetLocale["indexOf
"](flatLocales[i]) == 0){
7012 if(flatLocales[i].length > bestLocale.length){
7013 bestLocale = flatLocales[i];
7018 bestLocale = "ROOT
";
7022 //See if the desired locale is already loaded.
7023 var tempLocale = availableFlatLocales ? bestLocale : targetLocale;
7024 var bundle = dojo._loadedModules[bundlePackage];
7025 var localizedBundle = null;
7027 if(dojo.config.localizationComplete && bundle._built){return;}
7028 var jsLoc = tempLocale.replace(/-/g, '_');
7029 var translationPackage = bundlePackage+"."+jsLoc;
7030 localizedBundle = dojo._loadedModules[translationPackage];
7033 if(!localizedBundle){
7034 bundle = dojo["provide
"](bundlePackage);
7035 var syms = dojo._getModuleSymbols(moduleName);
7036 var modpath = syms.concat("nls
").join("/");
7039 dojo.i18n._searchLocalePath(tempLocale, availableFlatLocales, function(loc){
7040 var jsLoc = loc.replace(/-/g, '_');
7041 var translationPackage = bundlePackage + "." + jsLoc;
7043 if(!dojo._loadedModules[translationPackage]){
7044 // Mark loaded whether it's found or not, so that further load attempts will not be made
7045 dojo["provide
"](translationPackage);
7046 var module = [modpath];
7047 if(loc != "ROOT
"){module.push(loc);}
7048 module.push(bundleName);
7049 var filespec = module.join("/") + '.js';
7050 loaded = dojo._loadPath(filespec, null, function(hash){
7051 // Use singleton with prototype to point to parent bundle, then mix-in result from loadPath
7052 var clazz = function(){};
7053 clazz.prototype = parent;
7054 bundle[jsLoc] = new clazz();
7055 for(var j in hash){ bundle[jsLoc][j] = hash[j]; }
7060 if(loaded && bundle[jsLoc]){
7061 parent = bundle[jsLoc];
7063 bundle[jsLoc] = parent;
7066 if(availableFlatLocales){
7067 //Stop the locale path searching if we know the availableFlatLocales, since
7068 //the first call to this function will load the only bundle that is needed.
7074 //Save the best locale bundle as the target locale bundle when we know the
7075 //the available bundles.
7076 if(availableFlatLocales && targetLocale != bestLocale){
7077 bundle[targetLocale.replace(/-/g, '_')] = bundle[bestLocale.replace(/-/g, '_')];
7082 // If other locales are used, dojo.requireLocalization should load them as
7083 // well, by default.
7085 // Override dojo.requireLocalization to do load the default bundle, then
7086 // iterate through the extraLocale list and load those translations as
7087 // well, unless a particular locale was requested.
7089 var extra = dojo.config.extraLocale;
7091 if(!extra instanceof Array){
7095 var req = dojo.i18n._requireLocalization;
7096 dojo.i18n._requireLocalization = function(m, b, locale, availableFlatLocales){
7097 req(m,b,locale, availableFlatLocales);
7099 for(var i=0; i<extra.length; i++){
7100 req(m,b,extra[i], availableFlatLocales);
7106 dojo.i18n._searchLocalePath = function(/*String*/locale, /*Boolean*/down, /*Function*/searchFunc){
7108 // A helper method to assist in searching for locale-based resources.
7109 // Will iterate through the variants of a particular locale, either up
7110 // or down, executing a callback function. For example, "en
-us
" and
7111 // true will try "en
-us
" followed by "en
" and finally "ROOT
".
7113 locale = dojo.i18n.normalizeLocale(locale);
7115 var elements = locale.split('-');
7116 var searchlist = [];
7117 for(var i = elements.length; i > 0; i--){
7118 searchlist.push(elements.slice(0, i).join('-'));
7120 searchlist.push(false);
7121 if(down){searchlist.reverse();}
7123 for(var j = searchlist.length - 1; j >= 0; j--){
7124 var loc = searchlist[j] || "ROOT
";
7125 var stop = searchFunc(loc);
7130 dojo.i18n._preloadLocalizations = function(/*String*/bundlePrefix, /*Array*/localesGenerated){
7132 // Load built, flattened resource bundles, if available for all
7133 // locales used in the page. Only called by built layer files.
7135 function preload(locale){
7136 locale = dojo.i18n.normalizeLocale(locale);
7137 dojo.i18n._searchLocalePath(locale, true, function(loc){
7138 for(var i=0; i<localesGenerated.length;i++){
7139 if(localesGenerated[i] == loc){
7140 dojo["require
"](bundlePrefix+"_
"+loc);
7141 return true; // Boolean
7144 return false; // Boolean
7148 var extra = dojo.config.extraLocale||[];
7149 for(var i=0; i<extra.length; i++){
7156 if(!dojo._hasResource["dijit
._PaletteMixin
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
7157 dojo._hasResource["dijit
._PaletteMixin
"] = true;
7158 dojo.provide("dijit
._PaletteMixin
");
7161 dojo.declare("dijit
._PaletteMixin
",
7162 [dijit._CssStateMixin],
7165 // A keyboard accessible palette, for picking a color/emoticon/etc.
7167 // A mixin for a grid showing various entities, so the user can pick a certain entity.
7169 // defaultTimeout: Number
7170 // Number of milliseconds before a held key or button becomes typematic
7171 defaultTimeout: 500,
7173 // timeoutChangeRate: Number
7174 // Fraction of time used to change the typematic timer between events
7175 // 1.0 means that each typematic event fires at defaultTimeout intervals
7176 // < 1.0 means that each typematic event fires at an increasing faster rate
7177 timeoutChangeRate: 0.90,
7180 // Currently selected color/emoticon/etc.
7183 // _selectedCell: [private] Integer
7184 // Index of the currently selected cell. Initially, none selected
7187 // _currentFocus: [private] DomNode
7188 // The currently focused cell (if the palette itself has focus), or otherwise
7189 // the cell to be focused when the palette itself gets focus.
7190 // Different from value, which represents the selected (i.e. clicked) cell.
7192 _currentFocus: null,
7195 // _xDim: [protected] Integer
7196 // This is the number of cells horizontally across.
7201 // _yDim: [protected] Integer
7202 // This is the number of cells vertically down.
7208 // Widget tab index.
7211 // cellClass: [protected] String
7212 // CSS class applied to each cell in the palette
7213 cellClass: "dijitPaletteCell
",
7215 // dyeClass: [protected] String
7216 // Name of javascript class for Object created for each cell of the palette.
7217 // dyeClass should implements dijit.Dye interface
7220 _preparePalette: function(choices, titles) {
7222 // Subclass must call _preparePalette() from postCreate(), passing in the tooltip
7224 // choices: String[][]
7225 // id's for each cell of the palette, used to create Dye JS object for each cell
7227 // Localized tooltip for each cell
7230 var url = this._blankGif;
7232 var dyeClassObj = dojo.getObject(this.dyeClass);
7234 for(var row=0; row < choices.length; row++){
7235 var rowNode = dojo.create("tr
", {tabIndex: "-1"}, this.gridNode);
7236 for(var col=0; col < choices[row].length; col++){
7237 var value = choices[row][col];
7239 var cellObject = new dyeClassObj(value);
7241 var cellNode = dojo.create("td
", {
7242 "class": this.cellClass,
7244 title: titles[value]
7247 // prepare cell inner structure
7248 cellObject.fillCell(cellNode, url);
7250 this.connect(cellNode, "ondijitclick
", "_onCellClick
");
7251 this._trackMouseState(cellNode, this.cellClass);
7253 dojo.place(cellNode, rowNode);
7255 cellNode.index = this._cells.length;
7257 // save cell info into _cells
7258 this._cells.push({node:cellNode, dye:cellObject});
7262 this._xDim = choices[0].length;
7263 this._yDim = choices.length;
7265 // Now set all events
7266 // The palette itself is navigated to with the tab key on the keyboard
7267 // Keyboard navigation within the Palette is with the arrow keys
7268 // Spacebar selects the cell.
7269 // For the up key the index is changed by negative the x dimension.
7271 var keyIncrementMap = {
7272 UP_ARROW: -this._xDim,
7273 // The down key the index is increase by the x dimension.
7274 DOWN_ARROW: this._xDim,
7275 // Right and left move the index by 1.
7276 RIGHT_ARROW: this.isLeftToRight() ? 1 : -1,
7277 LEFT_ARROW: this.isLeftToRight() ? -1 : 1
7279 for(var key in keyIncrementMap){
7280 this._connects.push(
7281 dijit.typematic.addKeyListener(
7283 {charOrCode:dojo.keys[key], ctrlKey:false, altKey:false, shiftKey:false},
7286 var increment = keyIncrementMap[key];
7287 return function(count){ this._navigateByKey(increment, count); };
7289 this.timeoutChangeRate,
7296 postCreate: function(){
7297 this.inherited(arguments);
7299 // Set initial navigable node.
7300 this._setCurrent(this._cells[0].node);
7305 // Focus this widget. Puts focus on the most recently focused cell.
7307 // The cell already has tabIndex set, just need to set CSS and focus it
7308 dijit.focus(this._currentFocus);
7311 _onCellClick: function(/*Event*/ evt){
7313 // Handler for click, enter key & space key. Selects the cell.
7319 var target = evt.currentTarget,
7320 value = this._getDye(target).getValue();
7322 // First focus the clicked cell, and then send onChange() notification.
7323 // onChange() (via _setValueAttr) must be after the focus call, because
7324 // it may trigger a refocus to somewhere else (like the Editor content area), and that
7325 // second focus should win.
7326 // Use setTimeout because IE doesn't like changing focus inside of an event handler.
7327 this._setCurrent(target);
7328 setTimeout(dojo.hitch(this, function(){
7329 dijit.focus(target);
7330 this._setValueAttr(value, true);
7333 // workaround bug where hover class is not removed on popup because the popup is
7334 // closed and then there's no onblur event on the cell
7335 dojo.removeClass(target, "dijitPaletteCellHover
");
7337 dojo.stopEvent(evt);
7340 _setCurrent: function(/*DomNode*/ node){
7342 // Sets which node is the focused cell.
7344 // At any point in time there's exactly one
7345 // cell with tabIndex != -1. If focus is inside the palette then
7346 // focus is on that cell.
7348 // After calling this method, arrow key handlers and mouse click handlers
7349 // should focus the cell in a setTimeout().
7352 if("_currentFocus
" in this){
7353 // Remove tabIndex on old cell
7354 dojo.attr(this._currentFocus, "tabIndex
", "-1");
7357 // Set tabIndex of new cell
7358 this._currentFocus = node;
7360 dojo.attr(node, "tabIndex
", this.tabIndex);
7364 _setValueAttr: function(value, priorityChange){
7366 // This selects a cell. It triggers the onChange event.
7367 // value: String value of the cell to select
7371 // Optional parameter used to tell the select whether or not to fire
7374 // clear old value and selected cell
7376 if(this._selectedCell >= 0){
7377 dojo.removeClass(this._cells[this._selectedCell].node, "dijitPaletteCellSelected
");
7379 this._selectedCell = -1;
7381 // search for cell matching specified value
7383 for(var i = 0; i < this._cells.length; i++){
7384 if(value == this._cells[i].dye.getValue()){
7385 this._selectedCell = i;
7388 dojo.addClass(this._cells[i].node, "dijitPaletteCellSelected
");
7390 if(priorityChange || priorityChange === undefined){
7391 this.onChange(value);
7400 onChange: function(value){
7402 // Callback when a cell is selected.
7404 // Value corresponding to cell.
7407 _navigateByKey: function(increment, typeCount){
7409 // This is the callback for typematic.
7410 // It changes the focus and the highlighed cell.
7412 // How much the key is navigated.
7414 // How many times typematic has fired.
7418 // typecount == -1 means the key is released.
7419 if(typeCount == -1){ return; }
7421 var newFocusIndex = this._currentFocus.index + increment;
7422 if(newFocusIndex < this._cells.length && newFocusIndex > -1){
7423 var focusNode = this._cells[newFocusIndex].node;
7424 this._setCurrent(focusNode);
7426 // Actually focus the node, for the benefit of screen readers.
7427 // Use setTimeout because IE doesn't like changing focus inside of an event handler
7428 setTimeout(dojo.hitch(dijit, "focus
", focusNode), 0);
7432 _getDye: function(/*DomNode*/ cell){
7434 // Get JS object for given cell DOMNode
7436 return this._cells[cell.index].dye;
7441 dojo.declare("dijit
.Dye
",
7445 // Interface for the JS Object associated with a palette cell (i.e. DOMNode)
7447 constructor: function(alias){
7449 // Initialize according to value or alias like "white
"
7453 getValue: function(){
7455 // Return "value
" of cell; meaning of "value
" varies by subclass.
7457 // For example color hex value, emoticon ascii value etc, entity hex value.
7460 fillCell: function(cell, blankGif){
7462 // Add cell DOMNode inner structure
7464 // The surrounding cell
7466 // URL for blank cell image
7474 if(!dojo._hasResource["dijit
.ColorPalette
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
7475 dojo._hasResource["dijit
.ColorPalette
"] = true;
7476 dojo.provide("dijit
.ColorPalette
");
7487 dojo.declare("dijit
.ColorPalette
",
7488 [dijit._Widget, dijit._Templated, dijit._PaletteMixin],
7491 // A keyboard accessible color-picking widget
7493 // Grid showing various colors, so the user can pick a certain color.
7494 // Can be used standalone, or as a popup.
7497 // | <div dojoType="dijit
.ColorPalette
"></div>
7500 // | var picker = new dijit.ColorPalette({ },srcNode);
7501 // | picker.startup();
7505 // Size of grid, either "7x10
" or "3x4
".
7508 // _palettes: [protected] Map
7509 // This represents the value of the colors.
7510 // The first level is a hashmap of the different palettes available.
7511 // The next two dimensions represent the columns and rows of colors.
7513 "7x10
": [["white
", "seashell
", "cornsilk
", "lemonchiffon
","lightyellow
", "palegreen
", "paleturquoise
", "lightcyan
", "lavender
", "plum
"],
7514 ["lightgray
", "pink
", "bisque
", "moccasin
", "khaki
", "lightgreen
", "lightseagreen
", "lightskyblue
", "cornflowerblue
", "violet
"],
7515 ["silver
", "lightcoral
", "sandybrown
", "orange
", "palegoldenrod
", "chartreuse
", "mediumturquoise
", "skyblue
", "mediumslateblue
","orchid
"],
7516 ["gray
", "red
", "orangered
", "darkorange
", "yellow
", "limegreen
", "darkseagreen
", "royalblue
", "slateblue
", "mediumorchid
"],
7517 ["dimgray
", "crimson
", "chocolate
", "coral
", "gold
", "forestgreen
", "seagreen
", "blue
", "blueviolet
", "darkorchid
"],
7518 ["darkslategray
","firebrick
","saddlebrown
", "sienna
", "olive
", "green
", "darkcyan
", "mediumblue
","darkslateblue
", "darkmagenta
" ],
7519 ["black
", "darkred
", "maroon
", "brown
", "darkolivegreen
", "darkgreen
", "midnightblue
", "navy
", "indigo
", "purple
"]],
7521 "3x4
": [["white
", "lime
", "green
", "blue
"],
7522 ["silver
", "yellow
", "fuchsia
", "navy
"],
7523 ["gray
", "red
", "purple
", "black
"]]
7526 // _imagePaths: [protected] Map
7527 // This is stores the path to the palette images
7529 "7x10
": dojo.moduleUrl("dijit
.themes
", "a11y
/colors7x10
.png
"),
7530 "3x4
": dojo.moduleUrl("dijit
.themes
", "a11y
/colors3x4
.png
"),
7531 "7x10
-rtl
": dojo.moduleUrl("dijit
.themes
", "a11y
/colors7x10
-rtl
.png
"),
7532 "3x4
-rtl
": dojo.moduleUrl("dijit
.themes
", "a11y
/colors3x4
-rtl
.png
")
7535 // templateString: String
7536 // The template of this widget.
7537 templateString: dojo.cache("dijit
", "templates
/ColorPalette.html", "<div class=\"dijitInline dijitColorPalette\">\n\t<img class=\"dijitColorPaletteUnder\" dojoAttachPoint=\"imageNode\" waiRole=\"presentation\" alt=\"\"/>\n\t<table
class=\"dijitPaletteTable
\" cellSpacing
=\"0\" cellPadding
=\"0\">\n\t\t<tbody dojoAttachPoint
=\"gridNode
\"></tbody>\n\t</table
>\n</div
>\n"),
7539 baseClass: "dijitColorPalette
",
7541 dyeClass: 'dijit._Color',
7543 buildRendering: function(){
7544 // Instantiate the template, which makes a skeleton into which we'll insert a bunch of
7547 this.inherited(arguments);
7549 this.imageNode.setAttribute("src
", this._imagePaths[this.palette + (this.isLeftToRight() ? "" : "-rtl
")].toString());
7551 var i18nColorNames = dojo.i18n.getLocalization("dojo
", "colors
", this.lang);
7552 this._preparePalette(
7553 this._palettes[this.palette],
7559 dojo.declare("dijit
._Color
", dojo.Color,
7561 // Object associated with each cell in a ColorPalette palette.
7562 // Implements dijit.Dye.
7564 constructor: function(/*String*/alias){
7565 this._alias = alias;
7566 this.setColor(dojo.Color.named[alias]);
7569 getValue: function(){
7571 // Note that although dijit._Color is initialized with a value like "white
" getValue() always
7572 // returns a hex value
7573 return this.toHex();
7576 fillCell: function(/*DOMNode*/ cell, /*String*/ blankGif){
7577 dojo.create("img
", {
7579 "class": "dijitPaletteImg
",
7588 if(!dojo._hasResource["dojo
.dnd
.common
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
7589 dojo._hasResource["dojo
.dnd
.common
"] = true;
7590 dojo.provide("dojo
.dnd
.common
");
7592 dojo.dnd.getCopyKeyState = dojo.isCopyKey;
7594 dojo.dnd._uniqueId = 0;
7595 dojo.dnd.getUniqueId = function(){
7597 // returns a unique string for use with any DOM element
7600 id = dojo._scopeName + "Unique
" + (++dojo.dnd._uniqueId);
7601 }while(dojo.byId(id));
7605 dojo.dnd._empty = {};
7607 dojo.dnd.isFormElement = function(/*Event*/ e){
7609 // returns true if user clicked on a form element
7611 if(t.nodeType == 3 /*TEXT_NODE*/){
7614 return " button textarea input select option
".indexOf(" " + t.tagName.toLowerCase() + " ") >= 0; // Boolean
7619 if(!dojo._hasResource["dojo
.dnd
.autoscroll
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
7620 dojo._hasResource["dojo
.dnd
.autoscroll
"] = true;
7621 dojo.provide("dojo
.dnd
.autoscroll
");
7623 dojo.dnd.getViewport = function(){
7625 // Returns a viewport size (visible part of the window)
7627 // TODO: remove this when getViewport() moved to dojo core, see #7028
7629 // FIXME: need more docs!!
7630 var d = dojo.doc, dd = d.documentElement, w = window, b = dojo.body();
7632 return {w: dd.clientWidth, h: w.innerHeight}; // Object
7633 }else if(!dojo.isOpera && w.innerWidth){
7634 return {w: w.innerWidth, h: w.innerHeight}; // Object
7635 }else if (!dojo.isOpera && dd && dd.clientWidth){
7636 return {w: dd.clientWidth, h: dd.clientHeight}; // Object
7637 }else if (b.clientWidth){
7638 return {w: b.clientWidth, h: b.clientHeight}; // Object
7640 return null; // Object
7643 dojo.dnd.V_TRIGGER_AUTOSCROLL = 32;
7644 dojo.dnd.H_TRIGGER_AUTOSCROLL = 32;
7646 dojo.dnd.V_AUTOSCROLL_VALUE = 16;
7647 dojo.dnd.H_AUTOSCROLL_VALUE = 16;
7649 dojo.dnd.autoScroll = function(e){
7651 // a handler for onmousemove event, which scrolls the window, if
7654 // onmousemove event
7656 // FIXME: needs more docs!
7657 var v = dojo.dnd.getViewport(), dx = 0, dy = 0;
7658 if(e.clientX < dojo.dnd.H_TRIGGER_AUTOSCROLL){
7659 dx = -dojo.dnd.H_AUTOSCROLL_VALUE;
7660 }else if(e.clientX > v.w - dojo.dnd.H_TRIGGER_AUTOSCROLL){
7661 dx = dojo.dnd.H_AUTOSCROLL_VALUE;
7663 if(e.clientY < dojo.dnd.V_TRIGGER_AUTOSCROLL){
7664 dy = -dojo.dnd.V_AUTOSCROLL_VALUE;
7665 }else if(e.clientY > v.h - dojo.dnd.V_TRIGGER_AUTOSCROLL){
7666 dy = dojo.dnd.V_AUTOSCROLL_VALUE;
7668 window.scrollBy(dx, dy);
7671 dojo.dnd._validNodes = {"div
": 1, "p
": 1, "td
": 1};
7672 dojo.dnd._validOverflow = {"auto
": 1, "scroll
": 1};
7674 dojo.dnd.autoScrollNodes = function(e){
7676 // a handler for onmousemove event, which scrolls the first avaialble
7677 // Dom element, it falls back to dojo.dnd.autoScroll()
7679 // onmousemove event
7681 // FIXME: needs more docs!
7682 for(var n = e.target; n;){
7683 if(n.nodeType == 1 && (n.tagName.toLowerCase() in dojo.dnd._validNodes)){
7684 var s = dojo.getComputedStyle(n);
7685 if(s.overflow.toLowerCase() in dojo.dnd._validOverflow){
7686 var b = dojo._getContentBox(n, s), t = dojo.position(n, true);
7687 //console.log(b.l, b.t, t.x, t.y, n.scrollLeft, n.scrollTop);
7688 var w = Math.min(dojo.dnd.H_TRIGGER_AUTOSCROLL, b.w / 2),
7689 h = Math.min(dojo.dnd.V_TRIGGER_AUTOSCROLL, b.h / 2),
7690 rx = e.pageX - t.x, ry = e.pageY - t.y, dx = 0, dy = 0;
7691 if(dojo.isWebKit || dojo.isOpera){
7692 // FIXME: this code should not be here, it should be taken into account
7693 // either by the event fixing code, or the dojo.position()
7694 // FIXME: this code doesn't work on Opera 9.5 Beta
7695 rx += dojo.body().scrollLeft, ry += dojo.body().scrollTop;
7697 if(rx > 0 && rx < b.w){
7700 }else if(rx > b.w - w){
7704 //console.log("ry
=", ry, "b
.h
=", b.h, "h
=", h);
7705 if(ry > 0 && ry < b.h){
7708 }else if(ry > b.h - h){
7712 var oldLeft = n.scrollLeft, oldTop = n.scrollTop;
7713 n.scrollLeft = n.scrollLeft + dx;
7714 n.scrollTop = n.scrollTop + dy;
7715 if(oldLeft != n.scrollLeft || oldTop != n.scrollTop){ return; }
7724 dojo.dnd.autoScroll(e);
7729 if(!dojo._hasResource["dojo
.dnd
.Mover
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
7730 dojo._hasResource["dojo
.dnd
.Mover
"] = true;
7731 dojo.provide("dojo
.dnd
.Mover
");
7736 dojo.declare("dojo
.dnd
.Mover
", null, {
7737 constructor: function(node, e, host){
7739 // an object, which makes a node follow the mouse.
7740 // Used as a default mover, and as a base class for custom movers.
7742 // a node (or node's id) to be moved
7744 // a mouse event, which started the move;
7745 // only pageX and pageY properties are used
7747 // object which implements the functionality of the move,
7748 // and defines proper events (onMoveStart and onMoveStop)
7749 this.node = dojo.byId(node);
7750 this.marginBox = {l: e.pageX, t: e.pageY};
7751 this.mouseButton = e.button;
7752 var h = this.host = host, d = node.ownerDocument,
7753 firstEvent = dojo.connect(d, "onmousemove
", this, "onFirstMove
");
7755 dojo.connect(d, "onmousemove
", this, "onMouseMove
"),
7756 dojo.connect(d, "onmouseup
", this, "onMouseUp
"),
7757 // cancel text selection and text dragging
7758 dojo.connect(d, "ondragstart
", dojo.stopEvent),
7759 dojo.connect(d.body, "onselectstart
", dojo.stopEvent),
7762 // notify that the move has started
7763 if(h && h.onMoveStart){
7764 h.onMoveStart(this);
7767 // mouse event processors
7768 onMouseMove: function(e){
7770 // event processor for onmousemove
7773 dojo.dnd.autoScroll(e);
7774 var m = this.marginBox;
7775 this.host.onMove(this, {l: m.l + e.pageX, t: m.t + e.pageY}, e);
7778 onMouseUp: function(e){
7779 if(dojo.isWebKit && dojo.isMac && this.mouseButton == 2 ?
7780 e.button == 0 : this.mouseButton == e.button){
7786 onFirstMove: function(e){
7788 // makes the node absolute; it is meant to be called only once.
7789 // relative and absolutely positioned nodes are assumed to use pixel units
7790 var s = this.node.style, l, t, h = this.host;
7794 // assume that left and top values are in pixels already
7795 l = Math.round(parseFloat(s.left)) || 0;
7796 t = Math.round(parseFloat(s.top)) || 0;
7799 s.position = "absolute
"; // enforcing the absolute mode
7800 var m = dojo.marginBox(this.node);
7801 // event.pageX/pageY (which we used to generate the initial
7802 // margin box) includes padding and margin set on the body.
7803 // However, setting the node's position to absolute and then
7804 // doing dojo.marginBox on it *doesn't* take that additional
7805 // space into account - so we need to subtract the combined
7806 // padding and margin. We use getComputedStyle and
7807 // _getMarginBox/_getContentBox to avoid the extra lookup of
7808 // the computed style.
7809 var b = dojo.doc.body;
7810 var bs = dojo.getComputedStyle(b);
7811 var bm = dojo._getMarginBox(b, bs);
7812 var bc = dojo._getContentBox(b, bs);
7813 l = m.l - (bc.l - bm.l);
7814 t = m.t - (bc.t - bm.t);
7817 this.marginBox.l = l - this.marginBox.l;
7818 this.marginBox.t = t - this.marginBox.t;
7819 if(h && h.onFirstMove){
7820 h.onFirstMove(this, e);
7822 dojo.disconnect(this.events.pop());
7824 destroy: function(){
7826 // stops the move, deletes all references, so the object can be garbage-collected
7827 dojo.forEach(this.events, dojo.disconnect);
7828 // undo global settings
7830 if(h && h.onMoveStop){
7834 this.events = this.node = this.host = null;
7840 if(!dojo._hasResource["dojo
.dnd
.Moveable
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
7841 dojo._hasResource["dojo
.dnd
.Moveable
"] = true;
7842 dojo.provide("dojo
.dnd
.Moveable
");
7847 dojo.declare("dojo
.dnd
.__MoveableArgs
", [], {
7848 // handle: Node||String
7849 // A node (or node's id), which is used as a mouse handle.
7850 // If omitted, the node itself is used as a handle.
7854 // delay move by this number of pixels
7858 // skip move of form elements
7862 // a constructor of custom Mover
7863 mover: dojo.dnd.Mover
7867 dojo.declare("dojo
.dnd
.Moveable
", null, {
7868 // object attributes (for markup)
7873 constructor: function(node, params){
7875 // an object, which makes a node moveable
7877 // a node (or node's id) to be moved
7878 // params: dojo.dnd.__MoveableArgs?
7879 // optional parameters
7880 this.node = dojo.byId(node);
7881 if(!params){ params = {}; }
7882 this.handle = params.handle ? dojo.byId(params.handle) : null;
7883 if(!this.handle){ this.handle = this.node; }
7884 this.delay = params.delay > 0 ? params.delay : 0;
7885 this.skip = params.skip;
7886 this.mover = params.mover ? params.mover : dojo.dnd.Mover;
7888 dojo.connect(this.handle, "onmousedown
", this, "onMouseDown
"),
7889 // cancel text selection and text dragging
7890 dojo.connect(this.handle, "ondragstart
", this, "onSelectStart
"),
7891 dojo.connect(this.handle, "onselectstart
", this, "onSelectStart
")
7896 markupFactory: function(params, node){
7897 return new dojo.dnd.Moveable(node, params);
7901 destroy: function(){
7903 // stops watching for possible move, deletes all references, so the object can be garbage-collected
7904 dojo.forEach(this.events, dojo.disconnect);
7905 this.events = this.node = this.handle = null;
7908 // mouse event processors
7909 onMouseDown: function(e){
7911 // event processor for onmousedown, creates a Mover for the node
7914 if(this.skip && dojo.dnd.isFormElement(e)){ return; }
7917 dojo.connect(this.handle, "onmousemove
", this, "onMouseMove
"),
7918 dojo.connect(this.handle, "onmouseup
", this, "onMouseUp
")
7920 this._lastX = e.pageX;
7921 this._lastY = e.pageY;
7923 this.onDragDetected(e);
7927 onMouseMove: function(e){
7929 // event processor for onmousemove, used only for delayed drags
7932 if(Math.abs(e.pageX - this._lastX) > this.delay || Math.abs(e.pageY - this._lastY) > this.delay){
7934 this.onDragDetected(e);
7938 onMouseUp: function(e){
7940 // event processor for onmouseup, used only for delayed drags
7943 for(var i = 0; i < 2; ++i){
7944 dojo.disconnect(this.events.pop());
7948 onSelectStart: function(e){
7950 // event processor for onselectevent and ondragevent
7953 if(!this.skip || !dojo.dnd.isFormElement(e)){
7959 onDragDetected: function(/* Event */ e){
7961 // called when the drag is detected;
7962 // responsible for creation of the mover
7963 new this.mover(this.node, e, this);
7965 onMoveStart: function(/* dojo.dnd.Mover */ mover){
7967 // called before every move operation
7968 dojo.publish("/dnd/move/start
", [mover]);
7969 dojo.addClass(dojo.body(), "dojoMove
");
7970 dojo.addClass(this.node, "dojoMoveItem
");
7972 onMoveStop: function(/* dojo.dnd.Mover */ mover){
7974 // called after every move operation
7975 dojo.publish("/dnd/move/stop
", [mover]);
7976 dojo.removeClass(dojo.body(), "dojoMove
");
7977 dojo.removeClass(this.node, "dojoMoveItem
");
7979 onFirstMove: function(/* dojo.dnd.Mover */ mover, /* Event */ e){
7981 // called during the very first move notification;
7982 // can be used to initialize coordinates, can be overwritten.
7984 // default implementation does nothing
7986 onMove: function(/* dojo.dnd.Mover */ mover, /* Object */ leftTop, /* Event */ e){
7988 // called during every move notification;
7989 // should actually move the node; can be overwritten.
7990 this.onMoving(mover, leftTop);
7991 var s = mover.node.style;
7992 s.left = leftTop.l + "px
";
7993 s.top = leftTop.t + "px
";
7994 this.onMoved(mover, leftTop);
7996 onMoving: function(/* dojo.dnd.Mover */ mover, /* Object */ leftTop){
7998 // called before every incremental move; can be overwritten.
8000 // default implementation does nothing
8002 onMoved: function(/* dojo.dnd.Mover */ mover, /* Object */ leftTop){
8004 // called after every incremental move; can be overwritten.
8006 // default implementation does nothing
8012 if(!dojo._hasResource["dojo
.dnd
.move"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
8013 dojo._hasResource["dojo
.dnd
.move"] = true;
8014 dojo.provide("dojo
.dnd
.move");
8020 dojo.declare("dojo
.dnd
.move.__constrainedMoveableArgs
", [dojo.dnd.__MoveableArgs], {
8021 // constraints: Function
8022 // Calculates a constraint box.
8023 // It is called in a context of the moveable object.
8024 constraints: function(){},
8027 // restrict move within boundaries.
8032 dojo.declare("dojo
.dnd
.move.constrainedMoveable
", dojo.dnd.Moveable, {
8033 // object attributes (for markup)
8034 constraints: function(){},
8038 markupFactory: function(params, node){
8039 return new dojo.dnd.move.constrainedMoveable(node, params);
8042 constructor: function(node, params){
8044 // an object that makes a node moveable
8046 // a node (or node's id) to be moved
8047 // params: dojo.dnd.move.__constrainedMoveableArgs?
8048 // an optional object with additional parameters;
8049 // the rest is passed to the base class
8050 if(!params){ params = {}; }
8051 this.constraints = params.constraints;
8052 this.within = params.within;
8054 onFirstMove: function(/* dojo.dnd.Mover */ mover){
8056 // called during the very first move notification;
8057 // can be used to initialize coordinates, can be overwritten.
8058 var c = this.constraintBox = this.constraints.call(this, mover);
8062 var mb = dojo.marginBox(mover.node);
8067 onMove: function(/* dojo.dnd.Mover */ mover, /* Object */ leftTop){
8069 // called during every move notification;
8070 // should actually move the node; can be overwritten.
8071 var c = this.constraintBox, s = mover.node.style;
8072 s.left = (leftTop.l < c.l ? c.l : c.r < leftTop.l ? c.r : leftTop.l) + "px
";
8073 s.top = (leftTop.t < c.t ? c.t : c.b < leftTop.t ? c.b : leftTop.t) + "px
";
8078 dojo.declare("dojo
.dnd
.move.__boxConstrainedMoveableArgs
", [dojo.dnd.move.__constrainedMoveableArgs], {
8085 dojo.declare("dojo
.dnd
.move.boxConstrainedMoveable
", dojo.dnd.move.constrainedMoveable, {
8087 // object attributes (for markup)
8091 markupFactory: function(params, node){
8092 return new dojo.dnd.move.boxConstrainedMoveable(node, params);
8095 constructor: function(node, params){
8097 // an object, which makes a node moveable
8099 // a node (or node's id) to be moved
8100 // params: dojo.dnd.move.__boxConstrainedMoveableArgs?
8101 // an optional object with parameters
8102 var box = params && params.box;
8103 this.constraints = function(){ return box; };
8108 dojo.declare("dojo
.dnd
.move.__parentConstrainedMoveableArgs
", [dojo.dnd.move.__constrainedMoveableArgs], {
8110 // A parent's area to restrict the move.
8111 // Can be "margin
", "border
", "padding
", or "content
".
8116 dojo.declare("dojo
.dnd
.move.parentConstrainedMoveable
", dojo.dnd.move.constrainedMoveable, {
8118 // object attributes (for markup)
8122 markupFactory: function(params, node){
8123 return new dojo.dnd.move.parentConstrainedMoveable(node, params);
8126 constructor: function(node, params){
8128 // an object, which makes a node moveable
8130 // a node (or node's id) to be moved
8131 // params: dojo.dnd.move.__parentConstrainedMoveableArgs?
8132 // an optional object with parameters
8133 var area = params && params.area;
8134 this.constraints = function(){
8135 var n = this.node.parentNode,
8136 s = dojo.getComputedStyle(n),
8137 mb = dojo._getMarginBox(n, s);
8138 if(area == "margin
"){
8139 return mb; // Object
8141 var t = dojo._getMarginExtents(n, s);
8142 mb.l += t.l, mb.t += t.t, mb.w -= t.w, mb.h -= t.h;
8143 if(area == "border
"){
8144 return mb; // Object
8146 t = dojo._getBorderExtents(n, s);
8147 mb.l += t.l, mb.t += t.t, mb.w -= t.w, mb.h -= t.h;
8148 if(area == "padding
"){
8149 return mb; // Object
8151 t = dojo._getPadExtents(n, s);
8152 mb.l += t.l, mb.t += t.t, mb.w -= t.w, mb.h -= t.h;
8153 return mb; // Object
8158 // WARNING: below are obsolete objects, instead of custom movers use custom moveables (above)
8160 dojo.dnd.move.constrainedMover = function(fun, within){
8162 // returns a constrained version of dojo.dnd.Mover
8164 // this function produces n object, which will put a constraint on
8165 // the margin box of dragged object in absolute coordinates
8167 // called on drag, and returns a constraint box
8169 // if true, constraints the whole dragged object withtin the rectangle,
8170 // otherwise the constraint is applied to the left-top corner
8172 dojo.deprecated("dojo
.dnd
.move.constrainedMover
, use dojo
.dnd
.move.constrainedMoveable instead
");
8173 var mover = function(node, e, notifier){
8174 dojo.dnd.Mover.call(this, node, e, notifier);
8176 dojo.extend(mover, dojo.dnd.Mover.prototype);
8177 dojo.extend(mover, {
8178 onMouseMove: function(e){
8179 // summary: event processor for onmousemove
8180 // e: Event: mouse event
8181 dojo.dnd.autoScroll(e);
8182 var m = this.marginBox, c = this.constraintBox,
8183 l = m.l + e.pageX, t = m.t + e.pageY;
8184 l = l < c.l ? c.l : c.r < l ? c.r : l;
8185 t = t < c.t ? c.t : c.b < t ? c.b : t;
8186 this.host.onMove(this, {l: l, t: t});
8188 onFirstMove: function(){
8189 // summary: called once to initialize things; it is meant to be called only once
8190 dojo.dnd.Mover.prototype.onFirstMove.call(this);
8191 var c = this.constraintBox = fun.call(this);
8195 var mb = dojo.marginBox(this.node);
8201 return mover; // Object
8204 dojo.dnd.move.boxConstrainedMover = function(box, within){
8206 // a specialization of dojo.dnd.constrainedMover, which constrains to the specified box
8208 // a constraint box (l, t, w, h)
8210 // if true, constraints the whole dragged object withtin the rectangle,
8211 // otherwise the constraint is applied to the left-top corner
8213 dojo.deprecated("dojo
.dnd
.move.boxConstrainedMover
, use dojo
.dnd
.move.boxConstrainedMoveable instead
");
8214 return dojo.dnd.move.constrainedMover(function(){ return box; }, within); // Object
8217 dojo.dnd.move.parentConstrainedMover = function(area, within){
8219 // a specialization of dojo.dnd.constrainedMover, which constrains to the parent node
8221 // "margin
" to constrain within the parent's margin box, "border
" for the border box,
8222 // "padding
" for the padding box, and "content
" for the content box; "content
" is the default value.
8224 // if true, constraints the whole dragged object within the rectangle,
8225 // otherwise the constraint is applied to the left-top corner
8227 dojo.deprecated("dojo
.dnd
.move.parentConstrainedMover
, use dojo
.dnd
.move.parentConstrainedMoveable instead
");
8228 var fun = function(){
8229 var n = this.node.parentNode,
8230 s = dojo.getComputedStyle(n),
8231 mb = dojo._getMarginBox(n, s);
8232 if(area == "margin
"){
8233 return mb; // Object
8235 var t = dojo._getMarginExtents(n, s);
8236 mb.l += t.l, mb.t += t.t, mb.w -= t.w, mb.h -= t.h;
8237 if(area == "border
"){
8238 return mb; // Object
8240 t = dojo._getBorderExtents(n, s);
8241 mb.l += t.l, mb.t += t.t, mb.w -= t.w, mb.h -= t.h;
8242 if(area == "padding
"){
8243 return mb; // Object
8245 t = dojo._getPadExtents(n, s);
8246 mb.l += t.l, mb.t += t.t, mb.w -= t.w, mb.h -= t.h;
8247 return mb; // Object
8249 return dojo.dnd.move.constrainedMover(fun, within); // Object
8252 // patching functions one level up for compatibility
8254 dojo.dnd.constrainedMover = dojo.dnd.move.constrainedMover;
8255 dojo.dnd.boxConstrainedMover = dojo.dnd.move.boxConstrainedMover;
8256 dojo.dnd.parentConstrainedMover = dojo.dnd.move.parentConstrainedMover;
8260 if(!dojo._hasResource["dojo
.dnd
.TimedMoveable
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
8261 dojo._hasResource["dojo
.dnd
.TimedMoveable
"] = true;
8262 dojo.provide("dojo
.dnd
.TimedMoveable
");
8267 dojo.declare("dojo
.dnd
.__TimedMoveableArgs
", [dojo.dnd.__MoveableArgs], {
8269 // delay move by this number of ms,
8270 // accumulating position changes during the timeout
8276 // precalculate long expressions
8277 var oldOnMove = dojo.dnd.Moveable.prototype.onMove;
8279 dojo.declare("dojo
.dnd
.TimedMoveable
", dojo.dnd.Moveable, {
8281 // A specialized version of Moveable to support an FPS throttling.
8282 // This class puts an upper restriction on FPS, which may reduce
8283 // the CPU load. The additional parameter "timeout
" regulates
8284 // the delay before actually moving the moveable object.
8286 // object attributes (for markup)
8287 timeout: 40, // in ms, 40ms corresponds to 25 fps
8289 constructor: function(node, params){
8291 // an object that makes a node moveable with a timer
8292 // node: Node||String
8293 // a node (or node's id) to be moved
8294 // params: dojo.dnd.__TimedMoveableArgs
8295 // object with additional parameters.
8297 // sanitize parameters
8298 if(!params){ params = {}; }
8299 if(params.timeout && typeof params.timeout == "number
" && params.timeout >= 0){
8300 this.timeout = params.timeout;
8305 markupFactory: function(params, node){
8306 return new dojo.dnd.TimedMoveable(node, params);
8309 onMoveStop: function(/* dojo.dnd.Mover */ mover){
8312 clearTimeout(mover._timer)
8313 // reflect the last received position
8314 oldOnMove.call(this, mover, mover._leftTop)
8316 dojo.dnd.Moveable.prototype.onMoveStop.apply(this, arguments);
8318 onMove: function(/* dojo.dnd.Mover */ mover, /* Object */ leftTop){
8319 mover._leftTop = leftTop;
8321 var _t = this; // to avoid using dojo.hitch()
8322 mover._timer = setTimeout(function(){
8323 // we don't have any pending requests
8324 mover._timer = null;
8325 // reflect the last received position
8326 oldOnMove.call(_t, mover, mover._leftTop);
8335 if(!dojo._hasResource["dijit
.form
._FormMixin
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
8336 dojo._hasResource["dijit
.form
._FormMixin
"] = true;
8337 dojo.provide("dijit
.form
._FormMixin
");
8341 dojo.declare("dijit
.form
._FormMixin
", null,
8344 // Mixin for containers of form widgets (i.e. widgets that represent a single value
8345 // and can be children of a <form> node or dijit.form.Form widget)
8347 // Can extract all the form widgets
8348 // values and combine them into a single javascript object, or alternately
8349 // take such an object and set the values for all the contained
8354 // Name/value hash for each child widget with a name and value.
8355 // Child widgets without names are not part of the hash.
8357 // If there are multiple child widgets w/the same name, value is an array,
8358 // unless they are radio buttons in which case value is a scalar (since only
8359 // one radio button can be checked at a time).
8361 // If a child widget's name is a dot separated list (like a.b.c.d), it's a nested structure.
8364 // | { name: "John Smith
", interests: ["sports
", "movies
"] }
8369 // * better handling for arrays. Often form elements have names with [] like
8370 // * people[3].sex (for a list of people [{name: Bill, sex: M}, ...])
8375 dojo.forEach(this.getDescendants(), function(widget){
8382 validate: function(){
8384 // returns if the form is valid - same as isValid - but
8385 // provides a few additional (ui-specific) features.
8386 // 1 - it will highlight any sub-widgets that are not
8388 // 2 - it will call focus() on the first invalid
8390 var didFocus = false;
8391 return dojo.every(dojo.map(this.getDescendants(), function(widget){
8392 // Need to set this so that "required
" widgets get their
8394 widget._hasBeenBlurred = true;
8395 var valid = widget.disabled || !widget.validate || widget.validate();
8396 if(!valid && !didFocus){
8397 // Set focus of the first non-valid widget
8398 dojo.window.scrollIntoView(widget.containerNode || widget.domNode);
8403 }), function(item){ return item; });
8406 setValues: function(val){
8407 dojo.deprecated(this.declaredClass+"::setValues() is deprecated
. Use
set('value', val
) instead
.", "", "2.0");
8408 return this.set('value', val);
8410 _setValueAttr: function(/*object*/obj){
8412 // Fill in form values from according to an Object (in the format returned by attr('value'))
8414 // generate map from name --> [list of widgets with that name]
8416 dojo.forEach(this.getDescendants(), function(widget){
8417 if(!widget.name){ return; }
8418 var entry = map[widget.name] || (map[widget.name] = [] );
8422 for(var name in map){
8423 if(!map.hasOwnProperty(name)){
8426 var widgets = map[name], // array of widgets w/this name
8427 values = dojo.getObject(name, false, obj); // list of values for those widgets
8429 if(values === undefined){
8432 if(!dojo.isArray(values)){
8433 values = [ values ];
8435 if(typeof widgets[0].checked == 'boolean'){
8436 // for checkbox/radio, values is a list of which widgets should be checked
8437 dojo.forEach(widgets, function(w, i){
8438 w.set('value', dojo.indexOf(values, w.value) != -1);
8440 }else if(widgets[0].multiple){
8441 // it takes an array (e.g. multi-select)
8442 widgets[0].set('value', values);
8444 // otherwise, values is a list of values to be assigned sequentially to each widget
8445 dojo.forEach(widgets, function(w, i){
8446 w.set('value', values[i]);
8452 * TODO: code for plain input boxes (this shouldn't run for inputs that are part of widgets)
8454 dojo.forEach(this.containerNode.elements, function(element){
8455 if(element.name == ''){return}; // like "continue"
8456 var namePath = element.name.split(".");
8458 var name=namePath[namePath.length-1];
8459 for(var j=1,len2=namePath.length;j<len2;++j){
8460 var p=namePath[j - 1];
8461 // repeater support block
8462 var nameA=p.split("[");
8463 if(nameA.length > 1){
8464 if(typeof(myObj[nameA[0]]) == "undefined"){
8465 myObj[nameA[0]]=[ ];
8468 nameIndex=parseInt(nameA[1]);
8469 if(typeof(myObj[nameA[0]][nameIndex]) == "undefined"){
8470 myObj[nameA[0]][nameIndex] = { };
8472 myObj=myObj[nameA[0]][nameIndex];
8474 } // repeater support ends
8476 if(typeof(myObj[p]) == "undefined"){
8483 if(typeof(myObj) == "undefined"){
8484 return; // like "continue"
8486 if(typeof(myObj[name]) == "undefined" && this.ignoreNullValues){
8487 return; // like "continue"
8490 // TODO: widget values (just call attr('value', ...) on the widget)
8492 // TODO: maybe should call dojo.getNodeProp() instead
8493 switch(element.type){
8495 element.checked = (name in myObj) &&
8496 dojo.some(myObj[name], function(val){ return val == element.value; });
8499 element.checked = (name in myObj) && myObj[name] == element.value;
8501 case "select
-multiple
":
8502 element.selectedIndex=-1;
8503 dojo.forEach(element.options, function(option){
8504 option.selected = dojo.some(myObj[name], function(val){ return option.value == val; });
8508 element.selectedIndex="0";
8509 dojo.forEach(element.options, function(option){
8510 option.selected = option.value == myObj[name];
8517 element.value = myObj[name] || "";
8524 getValues: function(){
8525 dojo.deprecated(this.declaredClass+"::getValues() is deprecated
. Use
get('value') instead
.", "", "2.0");
8526 return this.get('value');
8528 _getValueAttr: function(){
8530 // Returns Object representing form values.
8532 // Returns name/value hash for each form element.
8533 // If there are multiple elements w/the same name, value is an array,
8534 // unless they are radio buttons in which case value is a scalar since only
8535 // one can be checked at a time.
8537 // If the name is a dot separated list (like a.b.c.d), creates a nested structure.
8538 // Only works on widget form elements.
8540 // | { name: "John Smith
", interests: ["sports
", "movies
"] }
8542 // get widget values
8544 dojo.forEach(this.getDescendants(), function(widget){
8545 var name = widget.name;
8546 if(!name || widget.disabled){ return; }
8548 // Single value widget (checkbox, radio, or plain <input> type widget
8549 var value = widget.get('value');
8551 // Store widget's value(s) as a scalar, except for checkboxes which are automatically arrays
8552 if(typeof widget.checked == 'boolean'){
8553 if(/Radio/.test(widget.declaredClass)){
8555 if(value !== false){
8556 dojo.setObject(name, value, obj);
8558 // give radio widgets a default of null
8559 value = dojo.getObject(name, false, obj);
8560 if(value === undefined){
8561 dojo.setObject(name, null, obj);
8565 // checkbox/toggle button
8566 var ary=dojo.getObject(name, false, obj);
8569 dojo.setObject(name, ary, obj);
8571 if(value !== false){
8576 var prev=dojo.getObject(name, false, obj);
8577 if(typeof prev != "undefined"){
8578 if(dojo.isArray(prev)){
8581 dojo.setObject(name, [prev, value], obj);
8585 dojo.setObject(name, value, obj);
8591 * code for plain input boxes (see also dojo.formToObject, can we use that instead of this code?
8592 * but it doesn't understand [] notation, presumably)
8594 dojo.forEach(this.containerNode.elements, function(elm){
8596 return; // like "continue"
8598 var namePath = elm.name.split(".");
8600 var name=namePath[namePath.length-1];
8601 for(var j=1,len2=namePath.length;j<len2;++j){
8602 var nameIndex = null;
8603 var p=namePath[j - 1];
8604 var nameA=p.split("[");
8605 if(nameA.length > 1){
8606 if(typeof(myObj[nameA[0]]) == "undefined"){
8607 myObj[nameA[0]]=[ ];
8609 nameIndex=parseInt(nameA[1]);
8610 if(typeof(myObj[nameA[0]][nameIndex]) == "undefined"){
8611 myObj[nameA[0]][nameIndex] = { };
8613 } else if(typeof(myObj[nameA[0]]) == "undefined"){
8614 myObj[nameA[0]] = { }
8617 if(nameA.length == 1){
8618 myObj=myObj[nameA[0]];
8620 myObj=myObj[nameA[0]][nameIndex];
8624 if((elm.type != "select
-multiple
" && elm.type != "checkbox
" && elm.type != "radio
") || (elm.type == "radio
" && elm.checked)){
8625 if(name == name.split("[")[0]){
8626 myObj[name]=elm.value;
8628 // can not set value when there is no name
8630 } else if(elm.type == "checkbox
" && elm.checked){
8631 if(typeof(myObj[name]) == 'undefined'){
8634 myObj[name].push(elm.value);
8635 } else if(elm.type == "select
-multiple
"){
8636 if(typeof(myObj[name]) == 'undefined'){
8639 for(var jdx=0,len3=elm.options.length; jdx<len3; ++jdx){
8640 if(elm.options[jdx].selected){
8641 myObj[name].push(elm.options[jdx].value);
8651 // TODO: ComboBox might need time to process a recently input value. This should be async?
8652 isValid: function(){
8654 // Returns true if all of the widgets are valid
8656 // This also populate this._invalidWidgets[] array with list of invalid widgets...
8657 // TODO: put that into separate function? It's confusing to have that as a side effect
8658 // of a method named isValid().
8660 this._invalidWidgets = dojo.filter(this.getDescendants(), function(widget){
8661 return !widget.disabled && widget.isValid && !widget.isValid();
8663 return !this._invalidWidgets.length;
8667 onValidStateChange: function(isValid){
8669 // Stub function to connect to if you want to do something
8670 // (like disable/enable a submit button) when the valid
8671 // state changes on the form as a whole.
8674 _widgetChange: function(widget){
8676 // Connected to a widget's onChange function - update our
8677 // valid state, if needed.
8678 var isValid = this._lastValidState;
8679 if(!widget || this._lastValidState === undefined){
8680 // We have passed a null widget, or we haven't been validated
8681 // yet - let's re-check all our children
8682 // This happens when we connect (or reconnect) our children
8683 isValid = this.isValid();
8684 if(this._lastValidState === undefined){
8685 // Set this so that we don't fire an onValidStateChange
8687 this._lastValidState = isValid;
8689 }else if(widget.isValid){
8690 this._invalidWidgets = dojo.filter(this._invalidWidgets || [], function(w){
8691 return (w != widget);
8693 if(!widget.isValid() && !widget.get("disabled
")){
8694 this._invalidWidgets.push(widget);
8696 isValid = (this._invalidWidgets.length === 0);
8698 if(isValid !== this._lastValidState){
8699 this._lastValidState = isValid;
8700 this.onValidStateChange(isValid);
8704 connectChildren: function(){
8706 // Connects to the onChange function of all children to
8707 // track valid state changes. You can call this function
8708 // directly, ex. in the event that you programmatically
8709 // add a widget to the form *after* the form has been
8711 dojo.forEach(this._changeConnections, dojo.hitch(this, "disconnect
"));
8714 // we connect to validate - so that it better reflects the states
8715 // of the widgets - also, we only connect if it has a validate
8716 // function (to avoid too many unneeded connections)
8717 var conns = (this._changeConnections = []);
8718 dojo.forEach(dojo.filter(this.getDescendants(),
8719 function(item){ return item.validate; }
8722 // We are interested in whenever the widget is validated - or
8723 // whenever the disabled attribute on that widget is changed
8724 conns.push(_this.connect(widget, "validate
",
8725 dojo.hitch(_this, "_widgetChange
", widget)));
8726 conns.push(_this.connect(widget, "_setDisabledAttr
",
8727 dojo.hitch(_this, "_widgetChange
", widget)));
8730 // Call the widget change function to update the valid state, in
8731 // case something is different now.
8732 this._widgetChange(null);
8735 startup: function(){
8736 this.inherited(arguments);
8737 // Initialize our valid state tracking. Needs to be done in startup
8738 // because it's not guaranteed that our children are initialized
8740 this._changeConnections = [];
8741 this.connectChildren();
8747 if(!dojo._hasResource["dijit
._DialogMixin
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
8748 dojo._hasResource["dijit
._DialogMixin
"] = true;
8749 dojo.provide("dijit
._DialogMixin
");
8753 dojo.declare("dijit
._DialogMixin
", null,
8756 // This provides functions useful to Dialog and TooltipDialog
8758 attributeMap: dijit._Widget.prototype.attributeMap,
8760 execute: function(/*Object*/ formContents){
8762 // Callback when the user hits the submit button.
8763 // Override this method to handle Dialog execution.
8765 // After the user has pressed the submit button, the Dialog
8766 // first calls onExecute() to notify the container to hide the
8767 // dialog and restore focus to wherever it used to be.
8769 // *Then* this method is called.
8774 onCancel: function(){
8776 // Called when user has pressed the Dialog's cancel button, to notify container.
8778 // Developer shouldn't override or connect to this method;
8779 // it's a private communication device between the TooltipDialog
8780 // and the thing that opened it (ex: `dijit.form.DropDownButton`)
8785 onExecute: function(){
8787 // Called when user has pressed the dialog's OK button, to notify container.
8789 // Developer shouldn't override or connect to this method;
8790 // it's a private communication device between the TooltipDialog
8791 // and the thing that opened it (ex: `dijit.form.DropDownButton`)
8796 _onSubmit: function(){
8798 // Callback when user hits submit button
8801 this.onExecute(); // notify container that we are about to execute
8802 this.execute(this.get('value'));
8805 _getFocusItems: function(/*Node*/ dialogNode){
8807 // Find focusable Items each time a dialog is opened,
8808 // setting _firstFocusItem and _lastFocusItem
8812 var elems = dijit._getTabNavigable(dojo.byId(dialogNode));
8813 this._firstFocusItem = elems.lowest || elems.first || dialogNode;
8814 this._lastFocusItem = elems.last || elems.highest || this._firstFocusItem;
8815 if(dojo.isMoz && this._firstFocusItem.tagName.toLowerCase() == "input
" &&
8816 dojo.getNodeProp(this._firstFocusItem, "type
").toLowerCase() == "file
"){
8817 // FF doesn't behave well when first element is input type=file, set first focusable to dialog container
8818 dojo.attr(dialogNode, "tabIndex
", "0");
8819 this._firstFocusItem = dialogNode;
8827 if(!dojo._hasResource["dijit
.DialogUnderlay
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
8828 dojo._hasResource["dijit
.DialogUnderlay
"] = true;
8829 dojo.provide("dijit
.DialogUnderlay
");
8837 "dijit
.DialogUnderlay
",
8838 [dijit._Widget, dijit._Templated],
8841 // The component that blocks the screen behind a `dijit.Dialog`
8844 // A component used to block input behind a `dijit.Dialog`. Only a single
8845 // instance of this widget is created by `dijit.Dialog`, and saved as
8846 // a reference to be shared between all Dialogs as `dijit._underlay`
8848 // The underlay itself can be styled based on and id:
8849 // | #myDialog_underlay { background-color:red; }
8851 // In the case of `dijit.Dialog`, this id is based on the id of the Dialog,
8852 // suffixed with _underlay.
8854 // Template has two divs; outer div is used for fade-in/fade-out, and also to hold background iframe.
8855 // Inner div has opacity specified in CSS file.
8856 templateString: "<div
class='dijitDialogUnderlayWrapper'><div
class='dijitDialogUnderlay' dojoAttachPoint
='node'></div></div>",
8858 // Parameters on creation or updatable later
8861 // Id of the dialog.... DialogUnderlay's id is based on this id
8865 // This class name is used on the DialogUnderlay node, in addition to dijitDialogUnderlay
8868 attributeMap: { id: "domNode
" },
8870 _setDialogIdAttr: function(id){
8871 dojo.attr(this.node, "id
", id + "_underlay
");
8874 _setClassAttr: function(clazz){
8875 this.node.className = "dijitDialogUnderlay
" + clazz;
8878 postCreate: function(){
8880 // Append the underlay to the body
8881 dojo.body().appendChild(this.domNode);
8886 // Sets the background to the size of the viewport
8889 // Sets the background to the size of the viewport (rather than the size
8890 // of the document) since we need to cover the whole browser window, even
8891 // if the document is only a few lines long.
8895 var is = this.node.style,
8896 os = this.domNode.style;
8898 // hide the background temporarily, so that the background itself isn't
8899 // causing scrollbars to appear (might happen when user shrinks browser
8900 // window and then we are called to resize)
8901 os.display = "none
";
8903 // then resize and show
8904 var viewport = dojo.window.getBox();
8905 os.top = viewport.t + "px
";
8906 os.left = viewport.l + "px
";
8907 is.width = viewport.w + "px
";
8908 is.height = viewport.h + "px
";
8909 os.display = "block
";
8914 // Show the dialog underlay
8915 this.domNode.style.display = "block
";
8917 this.bgIframe = new dijit.BackgroundIframe(this.domNode);
8922 // Hides the dialog underlay
8923 this.bgIframe.destroy();
8924 this.domNode.style.display = "none
";
8927 uninitialize: function(){
8929 this.bgIframe.destroy();
8931 this.inherited(arguments);
8938 if(!dojo._hasResource["dojo
.html
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
8939 dojo._hasResource["dojo
.html
"] = true;
8940 dojo.provide("dojo
.html
");
8942 // the parser might be needed..
8945 (function(){ // private scope, sort of a namespace
8947 // idCounter is incremented with each instantiation to allow asignment of a unique id for tracking, logging purposes
8951 dojo.html._secureForInnerHtml = function(/*String*/ cont){
8953 // removes !DOCTYPE and title elements from the html string.
8955 // khtml is picky about dom faults, you can't attach a style or <title> node as child of body
8956 // must go into head, so we need to cut out those tags
8958 // An html string for insertion into the dom
8960 return cont.replace(/(?:\s*<!DOCTYPE\s[^>]+>|<title[^>]*>[\s\S]*?<\/title>)/ig, ""); // String
8964 dojo.html._emptyNode = function(node){
8966 // removes all child nodes from the given node
8968 // the parent element
8971 dojo.html._emptyNode = dojo.empty;
8973 dojo.html._setNodeContent = function(/* DomNode */ node, /* String|DomNode|NodeList */ cont){
8975 // inserts the given content into the given node
8977 // the parent element
8979 // the content to be set on the parent element.
8980 // This can be an html string, a node reference or a NodeList, dojo.NodeList, Array or other enumerable list of nodes
8986 if(typeof cont == "string
") {
8987 cont = d._toDom(cont, node.ownerDocument);
8989 if(!cont.nodeType && d.isArrayLike(cont)) {
8990 // handle as enumerable, but it may shrink as we enumerate it
8991 for(var startlen=cont.length, i=0; i<cont.length; i=startlen==cont.length ? i+1 : 0) {
8992 d.place( cont[i], node, "last
");
8995 // pass nodes, documentFragments and unknowns through to dojo.place
8996 d.place(cont, node, "last
");
9004 // we wrap up the content-setting operation in a object
9005 dojo.declare("dojo
.html
._ContentSetter
", null,
9007 // node: DomNode|String
9008 // An node which will be the parent element that we set content into
9011 // content: String|DomNode|DomNode[]
9012 // The content to be placed in the node. Can be an HTML string, a node reference, or a enumerable list of nodes
9016 // Usually only used internally, and auto-generated with each instance
9019 // cleanContent: Boolean
9020 // Should the content be treated as a full html document,
9021 // and the real content stripped of <html>, <body> wrapper before injection
9022 cleanContent: false,
9024 // extractContent: Boolean
9025 // Should the content be treated as a full html document, and the real content stripped of <html>, <body> wrapper before injection
9026 extractContent: false,
9028 // parseContent: Boolean
9029 // Should the node by passed to the parser after the new content is set
9030 parseContent: false,
9033 constructor: function(/* Object */params, /* String|DomNode */node){
9035 // Provides a configurable, extensible object to wrap the setting on content on a node
9036 // call the set() method to actually set the content..
9038 // the original params are mixed directly into the instance "this"
9039 dojo.mixin(this, params || {});
9041 // give precedence to params.node vs. the node argument
9042 // and ensure its a node, not an id string
9043 node = this.node = dojo.byId( this.node || node );
9048 (node) ? node.id || node.tagName : "",
9053 set: function(/* String|DomNode|NodeList? */ cont, /* Object? */ params){
9055 // front-end to the set-content sequence
9057 // An html string, node or enumerable list of nodes for insertion into the dom
9058 // If not provided, the object's content property will be used
9059 if(undefined !== cont){
9060 this.content = cont;
9062 // in the re-use scenario, set needs to be able to mixin new configuration
9064 this._mixin(params);
9073 setContent: function(){
9075 // sets the content on the node
9077 var node = this.node;
9080 throw new Error(this.declaredClass + ": setContent given no node
");
9083 node = dojo.html._setNodeContent(node, this.content);
9085 // check if a domfault occurs when we are appending this.errorMessage
9086 // like for instance if domNode is a UL and we try append a DIV
9088 // FIXME: need to allow the user to provide a content error message string
9089 var errMess = this.onContentError(e);
9091 node.innerHTML = errMess;
9093 console.error('Fatal ' + this.declaredClass + '.setContent could not change content due to '+e.message, e);
9096 // always put back the node for the next method
9097 this.node = node; // DomNode
9102 // cleanly empty out existing content
9104 // destroy any widgets from a previous run
9105 // NOTE: if you dont want this you'll need to empty
9106 // the parseResults array property yourself to avoid bad things happenning
9107 if(this.parseResults && this.parseResults.length) {
9108 dojo.forEach(this.parseResults, function(w) {
9113 delete this.parseResults;
9115 // this is fast, but if you know its already empty or safe, you could
9116 // override empty to skip this step
9117 dojo.html._emptyNode(this.node);
9120 onBegin: function(){
9122 // Called after instantiation, but before set();
9123 // It allows modification of any of the object properties
9124 // - including the node and content provided - before the set operation actually takes place
9125 // This default implementation checks for cleanContent and extractContent flags to
9126 // optionally pre-process html string content
9127 var cont = this.content;
9129 if(dojo.isString(cont)){
9130 if(this.cleanContent){
9131 cont = dojo.html._secureForInnerHtml(cont);
9134 if(this.extractContent){
9135 var match = cont.match(/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im);
9136 if(match){ cont = match[1]; }
9140 // clean out the node and any cruft associated with it - like widgets
9143 this.content = cont;
9144 return this.node; /* DomNode */
9149 // Called after set(), when the new content has been pushed into the node
9150 // It provides an opportunity for post-processing before handing back the node to the caller
9151 // This default implementation checks a parseContent flag to optionally run the dojo parser over the new content
9152 if(this.parseContent){
9153 // populates this.parseResults if you need those..
9156 return this.node; /* DomNode */
9159 tearDown: function(){
9161 // manually reset the Setter instance if its being re-used for example for another set()
9163 // tearDown() is not called automatically.
9164 // In normal use, the Setter instance properties are simply allowed to fall out of scope
9165 // but the tearDown method can be called to explicitly reset this instance.
9166 delete this.parseResults;
9168 delete this.content;
9171 onContentError: function(err){
9172 return "Error occured setting content
: " + err;
9175 _mixin: function(params){
9176 // mix properties/methods into the instance
9177 // TODO: the intention with tearDown is to put the Setter's state
9178 // back to that of the original constructor (vs. deleting/resetting everything regardless of ctor params)
9179 // so we could do something here to move the original properties aside for later restoration
9180 var empty = {}, key;
9182 if(key in empty){ continue; }
9183 // TODO: here's our opportunity to mask the properties we dont consider configurable/overridable
9184 // .. but history shows we'll almost always guess wrong
9185 this[key] = params[key];
9190 // runs the dojo parser over the node contents, storing any results in this.parseResults
9191 // Any errors resulting from parsing are passed to _onError for handling
9193 var rootNode = this.node;
9195 // store the results (widgets, whatever) for potential retrieval
9196 this.parseResults = dojo.parser.parse({
9202 this._onError('Content', e, "Error parsing
in _ContentSetter
#"+this.id);
9206 _onError: function(type, err, consoleText){
9208 // shows user the string that is returned by on[type]Error
9209 // overide/implement on[type]Error and return your own string to customize
9210 var errText = this['on' + type + 'Error'].call(this, err);
9212 console.error(consoleText, err);
9213 }else if(errText){ // a empty string won't change current content
9214 dojo.html._setNodeContent(this.node, errText, true);
9217 }); // end dojo.declare()
9219 dojo.html.set = function(/* DomNode */ node, /* String|DomNode|NodeList */ cont, /* Object? */ params){
9221 // inserts (replaces) the given content into the given node. dojo.place(cont, node, "only
")
9222 // may be a better choice for simple HTML insertion.
9224 // Unless you need to use the params capabilities of this method, you should use
9225 // dojo.place(cont, node, "only
"). dojo.place() has more robust support for injecting
9226 // an HTML string into the DOM, but it only handles inserting an HTML string as DOM
9227 // elements, or inserting a DOM node. dojo.place does not handle NodeList insertions
9228 // or the other capabilities as defined by the params object for this method.
9230 // the parent element that will receive the content
9232 // the content to be set on the parent element.
9233 // This can be an html string, a node reference or a NodeList, dojo.NodeList, Array or other enumerable list of nodes
9235 // Optional flags/properties to configure the content-setting. See dojo.html._ContentSetter
9237 // A safe string/node/nodelist content replacement/injection with hooks for extension
9239 // dojo.html.set(node, "some string
");
9240 // dojo.html.set(node, contentNode, {options});
9241 // dojo.html.set(node, myNode.childNodes, {options});
9242 if(undefined == cont){
9243 console.warn("dojo
.html
.set: no cont argument provided
, using empty string
");
9248 return dojo.html._setNodeContent(node, cont, true);
9250 // more options but slower
9251 // note the arguments are reversed in order, to match the convention for instantiation via the parser
9252 var op = new dojo.html._ContentSetter(dojo.mixin(
9254 { content: cont, node: node }
9263 if(!dojo._hasResource["dijit
.layout
.ContentPane
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
9264 dojo._hasResource["dijit
.layout
.ContentPane
"] = true;
9265 dojo.provide("dijit
.layout
.ContentPane
");
9269 // for dijit.layout.marginBox2contentBox()
9277 "dijit
.layout
.ContentPane
", dijit._Widget,
9280 // A widget that acts as a container for mixed HTML and widgets, and includes an Ajax interface
9282 // A widget that can be used as a stand alone widget
9283 // or as a base class for other widgets.
9285 // Handles replacement of document fragment using either external uri or javascript
9286 // generated markup or DOM content, instantiating widgets within that content.
9287 // Don't confuse it with an iframe, it only needs/wants document fragments.
9288 // It's useful as a child of LayoutContainer, SplitContainer, or TabContainer.
9289 // But note that those classes can contain any widget as a child.
9291 // Some quick samples:
9292 // To change the innerHTML use .set('content', '<b>new content</b>')
9294 // Or you can send it a NodeList, .set('content', dojo.query('div [class=selected]', userSelection))
9295 // please note that the nodes in NodeList will copied, not moved
9297 // To do a ajax update use .set('href', url)
9300 // The href of the content that displays now.
9301 // Set this at construction if you want to load data externally when the
9302 // pane is shown. (Set preload=true to load it immediately.)
9303 // Changing href after creation doesn't have any effect; Use set('href', ...);
9307 // content: String || DomNode || NodeList || dijit._Widget
9308 // The innerHTML of the ContentPane.
9309 // Note that the initialization parameter / argument to attr("content
", ...)
9310 // can be a String, DomNode, Nodelist, or _Widget.
9314 // extractContent: Boolean
9315 // Extract visible content from inside of <body> .... </body>.
9316 // I.e., strip <html> and <head> (and it's contents) from the href
9317 extractContent: false,
9319 // parseOnLoad: Boolean
9320 // Parse content and create the widgets, if any.
9323 // preventCache: Boolean
9324 // Prevent caching of data from href's by appending a timestamp to the href.
9325 preventCache: false,
9328 // Force load of data on initialization even if pane is hidden.
9331 // refreshOnShow: Boolean
9332 // Refresh (re-download) content when pane goes from hidden to shown
9333 refreshOnShow: false,
9335 // loadingMessage: String
9336 // Message that shows while downloading
9337 loadingMessage: "<span
class='dijitContentPaneLoading'>${loadingState}
</span
>",
9339 // errorMessage: String
9340 // Message that shows if an error occurs
9341 errorMessage: "<span
class='dijitContentPaneError'>${errorState}
</span
>",
9343 // isLoaded: [readonly] Boolean
9344 // True if the ContentPane has data in it, either specified
9345 // during initialization (via href or inline content), or set
9346 // via attr('content', ...) / attr('href', ...)
9348 // False if it doesn't have any content, or if ContentPane is
9349 // still in the process of downloading href.
9352 baseClass: "dijitContentPane
",
9354 // doLayout: Boolean
9355 // - false - don't adjust size of children
9356 // - true - if there is a single visible child widget, set it's size to
9357 // however big the ContentPane is
9361 // Parameters to pass to xhrGet() request, for example:
9362 // | <div dojoType="dijit
.layout
.ContentPane
" href="./bar
" ioArgs="{timeout
: 500}">
9365 // isContainer: [protected] Boolean
9366 // Indicates that this widget acts as a "parent
" to the descendant widgets.
9367 // When the parent is started it will call startup() on the child widgets.
9368 // See also `isLayoutContainer`.
9371 // isLayoutContainer: [protected] Boolean
9372 // Indicates that this widget will call resize() on it's child widgets
9373 // when they become visible.
9374 isLayoutContainer: true,
9376 // onLoadDeferred: [readonly] dojo.Deferred
9377 // This is the `dojo.Deferred` returned by attr('href', ...) and refresh().
9378 // Calling onLoadDeferred.addCallback() or addErrback() registers your
9379 // callback to be called only once, when the prior attr('href', ...) call or
9380 // the initial href parameter to the constructor finishes loading.
9382 // This is different than an onLoad() handler which gets called any time any href is loaded.
9383 onLoadDeferred: null,
9385 // Override _Widget's attributeMap because we don't want the title attribute (used to specify
9386 // tab labels) to be copied to ContentPane.domNode... otherwise a tooltip shows up over the
9388 attributeMap: dojo.delegate(dijit._Widget.prototype.attributeMap, {
9392 postMixInProperties: function(){
9393 this.inherited(arguments);
9394 var messages = dojo.i18n.getLocalization("dijit
", "loading
", this.lang);
9395 this.loadingMessage = dojo.string.substitute(this.loadingMessage, messages);
9396 this.errorMessage = dojo.string.substitute(this.errorMessage, messages);
9398 // Detect if we were initialized with data
9399 if(!this.href && this.srcNodeRef && this.srcNodeRef.innerHTML){
9400 this.isLoaded = true;
9404 buildRendering: function(){
9405 // Overrides Widget.buildRendering().
9406 // Since we have no template we need to set this.containerNode ourselves.
9407 // For subclasses of ContentPane do have a template, does nothing.
9408 this.inherited(arguments);
9409 if(!this.containerNode){
9410 // make getDescendants() work
9411 this.containerNode = this.domNode;
9415 postCreate: function(){
9416 // remove the title attribute so it doesn't show up when hovering
9418 this.domNode.title = "";
9420 if(!dojo.attr(this.domNode,"role
")){
9421 dijit.setWaiRole(this.domNode, "group
");
9424 dojo.addClass(this.domNode, this.baseClass);
9427 startup: function(){
9429 // See `dijit.layout._LayoutWidget.startup` for description.
9430 // Although ContentPane doesn't extend _LayoutWidget, it does implement
9432 if(this._started){ return; }
9434 var parent = dijit._Contained.prototype.getParent.call(this);
9435 this._childOfLayoutWidget = parent && parent.isLayoutContainer;
9437 // I need to call resize() on my child/children (when I become visible), unless
9438 // I'm the child of a layout widget in which case my parent will call resize() on me and I'll do it then.
9439 this._needLayout = !this._childOfLayoutWidget;
9442 dojo.forEach(this.getChildren(), function(child){
9447 if(this._isShown() || this.preload){
9451 this.inherited(arguments);
9454 _checkIfSingleChild: function(){
9456 // Test if we have exactly one visible widget as a child,
9457 // and if so assume that we are a container for that widget,
9458 // and should propogate startup() and resize() calls to it.
9459 // Skips over things like data stores since they aren't visible.
9461 var childNodes = dojo.query("> *", this.containerNode).filter(function(node){
9462 return node.tagName !== "SCRIPT
"; // or a regexp for hidden elements like script|area|map|etc..
9464 childWidgetNodes = childNodes.filter(function(node){
9465 return dojo.hasAttr(node, "dojoType
") || dojo.hasAttr(node, "widgetId
");
9467 candidateWidgets = dojo.filter(childWidgetNodes.map(dijit.byNode), function(widget){
9468 return widget && widget.domNode && widget.resize;
9472 // all child nodes are widgets
9473 childNodes.length == childWidgetNodes.length &&
9475 // all but one are invisible (like dojo.data)
9476 candidateWidgets.length == 1
9478 this._singleChild = candidateWidgets[0];
9480 delete this._singleChild;
9483 // So we can set overflow: hidden to avoid a safari bug w/scrollbars showing up (#9449)
9484 dojo.toggleClass(this.containerNode, this.baseClass + "SingleChild
", !!this._singleChild);
9487 setHref: function(/*String|Uri*/ href){
9489 // Deprecated. Use set('href', ...) instead.
9490 dojo.deprecated("dijit
.layout
.ContentPane
.setHref() is deprecated
. Use
set('href', ...) instead
.", "", "2.0");
9491 return this.set("href
", href);
9493 _setHrefAttr: function(/*String|Uri*/ href){
9495 // Hook so attr("href
", ...) works.
9497 // Reset the (external defined) content of this pane and replace with new url
9498 // Note: It delays the download until widget is shown if preload is false.
9500 // url to the page you want to get, must be within the same domain as your mainpage
9502 // Cancel any in-flight requests (an attr('href') will cancel any in-flight attr('href', ...))
9505 this.onLoadDeferred = new dojo.Deferred(dojo.hitch(this, "cancel
"));
9509 // _setHrefAttr() is called during creation and by the user, after creation.
9510 // only in the second case do we actually load the URL; otherwise it's done in startup()
9511 if(this._created && (this.preload || this._isShown())){
9514 // Set flag to indicate that href needs to be loaded the next time the
9515 // ContentPane is made visible
9516 this._hrefChanged = true;
9519 return this.onLoadDeferred; // dojo.Deferred
9522 setContent: function(/*String|DomNode|Nodelist*/data){
9524 // Deprecated. Use set('content', ...) instead.
9525 dojo.deprecated("dijit
.layout
.ContentPane
.setContent() is deprecated
. Use
set('content', ...) instead
.", "", "2.0");
9526 this.set("content
", data);
9528 _setContentAttr: function(/*String|DomNode|Nodelist*/data){
9530 // Hook to make attr("content
", ...) work.
9531 // Replaces old content with data content, include style classes from old content
9533 // the new Content may be String, DomNode or NodeList
9535 // if data is a NodeList (or an array of nodes) nodes are copied
9536 // so you can import nodes from another document implicitly
9538 // clear href so we can't run refresh and clear content
9539 // refresh should only work if we downloaded the content
9542 // Cancel any in-flight requests (an attr('content') will cancel any in-flight attr('href', ...))
9545 // Even though user is just setting content directly, still need to define an onLoadDeferred
9546 // because the _onLoadHandler() handler is still getting called from setContent()
9547 this.onLoadDeferred = new dojo.Deferred(dojo.hitch(this, "cancel
"));
9549 this._setContent(data || "");
9551 this._isDownloaded = false; // mark that content is from a attr('content') not an attr('href')
9553 return this.onLoadDeferred; // dojo.Deferred
9555 _getContentAttr: function(){
9557 // Hook to make attr("content
") work
9558 return this.containerNode.innerHTML;
9563 // Cancels an in-flight download of content
9564 if(this._xhrDfd && (this._xhrDfd.fired == -1)){
9565 this._xhrDfd.cancel();
9567 delete this._xhrDfd; // garbage collect
9569 this.onLoadDeferred = null;
9572 uninitialize: function(){
9573 if(this._beingDestroyed){
9576 this.inherited(arguments);
9579 destroyRecursive: function(/*Boolean*/ preserveDom){
9581 // Destroy the ContentPane and its contents
9583 // if we have multiple controllers destroying us, bail after the first
9584 if(this._beingDestroyed){
9587 this.inherited(arguments);
9590 resize: function(changeSize, resultSize){
9592 // See `dijit.layout._LayoutWidget.resize` for description.
9593 // Although ContentPane doesn't extend _LayoutWidget, it does implement
9596 // For the TabContainer --> BorderContainer --> ContentPane case, _onShow() is
9597 // never called, so resize() is our trigger to do the initial href download.
9598 if(!this._wasShown){
9602 this._resizeCalled = true;
9604 // Set margin box size, unless it wasn't specified, in which case use current size.
9606 dojo.marginBox(this.domNode, changeSize);
9609 // Compute content box size of containerNode in case we [later] need to size our single child.
9610 var cn = this.containerNode;
9611 if(cn === this.domNode){
9612 // If changeSize or resultSize was passed to this method and this.containerNode ==
9613 // this.domNode then we can compute the content-box size without querying the node,
9614 // which is more reliable (similar to LayoutWidget.resize) (see for example #9449).
9615 var mb = resultSize || {};
9616 dojo.mixin(mb, changeSize || {}); // changeSize overrides resultSize
9617 if(!("h
" in mb) || !("w
" in mb)){
9618 mb = dojo.mixin(dojo.marginBox(cn), mb); // just use dojo.marginBox() to fill in missing values
9620 this._contentBox = dijit.layout.marginBox2contentBox(cn, mb);
9622 this._contentBox = dojo.contentBox(cn);
9625 // Make my children layout, or size my single child widget
9626 this._layoutChildren();
9629 _isShown: function(){
9631 // Returns true if the content is currently shown.
9633 // If I am a child of a layout widget then it actually returns true if I've ever been visible,
9634 // not whether I'm currently visible, since that's much faster than tracing up the DOM/widget
9635 // tree every call, and at least solves the performance problem on page load by deferring loading
9636 // hidden ContentPanes until they are first shown
9638 if(this._childOfLayoutWidget){
9639 // If we are TitlePane, etc - we return that only *IF* we've been resized
9640 if(this._resizeCalled && "open
" in this){
9643 return this._resizeCalled;
9644 }else if("open
" in this){
9645 return this.open; // for TitlePane, etc.
9647 // TODO: with _childOfLayoutWidget check maybe this branch no longer necessary?
9648 var node = this.domNode;
9649 return (node.style.display != 'none') && (node.style.visibility != 'hidden') && !dojo.hasClass(node, "dijitHidden
");
9653 _onShow: function(){
9655 // Called when the ContentPane is made visible
9657 // For a plain ContentPane, this is called on initialization, from startup().
9658 // If the ContentPane is a hidden pane of a TabContainer etc., then it's
9659 // called whenever the pane is made visible.
9661 // Does necessary processing, including href download and layout/resize of
9665 if(!this._xhrDfd && // if there's an href that isn't already being loaded
9666 (!this.isLoaded || this._hrefChanged || this.refreshOnShow)
9671 // If we are the child of a layout widget then the layout widget will call resize() on
9672 // us, and then we will size our child/children. Otherwise, we need to do it now.
9673 if(!this._childOfLayoutWidget && this._needLayout){
9674 // If a layout has been scheduled for when we become visible, do it now
9675 this._layoutChildren();
9679 this.inherited(arguments);
9681 // Need to keep track of whether ContentPane has been shown (which is different than
9682 // whether or not it's currently visible).
9683 this._wasShown = true;
9686 refresh: function(){
9688 // [Re]download contents of href and display
9690 // 1. cancels any currently in-flight requests
9691 // 2. posts "loading
..." message
9692 // 3. sends XHR to download new data
9694 // Cancel possible prior in-flight request
9697 this.onLoadDeferred = new dojo.Deferred(dojo.hitch(this, "cancel
"));
9699 return this.onLoadDeferred;
9704 // Load/reload the href specified in this.href
9706 // display loading message
9707 this._setContent(this.onDownloadStart(), true);
9711 preventCache: (this.preventCache || this.refreshOnShow),
9715 if(dojo.isObject(this.ioArgs)){
9716 dojo.mixin(getArgs, this.ioArgs);
9719 var hand = (this._xhrDfd = (this.ioMethod || dojo.xhrGet)(getArgs));
9721 hand.addCallback(function(html){
9723 self._isDownloaded = true;
9724 self._setContent(html, false);
9725 self.onDownloadEnd();
9727 self._onError('Content', err); // onContentError
9729 delete self._xhrDfd;
9733 hand.addErrback(function(err){
9735 // show error message in the pane
9736 self._onError('Download', err); // onDownloadError
9738 delete self._xhrDfd;
9742 // Remove flag saying that a load is needed
9743 delete this._hrefChanged;
9746 _onLoadHandler: function(data){
9748 // This is called whenever new content is being loaded
9749 this.isLoaded = true;
9751 this.onLoadDeferred.callback(data);
9754 console.error('Error '+this.widgetId+' running custom onLoad code: ' + e.message);
9758 _onUnloadHandler: function(){
9760 // This is called whenever the content is being unloaded
9761 this.isLoaded = false;
9765 console.error('Error '+this.widgetId+' running custom onUnload code: ' + e.message);
9769 destroyDescendants: function(){
9771 // Destroy all the widgets inside the ContentPane and empty containerNode
9773 // Make sure we call onUnload (but only when the ContentPane has real content)
9775 this._onUnloadHandler();
9778 // Even if this.isLoaded == false there might still be a "Loading
..." message
9779 // to erase, so continue...
9781 // For historical reasons we need to delete all widgets under this.containerNode,
9782 // even ones that the user has created manually.
9783 var setter = this._contentSetter;
9784 dojo.forEach(this.getChildren(), function(widget){
9785 if(widget.destroyRecursive){
9786 widget.destroyRecursive();
9790 // Most of the widgets in setter.parseResults have already been destroyed, but
9791 // things like Menu that have been moved to <body> haven't yet
9792 dojo.forEach(setter.parseResults, function(widget){
9793 if(widget.destroyRecursive && widget.domNode && widget.domNode.parentNode == dojo.body()){
9794 widget.destroyRecursive();
9797 delete setter.parseResults;
9800 // And then clear away all the DOM nodes
9801 dojo.html._emptyNode(this.containerNode);
9803 // Delete any state information we have about current contents
9804 delete this._singleChild;
9807 _setContent: function(cont, isFakeContent){
9809 // Insert the content into the container node
9811 // first get rid of child widgets
9812 this.destroyDescendants();
9814 // dojo.html.set will take care of the rest of the details
9815 // we provide an override for the error handling to ensure the widget gets the errors
9816 // configure the setter instance with only the relevant widget instance properties
9817 // NOTE: unless we hook into attr, or provide property setters for each property,
9818 // we need to re-configure the ContentSetter with each use
9819 var setter = this._contentSetter;
9820 if(! (setter && setter instanceof dojo.html._ContentSetter)){
9821 setter = this._contentSetter = new dojo.html._ContentSetter({
9822 node: this.containerNode,
9823 _onError: dojo.hitch(this, this._onError),
9824 onContentError: dojo.hitch(this, function(e){
9825 // fires if a domfault occurs when we are appending this.errorMessage
9826 // like for instance if domNode is a UL and we try append a DIV
9827 var errMess = this.onContentError(e);
9829 this.containerNode.innerHTML = errMess;
9831 console.error('Fatal '+this.id+' could not change content due to '+e.message, e);
9838 var setterParams = dojo.mixin({
9839 cleanContent: this.cleanContent,
9840 extractContent: this.extractContent,
9841 parseContent: this.parseOnLoad,
9844 }, this._contentSetterParams || {});
9846 dojo.mixin(setter, setterParams);
9848 setter.set( (dojo.isObject(cont) && cont.domNode) ? cont.domNode : cont );
9850 // setter params must be pulled afresh from the ContentPane each time
9851 delete this._contentSetterParams;
9854 // Startup each top level child widget (and they will start their children, recursively)
9855 dojo.forEach(this.getChildren(), function(child){
9856 // The parser has already called startup on all widgets *without* a getParent() method
9857 if(!this.parseOnLoad || child.getParent){
9862 // Call resize() on each of my child layout widgets,
9863 // or resize() on my single child layout widget...
9864 // either now (if I'm currently visible)
9865 // or when I become visible
9866 this._scheduleLayout();
9868 this._onLoadHandler(cont);
9872 _onError: function(type, err, consoleText){
9873 this.onLoadDeferred.errback(err);
9875 // shows user the string that is returned by on[type]Error
9876 // overide on[type]Error and return your own string to customize
9877 var errText = this['on' + type + 'Error'].call(this, err);
9879 console.error(consoleText, err);
9880 }else if(errText){// a empty string won't change current content
9881 this._setContent(errText, true);
9885 _scheduleLayout: function(){
9887 // Call resize() on each of my child layout widgets, either now
9888 // (if I'm currently visible) or when I become visible
9889 if(this._isShown()){
9890 this._layoutChildren();
9892 this._needLayout = true;
9896 _layoutChildren: function(){
9898 // Since I am a Container widget, each of my children expects me to
9899 // call resize() or layout() on them.
9901 // Should be called on initialization and also whenever we get new content
9902 // (from an href, or from attr('content', ...))... but deferred until
9903 // the ContentPane is visible
9906 this._checkIfSingleChild();
9909 if(this._singleChild && this._singleChild.resize){
9910 var cb = this._contentBox || dojo.contentBox(this.containerNode);
9912 // note: if widget has padding this._contentBox will have l and t set,
9913 // but don't pass them to resize() or it will doubly-offset the child
9914 this._singleChild.resize({w: cb.w, h: cb.h});
9916 // All my child widgets are independently sized (rather than matching my size),
9917 // but I still need to call resize() on each child to make it layout.
9918 dojo.forEach(this.getChildren(), function(widget){
9924 delete this._needLayout;
9927 // EVENT's, should be overide-able
9928 onLoad: function(data){
9930 // Event hook, is called after everything is loaded and widgetified
9935 onUnload: function(){
9937 // Event hook, is called before old content is cleared
9942 onDownloadStart: function(){
9944 // Called before download starts.
9946 // The string returned by this function will be the html
9947 // that tells the user we are loading something.
9948 // Override with your own function if you want to change text.
9951 return this.loadingMessage;
9954 onContentError: function(/*Error*/ error){
9956 // Called on DOM faults, require faults etc. in content.
9958 // In order to display an error message in the pane, return
9959 // the error message from this method, as an HTML string.
9961 // By default (if this method is not overriden), it returns
9962 // nothing, so the error message is just printed to the console.
9967 onDownloadError: function(/*Error*/ error){
9969 // Called when download error occurs.
9971 // In order to display an error message in the pane, return
9972 // the error message from this method, as an HTML string.
9974 // Default behavior (if this method is not overriden) is to display
9975 // the error message inside the pane.
9978 return this.errorMessage;
9981 onDownloadEnd: function(){
9983 // Called when download is finished.
9991 if(!dojo._hasResource["dijit
.TooltipDialog
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
9992 dojo._hasResource["dijit
.TooltipDialog
"] = true;
9993 dojo.provide("dijit
.TooltipDialog
");
10001 "dijit
.TooltipDialog
",
10002 [dijit.layout.ContentPane, dijit._Templated, dijit.form._FormMixin, dijit._DialogMixin],
10005 // Pops up a dialog that appears like a Tooltip
10008 // Description of tooltip dialog (required for a11y)
10011 // doLayout: [protected] Boolean
10012 // Don't change this parameter from the default value.
10013 // This ContentPane parameter doesn't make sense for TooltipDialog, since TooltipDialog
10014 // is never a child of a layout container, nor can you specify the size of
10015 // TooltipDialog in order to control the size of an inner widget.
10018 // autofocus: Boolean
10019 // A Toggle to modify the default focus behavior of a Dialog, which
10020 // is to focus on the first dialog element after opening the dialog.
10021 // False will disable autofocusing. Default: true
10024 // baseClass: [protected] String
10025 // The root className to use for the various states of this widget
10026 baseClass: "dijitTooltipDialog
",
10028 // _firstFocusItem: [private] [readonly] DomNode
10029 // The pointer to the first focusable node in the dialog.
10030 // Set by `dijit._DialogMixin._getFocusItems`.
10031 _firstFocusItem: null,
10033 // _lastFocusItem: [private] [readonly] DomNode
10034 // The pointer to which node has focus prior to our dialog.
10035 // Set by `dijit._DialogMixin._getFocusItems`.
10036 _lastFocusItem: null,
10038 templateString: dojo.cache("dijit
", "templates
/TooltipDialog.html", "<div waiRole=\"presentation\">\n\t<div class=\"dijitTooltipContainer\" waiRole=\"presentation\">\n\t\t<div class =\"dijitTooltipContents dijitTooltipFocusNode\" dojoAttachPoint=\"containerNode\" tabindex=\"-1\" waiRole=\"dialog\"></div>\n\t</div>\n\t<div class=\"dijitTooltipConnector\" waiRole=\"presentation\"></div>\n</div
>\n"),
10040 postCreate: function(){
10041 this.inherited(arguments);
10042 this.connect(this.containerNode, "onkeypress
", "_onKey
");
10043 this.containerNode.title = this.title;
10046 orient: function(/*DomNode*/ node, /*String*/ aroundCorner, /*String*/ corner){
10048 // Configure widget to be displayed in given position relative to the button.
10049 // This is called from the dijit.popup code, and should not be called
10053 var c = this._currentOrientClass;
10055 dojo.removeClass(this.domNode, c);
10057 c = "dijitTooltipAB
"+(corner.charAt(1) == 'L'?"Left
":"Right
")+" dijitTooltip
"+(corner.charAt(0) == 'T' ? "Below
" : "Above
");
10058 dojo.addClass(this.domNode, c);
10059 this._currentOrientClass = c;
10062 onOpen: function(/*Object*/ pos){
10064 // Called when dialog is displayed.
10065 // This is called from the dijit.popup code, and should not be called directly.
10069 this.orient(this.domNode,pos.aroundCorner, pos.corner);
10070 this._onShow(); // lazy load trigger
10072 if(this.autofocus){
10073 this._getFocusItems(this.containerNode);
10074 dijit.focus(this._firstFocusItem);
10078 onClose: function(){
10080 // Called when dialog is hidden.
10081 // This is called from the dijit.popup code, and should not be called directly.
10087 _onKey: function(/*Event*/ evt){
10089 // Handler for keyboard events
10091 // Keep keyboard focus in dialog; close dialog on escape key
10095 var node = evt.target;
10096 var dk = dojo.keys;
10097 if(evt.charOrCode === dk.TAB){
10098 this._getFocusItems(this.containerNode);
10100 var singleFocusItem = (this._firstFocusItem == this._lastFocusItem);
10101 if(evt.charOrCode == dk.ESCAPE){
10102 // Use setTimeout to avoid crash on IE, see #10396.
10103 setTimeout(dojo.hitch(this, "onCancel
"), 0);
10104 dojo.stopEvent(evt);
10105 }else if(node == this._firstFocusItem && evt.shiftKey && evt.charOrCode === dk.TAB){
10106 if(!singleFocusItem){
10107 dijit.focus(this._lastFocusItem); // send focus to last item in dialog
10109 dojo.stopEvent(evt);
10110 }else if(node == this._lastFocusItem && evt.charOrCode === dk.TAB && !evt.shiftKey){
10111 if(!singleFocusItem){
10112 dijit.focus(this._firstFocusItem); // send focus to first item in dialog
10114 dojo.stopEvent(evt);
10115 }else if(evt.charOrCode === dk.TAB){
10116 // we want the browser's default tab handling to move focus
10117 // but we don't want the tab to propagate upwards
10118 evt.stopPropagation();
10126 if(!dojo._hasResource["dijit
.Dialog
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
10127 dojo._hasResource["dijit
.Dialog
"] = true;
10128 dojo.provide("dijit
.Dialog
");
10145 dijit._underlay = function(kwArgs){
10147 // A shared instance of a `dijit.DialogUnderlay`
10150 // A shared instance of a `dijit.DialogUnderlay` created and
10151 // used by `dijit.Dialog`, though never created until some Dialog
10152 // or subclass thereof is shown.
10157 "dijit
._DialogBase
",
10158 [dijit._Templated, dijit.form._FormMixin, dijit._DialogMixin, dijit._CssStateMixin],
10161 // A modal dialog Widget
10164 // Pops up a modal dialog window, blocking access to the screen
10165 // and also graying out the screen Dialog is extended from
10166 // ContentPane so it supports all the same parameters (href, etc.)
10169 // | <div dojoType="dijit
.Dialog
" href="test
.html
"></div>
10172 // | var foo = new dijit.Dialog({ title: "test dialog
", content: "test content
" };
10173 // | dojo.body().appendChild(foo.domNode);
10174 // | foo.startup();
10176 templateString: dojo.cache("dijit
", "templates
/Dialog.html", "<div class=\"dijitDialog\" tabindex=\"-1\" waiRole=\"dialog\" waiState=\"labelledby-${id}_title\">\n\t<div dojoAttachPoint=\"titleBar\" class=\"dijitDialogTitleBar\">\n\t<span dojoAttachPoint=\"titleNode\" class=\"dijitDialogTitle\" id=\"${id}_title\"></span>\n\t<span dojoAttachPoint
=\"closeButtonNode
\" class=\"dijitDialogCloseIcon
\" dojoAttachEvent
=\"onclick
: onCancel
\" title
=\"${buttonCancel}
\">\n\t\t<span dojoAttachPoint
=\"closeText
\" class=\"closeText
\" title
=\"${buttonCancel}
\">x
</span>\n\t</span>\n\t</div>\n\t\t<div dojoAttachPoint=\"containerNode\" class=\"dijitDialogPaneContent\"></div>\n</div
>\n"),
10178 baseClass: "dijitDialog
",
10181 closeButtonNode: "dijitDialogCloseIcon
"
10184 attributeMap: dojo.delegate(dijit._Widget.prototype.attributeMap, {
10186 { node: "titleNode
", type: "innerHTML
" },
10187 { node: "titleBar
", type: "attribute
" }
10189 "aria
-describedby
":""
10193 // True if Dialog is currently displayed on screen.
10196 // duration: Integer
10197 // The time in milliseconds it takes the dialog to fade in and out
10198 duration: dijit.defaultDuration,
10200 // refocus: Boolean
10201 // A Toggle to modify the default focus behavior of a Dialog, which
10202 // is to re-focus the element which had focus before being opened.
10203 // False will disable refocusing. Default: true
10206 // autofocus: Boolean
10207 // A Toggle to modify the default focus behavior of a Dialog, which
10208 // is to focus on the first dialog element after opening the dialog.
10209 // False will disable autofocusing. Default: true
10212 // _firstFocusItem: [private] [readonly] DomNode
10213 // The pointer to the first focusable node in the dialog.
10214 // Set by `dijit._DialogMixin._getFocusItems`.
10215 _firstFocusItem: null,
10217 // _lastFocusItem: [private] [readonly] DomNode
10218 // The pointer to which node has focus prior to our dialog.
10219 // Set by `dijit._DialogMixin._getFocusItems`.
10220 _lastFocusItem: null,
10222 // doLayout: [protected] Boolean
10223 // Don't change this parameter from the default value.
10224 // This ContentPane parameter doesn't make sense for Dialog, since Dialog
10225 // is never a child of a layout container, nor can you specify the size of
10226 // Dialog in order to control the size of an inner widget.
10229 // draggable: Boolean
10230 // Toggles the moveable aspect of the Dialog. If true, Dialog
10231 // can be dragged by it's title. If false it will remain centered
10232 // in the viewport.
10235 //aria-describedby: String
10236 // Allows the user to add an aria-describedby attribute onto the dialog. The value should
10237 // be the id of the container element of text that describes the dialog purpose (usually
10238 // the first text in the dialog).
10239 // <div dojoType="dijit
.Dialog
" aria-describedby="intro
" .....>
10240 // <div id="intro
">Introductory text</div>
10241 // <div>rest of dialog contents</div>
10243 "aria
-describedby
":"",
10245 postMixInProperties: function(){
10246 var _nlsResources = dojo.i18n.getLocalization("dijit
", "common
");
10247 dojo.mixin(this, _nlsResources);
10248 this.inherited(arguments);
10251 postCreate: function(){
10252 dojo.style(this.domNode, {
10254 position:"absolute
"
10256 dojo.body().appendChild(this.domNode);
10258 this.inherited(arguments);
10260 this.connect(this, "onExecute
", "hide
");
10261 this.connect(this, "onCancel
", "hide
");
10262 this._modalconnects = [];
10265 onLoad: function(){
10267 // Called when data has been loaded from an href.
10268 // Unlike most other callbacks, this function can be connected to (via `dojo.connect`)
10269 // but should *not* be overriden.
10273 // when href is specified we need to reposition the dialog after the data is loaded
10274 // and find the focusable elements
10276 if(this.autofocus){
10277 this._getFocusItems(this.domNode);
10278 dijit.focus(this._firstFocusItem);
10280 this.inherited(arguments);
10283 _endDrag: function(e){
10285 // Called after dragging the Dialog. Saves the position of the dialog in the viewport.
10288 if(e && e.node && e.node === this.domNode){
10289 this._relativePosition = dojo.position(e.node);
10293 _setup: function(){
10295 // Stuff we need to do before showing the Dialog for the first
10296 // time (but we defer it until right beforehand, for
10297 // performance reasons).
10301 var node = this.domNode;
10303 if(this.titleBar && this.draggable){
10304 this._moveable = (dojo.isIE == 6) ?
10305 new dojo.dnd.TimedMoveable(node, { handle: this.titleBar }) : // prevent overload, see #5285
10306 new dojo.dnd.Moveable(node, { handle: this.titleBar, timeout: 0 });
10307 dojo.subscribe("/dnd/move/stop
",this,"_endDrag
");
10309 dojo.addClass(node,"dijitDialogFixed
");
10312 this.underlayAttrs = {
10314 "class": dojo.map(this["class"].split(/\s/), function(s){ return s+"_underlay
"; }).join(" ")
10317 this._fadeIn = dojo.fadeIn({
10319 duration: this.duration,
10320 beforeBegin: dojo.hitch(this, function(){
10321 var underlay = dijit._underlay;
10323 underlay = dijit._underlay = new dijit.DialogUnderlay(this.underlayAttrs);
10325 underlay.set(this.underlayAttrs);
10328 var ds = dijit._dialogStack,
10329 zIndex = 948 + ds.length*2;
10330 if(ds.length == 1){ // first dialog
10333 dojo.style(dijit._underlay.domNode, 'zIndex', zIndex);
10334 dojo.style(this.domNode, 'zIndex', zIndex + 1);
10336 onEnd: dojo.hitch(this, function(){
10337 if(this.autofocus){
10338 // find focusable Items each time dialog is shown since if dialog contains a widget the
10339 // first focusable items can change
10340 this._getFocusItems(this.domNode);
10341 dijit.focus(this._firstFocusItem);
10346 this._fadeOut = dojo.fadeOut({
10348 duration: this.duration,
10349 onEnd: dojo.hitch(this, function(){
10350 node.style.display = "none
";
10352 // Restore the previous dialog in the stack, or if this is the only dialog
10353 // then restore to original page
10354 var ds = dijit._dialogStack;
10355 if(ds.length == 0){
10356 dijit._underlay.hide();
10358 dojo.style(dijit._underlay.domNode, 'zIndex', 948 + ds.length*2);
10359 dijit._underlay.set(ds[ds.length-1].underlayAttrs);
10362 // Restore focus to wherever it was before this dialog was displayed
10364 var focus = this._savedFocus;
10366 // If we are returning control to a previous dialog but for some reason
10367 // that dialog didn't have a focused field, set focus to first focusable item.
10368 // This situation could happen if two dialogs appeared at nearly the same time,
10369 // since a dialog doesn't set it's focus until the fade-in is finished.
10371 var pd = ds[ds.length-1];
10372 if(!dojo.isDescendant(focus.node, pd.domNode)){
10373 pd._getFocusItems(pd.domNode);
10374 focus = pd._firstFocusItem;
10378 dijit.focus(focus);
10384 uninitialize: function(){
10385 var wasPlaying = false;
10386 if(this._fadeIn && this._fadeIn.status() == "playing
"){
10388 this._fadeIn.stop();
10390 if(this._fadeOut && this._fadeOut.status() == "playing
"){
10392 this._fadeOut.stop();
10395 // Hide the underlay, unless the underlay widget has already been destroyed
10396 // because we are being called during page unload (when all widgets are destroyed)
10397 if((this.open || wasPlaying) && !dijit._underlay._destroyed){
10398 dijit._underlay.hide();
10401 if(this._moveable){
10402 this._moveable.destroy();
10404 this.inherited(arguments);
10409 // If necessary, shrink dialog contents so dialog fits in viewport
10413 this._checkIfSingleChild();
10415 // If we resized the dialog contents earlier, reset them back to original size, so
10416 // that if the user later increases the viewport size, the dialog can display w/out a scrollbar.
10417 // Need to do this before the dojo.marginBox(this.domNode) call below.
10418 if(this._singleChild){
10419 if(this._singleChildOriginalStyle){
10420 this._singleChild.domNode.style.cssText = this._singleChildOriginalStyle;
10422 delete this._singleChildOriginalStyle;
10424 dojo.style(this.containerNode, {
10430 var mb = dojo.marginBox(this.domNode);
10431 var viewport = dojo.window.getBox();
10432 if(mb.w >= viewport.w || mb.h >= viewport.h){
10433 // Reduce size of dialog contents so that dialog fits in viewport
10435 var w = Math.min(mb.w, Math.floor(viewport.w * 0.75)),
10436 h = Math.min(mb.h, Math.floor(viewport.h * 0.75));
10438 if(this._singleChild && this._singleChild.resize){
10439 this._singleChildOriginalStyle = this._singleChild.domNode.style.cssText;
10440 this._singleChild.resize({w: w, h: h});
10442 dojo.style(this.containerNode, {
10446 position: "relative
" // workaround IE bug moving scrollbar or dragging dialog
10450 if(this._singleChild && this._singleChild.resize){
10451 this._singleChild.resize();
10456 _position: function(){
10458 // Position modal dialog in the viewport. If no relative offset
10459 // in the viewport has been determined (by dragging, for instance),
10460 // center the node. Otherwise, use the Dialog's stored relative offset,
10461 // and position the node to top: left: values based on the viewport.
10464 if(!dojo.hasClass(dojo.body(),"dojoMove
")){
10465 var node = this.domNode,
10466 viewport = dojo.window.getBox(),
10467 p = this._relativePosition,
10468 bb = p ? null : dojo._getBorderBox(node),
10469 l = Math.floor(viewport.l + (p ? p.x : (viewport.w - bb.w) / 2)),
10470 t = Math.floor(viewport.t + (p ? p.y : (viewport.h - bb.h) / 2))
10479 _onKey: function(/*Event*/ evt){
10481 // Handles the keyboard events for accessibility reasons
10485 var ds = dijit._dialogStack;
10486 if(ds[ds.length-1] != this){
10487 // console.debug(this.id + ': skipping because', this, 'is not the active dialog');
10491 if(evt.charOrCode){
10492 var dk = dojo.keys;
10493 var node = evt.target;
10494 if(evt.charOrCode === dk.TAB){
10495 this._getFocusItems(this.domNode);
10497 var singleFocusItem = (this._firstFocusItem == this._lastFocusItem);
10498 // see if we are shift-tabbing from first focusable item on dialog
10499 if(node == this._firstFocusItem && evt.shiftKey && evt.charOrCode === dk.TAB){
10500 if(!singleFocusItem){
10501 dijit.focus(this._lastFocusItem); // send focus to last item in dialog
10503 dojo.stopEvent(evt);
10504 }else if(node == this._lastFocusItem && evt.charOrCode === dk.TAB && !evt.shiftKey){
10505 if(!singleFocusItem){
10506 dijit.focus(this._firstFocusItem); // send focus to first item in dialog
10508 dojo.stopEvent(evt);
10510 // see if the key is for the dialog
10512 if(node == this.domNode || dojo.hasClass(node, "dijitPopup
")){
10513 if(evt.charOrCode == dk.ESCAPE){
10516 return; // just let it go
10519 node = node.parentNode;
10521 // this key is for the disabled document window
10522 if(evt.charOrCode !== dk.TAB){ // allow tabbing into the dialog for a11y
10523 dojo.stopEvent(evt);
10524 // opera won't tab to a div
10525 }else if(!dojo.isOpera){
10527 this._firstFocusItem.focus();
10528 }catch(e){ /*squelch*/ }
10536 // Display the dialog
10537 if(this.open){ return; }
10539 // first time we show the dialog, there's some initialization stuff to do
10540 if(!this._alreadyInitialized){
10542 this._alreadyInitialized=true;
10545 if(this._fadeOut.status() == "playing
"){
10546 this._fadeOut.stop();
10549 this._modalconnects.push(dojo.connect(window, "onscroll
", this, "layout
"));
10550 this._modalconnects.push(dojo.connect(window, "onresize
", this, function(){
10551 // IE gives spurious resize events and can actually get stuck
10552 // in an infinite loop if we don't ignore them
10553 var viewport = dojo.window.getBox();
10554 if(!this._oldViewport ||
10555 viewport.h != this._oldViewport.h ||
10556 viewport.w != this._oldViewport.w){
10558 this._oldViewport = viewport;
10561 this._modalconnects.push(dojo.connect(dojo.doc.documentElement, "onkeypress
", this, "_onKey
"));
10563 dojo.style(this.domNode, {
10569 this._onShow(); // lazy load trigger
10573 dijit._dialogStack.push(this);
10574 this._fadeIn.play();
10576 this._savedFocus = dijit.getFocus(this);
10583 // if we haven't been initialized yet then we aren't showing and we can just return
10584 // or if we aren't the active dialog, don't allow us to close yet
10585 var ds = dijit._dialogStack;
10586 if(!this._alreadyInitialized || this != ds[ds.length-1]){
10590 if(this._fadeIn.status() == "playing
"){
10591 this._fadeIn.stop();
10594 // throw away current active dialog from stack -- making the previous dialog or the node on the original page active
10597 this._fadeOut.play();
10599 if(this._scrollConnected){
10600 this._scrollConnected = false;
10602 dojo.forEach(this._modalconnects, dojo.disconnect);
10603 this._modalconnects = [];
10605 if(this._relativePosition){
10606 delete this._relativePosition;
10613 layout: function(){
10615 // Position the Dialog and the underlay
10618 if(this.domNode.style.display != "none
"){
10619 if(dijit._underlay){ // avoid race condition during show()
10620 dijit._underlay.layout();
10626 destroy: function(){
10627 dojo.forEach(this._modalconnects, dojo.disconnect);
10628 if(this.refocus && this.open){
10629 setTimeout(dojo.hitch(dijit,"focus
",this._savedFocus), 25);
10631 this.inherited(arguments);
10638 [dijit.layout.ContentPane, dijit._DialogBase],
10642 // Stack of currenctly displayed dialogs, layered on top of each other
10643 dijit._dialogStack = [];
10645 // For back-compat. TODO: remove in 2.0
10650 if(!dojo._hasResource["dijit
._HasDropDown
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
10651 dojo._hasResource["dijit
._HasDropDown
"] = true;
10652 dojo.provide("dijit
._HasDropDown
");
10657 dojo.declare("dijit
._HasDropDown
",
10661 // Mixin for widgets that need drop down ability.
10663 // _buttonNode: [protected] DomNode
10664 // The button/icon/node to click to display the drop down.
10665 // Can be set via a dojoAttachPoint assignment.
10666 // If missing, then either focusNode or domNode (if focusNode is also missing) will be used.
10669 // _arrowWrapperNode: [protected] DomNode
10670 // Will set CSS class dijitUpArrow, dijitDownArrow, dijitRightArrow etc. on this node depending
10671 // on where the drop down is set to be positioned.
10672 // Can be set via a dojoAttachPoint assignment.
10673 // If missing, then _buttonNode will be used.
10674 _arrowWrapperNode: null,
10676 // _popupStateNode: [protected] DomNode
10677 // The node to set the popupActive class on.
10678 // Can be set via a dojoAttachPoint assignment.
10679 // If missing, then focusNode or _buttonNode (if focusNode is missing) will be used.
10680 _popupStateNode: null,
10682 // _aroundNode: [protected] DomNode
10683 // The node to display the popup around.
10684 // Can be set via a dojoAttachPoint assignment.
10685 // If missing, then domNode will be used.
10688 // dropDown: [protected] Widget
10689 // The widget to display as a popup. This widget *must* be
10690 // defined before the startup function is called.
10693 // autoWidth: [protected] Boolean
10694 // Set to true to make the drop down at least as wide as this
10695 // widget. Set to false if the drop down should just be its
10699 // forceWidth: [protected] Boolean
10700 // Set to true to make the drop down exactly as wide as this
10701 // widget. Overrides autoWidth.
10704 // maxHeight: [protected] Integer
10705 // The max height for our dropdown. Set to 0 for no max height.
10706 // any dropdown taller than this will have scrollbars
10709 // dropDownPosition: [const] String[]
10710 // This variable controls the position of the drop down.
10711 // It's an array of strings with the following values:
10713 // * before: places drop down to the left of the target node/widget, or to the right in
10714 // the case of RTL scripts like Hebrew and Arabic
10715 // * after: places drop down to the right of the target node/widget, or to the left in
10716 // the case of RTL scripts like Hebrew and Arabic
10717 // * above: drop down goes above target node
10718 // * below: drop down goes below target node
10720 // The list is positions is tried, in order, until a position is found where the drop down fits
10721 // within the viewport.
10723 dropDownPosition: ["below
","above
"],
10725 // _stopClickEvents: Boolean
10726 // When set to false, the click events will not be stopped, in
10727 // case you want to use them in your subwidget
10728 _stopClickEvents: true,
10730 _onDropDownMouseDown: function(/*Event*/ e){
10732 // Callback when the user mousedown's on the arrow icon
10734 if(this.disabled || this.readOnly){ return; }
10736 this._docHandler = this.connect(dojo.doc, "onmouseup
", "_onDropDownMouseUp
");
10738 this.toggleDropDown();
10741 _onDropDownMouseUp: function(/*Event?*/ e){
10743 // Callback when the user lifts their mouse after mouse down on the arrow icon.
10744 // If the drop is a simple menu and the mouse is over the menu, we execute it, otherwise, we focus our
10745 // dropDown node. If the event is missing, then we are not
10746 // a mouseup event.
10748 // This is useful for the common mouse movement pattern
10749 // with native browser <select> nodes:
10750 // 1. mouse down on the select node (probably on the arrow)
10751 // 2. move mouse to a menu item while holding down the mouse button
10752 // 3. mouse up. this selects the menu item as though the user had clicked it.
10753 if(e && this._docHandler){
10754 this.disconnect(this._docHandler);
10756 var dropDown = this.dropDown, overMenu = false;
10758 if(e && this._opened){
10759 // This code deals with the corner-case when the drop down covers the original widget,
10760 // because it's so large. In that case mouse-up shouldn't select a value from the menu.
10761 // Find out if our target is somewhere in our dropdown widget,
10762 // but not over our _buttonNode (the clickable node)
10763 var c = dojo.position(this._buttonNode, true);
10764 if(!(e.pageX >= c.x && e.pageX <= c.x + c.w) ||
10765 !(e.pageY >= c.y && e.pageY <= c.y + c.h)){
10767 while(t && !overMenu){
10768 if(dojo.hasClass(t, "dijitPopup
")){
10776 if(dropDown.onItemClick){
10778 while(t && !(menuItem = dijit.byNode(t))){
10781 if(menuItem && menuItem.onClick && menuItem.getParent){
10782 menuItem.getParent().onItemClick(menuItem, e);
10789 if(this._opened && dropDown.focus){
10790 // Focus the dropdown widget - do it on a delay so that we
10791 // don't steal our own focus.
10792 window.setTimeout(dojo.hitch(dropDown, "focus
"), 1);
10796 _onDropDownClick: function(/*Event*/ e){
10797 // the drop down was already opened on mousedown/keydown; just need to call stopEvent()
10798 if(this._stopClickEvents){
10803 _setupDropdown: function(){
10805 // set up nodes and connect our mouse and keypress events
10806 this._buttonNode = this._buttonNode || this.focusNode || this.domNode;
10807 this._popupStateNode = this._popupStateNode || this.focusNode || this._buttonNode;
10808 this._aroundNode = this._aroundNode || this.domNode;
10809 this.connect(this._buttonNode, "onmousedown
", "_onDropDownMouseDown
");
10810 this.connect(this._buttonNode, "onclick
", "_onDropDownClick
");
10811 this.connect(this._buttonNode, "onkeydown
", "_onDropDownKeydown
");
10812 this.connect(this._buttonNode, "onkeyup
", "_onKey
");
10814 // If we have a _setStateClass function (which happens when
10815 // we are a form widget), then we need to connect our open/close
10817 if(this._setStateClass){
10818 this.connect(this, "openDropDown
", "_setStateClass
");
10819 this.connect(this, "closeDropDown
", "_setStateClass
");
10822 // Add a class to the "dijitDownArrowButton
" type class to _buttonNode so theme can set direction of arrow
10823 // based on where drop down will normally appear
10825 "after
" : this.isLeftToRight() ? "Right
" : "Left
",
10826 "before
" : this.isLeftToRight() ? "Left
" : "Right
",
10831 }[this.dropDownPosition[0]] || this.dropDownPosition[0] || "Down
";
10832 dojo.addClass(this._arrowWrapperNode || this._buttonNode, "dijit
" + defaultPos + "ArrowButton
");
10835 postCreate: function(){
10836 this._setupDropdown();
10837 this.inherited(arguments);
10840 destroyDescendants: function(){
10842 // Destroy the drop down, unless it's already been destroyed. This can happen because
10843 // the drop down is a direct child of <body> even though it's logically my child.
10844 if(!this.dropDown._destroyed){
10845 this.dropDown.destroyRecursive();
10847 delete this.dropDown;
10849 this.inherited(arguments);
10852 _onDropDownKeydown: function(/*Event*/ e){
10853 if(e.keyCode == dojo.keys.DOWN_ARROW || e.keyCode == dojo.keys.ENTER || e.keyCode == dojo.keys.SPACE){
10854 e.preventDefault(); // stop IE screen jump
10858 _onKey: function(/*Event*/ e){
10860 // Callback when the user presses a key while focused on the button node
10862 if(this.disabled || this.readOnly){ return; }
10863 var d = this.dropDown;
10864 if(d && this._opened && d.handleKey){
10865 if(d.handleKey(e) === false){ return; }
10867 if(d && this._opened && e.keyCode == dojo.keys.ESCAPE){
10868 this.toggleDropDown();
10869 }else if(d && !this._opened &&
10870 (e.keyCode == dojo.keys.DOWN_ARROW || e.keyCode == dojo.keys.ENTER || e.keyCode == dojo.keys.SPACE)){
10871 this.toggleDropDown();
10873 setTimeout(dojo.hitch(d, "focus
"), 1);
10878 _onBlur: function(){
10880 // Called magically when focus has shifted away from this widget and it's dropdown
10882 this.closeDropDown();
10883 // don't focus on button. the user has explicitly focused on something else.
10884 this.inherited(arguments);
10887 isLoaded: function(){
10889 // Returns whether or not the dropdown is loaded. This can
10890 // be overridden in order to force a call to loadDropDown().
10897 loadDropDown: function(/* Function */ loadCallback){
10899 // Loads the data for the dropdown, and at some point, calls
10900 // the given callback
10907 toggleDropDown: function(){
10909 // Toggle the drop-down widget; if it is up, close it, if not, open it
10913 if(this.disabled || this.readOnly){ return; }
10915 var dropDown = this.dropDown;
10916 if(!dropDown){ return; }
10918 // If we aren't loaded, load it first so there isn't a flicker
10919 if(!this.isLoaded()){
10920 this.loadDropDown(dojo.hitch(this, "openDropDown
"));
10923 this.openDropDown();
10926 this.closeDropDown();
10930 openDropDown: function(){
10932 // Opens the dropdown for this widget - it returns the
10933 // return value of dijit.popup.open
10937 var dropDown = this.dropDown;
10938 var ddNode = dropDown.domNode;
10941 // Prepare our popup's height and honor maxHeight if it exists.
10943 // TODO: isn't maxHeight dependent on the return value from dijit.popup.open(),
10944 // ie, dependent on how much space is available (BK)
10946 if(!this._preparedNode){
10947 dijit.popup.moveOffScreen(ddNode);
10948 this._preparedNode = true;
10949 // Check if we have explicitly set width and height on the dropdown widget dom node
10950 if(ddNode.style.width){
10951 this._explicitDDWidth = true;
10953 if(ddNode.style.height){
10954 this._explicitDDHeight = true;
10958 // Code for resizing dropdown (height limitation, or increasing width to match my width)
10959 if(this.maxHeight || this.forceWidth || this.autoWidth){
10962 visibility: "hidden
"
10964 if(!this._explicitDDWidth){
10965 myStyle.width = "";
10967 if(!this._explicitDDHeight){
10968 myStyle.height = "";
10970 dojo.style(ddNode, myStyle);
10972 // Get size of drop down, and determine if vertical scroll bar needed
10973 var mb = dojo.marginBox(ddNode);
10974 var overHeight = (this.maxHeight && mb.h > this.maxHeight);
10975 dojo.style(ddNode, {
10976 overflowX: "hidden
",
10977 overflowY: overHeight ? "auto
" : "hidden
"
10980 mb.h = this.maxHeight;
10982 mb.w += 16; // room for vertical scrollbar
10990 // Adjust dropdown width to match or be larger than my width
10991 if(this.forceWidth){
10992 mb.w = this.domNode.offsetWidth;
10993 }else if(this.autoWidth){
10994 mb.w = Math.max(mb.w, this.domNode.offsetWidth);
10999 // And finally, resize the dropdown to calculated height and width
11000 if(dojo.isFunction(dropDown.resize)){
11001 dropDown.resize(mb);
11003 dojo.marginBox(ddNode, mb);
11007 var retVal = dijit.popup.open({
11010 around: this._aroundNode,
11011 orient: dijit.getPopupAroundAlignment((this.dropDownPosition && this.dropDownPosition.length) ? this.dropDownPosition : ["below
"],this.isLeftToRight()),
11012 onExecute: function(){
11013 self.closeDropDown(true);
11015 onCancel: function(){
11016 self.closeDropDown(true);
11018 onClose: function(){
11019 dojo.attr(self._popupStateNode, "popupActive
", false);
11020 dojo.removeClass(self._popupStateNode, "dijitHasDropDownOpen
");
11021 self._opened = false;
11025 dojo.attr(this._popupStateNode, "popupActive
", "true");
11026 dojo.addClass(self._popupStateNode, "dijitHasDropDownOpen
");
11028 this.state="Opened
";
11029 // TODO: set this.checked and call setStateClass(), to affect button look while drop down is shown
11033 closeDropDown: function(/*Boolean*/ focus){
11035 // Closes the drop down on this widget
11040 if(focus){ this.focus(); }
11041 dijit.popup.close(this.dropDown);
11042 this._opened = false;
11052 if(!dojo._hasResource["dijit
.form
.Button
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11053 dojo._hasResource["dijit
.form
.Button
"] = true;
11054 dojo.provide("dijit
.form
.Button
");
11060 dojo.declare("dijit
.form
.Button
",
11061 dijit.form._FormWidget,
11064 // Basically the same thing as a normal HTML button, but with special styling.
11066 // Buttons can display a label, an icon, or both.
11067 // A label should always be specified (through innerHTML) or the label
11068 // attribute. It can be hidden via showLabel=false.
11070 // | <button dojoType="dijit
.form
.Button
" onClick="...">Hello world</button>
11073 // | var button1 = new dijit.form.Button({label: "hello world
", onClick: foo});
11074 // | dojo.body().appendChild(button1.domNode);
11076 // label: HTML String
11077 // Text to display in button.
11078 // If the label is hidden (showLabel=false) then and no title has
11079 // been specified, then label is also set as title attribute of icon.
11082 // showLabel: Boolean
11083 // Set this to true to hide the label text and display only the icon.
11084 // (If showLabel=false then iconClass must be specified.)
11085 // Especially useful for toolbars.
11086 // If showLabel=true, the label will become the title (a.k.a. tooltip/hint) of the icon.
11088 // The exception case is for computers in high-contrast mode, where the label
11089 // will still be displayed, since the icon doesn't appear.
11092 // iconClass: String
11093 // Class to apply to DOMNode in button to make it display an icon
11097 // Defines the type of button. "button
", "submit
", or "reset
".
11100 baseClass: "dijitButton
",
11102 templateString: dojo.cache("dijit
.form
", "templates
/Button.html", "<span class=\"dijit dijitReset dijitInline\"\n\t><span class=\"dijitReset dijitInline dijitButtonNode\"\n\t\tdojoAttachEvent=\"ondijitclick:_onButtonClick\"\n\t\t><span class=\"dijitReset dijitStretch dijitButtonContents\"\n\t\t\tdojoAttachPoint=\"titleNode,focusNode\"\n\t\t\twaiRole=\"button\" waiState=\"labelledby-${id}_label\"\n\t\t\t><span class=\"dijitReset dijitInline dijitIcon\" dojoAttachPoint=\"iconNode\"></span\n\t\t\t><span
class=\"dijitReset dijitToggleButtonIconChar
\">●
;</span\n\t\t\t><span class=\"dijitReset dijitInline dijitButtonText\"\n\t\t\t\tid=\"${id}_label\"\n\t\t\t\tdojoAttachPoint=\"containerNode\"\n\t\t\t></span\n\t\t></span\n\t></span\n\t><input ${!nameAttrSetting} type
=\"${type}
\" value
=\"${value}
\" class=\"dijitOffScreen
\"\n\t\tdojoAttachPoint=\"valueNode
\"\n/></span>\n"),
11104 attributeMap: dojo.delegate(dijit.form._FormWidget.prototype.attributeMap, {
11105 value: "valueNode
",
11106 iconClass: { node: "iconNode
", type: "class" }
11110 _onClick: function(/*Event*/ e){
11112 // Internal function to handle click actions
11116 this._clicked(); // widget click actions
11117 return this.onClick(e); // user click actions
11120 _onButtonClick: function(/*Event*/ e){
11122 // Handler when the user activates the button portion.
11123 if(this._onClick(e) === false){ // returning nothing is same as true
11124 e.preventDefault(); // needed for checkbox
11125 }else if(this.type == "submit
" && !(this.valueNode||this.focusNode).form){ // see if a nonform widget needs to be signalled
11126 for(var node=this.domNode; node.parentNode/*#5935*/; node=node.parentNode){
11127 var widget=dijit.byNode(node);
11128 if(widget && typeof widget._onSubmit == "function"){
11129 widget._onSubmit(e);
11133 }else if(this.valueNode){
11134 this.valueNode.click();
11135 e.preventDefault(); // cancel BUTTON click and continue with hidden INPUT click
11139 _fillContent: function(/*DomNode*/ source){
11140 // Overrides _Templated._fillContent().
11141 // If button label is specified as srcNodeRef.innerHTML rather than
11142 // this.params.label, handle it here.
11143 if(source && (!this.params || !("label
" in this.params))){
11144 this.set('label', source.innerHTML);
11148 postCreate: function(){
11149 dojo.setSelectable(this.focusNode, false);
11150 this.inherited(arguments);
11153 _setShowLabelAttr: function(val){
11154 if(this.containerNode){
11155 dojo.toggleClass(this.containerNode, "dijitDisplayNone
", !val);
11157 this.showLabel = val;
11160 onClick: function(/*Event*/ e){
11162 // Callback for when button is clicked.
11163 // If type="submit
", return true to perform submit, or false to cancel it.
11166 return true; // Boolean
11169 _clicked: function(/*Event*/ e){
11171 // Internal overridable function for when the button is clicked
11174 setLabel: function(/*String*/ content){
11176 // Deprecated. Use set('label', ...) instead.
11177 dojo.deprecated("dijit
.form
.Button
.setLabel() is deprecated
. Use
set('label', ...) instead
.", "", "2.0");
11178 this.set("label
", content);
11181 _setLabelAttr: function(/*String*/ content){
11183 // Hook for attr('label', ...) to work.
11185 // Set the label (text) of the button; takes an HTML string.
11186 this.containerNode.innerHTML = this.label = content;
11187 if(this.showLabel == false && !this.params.title){
11188 this.titleNode.title = dojo.trim(this.containerNode.innerText || this.containerNode.textContent || '');
11194 dojo.declare("dijit
.form
.DropDownButton
", [dijit.form.Button, dijit._Container, dijit._HasDropDown], {
11196 // A button with a drop down
11199 // | <button dojoType="dijit
.form
.DropDownButton
" label="Hello world
">
11200 // | <div dojotype="dijit
.Menu
">...</div>
11204 // | var button1 = new dijit.form.DropDownButton({ label: "hi
", dropDown: new dijit.Menu(...) });
11205 // | dojo.body().appendChild(button1);
11208 baseClass : "dijitDropDownButton
",
11210 templateString: dojo.cache("dijit
.form
", "templates
/DropDownButton.html", "<span class=\"dijit dijitReset dijitInline\"\n\t><span class='dijitReset dijitInline dijitButtonNode'\n\t\tdojoAttachEvent=\"ondijitclick:_onButtonClick\" dojoAttachPoint=\"_buttonNode\"\n\t\t><span class=\"dijitReset dijitStretch dijitButtonContents\"\n\t\t\tdojoAttachPoint=\"focusNode,titleNode,_arrowWrapperNode\"\n\t\t\twaiRole=\"button\" waiState=\"haspopup-true,labelledby-${id}_label\"\n\t\t\t><span class=\"dijitReset dijitInline dijitIcon\"\n\t\t\t\tdojoAttachPoint=\"iconNode\"\n\t\t\t></span\n\t\t\t><span
class=\"dijitReset dijitInline dijitButtonText
\"\n\t\t\t\tdojoAttachPoint=\"containerNode
,_popupStateNode
\"\n\t\t\t\tid=\"${id}_label
\"\n\t\t\t></span\n\t\t\t><span class=\"dijitReset dijitInline dijitArrowButtonInner\"></span\n\t\t\t><span
class=\"dijitReset dijitInline dijitArrowButtonChar
\">▼</span\n\t\t></span\n\t></span\n\t><input ${!nameAttrSetting} type=\"${type}\" value=\"${value}\" class=\"dijitOffScreen\"\n\t\tdojoAttachPoint=\"valueNode\"\n/></span
>\n"),
11212 _fillContent: function(){
11213 // Overrides Button._fillContent().
11215 // My inner HTML contains both the button contents and a drop down widget, like
11216 // <DropDownButton> <span>push me</span> <Menu> ... </Menu> </DropDownButton>
11217 // The first node is assumed to be the button content. The widget is the popup.
11219 if(this.srcNodeRef){ // programatically created buttons might not define srcNodeRef
11220 //FIXME: figure out how to filter out the widget and use all remaining nodes as button
11221 // content, not just nodes[0]
11222 var nodes = dojo.query("*", this.srcNodeRef);
11223 dijit.form.DropDownButton.superclass._fillContent.call(this, nodes[0]);
11225 // save pointer to srcNode so we can grab the drop down widget after it's instantiated
11226 this.dropDownContainer = this.srcNodeRef;
11230 startup: function(){
11231 if(this._started){ return; }
11233 // the child widget from srcNodeRef is the dropdown widget. Insert it in the page DOM,
11234 // make it invisible, and store a reference to pass to the popup code.
11235 if(!this.dropDown){
11236 var dropDownNode = dojo.query("[widgetId
]", this.dropDownContainer)[0];
11237 this.dropDown = dijit.byNode(dropDownNode);
11238 delete this.dropDownContainer;
11240 dijit.popup.moveOffScreen(this.dropDown.domNode);
11242 this.inherited(arguments);
11245 isLoaded: function(){
11246 // Returns whether or not we are loaded - if our dropdown has an href,
11247 // then we want to check that.
11248 var dropDown = this.dropDown;
11249 return (!dropDown.href || dropDown.isLoaded);
11252 loadDropDown: function(){
11253 // Loads our dropdown
11254 var dropDown = this.dropDown;
11255 if(!dropDown){ return; }
11256 if(!this.isLoaded()){
11257 var handler = dojo.connect(dropDown, "onLoad
", this, function(){
11258 dojo.disconnect(handler);
11259 this.openDropDown();
11261 dropDown.refresh();
11263 this.openDropDown();
11267 isFocusable: function(){
11268 // Overridden so that focus is handled by the _HasDropDown mixin, not by
11269 // the _FormWidget mixin.
11270 return this.inherited(arguments) && !this._mouseDown;
11274 dojo.declare("dijit
.form
.ComboButton
", dijit.form.DropDownButton, {
11276 // A combination button and drop-down button.
11277 // Users can click one side to "press
" the button, or click an arrow
11278 // icon to display the drop down.
11281 // | <button dojoType="dijit
.form
.ComboButton
" onClick="...">
11282 // | <span>Hello world</span>
11283 // | <div dojoType="dijit
.Menu
">...</div>
11287 // | var button1 = new dijit.form.ComboButton({label: "hello world
", onClick: foo, dropDown: "myMenu
"});
11288 // | dojo.body().appendChild(button1.domNode);
11291 templateString: dojo.cache("dijit
.form
", "templates
/ComboButton.html", "<table class=\"dijit dijitReset dijitInline dijitLeft\"\n\tcellspacing='0' cellpadding='0' waiRole=\"presentation\"\n\t><tbody waiRole=\"presentation\"><tr waiRole=\"presentation\"\n\t\t><td class=\"dijitReset dijitStretch dijitButtonNode\" dojoAttachPoint=\"buttonNode\" dojoAttachEvent=\"ondijitclick:_onButtonClick,onkeypress:_onButtonKeyPress\"\n\t\t><div id=\"${id}_button\" class=\"dijitReset dijitButtonContents\"\n\t\t\tdojoAttachPoint=\"titleNode\"\n\t\t\twaiRole=\"button\" waiState=\"labelledby-${id}_label\"\n\t\t\t><div class=\"dijitReset dijitInline dijitIcon\" dojoAttachPoint=\"iconNode\" waiRole=\"presentation\"></div\n\t\t\t><div
class=\"dijitReset dijitInline dijitButtonText
\" id
=\"${id}_label
\" dojoAttachPoint
=\"containerNode
\" waiRole
=\"presentation
\"></div\n\t\t></div\n\t\t></td\n\t\t><td id=\"${id}_arrow\" class='dijitReset dijitRight dijitButtonNode dijitArrowButton'\n\t\t\tdojoAttachPoint=\"_popupStateNode,focusNode,_buttonNode\"\n\t\t\tdojoAttachEvent=\"onkeypress:_onArrowKeyPress\"\n\t\t\ttitle=\"${optionsTitle}\"\n\t\t\twaiRole=\"button\" waiState=\"haspopup-true\"\n\t\t\t><div class=\"dijitReset dijitArrowButtonInner\" waiRole=\"presentation\"></div\n\t\t\t><div
class=\"dijitReset dijitArrowButtonChar
\" waiRole
=\"presentation
\">▼</div\n\t\t></td
\n\t\t><td style
=\"display
:none
!important
;\"\n\t\t\t><input ${!nameAttrSetting} type
=\"${type}
\" value
=\"${value}
\" dojoAttachPoint
=\"valueNode
\"\n\t\t/></td
></tr></tbody
\n></table
>\n"),
11293 attributeMap: dojo.mixin(dojo.clone(dijit.form.Button.prototype.attributeMap), {
11295 tabIndex: ["focusNode
", "titleNode
"],
11299 // optionsTitle: String
11300 // Text that describes the options menu (accessibility)
11303 baseClass: "dijitComboButton
",
11305 // Set classes like dijitButtonContentsHover or dijitArrowButtonActive depending on
11306 // mouse action over specified node
11308 "buttonNode
": "dijitButtonNode
",
11309 "titleNode
": "dijitButtonContents
",
11310 "_popupStateNode
": "dijitDownArrowButton
"
11313 _focusedNode: null,
11315 _onButtonKeyPress: function(/*Event*/ evt){
11317 // Handler for right arrow key when focus is on left part of button
11318 if(evt.charOrCode == dojo.keys[this.isLeftToRight() ? "RIGHT_ARROW
" : "LEFT_ARROW
"]){
11319 dijit.focus(this._popupStateNode);
11320 dojo.stopEvent(evt);
11324 _onArrowKeyPress: function(/*Event*/ evt){
11326 // Handler for left arrow key when focus is on right part of button
11327 if(evt.charOrCode == dojo.keys[this.isLeftToRight() ? "LEFT_ARROW
" : "RIGHT_ARROW
"]){
11328 dijit.focus(this.titleNode);
11329 dojo.stopEvent(evt);
11333 focus: function(/*String*/ position){
11335 // Focuses this widget to according to position, if specified,
11336 // otherwise on arrow node
11338 // "start
" or "end
"
11340 dijit.focus(position == "start
" ? this.titleNode : this._popupStateNode);
11344 dojo.declare("dijit
.form
.ToggleButton
", dijit.form.Button, {
11346 // A button that can be in two states (checked or not).
11347 // Can be base class for things like tabs or checkbox or radio buttons
11349 baseClass: "dijitToggleButton
",
11351 // checked: Boolean
11352 // Corresponds to the native HTML <input> element's attribute.
11353 // In markup, specified as "checked
='checked'" or just "checked
".
11354 // True if the button is depressed, or the checkbox is checked,
11355 // or the radio button is selected, etc.
11358 attributeMap: dojo.mixin(dojo.clone(dijit.form.Button.prototype.attributeMap), {
11359 checked:"focusNode
"
11362 _clicked: function(/*Event*/ evt){
11363 this.set('checked', !this.checked);
11366 _setCheckedAttr: function(/*Boolean*/ value, /* Boolean? */ priorityChange){
11367 this.checked = value;
11368 dojo.attr(this.focusNode || this.domNode, "checked
", value);
11369 dijit.setWaiState(this.focusNode || this.domNode, "pressed
", value);
11370 this._handleOnChange(value, priorityChange);
11373 setChecked: function(/*Boolean*/ checked){
11375 // Deprecated. Use set('checked', true/false) instead.
11376 dojo.deprecated("setChecked("+checked+") is deprecated
. Use
set('checked',"+checked+") instead
.", "", "2.0");
11377 this.set('checked', checked);
11382 // Reset the widget's value to what it was at initialization time
11384 this._hasBeenBlurred = false;
11386 // set checked state to original setting
11387 this.set('checked', this.params.checked || false);
11393 if(!dojo._hasResource["dijit
.form
.ToggleButton
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11394 dojo._hasResource["dijit
.form
.ToggleButton
"] = true;
11395 dojo.provide("dijit
.form
.ToggleButton
");
11400 if(!dojo._hasResource["dijit
.form
.CheckBox
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11401 dojo._hasResource["dijit
.form
.CheckBox
"] = true;
11402 dojo.provide("dijit
.form
.CheckBox
");
11407 "dijit
.form
.CheckBox
",
11408 dijit.form.ToggleButton,
11411 // Same as an HTML checkbox, but with fancy styling.
11414 // User interacts with real html inputs.
11415 // On onclick (which occurs by mouse click, space-bar, or
11416 // using the arrow keys to switch the selected radio button),
11417 // we update the state of the checkbox/radio.
11419 // There are two modes:
11420 // 1. High contrast mode
11423 // In case 1, the regular html inputs are shown and used by the user.
11424 // In case 2, the regular html inputs are invisible but still used by
11425 // the user. They are turned quasi-invisible and overlay the background-image.
11427 templateString: dojo.cache("dijit
.form
", "templates
/CheckBox.html", "<div class=\"dijit dijitReset dijitInline\" waiRole=\"presentation\"\n\t><input\n\t \t${!nameAttrSetting} type=\"${type}\" ${checkedAttrSetting}\n\t\tclass=\"dijitReset dijitCheckBoxInput\"\n\t\tdojoAttachPoint=\"focusNode\"\n\t \tdojoAttachEvent=\"onclick:_onClick\"\n/></div
>\n"),
11429 baseClass: "dijitCheckBox
",
11431 // type: [private] String
11432 // type attribute on <input> node.
11433 // Overrides `dijit.form.Button.type`. Users should not change this value.
11437 // As an initialization parameter, equivalent to value field on normal checkbox
11438 // (if checked, the value is passed as the value when form is submitted).
11440 // However, attr('value') will return either the string or false depending on
11441 // whether or not the checkbox is checked.
11443 // attr('value', string) will check the checkbox and change the value to the
11444 // specified string
11446 // attr('value', boolean) will change the checked state.
11449 // readOnly: Boolean
11450 // Should this widget respond to user input?
11451 // In markup, this is specified as "readOnly
".
11452 // Similar to disabled except readOnly form values are submitted.
11455 // the attributeMap should inherit from dijit.form._FormWidget.prototype.attributeMap
11456 // instead of ToggleButton as the icon mapping has no meaning for a CheckBox
11457 attributeMap: dojo.delegate(dijit.form._FormWidget.prototype.attributeMap, {
11458 readOnly: "focusNode
"
11461 _setReadOnlyAttr: function(/*Boolean*/ value){
11462 this.readOnly = value;
11463 dojo.attr(this.focusNode, 'readOnly', value);
11464 dijit.setWaiState(this.focusNode, "readonly
", value);
11467 _setValueAttr: function(/*String or Boolean*/ newValue, /*Boolean*/ priorityChange){
11469 // Handler for value= attribute to constructor, and also calls to
11470 // attr('value', val).
11472 // During initialization, just saves as attribute to the <input type=checkbox>.
11474 // After initialization,
11475 // when passed a boolean, controls whether or not the CheckBox is checked.
11476 // If passed a string, changes the value attribute of the CheckBox (the one
11477 // specified as "value
" when the CheckBox was constructed (ex: <input
11478 // dojoType="dijit
.CheckBox
" value="chicken
">)
11479 if(typeof newValue == "string
"){
11480 this.value = newValue;
11481 dojo.attr(this.focusNode, 'value', newValue);
11485 this.set('checked', newValue, priorityChange);
11488 _getValueAttr: function(){
11490 // Hook so attr('value') works.
11492 // If the CheckBox is checked, returns the value attribute.
11493 // Otherwise returns false.
11494 return (this.checked ? this.value : false);
11497 // Override dijit.form.Button._setLabelAttr() since we don't even have a containerNode.
11498 // Normally users won't try to set label, except when CheckBox or RadioButton is the child of a dojox.layout.TabContainer
11499 _setLabelAttr: undefined,
11501 postMixInProperties: function(){
11502 if(this.value == ""){
11506 // Need to set initial checked state as part of template, so that form submit works.
11507 // dojo.attr(node, "checked
", bool) doesn't work on IEuntil node has been attached
11508 // to <body>, see #8666
11509 this.checkedAttrSetting = this.checked ? "checked
" : "";
11511 this.inherited(arguments);
11514 _fillContent: function(/*DomNode*/ source){
11515 // Override Button::_fillContent() since it doesn't make sense for CheckBox,
11516 // since CheckBox doesn't even have a container
11520 // Override ToggleButton.reset()
11522 this._hasBeenBlurred = false;
11524 this.set('checked', this.params.checked || false);
11526 // Handle unlikely event that the <input type=checkbox> value attribute has changed
11527 this.value = this.params.value || "on
";
11528 dojo.attr(this.focusNode, 'value', this.value);
11531 _onFocus: function(){
11533 dojo.query("label
[for='"+this.id+"']").addClass("dijitFocusedLabel
");
11535 this.inherited(arguments);
11538 _onBlur: function(){
11540 dojo.query("label
[for='"+this.id+"']").removeClass("dijitFocusedLabel
");
11542 this.inherited(arguments);
11545 _onClick: function(/*Event*/ e){
11547 // Internal function to handle click actions - need to check
11548 // readOnly, since button no longer does that check.
11552 return this.inherited(arguments);
11558 "dijit
.form
.RadioButton
",
11559 dijit.form.CheckBox,
11562 // Same as an HTML radio, but with fancy styling.
11565 baseClass: "dijitRadio
",
11567 _setCheckedAttr: function(/*Boolean*/ value){
11568 // If I am being checked then have to deselect currently checked radio button
11569 this.inherited(arguments);
11570 if(!this._created){ return; }
11573 // search for radio buttons with the same name that need to be unchecked
11574 dojo.query("INPUT
[type
=radio
]", this.focusNode.form || dojo.doc).forEach( // can't use name= since dojo.query doesn't support [] in the name
11575 function(inputNode){
11576 if(inputNode.name == _this.name && inputNode != _this.focusNode && inputNode.form == _this.focusNode.form){
11577 var widget = dijit.getEnclosingWidget(inputNode);
11578 if(widget && widget.checked){
11579 widget.set('checked', false);
11587 _clicked: function(/*Event*/ e){
11589 this.set('checked', true);
11597 if(!dojo._hasResource["dijit
.form
.DropDownButton
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11598 dojo._hasResource["dijit
.form
.DropDownButton
"] = true;
11599 dojo.provide("dijit
.form
.DropDownButton
");
11605 if(!dojo._hasResource["dojo
.regexp
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11606 dojo._hasResource["dojo
.regexp
"] = true;
11607 dojo.provide("dojo
.regexp
");
11611 // summary: Regular expressions and Builder resources
11615 dojo.regexp.escapeString = function(/*String*/str, /*String?*/except){
11617 // Adds escape sequences for special characters in regular expressions
11619 // a String with special characters to be left unescaped
11621 return str.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, function(ch){
11622 if(except && except.indexOf(ch) != -1){
11629 dojo.regexp.buildGroupRE = function(/*Object|Array*/arr, /*Function*/re, /*Boolean?*/nonCapture){
11631 // Builds a regular expression that groups subexpressions
11633 // A utility function used by some of the RE generators. The
11634 // subexpressions are constructed by the function, re, in the second
11635 // parameter. re builds one subexpression for each elem in the array
11636 // a, in the first parameter. Returns a string for a regular
11637 // expression that groups all the subexpressions.
11639 // A single value or an array of values.
11641 // A function. Takes one parameter and converts it to a regular
11644 // If true, uses non-capturing match, otherwise matches are retained
11645 // by regular expression. Defaults to false
11647 // case 1: a is a single value.
11648 if(!(arr instanceof Array)){
11649 return re(arr); // String
11652 // case 2: a is an array
11654 for(var i = 0; i < arr.length; i++){
11655 // convert each elem to a RE
11656 b.push(re(arr[i]));
11659 // join the REs as alternatives in a RE group.
11660 return dojo.regexp.group(b.join("|"), nonCapture); // String
11663 dojo.regexp.group = function(/*String*/expression, /*Boolean?*/nonCapture){
11665 // adds group match to expression
11667 // If true, uses non-capturing match, otherwise matches are retained
11668 // by regular expression.
11669 return "(" + (nonCapture ? "?:":"") + expression + ")"; // String
11674 if(!dojo._hasResource["dojo
.data
.util
.sorter
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11675 dojo._hasResource["dojo
.data
.util
.sorter
"] = true;
11676 dojo.provide("dojo
.data
.util
.sorter
");
11678 dojo.data.util.sorter.basicComparator = function( /*anything*/ a,
11681 // Basic comparision function that compares if an item is greater or less than another item
11683 // returns 1 if a > b, -1 if a < b, 0 if equal.
11684 // 'null' values (null, undefined) are treated as larger values so that they're pushed to the end of the list.
11685 // And compared to each other, null is equivalent to undefined.
11687 //null is a problematic compare, so if null, we set to undefined.
11688 //Makes the check logic simple, compact, and consistent
11689 //And (null == undefined) === true, so the check later against null
11690 //works for undefined and is less bytes.
11700 }else if(a > b || a == null){
11703 return r; //int {-1,0,1}
11706 dojo.data.util.sorter.createSortFunction = function( /* attributes array */sortSpec,
11707 /*dojo.data.core.Read*/ store){
11709 // Helper function to generate the sorting function based off the list of sort attributes.
11711 // The sort function creation will look for a property on the store called 'comparatorMap'. If it exists
11712 // it will look in the mapping for comparisons function for the attributes. If one is found, it will
11713 // use it instead of the basic comparator, which is typically used for strings, ints, booleans, and dates.
11714 // Returns the sorting function for this particular list of attributes and sorting directions.
11717 // A JS object that array that defines out what attribute names to sort on and whether it should be descenting or asending.
11718 // The objects should be formatted as follows:
11720 // attribute: "attributeName
-string
" || attribute,
11721 // descending: true|false; // Default is false.
11724 // The datastore object to look up item values from.
11726 var sortFunctions=[];
11728 function createSortFunction(attr, dir, comp, s){
11729 //Passing in comp and s (comparator and store), makes this
11730 //function much faster.
11731 return function(itemA, itemB){
11732 var a = s.getValue(itemA, attr);
11733 var b = s.getValue(itemB, attr);
11734 return dir * comp(a,b); //int
11738 var map = store.comparatorMap;
11739 var bc = dojo.data.util.sorter.basicComparator;
11740 for(var i = 0; i < sortSpec.length; i++){
11741 sortAttribute = sortSpec[i];
11742 var attr = sortAttribute.attribute;
11744 var dir = (sortAttribute.descending) ? -1 : 1;
11747 if(typeof attr !== "string
" && ("toString
" in attr)){
11748 attr = attr.toString();
11750 comp = map[attr] || bc;
11752 sortFunctions.push(createSortFunction(attr,
11753 dir, comp, store));
11756 return function(rowA, rowB){
11758 while(i < sortFunctions.length){
11759 var ret = sortFunctions[i++](rowA, rowB);
11770 if(!dojo._hasResource["dojo
.data
.util
.simpleFetch
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11771 dojo._hasResource["dojo
.data
.util
.simpleFetch
"] = true;
11772 dojo.provide("dojo
.data
.util
.simpleFetch
");
11775 dojo.data.util.simpleFetch.fetch = function(/* Object? */ request){
11777 // The simpleFetch mixin is designed to serve as a set of function(s) that can
11778 // be mixed into other datastore implementations to accelerate their development.
11779 // The simpleFetch mixin should work well for any datastore that can respond to a _fetchItems()
11780 // call by returning an array of all the found items that matched the query. The simpleFetch mixin
11781 // is not designed to work for datastores that respond to a fetch() call by incrementally
11782 // loading items, or sequentially loading partial batches of the result
11783 // set. For datastores that mixin simpleFetch, simpleFetch
11784 // implements a fetch method that automatically handles eight of the fetch()
11785 // arguments -- onBegin, onItem, onComplete, onError, start, count, sort and scope
11786 // The class mixing in simpleFetch should not implement fetch(),
11787 // but should instead implement a _fetchItems() method. The _fetchItems()
11788 // method takes three arguments, the keywordArgs object that was passed
11789 // to fetch(), a callback function to be called when the result array is
11790 // available, and an error callback to be called if something goes wrong.
11791 // The _fetchItems() method should ignore any keywordArgs parameters for
11792 // start, count, onBegin, onItem, onComplete, onError, sort, and scope.
11793 // The _fetchItems() method needs to correctly handle any other keywordArgs
11794 // parameters, including the query parameter and any optional parameters
11795 // (such as includeChildren). The _fetchItems() method should create an array of
11796 // result items and pass it to the fetchHandler along with the original request object
11797 // -- or, the _fetchItems() method may, if it wants to, create an new request object
11798 // with other specifics about the request that are specific to the datastore and pass
11799 // that as the request object to the handler.
11801 // For more information on this specific function, see dojo.data.api.Read.fetch()
11802 request = request || {};
11803 if(!request.store){
11804 request.store = this;
11808 var _errorHandler = function(errorData, requestObject){
11809 if(requestObject.onError){
11810 var scope = requestObject.scope || dojo.global;
11811 requestObject.onError.call(scope, errorData, requestObject);
11815 var _fetchHandler = function(items, requestObject){
11816 var oldAbortFunction = requestObject.abort || null;
11817 var aborted = false;
11819 var startIndex = requestObject.start?requestObject.start:0;
11820 var endIndex = (requestObject.count && (requestObject.count !== Infinity))?(startIndex + requestObject.count):items.length;
11822 requestObject.abort = function(){
11824 if(oldAbortFunction){
11825 oldAbortFunction.call(requestObject);
11829 var scope = requestObject.scope || dojo.global;
11830 if(!requestObject.store){
11831 requestObject.store = self;
11833 if(requestObject.onBegin){
11834 requestObject.onBegin.call(scope, items.length, requestObject);
11836 if(requestObject.sort){
11837 items.sort(dojo.data.util.sorter.createSortFunction(requestObject.sort, self));
11839 if(requestObject.onItem){
11840 for(var i = startIndex; (i < items.length) && (i < endIndex); ++i){
11841 var item = items[i];
11843 requestObject.onItem.call(scope, item, requestObject);
11847 if(requestObject.onComplete && !aborted){
11849 if(!requestObject.onItem){
11850 subset = items.slice(startIndex, endIndex);
11852 requestObject.onComplete.call(scope, subset, requestObject);
11855 this._fetchItems(request, _fetchHandler, _errorHandler);
11856 return request; // Object
11861 if(!dojo._hasResource["dojo
.data
.util
.filter
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11862 dojo._hasResource["dojo
.data
.util
.filter
"] = true;
11863 dojo.provide("dojo
.data
.util
.filter
");
11865 dojo.data.util.filter.patternToRegExp = function(/*String*/pattern, /*boolean?*/ ignoreCase){
11867 // Helper function to convert a simple pattern to a regular expression for matching.
11869 // Returns a regular expression object that conforms to the defined conversion rules.
11872 // *ca* -> /^.*ca.*$/
11873 // *c\*a* -> /^.*c\*a.*$/
11874 // *c\*a?* -> /^.*c\*a..*$/
11878 // A simple matching pattern to convert that follows basic rules:
11879 // * Means match anything, so ca* means match anything starting with ca
11880 // ? Means match single character. So, b?b will match to bob and bab, and so on.
11881 // \ is an escape character. So for example, \* means do not treat * as a match, but literal character *.
11882 // To use a \ as a character in the string, it must be escaped. So in the pattern it should be
11883 // represented by \\ to be treated as an ordinary \ character instead of an escape.
11886 // An optional flag to indicate if the pattern matching should be treated as case-sensitive or not when comparing
11887 // By default, it is assumed case sensitive.
11891 for(var i = 0; i < pattern.length; i++){
11892 c = pattern.charAt(i);
11897 rxp += pattern.charAt(i);
11900 rxp += ".*"; break;
11915 rxp += "\\"; //fallthrough
11922 return new RegExp(rxp,"mi
"); //RegExp
11924 return new RegExp(rxp,"m
"); //RegExp
11931 if(!dojo._hasResource["dijit
.form
.TextBox
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
11932 dojo._hasResource["dijit
.form
.TextBox
"] = true;
11933 dojo.provide("dijit
.form
.TextBox
");
11938 "dijit
.form
.TextBox
",
11939 dijit.form._FormValueWidget,
11942 // A base class for textbox form inputs
11945 // Removes leading and trailing whitespace if true. Default is false.
11948 // uppercase: Boolean
11949 // Converts all characters to uppercase if true. Default is false.
11952 // lowercase: Boolean
11953 // Converts all characters to lowercase if true. Default is false.
11956 // propercase: Boolean
11957 // Converts the first character of each word to uppercase if true.
11960 // maxLength: String
11961 // HTML INPUT tag maxLength declaration.
11964 // selectOnClick: [const] Boolean
11965 // If true, all text will be selected when focused with mouse
11966 selectOnClick: false,
11968 // placeHolder: String
11969 // Defines a hint to help users fill out the input field (as defined in HTML 5).
11970 // This should only contain plain text (no html markup).
11973 templateString: dojo.cache("dijit
.form
", "templates
/TextBox.html", "<div class=\"dijit dijitReset dijitInline dijitLeft\" id=\"widget_${id}\" waiRole=\"presentation\"\n\t><div class=\"dijitReset dijitInputField dijitInputContainer\"\n\t\t><input class=\"dijitReset dijitInputInner\" dojoAttachPoint='textbox,focusNode' autocomplete=\"off\"\n\t\t\t${!nameAttrSetting} type='${type}'\n\t/></div\n></div>\n"),
11974 _singleNodeTemplate: '<input class="dijit dijitReset dijitLeft dijitInputField
" dojoAttachPoint="textbox
,focusNode
" autocomplete="off
" type="${type}
" ${!nameAttrSetting} />',
11976 _buttonInputDisabled: dojo.isIE ? "disabled
" : "", // allows IE to disallow focus, but Firefox cannot be disabled for mousedown events
11978 baseClass: "dijitTextBox
",
11980 attributeMap: dojo.delegate(dijit.form._FormValueWidget.prototype.attributeMap, {
11981 maxLength: "focusNode
"
11984 postMixInProperties: function(){
11985 var type = this.type.toLowerCase();
11986 if(this.templateString.toLowerCase() == "input
" || ((type == "hidden
" || type == "file
") && this.templateString == dijit.form.TextBox.prototype.templateString)){
11987 this.templateString = this._singleNodeTemplate;
11989 this.inherited(arguments);
11992 _setPlaceHolderAttr: function(v){
11993 this.placeHolder = v;
11995 this._attachPoints.push('_phspan');
11996 /* dijitInputField class gives placeHolder same padding as the input field
11997 * parent node already has dijitInputField class but it doesn't affect this <span>
11998 * since it's position: absolute.
12000 this._phspan = dojo.create('span',{className:'dijitPlaceHolder dijitInputField'},this.textbox,'after');
12002 this._phspan.innerHTML="";
12003 this._phspan.appendChild(document.createTextNode(v));
12005 this._updatePlaceHolder();
12008 _updatePlaceHolder: function(){
12010 this._phspan.style.display=(this.placeHolder&&!this._focused&&!this.textbox.value)?"":"none
";
12014 _getValueAttr: function(){
12016 // Hook so attr('value') works as we like.
12018 // For `dijit.form.TextBox` this basically returns the value of the <input>.
12020 // For `dijit.form.MappedTextBox` subclasses, which have both
12021 // a "displayed value
" and a separate "submit value
",
12022 // This treats the "displayed value
" as the master value, computing the
12023 // submit value from it via this.parse().
12024 return this.parse(this.get('displayedValue'), this.constraints);
12027 _setValueAttr: function(value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
12029 // Hook so attr('value', ...) works.
12032 // Sets the value of the widget to "value
" which can be of
12033 // any type as determined by the widget.
12036 // The visual element value is also set to a corresponding,
12037 // but not necessarily the same, value.
12040 // If specified, used to set the visual element value,
12041 // otherwise a computed visual value is used.
12044 // If true, an onChange event is fired immediately instead of
12045 // waiting for the next blur event.
12048 if(value !== undefined){
12049 // TODO: this is calling filter() on both the display value and the actual value.
12050 // I added a comment to the filter() definition about this, but it should be changed.
12051 filteredValue = this.filter(value);
12052 if(typeof formattedValue != "string
"){
12053 if(filteredValue !== null && ((typeof filteredValue != "number
") || !isNaN(filteredValue))){
12054 formattedValue = this.filter(this.format(filteredValue, this.constraints));
12055 }else{ formattedValue = ''; }
12058 if(formattedValue != null && formattedValue != undefined && ((typeof formattedValue) != "number
" || !isNaN(formattedValue)) && this.textbox.value != formattedValue){
12059 this.textbox.value = formattedValue;
12062 this._updatePlaceHolder();
12064 this.inherited(arguments, [filteredValue, priorityChange]);
12067 // displayedValue: String
12068 // For subclasses like ComboBox where the displayed value
12069 // (ex: Kentucky) and the serialized value (ex: KY) are different,
12070 // this represents the displayed value.
12072 // Setting 'displayedValue' through attr('displayedValue', ...)
12073 // updates 'value', and vice-versa. Otherwise 'value' is updated
12074 // from 'displayedValue' periodically, like onBlur etc.
12076 // TODO: move declaration to MappedTextBox?
12077 // Problem is that ComboBox references displayedValue,
12078 // for benefit of FilteringSelect.
12079 displayedValue: "",
12081 getDisplayedValue: function(){
12083 // Deprecated. Use set('displayedValue') instead.
12086 dojo.deprecated(this.declaredClass+"::getDisplayedValue() is deprecated
. Use
set('displayedValue') instead
.", "", "2.0");
12087 return this.get('displayedValue');
12090 _getDisplayedValueAttr: function(){
12092 // Hook so attr('displayedValue') works.
12094 // Returns the displayed value (what the user sees on the screen),
12095 // after filtering (ie, trimming spaces etc.).
12097 // For some subclasses of TextBox (like ComboBox), the displayed value
12098 // is different from the serialized value that's actually
12099 // sent to the server (see dijit.form.ValidationTextBox.serialize)
12101 return this.filter(this.textbox.value);
12104 setDisplayedValue: function(/*String*/value){
12106 // Deprecated. Use set('displayedValue', ...) instead.
12109 dojo.deprecated(this.declaredClass+"::setDisplayedValue() is deprecated
. Use
set('displayedValue', ...) instead
.", "", "2.0");
12110 this.set('displayedValue', value);
12113 _setDisplayedValueAttr: function(/*String*/value){
12115 // Hook so attr('displayedValue', ...) works.
12117 // Sets the value of the visual element to the string "value
".
12118 // The widget value is also set to a corresponding,
12119 // but not necessarily the same, value.
12121 if(value === null || value === undefined){ value = '' }
12122 else if(typeof value != "string
"){ value = String(value) }
12123 this.textbox.value = value;
12124 this._setValueAttr(this.get('value'), undefined, value);
12127 format: function(/* String */ value, /* Object */ constraints){
12129 // Replacable function to convert a value to a properly formatted string.
12131 // protected extension
12132 return ((value == null || value == undefined) ? "" : (value.toString ? value.toString() : value));
12135 parse: function(/* String */ value, /* Object */ constraints){
12137 // Replacable function to convert a formatted string to a value
12139 // protected extension
12141 return value; // String
12144 _refreshState: function(){
12146 // After the user types some characters, etc., this method is
12147 // called to check the field for validity etc. The base method
12148 // in `dijit.form.TextBox` does nothing, but subclasses override.
12153 _onInput: function(e){
12154 if(e && e.type && /key/i.test(e.type) && e.keyCode){
12156 case dojo.keys.SHIFT:
12157 case dojo.keys.ALT:
12158 case dojo.keys.CTRL:
12159 case dojo.keys.TAB:
12163 if(this.intermediateChanges){
12165 // the setTimeout allows the key to post to the widget input box
12166 setTimeout(function(){ _this._handleOnChange(_this.get('value'), false); }, 0);
12168 this._refreshState();
12171 postCreate: function(){
12172 // setting the value here is needed since value="" in the template causes "undefined"
12173 // and setting in the DOM (instead of the JS object) helps with form reset actions
12174 if(dojo.isIE){ // IE INPUT tag fontFamily has to be set directly using STYLE
12175 var s = dojo.getComputedStyle(this.domNode);
12177 var ff = s.fontFamily;
12179 var inputs = this.domNode.getElementsByTagName("INPUT
");
12181 for(var i=0; i < inputs.length; i++){
12182 inputs[i].style.fontFamily = ff;
12188 this.textbox.setAttribute("value
", this.textbox.value); // DOM and JS values shuld be the same
12189 this.inherited(arguments);
12190 if(dojo.isMoz || dojo.isOpera){
12191 this.connect(this.textbox, "oninput
", this._onInput);
12193 this.connect(this.textbox, "onkeydown
", this._onInput);
12194 this.connect(this.textbox, "onkeyup
", this._onInput);
12195 this.connect(this.textbox, "onpaste
", this._onInput);
12196 this.connect(this.textbox, "oncut
", this._onInput);
12200 _blankValue: '', // if the textbox is blank, what value should be reported
12201 filter: function(val){
12203 // Auto-corrections (such as trimming) that are applied to textbox
12204 // value on blur or form submit.
12206 // For MappedTextBox subclasses, this is called twice
12207 // - once with the display value
12208 // - once the value as set/returned by attr('value', ...)
12209 // and attr('value'), ex: a Number for NumberTextBox.
12211 // In the latter case it does corrections like converting null to NaN. In
12212 // the former case the NumberTextBox.filter() method calls this.inherited()
12213 // to execute standard trimming code in TextBox.filter().
12215 // TODO: break this into two methods in 2.0
12218 // protected extension
12219 if(val === null){ return this._blankValue; }
12220 if(typeof val != "string
"){ return val; }
12222 val = dojo.trim(val);
12224 if(this.uppercase){
12225 val = val.toUpperCase();
12227 if(this.lowercase){
12228 val = val.toLowerCase();
12230 if(this.propercase){
12231 val = val.replace(/[^\s]+/g, function(word){
12232 return word.substring(0,1).toUpperCase() + word.substring(1);
12238 _setBlurValue: function(){
12239 this._setValueAttr(this.get('value'), true);
12242 _onBlur: function(e){
12243 if(this.disabled){ return; }
12244 this._setBlurValue();
12245 this.inherited(arguments);
12247 if(this._selectOnClickHandle){
12248 this.disconnect(this._selectOnClickHandle);
12250 if(this.selectOnClick && dojo.isMoz){
12251 this.textbox.selectionStart = this.textbox.selectionEnd = undefined; // clear selection so that the next mouse click doesn't reselect
12254 this._updatePlaceHolder();
12257 _onFocus: function(/*String*/ by){
12258 if(this.disabled || this.readOnly){ return; }
12260 // Select all text on focus via click if nothing already selected.
12261 // Since mouse-up will clear the selection need to defer selection until after mouse-up.
12262 // Don't do anything on focus by tabbing into the widget since there's no associated mouse-up event.
12263 if(this.selectOnClick && by == "mouse
"){
12264 this._selectOnClickHandle = this.connect(this.domNode, "onmouseup
", function(){
12265 // Only select all text on first click; otherwise users would have no way to clear
12267 this.disconnect(this._selectOnClickHandle);
12269 // Check if the user selected some text manually (mouse-down, mouse-move, mouse-up)
12270 // and if not, then select all the text
12271 var textIsNotSelected;
12273 var range = dojo.doc.selection.createRange();
12274 var parent = range.parentElement();
12275 textIsNotSelected = parent == this.textbox && range.text.length == 0;
12277 textIsNotSelected = this.textbox.selectionStart == this.textbox.selectionEnd;
12279 if(textIsNotSelected){
12280 dijit.selectInputText(this.textbox);
12285 this._updatePlaceHolder();
12287 this._refreshState();
12288 this.inherited(arguments);
12292 // Overrides dijit._FormWidget.reset().
12293 // Additionally resets the displayed textbox value to ''
12294 this.textbox.value = '';
12295 this.inherited(arguments);
12300 dijit.selectInputText = function(/*DomNode*/element, /*Number?*/ start, /*Number?*/ stop){
12302 // Select text in the input element argument, from start (default 0), to stop (default end).
12304 // TODO: use functions in _editor/selection.js?
12305 var _window = dojo.global;
12306 var _document = dojo.doc;
12307 element = dojo.byId(element);
12308 if(isNaN(start)){ start = 0; }
12309 if(isNaN(stop)){ stop = element.value ? element.value.length : 0; }
12310 dijit.focus(element);
12311 if(_document["selection
"] && dojo.body()["createTextRange
"]){ // IE
12312 if(element.createTextRange){
12313 var range = element.createTextRange();
12316 moveStart("character
", -99999); // move to 0
12317 moveStart("character
", start); // delta from 0 is the correct position
12318 moveEnd("character
", stop-start);
12322 }else if(_window["getSelection
"]){
12323 if(element.setSelectionRange){
12324 element.setSelectionRange(start, stop);
12331 if(!dojo._hasResource["dijit
.Tooltip
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
12332 dojo._hasResource["dijit
.Tooltip
"] = true;
12333 dojo.provide("dijit
.Tooltip
");
12339 "dijit
._MasterTooltip
",
12340 [dijit._Widget, dijit._Templated],
12343 // Internal widget that holds the actual tooltip markup,
12344 // which occurs once per page.
12345 // Called by Tooltip widgets which are just containers to hold
12350 // duration: Integer
12351 // Milliseconds to fade in/fade out
12352 duration: dijit.defaultDuration,
12354 templateString: dojo.cache("dijit
", "templates
/Tooltip.html", "<div class=\"dijitTooltip dijitTooltipLeft\" id=\"dojoTooltip\">\n\t<div class=\"dijitTooltipContainer dijitTooltipContents\" dojoAttachPoint=\"containerNode\" waiRole='alert'></div>\n\t<div
class=\"dijitTooltipConnector
\"></div>\n</div>\n"),
12356 postCreate: function(){
12357 dojo.body().appendChild(this.domNode);
12359 this.bgIframe = new dijit.BackgroundIframe(this.domNode);
12361 // Setup fade-in and fade-out functions.
12362 this.fadeIn = dojo.fadeIn({ node: this.domNode, duration: this.duration, onEnd: dojo.hitch(this, "_onShow
") });
12363 this.fadeOut = dojo.fadeOut({ node: this.domNode, duration: this.duration, onEnd: dojo.hitch(this, "_onHide
") });
12367 show: function(/*String*/ innerHTML, /*DomNode*/ aroundNode, /*String[]?*/ position, /*Boolean*/ rtl){
12369 // Display tooltip w/specified contents to right of specified node
12370 // (To left if there's no space on the right, or if rtl == true)
12372 if(this.aroundNode && this.aroundNode === aroundNode){
12376 if(this.fadeOut.status() == "playing
"){
12377 // previous tooltip is being hidden; wait until the hide completes then show new one
12378 this._onDeck=arguments;
12381 this.containerNode.innerHTML=innerHTML;
12383 var pos = dijit.placeOnScreenAroundElement(this.domNode, aroundNode, dijit.getPopupAroundAlignment((position && position.length) ? position : dijit.Tooltip.defaultPosition, !rtl), dojo.hitch(this, "orient
"));
12386 dojo.style(this.domNode, "opacity
", 0);
12387 this.fadeIn.play();
12388 this.isShowingNow = true;
12389 this.aroundNode = aroundNode;
12392 orient: function(/* DomNode */ node, /* String */ aroundCorner, /* String */ tooltipCorner){
12394 // Private function to set CSS for tooltip node based on which position it's in.
12395 // This is called by the dijit popup code.
12399 node.className = "dijitTooltip
" +
12401 "BL
-TL
": "dijitTooltipBelow dijitTooltipABLeft
",
12402 "TL
-BL
": "dijitTooltipAbove dijitTooltipABLeft
",
12403 "BR
-TR
": "dijitTooltipBelow dijitTooltipABRight
",
12404 "TR
-BR
": "dijitTooltipAbove dijitTooltipABRight
",
12405 "BR
-BL
": "dijitTooltipRight
",
12406 "BL
-BR
": "dijitTooltipLeft
"
12407 }[aroundCorner + "-" + tooltipCorner];
12410 _onShow: function(){
12412 // Called at end of fade-in operation
12416 // the arrow won't show up on a node w/an opacity filter
12417 this.domNode.style.filter="";
12421 hide: function(aroundNode){
12423 // Hide the tooltip
12424 if(this._onDeck && this._onDeck[1] == aroundNode){
12425 // this hide request is for a show() that hasn't even started yet;
12426 // just cancel the pending show()
12428 }else if(this.aroundNode === aroundNode){
12429 // this hide request is for the currently displayed tooltip
12430 this.fadeIn.stop();
12431 this.isShowingNow = false;
12432 this.aroundNode = null;
12433 this.fadeOut.play();
12435 // just ignore the call, it's for a tooltip that has already been erased
12439 _onHide: function(){
12441 // Called at end of fade-out operation
12445 this.domNode.style.cssText=""; // to position offscreen again
12446 this.containerNode.innerHTML="";
12448 // a show request has been queued up; do it now
12449 this.show.apply(this, this._onDeck);
12457 dijit.showTooltip = function(/*String*/ innerHTML, /*DomNode*/ aroundNode, /*String[]?*/ position, /*Boolean*/ rtl){
12459 // Display tooltip w/specified contents in specified position.
12460 // See description of dijit.Tooltip.defaultPosition for details on position parameter.
12461 // If position is not specified then dijit.Tooltip.defaultPosition is used.
12462 if(!dijit._masterTT){ dijit._masterTT = new dijit._MasterTooltip(); }
12463 return dijit._masterTT.show(innerHTML, aroundNode, position, rtl);
12466 dijit.hideTooltip = function(aroundNode){
12468 // Hide the tooltip
12469 if(!dijit._masterTT){ dijit._masterTT = new dijit._MasterTooltip(); }
12470 return dijit._masterTT.hide(aroundNode);
12478 // Pops up a tooltip (a help message) when you hover over a node.
12481 // Text to display in the tooltip.
12482 // Specified as innerHTML when creating the widget from markup.
12485 // showDelay: Integer
12486 // Number of milliseconds to wait after hovering over/focusing on the object, before
12487 // the tooltip is displayed.
12490 // connectId: [const] String[]
12491 // Id's of domNodes to attach the tooltip to.
12492 // When user hovers over any of the specified dom nodes, the tooltip will appear.
12494 // Note: Currently connectId can only be specified on initialization, it cannot
12495 // be changed via attr('connectId', ...)
12497 // Note: in 2.0 this will be renamed to connectIds for less confusion.
12500 // position: String[]
12501 // See description of `dijit.Tooltip.defaultPosition` for details on position parameter.
12504 constructor: function(){
12505 // Map id's of nodes I'm connected to to a list of the this.connect() handles
12506 this._nodeConnectionsById = {};
12509 _setConnectIdAttr: function(newIds){
12510 for(var oldId in this._nodeConnectionsById){
12511 this.removeTarget(oldId);
12513 dojo.forEach(dojo.isArrayLike(newIds) ? newIds : [newIds], this.addTarget, this);
12516 _getConnectIdAttr: function(){
12518 for(var id in this._nodeConnectionsById){
12524 addTarget: function(/*DOMNODE || String*/ id){
12526 // Attach tooltip to specified node, if it's not already connected
12527 var node = dojo.byId(id);
12528 if(!node){ return; }
12529 if(node.id in this._nodeConnectionsById){ return; }//Already connected
12531 this._nodeConnectionsById[node.id] = [
12532 this.connect(node, "onmouseenter
", "_onTargetMouseEnter
"),
12533 this.connect(node, "onmouseleave
", "_onTargetMouseLeave
"),
12534 this.connect(node, "onfocus
", "_onTargetFocus
"),
12535 this.connect(node, "onblur
", "_onTargetBlur
")
12539 removeTarget: function(/*DOMNODE || String*/ node){
12541 // Detach tooltip from specified node
12543 // map from DOMNode back to plain id string
12544 var id = node.id || node;
12546 if(id in this._nodeConnectionsById){
12547 dojo.forEach(this._nodeConnectionsById[id], this.disconnect, this);
12548 delete this._nodeConnectionsById[id];
12552 postCreate: function(){
12553 dojo.addClass(this.domNode,"dijitTooltipData
");
12556 startup: function(){
12557 this.inherited(arguments);
12559 // If this tooltip was created in a template, or for some other reason the specified connectId[s]
12560 // didn't exist during the widget's initialization, then connect now.
12561 var ids = this.connectId;
12562 dojo.forEach(dojo.isArrayLike(ids) ? ids : [ids], this.addTarget, this);
12565 _onTargetMouseEnter: function(/*Event*/ e){
12567 // Handler for mouseenter event on the target node
12573 _onTargetMouseLeave: function(/*Event*/ e){
12575 // Handler for mouseleave event on the target node
12578 this._onUnHover(e);
12581 _onTargetFocus: function(/*Event*/ e){
12583 // Handler for focus event on the target node
12587 this._focus = true;
12591 _onTargetBlur: function(/*Event*/ e){
12593 // Handler for blur event on the target node
12597 this._focus = false;
12598 this._onUnHover(e);
12601 _onHover: function(/*Event*/ e){
12603 // Despite the name of this method, it actually handles both hover and focus
12604 // events on the target node, setting a timer to show the tooltip.
12607 if(!this._showTimer){
12608 var target = e.target;
12609 this._showTimer = setTimeout(dojo.hitch(this, function(){this.open(target)}), this.showDelay);
12613 _onUnHover: function(/*Event*/ e){
12615 // Despite the name of this method, it actually handles both mouseleave and blur
12616 // events on the target node, hiding the tooltip.
12620 // keep a tooltip open if the associated element still has focus (even though the
12621 // mouse moved away)
12622 if(this._focus){ return; }
12624 if(this._showTimer){
12625 clearTimeout(this._showTimer);
12626 delete this._showTimer;
12631 open: function(/*DomNode*/ target){
12633 // Display the tooltip; usually not called directly.
12637 if(this._showTimer){
12638 clearTimeout(this._showTimer);
12639 delete this._showTimer;
12641 dijit.showTooltip(this.label || this.domNode.innerHTML, target, this.position, !this.isLeftToRight());
12643 this._connectNode = target;
12644 this.onShow(target, this.position);
12649 // Hide the tooltip or cancel timer for show of tooltip
12653 if(this._connectNode){
12654 // if tooltip is currently shown
12655 dijit.hideTooltip(this._connectNode);
12656 delete this._connectNode;
12659 if(this._showTimer){
12660 // if tooltip is scheduled to be shown (after a brief delay)
12661 clearTimeout(this._showTimer);
12662 delete this._showTimer;
12666 onShow: function(target, position){
12668 // Called when the tooltip is shown
12673 onHide: function(){
12675 // Called when the tooltip is hidden
12680 uninitialize: function(){
12682 this.inherited(arguments);
12687 // dijit.Tooltip.defaultPosition: String[]
12688 // This variable controls the position of tooltips, if the position is not specified to
12689 // the Tooltip widget or *TextBox widget itself. It's an array of strings with the following values:
12691 // * before: places tooltip to the left of the target node/widget, or to the right in
12692 // the case of RTL scripts like Hebrew and Arabic
12693 // * after: places tooltip to the right of the target node/widget, or to the left in
12694 // the case of RTL scripts like Hebrew and Arabic
12695 // * above: tooltip goes above target node
12696 // * below: tooltip goes below target node
12698 // The list is positions is tried, in order, until a position is found where the tooltip fits
12699 // within the viewport.
12701 // Be careful setting this parameter. A value of "above
" may work fine until the user scrolls
12702 // the screen so that there's no room above the target node. Nodes with drop downs, like
12703 // DropDownButton or FilteringSelect, are especially problematic, in that you need to be sure
12704 // that the drop down and tooltip don't overlap, even when the viewport is scrolled so that there
12705 // is only room below (or above) the target node, but not both.
12706 dijit.Tooltip.defaultPosition = ["after
", "before
"];
12710 if(!dojo._hasResource["dijit
.form
.ValidationTextBox
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
12711 dojo._hasResource["dijit
.form
.ValidationTextBox
"] = true;
12712 dojo.provide("dijit
.form
.ValidationTextBox
");
12722 dijit.form.ValidationTextBox.__Constraints = function(){
12724 // locale used for validation, picks up value from this widget's lang attribute
12725 // _flags_: anything
12726 // various flags passed to regExpGen function
12733 "dijit
.form
.ValidationTextBox
",
12734 dijit.form.TextBox,
12737 // Base class for textbox widgets with the ability to validate content of various types and provide user feedback.
12741 templateString: dojo.cache("dijit
.form
", "templates
/ValidationTextBox.html", "<div class=\"dijit dijitReset dijitInlineTable dijitLeft\"\n\tid=\"widget_${id}\" waiRole=\"presentation\"\n\t><div class='dijitReset dijitValidationContainer'\n\t\t><input class=\"dijitReset dijitInputField dijitValidationIcon dijitValidationInner\" value=\"Χ \" type=\"text\" tabIndex=\"-1\" readOnly waiRole=\"presentation\"\n\t/></div\n\t><div class=\"dijitReset dijitInputField dijitInputContainer\"\n\t\t><input class=\"dijitReset dijitInputInner\" dojoAttachPoint='textbox,focusNode' autocomplete=\"off\"\n\t\t\t${!nameAttrSetting} type='${type}'\n\t/></div\n></div>\n"),
12742 baseClass: "dijitTextBox dijitValidationTextBox
",
12744 // required: Boolean
12745 // User is required to enter data into this field.
12748 // promptMessage: String
12749 // If defined, display this hint string immediately on focus to the textbox, if empty.
12750 // Think of this like a tooltip that tells the user what to do, not an error message
12751 // that tells the user what they've done wrong.
12753 // Message disappears when user starts typing.
12756 // invalidMessage: String
12757 // The message to display if value is invalid.
12758 // The translated string value is read from the message file by default.
12759 // Set to "" to use the promptMessage instead.
12760 invalidMessage: "$_unset_
$",
12762 // missingMessage: String
12763 // The message to display if value is empty and the field is required.
12764 // The translated string value is read from the message file by default.
12765 // Set to "" to use the invalidMessage instead.
12766 missingMessage: "$_unset_
$",
12768 // constraints: dijit.form.ValidationTextBox.__Constraints
12769 // user-defined object needed to pass parameters to the validator functions
12772 // regExp: [extension protected] String
12773 // regular expression string used to validate the input
12774 // Do not specify both regExp and regExpGen
12777 regExpGen: function(/*dijit.form.ValidationTextBox.__Constraints*/constraints){
12779 // Overridable function used to generate regExp when dependent on constraints.
12780 // Do not specify both regExp and regExpGen.
12782 // extension protected
12783 return this.regExp; // String
12786 // state: [readonly] String
12787 // Shows current state (ie, validation result) of input (Normal, Warning, or Error)
12790 // tooltipPosition: String[]
12791 // See description of `dijit.Tooltip.defaultPosition` for details on this parameter.
12792 tooltipPosition: [],
12794 _setValueAttr: function(){
12796 // Hook so attr('value', ...) works.
12797 this.inherited(arguments);
12798 this.validate(this._focused);
12801 validator: function(/*anything*/value, /*dijit.form.ValidationTextBox.__Constraints*/constraints){
12803 // Overridable function used to validate the text input against the regular expression.
12806 return (new RegExp("^(?:" + this.regExpGen(constraints) + ")"+(this.required?"":"?")+"$")).test(value) &&
12807 (!this.required || !this._isEmpty(value)) &&
12808 (this._isEmpty(value) || this.parse(value, constraints) !== undefined); // Boolean
12811 _isValidSubset: function(){
12813 // Returns true if the value is either already valid or could be made valid by appending characters.
12814 // This is used for validation while the user [may be] still typing.
12815 return this.textbox.value.search(this._partialre) == 0;
12818 isValid: function(/*Boolean*/ isFocused){
12820 // Tests if value is valid.
12821 // Can override with your own routine in a subclass.
12824 return this.validator(this.textbox.value, this.constraints);
12827 _isEmpty: function(value){
12829 // Checks for whitespace
12830 return /^\s*$/.test(value); // Boolean
12833 getErrorMessage: function(/*Boolean*/ isFocused){
12835 // Return an error message to show if appropriate
12838 return (this.required && this._isEmpty(this.textbox.value)) ? this.missingMessage : this.invalidMessage; // String
12841 getPromptMessage: function(/*Boolean*/ isFocused){
12843 // Return a hint message to show when widget is first focused
12846 return this.promptMessage; // String
12849 _maskValidSubsetError: true,
12850 validate: function(/*Boolean*/ isFocused){
12852 // Called by oninit, onblur, and onkeypress.
12854 // Show missing or invalid messages if appropriate, and highlight textbox field.
12858 var isValid = this.disabled || this.isValid(isFocused);
12859 if(isValid){ this._maskValidSubsetError = true; }
12860 var isEmpty = this._isEmpty(this.textbox.value);
12861 var isValidSubset = !isValid && !isEmpty && isFocused && this._isValidSubset();
12862 this.state = ((isValid || ((!this._hasBeenBlurred || isFocused) && isEmpty) || isValidSubset) && this._maskValidSubsetError) ? "" : "Error
";
12863 if(this.state == "Error
"){ this._maskValidSubsetError = isFocused; } // we want the error to show up afer a blur and refocus
12864 this._setStateClass();
12865 dijit.setWaiState(this.focusNode, "invalid
", isValid ? "false" : "true");
12867 if(this.state == "Error
"){
12868 message = this.getErrorMessage(true);
12870 message = this.getPromptMessage(true); // show the prompt whever there's no error
12872 this._maskValidSubsetError = true; // since we're focused, always mask warnings
12874 this.displayMessage(message);
12878 // _message: String
12879 // Currently displayed message
12882 displayMessage: function(/*String*/ message){
12884 // Overridable method to display validation errors/hints.
12885 // By default uses a tooltip.
12888 if(this._message == message){ return; }
12889 this._message = message;
12890 dijit.hideTooltip(this.domNode);
12892 dijit.showTooltip(message, this.domNode, this.tooltipPosition, !this.isLeftToRight());
12896 _refreshState: function(){
12897 // Overrides TextBox._refreshState()
12898 this.validate(this._focused);
12899 this.inherited(arguments);
12902 //////////// INITIALIZATION METHODS ///////////////////////////////////////
12904 constructor: function(){
12905 this.constraints = {};
12908 _setConstraintsAttr: function(/* Object */ constraints){
12909 if(!constraints.locale && this.lang){
12910 constraints.locale = this.lang;
12912 this.constraints = constraints;
12913 this._computePartialRE();
12916 _computePartialRE: function(){
12917 var p = this.regExpGen(this.constraints);
12919 var partialre = "";
12920 // parse the regexp and produce a new regexp that matches valid subsets
12921 // if the regexp is .* then there's no use in matching subsets since everything is valid
12922 if(p != ".*"){ this.regExp.replace(/\\.|\[\]|\[.*?[^\\]{1}\]|\{.*?\}|\(\?[=:!]|./g,
12924 switch(re.charAt(0)){
12936 partialre += "|$)";
12939 partialre += "(?:"+re+"|$)";
12944 try{ // this is needed for now since the above regexp parsing needs more test verification
12945 "".search(partialre);
12946 }catch(e){ // should never be here unless the original RE is bad or the parsing is bad
12947 partialre = this.regExp;
12948 console.warn('RegExp error in ' + this.declaredClass + ': ' + this.regExp);
12949 } // should never be here unless the original RE is bad or the parsing is bad
12950 this._partialre = "^(?:" + partialre + ")$";
12953 postMixInProperties: function(){
12954 this.inherited(arguments);
12955 this.messages = dojo.i18n.getLocalization("dijit
.form
", "validate
", this.lang);
12956 if(this.invalidMessage == "$_unset_
$"){ this.invalidMessage = this.messages.invalidMessage; }
12957 if(!this.invalidMessage){ this.invalidMessage = this.promptMessage; }
12958 if(this.missingMessage == "$_unset_
$"){ this.missingMessage = this.messages.missingMessage; }
12959 if(!this.missingMessage){ this.missingMessage = this.invalidMessage; }
12960 this._setConstraintsAttr(this.constraints); // this needs to happen now (and later) due to codependency on _set*Attr calls attachPoints
12963 _setDisabledAttr: function(/*Boolean*/ value){
12964 this.inherited(arguments); // call FormValueWidget._setDisabledAttr()
12965 this._refreshState();
12968 _setRequiredAttr: function(/*Boolean*/ value){
12969 this.required = value;
12970 dijit.setWaiState(this.focusNode, "required
", value);
12971 this._refreshState();
12975 // Overrides dijit.form.TextBox.reset() by also
12976 // hiding errors about partial matches
12977 this._maskValidSubsetError = true;
12978 this.inherited(arguments);
12981 _onBlur: function(){
12982 this.displayMessage('');
12983 this.inherited(arguments);
12989 "dijit
.form
.MappedTextBox
",
12990 dijit.form.ValidationTextBox,
12993 // A dijit.form.ValidationTextBox subclass which provides a base class for widgets that have
12994 // a visible formatted display value, and a serializable
12995 // value in a hidden input field which is actually sent to the server.
12997 // The visible display may
12998 // be locale-dependent and interactive. The value sent to the server is stored in a hidden
12999 // input field which uses the `name` attribute declared by the original widget. That value sent
13000 // to the server is defined by the dijit.form.MappedTextBox.serialize method and is typically
13005 postMixInProperties: function(){
13006 this.inherited(arguments);
13008 // we want the name attribute to go to the hidden <input>, not the displayed <input>,
13009 // so override _FormWidget.postMixInProperties() setting of nameAttrSetting
13010 this.nameAttrSetting = "";
13013 serialize: function(/*anything*/val, /*Object?*/options){
13015 // Overridable function used to convert the attr('value') result to a canonical
13016 // (non-localized) string. For example, will print dates in ISO format, and
13017 // numbers the same way as they are represented in javascript.
13019 // protected extension
13020 return val.toString ? val.toString() : ""; // String
13023 toString: function(){
13025 // Returns widget as a printable string using the widget's value
13028 var val = this.filter(this.get('value')); // call filter in case value is nonstring and filter has been customized
13029 return val != null ? (typeof val == "string
" ? val : this.serialize(val, this.constraints)) : ""; // String
13032 validate: function(){
13033 // Overrides `dijit.form.TextBox.validate`
13034 this.valueNode.value = this.toString();
13035 return this.inherited(arguments);
13038 buildRendering: function(){
13039 // Overrides `dijit._Templated.buildRendering`
13041 this.inherited(arguments);
13043 // Create a hidden <input> node with the serialized value used for submit
13044 // (as opposed to the displayed value).
13045 // Passing in name as markup rather than calling dojo.create() with an attrs argument
13046 // to make dojo.query(input[name=...]) work on IE. (see #8660)
13047 this.valueNode = dojo.place("<input type
='hidden'" + (this.name ? " name
='" + this.name + "'" : "") + ">", this.textbox, "after
");
13051 // Overrides `dijit.form.ValidationTextBox.reset` to
13052 // reset the hidden textbox value to ''
13053 this.valueNode.value = '';
13054 this.inherited(arguments);
13060 dijit.form.RangeBoundTextBox.__Constraints = function(){
13062 // Minimum signed value. Default is -Infinity
13064 // Maximum signed value. Default is +Infinity
13071 "dijit
.form
.RangeBoundTextBox
",
13072 dijit.form.MappedTextBox,
13075 // Base class for textbox form widgets which defines a range of valid values.
13077 // rangeMessage: String
13078 // The message to display if value is out-of-range
13082 // constraints: dijit.form.RangeBoundTextBox.__Constraints
13086 rangeCheck: function(/*Number*/ primitive, /*dijit.form.RangeBoundTextBox.__Constraints*/ constraints){
13088 // Overridable function used to validate the range of the numeric input value.
13091 return ("min
" in constraints? (this.compare(primitive,constraints.min) >= 0) : true) &&
13092 ("max
" in constraints? (this.compare(primitive,constraints.max) <= 0) : true); // Boolean
13095 isInRange: function(/*Boolean*/ isFocused){
13097 // Tests if the value is in the min/max range specified in constraints
13100 return this.rangeCheck(this.get('value'), this.constraints);
13103 _isDefinitelyOutOfRange: function(){
13105 // Returns true if the value is out of range and will remain
13106 // out of range even if the user types more characters
13107 var val = this.get('value');
13108 var isTooLittle = false;
13109 var isTooMuch = false;
13110 if("min
" in this.constraints){
13111 var min = this.constraints.min;
13112 min = this.compare(val, ((typeof min == "number
") && min >= 0 && val !=0) ? 0 : min);
13113 isTooLittle = (typeof min == "number
") && min < 0;
13115 if("max
" in this.constraints){
13116 var max = this.constraints.max;
13117 max = this.compare(val, ((typeof max != "number
") || max > 0) ? max : 0);
13118 isTooMuch = (typeof max == "number
") && max > 0;
13120 return isTooLittle || isTooMuch;
13123 _isValidSubset: function(){
13125 // Overrides `dijit.form.ValidationTextBox._isValidSubset`.
13126 // Returns true if the input is syntactically valid, and either within
13127 // range or could be made in range by more typing.
13128 return this.inherited(arguments) && !this._isDefinitelyOutOfRange();
13131 isValid: function(/*Boolean*/ isFocused){
13132 // Overrides dijit.form.ValidationTextBox.isValid to check that the value is also in range.
13133 return this.inherited(arguments) &&
13134 ((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
13137 getErrorMessage: function(/*Boolean*/ isFocused){
13138 // Overrides dijit.form.ValidationTextBox.getErrorMessage to print "out
of range
" message if appropriate
13139 var v = this.get('value');
13140 if(v !== null && v !== '' && v !== undefined && (typeof v != "number
" || !isNaN(v)) && !this.isInRange(isFocused)){ // don't check isInRange w/o a real value
13141 return this.rangeMessage; // String
13143 return this.inherited(arguments);
13146 postMixInProperties: function(){
13147 this.inherited(arguments);
13148 if(!this.rangeMessage){
13149 this.messages = dojo.i18n.getLocalization("dijit
.form
", "validate
", this.lang);
13150 this.rangeMessage = this.messages.rangeMessage;
13154 _setConstraintsAttr: function(/* Object */ constraints){
13155 this.inherited(arguments);
13156 if(this.focusNode){ // not set when called from postMixInProperties
13157 if(this.constraints.min !== undefined){
13158 dijit.setWaiState(this.focusNode, "valuemin
", this.constraints.min);
13160 dijit.removeWaiState(this.focusNode, "valuemin
");
13162 if(this.constraints.max !== undefined){
13163 dijit.setWaiState(this.focusNode, "valuemax
", this.constraints.max);
13165 dijit.removeWaiState(this.focusNode, "valuemax
");
13170 _setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange){
13172 // Hook so attr('value', ...) works.
13174 dijit.setWaiState(this.focusNode, "valuenow
", value);
13175 this.inherited(arguments);
13182 if(!dojo._hasResource["dijit
.form
.ComboBox
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
13183 dojo._hasResource["dijit
.form
.ComboBox
"] = true;
13184 dojo.provide("dijit
.form
.ComboBox
");
13198 "dijit
.form
.ComboBoxMixin
",
13202 // Implements the base functionality for `dijit.form.ComboBox`/`dijit.form.FilteringSelect`
13204 // All widgets that mix in dijit.form.ComboBoxMixin must extend `dijit.form._FormValueWidget`.
13209 // This is the item returned by the dojo.data.store implementation that
13210 // provides the data for this ComboBox, it's the currently selected item.
13213 // pageSize: Integer
13214 // Argument to data provider.
13215 // Specifies number of search results per page (before hitting "next
" button)
13216 pageSize: Infinity,
13219 // Reference to data provider object used by this ComboBox
13222 // fetchProperties: Object
13223 // Mixin to the dojo.data store's fetch.
13224 // For example, to set the sort order of the ComboBox menu, pass:
13225 // | { sort: {attribute:"name
",descending: true} }
13226 // To override the default queryOptions so that deep=false, do:
13227 // | { queryOptions: {ignoreCase: true, deep: false} }
13228 fetchProperties:{},
13231 // A query that can be passed to 'store' to initially filter the items,
13232 // before doing further filtering based on `searchAttr` and the key.
13233 // Any reference to the `searchAttr` is ignored.
13236 // autoComplete: Boolean
13237 // If user types in a partial string, and then tab out of the `<input>` box,
13238 // automatically copy the first entry displayed in the drop down list to
13239 // the `<input>` field
13240 autoComplete: true,
13242 // highlightMatch: String
13243 // One of: "first
", "all
" or "none
".
13245 // If the ComboBox/FilteringSelect opens with the search results and the searched
13246 // string can be found, it will be highlighted. If set to "all
"
13247 // then will probably want to change `queryExpr` parameter to '*${0}*'
13249 // Highlighting is only performed when `labelType` is "text
", so as to not
13250 // interfere with any HTML markup an HTML label might contain.
13251 highlightMatch: "first
",
13253 // searchDelay: Integer
13254 // Delay in milliseconds between when user types something and we start
13255 // searching based on that value
13258 // searchAttr: String
13259 // Search for items in the data store where this attribute (in the item)
13260 // matches what the user typed
13261 searchAttr: "name
",
13263 // labelAttr: String?
13264 // The entries in the drop down list come from this attribute in the
13265 // dojo.data items.
13266 // If not specified, the searchAttr attribute is used instead.
13269 // labelType: String
13270 // Specifies how to interpret the labelAttr in the data store items.
13271 // Can be "html
" or "text
".
13274 // queryExpr: String
13275 // This specifies what query ComboBox/FilteringSelect sends to the data store,
13276 // based on what the user has typed. Changing this expression will modify
13277 // whether the drop down shows only exact matches, a "starting
with" match,
13278 // etc. Use it in conjunction with highlightMatch.
13279 // dojo.data query expression pattern.
13280 // `${0}` will be substituted for the user text.
13281 // `*` is used for wildcards.
13282 // `${0}*` means "starts
with", `*${0}*` means "contains
", `${0}` means "is
"
13283 queryExpr: "${0}
*",
13285 // ignoreCase: Boolean
13286 // Set true if the ComboBox/FilteringSelect should ignore case when matching possible items
13289 // hasDownArrow: [const] Boolean
13290 // Set this textbox to have a down arrow button, to display the drop down list.
13291 // Defaults to true.
13292 hasDownArrow: true,
13294 templateString: dojo.cache("dijit
.form
", "templates
/ComboBox.html", "<div class=\"dijit dijitReset dijitInlineTable dijitLeft\"\n\tid=\"widget_${id}\"\n\tdojoAttachPoint=\"comboNode\" waiRole=\"combobox\"\n\t><div class='dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer'\n\t\tdojoAttachPoint=\"downArrowNode\" waiRole=\"presentation\"\n\t\tdojoAttachEvent=\"onmousedown:_onArrowMouseDown\"\n\t\t><input class=\"dijitReset dijitInputField dijitArrowButtonInner\" value=\"▼ \" type=\"text\" tabIndex=\"-1\" readOnly waiRole=\"presentation\"\n\t\t\t${_buttonInputDisabled}\n\t/></div\n\t><div class='dijitReset dijitValidationContainer'\n\t\t><input class=\"dijitReset dijitInputField dijitValidationIcon dijitValidationInner\" value=\"Χ \" type=\"text\" tabIndex=\"-1\" readOnly waiRole=\"presentation\"\n\t/></div\n\t><div class=\"dijitReset dijitInputField dijitInputContainer\"\n\t\t><input class='dijitReset dijitInputInner' ${!nameAttrSetting} type=\"text\" autocomplete=\"off\"\n\t\t\tdojoAttachEvent=\"onkeypress:_onKeyPress,compositionend\"\n\t\t\tdojoAttachPoint=\"textbox,focusNode\" waiRole=\"textbox\" waiState=\"haspopup-true,autocomplete-list\"\n\t/></div\n></div>\n"),
13296 baseClass: "dijitTextBox dijitComboBox
",
13298 // Set classes like dijitDownArrowButtonHover depending on
13299 // mouse action over button node
13301 "downArrowNode
": "dijitDownArrowButton
"
13304 _getCaretPos: function(/*DomNode*/ element){
13305 // khtml 3.5.2 has selection* methods as does webkit nightlies from 2005-06-22
13307 if(typeof(element.selectionStart) == "number
"){
13308 // FIXME: this is totally borked on Moz < 1.3. Any recourse?
13309 pos = element.selectionStart;
13310 }else if(dojo.isIE){
13311 // in the case of a mouse click in a popup being handled,
13312 // then the dojo.doc.selection is not the textarea, but the popup
13313 // var r = dojo.doc.selection.createRange();
13314 // hack to get IE 6 to play nice. What a POS browser.
13315 var tr = dojo.doc.selection.createRange().duplicate();
13316 var ntr = element.createTextRange();
13317 tr.move("character
",0);
13318 ntr.move("character
",0);
13320 // If control doesnt have focus, you get an exception.
13321 // Seems to happen on reverse-tab, but can also happen on tab (seems to be a race condition - only happens sometimes).
13322 // There appears to be no workaround for this - googled for quite a while.
13323 ntr.setEndPoint("EndToEnd
", tr);
13324 pos = String(ntr.text).replace(/\r/g,"").length;
13326 // If focus has shifted, 0 is fine for caret pos.
13332 _setCaretPos: function(/*DomNode*/ element, /*Number*/ location){
13333 location = parseInt(location);
13334 dijit.selectInputText(element, location, location);
13337 _setDisabledAttr: function(/*Boolean*/ value){
13338 // Additional code to set disabled state of ComboBox node.
13339 // Overrides _FormValueWidget._setDisabledAttr() or ValidationTextBox._setDisabledAttr().
13340 this.inherited(arguments);
13341 dijit.setWaiState(this.comboNode, "disabled
", value);
13344 _abortQuery: function(){
13345 // stop in-progress query
13346 if(this.searchTimer){
13347 clearTimeout(this.searchTimer);
13348 this.searchTimer = null;
13350 if(this._fetchHandle){
13351 if(this._fetchHandle.abort){ this._fetchHandle.abort(); }
13352 this._fetchHandle = null;
13356 _onInput: function(/*Event*/ evt){
13358 // Handles paste events
13359 if(!this.searchTimer && (evt.type == 'paste'/*IE|WebKit*/ || evt.type == 'input'/*Firefox*/) && this._lastInput != this.textbox.value){
13360 this.searchTimer = setTimeout(dojo.hitch(this, function(){
13361 this._onKeyPress({charOrCode: 229}); // fake IME key to cause a search
13362 }), 100); // long delay that will probably be preempted by keyboard input
13364 this.inherited(arguments);
13367 _onKeyPress: function(/*Event*/ evt){
13369 // Handles keyboard events
13370 var key = evt.charOrCode;
13371 // except for cutting/pasting case - ctrl + x/v
13372 if(evt.altKey || ((evt.ctrlKey || evt.metaKey) && (key != 'x' && key != 'v')) || key == dojo.keys.SHIFT){
13373 return; // throw out weird key combinations and spurious events
13375 var doSearch = false;
13376 var searchFunction = "_startSearchFromInput
";
13377 var pw = this._popupWidget;
13378 var dk = dojo.keys;
13379 var highlighted = null;
13380 this._prev_key_backspace = false;
13381 this._abortQuery();
13382 if(this._isShowingNow){
13384 highlighted = pw.getHighlightedOption();
13388 case dk.DOWN_ARROW:
13391 if(!this._isShowingNow){
13393 searchFunction = "_startSearchAll
";
13395 this._announceOption(highlighted);
13397 dojo.stopEvent(evt);
13401 // prevent submitting form if user presses enter. Also
13402 // prevent accepting the value if either Next or Previous
13405 // only stop event on prev/next
13406 if(highlighted == pw.nextButton){
13407 this._nextSearch(1);
13408 dojo.stopEvent(evt);
13410 }else if(highlighted == pw.previousButton){
13411 this._nextSearch(-1);
13412 dojo.stopEvent(evt);
13416 // Update 'value' (ex: KY) according to currently displayed text
13417 this._setBlurValue(); // set value if needed
13418 this._setCaretPos(this.focusNode, this.focusNode.value.length); // move cursor to end and cancel highlighting
13421 // prevent submit, but allow event to bubble
13422 evt.preventDefault();
13426 var newvalue = this.get('displayedValue');
13427 // if the user had More Choices selected fall into the
13430 newvalue == pw._messages["previousMessage
"] ||
13431 newvalue == pw._messages["nextMessage
"])
13436 this._selectOption();
13438 if(this._isShowingNow){
13439 this._lastQuery = null; // in case results come back later
13440 this._hideResultList();
13446 dojo.stopEvent(evt);
13447 this._selectOption();
13448 this._hideResultList();
13455 if(this._isShowingNow){
13456 dojo.stopEvent(evt);
13457 this._hideResultList();
13463 this._prev_key_backspace = true;
13468 // Non char keys (F1-F12 etc..) shouldn't open list.
13469 // Ascii characters and IME input (Chinese, Japanese etc.) should.
13470 // On IE and safari, IME input produces keycode == 229, and we simulate
13471 // it on firefox by attaching to compositionend event (see compositionend method)
13472 doSearch = typeof key == 'string' || key == 229;
13475 // need to wait a tad before start search so that the event
13476 // bubbles through DOM and we have value visible
13477 this.item = undefined; // undefined means item needs to be set
13478 this.searchTimer = setTimeout(dojo.hitch(this, searchFunction),1);
13482 _autoCompleteText: function(/*String*/ text){
13484 // Fill in the textbox with the first item from the drop down
13485 // list, and highlight the characters that were
13486 // auto-completed. For example, if user typed "CA
" and the
13487 // drop down list appeared, the textbox would be changed to
13488 // "California
" and "ifornia
" would be highlighted.
13490 var fn = this.focusNode;
13492 // IE7: clear selection so next highlight works all the time
13493 dijit.selectInputText(fn, fn.value.length);
13494 // does text autoComplete the value in the textbox?
13495 var caseFilter = this.ignoreCase? 'toLowerCase' : 'substr';
13496 if(text[caseFilter](0).indexOf(this.focusNode.value[caseFilter](0)) == 0){
13497 var cpos = this._getCaretPos(fn);
13498 // only try to extend if we added the last character at the end of the input
13499 if((cpos+1) > fn.value.length){
13500 // only add to input node as we would overwrite Capitalisation of chars
13501 // actually, that is ok
13502 fn.value = text;//.substr(cpos);
13503 // visually highlight the autocompleted characters
13504 dijit.selectInputText(fn, cpos);
13507 // text does not autoComplete; replace the whole value and highlight
13509 dijit.selectInputText(fn);
13513 _openResultList: function(/*Object*/ results, /*Object*/ dataObject){
13514 this._fetchHandle = null;
13515 if( this.disabled ||
13517 (dataObject.query[this.searchAttr] != this._lastQuery)
13521 this._popupWidget.clearResultList();
13522 if(!results.length && !this._maxOptions){ // this condition needs to match !this._isvalid set in FilteringSelect::_openResultList
13523 this._hideResultList();
13528 // Fill in the textbox with the first item from the drop down list,
13529 // and highlight the characters that were auto-completed. For
13530 // example, if user typed "CA
" and the drop down list appeared, the
13531 // textbox would be changed to "California
" and "ifornia
" would be
13534 dataObject._maxOptions = this._maxOptions;
13535 var nodes = this._popupWidget.createOptions(
13538 dojo.hitch(this, "_getMenuLabelFromItem
")
13541 // show our list (only if we have content, else nothing)
13542 this._showResultList();
13545 // tell the screen reader that the paging callback finished by
13546 // shouting the next choice
13547 if(dataObject.direction){
13548 if(1 == dataObject.direction){
13549 this._popupWidget.highlightFirstOption();
13550 }else if(-1 == dataObject.direction){
13551 this._popupWidget.highlightLastOption();
13553 this._announceOption(this._popupWidget.getHighlightedOption());
13554 }else if(this.autoComplete && !this._prev_key_backspace /*&& !dataObject.direction*/
13555 // when the user clicks the arrow button to show the full list,
13556 // startSearch looks for "*".
13557 // it does not make sense to autocomplete
13558 // if they are just previewing the options available.
13559 && !/^[*]+$/.test(dataObject.query[this.searchAttr])){
13560 this._announceOption(nodes[1]); // 1st real item
13564 _showResultList: function(){
13565 this._hideResultList();
13566 // hide the tooltip
13567 this.displayMessage("");
13569 // Position the list and if it's too big to fit on the screen then
13570 // size it to the maximum possible height
13571 // Our dear friend IE doesnt take max-height so we need to
13572 // calculate that on our own every time
13574 // TODO: want to redo this, see
13575 // http://trac.dojotoolkit.org/ticket/3272
13577 // http://trac.dojotoolkit.org/ticket/4108
13580 // natural size of the list has changed, so erase old
13581 // width/height settings, which were hardcoded in a previous
13582 // call to this function (via dojo.marginBox() call)
13583 dojo.style(this._popupWidget.domNode, {width: "", height: ""});
13585 var best = this.open();
13587 // only set auto scroll bars if necessary prevents issues with
13588 // scroll bars appearing when they shouldn't when node is made
13589 // wider (fractional pixels cause this)
13590 var popupbox = dojo.marginBox(this._popupWidget.domNode);
13591 this._popupWidget.domNode.style.overflow =
13592 ((best.h == popupbox.h) && (best.w == popupbox.w)) ? "hidden
" : "auto
";
13594 // borrow TextArea scrollbar test so content isn't covered by
13595 // scrollbar and horizontal scrollbar doesn't appear
13596 var newwidth = best.w;
13597 if(best.h < this._popupWidget.domNode.scrollHeight){
13600 dojo.marginBox(this._popupWidget.domNode, {
13602 w: Math.max(newwidth, this.domNode.offsetWidth)
13605 // If we increased the width of drop down to match the width of ComboBox.domNode,
13606 // then need to reposition the drop down (wrapper) so (all of) the drop down still
13607 // appears underneath the ComboBox.domNode
13608 if(newwidth < this.domNode.offsetWidth){
13609 this._popupWidget.domNode.parentNode.style.left = dojo.position(this.domNode, true).x + "px
";
13612 dijit.setWaiState(this.comboNode, "expanded
", "true");
13615 _hideResultList: function(){
13616 this._abortQuery();
13617 if(this._isShowingNow){
13618 dijit.popup.close(this._popupWidget);
13619 this._isShowingNow=false;
13620 dijit.setWaiState(this.comboNode, "expanded
", "false");
13621 dijit.removeWaiState(this.focusNode,"activedescendant
");
13625 _setBlurValue: function(){
13626 // if the user clicks away from the textbox OR tabs away, set the
13627 // value to the textbox value
13629 // if value is now more choices or previous choices, revert
13631 var newvalue = this.get('displayedValue');
13632 var pw = this._popupWidget;
13634 newvalue == pw._messages["previousMessage
"] ||
13635 newvalue == pw._messages["nextMessage
"]
13638 this._setValueAttr(this._lastValueReported, true);
13639 }else if(typeof this.item == "undefined"){
13640 // Update 'value' (ex: KY) according to currently displayed text
13642 this.set('displayedValue', newvalue);
13644 if(this.value != this._lastValueReported){
13645 dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true);
13647 this._refreshState();
13651 _onBlur: function(){
13653 // Called magically when focus has shifted away from this widget and it's drop down
13654 this._hideResultList();
13655 this.inherited(arguments);
13658 _setItemAttr: function(/*item*/ item, /*Boolean?*/ priorityChange, /*String?*/ displayedValue){
13660 // Set the displayed valued in the input box, and the hidden value
13661 // that gets submitted, based on a dojo.data store item.
13663 // Users shouldn't call this function; they should be calling
13664 // attr('item', value)
13667 if(!displayedValue){ displayedValue = this.labelFunc(item, this.store); }
13668 this.value = this._getValueField() != this.searchAttr? this.store.getIdentity(item) : displayedValue;
13670 dijit.form.ComboBox.superclass._setValueAttr.call(this, this.value, priorityChange, displayedValue);
13673 _announceOption: function(/*Node*/ node){
13675 // a11y code that puts the highlighted option in the textbox.
13676 // This way screen readers will know what is happening in the
13682 // pull the text value from the item attached to the DOM node
13684 if(node == this._popupWidget.nextButton ||
13685 node == this._popupWidget.previousButton){
13686 newValue = node.innerHTML;
13687 this.item = undefined;
13690 newValue = this.labelFunc(node.item, this.store);
13691 this.set('item', node.item, false, newValue);
13693 // get the text that the user manually entered (cut off autocompleted text)
13694 this.focusNode.value = this.focusNode.value.substring(0, this._lastInput.length);
13695 // set up ARIA activedescendant
13696 dijit.setWaiState(this.focusNode, "activedescendant
", dojo.attr(node, "id
"));
13697 // autocomplete the rest of the option to announce change
13698 this._autoCompleteText(newValue);
13701 _selectOption: function(/*Event*/ evt){
13703 // Menu callback function, called when an item in the menu is selected.
13705 this._announceOption(evt.target);
13707 this._hideResultList();
13708 this._setCaretPos(this.focusNode, this.focusNode.value.length);
13709 dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true); // set this.value and fire onChange
13712 _onArrowMouseDown: function(evt){
13714 // Callback when arrow is clicked
13715 if(this.disabled || this.readOnly){
13718 dojo.stopEvent(evt);
13720 if(this._isShowingNow){
13721 this._hideResultList();
13723 // forces full population of results, if they click
13724 // on the arrow it means they want to see more options
13725 this._startSearchAll();
13729 _startSearchAll: function(){
13730 this._startSearch('');
13733 _startSearchFromInput: function(){
13734 this._startSearch(this.focusNode.value.replace(/([\\\*\?])/g, "\\$1"));
13737 _getQueryString: function(/*String*/ text){
13738 return dojo.string.substitute(this.queryExpr, [text]);
13741 _startSearch: function(/*String*/ key){
13742 if(!this._popupWidget){
13743 var popupId = this.id + "_popup
";
13744 this._popupWidget = new dijit.form._ComboBoxMenu({
13745 onChange: dojo.hitch(this, this._selectOption),
13749 dijit.removeWaiState(this.focusNode,"activedescendant
");
13750 dijit.setWaiState(this.textbox,"owns
",popupId); // associate popup with textbox
13752 // create a new query to prevent accidentally querying for a hidden
13753 // value from FilteringSelect's keyField
13754 var query = dojo.clone(this.query); // #5970
13755 this._lastInput = key; // Store exactly what was entered by the user.
13756 this._lastQuery = query[this.searchAttr] = this._getQueryString(key);
13757 // #5970: set _lastQuery, *then* start the timeout
13758 // otherwise, if the user types and the last query returns before the timeout,
13759 // _lastQuery won't be set and their input gets rewritten
13760 this.searchTimer=setTimeout(dojo.hitch(this, function(query, _this){
13761 this.searchTimer = null;
13764 ignoreCase: this.ignoreCase,
13768 onBegin: dojo.hitch(this, "_setMaxOptions
"),
13769 onComplete: dojo.hitch(this, "_openResultList
"),
13770 onError: function(errText){
13771 _this._fetchHandle = null;
13772 console.error('dijit.form.ComboBox: ' + errText);
13773 dojo.hitch(_this, "_hideResultList
")();
13776 count: this.pageSize
13778 dojo.mixin(fetch, _this.fetchProperties);
13779 this._fetchHandle = _this.store.fetch(fetch);
13781 var nextSearch = function(dataObject, direction){
13782 dataObject.start += dataObject.count*direction;
13784 // tell callback the direction of the paging so the screen
13785 // reader knows which menu option to shout
13786 dataObject.direction = direction;
13787 this._fetchHandle = this.store.fetch(dataObject);
13789 this._nextSearch = this._popupWidget.onPage = dojo.hitch(this, nextSearch, this._fetchHandle);
13790 }, query, this), this.searchDelay);
13793 _setMaxOptions: function(size, request){
13794 this._maxOptions = size;
13797 _getValueField: function(){
13799 // Helper for postMixInProperties() to set this.value based on data inlined into the markup.
13800 // Returns the attribute name in the item (in dijit.form._ComboBoxDataStore) to use as the value.
13801 return this.searchAttr;
13804 /////////////// Event handlers /////////////////////
13806 // FIXME: For 2.0, rename to "_compositionEnd
"
13807 compositionend: function(/*Event*/ evt){
13809 // When inputting characters using an input method, such as
13810 // Asian languages, it will generate this event instead of
13811 // onKeyDown event.
13812 // Note: this event is only triggered in FF (not in IE/safari)
13816 // 229 is the code produced by IE and safari while pressing keys during
13818 this._onKeyPress({charOrCode: 229});
13821 //////////// INITIALIZATION METHODS ///////////////////////////////////////
13823 constructor: function(){
13825 this.fetchProperties={};
13828 postMixInProperties: function(){
13830 var srcNodeRef = this.srcNodeRef;
13832 // if user didn't specify store, then assume there are option tags
13833 this.store = new dijit.form._ComboBoxDataStore(srcNodeRef);
13835 // if there is no value set and there is an option list, set
13836 // the value to the first value to be consistent with native
13839 // Firefox and Safari set value
13840 // IE6 and Opera set selectedIndex, which is automatically set
13841 // by the selected attribute of an option tag
13842 // IE6 does not set value, Opera sets value = selectedIndex
13843 if(!("value
" in this.params)){
13844 var item = this.store.fetchSelectedItem();
13846 var valueField = this._getValueField();
13847 this.value = valueField != this.searchAttr? this.store.getValue(item, valueField) : this.labelFunc(item, this.store);
13851 this.inherited(arguments);
13854 postCreate: function(){
13856 // Subclasses must call this method from their postCreate() methods
13860 if(!this.hasDownArrow){
13861 this.downArrowNode.style.display = "none
";
13864 // find any associated label element and add to ComboBox node.
13865 var label=dojo.query('label[for="'+this.id+'"]');
13867 label[0].id = (this.id+"_label
");
13868 var cn=this.comboNode;
13869 dijit.setWaiState(cn, "labelledby
", label[0].id);
13872 this.inherited(arguments);
13875 uninitialize: function(){
13876 if(this._popupWidget && !this._popupWidget._destroyed){
13877 this._hideResultList();
13878 this._popupWidget.destroy();
13880 this.inherited(arguments);
13883 _getMenuLabelFromItem: function(/*Item*/ item){
13884 var label = this.labelAttr? this.store.getValue(item, this.labelAttr) : this.labelFunc(item, this.store);
13885 var labelType = this.labelType;
13886 // If labelType is not "text
" we don't want to screw any markup ot whatever.
13887 if(this.highlightMatch != "none
" && this.labelType == "text
" && this._lastInput){
13888 label = this.doHighlight(label, this._escapeHtml(this._lastInput));
13889 labelType = "html
";
13891 return {html: labelType == "html
", label: label};
13894 doHighlight: function(/*String*/label, /*String*/find){
13896 // Highlights the string entered by the user in the menu. By default this
13897 // highlights the first occurence found. Override this method
13898 // to implement your custom highlighing.
13902 // Add greedy when this.highlightMatch == "all
"
13903 var modifiers = "i
"+(this.highlightMatch == "all
"?"g
":"");
13904 var escapedLabel = this._escapeHtml(label);
13905 find = dojo.regexp.escapeString(find); // escape regexp special chars
13906 var ret = escapedLabel.replace(new RegExp("(^|\\s
)("+ find +")", modifiers),
13907 '$1<span class="dijitComboBoxHighlightMatch
">$2</span>');
13908 return ret;// returns String, (almost) valid HTML (entities encoded)
13911 _escapeHtml: function(/*string*/str){
13912 // TODO Should become dojo.html.entities(), when exists use instead
13914 // Adds escape sequences for special characters in XML: &<>"'
13915 str = String(str).replace(/&/gm, "&").replace(/</gm, "<")
13916 .replace(/>/gm, ">").replace(/"/gm, """);
13917 return str; // string
13922 // Opens the drop down menu. TODO: rename to _open.
13925 this._isShowingNow=true;
13926 return dijit.popup.open({
13927 popup: this._popupWidget,
13928 around: this.domNode,
13934 // Overrides the _FormWidget.reset().
13935 // Additionally reset the .item (to clean up).
13937 this.inherited(arguments);
13940 labelFunc: function(/*item*/ item, /*dojo.data.store*/ store){
13942 // Computes the label to display based on the dojo.data store item.
13944 // The label that the ComboBox should display
13948 // Use toString() because XMLStore returns an XMLItem whereas this
13949 // method is expected to return a String (#9354)
13950 return store.getValue(item, this.searchAttr).toString(); // String
13956 "dijit.form._ComboBoxMenu",
13957 [dijit._Widget, dijit._Templated, dijit._CssStateMixin],
13960 // Focus-less menu for internal use in `dijit.form.ComboBox`
13964 templateString: "<ul class='dijitReset dijitMenu
' dojoAttachEvent='onmousedown
:_onMouseDown
,onmouseup
:_onMouseUp
,onmouseover
:_onMouseOver
,onmouseout
:_onMouseOut
' tabIndex='-1' style='overflow
: \"auto
\"; overflow
-x
: \"hidden
\";'>"
13965 +"<li class='dijitMenuItem dijitMenuPreviousButton
' dojoAttachPoint='previousButton
' waiRole='option
'></li>"
13966 +"<li class='dijitMenuItem dijitMenuNextButton
' dojoAttachPoint='nextButton
' waiRole='option
'></li>"
13969 // _messages: Object
13970 // Holds "next" and "previous" text for paging buttons on drop down
13973 baseClass: "dijitComboBoxMenu",
13975 postMixInProperties: function(){
13976 this._messages = dojo.i18n.getLocalization("dijit.form", "ComboBox", this.lang);
13977 this.inherited(arguments);
13980 _setValueAttr: function(/*Object*/ value){
13981 this.value = value;
13982 this.onChange(value);
13986 onChange: function(/*Object*/ value){
13988 // Notifies ComboBox/FilteringSelect that user clicked an option in the drop down menu.
13989 // Probably should be called onSelect.
13993 onPage: function(/*Number*/ direction){
13995 // Notifies ComboBox/FilteringSelect that user clicked to advance to next/previous page.
14000 postCreate: function(){
14001 // fill in template with i18n messages
14002 this.previousButton.innerHTML = this._messages["previousMessage"];
14003 this.nextButton.innerHTML = this._messages["nextMessage"];
14004 this.inherited(arguments);
14007 onClose: function(){
14009 // Callback from dijit.popup code to this widget, notifying it that it closed
14012 this._blurOptionNode();
14015 _createOption: function(/*Object*/ item, labelFunc){
14017 // Creates an option to appear on the popup menu subclassed by
14018 // `dijit.form.FilteringSelect`.
14020 var labelObject = labelFunc(item);
14021 var menuitem = dojo.doc.createElement("li");
14022 dijit.setWaiRole(menuitem, "option");
14023 if(labelObject.html){
14024 menuitem.innerHTML = labelObject.label;
14026 menuitem.appendChild(
14027 dojo.doc.createTextNode(labelObject.label)
14030 // #3250: in blank options, assign a normal height
14031 if(menuitem.innerHTML == ""){
14032 menuitem.innerHTML = " ";
14034 menuitem.item=item;
14038 createOptions: function(results, dataObject, labelFunc){
14040 // Fills in the items in the drop down list
14042 // Array of dojo.data items
14046 // Function to produce a label in the drop down list from a dojo.data item
14048 //this._dataObject=dataObject;
14049 //this._dataObject.onComplete=dojo.hitch(comboBox, comboBox._openResultList);
14050 // display "Previous . . ." button
14051 this.previousButton.style.display = (dataObject.start == 0) ? "none" : "";
14052 dojo.attr(this.previousButton, "id", this.id + "_prev");
14053 // create options using _createOption function defined by parent
14054 // ComboBox (or FilteringSelect) class
14056 // iterate over cache nondestructively
14057 dojo.forEach(results, function(item, i){
14058 var menuitem = this._createOption(item, labelFunc);
14059 menuitem.className = "dijitReset dijitMenuItem" +
14060 (this.isLeftToRight() ? "" : " dijitMenuItemRtl");
14061 dojo.attr(menuitem, "id", this.id + i);
14062 this.domNode.insertBefore(menuitem, this.nextButton);
14064 // display "Next . . ." button
14065 var displayMore = false;
14066 //Try to determine if we should show 'more
'...
14067 if(dataObject._maxOptions && dataObject._maxOptions != -1){
14068 if((dataObject.start + dataObject.count) < dataObject._maxOptions){
14069 displayMore = true;
14070 }else if((dataObject.start + dataObject.count) > dataObject._maxOptions && dataObject.count == results.length){
14071 //Weird return from a datastore, where a start + count > maxOptions
14072 // implies maxOptions isn't really valid and we have to go into faking it
.
14073 //And more or less assume more if count == results.length
14074 displayMore
= true;
14076 }else if(dataObject
.count
== results
.length
){
14077 //Don't know the size, so we do the best we can based off count alone.
14078 //So, if we have an exact match to count, assume more.
14079 displayMore
= true;
14082 this.nextButton
.style
.display
= displayMore
? "" : "none";
14083 dojo
.attr(this.nextButton
,"id", this.id
+ "_next");
14084 return this.domNode
.childNodes
;
14087 clearResultList: function(){
14089 // Clears the entries in the drop down list, but of course keeps the previous and next buttons.
14090 while(this.domNode
.childNodes
.length
>2){
14091 this.domNode
.removeChild(this.domNode
.childNodes
[this.domNode
.childNodes
.length
-2]);
14095 _onMouseDown: function(/*Event*/ evt
){
14096 dojo
.stopEvent(evt
);
14099 _onMouseUp: function(/*Event*/ evt
){
14100 if(evt
.target
=== this.domNode
|| !this._highlighted_option
){
14102 }else if(evt
.target
== this.previousButton
){
14104 }else if(evt
.target
== this.nextButton
){
14107 var tgt
= evt
.target
;
14108 // while the clicked node is inside the div
14110 // recurse to the top
14111 tgt
= tgt
.parentNode
;
14113 this._setValueAttr({ target
: tgt
}, true);
14117 _onMouseOver: function(/*Event*/ evt
){
14118 if(evt
.target
=== this.domNode
){ return; }
14119 var tgt
= evt
.target
;
14120 if(!(tgt
== this.previousButton
|| tgt
== this.nextButton
)){
14121 // while the clicked node is inside the div
14123 // recurse to the top
14124 tgt
= tgt
.parentNode
;
14127 this._focusOptionNode(tgt
);
14130 _onMouseOut: function(/*Event*/ evt
){
14131 if(evt
.target
=== this.domNode
){ return; }
14132 this._blurOptionNode();
14135 _focusOptionNode: function(/*DomNode*/ node
){
14137 // Does the actual highlight.
14138 if(this._highlighted_option
!= node
){
14139 this._blurOptionNode();
14140 this._highlighted_option
= node
;
14141 dojo
.addClass(this._highlighted_option
, "dijitMenuItemSelected");
14145 _blurOptionNode: function(){
14147 // Removes highlight on highlighted option.
14148 if(this._highlighted_option
){
14149 dojo
.removeClass(this._highlighted_option
, "dijitMenuItemSelected");
14150 this._highlighted_option
= null;
14154 _highlightNextOption: function(){
14156 // Highlight the item just below the current selection.
14157 // If nothing selected, highlight first option.
14159 // because each press of a button clears the menu,
14160 // the highlighted option sometimes becomes detached from the menu!
14161 // test to see if the option has a parent to see if this is the case.
14162 if(!this.getHighlightedOption()){
14163 var fc
= this.domNode
.firstChild
;
14164 this._focusOptionNode(fc
.style
.display
== "none" ? fc
.nextSibling
: fc
);
14166 var ns
= this._highlighted_option
.nextSibling
;
14167 if(ns
&& ns
.style
.display
!= "none"){
14168 this._focusOptionNode(ns
);
14170 this.highlightFirstOption();
14173 // scrollIntoView is called outside of _focusOptionNode because in IE putting it inside causes the menu to scroll up on mouseover
14174 dojo
.window
.scrollIntoView(this._highlighted_option
);
14177 highlightFirstOption: function(){
14179 // Highlight the first real item in the list (not Previous Choices).
14180 var first
= this.domNode
.firstChild
;
14181 var second
= first
.nextSibling
;
14182 this._focusOptionNode(second
.style
.display
== "none" ? first
: second
); // remotely possible that Previous Choices is the only thing in the list
14183 dojo
.window
.scrollIntoView(this._highlighted_option
);
14186 highlightLastOption: function(){
14188 // Highlight the last real item in the list (not More Choices).
14189 this._focusOptionNode(this.domNode
.lastChild
.previousSibling
);
14190 dojo
.window
.scrollIntoView(this._highlighted_option
);
14193 _highlightPrevOption: function(){
14195 // Highlight the item just above the current selection.
14196 // If nothing selected, highlight last option (if
14197 // you select Previous and try to keep scrolling up the list).
14198 if(!this.getHighlightedOption()){
14199 var lc
= this.domNode
.lastChild
;
14200 this._focusOptionNode(lc
.style
.display
== "none" ? lc
.previousSibling
: lc
);
14202 var ps
= this._highlighted_option
.previousSibling
;
14203 if(ps
&& ps
.style
.display
!= "none"){
14204 this._focusOptionNode(ps
);
14206 this.highlightLastOption();
14209 dojo
.window
.scrollIntoView(this._highlighted_option
);
14212 _page: function(/*Boolean*/ up
){
14214 // Handles page-up and page-down keypresses
14216 var scrollamount
= 0;
14217 var oldscroll
= this.domNode
.scrollTop
;
14218 var height
= dojo
.style(this.domNode
, "height");
14219 // if no item is highlighted, highlight the first option
14220 if(!this.getHighlightedOption()){
14221 this._highlightNextOption();
14223 while(scrollamount
<height
){
14225 // stop at option 1
14226 if(!this.getHighlightedOption().previousSibling
||
14227 this._highlighted_option
.previousSibling
.style
.display
== "none"){
14230 this._highlightPrevOption();
14232 // stop at last option
14233 if(!this.getHighlightedOption().nextSibling
||
14234 this._highlighted_option
.nextSibling
.style
.display
== "none"){
14237 this._highlightNextOption();
14240 var newscroll
=this.domNode
.scrollTop
;
14241 scrollamount
+=(newscroll
-oldscroll
)*(up
? -1:1);
14242 oldscroll
=newscroll
;
14246 pageUp: function(){
14248 // Handles pageup keypress.
14249 // TODO: just call _page directly from handleKey().
14255 pageDown: function(){
14257 // Handles pagedown keypress.
14258 // TODO: just call _page directly from handleKey().
14264 getHighlightedOption: function(){
14266 // Returns the highlighted option.
14267 var ho
= this._highlighted_option
;
14268 return (ho
&& ho
.parentNode
) ? ho
: null;
14271 handleKey: function(key
){
14273 case dojo
.keys
.DOWN_ARROW
:
14274 this._highlightNextOption();
14276 case dojo
.keys
.PAGE_DOWN
:
14279 case dojo
.keys
.UP_ARROW
:
14280 this._highlightPrevOption();
14282 case dojo
.keys
.PAGE_UP
:
14291 "dijit.form.ComboBox",
14292 [dijit
.form
.ValidationTextBox
, dijit
.form
.ComboBoxMixin
],
14295 // Auto-completing text box, and base class for dijit.form.FilteringSelect.
14298 // The drop down box's values are populated from an class called
14299 // a data provider, which returns a list of values based on the characters
14300 // that the user has typed into the input box.
14301 // If OPTION tags are used as the data provider via markup,
14302 // then the OPTION tag's child text node is used as the widget value
14303 // when selected. The OPTION tag's value attribute is ignored.
14304 // To set the default value when using OPTION tags, specify the selected
14305 // attribute on 1 of the child OPTION tags.
14307 // Some of the options to the ComboBox are actually arguments to the data
14310 _setValueAttr: function(/*String*/ value
, /*Boolean?*/ priorityChange
, /*String?*/ displayedValue
){
14312 // Hook so attr('value', value) works.
14314 // Sets the value of the select.
14315 this.item
= null; // value not looked up in store
14316 if(!value
){ value
= ''; } // null translates to blank
14317 dijit
.form
.ValidationTextBox
.prototype._setValueAttr
.call(this, value
, priorityChange
, displayedValue
);
14322 dojo
.declare("dijit.form._ComboBoxDataStore", null, {
14324 // Inefficient but small data store specialized for inlined `dijit.form.ComboBox` data
14327 // Provides a store for inlined data like:
14330 // | <option value="AL">Alabama</option>
14333 // Actually. just implements the subset of dojo.data.Read/Notification
14334 // needed for ComboBox and FilteringSelect to work.
14336 // Note that an item is just a pointer to the <option> DomNode.
14338 constructor: function( /*DomNode*/ root
){
14340 if(root
.tagName
!= "SELECT" && root
.firstChild
){
14341 root
= dojo
.query("select", root
);
14342 if(root
.length
> 0){ // SELECT is a child of srcNodeRef
14344 }else{ // no select, so create 1 to parent the option tags to define selectedIndex
14345 this.root
.innerHTML
= "<SELECT>"+this.root
.innerHTML
+"</SELECT>";
14346 root
= this.root
.firstChild
;
14350 dojo
.query("> option", root
).forEach(function(node
){
14351 // TODO: this was added in #3858 but unclear why/if it's needed; doesn't seem to be.
14352 // If it is needed then can we just hide the select itself instead?
14353 //node.style.display="none";
14354 node
.innerHTML
= dojo
.trim(node
.innerHTML
);
14359 getValue: function( /* item */ item
,
14360 /* attribute-name-string */ attribute
,
14361 /* value? */ defaultValue
){
14362 return (attribute
== "value") ? item
.value
: (item
.innerText
|| item
.textContent
|| '');
14365 isItemLoaded: function(/* anything */ something
){
14369 getFeatures: function(){
14370 return {"dojo.data.api.Read": true, "dojo.data.api.Identity": true};
14373 _fetchItems: function( /* Object */ args
,
14374 /* Function */ findCallback
,
14375 /* Function */ errorCallback
){
14377 // See dojo.data.util.simpleFetch.fetch()
14378 if(!args
.query
){ args
.query
= {}; }
14379 if(!args
.query
.name
){ args
.query
.name
= ""; }
14380 if(!args
.queryOptions
){ args
.queryOptions
= {}; }
14381 var matcher
= dojo
.data
.util
.filter
.patternToRegExp(args
.query
.name
, args
.queryOptions
.ignoreCase
),
14382 items
= dojo
.query("> option", this.root
).filter(function(option
){
14383 return (option
.innerText
|| option
.textContent
|| '').match(matcher
);
14386 items
.sort(dojo
.data
.util
.sorter
.createSortFunction(args
.sort
, this));
14388 findCallback(items
, args
);
14391 close: function(/*dojo.data.api.Request || args || null */ request
){
14395 getLabel: function(/* item */ item
){
14396 return item
.innerHTML
;
14399 getIdentity: function(/* item */ item
){
14400 return dojo
.attr(item
, "value");
14403 fetchItemByIdentity: function(/* Object */ args
){
14405 // Given the identity of an item, this method returns the item that has
14406 // that identity through the onItem callback.
14407 // Refer to dojo.data.api.Identity.fetchItemByIdentity() for more details.
14410 // Given arguments like:
14412 // | {identity: "CA", onItem: function(item){...}
14414 // Call `onItem()` with the DOM node `<option value="CA">California</option>`
14415 var item
= dojo
.query("> option[value='" + args
.identity
+ "']", this.root
)[0];
14419 fetchSelectedItem: function(){
14421 // Get the option marked as selected, like `<option selected>`.
14422 // Not part of dojo.data API.
14423 var root
= this.root
,
14424 si
= root
.selectedIndex
;
14425 return typeof si
== "number"
14426 ? dojo
.query("> option:nth-child(" + (si
!= -1 ? si
+1 : 1) + ")", root
)[0]
14427 : null; // dojo.data.Item
14430 //Mix in the simple fetch implementation to this class.
14431 dojo
.extend(dijit
.form
._ComboBoxDataStore
,dojo
.data
.util
.simpleFetch
);
14435 if(!dojo
._hasResource
["dijit.form.FilteringSelect"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
14436 dojo
._hasResource
["dijit.form.FilteringSelect"] = true;
14437 dojo
.provide("dijit.form.FilteringSelect");
14442 "dijit.form.FilteringSelect",
14443 [dijit
.form
.MappedTextBox
, dijit
.form
.ComboBoxMixin
],
14446 // An enhanced version of the HTML SELECT tag, populated dynamically
14449 // An enhanced version of the HTML SELECT tag, populated dynamically. It works
14450 // very nicely with very large data sets because it can load and page data as needed.
14451 // It also resembles ComboBox, but does not allow values outside of the provided ones.
14452 // If OPTION tags are used as the data provider via markup, then the
14453 // OPTION tag's child text node is used as the displayed value when selected
14454 // while the OPTION tag's value attribute is used as the widget value on form submit.
14455 // To set the default value when using OPTION tags, specify the selected
14456 // attribute on 1 of the child OPTION tags.
14458 // Similar features:
14459 // - There is a drop down list of possible values.
14460 // - You can only enter a value from the drop down list. (You can't
14461 // enter an arbitrary value.)
14462 // - The value submitted with the form is the hidden value (ex: CA),
14463 // not the displayed value a.k.a. label (ex: California)
14465 // Enhancements over plain HTML version:
14466 // - If you type in some text then it will filter down the list of
14467 // possible values in the drop down list.
14468 // - List can be specified either as a static list or via a javascript
14469 // function (that can get the list from a server)
14473 // required: Boolean
14474 // True (default) if user is required to enter a value into this field.
14477 _lastDisplayedValue
: "",
14479 isValid: function(){
14480 // Overrides ValidationTextBox.isValid()
14481 return this._isvalid
|| (!this.required
&& this.get('displayedValue') == ""); // #5974
14484 _refreshState: function(){
14485 if(!this.searchTimer
){ // state will be refreshed after results are returned
14486 this.inherited(arguments
);
14490 _callbackSetLabel: function( /*Array*/ result
,
14491 /*Object*/ dataObject
,
14492 /*Boolean?*/ priorityChange
){
14494 // Callback function that dynamically sets the label of the
14497 // setValue does a synchronous lookup,
14498 // so it calls _callbackSetLabel directly,
14499 // and so does not pass dataObject
14500 // still need to test against _lastQuery in case it came too late
14501 if((dataObject
&& dataObject
.query
[this.searchAttr
] != this._lastQuery
) || (!dataObject
&& result
.length
&& this.store
.getIdentity(result
[0]) != this._lastQuery
)){
14504 if(!result
.length
){
14505 //#3268: do nothing on bad input
14506 //#3285: change CSS to indicate error
14507 this.valueNode
.value
= "";
14508 dijit
.form
.TextBox
.superclass
._setValueAttr
.call(this, "", priorityChange
|| (priorityChange
=== undefined && !this._focused
));
14509 this._isvalid
= false;
14510 this.validate(this._focused
);
14513 this.set('item', result
[0], priorityChange
);
14517 _openResultList: function(/*Object*/ results
, /*Object*/ dataObject
){
14518 // Overrides ComboBox._openResultList()
14520 // #3285: tap into search callback to see if user's query resembles a match
14521 if(dataObject
.query
[this.searchAttr
] != this._lastQuery
){
14524 if(this.item
=== undefined){ // item == undefined for keyboard search
14525 this._isvalid
= results
.length
!= 0 || this._maxOptions
!= 0; // result.length==0 && maxOptions != 0 implies the nextChoices item selected but then the datastore returned 0 more entries
14526 this.validate(true);
14528 dijit
.form
.ComboBoxMixin
.prototype._openResultList
.apply(this, arguments
);
14531 _getValueAttr: function(){
14533 // Hook for attr('value') to work.
14535 // don't get the textbox value but rather the previously set hidden value.
14536 // Use this.valueNode.value which isn't always set for other MappedTextBox widgets until blur
14537 return this.valueNode
.value
;
14540 _getValueField: function(){
14541 // Overrides ComboBox._getValueField()
14545 _setValueAttr: function(/*String*/ value
, /*Boolean?*/ priorityChange
){
14547 // Hook so attr('value', value) works.
14549 // Sets the value of the select.
14550 // Also sets the label to the corresponding value by reverse lookup.
14551 if(!this._onChangeActive
){ priorityChange
= null; }
14552 this._lastQuery
= value
;
14554 if(value
=== null || value
=== ''){
14555 this._setDisplayedValueAttr('', priorityChange
);
14559 //#3347: fetchItemByIdentity if no keyAttr specified
14561 this.store
.fetchItemByIdentity({
14563 onItem: function(item
){
14564 self
._callbackSetLabel(item
? [item
] : [], undefined, priorityChange
);
14569 _setItemAttr: function(/*item*/ item
, /*Boolean?*/ priorityChange
, /*String?*/ displayedValue
){
14571 // Set the displayed valued in the input box, and the hidden value
14572 // that gets submitted, based on a dojo.data store item.
14574 // Users shouldn't call this function; they should be calling
14575 // attr('item', value)
14578 this._isvalid
= true;
14579 this.inherited(arguments
);
14580 this.valueNode
.value
= this.value
;
14581 this._lastDisplayedValue
= this.textbox
.value
;
14584 _getDisplayQueryString: function(/*String*/ text
){
14585 return text
.replace(/([\\\*\?])/g, "\\$1");
14588 _setDisplayedValueAttr: function(/*String*/ label
, /*Boolean?*/ priorityChange
){
14590 // Hook so attr('displayedValue', label) works.
14592 // Sets textbox to display label. Also performs reverse lookup
14593 // to set the hidden value.
14595 // When this is called during initialization it'll ping the datastore
14596 // for reverse lookup, and when that completes (after an XHR request)
14597 // will call setValueAttr()... but that shouldn't trigger an onChange()
14598 // event, even when it happens after creation has finished
14599 if(!this._created
){
14600 priorityChange
= false;
14604 this._hideResultList();
14605 var query
= dojo
.clone(this.query
); // #6196: populate query with user-specifics
14606 // escape meta characters of dojo.data.util.filter.patternToRegExp().
14607 this._lastQuery
= query
[this.searchAttr
] = this._getDisplayQueryString(label
);
14608 // if the label is not valid, the callback will never set it,
14609 // so the last valid value will get the warning textbox set the
14610 // textbox value now so that the impending warning will make
14611 // sense to the user
14612 this.textbox
.value
= label
;
14613 this._lastDisplayedValue
= label
;
14618 ignoreCase
: this.ignoreCase
,
14621 onComplete: function(result
, dataObject
){
14622 _this
._fetchHandle
= null;
14623 dojo
.hitch(_this
, "_callbackSetLabel")(result
, dataObject
, priorityChange
);
14625 onError: function(errText
){
14626 _this
._fetchHandle
= null;
14627 console
.error('dijit.form.FilteringSelect: ' + errText
);
14628 dojo
.hitch(_this
, "_callbackSetLabel")([], undefined, false);
14631 dojo
.mixin(fetch
, this.fetchProperties
);
14632 this._fetchHandle
= this.store
.fetch(fetch
);
14636 postMixInProperties: function(){
14637 this.inherited(arguments
);
14638 this._isvalid
= !this.required
;
14642 this.set('displayedValue', this._lastDisplayedValue
);
14649 if(!dojo
._hasResource
["dijit.form.Form"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
14650 dojo
._hasResource
["dijit.form.Form"] = true;
14651 dojo
.provide("dijit.form.Form");
14659 [dijit
._Widget
, dijit
._Templated
, dijit
.form
._FormMixin
],
14662 // Widget corresponding to HTML form tag, for validation and serialization
14665 // | <form dojoType="dijit.form.Form" id="myForm">
14666 // | Name: <input type="text" name="name" />
14668 // | myObj = {name: "John Doe"};
14669 // | dijit.byId('myForm').set('value', myObj);
14671 // | myObj=dijit.byId('myForm').get('value');
14673 // HTML <FORM> attributes
14676 // Name of form for scripting.
14680 // Server-side form handler.
14684 // HTTP method used to submit the form, either "GET" or "POST".
14687 // encType: String?
14688 // Encoding type for the form, ex: application/x-www-form-urlencoded.
14691 // accept-charset: String?
14692 // List of supported charsets.
14693 "accept-charset": "",
14696 // List of MIME types for file upload.
14700 // Target frame for the document to be opened in.
14703 templateString
: "<form dojoAttachPoint='containerNode' dojoAttachEvent='onreset:_onReset,onsubmit:_onSubmit' ${!nameAttrSetting}></form>",
14705 attributeMap
: dojo
.delegate(dijit
._Widget
.prototype.attributeMap
, {
14709 "accept-charset": "",
14714 postMixInProperties: function(){
14715 // Setup name=foo string to be referenced from the template (but only if a name has been specified)
14716 // Unfortunately we can't use attributeMap to set the name due to IE limitations, see #8660
14717 this.nameAttrSetting
= this.name
? ("name='" + this.name
+ "'") : "";
14718 this.inherited(arguments
);
14721 execute: function(/*Object*/ formContents
){
14723 // Deprecated: use submit()
14728 onExecute: function(){
14730 // Deprecated: use onSubmit()
14735 _setEncTypeAttr: function(/*String*/ value
){
14736 this.encType
= value
;
14737 dojo
.attr(this.domNode
, "encType", value
);
14738 if(dojo
.isIE
){ this.domNode
.encoding
= value
; }
14741 postCreate: function(){
14742 // IE tries to hide encType
14743 // TODO: this code should be in parser, not here.
14744 if(dojo
.isIE
&& this.srcNodeRef
&& this.srcNodeRef
.attributes
){
14745 var item
= this.srcNodeRef
.attributes
.getNamedItem('encType');
14746 if(item
&& !item
.specified
&& (typeof item
.value
== "string")){
14747 this.set('encType', item
.value
);
14750 this.inherited(arguments
);
14753 reset: function(/*Event?*/ e
){
14755 // restores all widget values back to their init values,
14756 // calls onReset() which can cancel the reset by returning false
14758 // create fake event so we can know if preventDefault() is called
14760 returnValue
: true, // the IE way
14761 preventDefault: function(){ // not IE
14762 this.returnValue
= false;
14764 stopPropagation: function(){},
14765 currentTarget
: e
? e
.target
: this.domNode
,
14766 target
: e
? e
.target
: this.domNode
14768 // if return value is not exactly false, and haven't called preventDefault(), then reset
14769 if(!(this.onReset(faux
) === false) && faux
.returnValue
){
14770 this.inherited(arguments
, []);
14774 onReset: function(/*Event?*/ e
){
14776 // Callback when user resets the form. This method is intended
14777 // to be over-ridden. When the `reset` method is called
14778 // programmatically, the return value from `onReset` is used
14779 // to compute whether or not resetting should proceed
14782 return true; // Boolean
14785 _onReset: function(e
){
14791 _onSubmit: function(e
){
14792 var fp
= dijit
.form
.Form
.prototype;
14793 // TODO: remove this if statement beginning with 2.0
14794 if(this.execute
!= fp
.execute
|| this.onExecute
!= fp
.onExecute
){
14795 dojo
.deprecated("dijit.form.Form:execute()/onExecute() are deprecated. Use onSubmit() instead.", "", "2.0");
14797 this.execute(this.getValues());
14799 if(this.onSubmit(e
) === false){ // only exactly false stops submit
14804 onSubmit: function(/*Event?*/e
){
14806 // Callback when user submits the form.
14808 // This method is intended to be over-ridden, but by default it checks and
14809 // returns the validity of form elements. When the `submit`
14810 // method is called programmatically, the return value from
14811 // `onSubmit` is used to compute whether or not submission
14816 return this.isValid(); // Boolean
14819 submit: function(){
14821 // programmatically submit form if and only if the `onSubmit` returns true
14822 if(!(this.onSubmit() === false)){
14823 this.containerNode
.submit();
14831 if(!dojo
._hasResource
["dijit.form.RadioButton"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
14832 dojo
._hasResource
["dijit.form.RadioButton"] = true;
14833 dojo
.provide("dijit.form.RadioButton");
14836 // TODO: for 2.0, move the RadioButton code into this file
14840 if(!dojo
._hasResource
["dijit.form._FormSelectWidget"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
14841 dojo
._hasResource
["dijit.form._FormSelectWidget"] = true;
14842 dojo
.provide("dijit.form._FormSelectWidget");
14848 dijit.form.__SelectOption = function(){
14850 // The value of the option. Setting to empty (or missing) will
14851 // place a separator at that location
14853 // The label for our option. It can contain html tags.
14854 // selected: Boolean
14855 // Whether or not we are a selected option
14856 // disabled: Boolean
14857 // Whether or not this specific option is disabled
14858 this.value = value;
14859 this.label = label;
14860 this.selected = selected;
14861 this.disabled = disabled;
14865 dojo
.declare("dijit.form._FormSelectWidget", dijit
.form
._FormValueWidget
, {
14867 // Extends _FormValueWidget in order to provide "select-specific"
14868 // values - i.e., those values that are unique to <select> elements.
14869 // This also provides the mechanism for reading the elements from
14870 // a store, if desired.
14872 // multiple: Boolean
14873 // Whether or not we are multi-valued
14876 // options: dijit.form.__SelectOption[]
14877 // The set of options for our select item. Roughly corresponds to
14878 // the html <option> tag.
14881 // store: dojo.data.api.Identity
14882 // A store which, at the very least impelements dojo.data.api.Identity
14883 // to use for getting our list of options - rather than reading them
14884 // from the <option> html tags.
14888 // A query to use when fetching items from our store
14891 // queryOptions: object
14892 // Query options to use when fetching from the store
14893 queryOptions
: null,
14895 // onFetch: Function
14896 // A callback to do with an onFetch - but before any items are actually
14897 // iterated over (i.e. to filter even futher what you want to add)
14900 // sortByLabel: boolean
14901 // Flag to sort the options returned from a store by the label of
14906 // loadChildrenOnOpen: boolean
14907 // By default loadChildren is called when the items are fetched from the
14908 // store. This property allows delaying loadChildren (and the creation
14909 // of the options/menuitems) until the user opens the click the button.
14911 loadChildrenOnOpen
: false,
14913 getOptions: function(/* anything */ valueOrIdx
){
14915 // Returns a given option (or options).
14917 // If passed in as a string, that string is used to look up the option
14918 // in the array of options - based on the value property.
14919 // (See dijit.form.__SelectOption).
14921 // If passed in a number, then the option with the given index (0-based)
14922 // within this select will be returned.
14924 // If passed in a dijit.form.__SelectOption, the same option will be
14925 // returned if and only if it exists within this select.
14927 // If passed an array, then an array will be returned with each element
14928 // in the array being looked up.
14930 // If not passed a value, then all options will be returned
14933 // The option corresponding with the given value or index. null
14934 // is returned if any of the following are true:
14935 // - A string value is passed in which doesn't exist
14936 // - An index is passed in which is outside the bounds of the array of options
14937 // - A dijit.form.__SelectOption is passed in which is not a part of the select
14939 // NOTE: the compare for passing in a dijit.form.__SelectOption checks
14940 // if the value property matches - NOT if the exact option exists
14941 // NOTE: if passing in an array, null elements will be placed in the returned
14942 // array when a value is not found.
14943 var lookupValue
= valueOrIdx
, opts
= this.options
|| [], l
= opts
.length
;
14945 if(lookupValue
=== undefined){
14946 return opts
; // dijit.form.__SelectOption[]
14948 if(dojo
.isArray(lookupValue
)){
14949 return dojo
.map(lookupValue
, "return this.getOptions(item);", this); // dijit.form.__SelectOption[]
14951 if(dojo
.isObject(valueOrIdx
)){
14952 // We were passed an option - so see if it's in our array (directly),
14953 // and if it's not, try and find it by value.
14954 if(!dojo
.some(this.options
, function(o
, idx
){
14955 if(o
=== lookupValue
||
14956 (o
.value
&& o
.value
=== lookupValue
.value
)){
14965 if(typeof lookupValue
== "string"){
14966 for(var i
=0; i
<l
; i
++){
14967 if(opts
[i
].value
=== lookupValue
){
14973 if(typeof lookupValue
== "number" && lookupValue
>= 0 && lookupValue
< l
){
14974 return this.options
[lookupValue
] // dijit.form.__SelectOption
14976 return null; // null
14979 addOption: function(/* dijit.form.__SelectOption, dijit.form.__SelectOption[] */ option
){
14981 // Adds an option or options to the end of the select. If value
14982 // of the option is empty or missing, a separator is created instead.
14983 // Passing in an array of options will yield slightly better performance
14984 // since the children are only loaded once.
14985 if(!dojo
.isArray(option
)){ option
= [option
]; }
14986 dojo
.forEach(option
, function(i
){
14987 if(i
&& dojo
.isObject(i
)){
14988 this.options
.push(i
);
14991 this._loadChildren();
14994 removeOption: function(/* string, dijit.form.__SelectOption, number, or array */ valueOrIdx
){
14996 // Removes the given option or options. You can remove by string
14997 // (in which case the value is removed), number (in which case the
14998 // index in the options array is removed), or select option (in
14999 // which case, the select option with a matching value is removed).
15000 // You can also pass in an array of those values for a slightly
15001 // better performance since the children are only loaded once.
15002 if(!dojo
.isArray(valueOrIdx
)){ valueOrIdx
= [valueOrIdx
]; }
15003 var oldOpts
= this.getOptions(valueOrIdx
);
15004 dojo
.forEach(oldOpts
, function(i
){
15005 // We can get null back in our array - if our option was not found. In
15006 // that case, we don't want to blow up...
15008 this.options
= dojo
.filter(this.options
, function(node
, idx
){
15009 return (node
.value
!== i
.value
);
15011 this._removeOptionItem(i
);
15014 this._loadChildren();
15017 updateOption: function(/* dijit.form.__SelectOption, dijit.form.__SelectOption[] */ newOption
){
15019 // Updates the values of the given option. The option to update
15020 // is matched based on the value of the entered option. Passing
15021 // in an array of new options will yeild better performance since
15022 // the children will only be loaded once.
15023 if(!dojo
.isArray(newOption
)){ newOption
= [newOption
]; }
15024 dojo
.forEach(newOption
, function(i
){
15025 var oldOpt
= this.getOptions(i
), k
;
15027 for(k
in i
){ oldOpt
[k
] = i
[k
]; }
15030 this._loadChildren();
15033 setStore: function(/* dojo.data.api.Identity */ store
,
15034 /* anything? */ selectedValue
,
15035 /* Object? */ fetchArgs
){
15037 // Sets the store you would like to use with this select widget.
15038 // The selected value is the value of the new store to set. This
15039 // function returns the original store, in case you want to reuse
15040 // it or something.
15041 // store: dojo.data.api.Identity
15042 // The store you would like to use - it MUST implement Identity,
15043 // and MAY implement Notification.
15044 // selectedValue: anything?
15045 // The value that this widget should set itself to *after* the store
15047 // fetchArgs: Object?
15048 // The arguments that will be passed to the store's fetch() function
15049 var oStore
= this.store
;
15050 fetchArgs
= fetchArgs
|| {};
15051 if(oStore
!== store
){
15052 // Our store has changed, so update our notifications
15053 dojo
.forEach(this._notifyConnections
|| [], dojo
.disconnect
);
15054 delete this._notifyConnections
;
15055 if(store
&& store
.getFeatures()["dojo.data.api.Notification"]){
15056 this._notifyConnections
= [
15057 dojo
.connect(store
, "onNew", this, "_onNewItem"),
15058 dojo
.connect(store
, "onDelete", this, "_onDeleteItem"),
15059 dojo
.connect(store
, "onSet", this, "_onSetItem")
15062 this.store
= store
;
15065 // Turn off change notifications while we make all these changes
15066 this._onChangeActive
= false;
15068 // Remove existing options (if there are any)
15069 if(this.options
&& this.options
.length
){
15070 this.removeOption(this.options
);
15073 // Add our new options
15075 var cb = function(items
){
15076 if(this.sortByLabel
&& !fetchArgs
.sort
&& items
.length
){
15077 items
.sort(dojo
.data
.util
.sorter
.createSortFunction([{
15078 attribute
: store
.getLabelAttributes(items
[0])[0]
15082 if(fetchArgs
.onFetch
){
15083 items
= fetchArgs
.onFetch(items
);
15085 // TODO: Add these guys as a batch, instead of separately
15086 dojo
.forEach(items
, function(i
){
15087 this._addOptionForItem(i
);
15090 // Set our value (which might be undefined), and then tweak
15091 // it to send a change event with the real value
15092 this._loadingStore
= false;
15093 this.set("value", (("_pendingValue" in this) ? this._pendingValue
: selectedValue
));
15094 delete this._pendingValue
;
15096 if(!this.loadChildrenOnOpen
){
15097 this._loadChildren();
15099 this._pseudoLoadChildren(items
);
15101 this._fetchedWith
= opts
;
15102 this._lastValueReported
= this.multiple
? [] : null;
15103 this._onChangeActive
= true;
15105 this._handleOnChange(this.value
);
15107 var opts
= dojo
.mixin({onComplete
:cb
, scope
: this}, fetchArgs
);
15108 this._loadingStore
= true;
15111 delete this._fetchedWith
;
15113 return oStore
; // dojo.data.api.Identity
15116 _setValueAttr: function(/*anything*/ newValue
, /*Boolean, optional*/ priorityChange
){
15118 // set the value of the widget.
15119 // If a string is passed, then we set our value from looking it up.
15120 if(this._loadingStore
){
15121 // Our store is loading - so save our value, and we'll set it when
15123 this._pendingValue
= newValue
;
15126 var opts
= this.getOptions() || [];
15127 if(!dojo
.isArray(newValue
)){
15128 newValue
= [newValue
];
15130 dojo
.forEach(newValue
, function(i
, idx
){
15131 if(!dojo
.isObject(i
)){
15134 if(typeof i
=== "string"){
15135 newValue
[idx
] = dojo
.filter(opts
, function(node
){
15136 return node
.value
=== i
;
15137 })[0] || {value
: "", label
: ""};
15141 // Make sure some sane default is set
15142 newValue
= dojo
.filter(newValue
, function(i
){ return i
&& i
.value
; });
15143 if(!this.multiple
&& (!newValue
[0] || !newValue
[0].value
) && opts
.length
){
15144 newValue
[0] = opts
[0];
15146 dojo
.forEach(opts
, function(i
){
15147 i
.selected
= dojo
.some(newValue
, function(v
){ return v
.value
=== i
.value
; });
15149 var val
= dojo
.map(newValue
, function(i
){ return i
.value
; }),
15150 disp
= dojo
.map(newValue
, function(i
){ return i
.label
; });
15152 this.value
= this.multiple
? val
: val
[0];
15153 this._setDisplay(this.multiple
? disp
: disp
[0]);
15154 this._updateSelection();
15155 this._handleOnChange(this.value
, priorityChange
);
15158 _getDisplayedValueAttr: function(){
15160 // returns the displayed value of the widget
15161 var val
= this.get("value");
15162 if(!dojo
.isArray(val
)){
15165 var ret
= dojo
.map(this.getOptions(val
), function(v
){
15166 if(v
&& "label" in v
){
15173 return this.multiple
? ret
: ret
[0];
15176 _getValueDeprecated
: false, // remove when _FormWidget:getValue is removed
15177 getValue: function(){
15179 // get the value of the widget.
15180 return this._lastValue
;
15185 // restore the value to the last value passed to onChange
15186 this._setValueAttr(this._lastValueReported
, false);
15189 _loadChildren: function(){
15191 // Loads the children represented by this widget's options.
15192 // reset the menu to make it "populatable on the next click
15193 if(this._loadingStore
){ return; }
15194 dojo
.forEach(this._getChildren(), function(child
){
15195 child
.destroyRecursive();
15197 // Add each menu item
15198 dojo
.forEach(this.options
, this._addOptionItem
, this);
15201 this._updateSelection();
15204 _updateSelection: function(){
15206 // Sets the "selected" class on the item for styling purposes
15207 this.value
= this._getValueFromOpts();
15208 var val
= this.value
;
15209 if(!dojo
.isArray(val
)){
15213 dojo
.forEach(this._getChildren(), function(child
){
15214 var isSelected
= dojo
.some(val
, function(v
){
15215 return child
.option
&& (v
=== child
.option
.value
);
15217 dojo
.toggleClass(child
.domNode
, this.baseClass
+ "SelectedOption", isSelected
);
15218 dijit
.setWaiState(child
.domNode
, "selected", isSelected
);
15221 this._handleOnChange(this.value
);
15224 _getValueFromOpts: function(){
15226 // Returns the value of the widget by reading the options for
15227 // the selected flag
15228 var opts
= this.getOptions() || [];
15229 if(!this.multiple
&& opts
.length
){
15230 // Mirror what a select does - choose the first one
15231 var opt
= dojo
.filter(opts
, function(i
){
15234 if(opt
&& opt
.value
){
15237 opts
[0].selected
= true;
15238 return opts
[0].value
;
15240 }else if(this.multiple
){
15241 // Set value to be the sum of all selected
15242 return dojo
.map(dojo
.filter(opts
, function(i
){
15251 // Internal functions to call when we have store notifications come in
15252 _onNewItem: function(/* item */ item
, /* Object? */ parentInfo
){
15253 if(!parentInfo
|| !parentInfo
.parent
){
15254 // Only add it if we are top-level
15255 this._addOptionForItem(item
);
15258 _onDeleteItem: function(/* item */ item
){
15259 var store
= this.store
;
15260 this.removeOption(store
.getIdentity(item
));
15262 _onSetItem: function(/* item */ item
){
15263 this.updateOption(this._getOptionObjForItem(item
));
15266 _getOptionObjForItem: function(item
){
15268 // Returns an option object based off the given item. The "value"
15269 // of the option item will be the identity of the item, the "label"
15270 // of the option will be the label of the item. If the item contains
15271 // children, the children value of the item will be set
15272 var store
= this.store
, label
= store
.getLabel(item
),
15273 value
= (label
? store
.getIdentity(item
) : null);
15274 return {value
: value
, label
: label
, item
:item
}; // dijit.form.__SelectOption
15277 _addOptionForItem: function(/* item */ item
){
15279 // Creates (and adds) the option for the given item
15280 var store
= this.store
;
15281 if(!store
.isItemLoaded(item
)){
15282 // We are not loaded - so let's load it and add later
15283 store
.loadItem({item
: item
, onComplete: function(i
){
15284 this._addOptionForItem(item
);
15289 var newOpt
= this._getOptionObjForItem(item
);
15290 this.addOption(newOpt
);
15293 constructor: function(/* Object */ keywordArgs
){
15295 // Saves off our value, if we have an initial one set so we
15296 // can use it if we have a store as well (see startup())
15297 this._oValue
= (keywordArgs
|| {}).value
|| null;
15300 _fillContent: function(){
15302 // Loads our options and sets up our dropdown correctly. We
15303 // don't want any content, so we don't call any inherit chain
15305 var opts
= this.options
;
15307 opts
= this.options
= this.srcNodeRef
? dojo
.query(">",
15308 this.srcNodeRef
).map(function(node
){
15309 if(node
.getAttribute("type") === "separator"){
15310 return { value
: "", label
: "", selected
: false, disabled
: false };
15312 return { value
: node
.getAttribute("value"),
15313 label
: String(node
.innerHTML
),
15314 selected
: node
.getAttribute("selected") || false,
15315 disabled
: node
.getAttribute("disabled") || false };
15319 this.value
= this._getValueFromOpts();
15320 }else if(this.multiple
&& typeof this.value
== "string"){
15321 this.value
= this.value
.split(",");
15325 postCreate: function(){
15327 // sets up our event handling that we need for functioning
15329 dojo
.setSelectable(this.focusNode
, false);
15330 this.inherited(arguments
);
15332 // Make our event connections for updating state
15333 this.connect(this, "onChange", "_updateSelection");
15334 this.connect(this, "startup", "_loadChildren");
15336 this._setValueAttr(this.value
, null);
15339 startup: function(){
15341 // Connects in our store, if we have one defined
15342 this.inherited(arguments
);
15343 var store
= this.store
, fetchArgs
= {};
15344 dojo
.forEach(["query", "queryOptions", "onFetch"], function(i
){
15346 fetchArgs
[i
] = this[i
];
15350 if(store
&& store
.getFeatures()["dojo.data.api.Identity"]){
15351 // Temporarily set our store to null so that it will get set
15352 // and connected appropriately
15354 this.setStore(store
, this._oValue
, fetchArgs
);
15358 destroy: function(){
15360 // Clean up our connections
15361 dojo
.forEach(this._notifyConnections
|| [], dojo
.disconnect
);
15362 this.inherited(arguments
);
15365 _addOptionItem: function(/* dijit.form.__SelectOption */ option
){
15367 // User-overridable function which, for the given option, adds an
15368 // item to the select. If the option doesn't have a value, then a
15369 // separator is added in that place. Make sure to store the option
15370 // in the created option widget.
15373 _removeOptionItem: function(/* dijit.form.__SelectOption */ option
){
15375 // User-overridable function which, for the given option, removes
15376 // its item from the select.
15379 _setDisplay: function(/*String or String[]*/ newDisplay
){
15381 // Overridable function which will set the display for the
15382 // widget. newDisplay is either a string (in the case of
15383 // single selects) or array of strings (in the case of multi-selects)
15386 _getChildren: function(){
15388 // Overridable function to return the children that this widget contains.
15392 _getSelectedOptionsAttr: function(){
15394 // hooks into this.attr to provide a mechanism for getting the
15395 // option items for the current value of the widget.
15396 return this.getOptions(this.get("value"));
15399 _pseudoLoadChildren: function(/* item[] */ items
){
15401 // a function that will "fake" loading children, if needed, and
15402 // if we have set to not load children until the widget opens.
15404 // An array of items that will be loaded, when needed
15407 onSetStore: function(){
15409 // a function that can be connected to in order to receive a
15410 // notification that the store has finished loading and all options
15411 // from that store are available
15417 if(!dojo
._hasResource
["dijit._KeyNavContainer"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
15418 dojo
._hasResource
["dijit._KeyNavContainer"] = true;
15419 dojo
.provide("dijit._KeyNavContainer");
15422 dojo
.declare("dijit._KeyNavContainer",
15427 // A _Container with keyboard navigation of its children.
15429 // To use this mixin, call connectKeyNavHandlers() in
15430 // postCreate() and call startupKeyNavChildren() in startup().
15431 // It provides normalized keyboard and focusing code for Container
15434 // focusedChild: [protected] Widget
15435 // The currently focused child widget, or null if there isn't one
15436 focusedChild: null,
15439 // tabIndex: Integer
15440 // Tab index of the container; same as HTML tabIndex attribute.
15441 // Note then when user tabs into the container, focus is immediately
15442 // moved to the first item in the container.
15447 connectKeyNavHandlers: function(/*dojo.keys[]*/ prevKeyCodes
, /*dojo.keys[]*/ nextKeyCodes
){
15449 // Call in postCreate() to attach the keyboard handlers
15450 // to the container.
15451 // preKeyCodes: dojo.keys[]
15452 // Key codes for navigating to the previous child.
15453 // nextKeyCodes: dojo.keys[]
15454 // Key codes for navigating to the next child.
15458 var keyCodes
= (this._keyNavCodes
= {});
15459 var prev
= dojo
.hitch(this, this.focusPrev
);
15460 var next
= dojo
.hitch(this, this.focusNext
);
15461 dojo
.forEach(prevKeyCodes
, function(code
){ keyCodes
[code
] = prev
; });
15462 dojo
.forEach(nextKeyCodes
, function(code
){ keyCodes
[code
] = next
; });
15463 this.connect(this.domNode
, "onkeypress", "_onContainerKeypress");
15464 this.connect(this.domNode
, "onfocus", "_onContainerFocus");
15467 startupKeyNavChildren: function(){
15469 // Call in startup() to set child tabindexes to -1
15472 dojo
.forEach(this.getChildren(), dojo
.hitch(this, "_startupChild"));
15475 addChild: function(/*dijit._Widget*/ widget
, /*int?*/ insertIndex
){
15477 // Add a child to our _Container
15478 dijit
._KeyNavContainer
.superclass
.addChild
.apply(this, arguments
);
15479 this._startupChild(widget
);
15484 // Default focus() implementation: focus the first child.
15485 this.focusFirstChild();
15488 focusFirstChild: function(){
15490 // Focus the first focusable child in the container.
15493 var child
= this._getFirstFocusableChild();
15494 if(child
){ // edge case: Menu could be empty or hidden
15495 this.focusChild(child
);
15499 focusNext: function(){
15501 // Focus the next widget
15504 var child
= this._getNextFocusableChild(this.focusedChild
, 1);
15505 this.focusChild(child
);
15508 focusPrev: function(){
15510 // Focus the last focusable node in the previous widget
15511 // (ex: go to the ComboButton icon section rather than button section)
15514 var child
= this._getNextFocusableChild(this.focusedChild
, -1);
15515 this.focusChild(child
, true);
15518 focusChild: function(/*dijit._Widget*/ widget
, /*Boolean*/ last
){
15522 // Reference to container's child widget
15524 // If true and if widget has multiple focusable nodes, focus the
15525 // last one instead of the first one
15529 if(this.focusedChild
&& widget
!== this.focusedChild
){
15530 this._onChildBlur(this.focusedChild
);
15532 widget
.focus(last
? "end" : "start");
15533 this.focusedChild
= widget
;
15536 _startupChild: function(/*dijit._Widget*/ widget
){
15538 // Setup for each child widget
15540 // Sets tabIndex=-1 on each child, so that the tab key will
15541 // leave the container rather than visiting each child.
15545 widget
.set("tabIndex", "-1");
15547 this.connect(widget
, "_onFocus", function(){
15548 // Set valid tabIndex so tabbing away from widget goes to right place, see #10272
15549 widget
.set("tabIndex", this.tabIndex
);
15551 this.connect(widget
, "_onBlur", function(){
15552 widget
.set("tabIndex", "-1");
15556 _onContainerFocus: function(evt
){
15558 // Handler for when the container gets focus
15560 // Initially the container itself has a tabIndex, but when it gets
15561 // focus, switch focus to first child...
15565 // Note that we can't use _onFocus() because switching focus from the
15566 // _onFocus() handler confuses the focus.js code
15567 // (because it causes _onFocusNode() to be called recursively)
15569 // focus bubbles on Firefox,
15570 // so just make sure that focus has really gone to the container
15571 if(evt
.target
!== this.domNode
){ return; }
15573 this.focusFirstChild();
15575 // and then set the container's tabIndex to -1,
15576 // (don't remove as that breaks Safari 4)
15577 // so that tab or shift-tab will go to the fields after/before
15578 // the container, rather than the container itself
15579 dojo
.attr(this.domNode
, "tabIndex", "-1");
15582 _onBlur: function(evt
){
15583 // When focus is moved away the container, and its descendant (popup) widgets,
15584 // then restore the container's tabIndex so that user can tab to it again.
15585 // Note that using _onBlur() so that this doesn't happen when focus is shifted
15586 // to one of my child widgets (typically a popup)
15588 dojo
.attr(this.domNode
, "tabIndex", this.tabIndex
);
15590 this.inherited(arguments
);
15593 _onContainerKeypress: function(evt
){
15595 // When a key is pressed, if it's an arrow key etc. then
15596 // it's handled here.
15599 if(evt
.ctrlKey
|| evt
.altKey
){ return; }
15600 var func
= this._keyNavCodes
[evt
.charOrCode
];
15603 dojo
.stopEvent(evt
);
15607 _onChildBlur: function(/*dijit._Widget*/ widget
){
15609 // Called when focus leaves a child widget to go
15610 // to a sibling widget.
15615 _getFirstFocusableChild: function(){
15617 // Returns first child that can be focused
15618 return this._getNextFocusableChild(null, 1); // dijit._Widget
15621 _getNextFocusableChild: function(child
, dir
){
15623 // Returns the next or previous focusable child, compared
15626 // The current widget
15631 child
= this._getSiblingOfChild(child
, dir
);
15633 var children
= this.getChildren();
15634 for(var i
=0; i
< children
.length
; i
++){
15636 child
= children
[(dir
>0) ? 0 : (children
.length
-1)];
15638 if(child
.isFocusable()){
15639 return child
; // dijit._Widget
15641 child
= this._getSiblingOfChild(child
, dir
);
15643 // no focusable child found
15644 return null; // dijit._Widget
15651 if(!dojo
._hasResource
["dijit.MenuItem"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
15652 dojo
._hasResource
["dijit.MenuItem"] = true;
15653 dojo
.provide("dijit.MenuItem");
15660 dojo
.declare("dijit.MenuItem",
15661 [dijit
._Widget
, dijit
._Templated
, dijit
._Contained
, dijit
._CssStateMixin
],
15664 // A line item in a Menu Widget
15667 // icon, label, and expand arrow (BiDi-dependent) indicating sub-menu
15668 templateString
: dojo
.cache("dijit", "templates/MenuItem.html", "<tr class=\"dijitReset dijitMenuItem\" dojoAttachPoint=\"focusNode\" waiRole=\"menuitem\" tabIndex=\"-1\"\n\t\tdojoAttachEvent=\"onmouseenter:_onHover,onmouseleave:_onUnhover,ondijitclick:_onClick\">\n\t<td class=\"dijitReset dijitMenuItemIconCell\" waiRole=\"presentation\">\n\t\t<img src=\"${_blankGif}\" alt=\"\" class=\"dijitIcon dijitMenuItemIcon\" dojoAttachPoint=\"iconNode\"/>\n\t</td>\n\t<td class=\"dijitReset dijitMenuItemLabel\" colspan=\"2\" dojoAttachPoint=\"containerNode\"></td>\n\t<td class=\"dijitReset dijitMenuItemAccelKey\" style=\"display: none\" dojoAttachPoint=\"accelKeyNode\"></td>\n\t<td class=\"dijitReset dijitMenuArrowCell\" waiRole=\"presentation\">\n\t\t<div dojoAttachPoint=\"arrowWrapper\" style=\"visibility: hidden\">\n\t\t\t<img src=\"${_blankGif}\" alt=\"\" class=\"dijitMenuExpand\"/>\n\t\t\t<span class=\"dijitMenuExpandA11y\">+</span>\n\t\t</div>\n\t</td>\n</tr>\n"),
15670 attributeMap
: dojo
.delegate(dijit
._Widget
.prototype.attributeMap
, {
15671 label
: { node
: "containerNode", type
: "innerHTML" },
15672 iconClass
: { node
: "iconNode", type
: "class" }
15675 baseClass
: "dijitMenuItem",
15681 // iconClass: String
15682 // Class to apply to DOMNode to make it display an icon.
15685 // accelKey: String
15686 // Text for the accelerator (shortcut) key combination.
15687 // Note that although Menu can display accelerator keys there
15688 // is no infrastructure to actually catch and execute these
15692 // disabled: Boolean
15693 // If true, the menu item is disabled.
15694 // If false, the menu item is enabled.
15697 _fillContent: function(/*DomNode*/ source
){
15698 // If button label is specified as srcNodeRef.innerHTML rather than
15699 // this.params.label, handle it here.
15700 if(source
&& !("label" in this.params
)){
15701 this.set('label', source
.innerHTML
);
15705 postCreate: function(){
15706 this.inherited(arguments
);
15707 dojo
.setSelectable(this.domNode
, false);
15708 var label
= this.id
+"_text";
15709 dojo
.attr(this.containerNode
, "id", label
);
15710 if(this.accelKeyNode
){
15711 dojo
.attr(this.accelKeyNode
, "id", this.id
+ "_accel");
15712 label
+= " " + this.id
+ "_accel";
15714 dijit
.setWaiState(this.domNode
, "labelledby", label
);
15717 _onHover: function(){
15719 // Handler when mouse is moved onto menu item
15722 this.getParent().onItemHover(this);
15725 _onUnhover: function(){
15727 // Handler when mouse is moved off of menu item,
15728 // possibly to a child menu, or maybe to a sibling
15729 // menuitem or somewhere else entirely.
15733 // if we are unhovering the currently selected item
15734 // then unselect it
15735 this.getParent().onItemUnhover(this);
15737 // _onUnhover() is called when the menu is hidden (collapsed), due to clicking
15738 // a MenuItem and having it execut. When that happens, FF and IE don't generate
15739 // an onmouseout event for the MenuItem, so give _CssStateMixin some help
15740 this._hovering
= false;
15741 this._setStateClass();
15744 _onClick: function(evt
){
15746 // Internal handler for click events on MenuItem.
15749 this.getParent().onItemClick(this, evt
);
15750 dojo
.stopEvent(evt
);
15753 onClick: function(/*Event*/ evt
){
15755 // User defined function to handle clicks
15762 // Focus on this MenuItem
15764 if(dojo
.isIE
== 8){
15765 // needed for IE8 which won't scroll TR tags into view on focus yet calling scrollIntoView creates flicker (#10275)
15766 this.containerNode
.focus();
15768 dijit
.focus(this.focusNode
);
15770 // this throws on IE (at least) in some scenarios
15774 _onFocus: function(){
15776 // This is called by the focus manager when focus
15777 // goes to this MenuItem or a child menu.
15780 this._setSelected(true);
15781 this.getParent()._onItemFocus(this);
15783 this.inherited(arguments
);
15786 _setSelected: function(selected
){
15788 // Indicate that this node is the currently selected one
15793 * TODO: remove this method and calls to it, when _onBlur() is working for MenuItem.
15794 * Currently _onBlur() gets called when focus is moved from the MenuItem to a child menu.
15795 * That's not supposed to happen, but the problem is:
15796 * In order to allow dijit.popup's getTopPopup() to work,a sub menu's popupParent
15797 * points to the parent Menu, bypassing the parent MenuItem... thus the
15798 * MenuItem is not in the chain of active widgets and gets a premature call to
15802 dojo
.toggleClass(this.domNode
, "dijitMenuItemSelected", selected
);
15805 setLabel: function(/*String*/ content
){
15807 // Deprecated. Use set('label', ...) instead.
15810 dojo
.deprecated("dijit.MenuItem.setLabel() is deprecated. Use set('label', ...) instead.", "", "2.0");
15811 this.set("label", content
);
15814 setDisabled: function(/*Boolean*/ disabled
){
15816 // Deprecated. Use set('disabled', bool) instead.
15819 dojo
.deprecated("dijit.Menu.setDisabled() is deprecated. Use set('disabled', bool) instead.", "", "2.0");
15820 this.set('disabled', disabled
);
15822 _setDisabledAttr: function(/*Boolean*/ value
){
15824 // Hook for attr('disabled', ...) to work.
15825 // Enable or disable this menu item.
15826 this.disabled
= value
;
15827 dijit
.setWaiState(this.focusNode
, 'disabled', value
? 'true' : 'false');
15829 _setAccelKeyAttr: function(/*String*/ value
){
15831 // Hook for attr('accelKey', ...) to work.
15832 // Set accelKey on this menu item.
15833 this.accelKey
=value
;
15835 this.accelKeyNode
.style
.display
=value
?"":"none";
15836 this.accelKeyNode
.innerHTML
=value
;
15837 //have to use colSpan to make it work in IE
15838 dojo
.attr(this.containerNode
,'colSpan',value
?"1":"2");
15844 if(!dojo
._hasResource
["dijit.PopupMenuItem"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
15845 dojo
._hasResource
["dijit.PopupMenuItem"] = true;
15846 dojo
.provide("dijit.PopupMenuItem");
15850 dojo
.declare("dijit.PopupMenuItem",
15853 _fillContent: function(){
15855 // When Menu is declared in markup, this code gets the menu label and
15856 // the popup widget from the srcNodeRef.
15858 // srcNodeRefinnerHTML contains both the menu item text and a popup widget
15859 // The first part holds the menu item text and the second part is the popup
15861 // | <div dojoType="dijit.PopupMenuItem">
15862 // | <span>pick me</span>
15863 // | <popup> ... </popup>
15868 if(this.srcNodeRef
){
15869 var nodes
= dojo
.query("*", this.srcNodeRef
);
15870 dijit
.PopupMenuItem
.superclass
._fillContent
.call(this, nodes
[0]);
15872 // save pointer to srcNode so we can grab the drop down widget after it's instantiated
15873 this.dropDownContainer
= this.srcNodeRef
;
15877 startup: function(){
15878 if(this._started
){ return; }
15879 this.inherited(arguments
);
15881 // we didn't copy the dropdown widget from the this.srcNodeRef, so it's in no-man's
15882 // land now. move it to dojo.doc.body.
15884 var node
= dojo
.query("[widgetId]", this.dropDownContainer
)[0];
15885 this.popup
= dijit
.byNode(node
);
15887 dojo
.body().appendChild(this.popup
.domNode
);
15888 this.popup
.startup();
15890 this.popup
.domNode
.style
.display
="none";
15891 if(this.arrowWrapper
){
15892 dojo
.style(this.arrowWrapper
, "visibility", "");
15894 dijit
.setWaiState(this.focusNode
, "haspopup", "true");
15897 destroyDescendants: function(){
15899 // Destroy the popup, unless it's already been destroyed. This can happen because
15900 // the popup is a direct child of <body> even though it's logically my child.
15901 if(!this.popup
._destroyed
){
15902 this.popup
.destroyRecursive();
15906 this.inherited(arguments
);
15913 if(!dojo
._hasResource
["dijit.CheckedMenuItem"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
15914 dojo
._hasResource
["dijit.CheckedMenuItem"] = true;
15915 dojo
.provide("dijit.CheckedMenuItem");
15919 dojo
.declare("dijit.CheckedMenuItem",
15923 // A checkbox-like menu item for toggling on and off
15925 templateString
: dojo
.cache("dijit", "templates/CheckedMenuItem.html", "<tr class=\"dijitReset dijitMenuItem\" dojoAttachPoint=\"focusNode\" waiRole=\"menuitemcheckbox\" tabIndex=\"-1\"\n\t\tdojoAttachEvent=\"onmouseenter:_onHover,onmouseleave:_onUnhover,ondijitclick:_onClick\">\n\t<td class=\"dijitReset dijitMenuItemIconCell\" waiRole=\"presentation\">\n\t\t<img src=\"${_blankGif}\" alt=\"\" class=\"dijitMenuItemIcon dijitCheckedMenuItemIcon\" dojoAttachPoint=\"iconNode\"/>\n\t\t<span class=\"dijitCheckedMenuItemIconChar\">✓</span>\n\t</td>\n\t<td class=\"dijitReset dijitMenuItemLabel\" colspan=\"2\" dojoAttachPoint=\"containerNode,labelNode\"></td>\n\t<td class=\"dijitReset dijitMenuItemAccelKey\" style=\"display: none\" dojoAttachPoint=\"accelKeyNode\"></td>\n\t<td class=\"dijitReset dijitMenuArrowCell\" waiRole=\"presentation\"> </td>\n</tr>\n"),
15927 // checked: Boolean
15928 // Our checked state
15930 _setCheckedAttr: function(/*Boolean*/ checked
){
15932 // Hook so attr('checked', bool) works.
15933 // Sets the class and state for the check box.
15934 dojo
.toggleClass(this.domNode
, "dijitCheckedMenuItemChecked", checked
);
15935 dijit
.setWaiState(this.domNode
, "checked", checked
);
15936 this.checked
= checked
;
15939 onChange: function(/*Boolean*/ checked
){
15941 // User defined function to handle check/uncheck events
15946 _onClick: function(/*Event*/ e
){
15948 // Clicking this item just toggles its state
15951 if(!this.disabled
){
15952 this.set("checked", !this.checked
);
15953 this.onChange(this.checked
);
15955 this.inherited(arguments
);
15961 if(!dojo
._hasResource
["dijit.MenuSeparator"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
15962 dojo
._hasResource
["dijit.MenuSeparator"] = true;
15963 dojo
.provide("dijit.MenuSeparator");
15969 dojo
.declare("dijit.MenuSeparator",
15970 [dijit
._Widget
, dijit
._Templated
, dijit
._Contained
],
15973 // A line between two menu items
15975 templateString
: dojo
.cache("dijit", "templates/MenuSeparator.html", "<tr class=\"dijitMenuSeparator\">\n\t<td class=\"dijitMenuSeparatorIconCell\">\n\t\t<div class=\"dijitMenuSeparatorTop\"></div>\n\t\t<div class=\"dijitMenuSeparatorBottom\"></div>\n\t</td>\n\t<td colspan=\"3\" class=\"dijitMenuSeparatorLabelCell\">\n\t\t<div class=\"dijitMenuSeparatorTop dijitMenuSeparatorLabel\"></div>\n\t\t<div class=\"dijitMenuSeparatorBottom\"></div>\n\t</td>\n</tr>\n"),
15977 postCreate: function(){
15978 dojo
.setSelectable(this.domNode
, false);
15981 isFocusable: function(){
15983 // Override to always return false
15987 return false; // Boolean
15994 if(!dojo
._hasResource
["dijit.Menu"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
15995 dojo
._hasResource
["dijit.Menu"] = true;
15996 dojo
.provide("dijit.Menu");
16004 dojo
.declare("dijit._MenuBase",
16005 [dijit
._Widget
, dijit
._Templated
, dijit
._KeyNavContainer
],
16008 // Base class for Menu and MenuBar
16010 // parentMenu: [readonly] Widget
16011 // pointer to menu that displayed me
16014 // popupDelay: Integer
16015 // number of milliseconds before hovering (without clicking) causes the popup to automatically open.
16018 startup: function(){
16019 if(this._started
){ return; }
16021 dojo
.forEach(this.getChildren(), function(child
){ child
.startup(); });
16022 this.startupKeyNavChildren();
16024 this.inherited(arguments
);
16027 onExecute: function(){
16029 // Attach point for notification about when a menu item has been executed.
16030 // This is an internal mechanism used for Menus to signal to their parent to
16031 // close them, because they are about to execute the onClick handler. In
16032 // general developers should not attach to or override this method.
16037 onCancel: function(/*Boolean*/ closeAll
){
16039 // Attach point for notification about when the user cancels the current menu
16040 // This is an internal mechanism used for Menus to signal to their parent to
16041 // close them. In general developers should not attach to or override this method.
16046 _moveToPopup: function(/*Event*/ evt
){
16048 // This handles the right arrow key (left arrow key on RTL systems),
16049 // which will either open a submenu, or move to the next item in the
16050 // ancestor MenuBar
16054 if(this.focusedChild
&& this.focusedChild
.popup
&& !this.focusedChild
.disabled
){
16055 this.focusedChild
._onClick(evt
);
16057 var topMenu
= this._getTopMenu();
16058 if(topMenu
&& topMenu
._isMenuBar
){
16059 topMenu
.focusNext();
16064 _onPopupHover: function(/*Event*/ evt
){
16066 // This handler is called when the mouse moves over the popup.
16070 // if the mouse hovers over a menu popup that is in pending-close state,
16071 // then stop the close operation.
16072 // This can't be done in onItemHover since some popup targets don't have MenuItems (e.g. ColorPicker)
16073 if(this.currentPopup
&& this.currentPopup
._pendingClose_timer
){
16074 var parentMenu
= this.currentPopup
.parentMenu
;
16075 // highlight the parent menu item pointing to this popup
16076 if(parentMenu
.focusedChild
){
16077 parentMenu
.focusedChild
._setSelected(false);
16079 parentMenu
.focusedChild
= this.currentPopup
.from_item
;
16080 parentMenu
.focusedChild
._setSelected(true);
16081 // cancel the pending close
16082 this._stopPendingCloseTimer(this.currentPopup
);
16086 onItemHover: function(/*MenuItem*/ item
){
16088 // Called when cursor is over a MenuItem.
16092 // Don't do anything unless user has "activated" the menu by:
16094 // 2) opening it from a parent menu (which automatically focuses it)
16096 this.focusChild(item
);
16097 if(this.focusedChild
.popup
&& !this.focusedChild
.disabled
&& !this.hover_timer
){
16098 this.hover_timer
= setTimeout(dojo
.hitch(this, "_openPopup"), this.popupDelay
);
16101 // if the user is mixing mouse and keyboard navigation,
16102 // then the menu may not be active but a menu item has focus,
16103 // but it's not the item that the mouse just hovered over.
16104 // To avoid both keyboard and mouse selections, use the latest.
16105 if(this.focusedChild
){
16106 this.focusChild(item
);
16108 this._hoveredChild
= item
;
16111 _onChildBlur: function(item
){
16113 // Called when a child MenuItem becomes inactive because focus
16114 // has been removed from the MenuItem *and* it's descendant menus.
16117 this._stopPopupTimer();
16118 item
._setSelected(false);
16119 // Close all popups that are open and descendants of this menu
16120 var itemPopup
= item
.popup
;
16122 this._stopPendingCloseTimer(itemPopup
);
16123 itemPopup
._pendingClose_timer
= setTimeout(function(){
16124 itemPopup
._pendingClose_timer
= null;
16125 if(itemPopup
.parentMenu
){
16126 itemPopup
.parentMenu
.currentPopup
= null;
16128 dijit
.popup
.close(itemPopup
); // this calls onClose
16129 }, this.popupDelay
);
16133 onItemUnhover: function(/*MenuItem*/ item
){
16135 // Callback fires when mouse exits a MenuItem
16140 this._stopPopupTimer();
16142 if(this._hoveredChild
== item
){ this._hoveredChild
= null; }
16145 _stopPopupTimer: function(){
16147 // Cancels the popup timer because the user has stop hovering
16148 // on the MenuItem, etc.
16151 if(this.hover_timer
){
16152 clearTimeout(this.hover_timer
);
16153 this.hover_timer
= null;
16157 _stopPendingCloseTimer: function(/*dijit._Widget*/ popup
){
16159 // Cancels the pending-close timer because the close has been preempted
16162 if(popup
._pendingClose_timer
){
16163 clearTimeout(popup
._pendingClose_timer
);
16164 popup
._pendingClose_timer
= null;
16168 _stopFocusTimer: function(){
16170 // Cancels the pending-focus timer because the menu was closed before focus occured
16173 if(this._focus_timer
){
16174 clearTimeout(this._focus_timer
);
16175 this._focus_timer
= null;
16179 _getTopMenu: function(){
16181 // Returns the top menu in this chain of Menus
16184 for(var top
=this; top
.parentMenu
; top
=top
.parentMenu
);
16188 onItemClick: function(/*dijit._Widget*/ item
, /*Event*/ evt
){
16190 // Handle clicks on an item.
16194 // this can't be done in _onFocus since the _onFocus events occurs asynchronously
16195 if(typeof this.isShowingNow
== 'undefined'){ // non-popup menu
16196 this._markActive();
16199 this.focusChild(item
);
16201 if(item
.disabled
){ return false; }
16206 // before calling user defined handler, close hierarchy of menus
16207 // and restore focus to place it was when menu was opened
16210 // user defined handler for click
16215 _openPopup: function(){
16217 // Open the popup to the side of/underneath the current menu item
16221 this._stopPopupTimer();
16222 var from_item
= this.focusedChild
;
16223 if(!from_item
){ return; } // the focused child lost focus since the timer was started
16224 var popup
= from_item
.popup
;
16225 if(popup
.isShowingNow
){ return; }
16226 if(this.currentPopup
){
16227 this._stopPendingCloseTimer(this.currentPopup
);
16228 dijit
.popup
.close(this.currentPopup
);
16230 popup
.parentMenu
= this;
16231 popup
.from_item
= from_item
; // helps finding the parent item that should be focused for this popup
16236 around
: from_item
.domNode
,
16237 orient
: this._orient
|| (this.isLeftToRight() ?
16238 {'TR': 'TL', 'TL': 'TR', 'BR': 'BL', 'BL': 'BR'} :
16239 {'TL': 'TR', 'TR': 'TL', 'BL': 'BR', 'BR': 'BL'}),
16240 onCancel: function(){ // called when the child menu is canceled
16241 // set isActive=false (_closeChild vs _cleanUp) so that subsequent hovering will NOT open child menus
16242 // which seems aligned with the UX of most applications (e.g. notepad, wordpad, paint shop pro)
16243 self
.focusChild(from_item
); // put focus back on my node
16244 self
._cleanUp(); // close the submenu (be sure this is done _after_ focus is moved)
16245 from_item
._setSelected(true); // oops, _cleanUp() deselected the item
16246 self
.focusedChild
= from_item
; // and unset focusedChild
16248 onExecute
: dojo
.hitch(this, "_cleanUp")
16251 this.currentPopup
= popup
;
16252 // detect mouseovers to handle lazy mouse movements that temporarily focus other menu items
16253 popup
.connect(popup
.domNode
, "onmouseenter", dojo
.hitch(self
, "_onPopupHover")); // cleaned up when the popped-up widget is destroyed on close
16256 // If user is opening the popup via keyboard (right arrow, or down arrow for MenuBar),
16257 // if the cursor happens to collide with the popup, it will generate an onmouseover event
16258 // even though the mouse wasn't moved. Use a setTimeout() to call popup.focus so that
16259 // our focus() call overrides the onmouseover event, rather than vice-versa. (#8742)
16260 popup
._focus_timer
= setTimeout(dojo
.hitch(popup
, function(){
16261 this._focus_timer
= null;
16267 _markActive: function(){
16269 // Mark this menu's state as active.
16270 // Called when this Menu gets focus from:
16271 // 1) clicking it (mouse or via space/arrow key)
16272 // 2) being opened by a parent menu.
16273 // This is not called just from mouse hover.
16274 // Focusing a menu via TAB does NOT automatically set isActive
16275 // since TAB is a navigation operation and not a selection one.
16276 // For Windows apps, pressing the ALT key focuses the menubar
16277 // menus (similar to TAB navigation) but the menu is not active
16278 // (ie no dropdown) until an item is clicked.
16279 this.isActive
= true;
16280 dojo
.addClass(this.domNode
, "dijitMenuActive");
16281 dojo
.removeClass(this.domNode
, "dijitMenuPassive");
16284 onOpen: function(/*Event*/ e
){
16286 // Callback when this menu is opened.
16287 // This is called by the popup manager as notification that the menu
16292 this.isShowingNow
= true;
16293 this._markActive();
16296 _markInactive: function(){
16298 // Mark this menu's state as inactive.
16299 this.isActive
= false; // don't do this in _onBlur since the state is pending-close until we get here
16300 dojo
.removeClass(this.domNode
, "dijitMenuActive");
16301 dojo
.addClass(this.domNode
, "dijitMenuPassive");
16304 onClose: function(){
16306 // Callback when this menu is closed.
16307 // This is called by the popup manager as notification that the menu
16312 this._stopFocusTimer();
16313 this._markInactive();
16314 this.isShowingNow
= false;
16315 this.parentMenu
= null;
16318 _closeChild: function(){
16320 // Called when submenu is clicked or focus is lost. Close hierarchy of menus.
16323 this._stopPopupTimer();
16324 if(this.focusedChild
){ // unhighlight the focused item
16325 this.focusedChild
._setSelected(false);
16326 this.focusedChild
._onUnhover();
16327 this.focusedChild
= null;
16329 if(this.currentPopup
){
16330 // Close all popups that are open and descendants of this menu
16331 dijit
.popup
.close(this.currentPopup
);
16332 this.currentPopup
= null;
16336 _onItemFocus: function(/*MenuItem*/ item
){
16338 // Called when child of this Menu gets focus from:
16340 // 2) tabbing into it
16341 // 3) being opened by a parent menu.
16342 // This is not called just from mouse hover.
16343 if(this._hoveredChild
&& this._hoveredChild
!= item
){
16344 this._hoveredChild
._onUnhover(); // any previous mouse movement is trumped by focus selection
16348 _onBlur: function(){
16350 // Called when focus is moved away from this Menu and it's submenus.
16354 this.inherited(arguments
);
16357 _cleanUp: function(){
16359 // Called when the user is done with this menu. Closes hierarchy of menus.
16363 this._closeChild(); // don't call this.onClose since that's incorrect for MenuBar's that never close
16364 if(typeof this.isShowingNow
== 'undefined'){ // non-popup menu doesn't call onClose
16365 this._markInactive();
16370 dojo
.declare("dijit.Menu",
16374 // A context menu you can assign to multiple elements
16376 // TODO: most of the code in here is just for context menu (right-click menu)
16377 // support. In retrospect that should have been a separate class (dijit.ContextMenu).
16378 // Split them for 2.0
16380 constructor: function(){
16381 this._bindings
= [];
16384 templateString
: dojo
.cache("dijit", "templates/Menu.html", "<table class=\"dijit dijitMenu dijitMenuPassive dijitReset dijitMenuTable\" waiRole=\"menu\" tabIndex=\"${tabIndex}\" dojoAttachEvent=\"onkeypress:_onKeyPress\" cellspacing=0>\n\t<tbody class=\"dijitReset\" dojoAttachPoint=\"containerNode\"></tbody>\n</table>\n"),
16386 baseClass
: "dijitMenu",
16388 // targetNodeIds: [const] String[]
16389 // Array of dom node ids of nodes to attach to.
16390 // Fill this with nodeIds upon widget creation and it becomes context menu for those nodes.
16393 // contextMenuForWindow: [const] Boolean
16394 // If true, right clicking anywhere on the window will cause this context menu to open.
16395 // If false, must specify targetNodeIds.
16396 contextMenuForWindow
: false,
16398 // leftClickToOpen: [const] Boolean
16399 // If true, menu will open on left click instead of right click, similiar to a file menu.
16400 leftClickToOpen
: false,
16402 // refocus: Boolean
16403 // When this menu closes, re-focus the element which had focus before it was opened.
16406 postCreate: function(){
16407 if(this.contextMenuForWindow
){
16408 this.bindDomNode(dojo
.body());
16410 // TODO: should have _setTargetNodeIds() method to handle initialization and a possible
16411 // later attr('targetNodeIds', ...) call. There's also a problem that targetNodeIds[]
16412 // gets stale after calls to bindDomNode()/unBindDomNode() as it still is just the original list (see #9610)
16413 dojo
.forEach(this.targetNodeIds
, this.bindDomNode
, this);
16415 var k
= dojo
.keys
, l
= this.isLeftToRight();
16416 this._openSubMenuKey
= l
? k
.RIGHT_ARROW
: k
.LEFT_ARROW
;
16417 this._closeSubMenuKey
= l
? k
.LEFT_ARROW
: k
.RIGHT_ARROW
;
16418 this.connectKeyNavHandlers([k
.UP_ARROW
], [k
.DOWN_ARROW
]);
16421 _onKeyPress: function(/*Event*/ evt
){
16423 // Handle keyboard based menu navigation.
16427 if(evt
.ctrlKey
|| evt
.altKey
){ return; }
16429 switch(evt
.charOrCode
){
16430 case this._openSubMenuKey
:
16431 this._moveToPopup(evt
);
16432 dojo
.stopEvent(evt
);
16434 case this._closeSubMenuKey
:
16435 if(this.parentMenu
){
16436 if(this.parentMenu
._isMenuBar
){
16437 this.parentMenu
.focusPrev();
16439 this.onCancel(false);
16442 dojo
.stopEvent(evt
);
16448 // thanks burstlib!
16449 _iframeContentWindow: function(/* HTMLIFrameElement */iframe_el
){
16451 // Returns the window reference of the passed iframe
16454 var win
= dojo
.window
.get(this._iframeContentDocument(iframe_el
)) ||
16455 // Moz. TODO: is this available when defaultView isn't?
16456 this._iframeContentDocument(iframe_el
)['__parent__'] ||
16457 (iframe_el
.name
&& dojo
.doc
.frames
[iframe_el
.name
]) || null;
16458 return win
; // Window
16461 _iframeContentDocument: function(/* HTMLIFrameElement */iframe_el
){
16463 // Returns a reference to the document object inside iframe_el
16466 var doc
= iframe_el
.contentDocument
// W3
16467 || (iframe_el
.contentWindow
&& iframe_el
.contentWindow
.document
) // IE
16468 || (iframe_el
.name
&& dojo
.doc
.frames
[iframe_el
.name
] && dojo
.doc
.frames
[iframe_el
.name
].document
)
16470 return doc
; // HTMLDocument
16473 bindDomNode: function(/*String|DomNode*/ node
){
16475 // Attach menu to given node
16476 node
= dojo
.byId(node
);
16478 var cn
; // Connect node
16480 // Support context menus on iframes. Rather than binding to the iframe itself we need
16481 // to bind to the <body> node inside the iframe.
16482 if(node
.tagName
.toLowerCase() == "iframe"){
16484 win
= this._iframeContentWindow(iframe
);
16485 cn
= dojo
.withGlobal(win
, dojo
.body
);
16488 // To capture these events at the top level, attach to <html>, not <body>.
16489 // Otherwise right-click context menu just doesn't work.
16490 cn
= (node
== dojo
.body() ? dojo
.doc
.documentElement
: node
);
16494 // "binding" is the object to track our connection to the node (ie, the parameter to bindDomNode())
16500 // Save info about binding in _bindings[], and make node itself record index(+1) into
16501 // _bindings[] array. Prefix w/_dijitMenu to avoid setting an attribute that may
16502 // start with a number, which fails on FF/safari.
16503 dojo
.attr(node
, "_dijitMenu" + this.id
, this._bindings
.push(binding
));
16505 // Setup the connections to monitor click etc., unless we are connecting to an iframe which hasn't finished
16506 // loading yet, in which case we need to wait for the onload event first, and then connect
16507 // On linux Shift-F10 produces the oncontextmenu event, but on Windows it doesn't, so
16508 // we need to monitor keyboard events in addition to the oncontextmenu event.
16509 var doConnects
= dojo
.hitch(this, function(cn
){
16511 // TODO: when leftClickToOpen is true then shouldn't space/enter key trigger the menu,
16512 // rather than shift-F10?
16513 dojo
.connect(cn
, this.leftClickToOpen
? "onclick" : "oncontextmenu", this, function(evt
){
16514 // Schedule context menu to be opened unless it's already been scheduled from onkeydown handler
16515 dojo
.stopEvent(evt
);
16516 this._scheduleOpen(evt
.target
, iframe
, {x
: evt
.pageX
, y
: evt
.pageY
});
16518 dojo
.connect(cn
, "onkeydown", this, function(evt
){
16519 if(evt
.shiftKey
&& evt
.keyCode
== dojo
.keys
.F10
){
16520 dojo
.stopEvent(evt
);
16521 this._scheduleOpen(evt
.target
, iframe
); // no coords - open near target node
16526 binding
.connects
= cn
? doConnects(cn
) : [];
16529 // Setup handler to [re]bind to the iframe when the contents are initially loaded,
16530 // and every time the contents change.
16531 // Need to do this b/c we are actually binding to the iframe's <body> node.
16532 // Note: can't use dojo.connect(), see #9609.
16534 binding
.onloadHandler
= dojo
.hitch(this, function(){
16535 // want to remove old connections, but IE throws exceptions when trying to
16536 // access the <body> node because it's already gone, or at least in a state of limbo
16538 var win
= this._iframeContentWindow(iframe
);
16539 cn
= dojo
.withGlobal(win
, dojo
.body
);
16540 binding
.connects
= doConnects(cn
);
16542 if(iframe
.addEventListener
){
16543 iframe
.addEventListener("load", binding
.onloadHandler
, false);
16545 iframe
.attachEvent("onload", binding
.onloadHandler
);
16550 unBindDomNode: function(/*String|DomNode*/ nodeName
){
16552 // Detach menu from given node
16556 node
= dojo
.byId(nodeName
);
16558 // On IE the dojo.byId() call will get an exception if the attach point was
16559 // the <body> node of an <iframe> that has since been reloaded (and thus the
16560 // <body> node is in a limbo state of destruction.
16564 // node["_dijitMenu" + this.id] contains index(+1) into my _bindings[] array
16565 var attrName
= "_dijitMenu" + this.id
;
16566 if(node
&& dojo
.hasAttr(node
, attrName
)){
16567 var bid
= dojo
.attr(node
, attrName
)-1, b
= this._bindings
[bid
];
16568 dojo
.forEach(b
.connects
, dojo
.disconnect
);
16570 // Remove listener for iframe onload events
16571 var iframe
= b
.iframe
;
16573 if(iframe
.removeEventListener
){
16574 iframe
.removeEventListener("load", b
.onloadHandler
, false);
16576 iframe
.detachEvent("onload", b
.onloadHandler
);
16580 dojo
.removeAttr(node
, attrName
);
16581 delete this._bindings
[bid
];
16585 _scheduleOpen: function(/*DomNode?*/ target
, /*DomNode?*/ iframe
, /*Object?*/ coords
){
16587 // Set timer to display myself. Using a timer rather than displaying immediately solves
16590 // 1. IE: without the delay, focus work in "open" causes the system
16591 // context menu to appear in spite of stopEvent.
16593 // 2. Avoid double-shows on linux, where shift-F10 generates an oncontextmenu event
16594 // even after a dojo.stopEvent(e). (Shift-F10 on windows doesn't generate the
16595 // oncontextmenu event.)
16597 if(!this._openTimer
){
16598 this._openTimer
= setTimeout(dojo
.hitch(this, function(){
16599 delete this._openTimer
;
16609 _openMyself: function(args
){
16611 // Internal function for opening myself when the user does a right-click or something similar.
16613 // This is an Object containing:
16615 // The node that is being clicked
16617 // If an <iframe> is being clicked, iframe points to that iframe
16619 // Put menu at specified x/y position in viewport, or if iframe is
16620 // specified, then relative to iframe.
16622 // _openMyself() formerly took the event object, and since various code references
16623 // evt.target (after connecting to _openMyself()), using an Object for parameters
16624 // (so that old code still works).
16626 var target
= args
.target
,
16627 iframe
= args
.iframe
,
16628 coords
= args
.coords
;
16630 // Get coordinates to open menu, either at specified (mouse) position or (if triggered via keyboard)
16631 // then near the node the menu is assigned to.
16634 // Specified coordinates are on <body> node of an <iframe>, convert to match main document
16635 var od
= target
.ownerDocument
,
16636 ifc
= dojo
.position(iframe
, true),
16637 win
= this._iframeContentWindow(iframe
),
16638 scroll
= dojo
.withGlobal(win
, "_docScroll", dojo
);
16640 var cs
= dojo
.getComputedStyle(iframe
),
16641 tp
= dojo
._toPixelValue
,
16642 left
= (dojo
.isIE
&& dojo
.isQuirks
? 0 : tp(iframe
, cs
.paddingLeft
)) + (dojo
.isIE
&& dojo
.isQuirks
? tp(iframe
, cs
.borderLeftWidth
) : 0),
16643 top
= (dojo
.isIE
&& dojo
.isQuirks
? 0 : tp(iframe
, cs
.paddingTop
)) + (dojo
.isIE
&& dojo
.isQuirks
? tp(iframe
, cs
.borderTopWidth
) : 0);
16645 coords
.x
+= ifc
.x
+ left
- scroll
.x
;
16646 coords
.y
+= ifc
.y
+ top
- scroll
.y
;
16649 coords
= dojo
.position(target
, true);
16655 var savedFocus
= dijit
.getFocus(this);
16656 function closeAndRestoreFocus(){
16657 // user has clicked on a menu or popup
16659 dijit
.focus(savedFocus
);
16661 dijit
.popup
.close(self
);
16667 onExecute
: closeAndRestoreFocus
,
16668 onCancel
: closeAndRestoreFocus
,
16669 orient
: this.isLeftToRight() ? 'L' : 'R'
16673 this._onBlur = function(){
16674 this.inherited('_onBlur', arguments
);
16675 // Usually the parent closes the child widget but if this is a context
16676 // menu then there is no parent
16677 dijit
.popup
.close(this);
16678 // don't try to restore focus; user has clicked another part of the screen
16679 // and set focus there
16683 uninitialize: function(){
16684 dojo
.forEach(this._bindings
, function(b
){ if(b
){ this.unBindDomNode(b
.node
); } }, this);
16685 this.inherited(arguments
);
16690 // Back-compat (TODO: remove in 2.0)
16699 if(!dojo
._hasResource
["dijit.form.Select"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
16700 dojo
._hasResource
["dijit.form.Select"] = true;
16701 dojo
.provide("dijit.form.Select");
16710 dojo
.declare("dijit.form._SelectMenu", dijit
.Menu
, {
16712 // An internally-used menu for dropdown that allows us a vertical scrollbar
16713 buildRendering: function(){
16715 // Stub in our own changes, so that our domNode is not a table
16716 // otherwise, we won't respond correctly to heights/overflows
16717 this.inherited(arguments
);
16718 var o
= (this.menuTableNode
= this.domNode
);
16719 var n
= (this.domNode
= dojo
.create("div", {style
: {overflowX
: "hidden", overflowY
: "scroll"}}));
16721 o
.parentNode
.replaceChild(n
, o
);
16723 dojo
.removeClass(o
, "dijitMenuTable");
16724 n
.className
= o
.className
+ " dijitSelectMenu";
16725 o
.className
= "dijitReset dijitMenuTable";
16726 dijit
.setWaiRole(o
,"listbox");
16727 dijit
.setWaiRole(n
,"presentation");
16730 resize: function(/*Object*/ mb
){
16732 // Overridden so that we are able to handle resizing our
16733 // internal widget. Note that this is not a "full" resize
16734 // implementation - it only works correctly if you pass it a
16738 // The margin box to set this dropdown to.
16740 dojo
.marginBox(this.domNode
, mb
);
16742 // We've explicitly set the wrapper <div>'s width, so set <table> width to match.
16743 // 100% is safer than a pixel value because there may be a scroll bar with
16744 // browser/OS specific width.
16745 this.menuTableNode
.style
.width
= "100%";
16751 dojo
.declare("dijit.form.Select", [dijit
.form
._FormSelectWidget
, dijit
._HasDropDown
], {
16753 // This is a "styleable" select box - it is basically a DropDownButton which
16754 // can take a <select> as its input.
16756 baseClass
: "dijitSelect",
16758 templateString
: dojo
.cache("dijit.form", "templates/Select.html", "<table class=\"dijit dijitReset dijitInline dijitLeft\"\n\tdojoAttachPoint=\"_buttonNode,tableNode,focusNode\" cellspacing='0' cellpadding='0'\n\twaiRole=\"combobox\" waiState=\"haspopup-true\"\n\t><tbody waiRole=\"presentation\"><tr waiRole=\"presentation\"\n\t\t><td class=\"dijitReset dijitStretch dijitButtonContents dijitButtonNode\" waiRole=\"presentation\"\n\t\t\t><span class=\"dijitReset dijitInline dijitButtonText\" dojoAttachPoint=\"containerNode,_popupStateNode\"></span\n\t\t\t><input type=\"hidden\" ${!nameAttrSetting} dojoAttachPoint=\"valueNode\" value=\"${value}\" waiState=\"hidden-true\"\n\t\t/></td><td class=\"dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton\"\n\t\t\t\tdojoAttachPoint=\"titleNode\" waiRole=\"presentation\"\n\t\t\t><div class=\"dijitReset dijitArrowButtonInner\" waiRole=\"presentation\"></div\n\t\t\t><div class=\"dijitReset dijitArrowButtonChar\" waiRole=\"presentation\">▼</div\n\t\t></td\n\t></tr></tbody\n></table>\n"),
16760 // attributeMap: Object
16761 // Add in our style to be applied to the focus node
16762 attributeMap
: dojo
.mixin(dojo
.clone(dijit
.form
._FormSelectWidget
.prototype.attributeMap
),{style
:"tableNode"}),
16764 // required: Boolean
16765 // Can be true or false, default is false.
16769 // Shows current state (ie, validation result) of input (Normal, Warning, or Error)
16772 // tooltipPosition: String[]
16773 // See description of dijit.Tooltip.defaultPosition for details on this parameter.
16774 tooltipPosition
: [],
16776 // emptyLabel: string
16777 // What to display in an "empty" dropdown
16780 // _isLoaded: Boolean
16781 // Whether or not we have been loaded
16784 // _childrenLoaded: Boolean
16785 // Whether or not our children have been loaded
16786 _childrenLoaded
: false,
16788 _fillContent: function(){
16790 // Set the value to be the first, or the selected index
16791 this.inherited(arguments
);
16792 if(this.options
.length
&& !this.value
&& this.srcNodeRef
){
16793 var si
= this.srcNodeRef
.selectedIndex
;
16794 this.value
= this.options
[si
!= -1 ? si
: 0].value
;
16797 // Create the dropDown widget
16798 this.dropDown
= new dijit
.form
._SelectMenu({id
: this.id
+ "_menu"});
16799 dojo
.addClass(this.dropDown
.domNode
, this.baseClass
+ "Menu");
16802 _getMenuItemForOption: function(/*dijit.form.__SelectOption*/ option
){
16804 // For the given option, return the menu item that should be
16805 // used to display it. This can be overridden as needed
16807 // We are a separator (no label set for it)
16808 return new dijit
.MenuSeparator();
16810 // Just a regular menu option
16811 var click
= dojo
.hitch(this, "_setValueAttr", option
);
16812 var item
= new dijit
.MenuItem({
16814 label
: option
.label
,
16816 disabled
: option
.disabled
|| false
16818 dijit
.setWaiRole(item
.focusNode
, "listitem");
16823 _addOptionItem: function(/*dijit.form.__SelectOption*/ option
){
16825 // For the given option, add an option to our dropdown.
16826 // If the option doesn't have a value, then a separator is added
16829 this.dropDown
.addChild(this._getMenuItemForOption(option
));
16833 _getChildren: function(){
16834 if(!this.dropDown
){
16837 return this.dropDown
.getChildren();
16840 _loadChildren: function(/*Boolean*/ loadMenuItems
){
16842 // Resets the menu and the length attribute of the button - and
16843 // ensures that the label is appropriately set.
16844 // loadMenuItems: Boolean
16845 // actually loads the child menu items - we only do this when we are
16846 // populating for showing the dropdown.
16848 if(loadMenuItems
=== true){
16849 // this.inherited destroys this.dropDown's child widgets (MenuItems).
16850 // Avoid this.dropDown (Menu widget) having a pointer to a destroyed widget (which will cause
16851 // issues later in _setSelected). (see #10296)
16853 delete this.dropDown
.focusedChild
;
16855 if(this.options
.length
){
16856 this.inherited(arguments
);
16858 // Drop down menu is blank but add one blank entry just so something appears on the screen
16859 // to let users know that they are no choices (mimicing native select behavior)
16860 dojo
.forEach(this._getChildren(), function(child
){ child
.destroyRecursive(); });
16861 var item
= new dijit
.MenuItem({label
: " "});
16862 this.dropDown
.addChild(item
);
16865 this._updateSelection();
16868 var len
= this.options
.length
;
16869 this._isLoaded
= false;
16870 this._childrenLoaded
= true;
16872 if(!this._loadingStore
){
16873 // Don't call this if we are loading - since we will handle it later
16874 this._setValueAttr(this.value
);
16878 _setValueAttr: function(value
){
16879 this.inherited(arguments
);
16880 dojo
.attr(this.valueNode
, "value", this.get("value"));
16883 _setDisplay: function(/*String*/ newDisplay
){
16885 // sets the display for the given value (or values)
16886 this.containerNode
.innerHTML
= '<span class="dijitReset dijitInline ' + this.baseClass
+ 'Label">' +
16887 (newDisplay
|| this.emptyLabel
|| " ") +
16889 dijit
.setWaiState(this.focusNode
, "valuetext", (newDisplay
|| this.emptyLabel
|| " ") );
16892 validate: function(/*Boolean*/ isFocused
){
16894 // Called by oninit, onblur, and onkeypress.
16896 // Show missing or invalid messages if appropriate, and highlight textbox field.
16897 // Used when a select is initially set to no value and the user is required to
16900 var isValid
= this.isValid(isFocused
);
16901 this.state
= isValid
? "" : "Error";
16902 this._setStateClass();
16903 dijit
.setWaiState(this.focusNode
, "invalid", isValid
? "false" : "true");
16904 var message
= isValid
? "" : this._missingMsg
;
16905 if(this._message
!== message
){
16906 this._message
= message
;
16907 dijit
.hideTooltip(this.domNode
);
16909 dijit
.showTooltip(message
, this.domNode
, this.tooltipPosition
, !this.isLeftToRight());
16915 isValid: function(/*Boolean*/ isFocused
){
16917 // Whether or not this is a valid value. The only way a Select
16918 // can be invalid is when it's required but nothing is selected.
16919 return (!this.required
|| !(/^\s*$/.test(this.value
)));
16924 // Overridden so that the state will be cleared.
16925 this.inherited(arguments
);
16926 dijit
.hideTooltip(this.domNode
);
16928 this._setStateClass();
16929 delete this._message
;
16932 postMixInProperties: function(){
16934 // set the missing message
16935 this.inherited(arguments
);
16936 this._missingMsg
= dojo
.i18n
.getLocalization("dijit.form", "validate",
16937 this.lang
).missingMessage
;
16940 postCreate: function(){
16941 this.inherited(arguments
);
16942 if(this.tableNode
.style
.width
){
16943 dojo
.addClass(this.domNode
, this.baseClass
+ "FixedWidth");
16947 isLoaded: function(){
16948 return this._isLoaded
;
16951 loadDropDown: function(/*Function*/ loadCallback
){
16953 // populates the menu
16954 this._loadChildren(true);
16955 this._isLoaded
= true;
16959 closeDropDown: function(){
16960 // overriding _HasDropDown.closeDropDown()
16961 this.inherited(arguments
);
16963 if(this.dropDown
&& this.dropDown
.menuTableNode
){
16964 // Erase possible width: 100% setting from _SelectMenu.resize().
16965 // Leaving it would interfere with the next openDropDown() call, which
16966 // queries the natural size of the drop down.
16967 this.dropDown
.menuTableNode
.style
.width
= "";
16971 uninitialize: function(preserveDom
){
16972 if(this.dropDown
&& !this.dropDown
._destroyed
){
16973 this.dropDown
.destroyRecursive(preserveDom
);
16974 delete this.dropDown
;
16976 this.inherited(arguments
);
16982 if(!dojo
._hasResource
["dijit.form.SimpleTextarea"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
16983 dojo
._hasResource
["dijit.form.SimpleTextarea"] = true;
16984 dojo
.provide("dijit.form.SimpleTextarea");
16988 dojo
.declare("dijit.form.SimpleTextarea",
16989 dijit
.form
.TextBox
,
16992 // A simple textarea that degrades, and responds to
16993 // minimal LayoutContainer usage, and works with dijit.form.Form.
16994 // Doesn't automatically size according to input, like Textarea.
16997 // | <textarea dojoType="dijit.form.SimpleTextarea" name="foo" value="bar" rows=30 cols=40></textarea>
17000 // | new dijit.form.SimpleTextarea({ rows:20, cols:30 }, "foo");
17002 baseClass
: "dijitTextBox dijitTextArea",
17004 attributeMap
: dojo
.delegate(dijit
.form
._FormValueWidget
.prototype.attributeMap
, {
17005 rows
:"textbox", cols
: "textbox"
17009 // The number of rows of text.
17013 // The number of characters per line.
17016 templateString
: "<textarea ${!nameAttrSetting} dojoAttachPoint='focusNode,containerNode,textbox' autocomplete='off'></textarea>",
17018 postMixInProperties: function(){
17019 // Copy value from srcNodeRef, unless user specified a value explicitly (or there is no srcNodeRef)
17020 if(!this.value
&& this.srcNodeRef
){
17021 this.value
= this.srcNodeRef
.value
;
17023 this.inherited(arguments
);
17026 filter: function(/*String*/ value
){
17027 // Override TextBox.filter to deal with newlines... specifically (IIRC) this is for IE which writes newlines
17028 // as \r\n instead of just \n
17030 value
= value
.replace(/\r/g,"");
17032 return this.inherited(arguments
);
17035 postCreate: function(){
17036 this.inherited(arguments
);
17037 if(dojo
.isIE
&& this.cols
){ // attribute selectors is not supported in IE6
17038 dojo
.addClass(this.textbox
, "dijitTextAreaCols");
17042 _previousValue
: "",
17043 _onInput: function(/*Event?*/ e
){
17044 // Override TextBox._onInput() to enforce maxLength restriction
17045 if(this.maxLength
){
17046 var maxLength
= parseInt(this.maxLength
);
17047 var value
= this.textbox
.value
.replace(/\r/g,'');
17048 var overflow
= value
.length
- maxLength
;
17050 if(e
){ dojo
.stopEvent(e
); }
17051 var textarea
= this.textbox
;
17052 if(textarea
.selectionStart
){
17053 var pos
= textarea
.selectionStart
;
17056 cr
= (this.textbox
.value
.substring(0,pos
).match(/\r/g) || []).length
;
17058 this.textbox
.value
= value
.substring(0,pos
-overflow
-cr
)+value
.substring(pos
-cr
);
17059 textarea
.setSelectionRange(pos
-overflow
, pos
-overflow
);
17060 }else if(dojo
.doc
.selection
){ //IE
17062 var range
= dojo
.doc
.selection
.createRange();
17063 // delete overflow characters
17064 range
.moveStart("character", -overflow
);
17070 this._previousValue
= this.textbox
.value
;
17072 this.inherited(arguments
);
17078 if(!dojo
._hasResource
["dijit.InlineEditBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
17079 dojo
._hasResource
["dijit.InlineEditBox"] = true;
17080 dojo
.provide("dijit.InlineEditBox");
17091 dojo
.declare("dijit.InlineEditBox",
17095 // An element with in-line edit capabilites
17098 // Behavior for an existing node (`<p>`, `<div>`, `<span>`, etc.) so that
17099 // when you click it, an editor shows up in place of the original
17100 // text. Optionally, Save and Cancel button are displayed below the edit widget.
17101 // When Save is clicked, the text is pulled from the edit
17102 // widget and redisplayed and the edit widget is again hidden.
17103 // By default a plain Textarea widget is used as the editor (or for
17104 // inline values a TextBox), but you can specify an editor such as
17105 // dijit.Editor (for editing HTML) or a Slider (for adjusting a number).
17106 // An edit widget must support the following API to be used:
17107 // - displayedValue or value as initialization parameter,
17108 // and available through set('displayedValue') / set('value')
17110 // - DOM-node focusNode = node containing editable text
17112 // editing: [readonly] Boolean
17113 // Is the node currently in edit mode?
17116 // autoSave: Boolean
17117 // Changing the value automatically saves it; don't have to push save button
17118 // (and save button isn't even displayed)
17121 // buttonSave: String
17122 // Save button label
17125 // buttonCancel: String
17126 // Cancel button label
17129 // renderAsHtml: Boolean
17130 // Set this to true if the specified Editor's value should be interpreted as HTML
17131 // rather than plain text (ex: `dijit.Editor`)
17132 renderAsHtml
: false,
17135 // Class name for Editor widget
17136 editor
: "dijit.form.TextBox",
17138 // editorWrapper: String
17139 // Class name for widget that wraps the editor widget, displaying save/cancel
17141 editorWrapper
: "dijit._InlineEditor",
17143 // editorParams: Object
17144 // Set of parameters for editor, like {required: true}
17147 onChange: function(value
){
17149 // Set this handler to be notified of changes to value.
17154 onCancel: function(){
17156 // Set this handler to be notified when editing is cancelled.
17162 // Width of editor. By default it's width=100% (ie, block mode).
17166 // The display value of the widget in read-only mode
17169 // noValueIndicator: [const] String
17170 // The text that gets displayed when there is no value (so that the user has a place to click to edit)
17171 noValueIndicator
: dojo
.isIE
<= 6 ? // font-family needed on IE6 but it messes up IE8
17172 "<span style='font-family: wingdings; text-decoration: underline;'> ✍ </span>" :
17173 "<span style='text-decoration: underline;'> ✍ </span>",
17175 constructor: function(){
17177 // Sets up private arrays etc.
17180 this.editorParams
= {};
17183 postMixInProperties: function(){
17184 this.inherited(arguments
);
17186 // save pointer to original source node, since Widget nulls-out srcNodeRef
17187 this.displayNode
= this.srcNodeRef
;
17189 // connect handlers to the display node
17191 ondijitclick
: "_onClick",
17192 onmouseover
: "_onMouseOver",
17193 onmouseout
: "_onMouseOut",
17194 onfocus
: "_onMouseOver",
17195 onblur
: "_onMouseOut"
17197 for(var name
in events
){
17198 this.connect(this.displayNode
, name
, events
[name
]);
17200 dijit
.setWaiRole(this.displayNode
, "button");
17201 if(!this.displayNode
.getAttribute("tabIndex")){
17202 this.displayNode
.setAttribute("tabIndex", 0);
17205 if(!this.value
&& !("value" in this.params
)){ // "" is a good value if specified directly so check params){
17206 this.value
= dojo
.trim(this.renderAsHtml
? this.displayNode
.innerHTML
:
17207 (this.displayNode
.innerText
||this.displayNode
.textContent
||""));
17210 this.displayNode
.innerHTML
= this.noValueIndicator
;
17213 dojo
.addClass(this.displayNode
, 'dijitInlineEditBoxDisplayMode');
17216 setDisabled: function(/*Boolean*/ disabled
){
17218 // Deprecated. Use set('disabled', ...) instead.
17221 dojo
.deprecated("dijit.InlineEditBox.setDisabled() is deprecated. Use set('disabled', bool) instead.", "", "2.0");
17222 this.set('disabled', disabled
);
17225 _setDisabledAttr: function(/*Boolean*/ disabled
){
17227 // Hook to make set("disabled", ...) work.
17228 // Set disabled state of widget.
17229 this.disabled
= disabled
;
17230 dijit
.setWaiState(this.domNode
, "disabled", disabled
);
17232 this.displayNode
.removeAttribute("tabIndex");
17234 this.displayNode
.setAttribute("tabIndex", 0);
17236 dojo
.toggleClass(this.displayNode
, "dijitInlineEditBoxDisplayModeDisabled", disabled
);
17239 _onMouseOver: function(){
17241 // Handler for onmouseover and onfocus event.
17244 if(!this.disabled
){
17245 dojo
.addClass(this.displayNode
, "dijitInlineEditBoxDisplayModeHover");
17249 _onMouseOut: function(){
17251 // Handler for onmouseout and onblur event.
17254 dojo
.removeClass(this.displayNode
, "dijitInlineEditBoxDisplayModeHover");
17257 _onClick: function(/*Event*/ e
){
17259 // Handler for onclick event.
17262 if(this.disabled
){ return; }
17263 if(e
){ dojo
.stopEvent(e
); }
17264 this._onMouseOut();
17266 // Since FF gets upset if you move a node while in an event handler for that node...
17267 setTimeout(dojo
.hitch(this, "edit"), 0);
17272 // Display the editor widget in place of the original (read only) markup.
17276 if(this.disabled
|| this.editing
){ return; }
17277 this.editing
= true;
17279 // save some display node values that can be restored later
17280 this._savedPosition
= dojo
.style(this.displayNode
, "position") || "static";
17281 this._savedOpacity
= dojo
.style(this.displayNode
, "opacity") || "1";
17282 this._savedTabIndex
= dojo
.attr(this.displayNode
, "tabIndex") || "0";
17284 if(this.wrapperWidget
){
17285 var ew
= this.wrapperWidget
.editWidget
;
17286 ew
.set("displayedValue" in ew
? "displayedValue" : "value", this.value
);
17288 // Placeholder for edit widget
17289 // Put place holder (and eventually editWidget) before the display node so that it's positioned correctly
17290 // when Calendar dropdown appears, which happens automatically on focus.
17291 var placeholder
= dojo
.create("span", null, this.domNode
, "before");
17293 // Create the editor wrapper (the thing that holds the editor widget and the save/cancel buttons)
17294 var ewc
= dojo
.getObject(this.editorWrapper
);
17295 this.wrapperWidget
= new ewc({
17297 buttonSave
: this.buttonSave
,
17298 buttonCancel
: this.buttonCancel
,
17301 tabIndex
: this._savedTabIndex
,
17302 editor
: this.editor
,
17303 inlineEditBox
: this,
17304 sourceStyle
: dojo
.getComputedStyle(this.displayNode
),
17305 save
: dojo
.hitch(this, "save"),
17306 cancel
: dojo
.hitch(this, "cancel")
17309 var ww
= this.wrapperWidget
;
17312 dijit
.focus(dijit
.getFocus()); // IE (at least 8) needs help with tab order changes
17314 // to avoid screen jitter, we first create the editor with position:absolute, visibility:hidden,
17315 // and then when it's finished rendering, we switch from display mode to editor
17316 // position:absolute releases screen space allocated to the display node
17317 // opacity:0 is the same as visibility:hidden but is still focusable
17318 // visiblity:hidden removes focus outline
17320 dojo
.style(this.displayNode
, { position
: "absolute", opacity
: "0", display
: "none" }); // makes display node invisible, display style used for focus-ability
17321 dojo
.style(ww
.domNode
, { position
: this._savedPosition
, visibility
: "visible", opacity
: "1" });
17322 dojo
.attr(this.displayNode
, "tabIndex", "-1"); // needed by WebKit for TAB from editor to skip displayNode
17324 // Replace the display widget with edit widget, leaving them both displayed for a brief time so that
17325 // focus can be shifted without incident. (browser may needs some time to render the editor.)
17326 setTimeout(dojo
.hitch(this, function(){
17327 ww
.focus(); // both nodes are showing, so we can switch focus safely
17328 ww
._resetValue
= ww
.getValue();
17332 _onBlur: function(){
17334 // Called when focus moves outside the InlineEditBox.
17335 // Performs garbage collection.
17339 this.inherited(arguments
);
17341 /* causes IE focus problems, see TooltipDialog_a11y.html...
17342 setTimeout(dojo.hitch(this, function(){
17343 if(this.wrapperWidget){
17344 this.wrapperWidget.destroy();
17345 delete this.wrapperWidget;
17352 destroy: function(){
17353 if(this.wrapperWidget
){
17354 this.wrapperWidget
.destroy();
17355 delete this.wrapperWidget
;
17357 this.inherited(arguments
);
17360 _showText: function(/*Boolean*/ focus
){
17362 // Revert to display mode, and optionally focus on display node
17366 var ww
= this.wrapperWidget
;
17367 dojo
.style(ww
.domNode
, { position
: "absolute", visibility
: "hidden", opacity
: "0" }); // hide the editor from mouse/keyboard events
17368 dojo
.style(this.displayNode
, { position
: this._savedPosition
, opacity
: this._savedOpacity
, display
: "" }); // make the original text visible
17369 dojo
.attr(this.displayNode
, "tabIndex", this._savedTabIndex
);
17371 dijit
.focus(this.displayNode
);
17375 save: function(/*Boolean*/ focus
){
17377 // Save the contents of the editor and revert to display mode.
17379 // Focus on the display mode text
17383 if(this.disabled
|| !this.editing
){ return; }
17384 this.editing
= false;
17386 var ww
= this.wrapperWidget
;
17387 var value
= ww
.getValue();
17388 this.set('value', value
); // display changed, formatted value
17390 // tell the world that we have changed
17391 setTimeout(dojo
.hitch(this, "onChange", value
), 0); // setTimeout prevents browser freeze for long-running event handlers
17393 this._showText(focus
); // set focus as needed
17396 setValue: function(/*String*/ val
){
17398 // Deprecated. Use set('value', ...) instead.
17401 dojo
.deprecated("dijit.InlineEditBox.setValue() is deprecated. Use set('value', ...) instead.", "", "2.0");
17402 return this.set("value", val
);
17405 _setValueAttr: function(/*String*/ val
){
17407 // Hook to make set("value", ...) work.
17408 // Inserts specified HTML value into this node, or an "input needed" character if node is blank.
17410 this.value
= val
= dojo
.trim(val
);
17411 if(!this.renderAsHtml
){
17412 val
= val
.replace(/&/gm, "&").replace(/</gm, "<").replace(/>/gm, ">").replace(/"/gm, ""
;").replace(/\n/g, "<br
>");
17414 this.displayNode.innerHTML = val || this.noValueIndicator;
17417 getValue: function(){
17419 // Deprecated. Use get('value') instead.
17422 dojo.deprecated("dijit
.InlineEditBox
.getValue() is deprecated
. Use
get('value') instead
.", "", "2.0");
17423 return this.get("value
");
17426 cancel: function(/*Boolean*/ focus){
17428 // Revert to display mode, discarding any changes made in the editor
17432 if(this.disabled || !this.editing){ return; }
17433 this.editing = false;
17435 // tell the world that we have no changes
17436 setTimeout(dojo.hitch(this, "onCancel
"), 0); // setTimeout prevents browser freeze for long-running event handlers
17438 this._showText(focus);
17443 "dijit
._InlineEditor
",
17444 [dijit._Widget, dijit._Templated],
17447 // Internal widget used by InlineEditBox, displayed when in editing mode
17448 // to display the editor and maybe save/cancel buttons. Calling code should
17449 // connect to save/cancel methods to detect when editing is finished
17451 // Has mainly the same parameters as InlineEditBox, plus these values:
17454 // Set of CSS attributes of display node, to replicate in editor
17457 // Value as an HTML string or plain text string, depending on renderAsHTML flag
17459 templateString: dojo.cache("dijit
", "templates
/InlineEditBox.html", "<span dojoAttachPoint=\"editNode\" waiRole=\"presentation\" style=\"position: absolute; visibility:hidden\" class=\"dijitReset dijitInline\"\n\tdojoAttachEvent=\"onkeypress: _onKeyPress\"\n\t><span dojoAttachPoint=\"editorPlaceholder\"></span\n\t><span dojoAttachPoint
=\"buttonContainer
\"\n\t\t><button
class='saveButton' dojoAttachPoint
=\"saveButton
\" dojoType
=\"dijit
.form
.Button
\" dojoAttachEvent
=\"onClick
:save
\" label
=\"${buttonSave}
\"></button\n\t\t><button class='cancelButton' dojoAttachPoint=\"cancelButton\" dojoType=\"dijit.form.Button\" dojoAttachEvent=\"onClick:cancel\" label=\"${buttonCancel}\"></button
\n\t></span\n></span>\n"),
17460 widgetsInTemplate: true,
17462 postMixInProperties: function(){
17463 this.inherited(arguments);
17464 this.messages = dojo.i18n.getLocalization("dijit
", "common
", this.lang);
17465 dojo.forEach(["buttonSave
", "buttonCancel
"], function(prop){
17466 if(!this[prop]){ this[prop] = this.messages[prop]; }
17470 postCreate: function(){
17471 // Create edit widget in place in the template
17472 var cls = dojo.getObject(this.editor);
17474 // Copy the style from the source
17475 // Don't copy ALL properties though, just the necessary/applicable ones.
17476 // wrapperStyle/destStyle code is to workaround IE bug where getComputedStyle().fontSize
17477 // is a relative value like 200%, rather than an absolute value like 24px, and
17478 // the 200% can refer *either* to a setting on the node or it's ancestor (see #11175)
17479 var srcStyle = this.sourceStyle,
17480 editStyle = "line
-height
:" + srcStyle.lineHeight + ";",
17481 destStyle = dojo.getComputedStyle(this.domNode);
17482 dojo.forEach(["Weight
","Family
","Size
","Style
"], function(prop){
17483 var textStyle = srcStyle["font
"+prop],
17484 wrapperStyle = destStyle["font
"+prop];
17485 if(wrapperStyle != textStyle){
17486 editStyle += "font
-"+prop+":"+srcStyle["font
"+prop]+";";
17489 dojo.forEach(["marginTop
","marginBottom
","marginLeft
", "marginRight
"], function(prop){
17490 this.domNode.style[prop] = srcStyle[prop];
17492 var width = this.inlineEditBox.width;
17493 if(width == "100%"){
17495 editStyle += "width
:100%;";
17496 this.domNode.style.display = "block
";
17498 // inline-block mode
17499 editStyle += "width
:" + (width + (Number(width) == width ? "px
" : "")) + ";";
17501 var editorParams = dojo.delegate(this.inlineEditBox.editorParams, {
17506 editorParams[ "displayedValue
" in cls.prototype ? "displayedValue
" : "value
"] = this.value;
17507 var ew = (this.editWidget = new cls(editorParams, this.editorPlaceholder));
17509 if(this.inlineEditBox.autoSave){
17510 // Remove the save/cancel buttons since saving is done by simply tabbing away or
17511 // selecting a value from the drop down list
17512 dojo.destroy(this.buttonContainer);
17514 // Selecting a value from a drop down list causes an onChange event and then we save
17515 this.connect(ew, "onChange
", "_onChange
");
17517 // ESC and TAB should cancel and save. Note that edit widgets do a stopEvent() on ESC key (to
17518 // prevent Dialog from closing when the user just wants to revert the value in the edit widget),
17519 // so this is the only way we can see the key press event.
17520 this.connect(ew, "onKeyPress
", "_onKeyPress
");
17522 // If possible, enable/disable save button based on whether the user has changed the value
17523 if("intermediateChanges
" in cls.prototype){
17524 ew.set("intermediateChanges
", true);
17525 this.connect(ew, "onChange
", "_onIntermediateChange
");
17526 this.saveButton.set("disabled
", true);
17531 _onIntermediateChange: function(val){
17533 // Called for editor widgets that support the intermediateChanges=true flag as a way
17534 // to detect when to enable/disabled the save button
17535 this.saveButton.set("disabled
", (this.getValue() == this._resetValue) || !this.enableSave());
17538 destroy: function(){
17539 this.editWidget.destroy(true); // let the parent wrapper widget clean up the DOM
17540 this.inherited(arguments);
17543 getValue: function(){
17545 // Return the [display] value of the edit widget
17546 var ew = this.editWidget;
17547 return String(ew.get("displayedValue
" in ew ? "displayedValue
" : "value
"));
17550 _onKeyPress: function(e){
17552 // Handler for keypress in the edit box in autoSave mode.
17554 // For autoSave widgets, if Esc/Enter, call cancel/save.
17558 if(this.inlineEditBox.autoSave && this.inlineEditBox.editing){
17559 if(e.altKey || e.ctrlKey){ return; }
17560 // If Enter/Esc pressed, treat as save/cancel.
17561 if(e.charOrCode == dojo.keys.ESCAPE){
17563 this.cancel(true); // sets editing=false which short-circuits _onBlur processing
17564 }else if(e.charOrCode == dojo.keys.ENTER && e.target.tagName == "INPUT
"){
17566 this._onChange(); // fire _onBlur and then save
17569 // _onBlur will handle TAB automatically by allowing
17570 // the TAB to change focus before we mess with the DOM: #6227
17571 // Expounding by request:
17572 // The current focus is on the edit widget input field.
17573 // save() will hide and destroy this widget.
17574 // We want the focus to jump from the currently hidden
17575 // displayNode, but since it's hidden, it's impossible to
17576 // unhide it, focus it, and then have the browser focus
17577 // away from it to the next focusable element since each
17578 // of these events is asynchronous and the focus-to-next-element
17579 // is already queued.
17580 // So we allow the browser time to unqueue the move-focus event
17581 // before we do all the hide/show stuff.
17585 _onBlur: function(){
17587 // Called when focus moves outside the editor
17591 this.inherited(arguments);
17592 if(this.inlineEditBox.autoSave && this.inlineEditBox.editing){
17593 if(this.getValue() == this._resetValue){
17594 this.cancel(false);
17595 }else if(this.enableSave()){
17601 _onChange: function(){
17603 // Called when the underlying widget fires an onChange event,
17604 // such as when the user selects a value from the drop down list of a ComboBox,
17605 // which means that the user has finished entering the value and we should save.
17609 if(this.inlineEditBox.autoSave && this.inlineEditBox.editing && this.enableSave()){
17610 dojo.style(this.inlineEditBox.displayNode, { display: "" });
17611 dijit.focus(this.inlineEditBox.displayNode); // fires _onBlur which will save the formatted value
17615 enableSave: function(){
17617 // User overridable function returning a Boolean to indicate
17618 // if the Save button should be enabled or not - usually due to invalid conditions
17622 this.editWidget.isValid
17623 ? this.editWidget.isValid()
17630 // Focus the edit widget.
17634 this.editWidget.focus();
17635 setTimeout(dojo.hitch(this, function(){
17636 if(this.editWidget.focusNode && this.editWidget.focusNode.tagName == "INPUT
"){
17637 dijit.selectInputText(this.editWidget.focusNode);
17645 if(!dojo._hasResource["dojo
.cookie
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
17646 dojo._hasResource["dojo
.cookie
"] = true;
17647 dojo.provide("dojo
.cookie
");
17652 dojo.__cookieProps = function(){
17653 // expires: Date|String|Number?
17654 // If a number, the number of days from today at which the cookie
17655 // will expire. If a date, the date past which the cookie will expire.
17656 // If expires is in the past, the cookie will be deleted.
17657 // If expires is omitted or is 0, the cookie will expire when the browser closes. << FIXME: 0 seems to disappear right away? FF3.
17659 // The path to use for the cookie.
17661 // The domain to use for the cookie.
17662 // secure: Boolean?
17663 // Whether to only send the cookie on secure connections
17664 this.expires = expires;
17666 this.domain = domain;
17667 this.secure = secure;
17672 dojo.cookie = function(/*String*/name, /*String?*/value, /*dojo.__cookieProps?*/props){
17674 // Get or set a cookie.
17676 // If one argument is passed, returns the value of the cookie
17677 // For two or more arguments, acts as a setter.
17679 // Name of the cookie
17681 // Value for the cookie
17683 // Properties for the cookie
17685 // set a cookie with the JSON-serialized contents of an object which
17686 // will expire 5 days from now:
17687 // | dojo.cookie("configObj
", dojo.toJson(config), { expires: 5 });
17690 // de-serialize a cookie back into a JavaScript object:
17691 // | var config = dojo.fromJson(dojo.cookie("configObj
"));
17694 // delete a cookie:
17695 // | dojo.cookie("configObj
", null, {expires: -1});
17696 var c = document.cookie;
17697 if(arguments.length == 1){
17698 var matches = c.match(new RegExp("(?:^|; )" + dojo.regexp.escapeString(name) + "=([^;]*)"));
17699 return matches ? decodeURIComponent(matches[1]) : undefined; // String or undefined
17701 props = props || {};
17702 // FIXME: expires=0 seems to disappear right away, not on close? (FF3) Change docs?
17703 var exp = props.expires;
17704 if(typeof exp == "number
"){
17705 var d = new Date();
17706 d.setTime(d.getTime() + exp*24*60*60*1000);
17707 exp = props.expires = d;
17709 if(exp && exp.toUTCString){ props.expires = exp.toUTCString(); }
17711 value = encodeURIComponent(value);
17712 var updatedCookie = name + "=" + value, propName;
17713 for(propName in props){
17714 updatedCookie += "; " + propName;
17715 var propValue = props[propName];
17716 if(propValue !== true){ updatedCookie += "=" + propValue; }
17718 document.cookie = updatedCookie;
17722 dojo.cookie.isSupported = function(){
17724 // Use to determine if the current browser supports cookies or not.
17726 // Returns true if user allows cookies.
17727 // Returns false if user doesn't allow cookies.
17729 if(!("cookieEnabled
" in navigator)){
17730 this("__djCookieTest__
", "CookiesAllowed
");
17731 navigator.cookieEnabled = this("__djCookieTest__
") == "CookiesAllowed
";
17732 if(navigator.cookieEnabled){
17733 this("__djCookieTest__
", "", {expires: -1});
17736 return navigator.cookieEnabled;
17741 if(!dojo._hasResource["dijit
.layout
.StackController
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
17742 dojo._hasResource["dijit
.layout
.StackController
"] = true;
17743 dojo.provide("dijit
.layout
.StackController
");
17752 "dijit
.layout
.StackController
",
17753 [dijit._Widget, dijit._Templated, dijit._Container],
17756 // Set of buttons to select a page in a page list.
17758 // Monitors the specified StackContainer, and whenever a page is
17759 // added, deleted, or selected, updates itself accordingly.
17761 templateString: "<span wairole
='tablist' dojoAttachEvent
='onkeypress' class='dijitStackController'></span
>",
17763 // containerId: [const] String
17764 // The id of the page container that I point to
17767 // buttonWidget: [const] String
17768 // The name of the button widget to create to correspond to each page
17769 buttonWidget: "dijit
.layout
._StackButton
",
17771 postCreate: function(){
17772 dijit.setWaiRole(this.domNode, "tablist
");
17774 this.pane2button = {}; // mapping from pane id to buttons
17775 this.pane2handles = {}; // mapping from pane id to this.connect() handles
17777 // Listen to notifications from StackContainer
17778 this.subscribe(this.containerId+"-startup
", "onStartup
");
17779 this.subscribe(this.containerId+"-addChild
", "onAddChild
");
17780 this.subscribe(this.containerId+"-removeChild
", "onRemoveChild
");
17781 this.subscribe(this.containerId+"-selectChild
", "onSelectChild
");
17782 this.subscribe(this.containerId+"-containerKeyPress
", "onContainerKeyPress
");
17785 onStartup: function(/*Object*/ info){
17787 // Called after StackContainer has finished initializing
17790 dojo.forEach(info.children, this.onAddChild, this);
17792 // Show button corresponding to selected pane (unless selected
17793 // is null because there are no panes)
17794 this.onSelectChild(info.selected);
17798 destroy: function(){
17799 for(var pane in this.pane2button){
17800 this.onRemoveChild(dijit.byId(pane));
17802 this.inherited(arguments);
17805 onAddChild: function(/*dijit._Widget*/ page, /*Integer?*/ insertIndex){
17807 // Called whenever a page is added to the container.
17808 // Create button corresponding to the page.
17812 // create an instance of the button widget
17813 var cls = dojo.getObject(this.buttonWidget);
17814 var button = new cls({
17815 id: this.id + "_
" + page.id,
17819 showLabel: page.showTitle,
17820 iconClass: page.iconClass,
17821 closeButton: page.closable,
17822 title: page.tooltip
17824 dijit.setWaiState(button.focusNode,"selected
", "false");
17825 this.pane2handles[page.id] = [
17826 this.connect(page, 'set', function(name, value){
17829 showTitle: 'showLabel',
17830 iconClass: 'iconClass',
17831 closable: 'closeButton',
17835 button.set(buttonAttr, value);
17838 this.connect(button, 'onClick', dojo.hitch(this,"onButtonClick
", page)),
17839 this.connect(button, 'onClickCloseButton', dojo.hitch(this,"onCloseButtonClick
", page))
17841 this.addChild(button, insertIndex);
17842 this.pane2button[page.id] = button;
17843 page.controlButton = button; // this value might be overwritten if two tabs point to same container
17844 if(!this._currentChild){ // put the first child into the tab order
17845 button.focusNode.setAttribute("tabIndex
", "0");
17846 dijit.setWaiState(button.focusNode, "selected
", "true");
17847 this._currentChild = page;
17849 // make sure all tabs have the same length
17850 if(!this.isLeftToRight() && dojo.isIE && this._rectifyRtlTabList){
17851 this._rectifyRtlTabList();
17855 onRemoveChild: function(/*dijit._Widget*/ page){
17857 // Called whenever a page is removed from the container.
17858 // Remove the button corresponding to the page.
17862 if(this._currentChild === page){ this._currentChild = null; }
17863 dojo.forEach(this.pane2handles[page.id], this.disconnect, this);
17864 delete this.pane2handles[page.id];
17865 var button = this.pane2button[page.id];
17867 this.removeChild(button);
17868 delete this.pane2button[page.id];
17871 delete page.controlButton;
17874 onSelectChild: function(/*dijit._Widget*/ page){
17876 // Called when a page has been selected in the StackContainer, either by me or by another StackController
17880 if(!page){ return; }
17882 if(this._currentChild){
17883 var oldButton=this.pane2button[this._currentChild.id];
17884 oldButton.set('checked', false);
17885 dijit.setWaiState(oldButton.focusNode, "selected
", "false");
17886 oldButton.focusNode.setAttribute("tabIndex
", "-1");
17889 var newButton=this.pane2button[page.id];
17890 newButton.set('checked', true);
17891 dijit.setWaiState(newButton.focusNode, "selected
", "true");
17892 this._currentChild = page;
17893 newButton.focusNode.setAttribute("tabIndex
", "0");
17894 var container = dijit.byId(this.containerId);
17895 dijit.setWaiState(container.containerNode, "labelledby
", newButton.id);
17898 onButtonClick: function(/*dijit._Widget*/ page){
17900 // Called whenever one of my child buttons is pressed in an attempt to select a page
17904 var container = dijit.byId(this.containerId);
17905 container.selectChild(page);
17908 onCloseButtonClick: function(/*dijit._Widget*/ page){
17910 // Called whenever one of my child buttons [X] is pressed in an attempt to close a page
17914 var container = dijit.byId(this.containerId);
17915 container.closeChild(page);
17916 if(this._currentChild){
17917 var b = this.pane2button[this._currentChild.id];
17919 dijit.focus(b.focusNode || b.domNode);
17924 // TODO: this is a bit redundant with forward, back api in StackContainer
17925 adjacent: function(/*Boolean*/ forward){
17927 // Helper for onkeypress to find next/previous button
17931 if(!this.isLeftToRight() && (!this.tabPosition || /top|bottom/.test(this.tabPosition))){ forward = !forward; }
17932 // find currently focused button in children array
17933 var children = this.getChildren();
17934 var current = dojo.indexOf(children, this.pane2button[this._currentChild.id]);
17935 // pick next button to focus on
17936 var offset = forward ? 1 : children.length - 1;
17937 return children[ (current + offset) % children.length ]; // dijit._Widget
17940 onkeypress: function(/*Event*/ e){
17942 // Handle keystrokes on the page list, for advancing to next/previous button
17943 // and closing the current page if the page is closable.
17947 if(this.disabled || e.altKey ){ return; }
17948 var forward = null;
17949 if(e.ctrlKey || !e._djpage){
17951 switch(e.charOrCode){
17954 if(!e._djpage){ forward = false; }
17957 if(e.ctrlKey){ forward = false; }
17959 case k.RIGHT_ARROW:
17961 if(!e._djpage){ forward = true; }
17964 if(e.ctrlKey){ forward = true; }
17967 if(this._currentChild.closable){
17968 this.onCloseButtonClick(this._currentChild);
17974 if(e.charOrCode === k.TAB){
17975 this.adjacent(!e.shiftKey).onClick();
17977 }else if(e.charOrCode == "w
"){
17978 if(this._currentChild.closable){
17979 this.onCloseButtonClick(this._currentChild);
17981 dojo.stopEvent(e); // avoid browser tab closing.
17985 // handle page navigation
17986 if(forward !== null){
17987 this.adjacent(forward).onClick();
17993 onContainerKeyPress: function(/*Object*/ info){
17995 // Called when there was a keypress on the container
17998 info.e._djpage = info.page;
17999 this.onkeypress(info.e);
18004 dojo.declare("dijit
.layout
._StackButton
",
18005 dijit.form.ToggleButton,
18008 // Internal widget used by StackContainer.
18010 // The button-like or tab-like object you click to select or delete a page
18014 // Override _FormWidget.tabIndex.
18015 // StackContainer buttons are not in the tab order by default.
18016 // Probably we should be calling this.startupKeyNavChildren() instead.
18019 postCreate: function(/*Event*/ evt){
18020 dijit.setWaiRole((this.focusNode || this.domNode), "tab
");
18021 this.inherited(arguments);
18024 onClick: function(/*Event*/ evt){
18026 // This is for TabContainer where the tabs are <span> rather than button,
18027 // so need to set focus explicitly (on some browsers)
18028 // Note that you shouldn't override this method, but you can connect to it.
18029 dijit.focus(this.focusNode);
18031 // ... now let StackController catch the event and tell me what to do
18034 onClickCloseButton: function(/*Event*/ evt){
18036 // StackContainer connects to this function; if your widget contains a close button
18037 // then clicking it should call this function.
18038 // Note that you shouldn't override this method, but you can connect to it.
18039 evt.stopPropagation();
18046 if(!dojo._hasResource["dijit
.layout
.StackContainer
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
18047 dojo._hasResource["dijit
.layout
.StackContainer
"] = true;
18048 dojo.provide("dijit
.layout
.StackContainer
");
18056 "dijit
.layout
.StackContainer
",
18057 dijit.layout._LayoutWidget,
18060 // A container that has multiple children, but shows only
18061 // one child at a time
18064 // A container for widgets (ContentPanes, for example) That displays
18065 // only one Widget at a time.
18067 // Publishes topics [widgetId]-addChild, [widgetId]-removeChild, and [widgetId]-selectChild
18069 // Can be base class for container, Wizard, Show, etc.
18071 // doLayout: Boolean
18072 // If true, change the size of my currently displayed child to match my size
18075 // persist: Boolean
18076 // Remembers the selected child across sessions
18079 baseClass: "dijitStackContainer
",
18082 // selectedChildWidget: [readonly] dijit._Widget
18083 // References the currently selected child widget, if any.
18084 // Adjust selected child with selectChild() method.
18085 selectedChildWidget: null,
18088 postCreate: function(){
18089 this.inherited(arguments);
18090 dojo.addClass(this.domNode, "dijitLayoutContainer
");
18091 dijit.setWaiRole(this.containerNode, "tabpanel
");
18092 this.connect(this.domNode, "onkeypress
", this._onKeyPress);
18095 startup: function(){
18096 if(this._started){ return; }
18098 var children = this.getChildren();
18100 // Setup each page panel to be initially hidden
18101 dojo.forEach(children, this._setupChild, this);
18103 // Figure out which child to initially display, defaulting to first one
18105 this.selectedChildWidget = dijit.byId(dojo.cookie(this.id + "_selectedChild
"));
18107 dojo.some(children, function(child){
18108 if(child.selected){
18109 this.selectedChildWidget = child;
18111 return child.selected;
18114 var selected = this.selectedChildWidget;
18115 if(!selected && children[0]){
18116 selected = this.selectedChildWidget = children[0];
18117 selected.selected = true;
18120 // Publish information about myself so any StackControllers can initialize.
18121 // This needs to happen before this.inherited(arguments) so that for
18122 // TabContainer, this._contentBox doesn't include the space for the tab labels.
18123 dojo.publish(this.id+"-startup
", [{children: children, selected: selected}]);
18125 // Startup each child widget, and do initial layout like setting this._contentBox,
18126 // then calls this.resize() which does the initial sizing on the selected child.
18127 this.inherited(arguments);
18130 resize: function(){
18131 // Resize is called when we are first made visible (it's called from startup()
18132 // if we are initially visible). If this is the first time we've been made
18133 // visible then show our first child.
18134 var selected = this.selectedChildWidget;
18135 if(selected && !this._hasBeenShown){
18136 this._hasBeenShown = true;
18137 this._showChild(selected);
18139 this.inherited(arguments);
18142 _setupChild: function(/*dijit._Widget*/ child){
18143 // Overrides _LayoutWidget._setupChild()
18145 this.inherited(arguments);
18147 dojo.removeClass(child.domNode, "dijitVisible
");
18148 dojo.addClass(child.domNode, "dijitHidden
");
18150 // remove the title attribute so it doesn't show up when i hover
18152 child.domNode.title = "";
18155 addChild: function(/*dijit._Widget*/ child, /*Integer?*/ insertIndex){
18156 // Overrides _Container.addChild() to do layout and publish events
18158 this.inherited(arguments);
18161 dojo.publish(this.id+"-addChild
", [child, insertIndex]);
18163 // in case the tab titles have overflowed from one line to two lines
18164 // (or, if this if first child, from zero lines to one line)
18165 // TODO: w/ScrollingTabController this is no longer necessary, although
18166 // ScrollTabController.resize() does need to get called to show/hide
18167 // the navigation buttons as appropriate, but that's handled in ScrollingTabController.onAddChild()
18170 // if this is the first child, then select it
18171 if(!this.selectedChildWidget){
18172 this.selectChild(child);
18177 removeChild: function(/*dijit._Widget*/ page){
18178 // Overrides _Container.removeChild() to do layout and publish events
18180 this.inherited(arguments);
18183 // this will notify any tablists to remove a button; do this first because it may affect sizing
18184 dojo.publish(this.id + "-removeChild
", [page]);
18187 // If we are being destroyed than don't run the code below (to select another page), because we are deleting
18188 // every page one by one
18189 if(this._beingDestroyed){ return; }
18191 // Select new page to display, also updating TabController to show the respective tab.
18192 // Do this before layout call because it can affect the height of the TabController.
18193 if(this.selectedChildWidget === page){
18194 this.selectedChildWidget = undefined;
18196 var children = this.getChildren();
18197 if(children.length){
18198 this.selectChild(children[0]);
18204 // In case the tab titles now take up one line instead of two lines
18205 // (note though that ScrollingTabController never overflows to multiple lines),
18206 // or the height has changed slightly because of addition/removal of tab which close icon
18211 selectChild: function(/*dijit._Widget|String*/ page, /*Boolean*/ animate){
18213 // Show the given widget (which must be one of my children)
18215 // Reference to child widget or id of child widget
18217 page = dijit.byId(page);
18219 if(this.selectedChildWidget != page){
18220 // Deselect old page and select new one
18221 this._transition(page, this.selectedChildWidget, animate);
18222 this.selectedChildWidget = page;
18223 dojo.publish(this.id+"-selectChild
", [page]);
18226 dojo.cookie(this.id + "_selectedChild
", this.selectedChildWidget.id);
18231 _transition: function(/*dijit._Widget*/newWidget, /*dijit._Widget*/oldWidget){
18233 // Hide the old widget and display the new widget.
18234 // Subclasses should override this.
18236 // protected extension
18238 this._hideChild(oldWidget);
18240 this._showChild(newWidget);
18242 // Size the new widget, in case this is the first time it's being shown,
18243 // or I have been resized since the last time it was shown.
18244 // Note that page must be visible for resizing to work.
18245 if(newWidget.resize){
18247 newWidget.resize(this._containerContentBox || this._contentBox);
18249 // the child should pick it's own size but we still need to call resize()
18250 // (with no arguments) to let the widget lay itself out
18251 newWidget.resize();
18256 _adjacent: function(/*Boolean*/ forward){
18258 // Gets the next/previous child widget in this container from the current selection.
18259 var children = this.getChildren();
18260 var index = dojo.indexOf(children, this.selectedChildWidget);
18261 index += forward ? 1 : children.length - 1;
18262 return children[ index % children.length ]; // dijit._Widget
18265 forward: function(){
18267 // Advance to next page.
18268 this.selectChild(this._adjacent(true), true);
18273 // Go back to previous page.
18274 this.selectChild(this._adjacent(false), true);
18277 _onKeyPress: function(e){
18278 dojo.publish(this.id+"-containerKeyPress
", [{ e: e, page: this}]);
18281 layout: function(){
18282 // Implement _LayoutWidget.layout() virtual method.
18283 if(this.doLayout && this.selectedChildWidget && this.selectedChildWidget.resize){
18284 this.selectedChildWidget.resize(this._containerContentBox || this._contentBox);
18288 _showChild: function(/*dijit._Widget*/ page){
18290 // Show the specified child by changing it's CSS, and call _onShow()/onShow() so
18291 // it can do any updates it needs regarding loading href's etc.
18292 var children = this.getChildren();
18293 page.isFirstChild = (page == children[0]);
18294 page.isLastChild = (page == children[children.length-1]);
18295 page.selected = true;
18297 dojo.removeClass(page.domNode, "dijitHidden
");
18298 dojo.addClass(page.domNode, "dijitVisible
");
18303 _hideChild: function(/*dijit._Widget*/ page){
18305 // Hide the specified child by changing it's CSS, and call _onHide() so
18307 page.selected=false;
18308 dojo.removeClass(page.domNode, "dijitVisible
");
18309 dojo.addClass(page.domNode, "dijitHidden
");
18314 closeChild: function(/*dijit._Widget*/ page){
18316 // Callback when user clicks the [X] to remove a page.
18317 // If onClose() returns true then remove and destroy the child.
18320 var remove = page.onClose(this, page);
18322 this.removeChild(page);
18323 // makes sure we can clean up executeScripts in ContentPane onUnLoad
18324 page.destroyRecursive();
18328 destroyDescendants: function(/*Boolean*/preserveDom){
18329 dojo.forEach(this.getChildren(), function(child){
18330 this.removeChild(child);
18331 child.destroyRecursive(preserveDom);
18336 // For back-compat, remove for 2.0
18340 // These arguments can be specified for the children of a StackContainer.
18341 // Since any widget can be specified as a StackContainer child, mix them
18342 // into the base widget class. (This is a hack, but it's effective.)
18343 dojo.extend(dijit._Widget, {
18344 // selected: Boolean
18345 // Parameter for children of `dijit.layout.StackContainer` or subclasses.
18346 // Specifies that this widget should be the initially displayed pane.
18347 // Note: to change the selected child use `dijit.layout.StackContainer.selectChild`
18350 // closable: Boolean
18351 // Parameter for children of `dijit.layout.StackContainer` or subclasses.
18352 // True if user can close (destroy) this child, such as (for example) clicking the X on the tab.
18355 // iconClass: String
18356 // Parameter for children of `dijit.layout.StackContainer` or subclasses.
18357 // CSS Class specifying icon to use in label associated with this pane.
18360 // showTitle: Boolean
18361 // Parameter for children of `dijit.layout.StackContainer` or subclasses.
18362 // When true, display title of this widget as tab label etc., rather than just using
18363 // icon specified in iconClass
18369 if(!dojo._hasResource["dijit
.layout
.AccordionPane
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
18370 dojo._hasResource["dijit
.layout
.AccordionPane
"] = true;
18371 dojo.provide("dijit
.layout
.AccordionPane
");
18375 dojo.declare("dijit
.layout
.AccordionPane
", dijit.layout.ContentPane, {
18377 // Deprecated widget. Use `dijit.layout.ContentPane` instead.
18381 constructor: function(){
18382 dojo.deprecated("dijit
.layout
.AccordionPane deprecated
, use ContentPane instead
", "", "2.0");
18385 onSelected: function(){
18387 // called when this pane is selected
18393 if(!dojo._hasResource["dijit
.layout
.AccordionContainer
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
18394 dojo._hasResource["dijit
.layout
.AccordionContainer
"] = true;
18395 dojo.provide("dijit
.layout
.AccordionContainer
");
18405 // for back compat, remove for 2.0
18408 "dijit
.layout
.AccordionContainer
",
18409 dijit.layout.StackContainer,
18412 // Holds a set of panes where every pane's title is visible, but only one pane's content is visible at a time,
18413 // and switching between panes is visualized by sliding the other panes up/down.
18415 // | <div dojoType="dijit
.layout
.AccordionContainer
">
18416 // | <div dojoType="dijit
.layout
.ContentPane
" title="pane
1">
18418 // | <div dojoType="dijit
.layout
.ContentPane
" title="pane
2">
18419 // | <p>This is some text</p>
18423 // duration: Integer
18424 // Amount of time (in ms) it takes to slide panes
18425 duration: dijit.defaultDuration,
18427 // buttonWidget: [const] String
18428 // The name of the widget used to display the title of each pane
18429 buttonWidget: "dijit
.layout
._AccordionButton
",
18431 // _verticalSpace: Number
18432 // Pixels of space available for the open pane
18433 // (my content box size minus the cumulative size of all the title bars)
18436 baseClass: "dijitAccordionContainer
",
18438 postCreate: function(){
18439 this.domNode.style.overflow = "hidden
";
18440 this.inherited(arguments);
18441 dijit.setWaiRole(this.domNode, "tablist
");
18444 startup: function(){
18445 if(this._started){ return; }
18446 this.inherited(arguments);
18447 if(this.selectedChildWidget){
18448 var style = this.selectedChildWidget.containerNode.style;
18449 style.display = "";
18450 style.overflow = "auto
";
18451 this.selectedChildWidget._wrapperWidget.set("selected
", true);
18455 _getTargetHeight: function(/* Node */ node){
18457 // For the given node, returns the height that should be
18458 // set to achieve our vertical space (subtract any padding
18461 // This is used by the animations.
18463 // TODO: I don't think this works correctly in IE quirks when an elements
18464 // style.height including padding and borders
18465 var cs = dojo.getComputedStyle(node);
18466 return Math.max(this._verticalSpace - dojo._getPadBorderExtents(node, cs).h - dojo._getMarginExtents(node, cs).h, 0);
18469 layout: function(){
18470 // Implement _LayoutWidget.layout() virtual method.
18471 // Set the height of the open pane based on what room remains.
18473 var openPane = this.selectedChildWidget;
18475 if(!openPane){ return;}
18477 var openPaneContainer = openPane._wrapperWidget.domNode,
18478 openPaneContainerMargin = dojo._getMarginExtents(openPaneContainer),
18479 openPaneContainerPadBorder = dojo._getPadBorderExtents(openPaneContainer),
18480 mySize = this._contentBox;
18482 // get cumulative height of all the unselected title bars
18483 var totalCollapsedHeight = 0;
18484 dojo.forEach(this.getChildren(), function(child){
18485 if(child != openPane){
18486 totalCollapsedHeight += dojo.marginBox(child._wrapperWidget.domNode).h;
18489 this._verticalSpace = mySize.h - totalCollapsedHeight - openPaneContainerMargin.h
18490 - openPaneContainerPadBorder.h - openPane._buttonWidget.getTitleHeight();
18492 // Memo size to make displayed child
18493 this._containerContentBox = {
18494 h: this._verticalSpace,
18495 w: this._contentBox.w - openPaneContainerMargin.w - openPaneContainerPadBorder.w
18499 openPane.resize(this._containerContentBox);
18503 _setupChild: function(child){
18504 // Overrides _LayoutWidget._setupChild().
18505 // Put wrapper widget around the child widget, showing title
18507 child._wrapperWidget = new dijit.layout._AccordionInnerContainer({
18508 contentWidget: child,
18509 buttonWidget: this.buttonWidget,
18510 id: child.id + "_wrapper
",
18516 this.inherited(arguments);
18519 addChild: function(/*dijit._Widget*/ child, /*Integer?*/ insertIndex){
18521 // Adding a child to a started Accordion is complicated because children have
18522 // wrapper widgets. Default code path (calling this.inherited()) would add
18523 // the new child inside another child's wrapper.
18525 // First add in child as a direct child of this AccordionContainer
18526 dojo.place(child.domNode, this.containerNode, insertIndex);
18528 if(!child._started){
18532 // Then stick the wrapper widget around the child widget
18533 this._setupChild(child);
18535 // Code below copied from StackContainer
18536 dojo.publish(this.id+"-addChild
", [child, insertIndex]);
18538 if(!this.selectedChildWidget){
18539 this.selectChild(child);
18542 // We haven't been started yet so just add in the child widget directly,
18543 // and the wrapper will be created on startup()
18544 this.inherited(arguments);
18548 removeChild: function(child){
18549 // Overrides _LayoutWidget.removeChild().
18551 // destroy wrapper widget first, before StackContainer.getChildren() call
18552 child._wrapperWidget.destroy();
18553 delete child._wrapperWidget;
18554 dojo.removeClass(child.domNode, "dijitHidden
");
18556 this.inherited(arguments);
18559 getChildren: function(){
18560 // Overrides _Container.getChildren() to return content panes rather than internal AccordionInnerContainer panes
18561 return dojo.map(this.inherited(arguments), function(child){
18562 return child.declaredClass == "dijit
.layout
._AccordionInnerContainer
" ? child.contentWidget : child;
18566 destroy: function(){
18567 dojo.forEach(this.getChildren(), function(child){
18568 child._wrapperWidget.destroy();
18570 this.inherited(arguments);
18573 _transition: function(/*dijit._Widget?*/newWidget, /*dijit._Widget?*/oldWidget, /*Boolean*/ animate){
18574 // Overrides StackContainer._transition() to provide sliding of title bars etc.
18576 //TODO: should be able to replace this with calls to slideIn/slideOut
18577 if(this._inTransition){ return; }
18578 var animations = [];
18579 var paneHeight = this._verticalSpace;
18581 newWidget._wrapperWidget.set("selected
", true);
18583 this._showChild(newWidget); // prepare widget to be slid in
18585 // Size the new widget, in case this is the first time it's being shown,
18586 // or I have been resized since the last time it was shown.
18587 // Note that page must be visible for resizing to work.
18588 if(this.doLayout && newWidget.resize){
18589 newWidget.resize(this._containerContentBox);
18592 var newContents = newWidget.domNode;
18593 dojo.addClass(newContents, "dijitVisible
");
18594 dojo.removeClass(newContents, "dijitHidden
");
18597 var newContentsOverflow = newContents.style.overflow;
18598 newContents.style.overflow = "hidden
";
18599 animations.push(dojo.animateProperty({
18601 duration: this.duration,
18603 height: { start: 1, end: this._getTargetHeight(newContents) }
18606 newContents.style.overflow = newContentsOverflow;
18608 // Kick IE to workaround layout bug, see #11415
18610 setTimeout(function(){
18611 dojo.removeClass(newContents.parentNode, "dijitAccordionInnerContainerFocused
");
18612 setTimeout(function(){
18613 dojo.addClass(newContents.parentNode, "dijitAccordionInnerContainerFocused
");
18622 oldWidget._wrapperWidget.set("selected
", false);
18623 var oldContents = oldWidget.domNode;
18625 var oldContentsOverflow = oldContents.style.overflow;
18626 oldContents.style.overflow = "hidden
";
18627 animations.push(dojo.animateProperty({
18629 duration: this.duration,
18631 height: { start: this._getTargetHeight(oldContents), end: 1 }
18634 dojo.addClass(oldContents, "dijitHidden
");
18635 dojo.removeClass(oldContents, "dijitVisible
");
18636 oldContents.style.overflow = oldContentsOverflow;
18637 if(oldWidget.onHide){
18638 oldWidget.onHide();
18643 dojo.addClass(oldContents, "dijitHidden
");
18644 dojo.removeClass(oldContents, "dijitVisible
");
18645 if(oldWidget.onHide){
18646 oldWidget.onHide();
18652 this._inTransition = true;
18653 var combined = dojo.fx.combine(animations);
18654 combined.onEnd = dojo.hitch(this, function(){
18655 delete this._inTransition;
18661 // note: we are treating the container as controller here
18662 _onKeyPress: function(/*Event*/ e, /*dijit._Widget*/ fromTitle){
18664 // Handle keypress events
18666 // This is called from a handler on AccordionContainer.domNode
18667 // (setup in StackContainer), and is also called directly from
18668 // the click handler for accordion labels
18669 if(this._inTransition || this.disabled || e.altKey || !(fromTitle || e.ctrlKey)){
18670 if(this._inTransition){
18677 if((fromTitle && (c == k.LEFT_ARROW || c == k.UP_ARROW)) ||
18678 (e.ctrlKey && c == k.PAGE_UP)){
18679 this._adjacent(false)._buttonWidget._onTitleClick();
18681 }else if((fromTitle && (c == k.RIGHT_ARROW || c == k.DOWN_ARROW)) ||
18682 (e.ctrlKey && (c == k.PAGE_DOWN || c == k.TAB))){
18683 this._adjacent(true)._buttonWidget._onTitleClick();
18690 dojo.declare("dijit
.layout
._AccordionInnerContainer
",
18691 [dijit._Widget, dijit._CssStateMixin], {
18693 // Internal widget placed as direct child of AccordionContainer.containerNode.
18694 // When other widgets are added as children to an AccordionContainer they are wrapped in
18697 // buttonWidget: String
18698 // Name of class to use to instantiate title
18699 // (Wish we didn't have a separate widget for just the title but maintaining it
18700 // for backwards compatibility, is it worth it?)
18702 buttonWidget: null,
18704 // contentWidget: dijit._Widget
18705 // Pointer to the real child widget
18707 contentWidget: null,
18710 baseClass: "dijitAccordionInnerContainer
",
18712 // tell nested layout widget that we will take care of sizing
18714 isLayoutContainer: true,
18716 buildRendering: function(){
18717 // Create wrapper div, placed where the child is now
18718 this.domNode = dojo.place("<div
class='" + this.baseClass + "'>", this.contentWidget.domNode, "after
");
18720 // wrapper div's first child is the button widget (ie, the title bar)
18721 var child = this.contentWidget,
18722 cls = dojo.getObject(this.buttonWidget);
18723 this.button = child._buttonWidget = (new cls({
18724 contentWidget: child,
18725 label: child.title,
18726 title: child.tooltip,
18729 iconClass: child.iconClass,
18730 id: child.id + "_button
",
18731 parent: this.parent
18732 })).placeAt(this.domNode);
18734 // and then the actual content widget (changing it from prior-sibling to last-child)
18735 dojo.place(this.contentWidget.domNode, this.domNode);
18738 postCreate: function(){
18739 this.inherited(arguments);
18740 this.connect(this.contentWidget, 'set', function(name, value){
18741 var mappedName = {title: "label
", tooltip: "title
", iconClass: "iconClass
"}[name];
18743 this.button.set(mappedName, value);
18748 _setSelectedAttr: function(/*Boolean*/ isSelected){
18749 this.selected = isSelected;
18750 this.button.set("selected
", isSelected);
18752 var cw = this.contentWidget;
18753 if(cw.onSelected){ cw.onSelected(); }
18757 startup: function(){
18758 // Called by _Container.addChild()
18759 this.contentWidget.startup();
18762 destroy: function(){
18763 this.button.destroyRecursive();
18765 delete this.contentWidget._buttonWidget;
18766 delete this.contentWidget._wrapperWidget;
18768 this.inherited(arguments);
18771 destroyDescendants: function(){
18772 // since getChildren isn't working for me, have to code this manually
18773 this.contentWidget.destroyRecursive();
18777 dojo.declare("dijit
.layout
._AccordionButton
",
18778 [dijit._Widget, dijit._Templated, dijit._CssStateMixin],
18781 // The title bar to click to open up an accordion pane.
18782 // Internal widget used by AccordionContainer.
18786 templateString: dojo.cache("dijit
.layout
", "templates
/AccordionButton.html", "<div dojoAttachEvent='onclick:_onTitleClick' class='dijitAccordionTitle'>\n\t<div dojoAttachPoint='titleNode,focusNode' dojoAttachEvent='onkeypress:_onTitleKeyPress'\n\t\t\tclass='dijitAccordionTitleFocus' wairole=\"tab\" waiState=\"expanded-false\"\n\t\t><span class='dijitInline dijitAccordionArrow' waiRole=\"presentation\"></span\n\t\t><span
class='arrowTextUp' waiRole
=\"presentation
\">+</span\n\t\t><span class='arrowTextDown' waiRole=\"presentation\">-</span\n\t\t><img src
=\"${_blankGif}
\" alt
=\"\" class=\"dijitIcon
\" dojoAttachPoint
='iconNode' style
=\"vertical
-align
: middle
\" waiRole
=\"presentation
\"/>\n\t\t<span waiRole=\"presentation\" dojoAttachPoint='titleTextNode' class='dijitAccordionText'></span>\n\t</div>\n</div>\n"),
18787 attributeMap: dojo.mixin(dojo.clone(dijit.layout.ContentPane.prototype.attributeMap), {
18788 label: {node: "titleTextNode
", type: "innerHTML
" },
18789 title: {node: "titleTextNode
", type: "attribute
", attribute: "title
"},
18790 iconClass: { node: "iconNode
", type: "class" }
18793 baseClass: "dijitAccordionTitle
",
18795 getParent: function(){
18797 // Returns the AccordionContainer parent.
18800 return this.parent;
18803 postCreate: function(){
18804 this.inherited(arguments);
18805 dojo.setSelectable(this.domNode, false);
18806 var titleTextNodeId = dojo.attr(this.domNode,'id').replace(' ','_');
18807 dojo.attr(this.titleTextNode, "id
", titleTextNodeId+"_title
");
18808 dijit.setWaiState(this.focusNode, "labelledby
", dojo.attr(this.titleTextNode, "id
"));
18811 getTitleHeight: function(){
18813 // Returns the height of the title dom node.
18814 return dojo.marginBox(this.domNode).h; // Integer
18817 // TODO: maybe the parent should set these methods directly rather than forcing the code
18818 // into the button widget?
18819 _onTitleClick: function(){
18821 // Callback when someone clicks my title.
18822 var parent = this.getParent();
18823 if(!parent._inTransition){
18824 parent.selectChild(this.contentWidget, true);
18825 dijit.focus(this.focusNode);
18829 _onTitleKeyPress: function(/*Event*/ evt){
18830 return this.getParent()._onKeyPress(evt, this.contentWidget);
18833 _setSelectedAttr: function(/*Boolean*/ isSelected){
18834 this.selected = isSelected;
18835 dijit.setWaiState(this.focusNode, "expanded
", isSelected);
18836 dijit.setWaiState(this.focusNode, "selected
", isSelected);
18837 this.focusNode.setAttribute("tabIndex
", isSelected ? "0" : "-1");
18843 if(!dojo._hasResource["dijit
.layout
.BorderContainer
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
18844 dojo._hasResource["dijit
.layout
.BorderContainer
"] = true;
18845 dojo.provide("dijit
.layout
.BorderContainer
");
18851 "dijit
.layout
.BorderContainer
",
18852 dijit.layout._LayoutWidget,
18855 // Provides layout in up to 5 regions, a mandatory center with optional borders along its 4 sides.
18858 // A BorderContainer is a box with a specified size, such as style="width
: 500px
; height
: 500px
;",
18859 // that contains a child widget marked region="center
" and optionally children widgets marked
18860 // region equal to "top
", "bottom
", "leading
", "trailing
", "left
" or "right
".
18861 // Children along the edges will be laid out according to width or height dimensions and may
18862 // include optional splitters (splitter="true") to make them resizable by the user. The remaining
18863 // space is designated for the center region.
18865 // NOTE: Splitters must not be more than 50 pixels in width.
18867 // The outer size must be specified on the BorderContainer node. Width must be specified for the sides
18868 // and height for the top and bottom, respectively. No dimensions should be specified on the center;
18869 // it will fill the remaining space. Regions named "leading
" and "trailing
" may be used just like
18870 // "left
" and "right
" except that they will be reversed in right-to-left environments.
18873 // | <div dojoType="dijit
.layout
.BorderContainer
" design="sidebar
" gutters="false"
18874 // | style="width
: 400px
; height
: 300px
;">
18875 // | <div dojoType="ContentPane
" region="top
">header text</div>
18876 // | <div dojoType="ContentPane
" region="right
" splitter="true" style="width
: 200px
;">table of contents</div>
18877 // | <div dojoType="ContentPane
" region="center
">client area</div>
18881 // Which design is used for the layout:
18882 // - "headline
" (default) where the top and bottom extend
18883 // the full width of the container
18884 // - "sidebar
" where the left and right sides extend from top to bottom.
18885 design: "headline
",
18887 // gutters: Boolean
18888 // Give each pane a border and margin.
18889 // Margin determined by domNode.paddingLeft.
18890 // When false, only resizable panes have a gutter (i.e. draggable splitter) for resizing.
18893 // liveSplitters: Boolean
18894 // Specifies whether splitters resize as you drag (true) or only upon mouseup (false)
18895 liveSplitters: true,
18897 // persist: Boolean
18898 // Save splitter positions in a cookie.
18901 baseClass: "dijitBorderContainer
",
18903 // _splitterClass: String
18904 // Optional hook to override the default Splitter widget used by BorderContainer
18905 _splitterClass: "dijit
.layout
._Splitter
",
18907 postMixInProperties: function(){
18908 // change class name to indicate that BorderContainer is being used purely for
18909 // layout (like LayoutContainer) rather than for pretty formatting.
18911 this.baseClass += "NoGutter
";
18913 this.inherited(arguments);
18916 postCreate: function(){
18917 this.inherited(arguments);
18919 this._splitters = {};
18920 this._splitterThickness = {};
18923 startup: function(){
18924 if(this._started){ return; }
18925 dojo.forEach(this.getChildren(), this._setupChild, this);
18926 this.inherited(arguments);
18929 _setupChild: function(/*dijit._Widget*/ child){
18930 // Override _LayoutWidget._setupChild().
18932 var region = child.region;
18934 this.inherited(arguments);
18936 dojo.addClass(child.domNode, this.baseClass+"Pane
");
18938 var ltr = this.isLeftToRight();
18939 if(region == "leading
"){ region = ltr ? "left
" : "right
"; }
18940 if(region == "trailing
"){ region = ltr ? "right
" : "left
"; }
18942 //FIXME: redundant?
18943 this["_
"+region] = child.domNode;
18944 this["_
"+region+"Widget
"] = child;
18946 // Create draggable splitter for resizing pane,
18947 // or alternately if splitter=false but BorderContainer.gutters=true then
18948 // insert dummy div just for spacing
18949 if((child.splitter || this.gutters) && !this._splitters[region]){
18950 var _Splitter = dojo.getObject(child.splitter ? this._splitterClass : "dijit
.layout
._Gutter
");
18951 var splitter = new _Splitter({
18952 id: child.id + "_splitter
",
18956 live: this.liveSplitters
18958 splitter.isSplitter = true;
18959 this._splitters[region] = splitter.domNode;
18960 dojo.place(this._splitters[region], child.domNode, "after
");
18962 // Splitters arent added as Contained children, so we need to call startup explicitly
18963 splitter.startup();
18965 child.region = region;
18969 _computeSplitterThickness: function(region){
18970 this._splitterThickness[region] = this._splitterThickness[region] ||
18971 dojo.marginBox(this._splitters[region])[(/top|bottom/.test(region) ? 'h' : 'w')];
18974 layout: function(){
18975 // Implement _LayoutWidget.layout() virtual method.
18976 for(var region in this._splitters){ this._computeSplitterThickness(region); }
18977 this._layoutChildren();
18980 addChild: function(/*dijit._Widget*/ child, /*Integer?*/ insertIndex){
18981 // Override _LayoutWidget.addChild().
18982 this.inherited(arguments);
18984 this.layout(); //OPT
18988 removeChild: function(/*dijit._Widget*/ child){
18989 // Override _LayoutWidget.removeChild().
18990 var region = child.region;
18991 var splitter = this._splitters[region];
18993 dijit.byNode(splitter).destroy();
18994 delete this._splitters[region];
18995 delete this._splitterThickness[region];
18997 this.inherited(arguments);
18998 delete this["_
"+region];
18999 delete this["_
" +region+"Widget
"];
19001 this._layoutChildren();
19003 dojo.removeClass(child.domNode, this.baseClass+"Pane
");
19006 getChildren: function(){
19007 // Override _LayoutWidget.getChildren() to only return real children, not the splitters.
19008 return dojo.filter(this.inherited(arguments), function(widget){
19009 return !widget.isSplitter;
19013 getSplitter: function(/*String*/region){
19015 // Returns the widget responsible for rendering the splitter associated with region
19016 var splitter = this._splitters[region];
19017 return splitter ? dijit.byNode(splitter) : null;
19020 resize: function(newSize, currentSize){
19021 // Overrides _LayoutWidget.resize().
19023 // resetting potential padding to 0px to provide support for 100% width/height + padding
19024 // TODO: this hack doesn't respect the box model and is a temporary fix
19025 if(!this.cs || !this.pe){
19026 var node = this.domNode;
19027 this.cs = dojo.getComputedStyle(node);
19028 this.pe = dojo._getPadExtents(node, this.cs);
19029 this.pe.r = dojo._toPixelValue(node, this.cs.paddingRight);
19030 this.pe.b = dojo._toPixelValue(node, this.cs.paddingBottom);
19032 dojo.style(node, "padding
", "0px
");
19035 this.inherited(arguments);
19038 _layoutChildren: function(/*String?*/changedRegion, /*Number?*/ changedRegionSize){
19040 // This is the main routine for setting size/position of each child.
19042 // With no arguments, measures the height of top/bottom panes, the width
19043 // of left/right panes, and then sizes all panes accordingly.
19045 // With changedRegion specified (as "left
", "top
", "bottom
", or "right
"),
19046 // it changes that region's width/height to changedRegionSize and
19047 // then resizes other regions that were affected.
19049 // The region should be changed because splitter was dragged.
19050 // "left
", "right
", "top
", or "bottom
".
19051 // changedRegionSize:
19052 // The new width/height (in pixels) to make changedRegion
19054 if(!this._borderBox || !this._borderBox.h){
19055 // We are currently hidden, or we haven't been sized by our parent yet.
19056 // Abort. Someone will resize us later.
19060 var sidebarLayout = (this.design == "sidebar
");
19061 var topHeight = 0, bottomHeight = 0, leftWidth = 0, rightWidth = 0;
19062 var topStyle = {}, leftStyle = {}, rightStyle = {}, bottomStyle = {},
19063 centerStyle = (this._center && this._center.style) || {};
19065 var changedSide = /left|right/.test(changedRegion);
19067 var layoutSides = !changedRegion || (!changedSide && !sidebarLayout);
19068 var layoutTopBottom = !changedRegion || (changedSide && sidebarLayout);
19070 // Ask browser for width/height of side panes.
19071 // Would be nice to cache this but height can change according to width
19072 // (because words wrap around). I don't think width will ever change though
19073 // (except when the user drags a splitter).
19075 topStyle = (changedRegion == "top
" || layoutTopBottom) && this._top.style;
19076 topHeight = changedRegion == "top
" ? changedRegionSize : dojo.marginBox(this._top).h;
19079 leftStyle = (changedRegion == "left
" || layoutSides) && this._left.style;
19080 leftWidth = changedRegion == "left
" ? changedRegionSize : dojo.marginBox(this._left).w;
19083 rightStyle = (changedRegion == "right
" || layoutSides) && this._right.style;
19084 rightWidth = changedRegion == "right
" ? changedRegionSize : dojo.marginBox(this._right).w;
19087 bottomStyle = (changedRegion == "bottom
" || layoutTopBottom) && this._bottom.style;
19088 bottomHeight = changedRegion == "bottom
" ? changedRegionSize : dojo.marginBox(this._bottom).h;
19091 var splitters = this._splitters;
19092 var topSplitter = splitters.top, bottomSplitter = splitters.bottom,
19093 leftSplitter = splitters.left, rightSplitter = splitters.right;
19094 var splitterThickness = this._splitterThickness;
19095 var topSplitterThickness = splitterThickness.top || 0,
19096 leftSplitterThickness = splitterThickness.left || 0,
19097 rightSplitterThickness = splitterThickness.right || 0,
19098 bottomSplitterThickness = splitterThickness.bottom || 0;
19100 // Check for race condition where CSS hasn't finished loading, so
19101 // the splitter width == the viewport width (#5824)
19102 if(leftSplitterThickness > 50 || rightSplitterThickness > 50){
19103 setTimeout(dojo.hitch(this, function(){
19104 // Results are invalid. Clear them out.
19105 this._splitterThickness = {};
19107 for(var region in this._splitters){
19108 this._computeSplitterThickness(region);
19110 this._layoutChildren();
19117 var splitterBounds = {
19118 left: (sidebarLayout ? leftWidth + leftSplitterThickness: 0) + pe.l + "px
",
19119 right: (sidebarLayout ? rightWidth + rightSplitterThickness: 0) + pe.r + "px
"
19123 dojo.mixin(topSplitter.style, splitterBounds);
19124 topSplitter.style.top = topHeight + pe.t + "px
";
19127 if(bottomSplitter){
19128 dojo.mixin(bottomSplitter.style, splitterBounds);
19129 bottomSplitter.style.bottom = bottomHeight + pe.b + "px
";
19133 top: (sidebarLayout ? 0 : topHeight + topSplitterThickness) + pe.t + "px
",
19134 bottom: (sidebarLayout ? 0 : bottomHeight + bottomSplitterThickness) + pe.b + "px
"
19138 dojo.mixin(leftSplitter.style, splitterBounds);
19139 leftSplitter.style.left = leftWidth + pe.l + "px
";
19143 dojo.mixin(rightSplitter.style, splitterBounds);
19144 rightSplitter.style.right = rightWidth + pe.r + "px
";
19147 dojo.mixin(centerStyle, {
19148 top: pe.t + topHeight + topSplitterThickness + "px
",
19149 left: pe.l + leftWidth + leftSplitterThickness + "px
",
19150 right: pe.r + rightWidth + rightSplitterThickness + "px
",
19151 bottom: pe.b + bottomHeight + bottomSplitterThickness + "px
"
19155 top: sidebarLayout ? pe.t + "px
" : centerStyle.top,
19156 bottom: sidebarLayout ? pe.b + "px
" : centerStyle.bottom
19158 dojo.mixin(leftStyle, bounds);
19159 dojo.mixin(rightStyle, bounds);
19160 leftStyle.left = pe.l + "px
"; rightStyle.right = pe.r + "px
"; topStyle.top = pe.t + "px
"; bottomStyle.bottom = pe.b + "px
";
19162 topStyle.left = bottomStyle.left = leftWidth + leftSplitterThickness + pe.l + "px
";
19163 topStyle.right = bottomStyle.right = rightWidth + rightSplitterThickness + pe.r + "px
";
19165 topStyle.left = bottomStyle.left = pe.l + "px
";
19166 topStyle.right = bottomStyle.right = pe.r + "px
";
19169 // More calculations about sizes of panes
19170 var containerHeight = this._borderBox.h - pe.t - pe.b,
19171 middleHeight = containerHeight - ( topHeight + topSplitterThickness + bottomHeight + bottomSplitterThickness),
19172 sidebarHeight = sidebarLayout ? containerHeight : middleHeight;
19174 var containerWidth = this._borderBox.w - pe.l - pe.r,
19175 middleWidth = containerWidth - (leftWidth + leftSplitterThickness + rightWidth + rightSplitterThickness),
19176 sidebarWidth = sidebarLayout ? middleWidth : containerWidth;
19178 // New margin-box size of each pane
19180 top: { w: sidebarWidth, h: topHeight },
19181 bottom: { w: sidebarWidth, h: bottomHeight },
19182 left: { w: leftWidth, h: sidebarHeight },
19183 right: { w: rightWidth, h: sidebarHeight },
19184 center: { h: middleHeight, w: middleWidth }
19188 // Respond to splitter drag event by changing changedRegion's width or height
19189 var child = this["_
" + changedRegion + "Widget
"],
19191 mb[ /top|bottom/.test(changedRegion) ? "h
" : "w
"] = changedRegionSize;
19192 child.resize ? child.resize(mb, dim[child.region]) : dojo.marginBox(child.domNode, mb);
19195 // Nodes in IE<8 don't respond to t/l/b/r, and TEXTAREA doesn't respond in any browser
19196 var janky = dojo.isIE < 8 || (dojo.isIE && dojo.isQuirks) || dojo.some(this.getChildren(), function(child){
19197 return child.domNode.tagName == "TEXTAREA
" || child.domNode.tagName == "INPUT
";
19200 // Set the size of the children the old fashioned way, by setting
19201 // CSS width and height
19203 var resizeWidget = function(widget, changes, result){
19205 (widget.resize ? widget.resize(changes, result) : dojo.marginBox(widget.domNode, changes));
19209 if(leftSplitter){ leftSplitter.style.height = sidebarHeight; }
19210 if(rightSplitter){ rightSplitter.style.height = sidebarHeight; }
19211 resizeWidget(this._leftWidget, {h: sidebarHeight}, dim.left);
19212 resizeWidget(this._rightWidget, {h: sidebarHeight}, dim.right);
19214 if(topSplitter){ topSplitter.style.width = sidebarWidth; }
19215 if(bottomSplitter){ bottomSplitter.style.width = sidebarWidth; }
19216 resizeWidget(this._topWidget, {w: sidebarWidth}, dim.top);
19217 resizeWidget(this._bottomWidget, {w: sidebarWidth}, dim.bottom);
19219 resizeWidget(this._centerWidget, dim.center);
19221 // Calculate which panes need a notification that their size has been changed
19222 // (we've already set style.top/bottom/left/right on those other panes).
19223 var notifySides = !changedRegion || (/top|bottom/.test(changedRegion) && this.design != "sidebar
"),
19224 notifyTopBottom = !changedRegion || (/left|right/.test(changedRegion) && this.design == "sidebar
"),
19228 right: notifySides,
19229 top: notifyTopBottom,
19230 bottom: notifyTopBottom
19233 // Send notification to those panes that have changed size
19234 dojo.forEach(this.getChildren(), function(child){
19235 if(child.resize && notifyList[child.region]){
19236 child.resize(null, dim[child.region]);
19242 destroy: function(){
19243 for(var region in this._splitters){
19244 var splitter = this._splitters[region];
19245 dijit.byNode(splitter).destroy();
19246 dojo.destroy(splitter);
19248 delete this._splitters;
19249 delete this._splitterThickness;
19250 this.inherited(arguments);
19254 // This argument can be specified for the children of a BorderContainer.
19255 // Since any widget can be specified as a LayoutContainer child, mix it
19256 // into the base widget class. (This is a hack, but it's effective.)
19257 dojo.extend(dijit._Widget, {
19258 // region: [const] String
19259 // Parameter for children of `dijit.layout.BorderContainer`.
19260 // Values: "top
", "bottom
", "leading
", "trailing
", "left
", "right
", "center
".
19261 // See the `dijit.layout.BorderContainer` description for details.
19264 // splitter: [const] Boolean
19265 // Parameter for child of `dijit.layout.BorderContainer` where region != "center
".
19266 // If true, enables user to resize the widget by putting a draggable splitter between
19267 // this widget and the region=center widget.
19270 // minSize: [const] Number
19271 // Parameter for children of `dijit.layout.BorderContainer`.
19272 // Specifies a minimum size (in pixels) for this widget when resized by a splitter.
19275 // maxSize: [const] Number
19276 // Parameter for children of `dijit.layout.BorderContainer`.
19277 // Specifies a maximum size (in pixels) for this widget when resized by a splitter.
19283 dojo.declare("dijit
.layout
._Splitter
", [ dijit._Widget, dijit._Templated ],
19286 // A draggable spacer between two items in a `dijit.layout.BorderContainer`.
19288 // This is instantiated by `dijit.layout.BorderContainer`. Users should not
19289 // create it directly.
19294 // container: [const] dijit.layout.BorderContainer
19295 // Pointer to the parent BorderContainer
19298 // child: [const] dijit.layout._LayoutWidget
19299 // Pointer to the pane associated with this splitter
19303 // Region of pane associated with this splitter.
19304 // "top
", "bottom
", "left
", "right
".
19308 // live: [const] Boolean
19309 // If true, the child's size changes and the child widget is redrawn as you drag the splitter;
19310 // otherwise, the size doesn't change until you drop the splitter (by mouse-up)
19313 templateString: '<div class="dijitSplitter
" dojoAttachEvent="onkeypress
:_onKeyPress
,onmousedown
:_startDrag
,onmouseenter
:_onMouse
,onmouseleave
:_onMouse
" tabIndex="0" waiRole="separator
"><div class="dijitSplitterThumb
"></div></div>',
19315 postCreate: function(){
19316 this.inherited(arguments);
19317 this.horizontal = /top|bottom/.test(this.region);
19318 dojo.addClass(this.domNode, "dijitSplitter
" + (this.horizontal ? "H
" : "V
"));
19319 // dojo.addClass(this.child.domNode, "dijitSplitterPane
");
19320 // dojo.setSelectable(this.domNode, false); //TODO is this necessary?
19322 this._factor = /top|left/.test(this.region) ? 1 : -1;
19324 this._cookieName = this.container.id + "_
" + this.region;
19325 if(this.container.persist){
19326 // restore old size
19327 var persistSize = dojo.cookie(this._cookieName);
19329 this.child.domNode.style[this.horizontal ? "height
" : "width
"] = persistSize;
19334 _computeMaxSize: function(){
19336 // Compute the maximum size that my corresponding pane can be set to
19338 var dim = this.horizontal ? 'h' : 'w',
19339 thickness = this.container._splitterThickness[this.region];
19341 // Get DOMNode of opposite pane, if an opposite pane exists.
19342 // Ex: if I am the _Splitter for the left pane, then get the right pane.
19343 var flip = {left:'right', right:'left', top:'bottom', bottom:'top', leading:'trailing', trailing:'leading'},
19344 oppNode = this.container["_
" + flip[this.region]];
19346 // I can expand up to the edge of the opposite pane, or if there's no opposite pane, then to
19347 // edge of BorderContainer
19348 var available = dojo.contentBox(this.container.domNode)[dim] -
19349 (oppNode ? dojo.marginBox(oppNode)[dim] : 0) -
19350 20 - thickness * 2;
19352 return Math.min(this.child.maxSize, available);
19355 _startDrag: function(e){
19357 this.cover = dojo.doc.createElement('div');
19358 dojo.addClass(this.cover, "dijitSplitterCover
");
19359 dojo.place(this.cover, this.child.domNode, "after
");
19361 dojo.addClass(this.cover, "dijitSplitterCoverActive
");
19363 // Safeguard in case the stop event was missed. Shouldn't be necessary if we always get the mouse up.
19364 if(this.fake){ dojo.destroy(this.fake); }
19365 if(!(this._resize = this.live)){ //TODO: disable live for IE6?
19366 // create fake splitter to display at old position while we drag
19367 (this.fake = this.domNode.cloneNode(true)).removeAttribute("id
");
19368 dojo.addClass(this.domNode, "dijitSplitterShadow
");
19369 dojo.place(this.fake, this.domNode, "after
");
19371 dojo.addClass(this.domNode, "dijitSplitterActive
");
19372 dojo.addClass(this.domNode, "dijitSplitter
" + (this.horizontal ? "H
" : "V
") + "Active
");
19374 dojo.removeClass(this.fake, "dijitSplitterHover
");
19375 dojo.removeClass(this.fake, "dijitSplitter
" + (this.horizontal ? "H
" : "V
") + "Hover
");
19378 //Performance: load data info local vars for onmousevent function closure
19379 var factor = this._factor,
19380 max = this._computeMaxSize(),
19381 min = this.child.minSize || 20,
19382 isHorizontal = this.horizontal,
19383 axis = isHorizontal ? "pageY
" : "pageX
",
19384 pageStart = e[axis],
19385 splitterStyle = this.domNode.style,
19386 dim = isHorizontal ? 'h' : 'w',
19387 childStart = dojo.marginBox(this.child.domNode)[dim],
19388 region = this.region,
19389 splitterStart = parseInt(this.domNode.style[region], 10),
19390 resize = this._resize,
19391 childNode = this.child.domNode,
19392 layoutFunc = dojo.hitch(this.container, this.container._layoutChildren),
19395 this._handlers = (this._handlers || []).concat([
19396 dojo.connect(de, "onmousemove
", this._drag = function(e, forceResize){
19397 var delta = e[axis] - pageStart,
19398 childSize = factor * delta + childStart,
19399 boundChildSize = Math.max(Math.min(childSize, max), min);
19401 if(resize || forceResize){
19402 layoutFunc(region, boundChildSize);
19404 splitterStyle[region] = factor * delta + splitterStart + (boundChildSize - childSize) + "px
";
19406 dojo.connect(de, "ondragstart
", dojo.stopEvent),
19407 dojo.connect(dojo.body(), "onselectstart
", dojo.stopEvent),
19408 dojo.connect(de, "onmouseup
", this, "_stopDrag
")
19413 _onMouse: function(e){
19414 var o = (e.type == "mouseover
" || e.type == "mouseenter
");
19415 dojo.toggleClass(this.domNode, "dijitSplitterHover
", o);
19416 dojo.toggleClass(this.domNode, "dijitSplitter
" + (this.horizontal ? "H
" : "V
") + "Hover
", o);
19419 _stopDrag: function(e){
19422 dojo.removeClass(this.cover, "dijitSplitterCoverActive
");
19424 if(this.fake){ dojo.destroy(this.fake); }
19425 dojo.removeClass(this.domNode, "dijitSplitterActive
");
19426 dojo.removeClass(this.domNode, "dijitSplitter
" + (this.horizontal ? "H
" : "V
") + "Active
");
19427 dojo.removeClass(this.domNode, "dijitSplitterShadow
");
19428 this._drag(e); //TODO: redundant with onmousemove?
19429 this._drag(e, true);
19431 this._cleanupHandlers();
19435 if(this.container.persist){
19436 dojo.cookie(this._cookieName, this.child.domNode.style[this.horizontal ? "height
" : "width
"], {expires:365});
19440 _cleanupHandlers: function(){
19441 dojo.forEach(this._handlers, dojo.disconnect);
19442 delete this._handlers;
19445 _onKeyPress: function(/*Event*/ e){
19446 // should we apply typematic to this?
19447 this._resize = true;
19448 var horizontal = this.horizontal;
19450 var dk = dojo.keys;
19451 switch(e.charOrCode){
19452 case horizontal ? dk.UP_ARROW : dk.LEFT_ARROW:
19455 case horizontal ? dk.DOWN_ARROW : dk.RIGHT_ARROW:
19458 // this.inherited(arguments);
19461 var childSize = dojo.marginBox(this.child.domNode)[ horizontal ? 'h' : 'w' ] + this._factor * tick;
19462 this.container._layoutChildren(this.region, Math.max(Math.min(childSize, this._computeMaxSize()), this.child.minSize));
19466 destroy: function(){
19467 this._cleanupHandlers();
19469 delete this.container;
19472 this.inherited(arguments);
19476 dojo.declare("dijit
.layout
._Gutter
", [dijit._Widget, dijit._Templated ],
19479 // Just a spacer div to separate side pane from center pane.
19480 // Basically a trick to lookup the gutter/splitter width from the theme.
19482 // Instantiated by `dijit.layout.BorderContainer`. Users should not
19483 // create directly.
19487 templateString: '<div class="dijitGutter
" waiRole="presentation
"></div>',
19489 postCreate: function(){
19490 this.horizontal = /top|bottom/.test(this.region);
19491 dojo.addClass(this.domNode, "dijitGutter
" + (this.horizontal ? "H
" : "V
"));
19497 if(!dojo._hasResource["dijit
.layout
._TabContainerBase
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
19498 dojo._hasResource["dijit
.layout
._TabContainerBase
"] = true;
19499 dojo.provide("dijit
.layout
._TabContainerBase
");
19504 dojo.declare("dijit
.layout
._TabContainerBase
",
19505 [dijit.layout.StackContainer, dijit._Templated],
19508 // Abstract base class for TabContainer. Must define _makeController() to instantiate
19509 // and return the widget that displays the tab labels
19511 // A TabContainer is a container that has multiple panes, but shows only
19512 // one pane at a time. There are a set of tabs corresponding to each pane,
19513 // where each tab has the name (aka title) of the pane, and optionally a close button.
19515 // tabPosition: String
19516 // Defines where tabs go relative to tab content.
19517 // "top
", "bottom
", "left
-h
", "right
-h
"
19518 tabPosition: "top
",
19520 baseClass: "dijitTabContainer
",
19522 // tabStrip: Boolean
19523 // Defines whether the tablist gets an extra class for layouting, putting a border/shading
19524 // around the set of tabs.
19528 // If true, use styling for a TabContainer nested inside another TabContainer.
19529 // For tundra etc., makes tabs look like links, and hides the outer
19530 // border since the outer TabContainer already has a border.
19533 templateString: dojo.cache("dijit
.layout
", "templates
/TabContainer.html", "<div class=\"dijitTabContainer\">\n\t<div class=\"dijitTabListWrapper\" dojoAttachPoint=\"tablistNode\"></div>\n\t<div dojoAttachPoint
=\"tablistSpacer
\" class=\"dijitTabSpacer ${baseClass}
-spacer
\"></div>\n\t<div class=\"dijitTabPaneWrapper ${baseClass}-container\" dojoAttachPoint=\"containerNode\"></div>\n</div
>\n"),
19535 postMixInProperties: function(){
19536 // set class name according to tab position, ex: dijitTabContainerTop
19537 this.baseClass += this.tabPosition.charAt(0).toUpperCase() + this.tabPosition.substr(1).replace(/-.*/, "");
19539 this.srcNodeRef && dojo.style(this.srcNodeRef, "visibility
", "hidden
");
19541 this.inherited(arguments);
19544 postCreate: function(){
19545 this.inherited(arguments);
19547 // Create the tab list that will have a tab (a.k.a. tab button) for each tab panel
19548 this.tablist = this._makeController(this.tablistNode);
19550 if(!this.doLayout){ dojo.addClass(this.domNode, "dijitTabContainerNoLayout
"); }
19553 /* workaround IE's lack of support for "a
> b
" selectors by
19554 * tagging each node in the template.
19556 dojo.addClass(this.domNode, "dijitTabContainerNested
");
19557 dojo.addClass(this.tablist.containerNode, "dijitTabContainerTabListNested
");
19558 dojo.addClass(this.tablistSpacer, "dijitTabContainerSpacerNested
");
19559 dojo.addClass(this.containerNode, "dijitTabPaneWrapperNested
");
19561 dojo.addClass(this.domNode, "tabStrip
-" + (this.tabStrip ? "enabled
" : "disabled
"));
19565 _setupChild: function(/*dijit._Widget*/ tab){
19566 // Overrides StackContainer._setupChild().
19567 dojo.addClass(tab.domNode, "dijitTabPane
");
19568 this.inherited(arguments);
19571 startup: function(){
19572 if(this._started){ return; }
19574 // wire up the tablist and its tabs
19575 this.tablist.startup();
19577 this.inherited(arguments);
19580 layout: function(){
19581 // Overrides StackContainer.layout().
19582 // Configure the content pane to take up all the space except for where the tabs are
19584 if(!this._contentBox || typeof(this._contentBox.l) == "undefined"){return;}
19586 var sc = this.selectedChildWidget;
19589 // position and size the titles and the container node
19590 var titleAlign = this.tabPosition.replace(/-h/, "");
19591 this.tablist.layoutAlign = titleAlign;
19592 var children = [this.tablist, {
19593 domNode: this.tablistSpacer,
19594 layoutAlign: titleAlign
19596 domNode: this.containerNode,
19597 layoutAlign: "client
"
19599 dijit.layout.layoutChildren(this.domNode, this._contentBox, children);
19601 // Compute size to make each of my children.
19602 // children[2] is the margin-box size of this.containerNode, set by layoutChildren() call above
19603 this._containerContentBox = dijit.layout.marginBox2contentBox(this.containerNode, children[2]);
19605 if(sc && sc.resize){
19606 sc.resize(this._containerContentBox);
19609 // just layout the tab controller, so it can position left/right buttons etc.
19610 if(this.tablist.resize){
19611 this.tablist.resize({w: dojo.contentBox(this.domNode).w});
19614 // and call resize() on the selected pane just to tell it that it's been made visible
19615 if(sc && sc.resize){
19621 destroy: function(){
19623 this.tablist.destroy();
19625 this.inherited(arguments);
19632 if(!dojo._hasResource["dijit
.layout
.TabController
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
19633 dojo._hasResource["dijit
.layout
.TabController
"] = true;
19634 dojo.provide("dijit
.layout
.TabController
");
19638 // Menu is used for an accessible close button, would be nice to have a lighter-weight solution
19644 dojo.declare("dijit
.layout
.TabController
",
19645 dijit.layout.StackController,
19648 // Set of tabs (the things with titles and a close button, that you click to show a tab panel).
19649 // Used internally by `dijit.layout.TabContainer`.
19651 // Lets the user select the currently shown pane in a TabContainer or StackContainer.
19652 // TabController also monitors the TabContainer, and whenever a pane is
19653 // added or deleted updates itself accordingly.
19657 templateString: "<div wairole
='tablist' dojoAttachEvent
='onkeypress:onkeypress'></div
>",
19659 // tabPosition: String
19660 // Defines where tabs go relative to the content.
19661 // "top
", "bottom
", "left
-h
", "right
-h
"
19662 tabPosition: "top
",
19664 // buttonWidget: String
19665 // The name of the tab widget to create to correspond to each page
19666 buttonWidget: "dijit
.layout
._TabButton
",
19668 _rectifyRtlTabList: function(){
19670 // For left/right TabContainer when page is RTL mode, rectify the width of all tabs to be equal, otherwise the tab widths are different in IE
19672 if(0 >= this.tabPosition.indexOf('-h')){ return; }
19673 if(!this.pane2button){ return; }
19676 for(var pane in this.pane2button){
19677 var ow = this.pane2button[pane].innerDiv.scrollWidth;
19678 maxWidth = Math.max(maxWidth, ow);
19680 //unify the length of all the tabs
19681 for(pane in this.pane2button){
19682 this.pane2button[pane].innerDiv.style.width = maxWidth + 'px';
19687 dojo.declare("dijit
.layout
._TabButton
",
19688 dijit.layout._StackButton,
19691 // A tab (the thing you click to select a pane).
19693 // Contains the title of the pane, and optionally a close-button to destroy the pane.
19694 // This is an internal widget and should not be instantiated directly.
19698 // baseClass: String
19699 // The CSS class applied to the domNode.
19700 baseClass: "dijitTab
",
19702 // Apply dijitTabCloseButtonHover when close button is hovered
19704 closeNode: "dijitTabCloseButton
"
19707 templateString: dojo.cache("dijit
.layout
", "templates
/_TabButton.html", "<div waiRole=\"presentation\" dojoAttachPoint=\"titleNode\" dojoAttachEvent='onclick:onClick'>\n <div waiRole=\"presentation\" class='dijitTabInnerDiv' dojoAttachPoint='innerDiv'>\n <div waiRole=\"presentation\" class='dijitTabContent' dojoAttachPoint='tabContent'>\n \t<div waiRole=\"presentation\" dojoAttachPoint='focusNode'>\n\t\t <img src=\"${_blankGif}\" alt=\"\" class=\"dijitIcon\" dojoAttachPoint='iconNode' />\n\t\t <span dojoAttachPoint
='containerNode' class='tabLabel'></span>\n\t\t <span class=\"dijitInline dijitTabCloseButton dijitTabCloseIcon\" dojoAttachPoint='closeNode'\n\t\t \t\tdojoAttachEvent='onclick: onClickCloseButton' waiRole=\"presentation\">\n\t\t <span dojoAttachPoint='closeText' class='dijitTabCloseText'>x</span\n\t\t ></span>\n\t\t\t</div>\n </div>\n </div>\n</div
>\n"),
19709 // Override _FormWidget.scrollOnFocus.
19710 // Don't scroll the whole tab container into view when the button is focused.
19711 scrollOnFocus: false,
19713 postMixInProperties: function(){
19714 // Override blank iconClass from Button to do tab height adjustment on IE6,
19715 // to make sure that tabs with and w/out close icons are same height
19716 if(!this.iconClass){
19717 this.iconClass = "dijitTabButtonIcon
";
19721 postCreate: function(){
19722 this.inherited(arguments);
19723 dojo.setSelectable(this.containerNode, false);
19725 // If a custom icon class has not been set for the
19726 // tab icon, set its width to one pixel. This ensures
19727 // that the height styling of the tab is maintained,
19728 // as it is based on the height of the icon.
19729 // TODO: I still think we can just set dijitTabButtonIcon to 1px in CSS <Bill>
19730 if(this.iconNode.className == "dijitTabButtonIcon
"){
19731 dojo.style(this.iconNode, "width
", "1px
");
19735 startup: function(){
19736 this.inherited(arguments);
19737 var n = this.domNode;
19739 // Required to give IE6 a kick, as it initially hides the
19740 // tabs until they are focused on.
19741 setTimeout(function(){
19742 n.className = n.className;
19746 _setCloseButtonAttr: function(disp){
19747 this.closeButton = disp;
19748 dojo.toggleClass(this.innerDiv, "dijitClosable
", disp);
19749 this.closeNode.style.display = disp ? "" : "none
";
19751 var _nlsResources = dojo.i18n.getLocalization("dijit
", "common
");
19752 if(this.closeNode){
19753 dojo.attr(this.closeNode,"title
", _nlsResources.itemClose);
19755 // add context menu onto title button
19756 var _nlsResources = dojo.i18n.getLocalization("dijit
", "common
");
19757 this._closeMenu = new dijit.Menu({
19758 id: this.id+"_Menu
",
19761 targetNodeIds: [this.domNode]
19764 this._closeMenu.addChild(new dijit.MenuItem({
19765 label: _nlsResources.itemClose,
19768 onClick: dojo.hitch(this, "onClickCloseButton
")
19771 if(this._closeMenu){
19772 this._closeMenu.destroyRecursive();
19773 delete this._closeMenu;
19777 _setLabelAttr: function(/*String*/ content){
19779 // Hook for attr('label', ...) to work.
19781 // takes an HTML string.
19782 // Inherited ToggleButton implementation will Set the label (text) of the button;
19783 // Need to set the alt attribute of icon on tab buttons if no label displayed
19784 this.inherited(arguments);
19785 if(this.showLabel == false && !this.params.title){
19786 this.iconNode.alt = dojo.trim(this.containerNode.innerText || this.containerNode.textContent || '');
19790 destroy: function(){
19791 if(this._closeMenu){
19792 this._closeMenu.destroyRecursive();
19793 delete this._closeMenu;
19795 this.inherited(arguments);
19801 if(!dojo._hasResource["dijit
.layout
.ScrollingTabController
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
19802 dojo._hasResource["dijit
.layout
.ScrollingTabController
"] = true;
19803 dojo.provide("dijit
.layout
.ScrollingTabController
");
19808 dojo.declare("dijit
.layout
.ScrollingTabController
",
19809 dijit.layout.TabController,
19812 // Set of tabs with left/right arrow keys and a menu to switch between tabs not
19813 // all fitting on a single row.
19814 // Works only for horizontal tabs (either above or below the content, not to the left
19819 templateString: dojo.cache("dijit
.layout
", "templates
/ScrollingTabController.html", "<div class=\"dijitTabListContainer-${tabPosition}\" style=\"visibility:hidden\">\n\t<div dojoType=\"dijit.layout._ScrollingTabControllerButton\"\n\t\t\tclass=\"tabStripButton-${tabPosition}\"\n\t\t\tid=\"${id}_menuBtn\" iconClass=\"dijitTabStripMenuIcon\"\n\t\t\tdojoAttachPoint=\"_menuBtn\" showLabel=false>▼</div>\n\t<div dojoType
=\"dijit
.layout
._ScrollingTabControllerButton
\"\n\t\t\tclass=\"tabStripButton
-${tabPosition}
\"\n\t\t\tid=\"${id}_leftBtn
\" iconClass
=\"dijitTabStripSlideLeftIcon
\"\n\t\t\tdojoAttachPoint=\"_leftBtn
\" dojoAttachEvent
=\"onClick
: doSlideLeft
\" showLabel
=false>◀</div>\n\t<div dojoType=\"dijit.layout._ScrollingTabControllerButton\"\n\t\t\tclass=\"tabStripButton-${tabPosition}\"\n\t\t\tid=\"${id}_rightBtn\" iconClass=\"dijitTabStripSlideRightIcon\"\n\t\t\tdojoAttachPoint=\"_rightBtn\" dojoAttachEvent=\"onClick: doSlideRight\" showLabel=false>▶</div>\n\t<div
class='dijitTabListWrapper' dojoAttachPoint
='tablistWrapper'>\n\t\t<div wairole
='tablist' dojoAttachEvent
='onkeypress:onkeypress'\n\t\t\t\tdojoAttachPoint='containerNode' class='nowrapTabStrip'></div>\n\t</div>\n</div
>\n"),
19821 // useMenu:[const] Boolean
19822 // True if a menu should be used to select tabs when they are too
19823 // wide to fit the TabContainer, false otherwise.
19826 // useSlider: [const] Boolean
19827 // True if a slider should be used to select tabs when they are too
19828 // wide to fit the TabContainer, false otherwise.
19831 // tabStripClass: String
19832 // The css class to apply to the tab strip, if it is visible.
19835 widgetsInTemplate: true,
19837 // _minScroll: Number
19838 // The distance in pixels from the edge of the tab strip which,
19839 // if a scroll animation is less than, forces the scroll to
19840 // go all the way to the left/right.
19843 attributeMap: dojo.delegate(dijit._Widget.prototype.attributeMap, {
19844 "class": "containerNode
"
19847 postCreate: function(){
19848 this.inherited(arguments);
19849 var n = this.domNode;
19851 this.scrollNode = this.tablistWrapper;
19852 this._initButtons();
19854 if(!this.tabStripClass){
19855 this.tabStripClass = "dijitTabContainer
" +
19856 this.tabPosition.charAt(0).toUpperCase() +
19857 this.tabPosition.substr(1).replace(/-.*/, "") +
19859 dojo.addClass(n, "tabStrip
-disabled
")
19862 dojo.addClass(this.tablistWrapper, this.tabStripClass);
19865 onStartup: function(){
19866 this.inherited(arguments);
19868 // Do not show the TabController until the related
19869 // StackController has added it's children. This gives
19870 // a less visually jumpy instantiation.
19871 dojo.style(this.domNode, "visibility
", "visible
");
19872 this._postStartup = true;
19875 onAddChild: function(page, insertIndex){
19876 this.inherited(arguments);
19879 var containerId = this.containerId;
19880 menuItem = new dijit.MenuItem({
19881 id: page.id + "_stcMi
",
19885 onClick: dojo.hitch(this, function(){
19886 var container = dijit.byId(containerId);
19887 container.selectChild(page);
19890 this._menuChildren[page.id] = menuItem;
19891 this._menu.addChild(menuItem, insertIndex);
19894 // update the menuItem label when the button label is updated
19895 this.pane2handles[page.id].push(
19896 this.connect(this.pane2button[page.id], "set", function(name, value){
19897 if(this._postStartup){
19898 if(name == "label
"){
19900 menuItem.set(name, value);
19903 // The changed label will have changed the width of the
19904 // buttons, so do a resize
19906 this.resize(this._dim);
19913 // Increment the width of the wrapper when a tab is added
19914 // This makes sure that the buttons never wrap.
19915 // The value 200 is chosen as it should be bigger than most
19916 // Tab button widths.
19917 dojo.style(this.containerNode, "width
",
19918 (dojo.style(this.containerNode, "width
") + 200) + "px
");
19921 onRemoveChild: function(page, insertIndex){
19922 // null out _selectedTab because we are about to delete that dom node
19923 var button = this.pane2button[page.id];
19924 if(this._selectedTab === button.domNode){
19925 this._selectedTab = null;
19928 // delete menu entry corresponding to pane that was removed from TabContainer
19929 if(this.useMenu && page && page.id && this._menuChildren[page.id]){
19930 this._menu.removeChild(this._menuChildren[page.id]);
19931 this._menuChildren[page.id].destroy();
19932 delete this._menuChildren[page.id];
19935 this.inherited(arguments);
19938 _initButtons: function(){
19940 // Creates the buttons used to scroll to view tabs that
19941 // may not be visible if the TabContainer is too narrow.
19942 this._menuChildren = {};
19944 // Make a list of the buttons to display when the tab labels become
19945 // wider than the TabContainer, and hide the other buttons.
19946 // Also gets the total width of the displayed buttons.
19947 this._btnWidth = 0;
19948 this._buttons = dojo.query("> .tabStripButton
", this.domNode).filter(function(btn){
19949 if((this.useMenu && btn == this._menuBtn.domNode) ||
19950 (this.useSlider && (btn == this._rightBtn.domNode || btn == this._leftBtn.domNode))){
19951 this._btnWidth += dojo.marginBox(btn).w;
19954 dojo.style(btn, "display
", "none
");
19960 // Create the menu that is used to select tabs.
19961 this._menu = new dijit.Menu({
19962 id: this.id + "_menu
",
19965 targetNodeIds: [this._menuBtn.domNode],
19966 leftClickToOpen: true,
19967 refocus: false // selecting a menu item sets focus to a TabButton
19969 this._supportingWidgets.push(this._menu);
19973 _getTabsWidth: function(){
19974 var children = this.getChildren();
19975 if(children.length){
19976 var leftTab = children[this.isLeftToRight() ? 0 : children.length - 1].domNode,
19977 rightTab = children[this.isLeftToRight() ? children.length - 1 : 0].domNode;
19978 return rightTab.offsetLeft + dojo.style(rightTab, "width
") - leftTab.offsetLeft;
19984 _enableBtn: function(width){
19986 // Determines if the tabs are wider than the width of the TabContainer, and
19987 // thus that we need to display left/right/menu navigation buttons.
19988 var tabsWidth = this._getTabsWidth();
19989 width = width || dojo.style(this.scrollNode, "width
");
19990 return tabsWidth > 0 && width < tabsWidth;
19993 resize: function(dim){
19995 // Hides or displays the buttons used to scroll the tab list and launch the menu
19996 // that selects tabs.
19998 if(this.domNode.offsetWidth == 0){
20002 // Save the dimensions to be used when a child is renamed.
20005 // Set my height to be my natural height (tall enough for one row of tab labels),
20006 // and my content-box width based on margin-box width specified in dim parameter.
20007 // But first reset scrollNode.height in case it was set by layoutChildren() call
20008 // in a previous run of this method.
20009 this.scrollNode.style.height = "auto
";
20010 this._contentBox = dijit.layout.marginBox2contentBox(this.domNode, {h: 0, w: dim.w});
20011 this._contentBox.h = this.scrollNode.offsetHeight;
20012 dojo.contentBox(this.domNode, this._contentBox);
20014 // Show/hide the left/right/menu navigation buttons depending on whether or not they
20016 var enable = this._enableBtn(this._contentBox.w);
20017 this._buttons.style("display
", enable ? "" : "none
");
20019 // Position and size the navigation buttons and the tablist
20020 this._leftBtn.layoutAlign = "left
";
20021 this._rightBtn.layoutAlign = "right
";
20022 this._menuBtn.layoutAlign = this.isLeftToRight() ? "right
" : "left
";
20023 dijit.layout.layoutChildren(this.domNode, this._contentBox,
20024 [this._menuBtn, this._leftBtn, this._rightBtn, {domNode: this.scrollNode, layoutAlign: "client
"}]);
20026 // set proper scroll so that selected tab is visible
20027 if(this._selectedTab){
20028 if(this._anim && this._anim.status() == "playing
"){
20031 var w = this.scrollNode,
20032 sl = this._convertToScrollLeft(this._getScrollForSelectedTab());
20036 // Enable/disabled left right buttons depending on whether or not user can scroll to left or right
20037 this._setButtonClass(this._getScroll());
20039 this._postResize = true;
20042 _getScroll: function(){
20044 // Returns the current scroll of the tabs where 0 means
20045 // "scrolled all the way to the left
" and some positive number, based on #
20046 // of pixels of possible scroll (ex: 1000) means "scrolled all the way to the right
"
20047 var sl = (this.isLeftToRight() || dojo.isIE < 8 || (dojo.isIE && dojo.isQuirks) || dojo.isWebKit) ? this.scrollNode.scrollLeft :
20048 dojo.style(this.containerNode, "width
") - dojo.style(this.scrollNode, "width
")
20049 + (dojo.isIE == 8 ? -1 : 1) * this.scrollNode.scrollLeft;
20053 _convertToScrollLeft: function(val){
20055 // Given a scroll value where 0 means "scrolled all the way to the left
"
20056 // and some positive number, based on # of pixels of possible scroll (ex: 1000)
20057 // means "scrolled all the way to the right
", return value to set this.scrollNode.scrollLeft
20058 // to achieve that scroll.
20060 // This method is to adjust for RTL funniness in various browsers and versions.
20061 if(this.isLeftToRight() || dojo.isIE < 8 || (dojo.isIE && dojo.isQuirks) || dojo.isWebKit){
20064 var maxScroll = dojo.style(this.containerNode, "width
") - dojo.style(this.scrollNode, "width
");
20065 return (dojo.isIE == 8 ? -1 : 1) * (val - maxScroll);
20069 onSelectChild: function(/*dijit._Widget*/ page){
20071 // Smoothly scrolls to a tab when it is selected.
20073 var tab = this.pane2button[page.id];
20074 if(!tab || !page){return;}
20076 // Scroll to the selected tab, except on startup, when scrolling is handled in resize()
20077 var node = tab.domNode;
20078 if(this._postResize && node != this._selectedTab){
20079 this._selectedTab = node;
20081 var sl = this._getScroll();
20083 if(sl > node.offsetLeft ||
20084 sl + dojo.style(this.scrollNode, "width
") <
20085 node.offsetLeft + dojo.style(node, "width
")){
20086 this.createSmoothScroll().play();
20090 this.inherited(arguments);
20093 _getScrollBounds: function(){
20095 // Returns the minimum and maximum scroll setting to show the leftmost and rightmost
20096 // tabs (respectively)
20097 var children = this.getChildren(),
20098 scrollNodeWidth = dojo.style(this.scrollNode, "width
"), // about 500px
20099 containerWidth = dojo.style(this.containerNode, "width
"), // 50,000px
20100 maxPossibleScroll = containerWidth - scrollNodeWidth, // scrolling until right edge of containerNode visible
20101 tabsWidth = this._getTabsWidth();
20103 if(children.length && tabsWidth > scrollNodeWidth){
20104 // Scrolling should happen
20106 min: this.isLeftToRight() ? 0 : children[children.length-1].domNode.offsetLeft,
20107 max: this.isLeftToRight() ?
20108 (children[children.length-1].domNode.offsetLeft + dojo.style(children[children.length-1].domNode, "width
")) - scrollNodeWidth :
20112 // No scrolling needed, all tabs visible, we stay either scrolled to far left or far right (depending on dir)
20113 var onlyScrollPosition = this.isLeftToRight() ? 0 : maxPossibleScroll;
20115 min: onlyScrollPosition,
20116 max: onlyScrollPosition
20121 _getScrollForSelectedTab: function(){
20123 // Returns the scroll value setting so that the selected tab
20124 // will appear in the center
20125 var w = this.scrollNode,
20126 n = this._selectedTab,
20127 scrollNodeWidth = dojo.style(this.scrollNode, "width
"),
20128 scrollBounds = this._getScrollBounds();
20130 // TODO: scroll minimal amount (to either right or left) so that
20131 // selected tab is fully visible, and just return if it's already visible?
20132 var pos = (n.offsetLeft + dojo.style(n, "width
")/2) - scrollNodeWidth/2;
20133 pos = Math.min(Math.max(pos, scrollBounds.min), scrollBounds.max);
20136 // If scrolling close to the left side or right side, scroll
20137 // all the way to the left or right. See this._minScroll.
20138 // (But need to make sure that doesn't scroll the tab out of view...)
20142 createSmoothScroll : function(x){
20144 // Creates a dojo._Animation object that smoothly scrolls the tab list
20145 // either to a fixed horizontal pixel value, or to the selected tab.
20147 // If an number argument is passed to the function, that horizontal
20148 // pixel position is scrolled to. Otherwise the currently selected
20149 // tab is scrolled to.
20151 // An optional pixel value to scroll to, indicating distance from left.
20153 // Calculate position to scroll to
20154 if(arguments.length > 0){
20155 // position specified by caller, just make sure it's within bounds
20156 var scrollBounds = this._getScrollBounds();
20157 x = Math.min(Math.max(x, scrollBounds.min), scrollBounds.max);
20159 // scroll to center the current tab
20160 x = this._getScrollForSelectedTab();
20163 if(this._anim && this._anim.status() == "playing
"){
20168 w = this.scrollNode,
20169 anim = new dojo._Animation({
20170 beforeBegin: function(){
20171 if(this.curve){ delete this.curve; }
20172 var oldS = w.scrollLeft,
20173 newS = self._convertToScrollLeft(x);
20174 anim.curve = new dojo._Line(oldS, newS);
20176 onAnimate: function(val){
20177 w.scrollLeft = val;
20182 // Disable/enable left/right buttons according to new scroll position
20183 this._setButtonClass(x);
20185 return anim; // dojo._Animation
20188 _getBtnNode: function(e){
20190 // Gets a button DOM node from a mouse click event.
20192 // The mouse click event.
20194 while(n && !dojo.hasClass(n, "tabStripButton
")){
20200 doSlideRight: function(e){
20202 // Scrolls the menu to the right.
20204 // The mouse click event.
20205 this.doSlide(1, this._getBtnNode(e));
20208 doSlideLeft: function(e){
20210 // Scrolls the menu to the left.
20212 // The mouse click event.
20213 this.doSlide(-1,this._getBtnNode(e));
20216 doSlide: function(direction, node){
20218 // Scrolls the tab list to the left or right by 75% of the widget width.
20220 // If the direction is 1, the widget scrolls to the right, if it is
20221 // -1, it scrolls to the left.
20223 if(node && dojo.hasClass(node, "dijitTabDisabled
")){return;}
20225 var sWidth = dojo.style(this.scrollNode, "width
");
20226 var d = (sWidth * 0.75) * direction;
20228 var to = this._getScroll() + d;
20230 this._setButtonClass(to);
20232 this.createSmoothScroll(to).play();
20235 _setButtonClass: function(scroll){
20237 // Disables the left scroll button if the tabs are scrolled all the way to the left,
20238 // or the right scroll button in the opposite case.
20240 // amount of horizontal scroll
20242 var scrollBounds = this._getScrollBounds();
20243 this._leftBtn.set("disabled
", scroll <= scrollBounds.min);
20244 this._rightBtn.set("disabled
", scroll >= scrollBounds.max);
20248 dojo.declare("dijit
.layout
._ScrollingTabControllerButton
",
20251 baseClass: "dijitTab tabStripButton
",
20253 templateString: dojo.cache("dijit
.layout
", "templates
/_ScrollingTabControllerButton.html", "<div dojoAttachEvent=\"onclick:_onButtonClick\">\n\t<div waiRole=\"presentation\" class=\"dijitTabInnerDiv\" dojoattachpoint=\"innerDiv,focusNode\">\n\t\t<div waiRole=\"presentation\" class=\"dijitTabContent dijitButtonContents\" dojoattachpoint=\"tabContent\">\n\t\t\t<img waiRole=\"presentation\" alt=\"\" src=\"${_blankGif}\" class=\"dijitTabStripIcon\" dojoAttachPoint=\"iconNode\"/>\n\t\t\t<span dojoAttachPoint
=\"containerNode
,titleNode
\" class=\"dijitButtonText
\"></span>\n\t\t</div>\n\t</div>\n</div>\n"),
20255 // Override inherited tabIndex: 0 from dijit.form.Button, because user shouldn't be
20256 // able to tab to the left/right/menu buttons
20263 if(!dojo._hasResource["dijit
.layout
.TabContainer
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
20264 dojo._hasResource["dijit
.layout
.TabContainer
"] = true;
20265 dojo.provide("dijit
.layout
.TabContainer
");
20271 dojo.declare("dijit
.layout
.TabContainer
",
20272 dijit.layout._TabContainerBase,
20275 // A Container with tabs to select each child (only one of which is displayed at a time).
20277 // A TabContainer is a container that has multiple panes, but shows only
20278 // one pane at a time. There are a set of tabs corresponding to each pane,
20279 // where each tab has the name (aka title) of the pane, and optionally a close button.
20281 // useMenu: [const] Boolean
20282 // True if a menu should be used to select tabs when they are too
20283 // wide to fit the TabContainer, false otherwise.
20286 // useSlider: [const] Boolean
20287 // True if a slider should be used to select tabs when they are too
20288 // wide to fit the TabContainer, false otherwise.
20291 // controllerWidget: String
20292 // An optional parameter to override the widget used to display the tab labels
20293 controllerWidget: "",
20295 _makeController: function(/*DomNode*/ srcNode){
20297 // Instantiate tablist controller widget and return reference to it.
20298 // Callback from _TabContainerBase.postCreate().
20300 // protected extension
20302 var cls = this.baseClass + "-tabs
" + (this.doLayout ? "" : " dijitTabNoLayout
"),
20303 TabController = dojo.getObject(this.controllerWidget);
20305 return new TabController({
20306 id: this.id + "_tablist
",
20309 tabPosition: this.tabPosition,
20310 doLayout: this.doLayout,
20311 containerId: this.id,
20313 nested: this.nested,
20314 useMenu: this.useMenu,
20315 useSlider: this.useSlider,
20316 tabStripClass: this.tabStrip ? this.baseClass + (this.tabStrip ? "":"No
") + "Strip
": null
20320 postMixInProperties: function(){
20321 this.inherited(arguments);
20323 // Scrolling controller only works for horizontal non-nested tabs
20324 if(!this.controllerWidget){
20325 this.controllerWidget = (this.tabPosition == "top
" || this.tabPosition == "bottom
") && !this.nested ?
20326 "dijit
.layout
.ScrollingTabController
" : "dijit
.layout
.TabController
";
20334 if(!dojo._hasResource["dojo
.number
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
20335 dojo._hasResource["dojo
.number
"] = true;
20336 dojo.provide("dojo
.number
");
20346 // summary: localized formatting and parsing routines for Number
20349 dojo.number.__FormatOptions = function(){
20350 // pattern: String?
20351 // override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
20352 // with this string. Default value is based on locale. Overriding this property will defeat
20353 // localization. Literal characters in patterns are not supported.
20355 // choose a format type based on the locale from the following:
20356 // decimal, scientific (not yet supported), percent, currency. decimal by default.
20358 // fixed number of decimal places to show. This overrides any
20359 // information in the provided pattern.
20361 // 5 rounds to nearest .5; 0 rounds to nearest whole (default). -1
20362 // means do not round.
20364 // override the locale used to determine formatting rules
20365 // fractional: Boolean?
20366 // If false, show no decimal places, overriding places and pattern settings.
20367 this.pattern = pattern;
20369 this.places = places;
20370 this.round = round;
20371 this.locale = locale;
20372 this.fractional = fractional;
20376 dojo.number.format = function(/*Number*/value, /*dojo.number.__FormatOptions?*/options){
20378 // Format a Number as a String, using locale-specific settings
20380 // Create a string from a Number using a known localized pattern.
20381 // Formatting patterns appropriate to the locale are chosen from the
20382 // [Common Locale Data Repository](http://unicode.org/cldr) as well as the appropriate symbols and
20384 // If value is Infinity, -Infinity, or is not a valid JavaScript number, return null.
20386 // the number to be formatted
20388 options = dojo.mixin({}, options || {});
20389 var locale = dojo.i18n.normalizeLocale(options.locale),
20390 bundle = dojo.i18n.getLocalization("dojo
.cldr
", "number
", locale);
20391 options.customs = bundle;
20392 var pattern = options.pattern || bundle[(options.type || "decimal") + "Format
"];
20393 if(isNaN(value) || Math.abs(value) == Infinity){ return null; } // null
20394 return dojo.number._applyPattern(value, pattern, options); // String
20397 //dojo.number._numberPatternRE = /(?:[#0]*,?)*[#0](?:\.0*#*)?/; // not precise, but good enough
20398 dojo.number._numberPatternRE = /[#0,]*[#0](?:\.0*#*)?/; // not precise, but good enough
20400 dojo.number._applyPattern = function(/*Number*/value, /*String*/pattern, /*dojo.number.__FormatOptions?*/options){
20402 // Apply pattern to format value as a string using options. Gives no
20403 // consideration to local customs.
20405 // the number to be formatted.
20407 // a pattern string as described by
20408 // [unicode.org TR35](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
20409 // options: dojo.number.__FormatOptions?
20410 // _applyPattern is usually called via `dojo.number.format()` which
20411 // populates an extra property in the options parameter, "customs
".
20412 // The customs object specifies group and decimal parameters if set.
20414 //TODO: support escapes
20415 options = options || {};
20416 var group = options.customs.group,
20417 decimal = options.customs.decimal,
20418 patternList = pattern.split(';'),
20419 positivePattern = patternList[0];
20420 pattern = patternList[(value < 0) ? 1 : 0] || ("-" + positivePattern);
20422 //TODO: only test against unescaped
20423 if(pattern.indexOf('%') != -1){
20425 }else if(pattern.indexOf('\u2030') != -1){
20426 value *= 1000; // per mille
20427 }else if(pattern.indexOf('\u00a4') != -1){
20428 group = options.customs.currencyGroup || group;//mixins instead?
20429 decimal = options.customs.currencyDecimal || decimal;// Should these be mixins instead?
20430 pattern = pattern.replace(/\u00a4{1,3}/, function(match){
20431 var prop = ["symbol
", "currency
", "displayName
"][match.length-1];
20432 return options[prop] || options.currency || "";
20434 }else if(pattern.indexOf('E') != -1){
20435 throw new Error("exponential notation not supported
");
20438 //TODO: support @ sig figs?
20439 var numberPatternRE = dojo.number._numberPatternRE;
20440 var numberPattern = positivePattern.match(numberPatternRE);
20441 if(!numberPattern){
20442 throw new Error("unable to find a number expression
in pattern
: "+pattern);
20444 if(options.fractional === false){ options.places = 0; }
20445 return pattern.replace(numberPatternRE,
20446 dojo.number._formatAbsolute(value, numberPattern[0], {decimal: decimal, group: group, places: options.places, round: options.round}));
20449 dojo.number.round = function(/*Number*/value, /*Number?*/places, /*Number?*/increment){
20451 // Rounds to the nearest value with the given number of decimal places, away from zero
20453 // Rounds to the nearest value with the given number of decimal places, away from zero if equal.
20454 // Similar to Number.toFixed(), but compensates for browser quirks. Rounding can be done by
20455 // fractional increments also, such as the nearest quarter.
20456 // NOTE: Subject to floating point errors. See dojox.math.round for experimental workaround.
20458 // The number to round
20460 // The number of decimal places where rounding takes place. Defaults to 0 for whole rounding.
20461 // Must be non-negative.
20463 // Rounds next place to nearest value of increment/10. 10 by default.
20465 // >>> dojo.number.round(-0.5)
20467 // >>> dojo.number.round(162.295, 2)
20468 // 162.29 // note floating point error. Should be 162.3
20469 // >>> dojo.number.round(10.71, 0, 2.5)
20471 var factor = 10 / (increment || 10);
20472 return (factor * +value).toFixed(places) / factor; // Number
20475 if((0.9).toFixed() == 0){
20476 // (isIE) toFixed() bug workaround: Rounding fails on IE when most significant digit
20477 // is just after the rounding place and is >=5
20479 var round = dojo.number.round;
20480 dojo.number.round = function(v, p, m){
20481 var d = Math.pow(10, -p || 0), a = Math.abs(v);
20482 if(!v || a >= d || a * Math.pow(10, p + 1) < 5){
20485 return round(v, p, m) + (v > 0 ? d : -d);
20491 dojo.number.__FormatAbsoluteOptions = function(){
20492 // decimal: String?
20493 // the decimal separator
20495 // the group separator
20496 // places: Number?|String?
20497 // number of decimal places. the range "n
,m
" will format to m places.
20499 // 5 rounds to nearest .5; 0 rounds to nearest whole (default). -1
20500 // means don't round.
20501 this.decimal = decimal;
20502 this.group = group;
20503 this.places = places;
20504 this.round = round;
20508 dojo.number._formatAbsolute = function(/*Number*/value, /*String*/pattern, /*dojo.number.__FormatAbsoluteOptions?*/options){
20510 // Apply numeric pattern to absolute value using options. Gives no
20511 // consideration to local customs.
20513 // the number to be formatted, ignores sign
20515 // the number portion of a pattern (e.g. `#,##0.00`)
20516 options = options || {};
20517 if(options.places === true){options.places=0;}
20518 if(options.places === Infinity){options.places=6;} // avoid a loop; pick a limit
20520 var patternParts = pattern.split("."),
20521 comma = typeof options.places == "string
" && options.places.indexOf(","),
20522 maxPlaces = options.places;
20524 maxPlaces = options.places.substring(comma + 1);
20525 }else if(!(maxPlaces >= 0)){
20526 maxPlaces = (patternParts[1] || []).length;
20528 if(!(options.round < 0)){
20529 value = dojo.number.round(value, maxPlaces, options.round);
20532 var valueParts = String(Math.abs(value)).split("."),
20533 fractional = valueParts[1] || "";
20534 if(patternParts[1] || options.places){
20536 options.places = options.places.substring(0, comma);
20538 // Pad fractional with trailing zeros
20539 var pad = options.places !== undefined ? options.places : (patternParts[1] && patternParts[1].lastIndexOf("0") + 1);
20540 if(pad > fractional.length){
20541 valueParts[1] = dojo.string.pad(fractional, pad, '0', true);
20544 // Truncate fractional
20545 if(maxPlaces < fractional.length){
20546 valueParts[1] = fractional.substr(0, maxPlaces);
20549 if(valueParts[1]){ valueParts.pop(); }
20552 // Pad whole with leading zeros
20553 var patternDigits = patternParts[0].replace(',', '');
20554 pad = patternDigits.indexOf("0");
20556 pad = patternDigits.length - pad;
20557 if(pad > valueParts[0].length){
20558 valueParts[0] = dojo.string.pad(valueParts[0], pad);
20562 if(patternDigits.indexOf("#") == -1){
20563 valueParts[0] = valueParts[0].substr(valueParts[0].length - pad);
20567 // Add group separators
20568 var index = patternParts[0].lastIndexOf(','),
20569 groupSize, groupSize2;
20571 groupSize = patternParts[0].length - index - 1;
20572 var remainder = patternParts[0].substr(0, index);
20573 index = remainder.lastIndexOf(',');
20575 groupSize2 = remainder.length - index - 1;
20579 for(var whole = valueParts[0]; whole;){
20580 var off = whole.length - groupSize;
20581 pieces.push((off > 0) ? whole.substr(off) : whole);
20582 whole = (off > 0) ? whole.slice(0, off) : "";
20584 groupSize = groupSize2;
20588 valueParts[0] = pieces.reverse().join(options.group || ",");
20590 return valueParts.join(options.decimal || ".");
20594 dojo.number.__RegexpOptions = function(){
20595 // pattern: String?
20596 // override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
20597 // with this string. Default value is based on locale. Overriding this property will defeat
20600 // choose a format type based on the locale from the following:
20601 // decimal, scientific (not yet supported), percent, currency. decimal by default.
20603 // override the locale used to determine formatting rules
20604 // strict: Boolean?
20605 // strict parsing, false by default. Strict parsing requires input as produced by the format() method.
20606 // Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
20607 // places: Number|String?
20608 // number of decimal places to accept: Infinity, a positive number, or
20609 // a range "n
,m
". Defined by pattern or Infinity if pattern not provided.
20610 this.pattern = pattern;
20612 this.locale = locale;
20613 this.strict = strict;
20614 this.places = places;
20617 dojo.number.regexp = function(/*dojo.number.__RegexpOptions?*/options){
20619 // Builds the regular needed to parse a number
20621 // Returns regular expression with positive and negative match, group
20622 // and decimal separators
20623 return dojo.number._parseInfo(options).regexp; // String
20626 dojo.number._parseInfo = function(/*Object?*/options){
20627 options = options || {};
20628 var locale = dojo.i18n.normalizeLocale(options.locale),
20629 bundle = dojo.i18n.getLocalization("dojo
.cldr
", "number
", locale),
20630 pattern = options.pattern || bundle[(options.type || "decimal") + "Format
"],
20632 group = bundle.group,
20633 decimal = bundle.decimal,
20636 if(pattern.indexOf('%') != -1){
20638 }else if(pattern.indexOf('\u2030') != -1){
20639 factor /= 1000; // per mille
20641 var isCurrency = pattern.indexOf('\u00a4') != -1;
20643 group = bundle.currencyGroup || group;
20644 decimal = bundle.currencyDecimal || decimal;
20648 //TODO: handle quoted escapes
20649 var patternList = pattern.split(';');
20650 if(patternList.length == 1){
20651 patternList.push("-" + patternList[0]);
20654 var re = dojo.regexp.buildGroupRE(patternList, function(pattern){
20655 pattern = "(?:"+dojo.regexp.escapeString(pattern, '.')+")";
20656 return pattern.replace(dojo.number._numberPatternRE, function(format){
20659 separator: options.strict ? group : [group,""],
20660 fractional: options.fractional,
20665 parts = format.split('.'),
20666 places = options.places;
20668 // special condition for percent (factor != 1)
20669 // allow decimal places even if not specified in pattern
20670 if(parts.length == 1 && factor != 1){
20673 if(parts.length == 1 || places === 0){
20674 flags.fractional = false;
20676 if(places === undefined){ places = options.pattern ? parts[1].lastIndexOf('0') + 1 : Infinity; }
20677 if(places && options.fractional == undefined){flags.fractional = true;} // required fractional, unless otherwise specified
20678 if(!options.places && (places < parts[1].length)){ places += "," + parts[1].length; }
20679 flags.places = places;
20681 var groups = parts[0].split(',');
20682 if(groups.length > 1){
20683 flags.groupSize = groups.pop().length;
20684 if(groups.length > 1){
20685 flags.groupSize2 = groups.pop().length;
20688 return "("+dojo.number._realNumberRegexp(flags)+")";
20693 // substitute the currency symbol for the placeholder in the pattern
20694 re = re.replace(/([\s\xa0]*)(\u00a4{1,3})([\s\xa0]*)/g, function(match, before, target, after){
20695 var prop = ["symbol
", "currency
", "displayName
"][target.length-1],
20696 symbol = dojo.regexp.escapeString(options[prop] || options.currency || "");
20697 before = before ? "[\\s
\\xa0
]" : "";
20698 after = after ? "[\\s
\\xa0
]" : "";
20699 if(!options.strict){
20700 if(before){before += "*";}
20701 if(after){after += "*";}
20702 return "(?:"+before+symbol+after+")?";
20704 return before+symbol+after;
20708 //TODO: substitute localized sign/percent/permille/etc.?
20710 // normalize whitespace and return
20711 return {regexp: re.replace(/[\xa0 ]/g, "[\\s
\\xa0
]"), group: group, decimal: decimal, factor: factor}; // Object
20715 dojo.number.__ParseOptions = function(){
20716 // pattern: String?
20717 // override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
20718 // with this string. Default value is based on locale. Overriding this property will defeat
20719 // localization. Literal characters in patterns are not supported.
20721 // choose a format type based on the locale from the following:
20722 // decimal, scientific (not yet supported), percent, currency. decimal by default.
20724 // override the locale used to determine formatting rules
20725 // strict: Boolean?
20726 // strict parsing, false by default. Strict parsing requires input as produced by the format() method.
20727 // Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
20728 // fractional: Boolean?|Array?
20729 // Whether to include the fractional portion, where the number of decimal places are implied by pattern
20730 // or explicit 'places' parameter. The value [true,false] makes the fractional portion optional.
20731 this.pattern = pattern;
20733 this.locale = locale;
20734 this.strict = strict;
20735 this.fractional = fractional;
20738 dojo.number.parse = function(/*String*/expression, /*dojo.number.__ParseOptions?*/options){
20740 // Convert a properly formatted string to a primitive Number, using
20741 // locale-specific settings.
20743 // Create a Number from a string using a known localized pattern.
20744 // Formatting patterns are chosen appropriate to the locale
20745 // and follow the syntax described by
20746 // [unicode.org TR35](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
20747 // Note that literal characters in patterns are not supported.
20749 // A string representation of a Number
20750 var info = dojo.number._parseInfo(options),
20751 results = (new RegExp("^"+info.regexp+"$")).exec(expression);
20755 var absoluteMatch = results[1]; // match for the positive expression
20760 // matched the negative pattern
20761 absoluteMatch =results[2];
20765 // Transform it to something Javascript can parse as a number. Normalize
20766 // decimal point and strip out group separators or alternate forms of whitespace
20767 absoluteMatch = absoluteMatch.
20768 replace(new RegExp("["+info.group + "\\s
\\xa0
"+"]", "g
"), "").
20769 replace(info.decimal, ".");
20770 // Adjust for negative sign, percent, etc. as necessary
20771 return absoluteMatch * info.factor; //Number
20775 dojo.number.__RealNumberRegexpFlags = function(){
20777 // The integer number of decimal places or a range given as "n
,m
". If
20778 // not given, the decimal part is optional and the number of places is
20780 // decimal: String?
20781 // A string for the character used as the decimal point. Default
20783 // fractional: Boolean?|Array?
20784 // Whether decimal places are used. Can be true, false, or [true,
20785 // false]. Default is [true, false] which means optional.
20786 // exponent: Boolean?|Array?
20787 // Express in exponential notation. Can be true, false, or [true,
20788 // false]. Default is [true, false], (i.e. will match if the
20789 // exponential part is present are not).
20790 // eSigned: Boolean?|Array?
20791 // The leading plus-or-minus sign on the exponent. Can be true,
20792 // false, or [true, false]. Default is [true, false], (i.e. will
20793 // match if it is signed or unsigned). flags in regexp.integer can be
20795 this.places = places;
20796 this.decimal = decimal;
20797 this.fractional = fractional;
20798 this.exponent = exponent;
20799 this.eSigned = eSigned;
20803 dojo.number._realNumberRegexp = function(/*dojo.number.__RealNumberRegexpFlags?*/flags){
20805 // Builds a regular expression to match a real number in exponential
20808 // assign default values to missing parameters
20809 flags = flags || {};
20810 //TODO: use mixin instead?
20811 if(!("places
" in flags)){ flags.places = Infinity; }
20812 if(typeof flags.decimal != "string
"){ flags.decimal = "."; }
20813 if(!("fractional
" in flags) || /^0/.test(flags.places)){ flags.fractional = [true, false]; }
20814 if(!("exponent
" in flags)){ flags.exponent = [true, false]; }
20815 if(!("eSigned
" in flags)){ flags.eSigned = [true, false]; }
20817 var integerRE = dojo.number._integerRegexp(flags),
20818 decimalRE = dojo.regexp.buildGroupRE(flags.fractional,
20821 if(q && (flags.places!==0)){
20822 re = "\\" + flags.decimal;
20823 if(flags.places == Infinity){
20824 re = "(?:" + re + "\\d
+)?";
20826 re += "\\d
{" + flags.places + "}";
20834 var exponentRE = dojo.regexp.buildGroupRE(flags.exponent,
20836 if(q){ return "([eE
]" + dojo.number._integerRegexp({ signed: flags.eSigned}) + ")"; }
20841 var realRE = integerRE + decimalRE;
20842 // allow for decimals without integers, e.g. .25
20843 if(decimalRE){realRE = "(?:(?:"+ realRE + ")|(?:" + decimalRE + "))";}
20844 return realRE + exponentRE; // String
20848 dojo.number.__IntegerRegexpFlags = function(){
20849 // signed: Boolean?
20850 // The leading plus-or-minus sign. Can be true, false, or `[true,false]`.
20851 // Default is `[true, false]`, (i.e. will match if it is signed
20853 // separator: String?
20854 // The character used as the thousands separator. Default is no
20855 // separator. For more than one symbol use an array, e.g. `[",", ""]`,
20856 // makes ',' optional.
20857 // groupSize: Number?
20858 // group size between separators
20859 // groupSize2: Number?
20860 // second grouping, where separators 2..n have a different interval than the first separator (for India)
20861 this.signed = signed;
20862 this.separator = separator;
20863 this.groupSize = groupSize;
20864 this.groupSize2 = groupSize2;
20868 dojo.number._integerRegexp = function(/*dojo.number.__IntegerRegexpFlags?*/flags){
20870 // Builds a regular expression that matches an integer
20872 // assign default values to missing parameters
20873 flags = flags || {};
20874 if(!("signed
" in flags)){ flags.signed = [true, false]; }
20875 if(!("separator
" in flags)){
20876 flags.separator = "";
20877 }else if(!("groupSize
" in flags)){
20878 flags.groupSize = 3;
20881 var signRE = dojo.regexp.buildGroupRE(flags.signed,
20882 function(q){ return q ? "[-+]" : ""; },
20886 var numberRE = dojo.regexp.buildGroupRE(flags.separator,
20892 sep = dojo.regexp.escapeString(sep);
20893 if(sep == " "){ sep = "\\s
"; }
20894 else if(sep == "\xa0"){ sep = "\\s
\\xa0
"; }
20896 var grp = flags.groupSize, grp2 = flags.groupSize2;
20897 //TODO: should we continue to enforce that numbers with separators begin with 1-9? See #6933
20899 var grp2RE = "(?:0|[1-9]\\d
{0," + (grp2-1) + "}(?:[" + sep + "]\\d
{" + grp2 + "})*[" + sep + "]\\d
{" + grp + "})";
20900 return ((grp-grp2) > 0) ? "(?:" + grp2RE + "|(?:0|[1-9]\\d
{0," + (grp-1) + "}))" : grp2RE;
20902 return "(?:0|[1-9]\\d
{0," + (grp-1) + "}(?:[" + sep + "]\\d
{" + grp + "})*)";
20907 return signRE + numberRE; // String
20912 if(!dojo._hasResource["dijit
.ProgressBar
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
20913 dojo._hasResource["dijit
.ProgressBar
"] = true;
20914 dojo.provide("dijit
.ProgressBar
");
20922 dojo.declare("dijit
.ProgressBar
", [dijit._Widget, dijit._Templated], {
20924 // A progress indication widget, showing the amount completed
20925 // (often the percentage completed) of a task.
20928 // | <div dojoType="ProgressBar
"
20930 // | progress="..." maximum="...">
20934 // Note that the progress bar is updated via (a non-standard)
20935 // update() method, rather than via attr() like other widgets.
20937 // progress: [const] String (Percentage or Number)
20938 // Number or percentage indicating amount of task completed.
20939 // With "%": percentage value, 0% <= progress <= 100%, or
20940 // without "%": absolute value, 0 <= progress <= maximum
20941 // TODO: rename to value for 2.0
20944 // maximum: [const] Float
20945 // Max sample number
20948 // places: [const] Number
20949 // Number of places to show in values; 0 by default
20952 // indeterminate: [const] Boolean
20953 // If false: show progress value (number or percentage).
20954 // If true: show that a process is underway but that the amount completed is unknown.
20955 indeterminate: false,
20958 // this is the field name (for a form) if set. This needs to be set if you want to use
20959 // this widget in a dijit.form.Form widget (such as dijit.Dialog)
20962 templateString: dojo.cache("dijit
", "templates
/ProgressBar.html", "<div class=\"dijitProgressBar dijitProgressBarEmpty\"\n\t><div waiRole=\"progressbar\" dojoAttachPoint=\"internalProgress\" class=\"dijitProgressBarFull\"\n\t\t><div class=\"dijitProgressBarTile\"></div\n\t\t><span style
=\"visibility
:hidden
\"> 
;</span\n\t></div\n\t><div dojoAttachPoint
=\"label
\" class=\"dijitProgressBarLabel
\" id
=\"${id}_label
\"> 
;</div\n\t><img dojoAttachPoint=\"indeterminateHighContrastImage\" class=\"dijitProgressBarIndeterminateHighContrastImage\" alt=\"\"\n/></div
>\n"),
20964 // _indeterminateHighContrastImagePath: [private] dojo._URL
20965 // URL to image to use for indeterminate progress bar when display is in high contrast mode
20966 _indeterminateHighContrastImagePath:
20967 dojo.moduleUrl("dijit
", "themes
/a11y/indeterminate_progress.gif
"),
20969 // public functions
20970 postCreate: function(){
20971 this.inherited(arguments);
20972 this.indeterminateHighContrastImage.setAttribute("src
",
20973 this._indeterminateHighContrastImagePath.toString());
20977 update: function(/*Object?*/attributes){
20979 // Change attributes of ProgressBar, similar to attr(hash).
20982 // May provide progress and/or maximum properties on this parameter;
20983 // see attribute specs for details.
20986 // | myProgressBar.update({'indeterminate': true});
20987 // | myProgressBar.update({'progress': 80});
20989 // TODO: deprecate this method and use set() instead
20991 dojo.mixin(this, attributes || {});
20992 var tip = this.internalProgress;
20993 var percent = 1, classFunc;
20994 if(this.indeterminate){
20995 classFunc = "addClass
";
20996 dijit.removeWaiState(tip, "valuenow
");
20997 dijit.removeWaiState(tip, "valuemin
");
20998 dijit.removeWaiState(tip, "valuemax
");
21000 classFunc = "removeClass
";
21001 if(String(this.progress).indexOf("%") != -1){
21002 percent = Math.min(parseFloat(this.progress)/100, 1);
21003 this.progress = percent * this.maximum;
21005 this.progress = Math.min(this.progress, this.maximum);
21006 percent = this.progress / this.maximum;
21008 var text = this.report(percent);
21009 this.label.firstChild.nodeValue = text;
21010 dijit.setWaiState(tip, "describedby
", this.label.id);
21011 dijit.setWaiState(tip, "valuenow
", this.progress);
21012 dijit.setWaiState(tip, "valuemin
", 0);
21013 dijit.setWaiState(tip, "valuemax
", this.maximum);
21015 dojo[classFunc](this.domNode, "dijitProgressBarIndeterminate
");
21016 tip.style.width = (percent * 100) + "%";
21020 _setValueAttr: function(v){
21022 this.update({indeterminate:true});
21024 this.update({indeterminate:false, progress:v});
21028 _getValueAttr: function(){
21029 return this.progress;
21032 report: function(/*float*/percent){
21034 // Generates message to show inside progress bar (normally indicating amount of task completed).
21035 // May be overridden.
21039 return dojo.number.format(percent, { type: "percent
", places: this.places, locale: this.lang });
21042 onChange: function(){
21044 // Callback fired when progress updates.
21052 if(!dojo._hasResource["dijit
.ToolbarSeparator
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
21053 dojo._hasResource["dijit
.ToolbarSeparator
"] = true;
21054 dojo.provide("dijit
.ToolbarSeparator
");
21059 dojo.declare("dijit
.ToolbarSeparator
",
21060 [ dijit._Widget, dijit._Templated ],
21063 // A spacer between two `dijit.Toolbar` items
21064 templateString: '<div class="dijitToolbarSeparator dijitInline
" waiRole="presentation
"></div>',
21065 postCreate: function(){ dojo.setSelectable(this.domNode, false); },
21066 isFocusable: function(){
21068 // This widget isn't focusable, so pass along that fact.
21080 if(!dojo._hasResource["dijit
.Toolbar
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
21081 dojo._hasResource["dijit
.Toolbar
"] = true;
21082 dojo.provide("dijit
.Toolbar
");
21088 dojo.declare("dijit
.Toolbar
",
21089 [dijit._Widget, dijit._Templated, dijit._KeyNavContainer],
21092 // A Toolbar widget, used to hold things like `dijit.Editor` buttons
21095 '<div class="dijit
" waiRole="toolbar
" tabIndex="${tabIndex}
" dojoAttachPoint="containerNode
">' +
21096 // '<table style="table
-layout
: fixed
" class="dijitReset dijitToolbarTable
">' + // factor out style
21097 // '<tr class="dijitReset
" dojoAttachPoint="containerNode
"></tr>'+
21101 baseClass: "dijitToolbar
",
21103 postCreate: function(){
21104 this.connectKeyNavHandlers(
21105 this.isLeftToRight() ? [dojo.keys.LEFT_ARROW] : [dojo.keys.RIGHT_ARROW],
21106 this.isLeftToRight() ? [dojo.keys.RIGHT_ARROW] : [dojo.keys.LEFT_ARROW]
21108 this.inherited(arguments);
21111 startup: function(){
21112 if(this._started){ return; }
21114 this.startupKeyNavChildren();
21116 this.inherited(arguments);
21121 // For back-compat, remove for 2.0
21126 if(!dojo._hasResource["dojo
.DeferredList
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
21127 dojo._hasResource["dojo
.DeferredList
"] = true;
21128 dojo.provide("dojo
.DeferredList
");
21129 dojo.DeferredList = function(/*Array*/ list, /*Boolean?*/ fireOnOneCallback, /*Boolean?*/ fireOnOneErrback, /*Boolean?*/ consumeErrors, /*Function?*/ canceller){
21131 // Provides event handling for a group of Deferred objects.
21133 // DeferredList takes an array of existing deferreds and returns a new deferred of its own
21134 // this new deferred will typically have its callback fired when all of the deferreds in
21135 // the given list have fired their own deferreds. The parameters `fireOnOneCallback` and
21136 // fireOnOneErrback, will fire before all the deferreds as appropriate
21139 // The list of deferreds to be synchronizied with this DeferredList
21140 // fireOnOneCallback:
21141 // Will cause the DeferredLists callback to be fired as soon as any
21142 // of the deferreds in its list have been fired instead of waiting until
21143 // the entire list has finished
21144 // fireonOneErrback:
21145 // Will cause the errback to fire upon any of the deferreds errback
21147 // A deferred canceller function, see dojo.Deferred
21148 var resultList = [];
21149 dojo.Deferred.call(this);
21151 if(list.length === 0 && !fireOnOneCallback){
21152 this.resolve([0, []]);
21155 dojo.forEach(list, function(item, i){
21156 item.then(function(result){
21157 if(fireOnOneCallback){
21158 self.resolve([i, result]);
21160 addResult(true, result);
21163 if(fireOnOneErrback){
21164 self.reject(error);
21166 addResult(false, error);
21173 function addResult(succeeded, result){
21174 resultList[i] = [succeeded, result];
21176 if(finished === list.length){
21177 self.resolve(resultList);
21183 dojo.DeferredList.prototype = new dojo.Deferred();
21185 dojo.DeferredList.prototype.gatherResults= function(deferredList){
21187 // Gathers the results of the deferreds for packaging
21188 // as the parameters to the Deferred Lists' callback
21190 var d = new dojo.DeferredList(deferredList, false, true, false);
21191 d.addCallback(function(results){
21193 dojo.forEach(results, function(result){
21194 ret.push(result[1]);
21203 if(!dojo._hasResource["dijit
.tree
.TreeStoreModel
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
21204 dojo._hasResource["dijit
.tree
.TreeStoreModel
"] = true;
21205 dojo.provide("dijit
.tree
.TreeStoreModel
");
21208 "dijit
.tree
.TreeStoreModel
",
21212 // Implements dijit.Tree.model connecting to a store with a single
21213 // root item. Any methods passed into the constructor will override
21214 // the ones defined here.
21216 // store: dojo.data.Store
21217 // Underlying store
21220 // childrenAttrs: String[]
21221 // One or more attribute names (attributes in the dojo.data item) that specify that item's children
21222 childrenAttrs: ["children
"],
21224 // newItemIdAttr: String
21225 // Name of attribute in the Object passed to newItem() that specifies the id.
21227 // If newItemIdAttr is set then it's used when newItem() is called to see if an
21228 // item with the same id already exists, and if so just links to the old item
21229 // (so that the old item ends up with two parents).
21231 // Setting this to null or "" will make every drop create a new item.
21232 newItemIdAttr: "id
",
21234 // labelAttr: String
21235 // If specified, get label for tree node from this attribute, rather
21236 // than by calling store.getLabel()
21239 // root: [readonly] dojo.data.Item
21240 // Pointer to the root item (read only, not a parameter)
21244 // Specifies datastore query to return the root item for the tree.
21245 // Must only return a single item. Alternately can just pass in pointer
21251 // deferItemLoadingUntilExpand: Boolean
21252 // Setting this to true will cause the TreeStoreModel to defer calling loadItem on nodes
21253 // until they are expanded. This allows for lazying loading where only one
21254 // loadItem (and generally one network call, consequently) per expansion
21255 // (rather than one for each child).
21256 // This relies on partial loading of the children items; each children item of a
21257 // fully loaded item should contain the label and info about having children.
21258 deferItemLoadingUntilExpand: false,
21260 constructor: function(/* Object */ args){
21262 // Passed the arguments listed above (store, etc)
21266 dojo.mixin(this, args);
21268 this.connects = [];
21270 var store = this.store;
21271 if(!store.getFeatures()['dojo.data.api.Identity']){
21272 throw new Error("dijit
.Tree
: store must support dojo
.data
.Identity
");
21275 // if the store supports Notification, subscribe to the notification events
21276 if(store.getFeatures()['dojo.data.api.Notification']){
21277 this.connects = this.connects.concat([
21278 dojo.connect(store, "onNew
", this, "onNewItem
"),
21279 dojo.connect(store, "onDelete
", this, "onDeleteItem
"),
21280 dojo.connect(store, "onSet
", this, "onSetItem
")
21285 destroy: function(){
21286 dojo.forEach(this.connects, dojo.disconnect);
21287 // TODO: should cancel any in-progress processing of getRoot(), getChildren()
21290 // =======================================================================
21291 // Methods for traversing hierarchy
21293 getRoot: function(onItem, onError){
21295 // Calls onItem with the root item for the tree, possibly a fabricated item.
21296 // Calls onError on error.
21302 onComplete: dojo.hitch(this, function(items){
21303 if(items.length != 1){
21304 throw new Error(this.declaredClass + ": query
" + dojo.toJson(this.query) + " returned
" + items.length +
21305 " items
, but must
return exactly one item
");
21307 this.root = items[0];
21315 mayHaveChildren: function(/*dojo.data.Item*/ item){
21317 // Tells if an item has or may have children. Implementing logic here
21318 // avoids showing +/- expando icon for nodes that we know don't have children.
21319 // (For efficiency reasons we may not want to check if an element actually
21320 // has children until user clicks the expando node)
21321 return dojo.some(this.childrenAttrs, function(attr){
21322 return this.store.hasAttribute(item, attr);
21326 getChildren: function(/*dojo.data.Item*/ parentItem, /*function(items)*/ onComplete, /*function*/ onError){
21328 // Calls onComplete() with array of child items of given parent item, all loaded.
21330 var store = this.store;
21331 if(!store.isItemLoaded(parentItem)){
21332 // The parent is not loaded yet, we must be in deferItemLoadingUntilExpand
21333 // mode, so we will load it and just return the children (without loading each
21335 var getChildren = dojo.hitch(this, arguments.callee);
21338 onItem: function(parentItem){
21339 getChildren(parentItem, onComplete, onError);
21345 // get children of specified item
21346 var childItems = [];
21347 for(var i=0; i<this.childrenAttrs.length; i++){
21348 var vals = store.getValues(parentItem, this.childrenAttrs[i]);
21349 childItems = childItems.concat(vals);
21352 // count how many items need to be loaded
21353 var _waitCount = 0;
21354 if(!this.deferItemLoadingUntilExpand){
21355 dojo.forEach(childItems, function(item){ if(!store.isItemLoaded(item)){ _waitCount++; } });
21358 if(_waitCount == 0){
21359 // all items are already loaded (or we aren't loading them). proceed...
21360 onComplete(childItems);
21362 // still waiting for some or all of the items to load
21363 dojo.forEach(childItems, function(item, idx){
21364 if(!store.isItemLoaded(item)){
21367 onItem: function(item){
21368 childItems[idx] = item;
21369 if(--_waitCount == 0){
21370 // all nodes have been loaded, send them to the tree
21371 onComplete(childItems);
21381 // =======================================================================
21382 // Inspecting items
21384 isItem: function(/* anything */ something){
21385 return this.store.isItem(something); // Boolean
21388 fetchItemByIdentity: function(/* object */ keywordArgs){
21389 this.store.fetchItemByIdentity(keywordArgs);
21392 getIdentity: function(/* item */ item){
21393 return this.store.getIdentity(item); // Object
21396 getLabel: function(/*dojo.data.Item*/ item){
21398 // Get the label for an item
21399 if(this.labelAttr){
21400 return this.store.getValue(item,this.labelAttr); // String
21402 return this.store.getLabel(item); // String
21406 // =======================================================================
21409 newItem: function(/* dojo.dnd.Item */ args, /*Item*/ parent, /*int?*/ insertIndex){
21411 // Creates a new item. See `dojo.data.api.Write` for details on args.
21412 // Used in drag & drop when item from external source dropped onto tree.
21414 // Developers will need to override this method if new items get added
21415 // to parents with multiple children attributes, in order to define which
21416 // children attribute points to the new item.
21418 var pInfo = {parent: parent, attribute: this.childrenAttrs[0], insertIndex: insertIndex};
21420 if(this.newItemIdAttr && args[this.newItemIdAttr]){
21421 // Maybe there's already a corresponding item in the store; if so, reuse it.
21422 this.fetchItemByIdentity({identity: args[this.newItemIdAttr], scope: this, onItem: function(item){
21424 // There's already a matching item in store, use it
21425 this.pasteItem(item, null, parent, true, insertIndex);
21427 // Create new item in the tree, based on the drag source.
21428 this.store.newItem(args, pInfo);
21432 // [as far as we know] there is no id so we must assume this is a new item
21433 this.store.newItem(args, pInfo);
21437 pasteItem: function(/*Item*/ childItem, /*Item*/ oldParentItem, /*Item*/ newParentItem, /*Boolean*/ bCopy, /*int?*/ insertIndex){
21439 // Move or copy an item from one parent item to another.
21440 // Used in drag & drop
21441 var store = this.store,
21442 parentAttr = this.childrenAttrs[0]; // name of "children
" attr in parent item
21444 // remove child from source item, and record the attribute that child occurred in
21446 dojo.forEach(this.childrenAttrs, function(attr){
21447 if(store.containsValue(oldParentItem, attr, childItem)){
21449 var values = dojo.filter(store.getValues(oldParentItem, attr), function(x){
21450 return x != childItem;
21452 store.setValues(oldParentItem, attr, values);
21459 // modify target item's children attribute to include this item
21461 if(typeof insertIndex == "number
"){
21462 // call slice() to avoid modifying the original array, confusing the data store
21463 var childItems = store.getValues(newParentItem, parentAttr).slice();
21464 childItems.splice(insertIndex, 0, childItem);
21465 store.setValues(newParentItem, parentAttr, childItems);
21467 store.setValues(newParentItem, parentAttr,
21468 store.getValues(newParentItem, parentAttr).concat(childItem));
21473 // =======================================================================
21476 onChange: function(/*dojo.data.Item*/ item){
21478 // Callback whenever an item has changed, so that Tree
21479 // can update the label, icon, etc. Note that changes
21480 // to an item's children or parent(s) will trigger an
21481 // onChildrenChange() so you can ignore those changes here.
21486 onChildrenChange: function(/*dojo.data.Item*/ parent, /*dojo.data.Item[]*/ newChildrenList){
21488 // Callback to do notifications about new, updated, or deleted items.
21493 onDelete: function(/*dojo.data.Item*/ parent, /*dojo.data.Item[]*/ newChildrenList){
21495 // Callback when an item has been deleted.
21497 // Note that there will also be an onChildrenChange() callback for the parent
21503 // =======================================================================
21504 // Events from data store
21506 onNewItem: function(/* dojo.data.Item */ item, /* Object */ parentInfo){
21508 // Handler for when new items appear in the store, either from a drop operation
21509 // or some other way. Updates the tree view (if necessary).
21511 // If the new item is a child of an existing item,
21512 // calls onChildrenChange() with the new list of children
21513 // for that existing item.
21518 // We only care about the new item if it has a parent that corresponds to a TreeNode
21519 // we are currently displaying
21524 // Call onChildrenChange() on parent (ie, existing) item with new list of children
21525 // In the common case, the new list of children is simply parentInfo.newValue or
21526 // [ parentInfo.newValue ], although if items in the store has multiple
21527 // child attributes (see `childrenAttr`), then it's a superset of parentInfo.newValue,
21528 // so call getChildren() to be sure to get right answer.
21529 this.getChildren(parentInfo.item, dojo.hitch(this, function(children){
21530 this.onChildrenChange(parentInfo.item, children);
21534 onDeleteItem: function(/*Object*/ item){
21536 // Handler for delete notifications from underlying store
21537 this.onDelete(item);
21540 onSetItem: function(/* item */ item,
21541 /* attribute-name-string */ attribute,
21542 /* object | array */ oldValue,
21543 /* object | array */ newValue){
21545 // Updates the tree view according to changes in the data store.
21547 // Handles updates to an item's children by calling onChildrenChange(), and
21548 // other updates to an item by calling onChange().
21550 // See `onNewItem` for more details on handling updates to an item's children.
21554 if(dojo.indexOf(this.childrenAttrs, attribute) != -1){
21555 // item's children list changed
21556 this.getChildren(item, dojo.hitch(this, function(children){
21557 // See comments in onNewItem() about calling getChildren()
21558 this.onChildrenChange(item, children);
21561 // item's label/icon/etc. changed.
21562 this.onChange(item);
21571 if(!dojo._hasResource["dijit
.tree
.ForestStoreModel
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
21572 dojo._hasResource["dijit
.tree
.ForestStoreModel
"] = true;
21573 dojo.provide("dijit
.tree
.ForestStoreModel
");
21577 dojo.declare("dijit
.tree
.ForestStoreModel
", dijit.tree.TreeStoreModel, {
21579 // Interface between Tree and a dojo.store that doesn't have a root item,
21580 // i.e. has multiple "top level
" items.
21583 // Use this class to wrap a dojo.store, making all the items matching the specified query
21584 // appear as children of a fabricated "root item
". If no query is specified then all the
21585 // items returned by fetch() on the underlying store become children of the root item.
21586 // It allows dijit.Tree to assume a single root item, even if the store doesn't have one.
21588 // Parameters to constructor
21591 // ID of fabricated root item
21594 // rootLabel: String
21595 // Label of fabricated root item
21599 // Specifies the set of children of the root item.
21601 // | {type:'continent'}
21604 // End of parameters to constructor
21606 constructor: function(params){
21608 // Sets up variables, etc.
21612 // Make dummy root item
21617 label: params.rootLabel,
21618 children: params.rootChildren // optional param
21622 // =======================================================================
21623 // Methods for traversing hierarchy
21625 mayHaveChildren: function(/*dojo.data.Item*/ item){
21627 // Tells if an item has or may have children. Implementing logic here
21628 // avoids showing +/- expando icon for nodes that we know don't have children.
21629 // (For efficiency reasons we may not want to check if an element actually
21630 // has children until user clicks the expando node)
21633 return item === this.root || this.inherited(arguments);
21636 getChildren: function(/*dojo.data.Item*/ parentItem, /*function(items)*/ callback, /*function*/ onError){
21638 // Calls onComplete() with array of child items of given parent item, all loaded.
21639 if(parentItem === this.root){
21640 if(this.root.children){
21641 // already loaded, just return
21642 callback(this.root.children);
21646 onComplete: dojo.hitch(this, function(items){
21647 this.root.children = items;
21654 this.inherited(arguments);
21658 // =======================================================================
21659 // Inspecting items
21661 isItem: function(/* anything */ something){
21662 return (something === this.root) ? true : this.inherited(arguments);
21665 fetchItemByIdentity: function(/* object */ keywordArgs){
21666 if(keywordArgs.identity == this.root.id){
21667 var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
21668 if(keywordArgs.onItem){
21669 keywordArgs.onItem.call(scope, this.root);
21672 this.inherited(arguments);
21676 getIdentity: function(/* item */ item){
21677 return (item === this.root) ? this.root.id : this.inherited(arguments);
21680 getLabel: function(/* item */ item){
21681 return (item === this.root) ? this.root.label : this.inherited(arguments);
21684 // =======================================================================
21687 newItem: function(/* dojo.dnd.Item */ args, /*Item*/ parent, /*int?*/ insertIndex){
21689 // Creates a new item. See dojo.data.api.Write for details on args.
21690 // Used in drag & drop when item from external source dropped onto tree.
21691 if(parent === this.root){
21692 this.onNewRootItem(args);
21693 return this.store.newItem(args);
21695 return this.inherited(arguments);
21699 onNewRootItem: function(args){
21701 // User can override this method to modify a new element that's being
21702 // added to the root of the tree, for example to add a flag like root=true
21705 pasteItem: function(/*Item*/ childItem, /*Item*/ oldParentItem, /*Item*/ newParentItem, /*Boolean*/ bCopy, /*int?*/ insertIndex){
21707 // Move or copy an item from one parent item to another.
21708 // Used in drag & drop
21709 if(oldParentItem === this.root){
21711 // It's onLeaveRoot()'s responsibility to modify the item so it no longer matches
21712 // this.query... thus triggering an onChildrenChange() event to notify the Tree
21713 // that this element is no longer a child of the root node
21714 this.onLeaveRoot(childItem);
21717 dijit.tree.TreeStoreModel.prototype.pasteItem.call(this, childItem,
21718 oldParentItem === this.root ? null : oldParentItem,
21719 newParentItem === this.root ? null : newParentItem,
21723 if(newParentItem === this.root){
21724 // It's onAddToRoot()'s responsibility to modify the item so it matches
21725 // this.query... thus triggering an onChildrenChange() event to notify the Tree
21726 // that this element is now a child of the root node
21727 this.onAddToRoot(childItem);
21731 // =======================================================================
21732 // Handling for top level children
21734 onAddToRoot: function(/* item */ item){
21736 // Called when item added to root of tree; user must override this method
21737 // to modify the item so that it matches the query for top level items
21739 // | store.setValue(item, "root
", true);
21742 console.log(this, ": item
", item, " added to root
");
21745 onLeaveRoot: function(/* item */ item){
21747 // Called when item removed from root of tree; user must override this method
21748 // to modify the item so it doesn't match the query for top level items
21750 // | store.unsetAttribute(item, "root
");
21753 console.log(this, ": item
", item, " removed
from root
");
21756 // =======================================================================
21757 // Events from data store
21759 _requeryTop: function(){
21760 // reruns the query for the children of the root node,
21761 // sending out an onSet notification if those children have changed
21762 var oldChildren = this.root.children || [];
21765 onComplete: dojo.hitch(this, function(newChildren){
21766 this.root.children = newChildren;
21768 // If the list of children or the order of children has changed...
21769 if(oldChildren.length != newChildren.length ||
21770 dojo.some(oldChildren, function(item, idx){ return newChildren[idx] != item;})){
21771 this.onChildrenChange(this.root, newChildren);
21777 onNewItem: function(/* dojo.data.Item */ item, /* Object */ parentInfo){
21779 // Handler for when new items appear in the store. Developers should override this
21780 // method to be more efficient based on their app/data.
21782 // Note that the default implementation requeries the top level items every time
21783 // a new item is created, since any new item could be a top level item (even in
21784 // addition to being a child of another item, since items can have multiple parents).
21786 // Developers can override this function to do something more efficient if they can
21787 // detect which items are possible top level items (based on the item and the
21788 // parentInfo parameters). Often all top level items have parentInfo==null, but
21789 // that will depend on which store you use and what your data is like.
21792 this._requeryTop();
21794 this.inherited(arguments);
21797 onDeleteItem: function(/*Object*/ item){
21799 // Handler for delete notifications from underlying store
21801 // check if this was a child of root, and if so send notification that root's children
21803 if(dojo.indexOf(this.root.children, item) != -1){
21804 this._requeryTop();
21807 this.inherited(arguments);
21815 if(!dojo._hasResource["dijit
.Tree
"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
21816 dojo._hasResource["dijit
.Tree
"] = true;
21817 dojo.provide("dijit
.Tree
");
21831 [dijit._Widget, dijit._Templated, dijit._Container, dijit._Contained, dijit._CssStateMixin],
21834 // Single node within a tree. This class is used internally
21835 // by Tree and should not be accessed directly.
21839 // item: dojo.data.Item
21840 // the dojo.data entry this tree represents
21843 // isTreeNode: [protected] Boolean
21844 // Indicates that this is a TreeNode. Used by `dijit.Tree` only,
21845 // should not be accessed directly.
21849 // Text of this tree node
21852 // isExpandable: [private] Boolean
21853 // This node has children, so show the expando node (+ sign)
21854 isExpandable: null,
21856 // isExpanded: [readonly] Boolean
21857 // This node is currently expanded (ie, opened)
21860 // state: [private] String
21861 // Dynamic loading-related stuff.
21862 // When an empty folder node appears, it is "UNCHECKED
" first,
21863 // then after dojo.data query it becomes "LOADING
" and, finally "LOADED
"
21864 state: "UNCHECKED
",
21866 templateString: dojo.cache("dijit
", "templates
/TreeNode.html", "<div class=\"dijitTreeNode\" waiRole=\"presentation\"\n\t><div dojoAttachPoint=\"rowNode\" class=\"dijitTreeRow\" waiRole=\"presentation\" dojoAttachEvent=\"onmouseenter:_onMouseEnter, onmouseleave:_onMouseLeave, onclick:_onClick, ondblclick:_onDblClick\"\n\t\t><img src=\"${_blankGif}\" alt=\"\" dojoAttachPoint=\"expandoNode\" class=\"dijitTreeExpando\" waiRole=\"presentation\"\n\t\t/><span dojoAttachPoint
=\"expandoNodeText
\" class=\"dijitExpandoText
\" waiRole
=\"presentation
\"\n\t\t></span\n\t\t><span dojoAttachPoint=\"contentNode\"\n\t\t\tclass=\"dijitTreeContent\" waiRole=\"presentation\">\n\t\t\t<img src=\"${_blankGif}\" alt=\"\" dojoAttachPoint=\"iconNode\" class=\"dijitIcon dijitTreeIcon\" waiRole=\"presentation\"\n\t\t\t/><span dojoAttachPoint
=\"labelNode
\" class=\"dijitTreeLabel
\" wairole
=\"treeitem
\" tabindex
=\"-1\" waiState
=\"selected
-false\" dojoAttachEvent
=\"onfocus
:_onLabelFocus
\"></span>\n\t\t</span\n\t></div>\n\t<div dojoAttachPoint=\"containerNode\" class=\"dijitTreeContainer\" waiRole=\"presentation\" style=\"display: none;\"></div>\n</div
>\n"),
21868 baseClass: "dijitTreeNode
",
21870 // For hover effect for tree node, and focus effect for label
21872 rowNode: "dijitTreeRow
",
21873 labelNode: "dijitTreeLabel
"
21876 attributeMap: dojo.delegate(dijit._Widget.prototype.attributeMap, {
21877 label: {node: "labelNode
", type: "innerText
"},
21878 tooltip: {node: "rowNode
", type: "attribute
", attribute: "title
"}
21881 postCreate: function(){
21882 this.inherited(arguments);
21884 // set expand icon for leaf
21885 this._setExpando();
21887 // set icon and label class based on item
21888 this._updateItemClasses(this.item);
21890 if(this.isExpandable){
21891 dijit.setWaiState(this.labelNode, "expanded
", this.isExpanded);
21895 _setIndentAttr: function(indent){
21897 // Tell this node how many levels it should be indented
21899 // 0 for top level nodes, 1 for their children, 2 for their
21900 // grandchildren, etc.
21901 this.indent = indent;
21903 // Math.max() is to prevent negative padding on hidden root node (when indent == -1)
21904 var pixels = (Math.max(indent, 0) * this.tree._nodePixelIndent) + "px
";
21906 dojo.style(this.domNode, "backgroundPosition
", pixels + " 0px
");
21907 dojo.style(this.rowNode, this.isLeftToRight() ? "paddingLeft
" : "paddingRight
", pixels);
21909 dojo.forEach(this.getChildren(), function(child){
21910 child.set("indent
", indent+1);
21914 markProcessing: function(){
21916 // Visually denote that tree is loading data, etc.
21919 this.state = "LOADING
";
21920 this._setExpando(true);
21923 unmarkProcessing: function(){
21925 // Clear markup from markProcessing() call
21928 this._setExpando(false);
21931 _updateItemClasses: function(item){
21933 // Set appropriate CSS classes for icon and label dom node
21934 // (used to allow for item updates to change respective CSS)
21937 var tree = this.tree, model = tree.model;
21938 if(tree._v10Compat && item === model.root){
21939 // For back-compat with 1.0, need to use null to specify root item (TODO: remove in 2.0)
21942 this._applyClassAndStyle(item, "icon
", "Icon
");
21943 this._applyClassAndStyle(item, "label
", "Label
");
21944 this._applyClassAndStyle(item, "row
", "Row
");
21947 _applyClassAndStyle: function(item, lower, upper){
21949 // Set the appropriate CSS classes and styles for labels, icons and rows.
21955 // The lower case attribute to use, e.g. 'icon', 'label' or 'row'.
21958 // The upper case attribute to use, e.g. 'Icon', 'Label' or 'Row'.
21963 var clsName = "_
" + lower + "Class
";
21964 var nodeName = lower + "Node
";
21967 dojo.removeClass(this[nodeName], this[clsName]);
21969 this[clsName] = this.tree["get" + upper + "Class
"](item, this.isExpanded);
21971 dojo.addClass(this[nodeName], this[clsName]);
21973 dojo.style(this[nodeName], this.tree["get" + upper + "Style
"](item, this.isExpanded) || {});
21976 _updateLayout: function(){
21978 // Set appropriate CSS classes for this.domNode
21981 var parent = this.getParent();
21982 if(!parent || parent.rowNode.style.display == "none
"){
21983 /* if we are hiding the root node then make every first level child look like a root node */
21984 dojo.addClass(this.domNode, "dijitTreeIsRoot
");
21986 dojo.toggleClass(this.domNode, "dijitTreeIsLast
", !this.getNextSibling());
21990 _setExpando: function(/*Boolean*/ processing){
21992 // Set the right image for the expando node
21996 var styles = ["dijitTreeExpandoLoading
", "dijitTreeExpandoOpened
",
21997 "dijitTreeExpandoClosed
", "dijitTreeExpandoLeaf
"],
21998 _a11yStates = ["*","-","+","*"],
21999 idx = processing ? 0 : (this.isExpandable ? (this.isExpanded ? 1 : 2) : 3);
22001 // apply the appropriate class to the expando node
22002 dojo.removeClass(this.expandoNode, styles);
22003 dojo.addClass(this.expandoNode, styles[idx]);
22005 // provide a non-image based indicator for images-off mode
22006 this.expandoNodeText.innerHTML = _a11yStates[idx];
22010 expand: function(){
22012 // Show my children
22014 // Deferred that fires when expansion is complete
22016 // If there's already an expand in progress or we are already expanded, just return
22017 if(this._expandDeferred){
22018 return this._expandDeferred; // dojo.Deferred
22021 // cancel in progress collapse operation
22022 this._wipeOut && this._wipeOut.stop();
22024 // All the state information for when a node is expanded, maybe this should be
22025 // set when the animation completes instead
22026 this.isExpanded = true;
22027 dijit.setWaiState(this.labelNode, "expanded
", "true");
22028 dijit.setWaiRole(this.containerNode, "group
");
22029 dojo.addClass(this.contentNode,'dijitTreeContentExpanded');
22030 this._setExpando();
22031 this._updateItemClasses(this.item);
22032 if(this == this.tree.rootNode){
22033 dijit.setWaiState(this.tree.domNode, "expanded
", "true");
22037 wipeIn = dojo.fx.wipeIn({
22038 node: this.containerNode, duration: dijit.defaultDuration,
22040 def.callback(true);
22044 // Deferred that fires when expand is complete
22045 def = (this._expandDeferred = new dojo.Deferred(function(){
22052 return def; // dojo.Deferred
22055 collapse: function(){
22057 // Collapse this node (if it's expanded)
22059 if(!this.isExpanded){ return; }
22061 // cancel in progress expand operation
22062 if(this._expandDeferred){
22063 this._expandDeferred.cancel();
22064 delete this._expandDeferred;
22067 this.isExpanded = false;
22068 dijit.setWaiState(this.labelNode, "expanded
", "false");
22069 if(this == this.tree.rootNode){
22070 dijit.setWaiState(this.tree.domNode, "expanded
", "false");
22072 dojo.removeClass(this.contentNode,'dijitTreeContentExpanded');
22073 this._setExpando();
22074 this._updateItemClasses(this.item);
22076 if(!this._wipeOut){
22077 this._wipeOut = dojo.fx.wipeOut({
22078 node: this.containerNode, duration: dijit.defaultDuration
22081 this._wipeOut.play();
22085 // Levels from this node to the root node
22088 setChildItems: function(/* Object[] */ items){
22090 // Sets the child items of this node, removing/adding nodes
22091 // from current children to match specified items[] array.
22092 // Also, if this.persist == true, expands any children that were previously
22095 // Deferred object that fires after all previously opened children
22096 // have been expanded again (or fires instantly if there are no such children).
22098 var tree = this.tree,
22099 model = tree.model,
22100 defs = []; // list of deferreds that need to fire before I am complete
22103 // Orphan all my existing children.
22104 // If items contains some of the same items as before then we will reattach them.
22105 // Don't call this.removeChild() because that will collapse the tree etc.
22106 dojo.forEach(this.getChildren(), function(child){
22107 dijit._Container.prototype.removeChild.call(this, child);
22110 this.state = "LOADED
";
22112 if(items && items.length > 0){
22113 this.isExpandable = true;
22115 // Create _TreeNode widget for each specified tree node, unless one already
22116 // exists and isn't being used (presumably it's from a DnD move and was recently
22118 dojo.forEach(items, function(item){
22119 var id = model.getIdentity(item),
22120 existingNodes = tree._itemNodesMap[id],
22123 for(var i=0;i<existingNodes.length;i++){
22124 if(existingNodes[i] && !existingNodes[i].getParent()){
22125 node = existingNodes[i];
22126 node.set('indent', this.indent+1);
22132 node = this.tree._createTreeNode({
22135 isExpandable: model.mayHaveChildren(item),
22136 label: tree.getLabel(item),
22137 tooltip: tree.getTooltip(item),
22140 indent: this.indent + 1
22143 existingNodes.push(node);
22145 tree._itemNodesMap[id] = [node];
22148 this.addChild(node);
22150 // If node was previously opened then open it again now (this may trigger
22151 // more data store accesses, recursively)
22152 if(this.tree.autoExpand || this.tree._state(item)){
22153 defs.push(tree._expandNode(node));
22157 // note that updateLayout() needs to be called on each child after
22158 // _all_ the children exist
22159 dojo.forEach(this.getChildren(), function(child, idx){
22160 child._updateLayout();
22163 this.isExpandable=false;
22166 if(this._setExpando){
22167 // change expando to/from dot or + icon, as appropriate
22168 this._setExpando(false);
22171 // Set leaf icon or folder icon, as appropriate
22172 this._updateItemClasses(this.item);
22174 // On initial tree show, make the selected TreeNode as either the root node of the tree,
22175 // or the first child, if the root node is hidden
22176 if(this == tree.rootNode){
22177 var fc = this.tree.showRoot ? this : this.getChildren()[0];
22179 fc.setFocusable(true);
22180 tree.lastFocused = fc;
22182 // fallback: no nodes in tree so focus on Tree <div> itself
22183 tree.domNode.setAttribute("tabIndex
", "0");
22187 return new dojo.DeferredList(defs); // dojo.Deferred
22190 removeChild: function(/* treeNode */ node){
22191 this.inherited(arguments);
22193 var children = this.getChildren();
22194 if(children.length == 0){
22195 this.isExpandable = false;
22199 dojo.forEach(children, function(child){
22200 child._updateLayout();
22204 makeExpandable: function(){
22206 // if this node wasn't already showing the expando node,
22207 // turn it into one and call _setExpando()
22209 // TODO: hmm this isn't called from anywhere, maybe should remove it for 2.0
22211 this.isExpandable = true;
22212 this._setExpando(false);
22215 _onLabelFocus: function(evt){
22217 // Called when this row is focused (possibly programatically)
22218 // Note that we aren't using _onFocus() builtin to dijit
22219 // because it's called when focus is moved to a descendant TreeNode.
22222 this.tree._onNodeFocus(this);
22225 setSelected: function(/*Boolean*/ selected){
22227 // A Tree has a (single) currently selected node.
22228 // Mark that this node is/isn't that currently selected node.
22230 // In particular, setting a node as selected involves setting tabIndex
22231 // so that when user tabs to the tree, focus will go to that node (only).
22232 dijit.setWaiState(this.labelNode, "selected
", selected);
22233 dojo.toggleClass(this.rowNode, "dijitTreeRowSelected
", selected);
22236 setFocusable: function(/*Boolean*/ selected){
22238 // A Tree has a (single) node that's focusable.
22239 // Mark that this node is/isn't that currently focsuable node.
22241 // In particular, setting a node as selected involves setting tabIndex
22242 // so that when user tabs to the tree, focus will go to that node (only).
22244 this.labelNode.setAttribute("tabIndex
", selected ? "0" : "-1");
22247 _onClick: function(evt){
22249 // Handler for onclick event on a node
22252 this.tree._onClick(this, evt);
22254 _onDblClick: function(evt){
22256 // Handler for ondblclick event on a node
22259 this.tree._onDblClick(this, evt);
22262 _onMouseEnter: function(evt){
22264 // Handler for onmouseenter event on a node
22267 this.tree._onNodeMouseEnter(this, evt);
22270 _onMouseLeave: function(evt){
22272 // Handler for onmouseenter event on a node
22275 this.tree._onNodeMouseLeave(this, evt);
22281 [dijit._Widget, dijit._Templated],
22284 // This widget displays hierarchical data from a store.
22286 // store: [deprecated] String||dojo.data.Store
22287 // Deprecated. Use "model
" parameter instead.
22288 // The store to get data to display in the tree.
22291 // model: dijit.Tree.model
22292 // Interface to read tree data, get notifications of changes to tree data,
22293 // and for handling drop operations (i.e drag and drop onto the tree)
22296 // query: [deprecated] anything
22297 // Deprecated. User should specify query to the model directly instead.
22298 // Specifies datastore query to return the root item or top items for the tree.
22301 // label: [deprecated] String
22302 // Deprecated. Use dijit.tree.ForestStoreModel directly instead.
22303 // Used in conjunction with query parameter.
22304 // If a query is specified (rather than a root node id), and a label is also specified,
22305 // then a fake root node is created and displayed, with this label.
22308 // showRoot: [const] Boolean
22309 // Should the root node be displayed, or hidden?
22312 // childrenAttr: [deprecated] String[]
22313 // Deprecated. This information should be specified in the model.
22314 // One ore more attributes that holds children of a tree node
22315 childrenAttr: ["children
"],
22317 // path: String[] or Item[]
22318 // Full path from rootNode to selected node expressed as array of items or array of ids.
22319 // Since setting the path may be asynchronous (because ofwaiting on dojo.data), set("path
", ...)
22320 // returns a Deferred to indicate when the set is complete.
22323 // selectedItem: [readonly] Item
22324 // The currently selected item in this tree.
22325 // This property can only be set (via set('selectedItem', ...)) when that item is already
22326 // visible in the tree. (I.e. the tree has already been expanded to show that node.)
22327 // Should generally use `path` attribute to set the selected item instead.
22328 selectedItem: null,
22330 // openOnClick: Boolean
22331 // If true, clicking a folder node's label will open it, rather than calling onClick()
22332 openOnClick: false,
22334 // openOnDblClick: Boolean
22335 // If true, double-clicking a folder node's label will open it, rather than calling onDblClick()
22336 openOnDblClick: false,
22338 templateString: dojo.cache("dijit
", "templates
/Tree.html", "<div class=\"dijitTree dijitTreeContainer\" waiRole=\"tree\"\n\tdojoAttachEvent=\"onkeypress:_onKeyPress\">\n\t<div class=\"dijitInline dijitTreeIndent\" style=\"position: absolute; top: -9999px\" dojoAttachPoint=\"indentDetector\"></div>\n</div
>\n"),
22340 // persist: Boolean
22341 // Enables/disables use of cookies for state saving.
22344 // autoExpand: Boolean
22345 // Fully expand the tree on load. Overrides `persist`
22348 // dndController: [protected] String
22349 // Class name to use as as the dnd controller. Specifying this class enables DnD.
22350 // Generally you should specify this as "dijit
.tree
.dndSource
".
22351 dndController: null,
22353 // parameters to pull off of the tree and pass on to the dndController as its params
22354 dndParams: ["onDndDrop
","itemCreator
","onDndCancel
","checkAcceptance
", "checkItemAcceptance
", "dragThreshold
", "betweenThreshold
"],
22356 //declare the above items so they can be pulled from the tree's markup
22358 // onDndDrop: [protected] Function
22359 // Parameter to dndController, see `dijit.tree.dndSource.onDndDrop`.
22360 // Generally this doesn't need to be set.
22364 itemCreator: function(nodes, target, source){
22366 // Returns objects passed to `Tree.model.newItem()` based on DnD nodes
22367 // dropped onto the tree. Developer must override this method to enable
22368 // dropping from external sources onto this Tree, unless the Tree.model's items
22369 // happen to look like {id: 123, name: "Apple
" } with no other attributes.
22371 // For each node in nodes[], which came from source, create a hash of name/value
22372 // pairs to be passed to Tree.model.newItem(). Returns array of those hashes.
22373 // nodes: DomNode[]
22374 // The DOMNodes dragged from the source container
22376 // The target TreeNode.rowNode
22377 // source: dojo.dnd.Source
22378 // The source container the nodes were dragged from, perhaps another Tree or a plain dojo.dnd.Source
22379 // returns: Object[]
22380 // Array of name/value hashes for each new item to be added to the Tree, like:
22382 // | { id: 123, label: "apple
", foo: "bar
" },
22383 // | { id: 456, label: "pear
", zaz: "bam
" }
22392 // onDndCancel: [protected] Function
22393 // Parameter to dndController, see `dijit.tree.dndSource.onDndCancel`.
22394 // Generally this doesn't need to be set.
22398 checkAcceptance: function(source, nodes){
22400 // Checks if the Tree itself can accept nodes from this source
22401 // source: dijit.tree._dndSource
22402 // The source which provides items
22403 // nodes: DOMNode[]
22404 // Array of DOM nodes corresponding to nodes being dropped, dijitTreeRow nodes if
22405 // source is a dijit.Tree.
22408 return true; // Boolean
22411 checkAcceptance: null,
22414 checkItemAcceptance: function(target, source, position){
22416 // Stub function to be overridden if one wants to check for the ability to drop at the node/item level
22418 // In the base case, this is called to check if target can become a child of source.
22419 // When betweenThreshold is set, position="before
" or "after
" means that we
22420 // are asking if the source node can be dropped before/after the target node.
22422 // The dijitTreeRoot DOM node inside of the TreeNode that we are dropping on to
22423 // Use dijit.getEnclosingWidget(target) to get the TreeNode.
22424 // source: dijit.tree.dndSource
22425 // The (set of) nodes we are dropping
22426 // position: String
22427 // "over
", "before
", or "after
"
22430 return true; // Boolean
22433 checkItemAcceptance: null,
22435 // dragThreshold: Integer
22436 // Number of pixels mouse moves before it's considered the start of a drag operation
22439 // betweenThreshold: Integer
22440 // Set to a positive value to allow drag and drop "between
" nodes.
22442 // If during DnD mouse is over a (target) node but less than betweenThreshold
22443 // pixels from the bottom edge, dropping the the dragged node will make it
22444 // the next sibling of the target node, rather than the child.
22446 // Similarly, if mouse is over a target node but less that betweenThreshold
22447 // pixels from the top edge, dropping the dragged node will make it
22448 // the target node's previous sibling rather than the target node's child.
22449 betweenThreshold: 0,
22451 // _nodePixelIndent: Integer
22452 // Number of pixels to indent tree nodes (relative to parent node).
22453 // Default is 19 but can be overridden by setting CSS class dijitTreeIndent
22454 // and calling resize() or startup() on tree after it's in the DOM.
22455 _nodePixelIndent: 19,
22457 _publish: function(/*String*/ topicName, /*Object*/ message){
22459 // Publish a message for this widget/topic
22460 dojo.publish(this.id, [dojo.mixin({tree: this, event: topicName}, message || {})]);
22463 postMixInProperties: function(){
22466 if(this.autoExpand){
22467 // There's little point in saving opened/closed state of nodes for a Tree
22468 // that initially opens all it's nodes.
22469 this.persist = false;
22472 this._itemNodesMap={};
22474 if(!this.cookieName){
22475 this.cookieName = this.id + "SaveStateCookie
";
22478 this._loadDeferred = new dojo.Deferred();
22480 this.inherited(arguments);
22483 postCreate: function(){
22486 // Create glue between store and Tree, if not specified directly by user
22488 this._store2model();
22491 // monitor changes to items
22492 this.connect(this.model, "onChange
", "_onItemChange
");
22493 this.connect(this.model, "onChildrenChange
", "_onItemChildrenChange
");
22494 this.connect(this.model, "onDelete
", "_onItemDelete
");
22498 this.inherited(arguments);
22500 if(this.dndController){
22501 if(dojo.isString(this.dndController)){
22502 this.dndController = dojo.getObject(this.dndController);
22505 for(var i=0; i<this.dndParams.length;i++){
22506 if(this[this.dndParams[i]]){
22507 params[this.dndParams[i]] = this[this.dndParams[i]];
22510 this.dndController = new this.dndController(this, params);
22514 _store2model: function(){
22516 // User specified a store&query rather than model, so create model from store/query
22517 this._v10Compat = true;
22518 dojo.deprecated("Tree
: from version
2.0, should specify a model object rather than a store
/query
");
22520 var modelParams = {
22521 id: this.id + "_ForestStoreModel
",
22524 childrenAttrs: this.childrenAttr
22527 // Only override the model's mayHaveChildren() method if the user has specified an override
22528 if(this.params.mayHaveChildren){
22529 modelParams.mayHaveChildren = dojo.hitch(this, "mayHaveChildren
");
22532 if(this.params.getItemChildren){
22533 modelParams.getChildren = dojo.hitch(this, function(item, onComplete, onError){
22534 this.getItemChildren((this._v10Compat && item === this.model.root) ? null : item, onComplete, onError);
22537 this.model = new dijit.tree.ForestStoreModel(modelParams);
22539 // For backwards compatibility, the visibility of the root node is controlled by
22540 // whether or not the user has specified a label
22541 this.showRoot = Boolean(this.label);
22544 onLoad: function(){
22546 // Called when tree finishes loading and expanding.
22548 // If persist == true the loading may encompass many levels of fetches
22549 // from the data store, each asynchronous. Waits for all to finish.
22556 // Initial load of the tree.
22557 // Load root node (possibly hidden) and it's children.
22558 this.model.getRoot(
22559 dojo.hitch(this, function(item){
22560 var rn = (this.rootNode = this.tree._createTreeNode({
22563 isExpandable: true,
22564 label: this.label || this.getLabel(item),
22565 indent: this.showRoot ? 0 : -1
22567 if(!this.showRoot){
22568 rn.rowNode.style.display="none
";
22570 this.domNode.appendChild(rn.domNode);
22571 var identity = this.model.getIdentity(item);
22572 if(this._itemNodesMap[identity]){
22573 this._itemNodesMap[identity].push(rn);
22575 this._itemNodesMap[identity] = [rn];
22578 rn._updateLayout(); // sets "dijitTreeIsRoot
" CSS classname
22580 // load top level children and then fire onLoad() event
22581 this._expandNode(rn).addCallback(dojo.hitch(this, function(){
22582 this._loadDeferred.callback(true);
22587 console.error(this, ": error loading root
: ", err);
22592 getNodesByItem: function(/*dojo.data.Item or id*/ item){
22594 // Returns all tree nodes that refer to an item
22596 // Array of tree nodes that refer to passed item
22598 if(!item){ return []; }
22599 var identity = dojo.isString(item) ? item : this.model.getIdentity(item);
22600 // return a copy so widget don't get messed up by changes to returned array
22601 return [].concat(this._itemNodesMap[identity]);
22604 _setSelectedItemAttr: function(/*dojo.data.Item or id*/ item){
22606 // Select a tree node related to passed item.
22607 // WARNING: if model use multi-parented items or desired tree node isn't already loaded
22608 // behavior is undefined. Use set('path', ...) instead.
22610 var oldValue = this.get("selectedItem
");
22611 var identity = (!item || dojo.isString(item)) ? item : this.model.getIdentity(item);
22612 if(identity == oldValue ? this.model.getIdentity(oldValue) : null){ return; }
22613 var nodes = this._itemNodesMap[identity];
22614 this._selectNode((nodes && nodes[0]) || null); //select the first item
22617 _getSelectedItemAttr: function(){
22619 // Return item related to selected tree node.
22620 return this.selectedNode && this.selectedNode.item;
22623 _setPathAttr: function(/*Item[] || String[]*/ path){
22625 // Select the tree node identified by passed path.
22627 // Array of items or item id's
22629 // Deferred to indicate when the set is complete
22631 var d = new dojo.Deferred();
22633 this._selectNode(null);
22634 if(!path || !path.length){
22639 // If this is called during initialization, defer running until Tree has finished loading
22640 this._loadDeferred.addCallback(dojo.hitch(this, function(){
22641 if(!this.rootNode){
22642 d.reject(new Error("!this.rootNode
"));
22645 if(path[0] !== this.rootNode.item && (dojo.isString(path[0]) && path[0] != this.model.getIdentity(this.rootNode.item))){
22646 d.reject(new Error(this.id + ":path
[0] doesn
't match this.rootNode.item. Maybe you are using the wrong tree."));
22651 var node = this.rootNode;
22653 function advance(){
22655 // Called when "node" has completed loading and expanding. Pop the next item from the path
22656 // (which must be a child of "node") and advance to it, and then recurse.
22658 // Set item and identity to next item in path (node is pointing to the item that was popped
22659 // from the path _last_ time.
22660 var item = path.shift(),
22661 identity = dojo.isString(item) ? item : this.model.getIdentity(item);
22663 // Change "node" from previous item in path to the item we just popped from path
22664 dojo.some(this._itemNodesMap[identity], function(n){
22665 if(n.getParent() == node){
22673 // Need to do more expanding
22674 this._expandNode(node).addCallback(dojo.hitch(this, advance));
22676 // Final destination node, select it
22677 this._selectNode(node);
22679 // signal that path setting is finished
22684 this._expandNode(node).addCallback(dojo.hitch(this, advance));
22690 _getPathAttr: function(){
22692 // Return an array of items that is the path to selected tree node.
22693 if(!this.selectedNode){ return; }
22695 var treeNode = this.selectedNode;
22696 while(treeNode && treeNode !== this.rootNode){
22697 res.unshift(treeNode.item);
22698 treeNode = treeNode.getParent();
22700 res.unshift(this.rootNode.item);
22704 ////////////// Data store related functions //////////////////////
22705 // These just get passed to the model; they are here for back-compat
22707 mayHaveChildren: function(/*dojo.data.Item*/ item){
22709 // Deprecated. This should be specified on the model itself.
22711 // Overridable function to tell if an item has or may have children.
22712 // Controls whether or not +/- expando icon is shown.
22713 // (For efficiency reasons we may not want to check if an element actually
22714 // has children until user clicks the expando node)
22719 getItemChildren: function(/*dojo.data.Item*/ parentItem, /*function(items)*/ onComplete){
22721 // Deprecated. This should be specified on the model itself.
22723 // Overridable function that return array of child items of given parent item,
22724 // or if parentItem==null then return top items in tree
22729 ///////////////////////////////////////////////////////
22730 // Functions for converting an item to a TreeNode
22731 getLabel: function(/*dojo.data.Item*/ item){
22733 // Overridable function to get the label for a tree node (given the item)
22736 return this.model.getLabel(item); // String
22739 getIconClass: function(/*dojo.data.Item*/ item, /*Boolean*/ opened){
22741 // Overridable function to return CSS class name to display icon
22744 return (!item || this.model.mayHaveChildren(item)) ? (opened ? "dijitFolderOpened" : "dijitFolderClosed") : "dijitLeaf"
22747 getLabelClass: function(/*dojo.data.Item*/ item, /*Boolean*/ opened){
22749 // Overridable function to return CSS class name to display label
22754 getRowClass: function(/*dojo.data.Item*/ item, /*Boolean*/ opened){
22756 // Overridable function to return CSS class name to display row
22761 getIconStyle: function(/*dojo.data.Item*/ item, /*Boolean*/ opened){
22763 // Overridable function to return CSS styles to display icon
22765 // Object suitable for input to dojo.style() like {backgroundImage: "url(...)"}
22770 getLabelStyle: function(/*dojo.data.Item*/ item, /*Boolean*/ opened){
22772 // Overridable function to return CSS styles to display label
22774 // Object suitable for input to dojo.style() like {color: "red", background: "green"}
22779 getRowStyle: function(/*dojo.data.Item*/ item, /*Boolean*/ opened){
22781 // Overridable function to return CSS styles to display row
22783 // Object suitable for input to dojo.style() like {background-color: "#bbb"}
22788 getTooltip: function(/*dojo.data.Item*/ item){
22790 // Overridable function to get the tooltip for a tree node (given the item)
22793 return ""; // String
22796 /////////// Keyboard and Mouse handlers ////////////////////
22798 _onKeyPress: function(/*Event*/ e){
22800 // Translates keypress events into commands for the controller
22801 if(e.altKey){ return; }
22802 var dk = dojo.keys;
22803 var treeNode = dijit.getEnclosingWidget(e.target);
22804 if(!treeNode){ return; }
22806 var key = e.charOrCode;
22807 if(typeof key == "string"){ // handle printables (letter navigation)
22808 // Check for key navigation.
22809 if(!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey){
22810 this._onLetterKeyNav( { node: treeNode, key: key.toLowerCase() } );
22813 }else{ // handle non-printables (arrow keys)
22814 // clear record of recent printables (being saved for multi-char letter navigation),
22815 // because "a", down-arrow, "b" shouldn't search
for "ab"
22816 if(this._curSearch
){
22817 clearTimeout(this._curSearch
.timer
);
22818 delete this._curSearch
;
22821 var map
= this._keyHandlerMap
;
22823 // setup table mapping keys to events
22825 map
[dk
.ENTER
]="_onEnterKey";
22826 map
[this.isLeftToRight() ? dk
.LEFT_ARROW
: dk
.RIGHT_ARROW
]="_onLeftArrow";
22827 map
[this.isLeftToRight() ? dk
.RIGHT_ARROW
: dk
.LEFT_ARROW
]="_onRightArrow";
22828 map
[dk
.UP_ARROW
]="_onUpArrow";
22829 map
[dk
.DOWN_ARROW
]="_onDownArrow";
22830 map
[dk
.HOME
]="_onHomeKey";
22831 map
[dk
.END
]="_onEndKey";
22832 this._keyHandlerMap
= map
;
22834 if(this._keyHandlerMap
[key
]){
22835 this[this._keyHandlerMap
[key
]]( { node
: treeNode
, item
: treeNode
.item
, evt
: e
} );
22841 _onEnterKey: function(/*Object*/ message
, /*Event*/ evt
){
22842 this._publish("execute", { item
: message
.item
, node
: message
.node
} );
22843 this._selectNode(message
.node
);
22844 this.onClick(message
.item
, message
.node
, evt
);
22847 _onDownArrow: function(/*Object*/ message
){
22849 // down arrow pressed; get next visible node, set focus there
22850 var node
= this._getNextNode(message
.node
);
22851 if(node
&& node
.isTreeNode
){
22852 this.focusNode(node
);
22856 _onUpArrow: function(/*Object*/ message
){
22858 // Up arrow pressed; move to previous visible node
22860 var node
= message
.node
;
22862 // if younger siblings
22863 var previousSibling
= node
.getPreviousSibling();
22864 if(previousSibling
){
22865 node
= previousSibling
;
22866 // if the previous node is expanded, dive in deep
22867 while(node
.isExpandable
&& node
.isExpanded
&& node
.hasChildren()){
22868 // move to the last child
22869 var children
= node
.getChildren();
22870 node
= children
[children
.length
-1];
22873 // if this is the first child, return the parent
22874 // unless the parent is the root of a tree with a hidden root
22875 var parent
= node
.getParent();
22876 if(!(!this.showRoot
&& parent
=== this.rootNode
)){
22881 if(node
&& node
.isTreeNode
){
22882 this.focusNode(node
);
22886 _onRightArrow: function(/*Object*/ message
){
22888 // Right arrow pressed; go to child node
22889 var node
= message
.node
;
22891 // if not expanded, expand, else move to 1st child
22892 if(node
.isExpandable
&& !node
.isExpanded
){
22893 this._expandNode(node
);
22894 }else if(node
.hasChildren()){
22895 node
= node
.getChildren()[0];
22896 if(node
&& node
.isTreeNode
){
22897 this.focusNode(node
);
22902 _onLeftArrow: function(/*Object*/ message
){
22904 // Left arrow pressed.
22905 // If not collapsed, collapse, else move to parent.
22907 var node
= message
.node
;
22909 if(node
.isExpandable
&& node
.isExpanded
){
22910 this._collapseNode(node
);
22912 var parent
= node
.getParent();
22913 if(parent
&& parent
.isTreeNode
&& !(!this.showRoot
&& parent
=== this.rootNode
)){
22914 this.focusNode(parent
);
22919 _onHomeKey: function(){
22921 // Home key pressed; get first visible node, and set focus there
22922 var node
= this._getRootOrFirstNode();
22924 this.focusNode(node
);
22928 _onEndKey: function(/*Object*/ message
){
22930 // End key pressed; go to last visible node.
22932 var node
= this.rootNode
;
22933 while(node
.isExpanded
){
22934 var c
= node
.getChildren();
22935 node
= c
[c
.length
- 1];
22938 if(node
&& node
.isTreeNode
){
22939 this.focusNode(node
);
22943 // multiCharSearchDuration: Number
22944 // If multiple characters are typed where each keystroke happens within
22945 // multiCharSearchDuration of the previous keystroke,
22946 // search for nodes matching all the keystrokes.
22948 // For example, typing "ab" will search for entries starting with
22949 // "ab" unless the delay between "a" and "b" is greater than multiCharSearchDuration.
22950 multiCharSearchDuration
: 250,
22952 _onLetterKeyNav: function(message
){
22954 // Called when user presses a prinatable key; search for node starting with recently typed letters.
22956 // Like { node: TreeNode, key: 'a' } where key is the key the user pressed.
22958 // Branch depending on whether this key starts a new search, or modifies an existing search
22959 var cs
= this._curSearch
;
22961 // We are continuing a search. Ex: user has pressed 'a', and now has pressed
22962 // 'b', so we want to search for nodes starting w/"ab".
22963 cs
.pattern
= cs
.pattern
+ message
.key
;
22964 clearTimeout(cs
.timer
);
22966 // We are starting a new search
22967 cs
= this._curSearch
= {
22968 pattern
: message
.key
,
22969 startNode
: message
.node
22973 // set/reset timer to forget recent keystrokes
22975 cs
.timer
= setTimeout(function(){
22976 delete self
._curSearch
;
22977 }, this.multiCharSearchDuration
);
22979 // Navigate to TreeNode matching keystrokes [entered so far].
22980 var node
= cs
.startNode
;
22982 node
= this._getNextNode(node
);
22983 //check for last node, jump to first node if necessary
22985 node
= this._getRootOrFirstNode();
22987 }while(node
!== cs
.startNode
&& (node
.label
.toLowerCase().substr(0, cs
.pattern
.length
) != cs
.pattern
));
22988 if(node
&& node
.isTreeNode
){
22989 // no need to set focus if back where we started
22990 if(node
!== cs
.startNode
){
22991 this.focusNode(node
);
22996 _onClick: function(/*TreeNode*/ nodeWidget
, /*Event*/ e
){
22998 // Translates click events into commands for the controller to process
23000 var domElement
= e
.target
,
23001 isExpandoClick
= (domElement
== nodeWidget
.expandoNode
|| domElement
== nodeWidget
.expandoNodeText
);
23003 if( (this.openOnClick
&& nodeWidget
.isExpandable
) || isExpandoClick
){
23004 // expando node was clicked, or label of a folder node was clicked; open it
23005 if(nodeWidget
.isExpandable
){
23006 this._onExpandoClick({node
:nodeWidget
});
23009 this._publish("execute", { item
: nodeWidget
.item
, node
: nodeWidget
, evt
: e
} );
23010 this.onClick(nodeWidget
.item
, nodeWidget
, e
);
23011 this.focusNode(nodeWidget
);
23013 if(!isExpandoClick
){
23014 this._selectNode(nodeWidget
);
23018 _onDblClick: function(/*TreeNode*/ nodeWidget
, /*Event*/ e
){
23020 // Translates double-click events into commands for the controller to process
23022 var domElement
= e
.target
,
23023 isExpandoClick
= (domElement
== nodeWidget
.expandoNode
|| domElement
== nodeWidget
.expandoNodeText
);
23025 if( (this.openOnDblClick
&& nodeWidget
.isExpandable
) ||isExpandoClick
){
23026 // expando node was clicked, or label of a folder node was clicked; open it
23027 if(nodeWidget
.isExpandable
){
23028 this._onExpandoClick({node
:nodeWidget
});
23031 this._publish("execute", { item
: nodeWidget
.item
, node
: nodeWidget
, evt
: e
} );
23032 this.onDblClick(nodeWidget
.item
, nodeWidget
, e
);
23033 this.focusNode(nodeWidget
);
23035 if(!isExpandoClick
){
23036 this._selectNode(nodeWidget
);
23041 _onExpandoClick: function(/*Object*/ message
){
23043 // User clicked the +/- icon; expand or collapse my children.
23044 var node
= message
.node
;
23046 // If we are collapsing, we might be hiding the currently focused node.
23047 // Also, clicking the expando node might have erased focus from the current node.
23048 // For simplicity's sake just focus on the node with the expando.
23049 this.focusNode(node
);
23051 if(node
.isExpanded
){
23052 this._collapseNode(node
);
23054 this._expandNode(node
);
23058 onClick: function(/* dojo.data */ item
, /*TreeNode*/ node
, /*Event*/ evt
){
23060 // Callback when a tree node is clicked
23064 onDblClick: function(/* dojo.data */ item
, /*TreeNode*/ node
, /*Event*/ evt
){
23066 // Callback when a tree node is double-clicked
23070 onOpen: function(/* dojo.data */ item
, /*TreeNode*/ node
){
23072 // Callback when a node is opened
23076 onClose: function(/* dojo.data */ item
, /*TreeNode*/ node
){
23078 // Callback when a node is closed
23083 _getNextNode: function(node
){
23085 // Get next visible node
23087 if(node
.isExpandable
&& node
.isExpanded
&& node
.hasChildren()){
23088 // if this is an expanded node, get the first child
23089 return node
.getChildren()[0]; // _TreeNode
23091 // find a parent node with a sibling
23092 while(node
&& node
.isTreeNode
){
23093 var returnNode
= node
.getNextSibling();
23095 return returnNode
; // _TreeNode
23097 node
= node
.getParent();
23103 _getRootOrFirstNode: function(){
23105 // Get first visible node
23106 return this.showRoot
? this.rootNode
: this.rootNode
.getChildren()[0];
23109 _collapseNode: function(/*_TreeNode*/ node
){
23111 // Called when the user has requested to collapse the node
23113 if(node
._expandNodeDeferred
){
23114 delete node
._expandNodeDeferred
;
23117 if(node
.isExpandable
){
23118 if(node
.state
== "LOADING"){
23119 // ignore clicks while we are in the process of loading data
23124 this.onClose(node
.item
, node
);
23127 this._state(node
.item
,false);
23133 _expandNode: function(/*_TreeNode*/ node
, /*Boolean?*/ recursive
){
23135 // Called when the user has requested to expand the node
23137 // Internal flag used when _expandNode() calls itself, don't set.
23139 // Deferred that fires when the node is loaded and opened and (if persist=true) all it's descendants
23140 // that were previously opened too
23142 if(node
._expandNodeDeferred
&& !recursive
){
23143 // there's already an expand in progress (or completed), so just return
23144 return node
._expandNodeDeferred
; // dojo.Deferred
23147 var model
= this.model
,
23151 switch(node
.state
){
23153 // need to load all the children, and then expand
23154 node
.markProcessing();
23156 // Setup deferred to signal when the load and expand are finished.
23157 // Save that deferred in this._expandDeferred as a flag that operation is in progress.
23158 var def
= (node
._expandNodeDeferred
= new dojo
.Deferred());
23160 // Get the children
23164 node
.unmarkProcessing();
23166 // Display the children and also start expanding any children that were previously expanded
23167 // (if this.persist == true). The returned Deferred will fire when those expansions finish.
23168 var scid
= node
.setChildItems(items
);
23170 // Call _expandNode() again but this time it will just to do the animation (default branch).
23171 // The returned Deferred will fire when the animation completes.
23172 // TODO: seems like I can avoid recursion and just use a deferred to sequence the events?
23173 var ed
= _this
._expandNode(node
, true);
23175 // After the above two tasks (setChildItems() and recursive _expandNode()) finish,
23176 // signal that I am done.
23177 scid
.addCallback(function(){
23178 ed
.addCallback(function(){
23184 console
.error(_this
, ": error loading root children: ", err
);
23189 default: // "LOADED"
23190 // data is already loaded; just expand node
23191 def
= (node
._expandNodeDeferred
= node
.expand());
23193 this.onOpen(node
.item
, node
);
23196 this._state(item
, true);
23201 return def
; // dojo.Deferred
23204 ////////////////// Miscellaneous functions ////////////////
23206 focusNode: function(/* _tree.Node */ node
){
23208 // Focus on the specified node (which must be visible)
23212 // set focus so that the label will be voiced using screen readers
23213 dijit
.focus(node
.labelNode
);
23216 _selectNode: function(/*_tree.Node*/ node
){
23218 // Mark specified node as select, and unmark currently selected node.
23222 if(this.selectedNode
&& !this.selectedNode
._destroyed
){
23223 this.selectedNode
.setSelected(false);
23226 node
.setSelected(true);
23228 this.selectedNode
= node
;
23231 _onNodeFocus: function(/*dijit._Widget*/ node
){
23233 // Called when a TreeNode gets focus, either by user clicking
23234 // it, or programatically by arrow key handling code.
23236 // It marks that the current node is the selected one, and the previously
23237 // selected node no longer is.
23239 if(node
&& node
!= this.lastFocused
){
23240 if(this.lastFocused
&& !this.lastFocused
._destroyed
){
23241 // mark that the previously focsable node is no longer focusable
23242 this.lastFocused
.setFocusable(false);
23245 // mark that the new node is the currently selected one
23246 node
.setFocusable(true);
23247 this.lastFocused
= node
;
23251 _onNodeMouseEnter: function(/*dijit._Widget*/ node
){
23253 // Called when mouse is over a node (onmouseenter event),
23254 // this is monitored by the DND code
23257 _onNodeMouseLeave: function(/*dijit._Widget*/ node
){
23259 // Called when mouse leaves a node (onmouseleave event),
23260 // this is monitored by the DND code
23263 //////////////// Events from the model //////////////////////////
23265 _onItemChange: function(/*Item*/ item
){
23267 // Processes notification of a change to an item's scalar values like label
23268 var model
= this.model
,
23269 identity
= model
.getIdentity(item
),
23270 nodes
= this._itemNodesMap
[identity
];
23273 var label
= this.getLabel(item
),
23274 tooltip
= this.getTooltip(item
);
23275 dojo
.forEach(nodes
, function(node
){
23277 item
: item
, // theoretically could be new JS Object representing same item
23281 node
._updateItemClasses(item
);
23286 _onItemChildrenChange: function(/*dojo.data.Item*/ parent
, /*dojo.data.Item[]*/ newChildrenList
){
23288 // Processes notification of a change to an item's children
23289 var model
= this.model
,
23290 identity
= model
.getIdentity(parent
),
23291 parentNodes
= this._itemNodesMap
[identity
];
23294 dojo
.forEach(parentNodes
,function(parentNode
){
23295 parentNode
.setChildItems(newChildrenList
);
23300 _onItemDelete: function(/*Item*/ item
){
23302 // Processes notification of a deletion of an item
23303 var model
= this.model
,
23304 identity
= model
.getIdentity(item
),
23305 nodes
= this._itemNodesMap
[identity
];
23308 dojo
.forEach(nodes
,function(node
){
23309 var parent
= node
.getParent();
23311 // if node has not already been orphaned from a _onSetItem(parent, "children", ..) call...
23312 parent
.removeChild(node
);
23314 node
.destroyRecursive();
23316 delete this._itemNodesMap
[identity
];
23320 /////////////// Miscellaneous funcs
23322 _initState: function(){
23324 // Load in which nodes should be opened automatically
23326 var cookie
= dojo
.cookie(this.cookieName
);
23327 this._openedItemIds
= {};
23329 dojo
.forEach(cookie
.split(','), function(item
){
23330 this._openedItemIds
[item
] = true;
23335 _state: function(item
,expanded
){
23337 // Query or set expanded state for an item,
23341 var id
=this.model
.getIdentity(item
);
23342 if(arguments
.length
=== 1){
23343 return this._openedItemIds
[id
];
23346 this._openedItemIds
[id
] = true;
23348 delete this._openedItemIds
[id
];
23351 _saveState: function(){
23353 // Create and save a cookie with the currently expanded nodes identifiers
23358 for(var id
in this._openedItemIds
){
23361 dojo
.cookie(this.cookieName
, ary
.join(","), {expires
:365});
23364 destroy: function(){
23365 if(this._curSearch
){
23366 clearTimeout(this._curSearch
.timer
);
23367 delete this._curSearch
;
23370 this.rootNode
.destroyRecursive();
23372 if(this.dndController
&& !dojo
.isString(this.dndController
)){
23373 this.dndController
.destroy();
23375 this.rootNode
= null;
23376 this.inherited(arguments
);
23379 destroyRecursive: function(){
23380 // A tree is treated as a leaf, not as a node with children (like a grid),
23381 // but defining destroyRecursive for back-compat.
23385 resize: function(changeSize
){
23387 dojo
.marginBox(this.domNode
, changeSize
);
23388 dojo
.style(this.domNode
, "overflow", "auto"); // for scrollbars
23391 // The only JS sizing involved w/tree is the indentation, which is specified
23392 // in CSS and read in through this dummy indentDetector node (tree must be
23393 // visible and attached to the DOM to read this)
23394 this._nodePixelIndent
= dojo
.marginBox(this.tree
.indentDetector
).w
;
23396 if(this.tree
.rootNode
){
23397 // If tree has already loaded, then reset indent for all the nodes
23398 this.tree
.rootNode
.set('indent', this.showRoot
? 0 : -1);
23402 _createTreeNode: function(/*Object*/ args
){
23404 // creates a TreeNode
23406 // Developers can override this method to define their own TreeNode class;
23407 // However it will probably be removed in a future release in favor of a way
23408 // of just specifying a widget for the label, rather than one that contains
23409 // the children too.
23410 return new dijit
._TreeNode(args
);
23414 // For back-compat. TODO: remove in 2.0
23420 if(!dojo
._hasResource
["dojo.dnd.Container"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
23421 dojo
._hasResource
["dojo.dnd.Container"] = true;
23422 dojo
.provide("dojo.dnd.Container");
23430 "Over" - mouse over a container
23431 Container item states:
23433 "Over" - mouse over a container item
23437 dojo.declare("dojo.dnd.__ContainerArgs", [], {
23438 creator: function(){
23440 // a creator function, which takes a data item, and returns an object like that:
23441 // {node: newNode, data: usedData, type: arrayOfStrings}
23444 // skipForm: Boolean
23445 // don't start the drag operation, if clicked on form elements
23448 // dropParent: Node||String
23449 // node or node's id to use as the parent node for dropped items
23450 // (must be underneath the 'node' parameter in the DOM)
23453 // _skipStartup: Boolean
23454 // skip startup(), which collects children, for deferred initialization
23455 // (this is used in the markup mode)
23456 _skipStartup: false
23459 dojo.dnd.Item = function(){
23461 // Represents (one of) the source node(s) being dragged.
23462 // Contains (at least) the "type" and "data" attributes.
23464 // Type(s) of this item, by default this is ["text"]
23466 // Logical representation of the object being dragged.
23467 // If the drag object's type is "text" then data is a String,
23468 // if it's another type then data could be a different Object,
23469 // perhaps a name/value hash.
23476 dojo
.declare("dojo.dnd.Container", null, {
23478 // a Container object, which knows when mouse hovers over it,
23479 // and over which element it hovers
23481 // object attributes (for markup)
23485 // current: DomNode
23486 // The DOM node the mouse is currently hovered over
23489 // map: Hash<String, dojo.dnd.Item>
23490 // Map from an item's id (which is also the DOMNode's id) to
23491 // the dojo.dnd.Item itself.
23495 constructor: function(node
, params
){
23497 // a constructor of the Container
23499 // node or node's id to build the container on
23500 // params: dojo.dnd.__ContainerArgs
23501 // a dictionary of parameters
23502 this.node
= dojo
.byId(node
);
23503 if(!params
){ params
= {}; }
23504 this.creator
= params
.creator
|| null;
23505 this.skipForm
= params
.skipForm
;
23506 this.parent
= params
.dropParent
&& dojo
.byId(params
.dropParent
);
23508 // class-specific variables
23510 this.current
= null;
23513 this.containerState
= "";
23514 dojo
.addClass(this.node
, "dojoDndContainer");
23516 // mark up children
23517 if(!(params
&& params
._skipStartup
)){
23523 dojo
.connect(this.node
, "onmouseover", this, "onMouseOver"),
23524 dojo
.connect(this.node
, "onmouseout", this, "onMouseOut"),
23525 // cancel text selection and text dragging
23526 dojo
.connect(this.node
, "ondragstart", this, "onSelectStart"),
23527 dojo
.connect(this.node
, "onselectstart", this, "onSelectStart")
23531 // object attributes (for markup)
23532 creator: function(){
23534 // creator function, dummy at the moment
23537 // abstract access to the map
23538 getItem: function(/*String*/ key
){
23540 // returns a data item by its key (id)
23541 return this.map
[key
]; // dojo.dnd.Item
23543 setItem: function(/*String*/ key
, /*dojo.dnd.Item*/ data
){
23545 // associates a data item with its key (id)
23546 this.map
[key
] = data
;
23548 delItem: function(/*String*/ key
){
23550 // removes a data item from the map by its key (id)
23551 delete this.map
[key
];
23553 forInItems: function(/*Function*/ f
, /*Object?*/ o
){
23555 // iterates over a data map skipping members that
23556 // are present in the empty object (IE and/or 3rd-party libraries).
23557 o
= o
|| dojo
.global
;
23558 var m
= this.map
, e
= dojo
.dnd
._empty
;
23560 if(i
in e
){ continue; }
23561 f
.call(o
, m
[i
], i
, this);
23563 return o
; // Object
23565 clearItems: function(){
23567 // removes all data items from the map
23572 getAllNodes: function(){
23574 // returns a list (an array) of all valid child nodes
23575 return dojo
.query("> .dojoDndItem", this.parent
); // NodeList
23579 // sync up the node list with the data map
23581 this.getAllNodes().forEach(function(node
){
23583 var item
= this.getItem(node
.id
);
23585 map
[node
.id
] = item
;
23589 node
.id
= dojo
.dnd
.getUniqueId();
23591 var type
= node
.getAttribute("dndType"),
23592 data
= node
.getAttribute("dndData");
23594 data
: data
|| node
.innerHTML
,
23595 type
: type
? type
.split(/\s*,\s*/) : ["text"]
23599 return this; // self
23601 insertNodes: function(data
, before
, anchor
){
23603 // inserts an array of new nodes before/after an anchor node
23605 // a list of data items, which should be processed by the creator function
23607 // insert before the anchor, if true, and after the anchor otherwise
23609 // the anchor node to be used as a point of insertion
23610 if(!this.parent
.firstChild
){
23614 anchor
= this.parent
.firstChild
;
23618 anchor
= anchor
.nextSibling
;
23622 for(var i
= 0; i
< data
.length
; ++i
){
23623 var t
= this._normalizedCreator(data
[i
]);
23624 this.setItem(t
.node
.id
, {data
: t
.data
, type
: t
.type
});
23625 this.parent
.insertBefore(t
.node
, anchor
);
23628 for(var i
= 0; i
< data
.length
; ++i
){
23629 var t
= this._normalizedCreator(data
[i
]);
23630 this.setItem(t
.node
.id
, {data
: t
.data
, type
: t
.type
});
23631 this.parent
.appendChild(t
.node
);
23634 return this; // self
23636 destroy: function(){
23638 // prepares this object to be garbage-collected
23639 dojo
.forEach(this.events
, dojo
.disconnect
);
23641 this.node
= this.parent
= this.current
= null;
23645 markupFactory: function(params
, node
){
23646 params
._skipStartup
= true;
23647 return new dojo
.dnd
.Container(node
, params
);
23649 startup: function(){
23651 // collects valid child items and populate the map
23653 // set up the real parent node
23655 // use the standard algorithm, if not assigned
23656 this.parent
= this.node
;
23657 if(this.parent
.tagName
.toLowerCase() == "table"){
23658 var c
= this.parent
.getElementsByTagName("tbody");
23659 if(c
&& c
.length
){ this.parent
= c
[0]; }
23662 this.defaultCreator
= dojo
.dnd
._defaultCreator(this.parent
);
23664 // process specially marked children
23669 onMouseOver: function(e
){
23671 // event processor for onmouseover
23674 var n
= e
.relatedTarget
;
23676 if(n
== this.node
){ break; }
23684 this._changeState("Container", "Over");
23685 this.onOverEvent();
23687 n
= this._getChildByEvent(e
);
23688 if(this.current
== n
){ return; }
23689 if(this.current
){ this._removeItemClass(this.current
, "Over"); }
23690 if(n
){ this._addItemClass(n
, "Over"); }
23693 onMouseOut: function(e
){
23695 // event processor for onmouseout
23698 for(var n
= e
.relatedTarget
; n
;){
23699 if(n
== this.node
){ return; }
23707 this._removeItemClass(this.current
, "Over");
23708 this.current
= null;
23710 this._changeState("Container", "");
23713 onSelectStart: function(e
){
23715 // event processor for onselectevent and ondragevent
23718 if(!this.skipForm
|| !dojo
.dnd
.isFormElement(e
)){
23724 onOverEvent: function(){
23726 // this function is called once, when mouse is over our container
23728 onOutEvent: function(){
23730 // this function is called once, when mouse is out of our container
23732 _changeState: function(type
, newState
){
23734 // changes a named state to new state value
23736 // a name of the state to change
23737 // newState: String
23739 var prefix
= "dojoDnd" + type
;
23740 var state
= type
.toLowerCase() + "State";
23741 //dojo.replaceClass(this.node, prefix + newState, prefix + this[state]);
23742 dojo
.removeClass(this.node
, prefix
+ this[state
]);
23743 dojo
.addClass(this.node
, prefix
+ newState
);
23744 this[state
] = newState
;
23746 _addItemClass: function(node
, type
){
23748 // adds a class with prefix "dojoDndItem"
23752 // a variable suffix for a class name
23753 dojo
.addClass(node
, "dojoDndItem" + type
);
23755 _removeItemClass: function(node
, type
){
23757 // removes a class with prefix "dojoDndItem"
23761 // a variable suffix for a class name
23762 dojo
.removeClass(node
, "dojoDndItem" + type
);
23764 _getChildByEvent: function(e
){
23766 // gets a child, which is under the mouse at the moment, or null
23769 var node
= e
.target
;
23771 for(var parent
= node
.parentNode
; parent
; node
= parent
, parent
= node
.parentNode
){
23772 if(parent
== this.parent
&& dojo
.hasClass(node
, "dojoDndItem")){ return node
; }
23777 _normalizedCreator: function(/*dojo.dnd.Item*/ item
, /*String*/ hint
){
23779 // adds all necessary data to the output of the user-supplied creator function
23780 var t
= (this.creator
|| this.defaultCreator
).call(this, item
, hint
);
23781 if(!dojo
.isArray(t
.type
)){ t
.type
= ["text"]; }
23782 if(!t
.node
.id
){ t
.node
.id
= dojo
.dnd
.getUniqueId(); }
23783 dojo
.addClass(t
.node
, "dojoDndItem");
23788 dojo
.dnd
._createNode = function(tag
){
23790 // returns a function, which creates an element of given tag
23791 // (SPAN by default) and sets its innerHTML to given text
23793 // a tag name or empty for SPAN
23794 if(!tag
){ return dojo
.dnd
._createSpan
; }
23795 return function(text
){ // Function
23796 return dojo
.create(tag
, {innerHTML
: text
}); // Node
23800 dojo
.dnd
._createTrTd = function(text
){
23802 // creates a TR/TD structure with given text as an innerHTML of TD
23805 var tr
= dojo
.create("tr");
23806 dojo
.create("td", {innerHTML
: text
}, tr
);
23810 dojo
.dnd
._createSpan = function(text
){
23812 // creates a SPAN element with given text as its innerHTML
23815 return dojo
.create("span", {innerHTML
: text
}); // Node
23818 // dojo.dnd._defaultCreatorNodes: Object
23819 // a dictionary that maps container tag names to child tag names
23820 dojo
.dnd
._defaultCreatorNodes
= {ul
: "li", ol
: "li", div
: "div", p
: "div"};
23822 dojo
.dnd
._defaultCreator = function(node
){
23824 // takes a parent node, and returns an appropriate creator function
23826 // a container node
23827 var tag
= node
.tagName
.toLowerCase();
23828 var c
= tag
== "tbody" || tag
== "thead" ? dojo
.dnd
._createTrTd
:
23829 dojo
.dnd
._createNode(dojo
.dnd
._defaultCreatorNodes
[tag
]);
23830 return function(item
, hint
){ // Function
23831 var isObj
= item
&& dojo
.isObject(item
), data
, type
, n
;
23832 if(isObj
&& item
.tagName
&& item
.nodeType
&& item
.getAttribute
){
23833 // process a DOM node
23834 data
= item
.getAttribute("dndData") || item
.innerHTML
;
23835 type
= item
.getAttribute("dndType");
23836 type
= type
? type
.split(/\s*,\s*/) : ["text"];
23837 n
= item
; // this node is going to be moved rather than copied
23839 // process a DnD item object or a string
23840 data
= (isObj
&& item
.data
) ? item
.data
: item
;
23841 type
= (isObj
&& item
.type
) ? item
.type
: ["text"];
23842 n
= (hint
== "avatar" ? dojo
.dnd
._createSpan
: c
)(String(data
));
23845 n
.id
= dojo
.dnd
.getUniqueId();
23847 return {node
: n
, data
: data
, type
: type
};
23853 if(!dojo
._hasResource
["dijit.tree._dndContainer"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
23854 dojo
._hasResource
["dijit.tree._dndContainer"] = true;
23855 dojo
.provide("dijit.tree._dndContainer");
23859 dojo
.declare("dijit.tree._dndContainer",
23864 // This is a base class for `dijit.tree._dndSelector`, and isn't meant to be used directly.
23865 // It's modeled after `dojo.dnd.Container`.
23870 // current: DomNode
23871 // The currently hovered TreeNode.rowNode (which is the DOM node
23872 // associated w/a given node in the tree, excluding it's descendants)
23876 constructor: function(tree
, params
){
23878 // A constructor of the Container
23880 // Node or node's id to build the container on
23881 // params: dijit.tree.__SourceArgs
23882 // A dict of parameters, which gets mixed into the object
23886 this.node
= tree
.domNode
; // TODO: rename; it's not a TreeNode but the whole Tree
23887 dojo
.mixin(this, params
);
23889 // class-specific variables
23891 this.current
= null; // current TreeNode's DOM node
23894 this.containerState
= "";
23895 dojo
.addClass(this.node
, "dojoDndContainer");
23899 // container level events
23900 dojo
.connect(this.node
, "onmouseenter", this, "onOverEvent"),
23901 dojo
.connect(this.node
, "onmouseleave", this, "onOutEvent"),
23903 // switching between TreeNodes
23904 dojo
.connect(this.tree
, "_onNodeMouseEnter", this, "onMouseOver"),
23905 dojo
.connect(this.tree
, "_onNodeMouseLeave", this, "onMouseOut"),
23907 // cancel text selection and text dragging
23908 dojo
.connect(this.node
, "ondragstart", dojo
, "stopEvent"),
23909 dojo
.connect(this.node
, "onselectstart", dojo
, "stopEvent")
23913 getItem: function(/*String*/ key
){
23915 // Returns the dojo.dnd.Item (representing a dragged node) by it's key (id).
23916 // Called by dojo.dnd.Source.checkAcceptance().
23920 var node
= this.selection
[key
],
23922 data
: dijit
.getEnclosingWidget(node
),
23926 return ret
; // dojo.dnd.Item
23929 destroy: function(){
23931 // Prepares this object to be garbage-collected
23933 dojo
.forEach(this.events
, dojo
.disconnect
);
23934 // this.clearItems();
23935 this.node
= this.parent
= null;
23939 onMouseOver: function(/*TreeNode*/ widget
, /*Event*/ evt
){
23941 // Called when mouse is moved over a TreeNode
23944 this.current
= widget
.rowNode
;
23945 this.currentWidget
= widget
;
23948 onMouseOut: function(/*TreeNode*/ widget
, /*Event*/ evt
){
23950 // Called when mouse is moved away from a TreeNode
23953 this.current
= null;
23954 this.currentWidget
= null;
23957 _changeState: function(type
, newState
){
23959 // Changes a named state to new state value
23961 // A name of the state to change
23962 // newState: String
23964 var prefix
= "dojoDnd" + type
;
23965 var state
= type
.toLowerCase() + "State";
23966 //dojo.replaceClass(this.node, prefix + newState, prefix + this[state]);
23967 dojo
.removeClass(this.node
, prefix
+ this[state
]);
23968 dojo
.addClass(this.node
, prefix
+ newState
);
23969 this[state
] = newState
;
23972 _addItemClass: function(node
, type
){
23974 // Adds a class with prefix "dojoDndItem"
23978 // A variable suffix for a class name
23979 dojo
.addClass(node
, "dojoDndItem" + type
);
23982 _removeItemClass: function(node
, type
){
23984 // Removes a class with prefix "dojoDndItem"
23988 // A variable suffix for a class name
23989 dojo
.removeClass(node
, "dojoDndItem" + type
);
23992 onOverEvent: function(){
23994 // This function is called once, when mouse is over our container
23997 this._changeState("Container", "Over");
24000 onOutEvent: function(){
24002 // This function is called once, when mouse is out of our container
24005 this._changeState("Container", "");
24011 if(!dojo
._hasResource
["dijit.tree._dndSelector"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
24012 dojo
._hasResource
["dijit.tree._dndSelector"] = true;
24013 dojo
.provide("dijit.tree._dndSelector");
24017 dojo
.declare("dijit.tree._dndSelector",
24018 dijit
.tree
._dndContainer
,
24021 // This is a base class for `dijit.tree.dndSource` , and isn't meant to be used directly.
24022 // It's based on `dojo.dnd.Selector`.
24027 // selection: Hash<String, DomNode>
24028 // (id, DomNode) map for every TreeNode that's currently selected.
24029 // The DOMNode is the TreeNode.rowNode.
24033 constructor: function(tree
, params
){
24040 this.anchor
= null;
24041 this.simpleSelection
=false;
24044 dojo
.connect(this.tree
.domNode
, "onmousedown", this,"onMouseDown"),
24045 dojo
.connect(this.tree
.domNode
, "onmouseup", this,"onMouseUp"),
24046 dojo
.connect(this.tree
.domNode
, "onmousemove", this,"onMouseMove")
24050 // singular: Boolean
24051 // Allows selection of only one element, if true.
24052 // Tree hasn't been tested in singular=true mode, unclear if it works.
24057 getSelectedNodes: function(){
24059 // Returns the set of selected nodes.
24060 // Used by dndSource on the start of a drag.
24063 return this.selection
;
24066 selectNone: function(){
24068 // Unselects all items
24072 return this._removeSelection()._removeAnchor(); // self
24075 destroy: function(){
24077 // Prepares the object to be garbage-collected
24078 this.inherited(arguments
);
24079 this.selection
= this.anchor
= null;
24083 onMouseDown: function(e
){
24085 // Event processor for onmousedown
24091 if(!this.current
){ return; }
24093 if(e
.button
== dojo
.mouseButtons
.RIGHT
){ return; } // ignore right-click
24095 var treeNode
= dijit
.getEnclosingWidget(this.current
),
24096 id
= treeNode
.id
+ "-dnd" // so id doesn't conflict w/widget
24098 if(!dojo
.hasAttr(this.current
, "id")){
24099 dojo
.attr(this.current
, "id", id
);
24102 if(!this.singular
&& !dojo
.isCopyKey(e
) && !e
.shiftKey
&& (this.current
.id
in this.selection
)){
24103 this.simpleSelection
= true;
24108 if(this.anchor
== this.current
){
24109 if(dojo
.isCopyKey(e
)){
24114 this.anchor
= this.current
;
24115 this._addItemClass(this.anchor
, "Anchor");
24117 this.selection
[this.current
.id
] = this.current
;
24120 if(!this.singular
&& e
.shiftKey
){
24121 if(dojo
.isCopyKey(e
)){
24122 //TODO add range to selection
24124 //TODO select new range from anchor
24127 if(dojo
.isCopyKey(e
)){
24128 if(this.anchor
== this.current
){
24129 delete this.selection
[this.anchor
.id
];
24130 this._removeAnchor();
24132 if(this.current
.id
in this.selection
){
24133 this._removeItemClass(this.current
, "Selected");
24134 delete this.selection
[this.current
.id
];
24137 this._removeItemClass(this.anchor
, "Anchor");
24138 this._addItemClass(this.anchor
, "Selected");
24140 this.anchor
= this.current
;
24141 this._addItemClass(this.current
, "Anchor");
24142 this.selection
[this.current
.id
] = this.current
;
24146 if(!(id
in this.selection
)){
24148 this.anchor
= this.current
;
24149 this._addItemClass(this.current
, "Anchor");
24150 this.selection
[id
] = this.current
;
24159 onMouseUp: function(e
){
24161 // Event processor for onmouseup
24167 // TODO: this code is apparently for handling an edge case when the user is selecting
24168 // multiple nodes and then mousedowns on a node by accident... it lets the user keep the
24169 // current selection by moving the mouse away (or something like that). It doesn't seem
24170 // to work though and requires a lot of plumbing (including this code, the onmousemove
24171 // handler, and the this.simpleSelection attribute. Consider getting rid of all of it.
24173 if(!this.simpleSelection
){ return; }
24174 this.simpleSelection
= false;
24177 this.anchor
= this.current
;
24178 this._addItemClass(this.anchor
, "Anchor");
24179 this.selection
[this.current
.id
] = this.current
;
24182 onMouseMove: function(e
){
24184 // event processor for onmousemove
24187 this.simpleSelection
= false;
24190 _removeSelection: function(){
24192 // Unselects all items
24195 var e
= dojo
.dnd
._empty
;
24196 for(var i
in this.selection
){
24197 if(i
in e
){ continue; }
24198 var node
= dojo
.byId(i
);
24199 if(node
){ this._removeItemClass(node
, "Selected"); }
24201 this.selection
= {};
24202 return this; // self
24205 _removeAnchor: function(){
24207 // Removes the Anchor CSS class from a node.
24208 // According to `dojo.dnd.Selector`, anchor means that
24209 // "an item is selected, and is an anchor for a 'shift' selection".
24210 // It's not relevant for Tree at this point, since we don't support multiple selection.
24214 this._removeItemClass(this.anchor
, "Anchor");
24215 this.anchor
= null;
24217 return this; // self
24220 forInSelectedItems: function(/*Function*/ f
, /*Object?*/ o
){
24222 // Iterates over selected items;
24223 // see `dojo.dnd.Container.forInItems()` for details
24224 o
= o
|| dojo
.global
;
24225 for(var id
in this.selection
){
24226 console
.log("selected item id: " + id
);
24227 f
.call(o
, this.getItem(id
), id
, this);
24234 if(!dojo
._hasResource
["dojo.dnd.Avatar"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
24235 dojo
._hasResource
["dojo.dnd.Avatar"] = true;
24236 dojo
.provide("dojo.dnd.Avatar");
24240 dojo
.declare("dojo.dnd.Avatar", null, {
24242 // Object that represents transferred DnD items visually
24244 // a DnD manager object
24246 constructor: function(manager
){
24247 this.manager
= manager
;
24252 construct: function(){
24254 // constructor function;
24255 // it is separate so it can be (dynamically) overwritten in case of need
24256 this.isA11y
= dojo
.hasClass(dojo
.body(),"dijit_a11y");
24257 var a
= dojo
.create("table", {
24258 "class": "dojoDndAvatar",
24260 position
: "absolute",
24265 source
= this.manager
.source
, node
,
24266 b
= dojo
.create("tbody", null, a
),
24267 tr
= dojo
.create("tr", null, b
),
24268 td
= dojo
.create("td", null, tr
),
24269 icon
= this.isA11y
? dojo
.create("span", {
24271 innerHTML
: this.manager
.copy
? '+' : "<"
24273 span
= dojo
.create("span", {
24274 innerHTML
: source
.generateText
? this._generateText() : ""
24276 k
= Math
.min(5, this.manager
.nodes
.length
), i
= 0;
24277 // we have to set the opacity on IE only after the node is live
24279 "class": "dojoDndAvatarHeader",
24280 style
: {opacity
: 0.9}
24283 if(source
.creator
){
24284 // create an avatar representation of the node
24285 node
= source
._normalizedCreator(source
.getItem(this.manager
.nodes
[i
].id
).data
, "avatar").node
;
24287 // or just clone the node and hope it works
24288 node
= this.manager
.nodes
[i
].cloneNode(true);
24289 if(node
.tagName
.toLowerCase() == "tr"){
24290 // insert extra table nodes
24291 var table
= dojo
.create("table"),
24292 tbody
= dojo
.create("tbody", null, table
);
24293 tbody
.appendChild(node
);
24298 tr
= dojo
.create("tr", null, b
);
24299 td
= dojo
.create("td", null, tr
);
24300 td
.appendChild(node
);
24302 "class": "dojoDndAvatarItem",
24303 style
: {opacity
: (9 - i
) / 10}
24308 destroy: function(){
24310 // destructor for the avatar; called to remove all references so it can be garbage-collected
24311 dojo
.destroy(this.node
);
24314 update: function(){
24316 // updates the avatar to reflect the current DnD state
24317 dojo
[(this.manager
.canDropFlag
? "add" : "remove") + "Class"](this.node
, "dojoDndAvatarCanDrop");
24319 var icon
= dojo
.byId("a11yIcon");
24320 var text
= '+'; // assume canDrop && copy
24321 if (this.manager
.canDropFlag
&& !this.manager
.copy
) {
24322 text
= '< '; // canDrop && move
24323 }else if (!this.manager
.canDropFlag
&& !this.manager
.copy
) {
24324 text
= "o"; //!canDrop && move
24325 }else if(!this.manager
.canDropFlag
){
24326 text
= 'x'; // !canDrop && copy
24328 icon
.innerHTML
=text
;
24331 dojo
.query(("tr.dojoDndAvatarHeader td span" +(this.isA11y
? " span" : "")), this.node
).forEach(
24333 node
.innerHTML
= this._generateText();
24336 _generateText: function(){
24337 // summary: generates a proper text to reflect copying or moving of items
24338 return this.manager
.nodes
.length
.toString();
24344 if(!dojo
._hasResource
["dojo.dnd.Manager"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
24345 dojo
._hasResource
["dojo.dnd.Manager"] = true;
24346 dojo
.provide("dojo.dnd.Manager");
24352 dojo
.declare("dojo.dnd.Manager", null, {
24354 // the manager of DnD operations (usually a singleton)
24355 constructor: function(){
24356 this.avatar
= null;
24357 this.source
= null;
24360 this.target
= null;
24361 this.canDropFlag
= false;
24365 // avatar's offset from the mouse
24370 overSource: function(source
){
24372 // called when a source detected a mouse-over condition
24376 this.target
= (source
&& source
.targetState
!= "Disabled") ? source
: null;
24377 this.canDropFlag
= Boolean(this.target
);
24378 this.avatar
.update();
24380 dojo
.publish("/dnd/source/over", [source
]);
24382 outSource: function(source
){
24384 // called when a source detected a mouse-out condition
24388 if(this.target
== source
){
24389 this.target
= null;
24390 this.canDropFlag
= false;
24391 this.avatar
.update();
24392 dojo
.publish("/dnd/source/over", [null]);
24395 dojo
.publish("/dnd/source/over", [null]);
24398 startDrag: function(source
, nodes
, copy
){
24400 // called to initiate the DnD operation
24402 // the source which provides items
24404 // the list of transferred items
24406 // copy items, if true, move items otherwise
24407 this.source
= source
;
24408 this.nodes
= nodes
;
24409 this.copy
= Boolean(copy
); // normalizing to true boolean
24410 this.avatar
= this.makeAvatar();
24411 dojo
.body().appendChild(this.avatar
.node
);
24412 dojo
.publish("/dnd/start", [source
, nodes
, this.copy
]);
24414 dojo
.connect(dojo
.doc
, "onmousemove", this, "onMouseMove"),
24415 dojo
.connect(dojo
.doc
, "onmouseup", this, "onMouseUp"),
24416 dojo
.connect(dojo
.doc
, "onkeydown", this, "onKeyDown"),
24417 dojo
.connect(dojo
.doc
, "onkeyup", this, "onKeyUp"),
24418 // cancel text selection and text dragging
24419 dojo
.connect(dojo
.doc
, "ondragstart", dojo
.stopEvent
),
24420 dojo
.connect(dojo
.body(), "onselectstart", dojo
.stopEvent
)
24422 var c
= "dojoDnd" + (copy
? "Copy" : "Move");
24423 dojo
.addClass(dojo
.body(), c
);
24425 canDrop: function(flag
){
24427 // called to notify if the current target can accept items
24428 var canDropFlag
= Boolean(this.target
&& flag
);
24429 if(this.canDropFlag
!= canDropFlag
){
24430 this.canDropFlag
= canDropFlag
;
24431 this.avatar
.update();
24434 stopDrag: function(){
24436 // stop the DnD in progress
24437 dojo
.removeClass(dojo
.body(), "dojoDndCopy");
24438 dojo
.removeClass(dojo
.body(), "dojoDndMove");
24439 dojo
.forEach(this.events
, dojo
.disconnect
);
24441 this.avatar
.destroy();
24442 this.avatar
= null;
24443 this.source
= this.target
= null;
24446 makeAvatar: function(){
24448 // makes the avatar; it is separate to be overwritten dynamically, if needed
24449 return new dojo
.dnd
.Avatar(this);
24451 updateAvatar: function(){
24453 // updates the avatar; it is separate to be overwritten dynamically, if needed
24454 this.avatar
.update();
24457 // mouse event processors
24458 onMouseMove: function(e
){
24460 // event processor for onmousemove
24463 var a
= this.avatar
;
24465 dojo
.dnd
.autoScrollNodes(e
);
24466 //dojo.dnd.autoScroll(e);
24467 var s
= a
.node
.style
;
24468 s
.left
= (e
.pageX
+ this.OFFSET_X
) + "px";
24469 s
.top
= (e
.pageY
+ this.OFFSET_Y
) + "px";
24470 var copy
= Boolean(this.source
.copyState(dojo
.isCopyKey(e
)));
24471 if(this.copy
!= copy
){
24472 this._setCopyStatus(copy
);
24476 onMouseUp: function(e
){
24478 // event processor for onmouseup
24482 if(this.target
&& this.canDropFlag
){
24483 var copy
= Boolean(this.source
.copyState(dojo
.isCopyKey(e
))),
24484 params
= [this.source
, this.nodes
, copy
, this.target
, e
];
24485 dojo
.publish("/dnd/drop/before", params
);
24486 dojo
.publish("/dnd/drop", params
);
24488 dojo
.publish("/dnd/cancel");
24494 // keyboard event processors
24495 onKeyDown: function(e
){
24497 // event processor for onkeydown:
24498 // watching for CTRL for copy/move status, watching for ESCAPE to cancel the drag
24503 case dojo
.keys
.CTRL
:
24504 var copy
= Boolean(this.source
.copyState(true));
24505 if(this.copy
!= copy
){
24506 this._setCopyStatus(copy
);
24509 case dojo
.keys
.ESCAPE
:
24510 dojo
.publish("/dnd/cancel");
24516 onKeyUp: function(e
){
24518 // event processor for onkeyup, watching for CTRL for copy/move status
24521 if(this.avatar
&& e
.keyCode
== dojo
.keys
.CTRL
){
24522 var copy
= Boolean(this.source
.copyState(false));
24523 if(this.copy
!= copy
){
24524 this._setCopyStatus(copy
);
24530 _setCopyStatus: function(copy
){
24532 // changes the copy status
24536 this.source
._markDndStatus(this.copy
);
24537 this.updateAvatar();
24538 dojo
.removeClass(dojo
.body(), "dojoDnd" + (this.copy
? "Move" : "Copy"));
24539 dojo
.addClass(dojo
.body(), "dojoDnd" + (this.copy
? "Copy" : "Move"));
24543 // dojo.dnd._manager:
24544 // The manager singleton variable. Can be overwritten if needed.
24545 dojo
.dnd
._manager
= null;
24547 dojo
.dnd
.manager = function(){
24549 // Returns the current DnD manager. Creates one if it is not created yet.
24550 if(!dojo
.dnd
._manager
){
24551 dojo
.dnd
._manager
= new dojo
.dnd
.Manager();
24553 return dojo
.dnd
._manager
; // Object
24558 if(!dojo
._hasResource
["dijit.tree.dndSource"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
24559 dojo
._hasResource
["dijit.tree.dndSource"] = true;
24560 dojo
.provide("dijit.tree.dndSource");
24566 dijit.tree.__SourceArgs = function(){
24568 // A dict of parameters for Tree source configuration.
24569 // isSource: Boolean?
24570 // Can be used as a DnD source. Defaults to true.
24571 // accept: String[]
24572 // List of accepted types (text strings) for a target; defaults to
24573 // ["text", "treeNode"]
24574 // copyOnly: Boolean?
24575 // Copy items, if true, use a state of Ctrl key otherwise,
24576 // dragThreshold: Number
24577 // The move delay in pixels before detecting a drag; 0 by default
24578 // betweenThreshold: Integer
24579 // Distance from upper/lower edge of node to allow drop to reorder nodes
24580 this.isSource = isSource;
24581 this.accept = accept;
24582 this.autoSync = autoSync;
24583 this.copyOnly = copyOnly;
24584 this.dragThreshold = dragThreshold;
24585 this.betweenThreshold = betweenThreshold;
24589 dojo
.declare("dijit.tree.dndSource", dijit
.tree
._dndSelector
, {
24591 // Handles drag and drop operations (as a source or a target) for `dijit.Tree`
24593 // isSource: [private] Boolean
24594 // Can be used as a DnD source.
24597 // accept: String[]
24598 // List of accepted types (text strings) for the Tree; defaults to
24600 accept
: ["text", "treeNode"],
24602 // copyOnly: [private] Boolean
24603 // Copy items, if true, use a state of Ctrl key otherwise
24606 // dragThreshold: Number
24607 // The move delay in pixels before detecting a drag; 5 by default
24610 // betweenThreshold: Integer
24611 // Distance from upper/lower edge of node to allow drop to reorder nodes
24612 betweenThreshold
: 0,
24614 constructor: function(/*dijit.Tree*/ tree
, /*dijit.tree.__SourceArgs*/ params
){
24616 // a constructor of the Tree DnD Source
24619 if(!params
){ params
= {}; }
24620 dojo
.mixin(this, params
);
24621 this.isSource
= typeof params
.isSource
== "undefined" ? true : params
.isSource
;
24622 var type
= params
.accept
instanceof Array
? params
.accept
: ["text", "treeNode"];
24623 this.accept
= null;
24626 for(var i
= 0; i
< type
.length
; ++i
){
24627 this.accept
[type
[i
]] = 1;
24631 // class-specific variables
24632 this.isDragging
= false;
24633 this.mouseDown
= false;
24634 this.targetAnchor
= null; // DOMNode corresponding to the currently moused over TreeNode
24635 this.targetBox
= null; // coordinates of this.targetAnchor
24636 this.dropPosition
= ""; // whether mouse is over/after/before this.targetAnchor
24641 this.sourceState
= "";
24643 dojo
.addClass(this.node
, "dojoDndSource");
24645 this.targetState
= "";
24647 dojo
.addClass(this.node
, "dojoDndTarget");
24652 dojo
.subscribe("/dnd/source/over", this, "onDndSourceOver"),
24653 dojo
.subscribe("/dnd/start", this, "onDndStart"),
24654 dojo
.subscribe("/dnd/drop", this, "onDndDrop"),
24655 dojo
.subscribe("/dnd/cancel", this, "onDndCancel")
24660 checkAcceptance: function(source
, nodes
){
24662 // Checks if the target can accept nodes from this source
24663 // source: dijit.tree.dndSource
24664 // The source which provides items
24665 // nodes: DOMNode[]
24666 // Array of DOM nodes corresponding to nodes being dropped, dijitTreeRow nodes if
24667 // source is a dijit.Tree.
24670 return true; // Boolean
24673 copyState: function(keyPressed
){
24675 // Returns true, if we need to copy items, false to move.
24676 // It is separated to be overwritten dynamically, if needed.
24677 // keyPressed: Boolean
24678 // The "copy" control key was pressed
24681 return this.copyOnly
|| keyPressed
; // Boolean
24683 destroy: function(){
24685 // Prepares the object to be garbage-collected.
24686 this.inherited("destroy",arguments
);
24687 dojo
.forEach(this.topics
, dojo
.unsubscribe
);
24688 this.targetAnchor
= null;
24691 _onDragMouse: function(e
){
24693 // Helper method for processing onmousemove/onmouseover events while drag is in progress.
24694 // Keeps track of current drop target.
24696 var m
= dojo
.dnd
.manager(),
24697 oldTarget
= this.targetAnchor
, // the DOMNode corresponding to TreeNode mouse was previously over
24698 newTarget
= this.current
, // DOMNode corresponding to TreeNode mouse is currently over
24699 newTargetWidget
= this.currentWidget
, // the TreeNode itself
24700 oldDropPosition
= this.dropPosition
; // the previous drop position (over/before/after)
24702 // calculate if user is indicating to drop the dragged node before, after, or over
24703 // (i.e., to become a child of) the target node
24704 var newDropPosition
= "Over";
24705 if(newTarget
&& this.betweenThreshold
> 0){
24706 // If mouse is over a new TreeNode, then get new TreeNode's position and size
24707 if(!this.targetBox
|| oldTarget
!= newTarget
){
24708 this.targetBox
= dojo
.position(newTarget
, true);
24710 if((e
.pageY
- this.targetBox
.y
) <= this.betweenThreshold
){
24711 newDropPosition
= "Before";
24712 }else if((e
.pageY
- this.targetBox
.y
) >= (this.targetBox
.h
- this.betweenThreshold
)){
24713 newDropPosition
= "After";
24717 if(newTarget
!= oldTarget
|| newDropPosition
!= oldDropPosition
){
24719 this._removeItemClass(oldTarget
, oldDropPosition
);
24722 this._addItemClass(newTarget
, newDropPosition
);
24725 // Check if it's ok to drop the dragged node on/before/after the target node.
24728 }else if(newTargetWidget
== this.tree
.rootNode
&& newDropPosition
!= "Over"){
24729 // Can't drop before or after tree's root node; the dropped node would just disappear (at least visually)
24731 }else if(m
.source
== this && (newTarget
.id
in this.selection
)){
24732 // Guard against dropping onto yourself (TODO: guard against dropping onto your descendant, #7140)
24734 }else if(this.checkItemAcceptance(newTarget
, m
.source
, newDropPosition
.toLowerCase())
24735 && !this._isParentChildDrop(m
.source
, newTarget
)){
24741 this.targetAnchor
= newTarget
;
24742 this.dropPosition
= newDropPosition
;
24746 onMouseMove: function(e
){
24748 // Called for any onmousemove events over the Tree
24750 // onmousemouse event
24753 if(this.isDragging
&& this.targetState
== "Disabled"){ return; }
24754 this.inherited(arguments
);
24755 var m
= dojo
.dnd
.manager();
24756 if(this.isDragging
){
24757 this._onDragMouse(e
);
24759 if(this.mouseDown
&& this.isSource
&&
24760 (Math
.abs(e
.pageX
-this._lastX
)>=this.dragThreshold
|| Math
.abs(e
.pageY
-this._lastY
)>=this.dragThreshold
)){
24761 var n
= this.getSelectedNodes();
24767 m
.startDrag(this, nodes
, this.copyState(dojo
.isCopyKey(e
)));
24773 onMouseDown: function(e
){
24775 // Event processor for onmousedown
24777 // onmousedown event
24780 this.mouseDown
= true;
24781 this.mouseButton
= e
.button
;
24782 this._lastX
= e
.pageX
;
24783 this._lastY
= e
.pageY
;
24784 this.inherited("onMouseDown",arguments
);
24787 onMouseUp: function(e
){
24789 // Event processor for onmouseup
24794 if(this.mouseDown
){
24795 this.mouseDown
= false;
24796 this.inherited("onMouseUp",arguments
);
24800 onMouseOut: function(){
24802 // Event processor for when mouse is moved away from a TreeNode
24805 this.inherited(arguments
);
24806 this._unmarkTargetAnchor();
24809 checkItemAcceptance: function(target
, source
, position
){
24811 // Stub function to be overridden if one wants to check for the ability to drop at the node/item level
24813 // In the base case, this is called to check if target can become a child of source.
24814 // When betweenThreshold is set, position="before" or "after" means that we
24815 // are asking if the source node can be dropped before/after the target node.
24817 // The dijitTreeRoot DOM node inside of the TreeNode that we are dropping on to
24818 // Use dijit.getEnclosingWidget(target) to get the TreeNode.
24819 // source: dijit.tree.dndSource
24820 // The (set of) nodes we are dropping
24821 // position: String
24822 // "over", "before", or "after"
24828 // topic event processors
24829 onDndSourceOver: function(source
){
24831 // Topic event processor for /dnd/source/over, called when detected a current source.
24833 // The dijit.tree.dndSource / dojo.dnd.Source which has the mouse over it
24836 if(this != source
){
24837 this.mouseDown
= false;
24838 this._unmarkTargetAnchor();
24839 }else if(this.isDragging
){
24840 var m
= dojo
.dnd
.manager();
24844 onDndStart: function(source
, nodes
, copy
){
24846 // Topic event processor for /dnd/start, called to initiate the DnD operation
24848 // The dijit.tree.dndSource / dojo.dnd.Source which is providing the items
24849 // nodes: DomNode[]
24850 // The list of transferred items, dndTreeNode nodes if dragging from a Tree
24852 // Copy items, if true, move items otherwise
24857 this._changeState("Source", this == source
? (copy
? "Copied" : "Moved") : "");
24859 var accepted
= this.checkAcceptance(source
, nodes
);
24861 this._changeState("Target", accepted
? "" : "Disabled");
24863 if(this == source
){
24864 dojo
.dnd
.manager().overSource(this);
24867 this.isDragging
= true;
24870 itemCreator: function(/*DomNode[]*/ nodes
, target
, /*dojo.dnd.Source*/ source
){
24872 // Returns objects passed to `Tree.model.newItem()` based on DnD nodes
24873 // dropped onto the tree. Developer must override this method to enable
24874 // dropping from external sources onto this Tree, unless the Tree.model's items
24875 // happen to look like {id: 123, name: "Apple" } with no other attributes.
24877 // For each node in nodes[], which came from source, create a hash of name/value
24878 // pairs to be passed to Tree.model.newItem(). Returns array of those hashes.
24879 // returns: Object[]
24880 // Array of name/value hashes for each new item to be added to the Tree, like:
24882 // | { id: 123, label: "apple", foo: "bar" },
24883 // | { id: 456, label: "pear", zaz: "bam" }
24888 // TODO: for 2.0 refactor so itemCreator() is called once per drag node, and
24889 // make signature itemCreator(sourceItem, node, target) (or similar).
24891 return dojo
.map(nodes
, function(node
){
24894 "name": node
.textContent
|| node
.innerText
|| ""
24899 onDndDrop: function(source
, nodes
, copy
){
24901 // Topic event processor for /dnd/drop, called to finish the DnD operation.
24903 // Updates data store items according to where node was dragged from and dropped
24904 // to. The tree will then respond to those data store updates and redraw itself.
24906 // The dijit.tree.dndSource / dojo.dnd.Source which is providing the items
24907 // nodes: DomNode[]
24908 // The list of transferred items, dndTreeNode nodes if dragging from a Tree
24910 // Copy items, if true, move items otherwise
24913 if(this.containerState
== "Over"){
24914 var tree
= this.tree
,
24915 model
= tree
.model
,
24916 target
= this.targetAnchor
,
24917 requeryRoot
= false; // set to true iff top level items change
24919 this.isDragging
= false;
24921 // Compute the new parent item
24922 var targetWidget
= dijit
.getEnclosingWidget(target
);
24925 newParentItem
= (targetWidget
&& targetWidget
.item
) || tree
.item
;
24926 if(this.dropPosition
== "Before" || this.dropPosition
== "After"){
24927 // TODO: if there is no parent item then disallow the drop.
24928 // Actually this should be checked during onMouseMove too, to make the drag icon red.
24929 newParentItem
= (targetWidget
.getParent() && targetWidget
.getParent().item
) || tree
.item
;
24930 // Compute the insert index for reordering
24931 insertIndex
= targetWidget
.getIndexInParent();
24932 if(this.dropPosition
== "After"){
24933 insertIndex
= targetWidget
.getIndexInParent() + 1;
24936 newParentItem
= (targetWidget
&& targetWidget
.item
) || tree
.item
;
24939 // If necessary, use this variable to hold array of hashes to pass to model.newItem()
24940 // (one entry in the array for each dragged node).
24941 var newItemsParams
;
24943 dojo
.forEach(nodes
, function(node
, idx
){
24944 // dojo.dnd.Item representing the thing being dropped.
24945 // Don't confuse the use of item here (meaning a DnD item) with the
24946 // uses below where item means dojo.data item.
24947 var sourceItem
= source
.getItem(node
.id
);
24949 // Information that's available if the source is another Tree
24950 // (possibly but not necessarily this tree, possibly but not
24951 // necessarily the same model as this Tree)
24952 if(dojo
.indexOf(sourceItem
.type
, "treeNode") != -1){
24953 var childTreeNode
= sourceItem
.data
,
24954 childItem
= childTreeNode
.item
,
24955 oldParentItem
= childTreeNode
.getParent().item
;
24958 if(source
== this){
24959 // This is a node from my own tree, and we are moving it, not copying.
24960 // Remove item from old parent's children attribute.
24961 // TODO: dijit.tree.dndSelector should implement deleteSelectedNodes()
24962 // and this code should go there.
24964 if(typeof insertIndex
== "number"){
24965 if(newParentItem
== oldParentItem
&& childTreeNode
.getIndexInParent() < insertIndex
){
24969 model
.pasteItem(childItem
, oldParentItem
, newParentItem
, copy
, insertIndex
);
24970 }else if(model
.isItem(childItem
)){
24971 // Item from same model
24972 // (maybe we should only do this branch if the source is a tree?)
24973 model
.pasteItem(childItem
, oldParentItem
, newParentItem
, copy
, insertIndex
);
24975 // Get the hash to pass to model.newItem(). A single call to
24976 // itemCreator() returns an array of hashes, one for each drag source node.
24977 if(!newItemsParams
){
24978 newItemsParams
= this.itemCreator(nodes
, target
, source
);
24981 // Create new item in the tree, based on the drag source.
24982 model
.newItem(newItemsParams
[idx
], newParentItem
, insertIndex
);
24986 // Expand the target node (if it's currently collapsed) so the user can see
24987 // where their node was dropped. In particular since that node is still selected.
24988 this.tree
._expandNode(targetWidget
);
24990 this.onDndCancel();
24993 onDndCancel: function(){
24995 // Topic event processor for /dnd/cancel, called to cancel the DnD operation
24998 this._unmarkTargetAnchor();
24999 this.isDragging
= false;
25000 this.mouseDown
= false;
25001 delete this.mouseButton
;
25002 this._changeState("Source", "");
25003 this._changeState("Target", "");
25006 // When focus moves in/out of the entire Tree
25007 onOverEvent: function(){
25009 // This method is called when mouse is moved over our container (like onmouseenter)
25012 this.inherited(arguments
);
25013 dojo
.dnd
.manager().overSource(this);
25015 onOutEvent: function(){
25017 // This method is called when mouse is moved out of our container (like onmouseleave)
25020 this._unmarkTargetAnchor();
25021 var m
= dojo
.dnd
.manager();
25022 if(this.isDragging
){
25027 this.inherited(arguments
);
25030 _isParentChildDrop: function(source
, targetRow
){
25032 // Checks whether the dragged items are parent rows in the tree which are being
25033 // dragged into their own children.
25036 // The DragSource object.
25039 // The tree row onto which the dragged nodes are being dropped.
25044 // If the dragged object is not coming from the tree this widget belongs to,
25045 // it cannot be invalid.
25046 if(!source
.tree
|| source
.tree
!= this.tree
){
25051 var root
= source
.tree
.domNode
;
25053 for(var x
in source
.selection
){
25054 ids
[source
.selection
[x
].parentNode
.id
] = true;
25057 var node
= targetRow
.parentNode
;
25059 // Iterate up the DOM hierarchy from the target drop row,
25060 // checking of any of the dragged nodes have the same ID.
25061 while(node
!= root
&& (!node
.id
|| !ids
[node
.id
])){
25062 node
= node
.parentNode
;
25065 return node
.id
&& ids
[node
.id
];
25068 _unmarkTargetAnchor: function(){
25070 // Removes hover class of the current target anchor
25073 if(!this.targetAnchor
){ return; }
25074 this._removeItemClass(this.targetAnchor
, this.dropPosition
);
25075 this.targetAnchor
= null;
25076 this.targetBox
= null;
25077 this.dropPosition
= null;
25080 _markDndStatus: function(copy
){
25082 // Changes source's state based on "copy" status
25083 this._changeState("Source", copy
? "Copied" : "Moved");
25089 if(!dojo
._hasResource
["dojo.data.ItemFileReadStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
25090 dojo
._hasResource
["dojo.data.ItemFileReadStore"] = true;
25091 dojo
.provide("dojo.data.ItemFileReadStore");
25097 dojo
.declare("dojo.data.ItemFileReadStore", null,{
25099 // The ItemFileReadStore implements the dojo.data.api.Read API and reads
25100 // data from JSON files that have contents in this format --
25102 // { name:'Kermit', color:'green', age:12, friends:['Gonzo', {_reference:{name:'Fozzie Bear'}}]},
25103 // { name:'Fozzie Bear', wears:['hat', 'tie']},
25104 // { name:'Miss Piggy', pets:'Foo-Foo'}
25106 // Note that it can also contain an 'identifer' property that specified which attribute on the items
25107 // in the array of items that acts as the unique identifier for that item.
25109 constructor: function(/* Object */ keywordParameters
){
25110 // summary: constructor
25111 // keywordParameters: {url: String}
25112 // keywordParameters: {data: jsonObject}
25113 // keywordParameters: {typeMap: object)
25114 // The structure of the typeMap object is as follows:
25116 // type0: function || object,
25117 // type1: function || object,
25119 // typeN: function || object
25121 // Where if it is a function, it is assumed to be an object constructor that takes the
25122 // value of _value as the initialization parameters. If it is an object, then it is assumed
25123 // to be an object of general form:
25125 // type: function, //constructor.
25126 // deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
25129 this._arrayOfAllItems
= [];
25130 this._arrayOfTopLevelItems
= [];
25131 this._loadFinished
= false;
25132 this._jsonFileUrl
= keywordParameters
.url
;
25133 this._ccUrl
= keywordParameters
.url
;
25134 this.url
= keywordParameters
.url
;
25135 this._jsonData
= keywordParameters
.data
;
25137 this._datatypeMap
= keywordParameters
.typeMap
|| {};
25138 if(!this._datatypeMap
['Date']){
25139 //If no default mapping for dates, then set this as default.
25140 //We use the dojo.date.stamp here because the ISO format is the 'dojo way'
25141 //of generically representing dates.
25142 this._datatypeMap
['Date'] = {
25144 deserialize: function(value
){
25145 return dojo
.date
.stamp
.fromISOString(value
);
25149 this._features
= {'dojo.data.api.Read':true, 'dojo.data.api.Identity':true};
25150 this._itemsByIdentity
= null;
25151 this._storeRefPropName
= "_S"; // Default name for the store reference to attach to every item.
25152 this._itemNumPropName
= "_0"; // Default Item Id for isItem to attach to every item.
25153 this._rootItemPropName
= "_RI"; // Default Item Id for isItem to attach to every item.
25154 this._reverseRefMap
= "_RRM"; // Default attribute for constructing a reverse reference map for use with reference integrity
25155 this._loadInProgress
= false; //Got to track the initial load to prevent duelling loads of the dataset.
25156 this._queuedFetches
= [];
25157 if(keywordParameters
.urlPreventCache
!== undefined){
25158 this.urlPreventCache
= keywordParameters
.urlPreventCache
?true:false;
25160 if(keywordParameters
.hierarchical
!== undefined){
25161 this.hierarchical
= keywordParameters
.hierarchical
?true:false;
25163 if(keywordParameters
.clearOnClose
){
25164 this.clearOnClose
= true;
25166 if("failOk" in keywordParameters
){
25167 this.failOk
= keywordParameters
.failOk
?true:false;
25171 url
: "", // use "" rather than undefined for the benefit of the parser (#3539)
25173 //Internal var, crossCheckUrl. Used so that setting either url or _jsonFileUrl, can still trigger a reload
25174 //when clearOnClose and close is used.
25177 data
: null, // define this so that the parser can populate it
25179 typeMap
: null, //Define so parser can populate.
25181 //Parameter to allow users to specify if a close call should force a reload or not.
25182 //By default, it retains the old behavior of not clearing if close is called. But
25183 //if set true, the store will be reset to default state. Note that by doing this,
25184 //all item handles will become invalid and a new fetch must be issued.
25185 clearOnClose
: false,
25187 //Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url.
25188 //Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option.
25189 //Added for tracker: #6072
25190 urlPreventCache
: false,
25192 //Parameter for specifying that it is OK for the xhrGet call to fail silently.
25195 //Parameter to indicate to process data from the url as hierarchical
25196 //(data items can contain other data items in js form). Default is true
25197 //for backwards compatibility. False means only root items are processed
25198 //as items, all child objects outside of type-mapped objects and those in
25199 //specific reference format, are left straight JS data objects.
25200 hierarchical
: true,
25202 _assertIsItem: function(/* item */ item
){
25204 // This function tests whether the item passed in is indeed an item in the store.
25206 // The item to test for being contained by the store.
25207 if(!this.isItem(item
)){
25208 throw new Error("dojo.data.ItemFileReadStore: Invalid item argument.");
25212 _assertIsAttribute: function(/* attribute-name-string */ attribute
){
25214 // This function tests whether the item passed in is indeed a valid 'attribute' like type for the store.
25216 // The attribute to test for being contained by the store.
25217 if(typeof attribute
!== "string"){
25218 throw new Error("dojo.data.ItemFileReadStore: Invalid attribute argument.");
25222 getValue: function( /* item */ item
,
25223 /* attribute-name-string */ attribute
,
25224 /* value? */ defaultValue
){
25226 // See dojo.data.api.Read.getValue()
25227 var values
= this.getValues(item
, attribute
);
25228 return (values
.length
> 0)?values
[0]:defaultValue
; // mixed
25231 getValues: function(/* item */ item
,
25232 /* attribute-name-string */ attribute
){
25234 // See dojo.data.api.Read.getValues()
25236 this._assertIsItem(item
);
25237 this._assertIsAttribute(attribute
);
25238 // Clone it before returning. refs: #10474
25239 return (item
[attribute
] || []).slice(0); // Array
25242 getAttributes: function(/* item */ item
){
25244 // See dojo.data.api.Read.getAttributes()
25245 this._assertIsItem(item
);
25246 var attributes
= [];
25247 for(var key
in item
){
25248 // Save off only the real item attributes, not the special id marks for O(1) isItem.
25249 if((key
!== this._storeRefPropName
) && (key
!== this._itemNumPropName
) && (key
!== this._rootItemPropName
) && (key
!== this._reverseRefMap
)){
25250 attributes
.push(key
);
25253 return attributes
; // Array
25256 hasAttribute: function( /* item */ item
,
25257 /* attribute-name-string */ attribute
){
25259 // See dojo.data.api.Read.hasAttribute()
25260 this._assertIsItem(item
);
25261 this._assertIsAttribute(attribute
);
25262 return (attribute
in item
);
25265 containsValue: function(/* item */ item
,
25266 /* attribute-name-string */ attribute
,
25267 /* anything */ value
){
25269 // See dojo.data.api.Read.containsValue()
25270 var regexp
= undefined;
25271 if(typeof value
=== "string"){
25272 regexp
= dojo
.data
.util
.filter
.patternToRegExp(value
, false);
25274 return this._containsValue(item
, attribute
, value
, regexp
); //boolean.
25277 _containsValue: function( /* item */ item
,
25278 /* attribute-name-string */ attribute
,
25279 /* anything */ value
,
25280 /* RegExp?*/ regexp
){
25282 // Internal function for looking at the values contained by the item.
25284 // Internal function for looking at the values contained by the item. This
25285 // function allows for denoting if the comparison should be case sensitive for
25286 // strings or not (for handling filtering cases where string case should not matter)
25289 // The data item to examine for attribute values.
25291 // The attribute to inspect.
25293 // The value to match.
25295 // Optional regular expression generated off value if value was of string type to handle wildcarding.
25296 // If present and attribute values are string, then it can be used for comparison instead of 'value'
25297 return dojo
.some(this.getValues(item
, attribute
), function(possibleValue
){
25298 if(possibleValue
!== null && !dojo
.isObject(possibleValue
) && regexp
){
25299 if(possibleValue
.toString().match(regexp
)){
25300 return true; // Boolean
25302 }else if(value
=== possibleValue
){
25303 return true; // Boolean
25308 isItem: function(/* anything */ something
){
25310 // See dojo.data.api.Read.isItem()
25311 if(something
&& something
[this._storeRefPropName
] === this){
25312 if(this._arrayOfAllItems
[something
[this._itemNumPropName
]] === something
){
25316 return false; // Boolean
25319 isItemLoaded: function(/* anything */ something
){
25321 // See dojo.data.api.Read.isItemLoaded()
25322 return this.isItem(something
); //boolean
25325 loadItem: function(/* object */ keywordArgs
){
25327 // See dojo.data.api.Read.loadItem()
25328 this._assertIsItem(keywordArgs
.item
);
25331 getFeatures: function(){
25333 // See dojo.data.api.Read.getFeatures()
25334 return this._features
; //Object
25337 getLabel: function(/* item */ item
){
25339 // See dojo.data.api.Read.getLabel()
25340 if(this._labelAttr
&& this.isItem(item
)){
25341 return this.getValue(item
,this._labelAttr
); //String
25343 return undefined; //undefined
25346 getLabelAttributes: function(/* item */ item
){
25348 // See dojo.data.api.Read.getLabelAttributes()
25349 if(this._labelAttr
){
25350 return [this._labelAttr
]; //array
25352 return null; //null
25355 _fetchItems: function( /* Object */ keywordArgs
,
25356 /* Function */ findCallback
,
25357 /* Function */ errorCallback
){
25359 // See dojo.data.util.simpleFetch.fetch()
25361 filter = function(requestArgs
, arrayOfItems
){
25364 if(requestArgs
.query
){
25366 ignoreCase
= requestArgs
.queryOptions
? requestArgs
.queryOptions
.ignoreCase
: false;
25368 //See if there are any string values that can be regexp parsed first to avoid multiple regexp gens on the
25369 //same value for each item examined. Much more efficient.
25370 var regexpList
= {};
25371 for(key
in requestArgs
.query
){
25372 value
= requestArgs
.query
[key
];
25373 if(typeof value
=== "string"){
25374 regexpList
[key
] = dojo
.data
.util
.filter
.patternToRegExp(value
, ignoreCase
);
25375 }else if(value
instanceof RegExp
){
25376 regexpList
[key
] = value
;
25379 for(i
= 0; i
< arrayOfItems
.length
; ++i
){
25381 var candidateItem
= arrayOfItems
[i
];
25382 if(candidateItem
=== null){
25385 for(key
in requestArgs
.query
){
25386 value
= requestArgs
.query
[key
];
25387 if(!self
._containsValue(candidateItem
, key
, value
, regexpList
[key
])){
25393 items
.push(candidateItem
);
25396 findCallback(items
, requestArgs
);
25398 // We want a copy to pass back in case the parent wishes to sort the array.
25399 // We shouldn't allow resort of the internal list, so that multiple callers
25400 // can get lists and sort without affecting each other. We also need to
25401 // filter out any null values that have been left as a result of deleteItem()
25402 // calls in ItemFileWriteStore.
25403 for(i
= 0; i
< arrayOfItems
.length
; ++i
){
25404 var item
= arrayOfItems
[i
];
25409 findCallback(items
, requestArgs
);
25413 if(this._loadFinished
){
25414 filter(keywordArgs
, this._getItemsArray(keywordArgs
.queryOptions
));
25416 //Do a check on the JsonFileUrl and crosscheck it.
25417 //If it doesn't match the cross-check, it needs to be updated
25418 //This allows for either url or _jsonFileUrl to he changed to
25419 //reset the store load location. Done this way for backwards
25420 //compatibility. People use _jsonFileUrl (even though officially
25422 if(this._jsonFileUrl
!== this._ccUrl
){
25423 dojo
.deprecated("dojo.data.ItemFileReadStore: ",
25424 "To change the url, set the url property of the store," +
25425 " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
25426 this._ccUrl
= this._jsonFileUrl
;
25427 this.url
= this._jsonFileUrl
;
25428 }else if(this.url
!== this._ccUrl
){
25429 this._jsonFileUrl
= this.url
;
25430 this._ccUrl
= this.url
;
25433 //See if there was any forced reset of data.
25434 if(this.data
!= null && this._jsonData
== null){
25435 this._jsonData
= this.data
;
25439 if(this._jsonFileUrl
){
25440 //If fetches come in before the loading has finished, but while
25441 //a load is in progress, we have to defer the fetching to be
25442 //invoked in the callback.
25443 if(this._loadInProgress
){
25444 this._queuedFetches
.push({args
: keywordArgs
, filter
: filter
});
25446 this._loadInProgress
= true;
25448 url
: self
._jsonFileUrl
,
25449 handleAs
: "json-comment-optional",
25450 preventCache
: this.urlPreventCache
,
25451 failOk
: this.failOk
25453 var getHandler
= dojo
.xhrGet(getArgs
);
25454 getHandler
.addCallback(function(data
){
25456 self
._getItemsFromLoadedData(data
);
25457 self
._loadFinished
= true;
25458 self
._loadInProgress
= false;
25460 filter(keywordArgs
, self
._getItemsArray(keywordArgs
.queryOptions
));
25461 self
._handleQueuedFetches();
25463 self
._loadFinished
= true;
25464 self
._loadInProgress
= false;
25465 errorCallback(e
, keywordArgs
);
25468 getHandler
.addErrback(function(error
){
25469 self
._loadInProgress
= false;
25470 errorCallback(error
, keywordArgs
);
25473 //Wire up the cancel to abort of the request
25474 //This call cancel on the deferred if it hasn't been called
25475 //yet and then will chain to the simple abort of the
25476 //simpleFetch keywordArgs
25477 var oldAbort
= null;
25478 if(keywordArgs
.abort
){
25479 oldAbort
= keywordArgs
.abort
;
25481 keywordArgs
.abort = function(){
25482 var df
= getHandler
;
25483 if(df
&& df
.fired
=== -1){
25488 oldAbort
.call(keywordArgs
);
25492 }else if(this._jsonData
){
25494 this._loadFinished
= true;
25495 this._getItemsFromLoadedData(this._jsonData
);
25496 this._jsonData
= null;
25497 filter(keywordArgs
, this._getItemsArray(keywordArgs
.queryOptions
));
25499 errorCallback(e
, keywordArgs
);
25502 errorCallback(new Error("dojo.data.ItemFileReadStore: No JSON source data was provided as either URL or a nested Javascript object."), keywordArgs
);
25507 _handleQueuedFetches: function(){
25509 // Internal function to execute delayed request in the store.
25510 //Execute any deferred fetches now.
25511 if(this._queuedFetches
.length
> 0){
25512 for(var i
= 0; i
< this._queuedFetches
.length
; i
++){
25513 var fData
= this._queuedFetches
[i
],
25514 delayedQuery
= fData
.args
,
25515 delayedFilter
= fData
.filter
;
25517 delayedFilter(delayedQuery
, this._getItemsArray(delayedQuery
.queryOptions
));
25519 this.fetchItemByIdentity(delayedQuery
);
25522 this._queuedFetches
= [];
25526 _getItemsArray: function(/*object?*/queryOptions
){
25528 // Internal function to determine which list of items to search over.
25529 // queryOptions: The query options parameter, if any.
25530 if(queryOptions
&& queryOptions
.deep
){
25531 return this._arrayOfAllItems
;
25533 return this._arrayOfTopLevelItems
;
25536 close: function(/*dojo.data.api.Request || keywordArgs || null */ request
){
25538 // See dojo.data.api.Read.close()
25539 if(this.clearOnClose
&&
25540 this._loadFinished
&&
25541 !this._loadInProgress
){
25542 //Reset all internalsback to default state. This will force a reload
25543 //on next fetch. This also checks that the data or url param was set
25544 //so that the store knows it can get data. Without one of those being set,
25545 //the next fetch will trigger an error.
25547 if(((this._jsonFileUrl
== "" || this._jsonFileUrl
== null) &&
25548 (this.url
== "" || this.url
== null)
25549 ) && this.data
== null){
25550 console
.debug("dojo.data.ItemFileReadStore: WARNING! Data reload " +
25551 " information has not been provided." +
25552 " Please set 'url' or 'data' to the appropriate value before" +
25553 " the next fetch");
25555 this._arrayOfAllItems
= [];
25556 this._arrayOfTopLevelItems
= [];
25557 this._loadFinished
= false;
25558 this._itemsByIdentity
= null;
25559 this._loadInProgress
= false;
25560 this._queuedFetches
= [];
25564 _getItemsFromLoadedData: function(/* Object */ dataObject
){
25566 // Function to parse the loaded data into item format and build the internal items array.
25568 // Function to parse the loaded data into item format and build the internal items array.
25571 // The JS data object containing the raw data to convery into item format.
25574 // Array of items in store item format.
25576 // First, we define a couple little utility functions...
25577 var addingArrays
= false,
25580 function valueIsAnItem(/* anything */ aValue
){
25582 // Given any sort of value that could be in the raw json data,
25583 // return true if we should interpret the value as being an
25584 // item itself, rather than a literal value or a reference.
25586 // | false == valueIsAnItem("Kermit");
25587 // | false == valueIsAnItem(42);
25588 // | false == valueIsAnItem(new Date());
25589 // | false == valueIsAnItem({_type:'Date', _value:'May 14, 1802'});
25590 // | false == valueIsAnItem({_reference:'Kermit'});
25591 // | true == valueIsAnItem({name:'Kermit', color:'green'});
25592 // | true == valueIsAnItem({iggy:'pop'});
25593 // | true == valueIsAnItem({foo:42});
25595 (aValue
!== null) &&
25596 (typeof aValue
=== "object") &&
25597 (!dojo
.isArray(aValue
) || addingArrays
) &&
25598 (!dojo
.isFunction(aValue
)) &&
25599 (aValue
.constructor == Object
|| dojo
.isArray(aValue
)) &&
25600 (typeof aValue
._reference
=== "undefined") &&
25601 (typeof aValue
._type
=== "undefined") &&
25602 (typeof aValue
._value
=== "undefined") &&
25608 function addItemAndSubItemsToArrayOfAllItems(/* Item */ anItem
){
25609 self
._arrayOfAllItems
.push(anItem
);
25610 for(var attribute
in anItem
){
25611 var valueForAttribute
= anItem
[attribute
];
25612 if(valueForAttribute
){
25613 if(dojo
.isArray(valueForAttribute
)){
25614 var valueArray
= valueForAttribute
;
25615 for(var k
= 0; k
< valueArray
.length
; ++k
){
25616 var singleValue
= valueArray
[k
];
25617 if(valueIsAnItem(singleValue
)){
25618 addItemAndSubItemsToArrayOfAllItems(singleValue
);
25622 if(valueIsAnItem(valueForAttribute
)){
25623 addItemAndSubItemsToArrayOfAllItems(valueForAttribute
);
25630 this._labelAttr
= dataObject
.label
;
25632 // We need to do some transformations to convert the data structure
25633 // that we read from the file into a format that will be convenient
25634 // to work with in memory.
25636 // Step 1: Walk through the object hierarchy and build a list of all items
25639 this._arrayOfAllItems
= [];
25640 this._arrayOfTopLevelItems
= dataObject
.items
;
25642 for(i
= 0; i
< this._arrayOfTopLevelItems
.length
; ++i
){
25643 item
= this._arrayOfTopLevelItems
[i
];
25644 if(dojo
.isArray(item
)){
25645 addingArrays
= true;
25647 addItemAndSubItemsToArrayOfAllItems(item
);
25648 item
[this._rootItemPropName
]=true;
25651 // Step 2: Walk through all the attribute values of all the items,
25652 // and replace single values with arrays. For example, we change this:
25653 // { name:'Miss Piggy', pets:'Foo-Foo'}
25655 // { name:['Miss Piggy'], pets:['Foo-Foo']}
25657 // We also store the attribute names so we can validate our store
25658 // reference and item id special properties for the O(1) isItem
25659 var allAttributeNames
= {},
25662 for(i
= 0; i
< this._arrayOfAllItems
.length
; ++i
){
25663 item
= this._arrayOfAllItems
[i
];
25665 if(key
!== this._rootItemPropName
){
25666 var value
= item
[key
];
25667 if(value
!== null){
25668 if(!dojo
.isArray(value
)){
25669 item
[key
] = [value
];
25672 item
[key
] = [null];
25675 allAttributeNames
[key
]=key
;
25679 // Step 3: Build unique property names to use for the _storeRefPropName and _itemNumPropName
25680 // This should go really fast, it will generally never even run the loop.
25681 while(allAttributeNames
[this._storeRefPropName
]){
25682 this._storeRefPropName
+= "_";
25684 while(allAttributeNames
[this._itemNumPropName
]){
25685 this._itemNumPropName
+= "_";
25687 while(allAttributeNames
[this._reverseRefMap
]){
25688 this._reverseRefMap
+= "_";
25691 // Step 4: Some data files specify an optional 'identifier', which is
25692 // the name of an attribute that holds the identity of each item.
25693 // If this data file specified an identifier attribute, then build a
25694 // hash table of items keyed by the identity of the items.
25697 var identifier
= dataObject
.identifier
;
25699 this._itemsByIdentity
= {};
25700 this._features
['dojo.data.api.Identity'] = identifier
;
25701 for(i
= 0; i
< this._arrayOfAllItems
.length
; ++i
){
25702 item
= this._arrayOfAllItems
[i
];
25703 arrayOfValues
= item
[identifier
];
25704 var identity
= arrayOfValues
[0];
25705 if(!this._itemsByIdentity
[identity
]){
25706 this._itemsByIdentity
[identity
] = item
;
25708 if(this._jsonFileUrl
){
25709 throw new Error("dojo.data.ItemFileReadStore: The json data as specified by: [" + this._jsonFileUrl
+ "] is malformed. Items within the list have identifier: [" + identifier
+ "]. Value collided: [" + identity
+ "]");
25710 }else if(this._jsonData
){
25711 throw new Error("dojo.data.ItemFileReadStore: The json data provided by the creation arguments is malformed. Items within the list have identifier: [" + identifier
+ "]. Value collided: [" + identity
+ "]");
25716 this._features
['dojo.data.api.Identity'] = Number
;
25719 // Step 5: Walk through all the items, and set each item's properties
25720 // for _storeRefPropName and _itemNumPropName, so that store.isItem() will return true.
25721 for(i
= 0; i
< this._arrayOfAllItems
.length
; ++i
){
25722 item
= this._arrayOfAllItems
[i
];
25723 item
[this._storeRefPropName
] = this;
25724 item
[this._itemNumPropName
] = i
;
25727 // Step 6: We walk through all the attribute values of all the items,
25728 // looking for type/value literals and item-references.
25730 // We replace item-references with pointers to items. For example, we change:
25731 // { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
25733 // { name:['Kermit'], friends:[miss_piggy] }
25734 // (where miss_piggy is the object representing the 'Miss Piggy' item).
25736 // We replace type/value pairs with typed-literals. For example, we change:
25737 // { name:['Nelson Mandela'], born:[{_type:'Date', _value:'July 18, 1918'}] }
25739 // { name:['Kermit'], born:(new Date('July 18, 1918')) }
25741 // We also generate the associate map for all items for the O(1) isItem function.
25742 for(i
= 0; i
< this._arrayOfAllItems
.length
; ++i
){
25743 item
= this._arrayOfAllItems
[i
]; // example: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
25745 arrayOfValues
= item
[key
]; // example: [{_reference:{name:'Miss Piggy'}}]
25746 for(var j
= 0; j
< arrayOfValues
.length
; ++j
){
25747 value
= arrayOfValues
[j
]; // example: {_reference:{name:'Miss Piggy'}}
25748 if(value
!== null && typeof value
== "object"){
25749 if(("_type" in value
) && ("_value" in value
)){
25750 var type
= value
._type
; // examples: 'Date', 'Color', or 'ComplexNumber'
25751 var mappingObj
= this._datatypeMap
[type
]; // examples: Date, dojo.Color, foo.math.ComplexNumber, {type: dojo.Color, deserialize(value){ return new dojo.Color(value)}}
25753 throw new Error("dojo.data.ItemFileReadStore: in the typeMap constructor arg, no object class was specified for the datatype '" + type
+ "'");
25754 }else if(dojo
.isFunction(mappingObj
)){
25755 arrayOfValues
[j
] = new mappingObj(value
._value
);
25756 }else if(dojo
.isFunction(mappingObj
.deserialize
)){
25757 arrayOfValues
[j
] = mappingObj
.deserialize(value
._value
);
25759 throw new Error("dojo.data.ItemFileReadStore: Value provided in typeMap was neither a constructor, nor a an object with a deserialize function");
25762 if(value
._reference
){
25763 var referenceDescription
= value
._reference
; // example: {name:'Miss Piggy'}
25764 if(!dojo
.isObject(referenceDescription
)){
25765 // example: 'Miss Piggy'
25766 // from an item like: { name:['Kermit'], friends:[{_reference:'Miss Piggy'}]}
25767 arrayOfValues
[j
] = this._getItemByIdentity(referenceDescription
);
25769 // example: {name:'Miss Piggy'}
25770 // from an item like: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
25771 for(var k
= 0; k
< this._arrayOfAllItems
.length
; ++k
){
25772 var candidateItem
= this._arrayOfAllItems
[k
],
25774 for(var refKey
in referenceDescription
){
25775 if(candidateItem
[refKey
] != referenceDescription
[refKey
]){
25780 arrayOfValues
[j
] = candidateItem
;
25784 if(this.referenceIntegrity
){
25785 var refItem
= arrayOfValues
[j
];
25786 if(this.isItem(refItem
)){
25787 this._addReferenceToMap(refItem
, item
, key
);
25790 }else if(this.isItem(value
)){
25791 //It's a child item (not one referenced through _reference).
25792 //We need to treat this as a referenced item, so it can be cleaned up
25793 //in a write store easily.
25794 if(this.referenceIntegrity
){
25795 this._addReferenceToMap(value
, item
, key
);
25804 _addReferenceToMap: function(/*item*/ refItem
, /*item*/ parentItem
, /*string*/ attribute
){
25806 // Method to add an reference map entry for an item and attribute.
25808 // Method to add an reference map entry for an item and attribute. //
25810 // The item that is referenced.
25812 // The item that holds the new reference to refItem.
25814 // The attribute on parentItem that contains the new reference.
25816 //Stub function, does nothing. Real processing is in ItemFileWriteStore.
25819 getIdentity: function(/* item */ item
){
25821 // See dojo.data.api.Identity.getIdentity()
25822 var identifier
= this._features
['dojo.data.api.Identity'];
25823 if(identifier
=== Number
){
25824 return item
[this._itemNumPropName
]; // Number
25826 var arrayOfValues
= item
[identifier
];
25828 return arrayOfValues
[0]; // Object || String
25831 return null; // null
25834 fetchItemByIdentity: function(/* Object */ keywordArgs
){
25836 // See dojo.data.api.Identity.fetchItemByIdentity()
25838 // Hasn't loaded yet, we have to trigger the load.
25841 if(!this._loadFinished
){
25843 //Do a check on the JsonFileUrl and crosscheck it.
25844 //If it doesn't match the cross-check, it needs to be updated
25845 //This allows for either url or _jsonFileUrl to he changed to
25846 //reset the store load location. Done this way for backwards
25847 //compatibility. People use _jsonFileUrl (even though officially
25849 if(this._jsonFileUrl
!== this._ccUrl
){
25850 dojo
.deprecated("dojo.data.ItemFileReadStore: ",
25851 "To change the url, set the url property of the store," +
25852 " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
25853 this._ccUrl
= this._jsonFileUrl
;
25854 this.url
= this._jsonFileUrl
;
25855 }else if(this.url
!== this._ccUrl
){
25856 this._jsonFileUrl
= this.url
;
25857 this._ccUrl
= this.url
;
25860 //See if there was any forced reset of data.
25861 if(this.data
!= null && this._jsonData
== null){
25862 this._jsonData
= this.data
;
25866 if(this._jsonFileUrl
){
25868 if(this._loadInProgress
){
25869 this._queuedFetches
.push({args
: keywordArgs
});
25871 this._loadInProgress
= true;
25873 url
: self
._jsonFileUrl
,
25874 handleAs
: "json-comment-optional",
25875 preventCache
: this.urlPreventCache
,
25876 failOk
: this.failOk
25878 var getHandler
= dojo
.xhrGet(getArgs
);
25879 getHandler
.addCallback(function(data
){
25880 var scope
= keywordArgs
.scope
?keywordArgs
.scope
:dojo
.global
;
25882 self
._getItemsFromLoadedData(data
);
25883 self
._loadFinished
= true;
25884 self
._loadInProgress
= false;
25885 item
= self
._getItemByIdentity(keywordArgs
.identity
);
25886 if(keywordArgs
.onItem
){
25887 keywordArgs
.onItem
.call(scope
, item
);
25889 self
._handleQueuedFetches();
25891 self
._loadInProgress
= false;
25892 if(keywordArgs
.onError
){
25893 keywordArgs
.onError
.call(scope
, error
);
25897 getHandler
.addErrback(function(error
){
25898 self
._loadInProgress
= false;
25899 if(keywordArgs
.onError
){
25900 var scope
= keywordArgs
.scope
?keywordArgs
.scope
:dojo
.global
;
25901 keywordArgs
.onError
.call(scope
, error
);
25906 }else if(this._jsonData
){
25907 // Passed in data, no need to xhr.
25908 self
._getItemsFromLoadedData(self
._jsonData
);
25909 self
._jsonData
= null;
25910 self
._loadFinished
= true;
25911 item
= self
._getItemByIdentity(keywordArgs
.identity
);
25912 if(keywordArgs
.onItem
){
25913 scope
= keywordArgs
.scope
?keywordArgs
.scope
:dojo
.global
;
25914 keywordArgs
.onItem
.call(scope
, item
);
25918 // Already loaded. We can just look it up and call back.
25919 item
= this._getItemByIdentity(keywordArgs
.identity
);
25920 if(keywordArgs
.onItem
){
25921 scope
= keywordArgs
.scope
?keywordArgs
.scope
:dojo
.global
;
25922 keywordArgs
.onItem
.call(scope
, item
);
25927 _getItemByIdentity: function(/* Object */ identity
){
25929 // Internal function to look an item up by its identity map.
25931 if(this._itemsByIdentity
){
25932 item
= this._itemsByIdentity
[identity
];
25934 item
= this._arrayOfAllItems
[identity
];
25936 if(item
=== undefined){
25939 return item
; // Object
25942 getIdentityAttributes: function(/* item */ item
){
25944 // See dojo.data.api.Identity.getIdentifierAttributes()
25946 var identifier
= this._features
['dojo.data.api.Identity'];
25947 if(identifier
=== Number
){
25948 // If (identifier === Number) it means getIdentity() just returns
25949 // an integer item-number for each item. The dojo.data.api.Identity
25950 // spec says we need to return null if the identity is not composed
25952 return null; // null
25954 return [identifier
]; // Array
25958 _forceLoad: function(){
25960 // Internal function to force a load of the store if it hasn't occurred yet. This is required
25961 // for specific functions to work properly.
25963 //Do a check on the JsonFileUrl and crosscheck it.
25964 //If it doesn't match the cross-check, it needs to be updated
25965 //This allows for either url or _jsonFileUrl to he changed to
25966 //reset the store load location. Done this way for backwards
25967 //compatibility. People use _jsonFileUrl (even though officially
25969 if(this._jsonFileUrl
!== this._ccUrl
){
25970 dojo
.deprecated("dojo.data.ItemFileReadStore: ",
25971 "To change the url, set the url property of the store," +
25972 " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
25973 this._ccUrl
= this._jsonFileUrl
;
25974 this.url
= this._jsonFileUrl
;
25975 }else if(this.url
!== this._ccUrl
){
25976 this._jsonFileUrl
= this.url
;
25977 this._ccUrl
= this.url
;
25980 //See if there was any forced reset of data.
25981 if(this.data
!= null && this._jsonData
== null){
25982 this._jsonData
= this.data
;
25986 if(this._jsonFileUrl
){
25988 url
: this._jsonFileUrl
,
25989 handleAs
: "json-comment-optional",
25990 preventCache
: this.urlPreventCache
,
25991 failOk
: this.failOk
,
25994 var getHandler
= dojo
.xhrGet(getArgs
);
25995 getHandler
.addCallback(function(data
){
25997 //Check to be sure there wasn't another load going on concurrently
25998 //So we don't clobber data that comes in on it. If there is a load going on
25999 //then do not save this data. It will potentially clobber current data.
26000 //We mainly wanted to sync/wait here.
26001 //TODO: Revisit the loading scheme of this store to improve multi-initial
26002 //request handling.
26003 if(self
._loadInProgress
!== true && !self
._loadFinished
){
26004 self
._getItemsFromLoadedData(data
);
26005 self
._loadFinished
= true;
26006 }else if(self
._loadInProgress
){
26007 //Okay, we hit an error state we can't recover from. A forced load occurred
26008 //while an async load was occurring. Since we cannot block at this point, the best
26009 //that can be managed is to throw an error.
26010 throw new Error("dojo.data.ItemFileReadStore: Unable to perform a synchronous load, an async load is in progress.");
26017 getHandler
.addErrback(function(error
){
26020 }else if(this._jsonData
){
26021 self
._getItemsFromLoadedData(self
._jsonData
);
26022 self
._jsonData
= null;
26023 self
._loadFinished
= true;
26027 //Mix in the simple fetch implementation to this class.
26028 dojo
.extend(dojo
.data
.ItemFileReadStore
,dojo
.data
.util
.simpleFetch
);
26032 if(!dojo
._hasResource
["dojo.data.ItemFileWriteStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
26033 dojo
._hasResource
["dojo.data.ItemFileWriteStore"] = true;
26034 dojo
.provide("dojo.data.ItemFileWriteStore");
26037 dojo
.declare("dojo.data.ItemFileWriteStore", dojo
.data
.ItemFileReadStore
, {
26038 constructor: function(/* object */ keywordParameters
){
26039 // keywordParameters: {typeMap: object)
26040 // The structure of the typeMap object is as follows:
26042 // type0: function || object,
26043 // type1: function || object,
26045 // typeN: function || object
26047 // Where if it is a function, it is assumed to be an object constructor that takes the
26048 // value of _value as the initialization parameters. It is serialized assuming object.toString()
26049 // serialization. If it is an object, then it is assumed
26050 // to be an object of general form:
26052 // type: function, //constructor.
26053 // deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
26054 // serialize: function(object) //The function that converts the object back into the proper file format form.
26057 // ItemFileWriteStore extends ItemFileReadStore to implement these additional dojo.data APIs
26058 this._features
['dojo.data.api.Write'] = true;
26059 this._features
['dojo.data.api.Notification'] = true;
26061 // For keeping track of changes so that we can implement isDirty and revert
26068 if(!this._datatypeMap
['Date'].serialize
){
26069 this._datatypeMap
['Date'].serialize = function(obj
){
26070 return dojo
.date
.stamp
.toISOString(obj
, {zulu
:true});
26073 //Disable only if explicitly set to false.
26074 if(keywordParameters
&& (keywordParameters
.referenceIntegrity
=== false)){
26075 this.referenceIntegrity
= false;
26078 // this._saveInProgress is set to true, briefly, from when save() is first called to when it completes
26079 this._saveInProgress
= false;
26082 referenceIntegrity
: true, //Flag that defaultly enabled reference integrity tracking. This way it can also be disabled pogrammatially or declaratively.
26084 _assert: function(/* boolean */ condition
){
26086 throw new Error("assertion failed in ItemFileWriteStore");
26090 _getIdentifierAttribute: function(){
26091 var identifierAttribute
= this.getFeatures()['dojo.data.api.Identity'];
26092 // this._assert((identifierAttribute === Number) || (dojo.isString(identifierAttribute)));
26093 return identifierAttribute
;
26097 /* dojo.data.api.Write */
26099 newItem: function(/* Object? */ keywordArgs
, /* Object? */ parentInfo
){
26100 // summary: See dojo.data.api.Write.newItem()
26102 this._assert(!this._saveInProgress
);
26104 if(!this._loadFinished
){
26105 // We need to do this here so that we'll be able to find out what
26106 // identifierAttribute was specified in the data file.
26110 if(typeof keywordArgs
!= "object" && typeof keywordArgs
!= "undefined"){
26111 throw new Error("newItem() was passed something other than an object");
26113 var newIdentity
= null;
26114 var identifierAttribute
= this._getIdentifierAttribute();
26115 if(identifierAttribute
=== Number
){
26116 newIdentity
= this._arrayOfAllItems
.length
;
26118 newIdentity
= keywordArgs
[identifierAttribute
];
26119 if(typeof newIdentity
=== "undefined"){
26120 throw new Error("newItem() was not passed an identity for the new item");
26122 if(dojo
.isArray(newIdentity
)){
26123 throw new Error("newItem() was not passed an single-valued identity");
26127 // make sure this identity is not already in use by another item, if identifiers were
26128 // defined in the file. Otherwise it would be the item count,
26129 // which should always be unique in this case.
26130 if(this._itemsByIdentity
){
26131 this._assert(typeof this._itemsByIdentity
[newIdentity
] === "undefined");
26133 this._assert(typeof this._pending
._newItems
[newIdentity
] === "undefined");
26134 this._assert(typeof this._pending
._deletedItems
[newIdentity
] === "undefined");
26137 newItem
[this._storeRefPropName
] = this;
26138 newItem
[this._itemNumPropName
] = this._arrayOfAllItems
.length
;
26139 if(this._itemsByIdentity
){
26140 this._itemsByIdentity
[newIdentity
] = newItem
;
26141 //We have to set the identifier now, otherwise we can't look it
26142 //up at calls to setValueorValues in parentInfo handling.
26143 newItem
[identifierAttribute
] = [newIdentity
];
26145 this._arrayOfAllItems
.push(newItem
);
26147 //We need to construct some data for the onNew call too...
26150 // Now we need to check to see where we want to assign this thingm if any.
26151 if(parentInfo
&& parentInfo
.parent
&& parentInfo
.attribute
){
26153 item
: parentInfo
.parent
,
26154 attribute
: parentInfo
.attribute
,
26155 oldValue
: undefined
26158 //See if it is multi-valued or not and handle appropriately
26159 //Generally, all attributes are multi-valued for this store
26160 //So, we only need to append if there are already values present.
26161 var values
= this.getValues(parentInfo
.parent
, parentInfo
.attribute
);
26162 if(values
&& values
.length
> 0){
26163 var tempValues
= values
.slice(0, values
.length
);
26164 if(values
.length
=== 1){
26165 pInfo
.oldValue
= values
[0];
26167 pInfo
.oldValue
= values
.slice(0, values
.length
);
26169 tempValues
.push(newItem
);
26170 this._setValueOrValues(parentInfo
.parent
, parentInfo
.attribute
, tempValues
, false);
26171 pInfo
.newValue
= this.getValues(parentInfo
.parent
, parentInfo
.attribute
);
26173 this._setValueOrValues(parentInfo
.parent
, parentInfo
.attribute
, newItem
, false);
26174 pInfo
.newValue
= newItem
;
26177 //Toplevel item, add to both top list as well as all list.
26178 newItem
[this._rootItemPropName
]=true;
26179 this._arrayOfTopLevelItems
.push(newItem
);
26182 this._pending
._newItems
[newIdentity
] = newItem
;
26184 //Clone over the properties to the new item
26185 for(var key
in keywordArgs
){
26186 if(key
=== this._storeRefPropName
|| key
=== this._itemNumPropName
){
26187 // Bummer, the user is trying to do something like
26188 // newItem({_S:"foo"}). Unfortunately, our superclass,
26189 // ItemFileReadStore, is already using _S in each of our items
26190 // to hold private info. To avoid a naming collision, we
26191 // need to move all our private info to some other property
26192 // of all the items/objects. So, we need to iterate over all
26193 // the items and do something like:
26194 // item.__S = item._S;
26195 // item._S = undefined;
26196 // But first we have to make sure the new "__S" variable is
26197 // not in use, which means we have to iterate over all the
26198 // items checking for that.
26199 throw new Error("encountered bug in ItemFileWriteStore.newItem");
26201 var value
= keywordArgs
[key
];
26202 if(!dojo
.isArray(value
)){
26205 newItem
[key
] = value
;
26206 if(this.referenceIntegrity
){
26207 for(var i
= 0; i
< value
.length
; i
++){
26208 var val
= value
[i
];
26209 if(this.isItem(val
)){
26210 this._addReferenceToMap(val
, newItem
, key
);
26215 this.onNew(newItem
, pInfo
); // dojo.data.api.Notification call
26216 return newItem
; // item
26219 _removeArrayElement: function(/* Array */ array
, /* anything */ element
){
26220 var index
= dojo
.indexOf(array
, element
);
26222 array
.splice(index
, 1);
26228 deleteItem: function(/* item */ item
){
26229 // summary: See dojo.data.api.Write.deleteItem()
26230 this._assert(!this._saveInProgress
);
26231 this._assertIsItem(item
);
26233 // Remove this item from the _arrayOfAllItems, but leave a null value in place
26234 // of the item, so as not to change the length of the array, so that in newItem()
26235 // we can still safely do: newIdentity = this._arrayOfAllItems.length;
26236 var indexInArrayOfAllItems
= item
[this._itemNumPropName
];
26237 var identity
= this.getIdentity(item
);
26239 //If we have reference integrity on, we need to do reference cleanup for the deleted item
26240 if(this.referenceIntegrity
){
26241 //First scan all the attributes of this items for references and clean them up in the map
26242 //As this item is going away, no need to track its references anymore.
26244 //Get the attributes list before we generate the backup so it
26245 //doesn't pollute the attributes list.
26246 var attributes
= this.getAttributes(item
);
26248 //Backup the map, we'll have to restore it potentially, in a revert.
26249 if(item
[this._reverseRefMap
]){
26250 item
["backup_" + this._reverseRefMap
] = dojo
.clone(item
[this._reverseRefMap
]);
26253 //TODO: This causes a reversion problem. This list won't be restored on revert since it is
26254 //attached to the 'value'. item, not ours. Need to back tese up somehow too.
26255 //Maybe build a map of the backup of the entries and attach it to the deleted item to be restored
26256 //later. Or just record them and call _addReferenceToMap on them in revert.
26257 dojo
.forEach(attributes
, function(attribute
){
26258 dojo
.forEach(this.getValues(item
, attribute
), function(value
){
26259 if(this.isItem(value
)){
26260 //We have to back up all the references we had to others so they can be restored on a revert.
26261 if(!item
["backupRefs_" + this._reverseRefMap
]){
26262 item
["backupRefs_" + this._reverseRefMap
] = [];
26264 item
["backupRefs_" + this._reverseRefMap
].push({id
: this.getIdentity(value
), attr
: attribute
});
26265 this._removeReferenceFromMap(value
, item
, attribute
);
26270 //Next, see if we have references to this item, if we do, we have to clean them up too.
26271 var references
= item
[this._reverseRefMap
];
26273 //Look through all the items noted as references to clean them up.
26274 for(var itemId
in references
){
26275 var containingItem
= null;
26276 if(this._itemsByIdentity
){
26277 containingItem
= this._itemsByIdentity
[itemId
];
26279 containingItem
= this._arrayOfAllItems
[itemId
];
26281 //We have a reference to a containing item, now we have to process the
26282 //attributes and clear all references to the item being deleted.
26283 if(containingItem
){
26284 for(var attribute
in references
[itemId
]){
26285 var oldValues
= this.getValues(containingItem
, attribute
) || [];
26286 var newValues
= dojo
.filter(oldValues
, function(possibleItem
){
26287 return !(this.isItem(possibleItem
) && this.getIdentity(possibleItem
) == identity
);
26289 //Remove the note of the reference to the item and set the values on the modified attribute.
26290 this._removeReferenceFromMap(item
, containingItem
, attribute
);
26291 if(newValues
.length
< oldValues
.length
){
26292 this._setValueOrValues(containingItem
, attribute
, newValues
, true);
26300 this._arrayOfAllItems
[indexInArrayOfAllItems
] = null;
26302 item
[this._storeRefPropName
] = null;
26303 if(this._itemsByIdentity
){
26304 delete this._itemsByIdentity
[identity
];
26306 this._pending
._deletedItems
[identity
] = item
;
26308 //Remove from the toplevel items, if necessary...
26309 if(item
[this._rootItemPropName
]){
26310 this._removeArrayElement(this._arrayOfTopLevelItems
, item
);
26312 this.onDelete(item
); // dojo.data.api.Notification call
26316 setValue: function(/* item */ item
, /* attribute-name-string */ attribute
, /* almost anything */ value
){
26317 // summary: See dojo.data.api.Write.set()
26318 return this._setValueOrValues(item
, attribute
, value
, true); // boolean
26321 setValues: function(/* item */ item
, /* attribute-name-string */ attribute
, /* array */ values
){
26322 // summary: See dojo.data.api.Write.setValues()
26323 return this._setValueOrValues(item
, attribute
, values
, true); // boolean
26326 unsetAttribute: function(/* item */ item
, /* attribute-name-string */ attribute
){
26327 // summary: See dojo.data.api.Write.unsetAttribute()
26328 return this._setValueOrValues(item
, attribute
, [], true);
26331 _setValueOrValues: function(/* item */ item
, /* attribute-name-string */ attribute
, /* anything */ newValueOrValues
, /*boolean?*/ callOnSet
){
26332 this._assert(!this._saveInProgress
);
26334 // Check for valid arguments
26335 this._assertIsItem(item
);
26336 this._assert(dojo
.isString(attribute
));
26337 this._assert(typeof newValueOrValues
!== "undefined");
26339 // Make sure the user isn't trying to change the item's identity
26340 var identifierAttribute
= this._getIdentifierAttribute();
26341 if(attribute
== identifierAttribute
){
26342 throw new Error("ItemFileWriteStore does not have support for changing the value of an item's identifier.");
26345 // To implement the Notification API, we need to make a note of what
26346 // the old attribute value was, so that we can pass that info when
26347 // we call the onSet method.
26348 var oldValueOrValues
= this._getValueOrValues(item
, attribute
);
26350 var identity
= this.getIdentity(item
);
26351 if(!this._pending
._modifiedItems
[identity
]){
26352 // Before we actually change the item, we make a copy of it to
26353 // record the original state, so that we'll be able to revert if
26354 // the revert method gets called. If the item has already been
26355 // modified then there's no need to do this now, since we already
26356 // have a record of the original state.
26357 var copyOfItemState
= {};
26358 for(var key
in item
){
26359 if((key
=== this._storeRefPropName
) || (key
=== this._itemNumPropName
) || (key
=== this._rootItemPropName
)){
26360 copyOfItemState
[key
] = item
[key
];
26361 }else if(key
=== this._reverseRefMap
){
26362 copyOfItemState
[key
] = dojo
.clone(item
[key
]);
26364 copyOfItemState
[key
] = item
[key
].slice(0, item
[key
].length
);
26367 // Now mark the item as dirty, and save the copy of the original state
26368 this._pending
._modifiedItems
[identity
] = copyOfItemState
;
26371 // Okay, now we can actually change this attribute on the item
26372 var success
= false;
26374 if(dojo
.isArray(newValueOrValues
) && newValueOrValues
.length
=== 0){
26376 // If we were passed an empty array as the value, that counts
26377 // as "unsetting" the attribute, so we need to remove this
26378 // attribute from the item.
26379 success
= delete item
[attribute
];
26380 newValueOrValues
= undefined; // used in the onSet Notification call below
26382 if(this.referenceIntegrity
&& oldValueOrValues
){
26383 var oldValues
= oldValueOrValues
;
26384 if(!dojo
.isArray(oldValues
)){
26385 oldValues
= [oldValues
];
26387 for(var i
= 0; i
< oldValues
.length
; i
++){
26388 var value
= oldValues
[i
];
26389 if(this.isItem(value
)){
26390 this._removeReferenceFromMap(value
, item
, attribute
);
26396 if(dojo
.isArray(newValueOrValues
)){
26397 var newValues
= newValueOrValues
;
26398 // Unfortunately, it's not safe to just do this:
26399 // newValueArray = newValues;
26400 // Instead, we need to copy the array, which slice() does very nicely.
26401 // This is so that our internal data structure won't
26402 // get corrupted if the user mucks with the values array *after*
26403 // calling setValues().
26404 newValueArray
= newValueOrValues
.slice(0, newValueOrValues
.length
);
26406 newValueArray
= [newValueOrValues
];
26409 //We need to handle reference integrity if this is on.
26410 //In the case of set, we need to see if references were added or removed
26411 //and update the reference tracking map accordingly.
26412 if(this.referenceIntegrity
){
26413 if(oldValueOrValues
){
26414 var oldValues
= oldValueOrValues
;
26415 if(!dojo
.isArray(oldValues
)){
26416 oldValues
= [oldValues
];
26418 //Use an associative map to determine what was added/removed from the list.
26419 //Should be O(n) performant. First look at all the old values and make a list of them
26420 //Then for any item not in the old list, we add it. If it was already present, we remove it.
26421 //Then we pass over the map and any references left it it need to be removed (IE, no match in
26422 //the new values list).
26424 dojo
.forEach(oldValues
, function(possibleItem
){
26425 if(this.isItem(possibleItem
)){
26426 var id
= this.getIdentity(possibleItem
);
26427 map
[id
.toString()] = true;
26430 dojo
.forEach(newValueArray
, function(possibleItem
){
26431 if(this.isItem(possibleItem
)){
26432 var id
= this.getIdentity(possibleItem
);
26433 if(map
[id
.toString()]){
26434 delete map
[id
.toString()];
26436 this._addReferenceToMap(possibleItem
, item
, attribute
);
26440 for(var rId
in map
){
26442 if(this._itemsByIdentity
){
26443 removedItem
= this._itemsByIdentity
[rId
];
26445 removedItem
= this._arrayOfAllItems
[rId
];
26447 this._removeReferenceFromMap(removedItem
, item
, attribute
);
26450 //Everything is new (no old values) so we have to just
26451 //insert all the references, if any.
26452 for(var i
= 0; i
< newValueArray
.length
; i
++){
26453 var value
= newValueArray
[i
];
26454 if(this.isItem(value
)){
26455 this._addReferenceToMap(value
, item
, attribute
);
26460 item
[attribute
] = newValueArray
;
26464 // Now we make the dojo.data.api.Notification call
26466 this.onSet(item
, attribute
, oldValueOrValues
, newValueOrValues
);
26468 return success
; // boolean
26471 _addReferenceToMap: function(/*item*/ refItem
, /*item*/ parentItem
, /*string*/ attribute
){
26473 // Method to add an reference map entry for an item and attribute.
26475 // Method to add an reference map entry for an item and attribute. //
26477 // The item that is referenced.
26479 // The item that holds the new reference to refItem.
26481 // The attribute on parentItem that contains the new reference.
26483 var parentId
= this.getIdentity(parentItem
);
26484 var references
= refItem
[this._reverseRefMap
];
26487 references
= refItem
[this._reverseRefMap
] = {};
26489 var itemRef
= references
[parentId
];
26491 itemRef
= references
[parentId
] = {};
26493 itemRef
[attribute
] = true;
26496 _removeReferenceFromMap: function(/* item */ refItem
, /* item */ parentItem
, /*strin*/ attribute
){
26498 // Method to remove an reference map entry for an item and attribute.
26500 // Method to remove an reference map entry for an item and attribute. This will
26501 // also perform cleanup on the map such that if there are no more references at all to
26502 // the item, its reference object and entry are removed.
26505 // The item that is referenced.
26507 // The item holding a reference to refItem.
26509 // The attribute on parentItem that contains the reference.
26510 var identity
= this.getIdentity(parentItem
);
26511 var references
= refItem
[this._reverseRefMap
];
26514 for(itemId
in references
){
26515 if(itemId
== identity
){
26516 delete references
[itemId
][attribute
];
26517 if(this._isEmpty(references
[itemId
])){
26518 delete references
[itemId
];
26522 if(this._isEmpty(references
)){
26523 delete refItem
[this._reverseRefMap
];
26528 _dumpReferenceMap: function(){
26530 // Function to dump the reverse reference map of all items in the store for debug purposes.
26532 // Function to dump the reverse reference map of all items in the store for debug purposes.
26534 for(i
= 0; i
< this._arrayOfAllItems
.length
; i
++){
26535 var item
= this._arrayOfAllItems
[i
];
26536 if(item
&& item
[this._reverseRefMap
]){
26537 console
.log("Item: [" + this.getIdentity(item
) + "] is referenced by: " + dojo
.toJson(item
[this._reverseRefMap
]));
26542 _getValueOrValues: function(/* item */ item
, /* attribute-name-string */ attribute
){
26543 var valueOrValues
= undefined;
26544 if(this.hasAttribute(item
, attribute
)){
26545 var valueArray
= this.getValues(item
, attribute
);
26546 if(valueArray
.length
== 1){
26547 valueOrValues
= valueArray
[0];
26549 valueOrValues
= valueArray
;
26552 return valueOrValues
;
26555 _flatten: function(/* anything */ value
){
26556 if(this.isItem(value
)){
26558 // Given an item, return an serializable object that provides a
26559 // reference to the item.
26560 // For example, given kermit:
26561 // var kermit = store.newItem({id:2, name:"Kermit"});
26562 // we want to return
26564 var identity
= this.getIdentity(item
);
26565 var referenceObject
= {_reference
: identity
};
26566 return referenceObject
;
26568 if(typeof value
=== "object"){
26569 for(var type
in this._datatypeMap
){
26570 var typeMap
= this._datatypeMap
[type
];
26571 if(dojo
.isObject(typeMap
) && !dojo
.isFunction(typeMap
)){
26572 if(value
instanceof typeMap
.type
){
26573 if(!typeMap
.serialize
){
26574 throw new Error("ItemFileWriteStore: No serializer defined for type mapping: [" + type
+ "]");
26576 return {_type
: type
, _value
: typeMap
.serialize(value
)};
26578 } else if(value
instanceof typeMap
){
26579 //SImple mapping, therefore, return as a toString serialization.
26580 return {_type
: type
, _value
: value
.toString()};
26588 _getNewFileContentString: function(){
26590 // Generate a string that can be saved to a file.
26591 // The result should look similar to:
26592 // http://trac.dojotoolkit.org/browser/dojo/trunk/tests/data/countries.json
26593 var serializableStructure
= {};
26595 var identifierAttribute
= this._getIdentifierAttribute();
26596 if(identifierAttribute
!== Number
){
26597 serializableStructure
.identifier
= identifierAttribute
;
26599 if(this._labelAttr
){
26600 serializableStructure
.label
= this._labelAttr
;
26602 serializableStructure
.items
= [];
26603 for(var i
= 0; i
< this._arrayOfAllItems
.length
; ++i
){
26604 var item
= this._arrayOfAllItems
[i
];
26606 var serializableItem
= {};
26607 for(var key
in item
){
26608 if(key
!== this._storeRefPropName
&& key
!== this._itemNumPropName
&& key
!== this._reverseRefMap
&& key
!== this._rootItemPropName
){
26609 var attribute
= key
;
26610 var valueArray
= this.getValues(item
, attribute
);
26611 if(valueArray
.length
== 1){
26612 serializableItem
[attribute
] = this._flatten(valueArray
[0]);
26614 var serializableArray
= [];
26615 for(var j
= 0; j
< valueArray
.length
; ++j
){
26616 serializableArray
.push(this._flatten(valueArray
[j
]));
26617 serializableItem
[attribute
] = serializableArray
;
26622 serializableStructure
.items
.push(serializableItem
);
26625 var prettyPrint
= true;
26626 return dojo
.toJson(serializableStructure
, prettyPrint
);
26629 _isEmpty: function(something
){
26631 // Function to determine if an array or object has no properties or values.
26633 // The array or object to examine.
26635 if(dojo
.isObject(something
)){
26637 for(i
in something
){
26641 }else if(dojo
.isArray(something
)){
26642 if(something
.length
> 0){
26646 return empty
; //boolean
26649 save: function(/* object */ keywordArgs
){
26650 // summary: See dojo.data.api.Write.save()
26651 this._assert(!this._saveInProgress
);
26653 // this._saveInProgress is set to true, briefly, from when save is first called to when it completes
26654 this._saveInProgress
= true;
26657 var saveCompleteCallback = function(){
26664 self
._saveInProgress
= false; // must come after this._pending is cleared, but before any callbacks
26665 if(keywordArgs
&& keywordArgs
.onComplete
){
26666 var scope
= keywordArgs
.scope
|| dojo
.global
;
26667 keywordArgs
.onComplete
.call(scope
);
26670 var saveFailedCallback = function(err
){
26671 self
._saveInProgress
= false;
26672 if(keywordArgs
&& keywordArgs
.onError
){
26673 var scope
= keywordArgs
.scope
|| dojo
.global
;
26674 keywordArgs
.onError
.call(scope
, err
);
26678 if(this._saveEverything
){
26679 var newFileContentString
= this._getNewFileContentString();
26680 this._saveEverything(saveCompleteCallback
, saveFailedCallback
, newFileContentString
);
26682 if(this._saveCustom
){
26683 this._saveCustom(saveCompleteCallback
, saveFailedCallback
);
26685 if(!this._saveEverything
&& !this._saveCustom
){
26686 // Looks like there is no user-defined save-handler function.
26687 // That's fine, it just means the datastore is acting as a "mock-write"
26688 // store -- changes get saved in memory but don't get saved to disk.
26689 saveCompleteCallback();
26693 revert: function(){
26694 // summary: See dojo.data.api.Write.revert()
26695 this._assert(!this._saveInProgress
);
26698 for(identity
in this._pending
._modifiedItems
){
26699 // find the original item and the modified item that replaced it
26700 var copyOfItemState
= this._pending
._modifiedItems
[identity
];
26701 var modifiedItem
= null;
26702 if(this._itemsByIdentity
){
26703 modifiedItem
= this._itemsByIdentity
[identity
];
26705 modifiedItem
= this._arrayOfAllItems
[identity
];
26708 // Restore the original item into a full-fledged item again, we want to try to
26709 // keep the same object instance as if we don't it, causes bugs like #9022.
26710 copyOfItemState
[this._storeRefPropName
] = this;
26711 for(key
in modifiedItem
){
26712 delete modifiedItem
[key
];
26714 dojo
.mixin(modifiedItem
, copyOfItemState
);
26717 for(identity
in this._pending
._deletedItems
){
26718 deletedItem
= this._pending
._deletedItems
[identity
];
26719 deletedItem
[this._storeRefPropName
] = this;
26720 var index
= deletedItem
[this._itemNumPropName
];
26722 //Restore the reverse refererence map, if any.
26723 if(deletedItem
["backup_" + this._reverseRefMap
]){
26724 deletedItem
[this._reverseRefMap
] = deletedItem
["backup_" + this._reverseRefMap
];
26725 delete deletedItem
["backup_" + this._reverseRefMap
];
26727 this._arrayOfAllItems
[index
] = deletedItem
;
26728 if(this._itemsByIdentity
){
26729 this._itemsByIdentity
[identity
] = deletedItem
;
26731 if(deletedItem
[this._rootItemPropName
]){
26732 this._arrayOfTopLevelItems
.push(deletedItem
);
26735 //We have to pass through it again and restore the reference maps after all the
26736 //undeletes have occurred.
26737 for(identity
in this._pending
._deletedItems
){
26738 deletedItem
= this._pending
._deletedItems
[identity
];
26739 if(deletedItem
["backupRefs_" + this._reverseRefMap
]){
26740 dojo
.forEach(deletedItem
["backupRefs_" + this._reverseRefMap
], function(reference
){
26742 if(this._itemsByIdentity
){
26743 refItem
= this._itemsByIdentity
[reference
.id
];
26745 refItem
= this._arrayOfAllItems
[reference
.id
];
26747 this._addReferenceToMap(refItem
, deletedItem
, reference
.attr
);
26749 delete deletedItem
["backupRefs_" + this._reverseRefMap
];
26753 for(identity
in this._pending
._newItems
){
26754 var newItem
= this._pending
._newItems
[identity
];
26755 newItem
[this._storeRefPropName
] = null;
26756 // null out the new item, but don't change the array index so
26757 // so we can keep using _arrayOfAllItems.length.
26758 this._arrayOfAllItems
[newItem
[this._itemNumPropName
]] = null;
26759 if(newItem
[this._rootItemPropName
]){
26760 this._removeArrayElement(this._arrayOfTopLevelItems
, newItem
);
26762 if(this._itemsByIdentity
){
26763 delete this._itemsByIdentity
[identity
];
26772 return true; // boolean
26775 isDirty: function(/* item? */ item
){
26776 // summary: See dojo.data.api.Write.isDirty()
26778 // return true if the item is dirty
26779 var identity
= this.getIdentity(item
);
26780 return new Boolean(this._pending
._newItems
[identity
] ||
26781 this._pending
._modifiedItems
[identity
] ||
26782 this._pending
._deletedItems
[identity
]).valueOf(); // boolean
26784 // return true if the store is dirty -- which means return true
26785 // if there are any new items, dirty items, or modified items
26786 if(!this._isEmpty(this._pending
._newItems
) ||
26787 !this._isEmpty(this._pending
._modifiedItems
) ||
26788 !this._isEmpty(this._pending
._deletedItems
)){
26791 return false; // boolean
26795 /* dojo.data.api.Notification */
26797 onSet: function(/* item */ item
,
26798 /*attribute-name-string*/ attribute
,
26799 /*object | array*/ oldValue
,
26800 /*object | array*/ newValue
){
26801 // summary: See dojo.data.api.Notification.onSet()
26803 // No need to do anything. This method is here just so that the
26804 // client code can connect observers to it.
26807 onNew: function(/* item */ newItem
, /*object?*/ parentInfo
){
26808 // summary: See dojo.data.api.Notification.onNew()
26810 // No need to do anything. This method is here just so that the
26811 // client code can connect observers to it.
26814 onDelete: function(/* item */ deletedItem
){
26815 // summary: See dojo.data.api.Notification.onDelete()
26817 // No need to do anything. This method is here just so that the
26818 // client code can connect observers to it.
26821 close: function(/* object? */ request
){
26823 // Over-ride of base close function of ItemFileReadStore to add in check for store state.
26825 // Over-ride of base close function of ItemFileReadStore to add in check for store state.
26826 // If the store is still dirty (unsaved changes), then an error will be thrown instead of
26827 // clearing the internal state for reload from the url.
26829 //Clear if not dirty ... or throw an error
26830 if(this.clearOnClose
){
26831 if(!this.isDirty()){
26832 this.inherited(arguments
);
26834 //Only throw an error if the store was dirty and we were loading from a url (cannot reload from url until state is saved).
26835 throw new Error("dojo.data.ItemFileWriteStore: There are unsaved changes present in the store. Please save or revert the changes before invoking close.");
26844 dojo
.i18n
._preloadLocalizations("dojo.nls.tt-rss-layer", ["ROOT","ar","ca","cs","da","de","de-de","el","en","en-gb","en-us","es","es-es","fi","fi-fi","fr","fr-fr","he","he-il","hu","it","it-it","ja","ja-jp","ko","ko-kr","nb","nl","nl-nl","pl","pt","pt-br","pt-pt","ru","sk","sl","sv","th","tr","xx","zh","zh-cn","zh-tw"]);