or the inside the td,
// set node to the .
var node =
dojo.hasClass(evt.target, "dijitCalendarDateLabel") ?
evt.target.parentNode :
evt.target;
if(node && (node.dijitDateValue || node == this.previousYearLabelNode || node == this.nextYearLabelNode) ){
dojo.addClass(node, "dijitCalendarHoveredDate");
this._currentNode = node;
}
},
_onDayMouseOut: function(/*Event*/ evt){
// summary:
// Handler for mouse out events on days, clears hovered style
// tags:
// protected
if(!this._currentNode){ return; }
// if mouse out occurs moving from to inside , ignore it
if(evt.relatedTarget && evt.relatedTarget.parentNode == this._currentNode){ return; }
dojo.removeClass(this._currentNode, "dijitCalendarHoveredDate");
if(dojo.hasClass(this._currentNode, "dijitCalendarActiveDate")) {
dojo.removeClass(this._currentNode, "dijitCalendarActiveDate");
}
this._currentNode = null;
},
_onDayMouseDown: function(/*Event*/ evt){
var node = evt.target.parentNode;
if(node && node.dijitDateValue){
dojo.addClass(node, "dijitCalendarActiveDate");
this._currentNode = node;
}
},
_onDayMouseUp: function(/*Event*/ evt){
var node = evt.target.parentNode;
if(node && node.dijitDateValue){
dojo.removeClass(node, "dijitCalendarActiveDate");
}
},
//TODO: use typematic
//TODO: skip disabled dates without ending up in a loop
//TODO: could optimize by avoiding populate grid when month does not change
_onKeyPress: function(/*Event*/evt){
// summary:
// Provides keyboard navigation of calendar
// tags:
// protected
var dk = dojo.keys,
increment = -1,
interval,
newValue = this.value;
switch(evt.keyCode){
case dk.RIGHT_ARROW:
increment = 1;
//fallthrough...
case dk.LEFT_ARROW:
interval = "day";
if(!this.isLeftToRight()){ increment *= -1; }
break;
case dk.DOWN_ARROW:
increment = 1;
//fallthrough...
case dk.UP_ARROW:
interval = "week";
break;
case dk.PAGE_DOWN:
increment = 1;
//fallthrough...
case dk.PAGE_UP:
interval = evt.ctrlKey ? "year" : "month";
break;
case dk.END:
// go to the next month
newValue = this.dateFuncObj.add(newValue, "month", 1);
// subtract a day from the result when we're done
interval = "day";
//fallthrough...
case dk.HOME:
newValue = new Date(newValue).setDate(1);
break;
case dk.ENTER:
this.onValueSelected(this.get('value'));
break;
case dk.ESCAPE:
//TODO
default:
return;
}
dojo.stopEvent(evt);
if(interval){
newValue = this.dateFuncObj.add(newValue, interval, increment);
}
this.set("value", newValue);
},
onValueSelected: function(/*Date*/ date){
// summary:
// Notification that a date cell was selected. It may be the same as the previous value.
// description:
// Used by `dijit.form._DateTimeTextBox` (and thus `dijit.form.DateTextBox`)
// to get notification when the user has clicked a date.
// tags:
// protected
},
onChange: function(/*Date*/ date){
// summary:
// Called only when the selected date has changed
},
_isSelectedDate: function(/*Date*/ dateObject, /*String?*/ locale){
// summary:
// Extension point so developers can subclass Calendar to
// support multiple (concurrently) selected dates
// tags:
// protected extension
return !this.dateFuncObj.compare(dateObject, this.value, "date")
},
isDisabledDate: function(/*Date*/ dateObject, /*String?*/ locale){
// summary:
// May be overridden to disable certain dates in the calendar e.g. `isDisabledDate=dojo.date.locale.isWeekend`
// tags:
// extension
/*=====
return false; // Boolean
=====*/
},
getClassForDate: function(/*Date*/ dateObject, /*String?*/ locale){
// summary:
// May be overridden to return CSS classes to associate with the date entry for the given dateObject,
// for example to indicate a holiday in specified locale.
// tags:
// extension
/*=====
return ""; // String
=====*/
}
}
);
}
if(!dojo._hasResource["dijit.Tooltip"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.Tooltip"] = true;
dojo.provide("dijit.Tooltip");
dojo.declare(
"dijit._MasterTooltip",
[dijit._Widget, dijit._Templated],
{
// summary:
// Internal widget that holds the actual tooltip markup,
// which occurs once per page.
// Called by Tooltip widgets which are just containers to hold
// the markup
// tags:
// protected
// duration: Integer
// Milliseconds to fade in/fade out
duration: dijit.defaultDuration,
templateString: dojo.cache("dijit", "templates/Tooltip.html", "\n"),
postCreate: function(){
dojo.body().appendChild(this.domNode);
this.bgIframe = new dijit.BackgroundIframe(this.domNode);
// Setup fade-in and fade-out functions.
this.fadeIn = dojo.fadeIn({ node: this.domNode, duration: this.duration, onEnd: dojo.hitch(this, "_onShow") });
this.fadeOut = dojo.fadeOut({ node: this.domNode, duration: this.duration, onEnd: dojo.hitch(this, "_onHide") });
},
show: function(/*String*/ innerHTML, /*DomNode*/ aroundNode, /*String[]?*/ position, /*Boolean*/ rtl){
// summary:
// Display tooltip w/specified contents to right of specified node
// (To left if there's no space on the right, or if rtl == true)
if(this.aroundNode && this.aroundNode === aroundNode){
return;
}
if(this.fadeOut.status() == "playing"){
// previous tooltip is being hidden; wait until the hide completes then show new one
this._onDeck=arguments;
return;
}
this.containerNode.innerHTML=innerHTML;
var pos = dijit.placeOnScreenAroundElement(this.domNode, aroundNode, dijit.getPopupAroundAlignment((position && position.length) ? position : dijit.Tooltip.defaultPosition, !rtl), dojo.hitch(this, "orient"));
// show it
dojo.style(this.domNode, "opacity", 0);
this.fadeIn.play();
this.isShowingNow = true;
this.aroundNode = aroundNode;
},
orient: function(/* DomNode */ node, /* String */ aroundCorner, /* String */ tooltipCorner){
// summary:
// Private function to set CSS for tooltip node based on which position it's in.
// This is called by the dijit popup code.
// tags:
// protected
node.className = "dijitTooltip " +
{
"BL-TL": "dijitTooltipBelow dijitTooltipABLeft",
"TL-BL": "dijitTooltipAbove dijitTooltipABLeft",
"BR-TR": "dijitTooltipBelow dijitTooltipABRight",
"TR-BR": "dijitTooltipAbove dijitTooltipABRight",
"BR-BL": "dijitTooltipRight",
"BL-BR": "dijitTooltipLeft"
}[aroundCorner + "-" + tooltipCorner];
},
_onShow: function(){
// summary:
// Called at end of fade-in operation
// tags:
// protected
if(dojo.isIE){
// the arrow won't show up on a node w/an opacity filter
this.domNode.style.filter="";
}
},
hide: function(aroundNode){
// summary:
// Hide the tooltip
if(this._onDeck && this._onDeck[1] == aroundNode){
// this hide request is for a show() that hasn't even started yet;
// just cancel the pending show()
this._onDeck=null;
}else if(this.aroundNode === aroundNode){
// this hide request is for the currently displayed tooltip
this.fadeIn.stop();
this.isShowingNow = false;
this.aroundNode = null;
this.fadeOut.play();
}else{
// just ignore the call, it's for a tooltip that has already been erased
}
},
_onHide: function(){
// summary:
// Called at end of fade-out operation
// tags:
// protected
this.domNode.style.cssText=""; // to position offscreen again
this.containerNode.innerHTML="";
if(this._onDeck){
// a show request has been queued up; do it now
this.show.apply(this, this._onDeck);
this._onDeck=null;
}
}
}
);
dijit.showTooltip = function(/*String*/ innerHTML, /*DomNode*/ aroundNode, /*String[]?*/ position, /*Boolean*/ rtl){
// summary:
// Display tooltip w/specified contents in specified position.
// See description of dijit.Tooltip.defaultPosition for details on position parameter.
// If position is not specified then dijit.Tooltip.defaultPosition is used.
if(!dijit._masterTT){ dijit._masterTT = new dijit._MasterTooltip(); }
return dijit._masterTT.show(innerHTML, aroundNode, position, rtl);
};
dijit.hideTooltip = function(aroundNode){
// summary:
// Hide the tooltip
if(!dijit._masterTT){ dijit._masterTT = new dijit._MasterTooltip(); }
return dijit._masterTT.hide(aroundNode);
};
dojo.declare(
"dijit.Tooltip",
dijit._Widget,
{
// summary:
// Pops up a tooltip (a help message) when you hover over a node.
// label: String
// Text to display in the tooltip.
// Specified as innerHTML when creating the widget from markup.
label: "",
// showDelay: Integer
// Number of milliseconds to wait after hovering over/focusing on the object, before
// the tooltip is displayed.
showDelay: 400,
// connectId: [const] String[]
// Id's of domNodes to attach the tooltip to.
// When user hovers over any of the specified dom nodes, the tooltip will appear.
//
// Note: Currently connectId can only be specified on initialization, it cannot
// be changed via attr('connectId', ...)
//
// Note: in 2.0 this will be renamed to connectIds for less confusion.
connectId: [],
// position: String[]
// See description of `dijit.Tooltip.defaultPosition` for details on position parameter.
position: [],
constructor: function(){
// Map id's of nodes I'm connected to to a list of the this.connect() handles
this._nodeConnectionsById = {};
},
_setConnectIdAttr: function(newIds){
for(var oldId in this._nodeConnectionsById){
this.removeTarget(oldId);
}
dojo.forEach(dojo.isArrayLike(newIds) ? newIds : [newIds], this.addTarget, this);
},
_getConnectIdAttr: function(){
var ary = [];
for(var id in this._nodeConnectionsById){
ary.push(id);
}
return ary;
},
addTarget: function(/*DOMNODE || String*/ id){
// summary:
// Attach tooltip to specified node, if it's not already connected
var node = dojo.byId(id);
if(!node){ return; }
if(node.id in this._nodeConnectionsById){ return; }//Already connected
this._nodeConnectionsById[node.id] = [
this.connect(node, "onmouseenter", "_onTargetMouseEnter"),
this.connect(node, "onmouseleave", "_onTargetMouseLeave"),
this.connect(node, "onfocus", "_onTargetFocus"),
this.connect(node, "onblur", "_onTargetBlur")
];
},
removeTarget: function(/*DOMNODE || String*/ node){
// summary:
// Detach tooltip from specified node
// map from DOMNode back to plain id string
var id = node.id || node;
if(id in this._nodeConnectionsById){
dojo.forEach(this._nodeConnectionsById[id], this.disconnect, this);
delete this._nodeConnectionsById[id];
}
},
postCreate: function(){
dojo.addClass(this.domNode,"dijitTooltipData");
},
startup: function(){
this.inherited(arguments);
// If this tooltip was created in a template, or for some other reason the specified connectId[s]
// didn't exist during the widget's initialization, then connect now.
var ids = this.connectId;
dojo.forEach(dojo.isArrayLike(ids) ? ids : [ids], this.addTarget, this);
},
_onTargetMouseEnter: function(/*Event*/ e){
// summary:
// Handler for mouseenter event on the target node
// tags:
// private
this._onHover(e);
},
_onTargetMouseLeave: function(/*Event*/ e){
// summary:
// Handler for mouseleave event on the target node
// tags:
// private
this._onUnHover(e);
},
_onTargetFocus: function(/*Event*/ e){
// summary:
// Handler for focus event on the target node
// tags:
// private
this._focus = true;
this._onHover(e);
},
_onTargetBlur: function(/*Event*/ e){
// summary:
// Handler for blur event on the target node
// tags:
// private
this._focus = false;
this._onUnHover(e);
},
_onHover: function(/*Event*/ e){
// summary:
// Despite the name of this method, it actually handles both hover and focus
// events on the target node, setting a timer to show the tooltip.
// tags:
// private
if(!this._showTimer){
var target = e.target;
this._showTimer = setTimeout(dojo.hitch(this, function(){this.open(target)}), this.showDelay);
}
},
_onUnHover: function(/*Event*/ e){
// summary:
// Despite the name of this method, it actually handles both mouseleave and blur
// events on the target node, hiding the tooltip.
// tags:
// private
// keep a tooltip open if the associated element still has focus (even though the
// mouse moved away)
if(this._focus){ return; }
if(this._showTimer){
clearTimeout(this._showTimer);
delete this._showTimer;
}
this.close();
},
open: function(/*DomNode*/ target){
// summary:
// Display the tooltip; usually not called directly.
// tags:
// private
if(this._showTimer){
clearTimeout(this._showTimer);
delete this._showTimer;
}
dijit.showTooltip(this.label || this.domNode.innerHTML, target, this.position, !this.isLeftToRight());
this._connectNode = target;
this.onShow(target, this.position);
},
close: function(){
// summary:
// Hide the tooltip or cancel timer for show of tooltip
// tags:
// private
if(this._connectNode){
// if tooltip is currently shown
dijit.hideTooltip(this._connectNode);
delete this._connectNode;
this.onHide();
}
if(this._showTimer){
// if tooltip is scheduled to be shown (after a brief delay)
clearTimeout(this._showTimer);
delete this._showTimer;
}
},
onShow: function(target, position){
// summary:
// Called when the tooltip is shown
// tags:
// callback
},
onHide: function(){
// summary:
// Called when the tooltip is hidden
// tags:
// callback
},
uninitialize: function(){
this.close();
this.inherited(arguments);
}
}
);
// dijit.Tooltip.defaultPosition: String[]
// This variable controls the position of tooltips, if the position is not specified to
// the Tooltip widget or *TextBox widget itself. It's an array of strings with the following values:
//
// * before: places tooltip to the left of the target node/widget, or to the right in
// the case of RTL scripts like Hebrew and Arabic
// * after: places tooltip to the right of the target node/widget, or to the left in
// the case of RTL scripts like Hebrew and Arabic
// * above: tooltip goes above target node
// * below: tooltip goes below target node
//
// The list is positions is tried, in order, until a position is found where the tooltip fits
// within the viewport.
//
// Be careful setting this parameter. A value of "above" may work fine until the user scrolls
// the screen so that there's no room above the target node. Nodes with drop downs, like
// DropDownButton or FilteringSelect, are especially problematic, in that you need to be sure
// that the drop down and tooltip don't overlap, even when the viewport is scrolled so that there
// is only room below (or above) the target node, but not both.
dijit.Tooltip.defaultPosition = ["after", "before"];
}
if(!dojo._hasResource["dijit.form.ValidationTextBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.ValidationTextBox"] = true;
dojo.provide("dijit.form.ValidationTextBox");
/*=====
dijit.form.ValidationTextBox.__Constraints = function(){
// locale: String
// locale used for validation, picks up value from this widget's lang attribute
// _flags_: anything
// various flags passed to regExpGen function
this.locale = "";
this._flags_ = "";
}
=====*/
dojo.declare(
"dijit.form.ValidationTextBox",
dijit.form.TextBox,
{
// summary:
// Base class for textbox widgets with the ability to validate content of various types and provide user feedback.
// tags:
// protected
templateString: dojo.cache("dijit.form", "templates/ValidationTextBox.html", "\n"),
baseClass: "dijitTextBox dijitValidationTextBox",
// required: Boolean
// User is required to enter data into this field.
required: false,
// promptMessage: String
// If defined, display this hint string immediately on focus to the textbox, if empty.
// Think of this like a tooltip that tells the user what to do, not an error message
// that tells the user what they've done wrong.
//
// Message disappears when user starts typing.
promptMessage: "",
// invalidMessage: String
// The message to display if value is invalid.
// The translated string value is read from the message file by default.
// Set to "" to use the promptMessage instead.
invalidMessage: "$_unset_$",
// missingMessage: String
// The message to display if value is empty and the field is required.
// The translated string value is read from the message file by default.
// Set to "" to use the invalidMessage instead.
missingMessage: "$_unset_$",
// constraints: dijit.form.ValidationTextBox.__Constraints
// user-defined object needed to pass parameters to the validator functions
constraints: {},
// regExp: [extension protected] String
// regular expression string used to validate the input
// Do not specify both regExp and regExpGen
regExp: ".*",
regExpGen: function(/*dijit.form.ValidationTextBox.__Constraints*/constraints){
// summary:
// Overridable function used to generate regExp when dependent on constraints.
// Do not specify both regExp and regExpGen.
// tags:
// extension protected
return this.regExp; // String
},
// state: [readonly] String
// Shows current state (ie, validation result) of input (Normal, Warning, or Error)
state: "",
// tooltipPosition: String[]
// See description of `dijit.Tooltip.defaultPosition` for details on this parameter.
tooltipPosition: [],
_setValueAttr: function(){
// summary:
// Hook so attr('value', ...) works.
this.inherited(arguments);
this.validate(this._focused);
},
validator: function(/*anything*/value, /*dijit.form.ValidationTextBox.__Constraints*/constraints){
// summary:
// Overridable function used to validate the text input against the regular expression.
// tags:
// protected
return (new RegExp("^(?:" + this.regExpGen(constraints) + ")"+(this.required?"":"?")+"$")).test(value) &&
(!this.required || !this._isEmpty(value)) &&
(this._isEmpty(value) || this.parse(value, constraints) !== undefined); // Boolean
},
_isValidSubset: function(){
// summary:
// Returns true if the value is either already valid or could be made valid by appending characters.
// This is used for validation while the user [may be] still typing.
return this.textbox.value.search(this._partialre) == 0;
},
isValid: function(/*Boolean*/ isFocused){
// summary:
// Tests if value is valid.
// Can override with your own routine in a subclass.
// tags:
// protected
return this.validator(this.textbox.value, this.constraints);
},
_isEmpty: function(value){
// summary:
// Checks for whitespace
return /^\s*$/.test(value); // Boolean
},
getErrorMessage: function(/*Boolean*/ isFocused){
// summary:
// Return an error message to show if appropriate
// tags:
// protected
return (this.required && this._isEmpty(this.textbox.value)) ? this.missingMessage : this.invalidMessage; // String
},
getPromptMessage: function(/*Boolean*/ isFocused){
// summary:
// Return a hint message to show when widget is first focused
// tags:
// protected
return this.promptMessage; // String
},
_maskValidSubsetError: true,
validate: function(/*Boolean*/ isFocused){
// summary:
// Called by oninit, onblur, and onkeypress.
// description:
// Show missing or invalid messages if appropriate, and highlight textbox field.
// tags:
// protected
var message = "";
var isValid = this.disabled || this.isValid(isFocused);
if(isValid){ this._maskValidSubsetError = true; }
var isEmpty = this._isEmpty(this.textbox.value);
var isValidSubset = !isValid && !isEmpty && isFocused && this._isValidSubset();
this.state = ((isValid || ((!this._hasBeenBlurred || isFocused) && isEmpty) || isValidSubset) && this._maskValidSubsetError) ? "" : "Error";
if(this.state == "Error"){ this._maskValidSubsetError = isFocused; } // we want the error to show up afer a blur and refocus
this._setStateClass();
dijit.setWaiState(this.focusNode, "invalid", isValid ? "false" : "true");
if(isFocused){
if(this.state == "Error"){
message = this.getErrorMessage(true);
}else{
message = this.getPromptMessage(true); // show the prompt whever there's no error
}
this._maskValidSubsetError = true; // since we're focused, always mask warnings
}
this.displayMessage(message);
return isValid;
},
// _message: String
// Currently displayed message
_message: "",
displayMessage: function(/*String*/ message){
// summary:
// Overridable method to display validation errors/hints.
// By default uses a tooltip.
// tags:
// extension
if(this._message == message){ return; }
this._message = message;
dijit.hideTooltip(this.domNode);
if(message){
dijit.showTooltip(message, this.domNode, this.tooltipPosition, !this.isLeftToRight());
}
},
_refreshState: function(){
// Overrides TextBox._refreshState()
this.validate(this._focused);
this.inherited(arguments);
},
//////////// INITIALIZATION METHODS ///////////////////////////////////////
constructor: function(){
this.constraints = {};
},
_setConstraintsAttr: function(/* Object */ constraints){
if(!constraints.locale && this.lang){
constraints.locale = this.lang;
}
this.constraints = constraints;
this._computePartialRE();
},
_computePartialRE: function(){
var p = this.regExpGen(this.constraints);
this.regExp = p;
var partialre = "";
// parse the regexp and produce a new regexp that matches valid subsets
// if the regexp is .* then there's no use in matching subsets since everything is valid
if(p != ".*"){ this.regExp.replace(/\\.|\[\]|\[.*?[^\\]{1}\]|\{.*?\}|\(\?[=:!]|./g,
function (re){
switch(re.charAt(0)){
case '{':
case '+':
case '?':
case '*':
case '^':
case '$':
case '|':
case '(':
partialre += re;
break;
case ")":
partialre += "|$)";
break;
default:
partialre += "(?:"+re+"|$)";
break;
}
}
);}
try{ // this is needed for now since the above regexp parsing needs more test verification
"".search(partialre);
}catch(e){ // should never be here unless the original RE is bad or the parsing is bad
partialre = this.regExp;
console.warn('RegExp error in ' + this.declaredClass + ': ' + this.regExp);
} // should never be here unless the original RE is bad or the parsing is bad
this._partialre = "^(?:" + partialre + ")$";
},
postMixInProperties: function(){
this.inherited(arguments);
this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
if(this.invalidMessage == "$_unset_$"){ this.invalidMessage = this.messages.invalidMessage; }
if(!this.invalidMessage){ this.invalidMessage = this.promptMessage; }
if(this.missingMessage == "$_unset_$"){ this.missingMessage = this.messages.missingMessage; }
if(!this.missingMessage){ this.missingMessage = this.invalidMessage; }
this._setConstraintsAttr(this.constraints); // this needs to happen now (and later) due to codependency on _set*Attr calls attachPoints
},
_setDisabledAttr: function(/*Boolean*/ value){
this.inherited(arguments); // call FormValueWidget._setDisabledAttr()
this._refreshState();
},
_setRequiredAttr: function(/*Boolean*/ value){
this.required = value;
dijit.setWaiState(this.focusNode, "required", value);
this._refreshState();
},
reset:function(){
// Overrides dijit.form.TextBox.reset() by also
// hiding errors about partial matches
this._maskValidSubsetError = true;
this.inherited(arguments);
},
_onBlur: function(){
this.displayMessage('');
this.inherited(arguments);
}
}
);
dojo.declare(
"dijit.form.MappedTextBox",
dijit.form.ValidationTextBox,
{
// summary:
// A dijit.form.ValidationTextBox subclass which provides a base class for widgets that have
// a visible formatted display value, and a serializable
// value in a hidden input field which is actually sent to the server.
// description:
// The visible display may
// be locale-dependent and interactive. The value sent to the server is stored in a hidden
// input field which uses the `name` attribute declared by the original widget. That value sent
// to the server is defined by the dijit.form.MappedTextBox.serialize method and is typically
// locale-neutral.
// tags:
// protected
postMixInProperties: function(){
this.inherited(arguments);
// we want the name attribute to go to the hidden , not the displayed ,
// so override _FormWidget.postMixInProperties() setting of nameAttrSetting
this.nameAttrSetting = "";
},
serialize: function(/*anything*/val, /*Object?*/options){
// summary:
// Overridable function used to convert the attr('value') result to a canonical
// (non-localized) string. For example, will print dates in ISO format, and
// numbers the same way as they are represented in javascript.
// tags:
// protected extension
return val.toString ? val.toString() : ""; // String
},
toString: function(){
// summary:
// Returns widget as a printable string using the widget's value
// tags:
// protected
var val = this.filter(this.get('value')); // call filter in case value is nonstring and filter has been customized
return val != null ? (typeof val == "string" ? val : this.serialize(val, this.constraints)) : ""; // String
},
validate: function(){
// Overrides `dijit.form.TextBox.validate`
this.valueNode.value = this.toString();
return this.inherited(arguments);
},
buildRendering: function(){
// Overrides `dijit._Templated.buildRendering`
this.inherited(arguments);
// Create a hidden node with the serialized value used for submit
// (as opposed to the displayed value).
// Passing in name as markup rather than calling dojo.create() with an attrs argument
// to make dojo.query(input[name=...]) work on IE. (see #8660)
this.valueNode = dojo.place(" ", this.textbox, "after");
},
reset:function(){
// Overrides `dijit.form.ValidationTextBox.reset` to
// reset the hidden textbox value to ''
this.valueNode.value = '';
this.inherited(arguments);
}
}
);
/*=====
dijit.form.RangeBoundTextBox.__Constraints = function(){
// min: Number
// Minimum signed value. Default is -Infinity
// max: Number
// Maximum signed value. Default is +Infinity
this.min = min;
this.max = max;
}
=====*/
dojo.declare(
"dijit.form.RangeBoundTextBox",
dijit.form.MappedTextBox,
{
// summary:
// Base class for textbox form widgets which defines a range of valid values.
// rangeMessage: String
// The message to display if value is out-of-range
rangeMessage: "",
/*=====
// constraints: dijit.form.RangeBoundTextBox.__Constraints
constraints: {},
======*/
rangeCheck: function(/*Number*/ primitive, /*dijit.form.RangeBoundTextBox.__Constraints*/ constraints){
// summary:
// Overridable function used to validate the range of the numeric input value.
// tags:
// protected
return ("min" in constraints? (this.compare(primitive,constraints.min) >= 0) : true) &&
("max" in constraints? (this.compare(primitive,constraints.max) <= 0) : true); // Boolean
},
isInRange: function(/*Boolean*/ isFocused){
// summary:
// Tests if the value is in the min/max range specified in constraints
// tags:
// protected
return this.rangeCheck(this.get('value'), this.constraints);
},
_isDefinitelyOutOfRange: function(){
// summary:
// Returns true if the value is out of range and will remain
// out of range even if the user types more characters
var val = this.get('value');
var isTooLittle = false;
var isTooMuch = false;
if("min" in this.constraints){
var min = this.constraints.min;
min = this.compare(val, ((typeof min == "number") && min >= 0 && val !=0) ? 0 : min);
isTooLittle = (typeof min == "number") && min < 0;
}
if("max" in this.constraints){
var max = this.constraints.max;
max = this.compare(val, ((typeof max != "number") || max > 0) ? max : 0);
isTooMuch = (typeof max == "number") && max > 0;
}
return isTooLittle || isTooMuch;
},
_isValidSubset: function(){
// summary:
// Overrides `dijit.form.ValidationTextBox._isValidSubset`.
// Returns true if the input is syntactically valid, and either within
// range or could be made in range by more typing.
return this.inherited(arguments) && !this._isDefinitelyOutOfRange();
},
isValid: function(/*Boolean*/ isFocused){
// Overrides dijit.form.ValidationTextBox.isValid to check that the value is also in range.
return this.inherited(arguments) &&
((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
},
getErrorMessage: function(/*Boolean*/ isFocused){
// Overrides dijit.form.ValidationTextBox.getErrorMessage to print "out of range" message if appropriate
var v = this.get('value');
if(v !== null && v !== '' && v !== undefined && (typeof v != "number" || !isNaN(v)) && !this.isInRange(isFocused)){ // don't check isInRange w/o a real value
return this.rangeMessage; // String
}
return this.inherited(arguments);
},
postMixInProperties: function(){
this.inherited(arguments);
if(!this.rangeMessage){
this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
this.rangeMessage = this.messages.rangeMessage;
}
},
_setConstraintsAttr: function(/* Object */ constraints){
this.inherited(arguments);
if(this.focusNode){ // not set when called from postMixInProperties
if(this.constraints.min !== undefined){
dijit.setWaiState(this.focusNode, "valuemin", this.constraints.min);
}else{
dijit.removeWaiState(this.focusNode, "valuemin");
}
if(this.constraints.max !== undefined){
dijit.setWaiState(this.focusNode, "valuemax", this.constraints.max);
}else{
dijit.removeWaiState(this.focusNode, "valuemax");
}
}
},
_setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange){
// summary:
// Hook so attr('value', ...) works.
dijit.setWaiState(this.focusNode, "valuenow", value);
this.inherited(arguments);
}
}
);
}
if(!dojo._hasResource["dijit.form._DateTimeTextBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form._DateTimeTextBox"] = true;
dojo.provide("dijit.form._DateTimeTextBox");
new Date("X"); // workaround for #11279, new Date("") == NaN
/*=====
dojo.declare(
"dijit.form._DateTimeTextBox.__Constraints",
[dijit.form.RangeBoundTextBox.__Constraints, dojo.date.locale.__FormatOptions], {
// summary:
// Specifies both the rules on valid/invalid values (first/last date/time allowed),
// and also formatting options for how the date/time is displayed.
// example:
// To restrict to dates within 2004, displayed in a long format like "December 25, 2005":
// | {min:'2004-01-01',max:'2004-12-31', formatLength:'long'}
});
=====*/
dojo.declare(
"dijit.form._DateTimeTextBox",
dijit.form.RangeBoundTextBox,
{
// summary:
// Base class for validating, serializable, range-bound date or time text box.
// constraints: dijit.form._DateTimeTextBox.__Constraints
// Despite the name, this parameter specifies both constraints on the input
// (including starting/ending dates/times allowed) as well as
// formatting options like whether the date is displayed in long (ex: December 25, 2005)
// or short (ex: 12/25/2005) format. See `dijit.form._DateTimeTextBox.__Constraints` for details.
/*=====
constraints: {},
======*/
// Override ValidationTextBox.regExpGen().... we use a reg-ex generating function rather
// than a straight regexp to deal with locale (plus formatting options too?)
regExpGen: dojo.date.locale.regexp,
// datePackage: String
// JavaScript namespace to find calendar routines. Uses Gregorian calendar routines
// at dojo.date, by default.
datePackage: "dojo.date",
// Override _FormWidget.compare() to work for dates/times
compare: dojo.date.compare,
format: function(/*Date*/ value, /*dojo.date.locale.__FormatOptions*/ constraints){
// summary:
// Formats the value as a Date, according to specified locale (second argument)
// tags:
// protected
if(!value){ return ''; }
return this.dateLocaleModule.format(value, constraints);
},
parse: function(/*String*/ value, /*dojo.date.locale.__FormatOptions*/ constraints){
// summary:
// Parses as string as a Date, according to constraints
// tags:
// protected
return this.dateLocaleModule.parse(value, constraints) || (this._isEmpty(value) ? null : undefined); // Date
},
// Overrides ValidationTextBox.serialize() to serialize a date in canonical ISO format.
serialize: function(/*anything*/val, /*Object?*/options){
if(val.toGregorian){
val = val.toGregorian();
}
return dojo.date.stamp.toISOString(val, options);
},
// value: Date
// The value of this widget as a JavaScript Date object. Use get("value") / set("value", val) to manipulate.
// When passed to the parser in markup, must be specified according to `dojo.date.stamp.fromISOString`
value: new Date(""), // value.toString()="NaN"
_blankValue: null, // used by filter() when the textbox is blank
// popupClass: [protected extension] String
// Name of the popup widget class used to select a date/time.
// Subclasses should specify this.
popupClass: "", // default is no popup = text only
// _selector: [protected extension] String
// Specifies constraints.selector passed to dojo.date functions, should be either
// "date" or "time".
// Subclass must specify this.
_selector: "",
constructor: function(/*Object*/args){
var dateClass = args.datePackage ? args.datePackage + ".Date" : "Date";
this.dateClassObj = dojo.getObject(dateClass, false);
this.value = new this.dateClassObj("");
this.datePackage = args.datePackage || this.datePackage;
this.dateLocaleModule = dojo.getObject(this.datePackage + ".locale", false);
this.regExpGen = this.dateLocaleModule.regexp;
},
_setConstraintsAttr: function(/* Object */ constraints){
constraints.selector = this._selector;
constraints.fullYear = true; // see #5465 - always format with 4-digit years
var fromISO = dojo.date.stamp.fromISOString;
if(typeof constraints.min == "string"){ constraints.min = fromISO(constraints.min); }
if(typeof constraints.max == "string"){ constraints.max = fromISO(constraints.max); }
this.inherited(arguments, [constraints]);
},
_onFocus: function(/*Event*/ evt){
// summary:
// open the popup
this._open();
this.inherited(arguments);
},
_setValueAttr: function(/*Date*/ value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
// summary:
// Sets the date on this textbox. Note that `value` must be like a Javascript Date object.
if(value !== undefined){
if(!value || value.toString() == dijit.form._DateTimeTextBox.prototype.value.toString()){
value = null;
}
if(value instanceof Date && !(this.dateClassObj instanceof Date)){
value = new this.dateClassObj(value);
}
}
this.inherited(arguments, [value, priorityChange, formattedValue]);
if(this._picker){
// #3948: fix blank date on popup only
if(!value){value = new this.dateClassObj();}
this._picker.set('value', value);
}
},
_open: function(){
// summary:
// opens the TimePicker, and sets the onValueSelected value
if(this.disabled || this.readOnly || !this.popupClass){return;}
var textBox = this;
if(!this._picker){
var PopupProto = dojo.getObject(this.popupClass, false);
this._picker = new PopupProto({
onValueSelected: function(value){
if(textBox._tabbingAway){
delete textBox._tabbingAway;
}else{
textBox.focus(); // focus the textbox before the popup closes to avoid reopening the popup
}
setTimeout(dojo.hitch(textBox, "_close"), 1); // allow focus time to take
// this will cause InlineEditBox and other handlers to do stuff so make sure it's last
dijit.form._DateTimeTextBox.superclass._setValueAttr.call(textBox, value, true);
},
id: this.id + "_popup",
dir: textBox.dir,
lang: textBox.lang,
value: this.get('value') || new this.dateClassObj(),
constraints: textBox.constraints,
datePackage: textBox.datePackage,
isDisabledDate: function(/*Date*/ date){
// summary:
// disables dates outside of the min/max of the _DateTimeTextBox
var compare = dojo.date.compare;
var constraints = textBox.constraints;
return constraints && (
(constraints.min && compare(constraints.min, date, textBox._selector) > 0) ||
(constraints.max && compare(constraints.max, date, textBox._selector) < 0)
);
}
});
}
if(!this._opened){
// Open drop down. Align left sides of input box and drop down, even in RTL mode,
// otherwise positioning thrown off when the drop down width is changed in marginBox call below (#10676)
dijit.popup.open({
parent: this,
popup: this._picker,
orient: {'BL':'TL', 'TL':'BL'},
around: this.domNode,
onCancel: dojo.hitch(this, this._close),
onClose: function(){ textBox._opened=false; }
});
this._opened=true;
}
dojo.marginBox(this._picker.domNode,{ w:this.domNode.offsetWidth });
},
_close: function(){
if(this._opened){
dijit.popup.close(this._picker);
this._opened=false;
}
},
_onBlur: function(){
// summary:
// Called magically when focus has shifted away from this widget and it's dropdown
this._close();
if(this._picker){
// teardown so that constraints will be rebuilt next time (redundant reference: #6002)
this._picker.destroy();
delete this._picker;
}
this.inherited(arguments);
// don't focus on . the user has explicitly focused on something else.
},
_getDisplayedValueAttr: function(){
return this.textbox.value;
},
_setDisplayedValueAttr: function(/*String*/ value, /*Boolean?*/ priorityChange){
this._setValueAttr(this.parse(value, this.constraints), priorityChange, value);
},
destroy: function(){
if(this._picker){
this._picker.destroy();
delete this._picker;
}
this.inherited(arguments);
},
postCreate: function(){
this.inherited(arguments);
this.connect(this.focusNode, 'onkeypress', this._onKeyPress);
this.connect(this.focusNode, 'onclick', this._open);
},
_onKeyPress: function(/*Event*/ e){
// summary:
// Handler for keypress events
var p = this._picker, dk = dojo.keys;
// Handle the key in the picker, if it has a handler. If the handler
// returns false, then don't handle any other keys.
if(p && this._opened && p.handleKey){
if(p.handleKey(e) === false){ return; }
}
if(this._opened && e.charOrCode == dk.ESCAPE && !(e.shiftKey || e.ctrlKey || e.altKey || e.metaKey)){
this._close();
dojo.stopEvent(e);
}else if(!this._opened && e.charOrCode == dk.DOWN_ARROW){
this._open();
dojo.stopEvent(e);
}else if(e.charOrCode === dk.TAB){
this._tabbingAway = true;
}else if(this._opened && (e.keyChar || e.charOrCode === dk.BACKSPACE || e.charOrCode == dk.DELETE)){
// Replace the element - but do it after a delay to allow for
// filtering to occur
setTimeout(dojo.hitch(this, function(){
if(this._picker && this._opened){
dijit.placeOnScreenAroundElement(p.domNode.parentNode, this.domNode, {'BL':'TL', 'TL':'BL'}, p.orient ? dojo.hitch(p, "orient") : null);
}
}), 1);
}
}
}
);
}
if(!dojo._hasResource["dijit.form.DateTextBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.DateTextBox"] = true;
dojo.provide("dijit.form.DateTextBox");
dojo.declare(
"dijit.form.DateTextBox",
dijit.form._DateTimeTextBox,
{
// summary:
// A validating, serializable, range-bound date text box with a drop down calendar
//
// Example:
// | new dijit.form.DateTextBox({value: new Date(2009, 0, 20)})
//
// Example:
// |
baseClass: "dijitTextBox dijitDateTextBox",
popupClass: "dijit.Calendar",
_selector: "date",
// value: Date
// The value of this widget as a JavaScript Date object, with only year/month/day specified.
// If specified in markup, use the format specified in `dojo.date.stamp.fromISOString`
value: new Date("") // value.toString()="NaN"
}
);
}
if(!dojo._hasResource["dijit._TimePicker"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit._TimePicker"] = true;
dojo.provide("dijit._TimePicker");
/*=====
dojo.declare(
"dijit._TimePicker.__Constraints",
dojo.date.locale.__FormatOptions,
{
// clickableIncrement: String
// See `dijit._TimePicker.clickableIncrement`
clickableIncrement: "T00:15:00",
// visibleIncrement: String
// See `dijit._TimePicker.visibleIncrement`
visibleIncrement: "T01:00:00",
// visibleRange: String
// See `dijit._TimePicker.visibleRange`
visibleRange: "T05:00:00"
}
);
=====*/
dojo.declare("dijit._TimePicker",
[dijit._Widget, dijit._Templated],
{
// summary:
// A graphical time picker.
// This widget is used internally by other widgets and is not available
// as a standalone widget due to lack of accessibility support.
templateString: dojo.cache("dijit", "templates/TimePicker.html", "\n"),
// baseClass: [protected] String
// The root className to use for the various states of this widget
baseClass: "dijitTimePicker",
// clickableIncrement: String
// ISO-8601 string representing the amount by which
// every clickable element in the time picker increases.
// Set in local time, without a time zone.
// Example: `T00:15:00` creates 15 minute increments
// Must divide dijit._TimePicker.visibleIncrement evenly
clickableIncrement: "T00:15:00",
// visibleIncrement: String
// ISO-8601 string representing the amount by which
// every element with a visible time in the time picker increases.
// Set in local time, without a time zone.
// Example: `T01:00:00` creates text in every 1 hour increment
visibleIncrement: "T01:00:00",
// visibleRange: String
// ISO-8601 string representing the range of this TimePicker.
// The TimePicker will only display times in this range.
// Example: `T05:00:00` displays 5 hours of options
visibleRange: "T05:00:00",
// value: String
// Date to display.
// Defaults to current time and date.
// Can be a Date object or an ISO-8601 string.
// If you specify the GMT time zone (`-01:00`),
// the time will be converted to the local time in the local time zone.
// Otherwise, the time is considered to be in the local time zone.
// If you specify the date and isDate is true, the date is used.
// Example: if your local time zone is `GMT -05:00`,
// `T10:00:00` becomes `T10:00:00-05:00` (considered to be local time),
// `T10:00:00-01:00` becomes `T06:00:00-05:00` (4 hour difference),
// `T10:00:00Z` becomes `T05:00:00-05:00` (5 hour difference between Zulu and local time)
// `yyyy-mm-ddThh:mm:ss` is the format to set the date and time
// Example: `2007-06-01T09:00:00`
value: new Date(),
_visibleIncrement:2,
_clickableIncrement:1,
_totalIncrements:10,
// constraints: dijit._TimePicker.__Constraints
// Specifies valid range of times (start time, end time)
constraints:{},
/*=====
serialize: function(val, options){
// summary:
// User overridable function used to convert the attr('value') result to a String
// val: Date
// The current value
// options: Object?
// tags:
// protected
},
=====*/
serialize: dojo.date.stamp.toISOString,
// _filterString: string
// The string to filter by
_filterString: "",
setValue: function(/*Date*/ value){
// summary:
// Deprecated. Used attr('value') instead.
// tags:
// deprecated
dojo.deprecated("dijit._TimePicker:setValue() is deprecated. Use set('value', ...) instead.", "", "2.0");
this.set('value', value);
},
_setValueAttr: function(/*Date*/ date){
// summary:
// Hook so attr('value', ...) works.
// description:
// Set the value of the TimePicker.
// Redraws the TimePicker around the new date.
// tags:
// protected
this.value = date;
this._showText();
},
onOpen: function(best){
// summary:
// This is called by the popup manager when a TimeTextBox is displayed on the screen
// best:
// Whether it is being displayed above or below the `dijit.form.TimeTextBox`
// tags:
// protected
if(this._beenOpened && this.domNode.parentNode){
// We've been opened before - so set our filter to to the
// currently-displayed value (or empty string if it's already
// valid)
var p = dijit.byId(this.domNode.parentNode.dijitPopupParent);
if(p){
var val = p.get('displayedValue');
if(val && !p.parse(val, p.constraints)){
this._filterString = val;
}else{
this._filterString = "";
}
this._showText();
}
}
this._beenOpened = true;
},
isDisabledDate: function(/*Date*/ dateObject, /*String?*/ locale){
// summary:
// May be overridden to disable certain dates in the TimePicker e.g. `isDisabledDate=dojo.date.locale.isWeekend`
// type:
// extension
return false; // Boolean
},
_getFilteredNodes: function(/*number*/ start, /*number*/ maxNum, /*Boolean*/ before){
// summary:
// Returns an array of nodes with the filter applied. At most maxNum nodes
// will be returned - but fewer may be returned as well. If the
// before parameter is set to true, then it will return the elements
// before the given index
// tags:
// private
var nodes = [], n, i = start, max = this._maxIncrement + Math.abs(i),
chk = before?-1:1, dec = before?1:0, inc = before?0:1;
do{
i = i - dec;
n = this._createOption(i);
if(n){nodes.push(n);}
i = i + inc;
}while(nodes.length < maxNum && (i*chk) < max);
if(before){ nodes.reverse(); }
return nodes;
},
_showText: function(){
// summary:
// Displays the relevant choices in the drop down list
// tags:
// private
this.timeMenu.innerHTML = "";
var fromIso = dojo.date.stamp.fromISOString;
this._clickableIncrementDate=fromIso(this.clickableIncrement);
this._visibleIncrementDate=fromIso(this.visibleIncrement);
this._visibleRangeDate=fromIso(this.visibleRange);
// get the value of the increments and the range in seconds (since 00:00:00) to find out how many divs to create
var sinceMidnight = function(/*Date*/ date){
return date.getHours() * 60 * 60 + date.getMinutes() * 60 + date.getSeconds();
};
var clickableIncrementSeconds = sinceMidnight(this._clickableIncrementDate);
var visibleIncrementSeconds = sinceMidnight(this._visibleIncrementDate);
var visibleRangeSeconds = sinceMidnight(this._visibleRangeDate);
// round reference date to previous visible increment
var time = this.value.getTime();
this._refDate = new Date(time - time % (visibleIncrementSeconds*1000));
this._refDate.setFullYear(1970,0,1); // match parse defaults
// assume clickable increment is the smallest unit
this._clickableIncrement = 1;
// divide the visible range by the clickable increment to get the number of divs to create
// example: 10:00:00/00:15:00 -> display 40 divs
this._totalIncrements = visibleRangeSeconds / clickableIncrementSeconds;
// divide the visible increments by the clickable increments to get how often to display the time inline
// example: 01:00:00/00:15:00 -> display the time every 4 divs
this._visibleIncrement = visibleIncrementSeconds / clickableIncrementSeconds;
// divide the number of seconds in a day by the clickable increment in seconds to get the
// absolute max number of increments.
this._maxIncrement = (60 * 60 * 24) / clickableIncrementSeconds;
// find the nodes we should display based on our filter
var before = this._getFilteredNodes(0, this._totalIncrements >> 1, true);
var after = this._getFilteredNodes(0, this._totalIncrements >> 1, false);
if(before.length < this._totalIncrements >> 1){
before = before.slice(before.length / 2);
after = after.slice(0, after.length / 2);
}
dojo.forEach(before.concat(after), function(n){this.timeMenu.appendChild(n);}, this);
// TODO:
// I commented this out because it
// causes problems for a TimeTextBox in a Dialog, or as the editor of an InlineEditBox,
// because the timeMenu node isn't visible yet. -- Bill (Bug #????)
// dijit.focus(this.timeMenu);
},
postCreate: function(){
// instantiate constraints
if(this.constraints === dijit._TimePicker.prototype.constraints){
this.constraints={};
}
// brings in visibleRange, increments, etc.
dojo.mixin(this, this.constraints);
// dojo.date.locale needs the lang in the constraints as locale
if(!this.constraints.locale){
this.constraints.locale=this.lang;
}
// assign typematic mouse listeners to the arrow buttons
this.connect(this.timeMenu, dojo.isIE ? "onmousewheel" : 'DOMMouseScroll', "_mouseWheeled");
var _this = this;
var typematic = function(){
_this._connects.push(
dijit.typematic.addMouseListener.apply(null, arguments)
);
};
typematic(this.upArrow,this,this._onArrowUp, 1.0, 50);
typematic(this.downArrow,this,this._onArrowDown, 1.0, 50);
// Connect some callback functions to the hover event of the arrows
var triggerFx = function(cb){
return function(cnt){
// don't run on the first firing
if(cnt > 0){cb.call(this, arguments);}
};
};
var hoverFx = function(node, cb){
return function(e){
dojo.stopEvent(e);
dijit.typematic.trigger(e, this, node, triggerFx(cb), node, 1.0, 50);
};
};
this.connect(this.upArrow, "onmouseover", hoverFx(this.upArrow, this._onArrowUp));
this.connect(this.downArrow, "onmouseover", hoverFx(this.downArrow, this._onArrowDown));
this.inherited(arguments);
},
_buttonMouse: function(/*Event*/ e){
// summary:
// Handler for hover (and unhover) on up/down arrows
// tags:
// private
// in non-IE browser the "mouseenter" event will become "mouseover",
// but in IE it's still "mouseenter"
dojo.toggleClass(e.currentTarget, e.currentTarget == this.upArrow ? "dijitUpArrowHover" : "dijitDownArrowHover",
e.type == "mouseenter" || e.type == "mouseover");
},
_createOption: function(/*Number*/ index){
// summary:
// Creates a clickable time option
// tags:
// private
var date = new Date(this._refDate);
var incrementDate = this._clickableIncrementDate;
date.setHours(date.getHours() + incrementDate.getHours() * index,
date.getMinutes() + incrementDate.getMinutes() * index,
date.getSeconds() + incrementDate.getSeconds() * index);
if(this.constraints.selector == "time"){
date.setFullYear(1970,0,1); // make sure each time is for the same date
}
var dateString = dojo.date.locale.format(date, this.constraints);
if(this._filterString && dateString.toLowerCase().indexOf(this._filterString) !== 0){
// Doesn't match the filter - return null
return null;
}
var div = dojo.create("div", {"class": this.baseClass+"Item"});
div.date = date;
div.index = index;
dojo.create('div',{
"class": this.baseClass + "ItemInner",
innerHTML: dateString
}, div);
if(index%this._visibleIncrement<1 && index%this._visibleIncrement>-1){
dojo.addClass(div, this.baseClass+"Marker");
}else if(!(index%this._clickableIncrement)){
dojo.addClass(div, this.baseClass+"Tick");
}
if(this.isDisabledDate(date)){
// set disabled
dojo.addClass(div, this.baseClass+"ItemDisabled");
}
if(!dojo.date.compare(this.value, date, this.constraints.selector)){
div.selected = true;
dojo.addClass(div, this.baseClass+"ItemSelected");
if(dojo.hasClass(div, this.baseClass+"Marker")){
dojo.addClass(div, this.baseClass+"MarkerSelected");
}else{
dojo.addClass(div, this.baseClass+"TickSelected");
}
}
return div;
},
_onOptionSelected: function(/*Object*/ tgt){
// summary:
// Called when user clicks an option in the drop down list
// tags:
// private
var tdate = tgt.target.date || tgt.target.parentNode.date;
if(!tdate || this.isDisabledDate(tdate)){ return; }
this._highlighted_option = null;
this.set('value', tdate);
this.onValueSelected(tdate);
},
onValueSelected: function(/*Date*/ time){
// summary:
// Notification that a time was selected. It may be the same as the previous value.
// description:
// Used by `dijit.form._DateTimeTextBox` (and thus `dijit.form.TimeTextBox`)
// to get notification when the user has clicked a time.
// tags:
// protected
},
_highlightOption: function(/*node*/ node, /*Boolean*/ highlight){
// summary:
// Turns on/off hover effect on a node based on mouse out/over event
// tags:
// private
if(!node){return;}
if(highlight){
if(this._highlighted_option){
this._highlightOption(this._highlighted_option, false);
}
this._highlighted_option = node;
}else if(this._highlighted_option !== node){
return;
}else{
this._highlighted_option = null;
}
dojo.toggleClass(node, this.baseClass+"ItemHover", highlight);
if(dojo.hasClass(node, this.baseClass+"Marker")){
dojo.toggleClass(node, this.baseClass+"MarkerHover", highlight);
}else{
dojo.toggleClass(node, this.baseClass+"TickHover", highlight);
}
},
onmouseover: function(/*Event*/ e){
// summary:
// Handler for onmouseover event
// tags:
// private
this._keyboardSelected = null;
var tgr = (e.target.parentNode === this.timeMenu) ? e.target : e.target.parentNode;
// if we aren't targeting an item, then we return
if(!dojo.hasClass(tgr, this.baseClass+"Item")){return;}
this._highlightOption(tgr, true);
},
onmouseout: function(/*Event*/ e){
// summary:
// Handler for onmouseout event
// tags:
// private
this._keyboardSelected = null;
var tgr = (e.target.parentNode === this.timeMenu) ? e.target : e.target.parentNode;
this._highlightOption(tgr, false);
},
_mouseWheeled: function(/*Event*/ e){
// summary:
// Handle the mouse wheel events
// tags:
// private
this._keyboardSelected = null;
dojo.stopEvent(e);
// we're not _measuring_ the scroll amount, just direction
var scrollAmount = (dojo.isIE ? e.wheelDelta : -e.detail);
this[(scrollAmount>0 ? "_onArrowUp" : "_onArrowDown")](); // yes, we're making a new dom node every time you mousewheel, or click
},
_onArrowUp: function(count){
// summary:
// Handler for up arrow key.
// description:
// Removes the bottom time and add one to the top
// tags:
// private
if(typeof count == "number" && count == -1){ return; } // typematic end
if(!this.timeMenu.childNodes.length){ return; }
var index = this.timeMenu.childNodes[0].index;
var divs = this._getFilteredNodes(index, 1, true);
if(divs.length){
this.timeMenu.removeChild(this.timeMenu.childNodes[this.timeMenu.childNodes.length - 1]);
this.timeMenu.insertBefore(divs[0], this.timeMenu.childNodes[0]);
}
},
_onArrowDown: function(count){
// summary:
// Handler for up arrow key.
// description:
// Remove the top time and add one to the bottom
// tags:
// private
if(typeof count == "number" && count == -1){ return; } // typematic end
if(!this.timeMenu.childNodes.length){ return; }
var index = this.timeMenu.childNodes[this.timeMenu.childNodes.length - 1].index + 1;
var divs = this._getFilteredNodes(index, 1, false);
if(divs.length){
this.timeMenu.removeChild(this.timeMenu.childNodes[0]);
this.timeMenu.appendChild(divs[0]);
}
},
handleKey: function(/*Event*/ e){
// summary:
// Called from `dijit.form._DateTimeTextBox` to pass a keypress event
// from the `dijit.form.TimeTextBox` to be handled in this widget
// tags:
// protected
var dk = dojo.keys;
if(e.keyChar || e.charOrCode === dk.BACKSPACE || e.charOrCode == dk.DELETE){
// Set a timeout to kick off our filter
setTimeout(dojo.hitch(this, function(){
this._filterString = e.target.value.toLowerCase();
this._showText();
}),1);
}else if(e.charOrCode == dk.DOWN_ARROW || e.charOrCode == dk.UP_ARROW){
dojo.stopEvent(e);
// Figure out which option to highlight now and then highlight it
if(this._highlighted_option && !this._highlighted_option.parentNode){
this._highlighted_option = null;
}
var timeMenu = this.timeMenu,
tgt = this._highlighted_option || dojo.query("." + this.baseClass + "ItemSelected", timeMenu)[0];
if(!tgt){
tgt = timeMenu.childNodes[0];
}else if(timeMenu.childNodes.length){
if(e.charOrCode == dk.DOWN_ARROW && !tgt.nextSibling){
this._onArrowDown();
}else if(e.charOrCode == dk.UP_ARROW && !tgt.previousSibling){
this._onArrowUp();
}
if(e.charOrCode == dk.DOWN_ARROW){
tgt = tgt.nextSibling;
}else{
tgt = tgt.previousSibling;
}
}
this._highlightOption(tgt, true);
this._keyboardSelected = tgt;
}else if(this._highlighted_option && (e.charOrCode == dk.ENTER || e.charOrCode === dk.TAB)){
// Accept the currently-highlighted option as the value
if(!this._keyboardSelected && e.charOrCode === dk.TAB){ return; } // mouse hover followed by TAB is NO selection
if(e.charOrCode == dk.ENTER){dojo.stopEvent(e);}
this._onOptionSelected({target: this._highlighted_option});
}
}
}
);
}
if(!dojo._hasResource["dijit.form.TimeTextBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.TimeTextBox"] = true;
dojo.provide("dijit.form.TimeTextBox");
/*=====
dojo.declare(
"dijit.form.TimeTextBox.__Constraints",
[dijit.form._DateTimeTextBox.__Constraints, dijit._TimePicker.__Constraints]
);
=====*/
dojo.declare(
"dijit.form.TimeTextBox",
dijit.form._DateTimeTextBox,
{
// summary:
// A validating, serializable, range-bound time text box with a drop down time picker
baseClass: "dijitTextBox dijitTimeTextBox",
popupClass: "dijit._TimePicker",
_selector: "time",
/*=====
// constraints: dijit.form.TimeTextBox.__Constraints
constraints:{},
=====*/
// value: Date
// The value of this widget as a JavaScript Date object. Note that the date portion implies time zone and daylight savings rules.
//
// Example:
// | new dijit.form.TimeTextBox({value: dojo.date.stamp.fromISOString("T12:59:59", new Date())})
//
// When passed to the parser in markup, must be specified according to locale-independent
// `dojo.date.stamp.fromISOString` format.
//
// Example:
// |
value: new Date("") // value.toString()="NaN"
//FIXME: in markup, you have no control over daylight savings
}
);
}
if(!dojo._hasResource["dojo.data.util.sorter"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.data.util.sorter"] = true;
dojo.provide("dojo.data.util.sorter");
dojo.data.util.sorter.basicComparator = function( /*anything*/ a,
/*anything*/ b){
// summary:
// Basic comparision function that compares if an item is greater or less than another item
// description:
// returns 1 if a > b, -1 if a < b, 0 if equal.
// 'null' values (null, undefined) are treated as larger values so that they're pushed to the end of the list.
// And compared to each other, null is equivalent to undefined.
//null is a problematic compare, so if null, we set to undefined.
//Makes the check logic simple, compact, and consistent
//And (null == undefined) === true, so the check later against null
//works for undefined and is less bytes.
var r = -1;
if(a === null){
a = undefined;
}
if(b === null){
b = undefined;
}
if(a == b){
r = 0;
}else if(a > b || a == null){
r = 1;
}
return r; //int {-1,0,1}
};
dojo.data.util.sorter.createSortFunction = function( /* attributes array */sortSpec,
/*dojo.data.core.Read*/ store){
// summary:
// Helper function to generate the sorting function based off the list of sort attributes.
// description:
// The sort function creation will look for a property on the store called 'comparatorMap'. If it exists
// it will look in the mapping for comparisons function for the attributes. If one is found, it will
// use it instead of the basic comparator, which is typically used for strings, ints, booleans, and dates.
// Returns the sorting function for this particular list of attributes and sorting directions.
//
// sortSpec: array
// A JS object that array that defines out what attribute names to sort on and whether it should be descenting or asending.
// The objects should be formatted as follows:
// {
// attribute: "attributeName-string" || attribute,
// descending: true|false; // Default is false.
// }
// store: object
// The datastore object to look up item values from.
//
var sortFunctions=[];
function createSortFunction(attr, dir, comp, s){
//Passing in comp and s (comparator and store), makes this
//function much faster.
return function(itemA, itemB){
var a = s.getValue(itemA, attr);
var b = s.getValue(itemB, attr);
return dir * comp(a,b); //int
};
}
var sortAttribute;
var map = store.comparatorMap;
var bc = dojo.data.util.sorter.basicComparator;
for(var i = 0; i < sortSpec.length; i++){
sortAttribute = sortSpec[i];
var attr = sortAttribute.attribute;
if(attr){
var dir = (sortAttribute.descending) ? -1 : 1;
var comp = bc;
if(map){
if(typeof attr !== "string" && ("toString" in attr)){
attr = attr.toString();
}
comp = map[attr] || bc;
}
sortFunctions.push(createSortFunction(attr,
dir, comp, store));
}
}
return function(rowA, rowB){
var i=0;
while(i < sortFunctions.length){
var ret = sortFunctions[i++](rowA, rowB);
if(ret !== 0){
return ret;//int
}
}
return 0; //int
}; // Function
};
}
if(!dojo._hasResource["dojo.data.util.simpleFetch"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.data.util.simpleFetch"] = true;
dojo.provide("dojo.data.util.simpleFetch");
dojo.data.util.simpleFetch.fetch = function(/* Object? */ request){
// summary:
// The simpleFetch mixin is designed to serve as a set of function(s) that can
// be mixed into other datastore implementations to accelerate their development.
// The simpleFetch mixin should work well for any datastore that can respond to a _fetchItems()
// call by returning an array of all the found items that matched the query. The simpleFetch mixin
// is not designed to work for datastores that respond to a fetch() call by incrementally
// loading items, or sequentially loading partial batches of the result
// set. For datastores that mixin simpleFetch, simpleFetch
// implements a fetch method that automatically handles eight of the fetch()
// arguments -- onBegin, onItem, onComplete, onError, start, count, sort and scope
// The class mixing in simpleFetch should not implement fetch(),
// but should instead implement a _fetchItems() method. The _fetchItems()
// method takes three arguments, the keywordArgs object that was passed
// to fetch(), a callback function to be called when the result array is
// available, and an error callback to be called if something goes wrong.
// The _fetchItems() method should ignore any keywordArgs parameters for
// start, count, onBegin, onItem, onComplete, onError, sort, and scope.
// The _fetchItems() method needs to correctly handle any other keywordArgs
// parameters, including the query parameter and any optional parameters
// (such as includeChildren). The _fetchItems() method should create an array of
// result items and pass it to the fetchHandler along with the original request object
// -- or, the _fetchItems() method may, if it wants to, create an new request object
// with other specifics about the request that are specific to the datastore and pass
// that as the request object to the handler.
//
// For more information on this specific function, see dojo.data.api.Read.fetch()
request = request || {};
if(!request.store){
request.store = this;
}
var self = this;
var _errorHandler = function(errorData, requestObject){
if(requestObject.onError){
var scope = requestObject.scope || dojo.global;
requestObject.onError.call(scope, errorData, requestObject);
}
};
var _fetchHandler = function(items, requestObject){
var oldAbortFunction = requestObject.abort || null;
var aborted = false;
var startIndex = requestObject.start?requestObject.start:0;
var endIndex = (requestObject.count && (requestObject.count !== Infinity))?(startIndex + requestObject.count):items.length;
requestObject.abort = function(){
aborted = true;
if(oldAbortFunction){
oldAbortFunction.call(requestObject);
}
};
var scope = requestObject.scope || dojo.global;
if(!requestObject.store){
requestObject.store = self;
}
if(requestObject.onBegin){
requestObject.onBegin.call(scope, items.length, requestObject);
}
if(requestObject.sort){
items.sort(dojo.data.util.sorter.createSortFunction(requestObject.sort, self));
}
if(requestObject.onItem){
for(var i = startIndex; (i < items.length) && (i < endIndex); ++i){
var item = items[i];
if(!aborted){
requestObject.onItem.call(scope, item, requestObject);
}
}
}
if(requestObject.onComplete && !aborted){
var subset = null;
if(!requestObject.onItem){
subset = items.slice(startIndex, endIndex);
}
requestObject.onComplete.call(scope, subset, requestObject);
}
};
this._fetchItems(request, _fetchHandler, _errorHandler);
return request; // Object
};
}
if(!dojo._hasResource["dojo.data.util.filter"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.data.util.filter"] = true;
dojo.provide("dojo.data.util.filter");
dojo.data.util.filter.patternToRegExp = function(/*String*/pattern, /*boolean?*/ ignoreCase){
// summary:
// Helper function to convert a simple pattern to a regular expression for matching.
// description:
// Returns a regular expression object that conforms to the defined conversion rules.
// For example:
// ca* -> /^ca.*$/
// *ca* -> /^.*ca.*$/
// *c\*a* -> /^.*c\*a.*$/
// *c\*a?* -> /^.*c\*a..*$/
// and so on.
//
// pattern: string
// A simple matching pattern to convert that follows basic rules:
// * Means match anything, so ca* means match anything starting with ca
// ? Means match single character. So, b?b will match to bob and bab, and so on.
// \ is an escape character. So for example, \* means do not treat * as a match, but literal character *.
// To use a \ as a character in the string, it must be escaped. So in the pattern it should be
// represented by \\ to be treated as an ordinary \ character instead of an escape.
//
// ignoreCase:
// An optional flag to indicate if the pattern matching should be treated as case-sensitive or not when comparing
// By default, it is assumed case sensitive.
var rxp = "^";
var c = null;
for(var i = 0; i < pattern.length; i++){
c = pattern.charAt(i);
switch(c){
case '\\':
rxp += c;
i++;
rxp += pattern.charAt(i);
break;
case '*':
rxp += ".*"; break;
case '?':
rxp += "."; break;
case '$':
case '^':
case '/':
case '+':
case '.':
case '|':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
rxp += "\\"; //fallthrough
default:
rxp += c;
}
}
rxp += "$";
if(ignoreCase){
return new RegExp(rxp,"mi"); //RegExp
}else{
return new RegExp(rxp,"m"); //RegExp
}
};
}
if(!dojo._hasResource["dijit.form.ComboBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.ComboBox"] = true;
dojo.provide("dijit.form.ComboBox");
dojo.declare(
"dijit.form.ComboBoxMixin",
null,
{
// summary:
// Implements the base functionality for `dijit.form.ComboBox`/`dijit.form.FilteringSelect`
// description:
// All widgets that mix in dijit.form.ComboBoxMixin must extend `dijit.form._FormValueWidget`.
// tags:
// protected
// item: Object
// This is the item returned by the dojo.data.store implementation that
// provides the data for this ComboBox, it's the currently selected item.
item: null,
// pageSize: Integer
// Argument to data provider.
// Specifies number of search results per page (before hitting "next" button)
pageSize: Infinity,
// store: Object
// Reference to data provider object used by this ComboBox
store: null,
// fetchProperties: Object
// Mixin to the dojo.data store's fetch.
// For example, to set the sort order of the ComboBox menu, pass:
// | { sort: {attribute:"name",descending: true} }
// To override the default queryOptions so that deep=false, do:
// | { queryOptions: {ignoreCase: true, deep: false} }
fetchProperties:{},
// query: Object
// A query that can be passed to 'store' to initially filter the items,
// before doing further filtering based on `searchAttr` and the key.
// Any reference to the `searchAttr` is ignored.
query: {},
// autoComplete: Boolean
// If user types in a partial string, and then tab out of the ` ` box,
// automatically copy the first entry displayed in the drop down list to
// the ` ` field
autoComplete: true,
// highlightMatch: String
// One of: "first", "all" or "none".
//
// If the ComboBox/FilteringSelect opens with the search results and the searched
// string can be found, it will be highlighted. If set to "all"
// then will probably want to change `queryExpr` parameter to '*${0}*'
//
// Highlighting is only performed when `labelType` is "text", so as to not
// interfere with any HTML markup an HTML label might contain.
highlightMatch: "first",
// searchDelay: Integer
// Delay in milliseconds between when user types something and we start
// searching based on that value
searchDelay: 100,
// searchAttr: String
// Search for items in the data store where this attribute (in the item)
// matches what the user typed
searchAttr: "name",
// labelAttr: String?
// The entries in the drop down list come from this attribute in the
// dojo.data items.
// If not specified, the searchAttr attribute is used instead.
labelAttr: "",
// labelType: String
// Specifies how to interpret the labelAttr in the data store items.
// Can be "html" or "text".
labelType: "text",
// queryExpr: String
// This specifies what query ComboBox/FilteringSelect sends to the data store,
// based on what the user has typed. Changing this expression will modify
// whether the drop down shows only exact matches, a "starting with" match,
// etc. Use it in conjunction with highlightMatch.
// dojo.data query expression pattern.
// `${0}` will be substituted for the user text.
// `*` is used for wildcards.
// `${0}*` means "starts with", `*${0}*` means "contains", `${0}` means "is"
queryExpr: "${0}*",
// ignoreCase: Boolean
// Set true if the ComboBox/FilteringSelect should ignore case when matching possible items
ignoreCase: true,
// hasDownArrow: [const] Boolean
// Set this textbox to have a down arrow button, to display the drop down list.
// Defaults to true.
hasDownArrow: true,
templateString: dojo.cache("dijit.form", "templates/ComboBox.html", "\n"),
baseClass: "dijitTextBox dijitComboBox",
// Set classes like dijitDownArrowButtonHover depending on
// mouse action over button node
cssStateNodes: {
"downArrowNode": "dijitDownArrowButton"
},
_getCaretPos: function(/*DomNode*/ element){
// khtml 3.5.2 has selection* methods as does webkit nightlies from 2005-06-22
var pos = 0;
if(typeof(element.selectionStart) == "number"){
// FIXME: this is totally borked on Moz < 1.3. Any recourse?
pos = element.selectionStart;
}else if(dojo.isIE){
// in the case of a mouse click in a popup being handled,
// then the dojo.doc.selection is not the textarea, but the popup
// var r = dojo.doc.selection.createRange();
// hack to get IE 6 to play nice. What a POS browser.
var tr = dojo.doc.selection.createRange().duplicate();
var ntr = element.createTextRange();
tr.move("character",0);
ntr.move("character",0);
try{
// If control doesnt have focus, you get an exception.
// Seems to happen on reverse-tab, but can also happen on tab (seems to be a race condition - only happens sometimes).
// There appears to be no workaround for this - googled for quite a while.
ntr.setEndPoint("EndToEnd", tr);
pos = String(ntr.text).replace(/\r/g,"").length;
}catch(e){
// If focus has shifted, 0 is fine for caret pos.
}
}
return pos;
},
_setCaretPos: function(/*DomNode*/ element, /*Number*/ location){
location = parseInt(location);
dijit.selectInputText(element, location, location);
},
_setDisabledAttr: function(/*Boolean*/ value){
// Additional code to set disabled state of ComboBox node.
// Overrides _FormValueWidget._setDisabledAttr() or ValidationTextBox._setDisabledAttr().
this.inherited(arguments);
dijit.setWaiState(this.comboNode, "disabled", value);
},
_abortQuery: function(){
// stop in-progress query
if(this.searchTimer){
clearTimeout(this.searchTimer);
this.searchTimer = null;
}
if(this._fetchHandle){
if(this._fetchHandle.abort){ this._fetchHandle.abort(); }
this._fetchHandle = null;
}
},
_onInput: function(/*Event*/ evt){
// summary:
// Handles paste events
if(!this.searchTimer && (evt.type == 'paste'/*IE|WebKit*/ || evt.type == 'input'/*Firefox*/) && this._lastInput != this.textbox.value){
this.searchTimer = setTimeout(dojo.hitch(this, function(){
this._onKeyPress({charOrCode: 229}); // fake IME key to cause a search
}), 100); // long delay that will probably be preempted by keyboard input
}
this.inherited(arguments);
},
_onKeyPress: function(/*Event*/ evt){
// summary:
// Handles keyboard events
var key = evt.charOrCode;
// except for cutting/pasting case - ctrl + x/v
if(evt.altKey || ((evt.ctrlKey || evt.metaKey) && (key != 'x' && key != 'v')) || key == dojo.keys.SHIFT){
return; // throw out weird key combinations and spurious events
}
var doSearch = false;
var searchFunction = "_startSearchFromInput";
var pw = this._popupWidget;
var dk = dojo.keys;
var highlighted = null;
this._prev_key_backspace = false;
this._abortQuery();
if(this._isShowingNow){
pw.handleKey(key);
highlighted = pw.getHighlightedOption();
}
switch(key){
case dk.PAGE_DOWN:
case dk.DOWN_ARROW:
case dk.PAGE_UP:
case dk.UP_ARROW:
if(!this._isShowingNow){
doSearch = true;
searchFunction = "_startSearchAll";
}else{
this._announceOption(highlighted);
}
dojo.stopEvent(evt);
break;
case dk.ENTER:
// prevent submitting form if user presses enter. Also
// prevent accepting the value if either Next or Previous
// are selected
if(highlighted){
// only stop event on prev/next
if(highlighted == pw.nextButton){
this._nextSearch(1);
dojo.stopEvent(evt);
break;
}else if(highlighted == pw.previousButton){
this._nextSearch(-1);
dojo.stopEvent(evt);
break;
}
}else{
// Update 'value' (ex: KY) according to currently displayed text
this._setBlurValue(); // set value if needed
this._setCaretPos(this.focusNode, this.focusNode.value.length); // move cursor to end and cancel highlighting
}
// default case:
// prevent submit, but allow event to bubble
evt.preventDefault();
// fall through
case dk.TAB:
var newvalue = this.get('displayedValue');
// if the user had More Choices selected fall into the
// _onBlur handler
if(pw && (
newvalue == pw._messages["previousMessage"] ||
newvalue == pw._messages["nextMessage"])
){
break;
}
if(highlighted){
this._selectOption();
}
if(this._isShowingNow){
this._lastQuery = null; // in case results come back later
this._hideResultList();
}
break;
case ' ':
if(highlighted){
dojo.stopEvent(evt);
this._selectOption();
this._hideResultList();
}else{
doSearch = true;
}
break;
case dk.ESCAPE:
if(this._isShowingNow){
dojo.stopEvent(evt);
this._hideResultList();
}
break;
case dk.DELETE:
case dk.BACKSPACE:
this._prev_key_backspace = true;
doSearch = true;
break;
default:
// Non char keys (F1-F12 etc..) shouldn't open list.
// Ascii characters and IME input (Chinese, Japanese etc.) should.
// On IE and safari, IME input produces keycode == 229, and we simulate
// it on firefox by attaching to compositionend event (see compositionend method)
doSearch = typeof key == 'string' || key == 229;
}
if(doSearch){
// need to wait a tad before start search so that the event
// bubbles through DOM and we have value visible
this.item = undefined; // undefined means item needs to be set
this.searchTimer = setTimeout(dojo.hitch(this, searchFunction),1);
}
},
_autoCompleteText: function(/*String*/ text){
// summary:
// Fill in the textbox with the first item from the drop down
// list, and highlight the characters that were
// auto-completed. For example, if user typed "CA" and the
// drop down list appeared, the textbox would be changed to
// "California" and "ifornia" would be highlighted.
var fn = this.focusNode;
// IE7: clear selection so next highlight works all the time
dijit.selectInputText(fn, fn.value.length);
// does text autoComplete the value in the textbox?
var caseFilter = this.ignoreCase? 'toLowerCase' : 'substr';
if(text[caseFilter](0).indexOf(this.focusNode.value[caseFilter](0)) == 0){
var cpos = this._getCaretPos(fn);
// only try to extend if we added the last character at the end of the input
if((cpos+1) > fn.value.length){
// only add to input node as we would overwrite Capitalisation of chars
// actually, that is ok
fn.value = text;//.substr(cpos);
// visually highlight the autocompleted characters
dijit.selectInputText(fn, cpos);
}
}else{
// text does not autoComplete; replace the whole value and highlight
fn.value = text;
dijit.selectInputText(fn);
}
},
_openResultList: function(/*Object*/ results, /*Object*/ dataObject){
this._fetchHandle = null;
if( this.disabled ||
this.readOnly ||
(dataObject.query[this.searchAttr] != this._lastQuery)
){
return;
}
this._popupWidget.clearResultList();
if(!results.length && !this._maxOptions){ // this condition needs to match !this._isvalid set in FilteringSelect::_openResultList
this._hideResultList();
return;
}
// Fill in the textbox with the first item from the drop down list,
// and highlight the characters that were auto-completed. For
// example, if user typed "CA" and the drop down list appeared, the
// textbox would be changed to "California" and "ifornia" would be
// highlighted.
dataObject._maxOptions = this._maxOptions;
var nodes = this._popupWidget.createOptions(
results,
dataObject,
dojo.hitch(this, "_getMenuLabelFromItem")
);
// show our list (only if we have content, else nothing)
this._showResultList();
// #4091:
// tell the screen reader that the paging callback finished by
// shouting the next choice
if(dataObject.direction){
if(1 == dataObject.direction){
this._popupWidget.highlightFirstOption();
}else if(-1 == dataObject.direction){
this._popupWidget.highlightLastOption();
}
this._announceOption(this._popupWidget.getHighlightedOption());
}else if(this.autoComplete && !this._prev_key_backspace /*&& !dataObject.direction*/
// when the user clicks the arrow button to show the full list,
// startSearch looks for "*".
// it does not make sense to autocomplete
// if they are just previewing the options available.
&& !/^[*]+$/.test(dataObject.query[this.searchAttr])){
this._announceOption(nodes[1]); // 1st real item
}
},
_showResultList: function(){
this._hideResultList();
// hide the tooltip
this.displayMessage("");
// Position the list and if it's too big to fit on the screen then
// size it to the maximum possible height
// Our dear friend IE doesnt take max-height so we need to
// calculate that on our own every time
// TODO: want to redo this, see
// http://trac.dojotoolkit.org/ticket/3272
// and
// http://trac.dojotoolkit.org/ticket/4108
// natural size of the list has changed, so erase old
// width/height settings, which were hardcoded in a previous
// call to this function (via dojo.marginBox() call)
dojo.style(this._popupWidget.domNode, {width: "", height: ""});
var best = this.open();
// #3212:
// only set auto scroll bars if necessary prevents issues with
// scroll bars appearing when they shouldn't when node is made
// wider (fractional pixels cause this)
var popupbox = dojo.marginBox(this._popupWidget.domNode);
this._popupWidget.domNode.style.overflow =
((best.h == popupbox.h) && (best.w == popupbox.w)) ? "hidden" : "auto";
// #4134:
// borrow TextArea scrollbar test so content isn't covered by
// scrollbar and horizontal scrollbar doesn't appear
var newwidth = best.w;
if(best.h < this._popupWidget.domNode.scrollHeight){
newwidth += 16;
}
dojo.marginBox(this._popupWidget.domNode, {
h: best.h,
w: Math.max(newwidth, this.domNode.offsetWidth)
});
// If we increased the width of drop down to match the width of ComboBox.domNode,
// then need to reposition the drop down (wrapper) so (all of) the drop down still
// appears underneath the ComboBox.domNode
if(newwidth < this.domNode.offsetWidth){
this._popupWidget.domNode.parentNode.style.left = dojo.position(this.domNode, true).x + "px";
}
dijit.setWaiState(this.comboNode, "expanded", "true");
},
_hideResultList: function(){
this._abortQuery();
if(this._isShowingNow){
dijit.popup.close(this._popupWidget);
this._isShowingNow=false;
dijit.setWaiState(this.comboNode, "expanded", "false");
dijit.removeWaiState(this.focusNode,"activedescendant");
}
},
_setBlurValue: function(){
// if the user clicks away from the textbox OR tabs away, set the
// value to the textbox value
// #4617:
// if value is now more choices or previous choices, revert
// the value
var newvalue = this.get('displayedValue');
var pw = this._popupWidget;
if(pw && (
newvalue == pw._messages["previousMessage"] ||
newvalue == pw._messages["nextMessage"]
)
){
this._setValueAttr(this._lastValueReported, true);
}else if(typeof this.item == "undefined"){
// Update 'value' (ex: KY) according to currently displayed text
this.item = null;
this.set('displayedValue', newvalue);
}else{
if(this.value != this._lastValueReported){
dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true);
}
this._refreshState();
}
},
_onBlur: function(){
// summary:
// Called magically when focus has shifted away from this widget and it's drop down
this._hideResultList();
this.inherited(arguments);
},
_setItemAttr: function(/*item*/ item, /*Boolean?*/ priorityChange, /*String?*/ displayedValue){
// summary:
// Set the displayed valued in the input box, and the hidden value
// that gets submitted, based on a dojo.data store item.
// description:
// Users shouldn't call this function; they should be calling
// attr('item', value)
// tags:
// private
if(!displayedValue){ displayedValue = this.labelFunc(item, this.store); }
this.value = this._getValueField() != this.searchAttr? this.store.getIdentity(item) : displayedValue;
this.item = item;
dijit.form.ComboBox.superclass._setValueAttr.call(this, this.value, priorityChange, displayedValue);
},
_announceOption: function(/*Node*/ node){
// summary:
// a11y code that puts the highlighted option in the textbox.
// This way screen readers will know what is happening in the
// menu.
if(!node){
return;
}
// pull the text value from the item attached to the DOM node
var newValue;
if(node == this._popupWidget.nextButton ||
node == this._popupWidget.previousButton){
newValue = node.innerHTML;
this.item = undefined;
this.value = '';
}else{
newValue = this.labelFunc(node.item, this.store);
this.set('item', node.item, false, newValue);
}
// get the text that the user manually entered (cut off autocompleted text)
this.focusNode.value = this.focusNode.value.substring(0, this._lastInput.length);
// set up ARIA activedescendant
dijit.setWaiState(this.focusNode, "activedescendant", dojo.attr(node, "id"));
// autocomplete the rest of the option to announce change
this._autoCompleteText(newValue);
},
_selectOption: function(/*Event*/ evt){
// summary:
// Menu callback function, called when an item in the menu is selected.
if(evt){
this._announceOption(evt.target);
}
this._hideResultList();
this._setCaretPos(this.focusNode, this.focusNode.value.length);
dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true); // set this.value and fire onChange
},
_onArrowMouseDown: function(evt){
// summary:
// Callback when arrow is clicked
if(this.disabled || this.readOnly){
return;
}
dojo.stopEvent(evt);
this.focus();
if(this._isShowingNow){
this._hideResultList();
}else{
// forces full population of results, if they click
// on the arrow it means they want to see more options
this._startSearchAll();
}
},
_startSearchAll: function(){
this._startSearch('');
},
_startSearchFromInput: function(){
this._startSearch(this.focusNode.value.replace(/([\\\*\?])/g, "\\$1"));
},
_getQueryString: function(/*String*/ text){
return dojo.string.substitute(this.queryExpr, [text]);
},
_startSearch: function(/*String*/ key){
if(!this._popupWidget){
var popupId = this.id + "_popup";
this._popupWidget = new dijit.form._ComboBoxMenu({
onChange: dojo.hitch(this, this._selectOption),
id: popupId,
dir: this.dir
});
dijit.removeWaiState(this.focusNode,"activedescendant");
dijit.setWaiState(this.textbox,"owns",popupId); // associate popup with textbox
}
// create a new query to prevent accidentally querying for a hidden
// value from FilteringSelect's keyField
var query = dojo.clone(this.query); // #5970
this._lastInput = key; // Store exactly what was entered by the user.
this._lastQuery = query[this.searchAttr] = this._getQueryString(key);
// #5970: set _lastQuery, *then* start the timeout
// otherwise, if the user types and the last query returns before the timeout,
// _lastQuery won't be set and their input gets rewritten
this.searchTimer=setTimeout(dojo.hitch(this, function(query, _this){
this.searchTimer = null;
var fetch = {
queryOptions: {
ignoreCase: this.ignoreCase,
deep: true
},
query: query,
onBegin: dojo.hitch(this, "_setMaxOptions"),
onComplete: dojo.hitch(this, "_openResultList"),
onError: function(errText){
_this._fetchHandle = null;
console.error('dijit.form.ComboBox: ' + errText);
dojo.hitch(_this, "_hideResultList")();
},
start: 0,
count: this.pageSize
};
dojo.mixin(fetch, _this.fetchProperties);
this._fetchHandle = _this.store.fetch(fetch);
var nextSearch = function(dataObject, direction){
dataObject.start += dataObject.count*direction;
// #4091:
// tell callback the direction of the paging so the screen
// reader knows which menu option to shout
dataObject.direction = direction;
this._fetchHandle = this.store.fetch(dataObject);
};
this._nextSearch = this._popupWidget.onPage = dojo.hitch(this, nextSearch, this._fetchHandle);
}, query, this), this.searchDelay);
},
_setMaxOptions: function(size, request){
this._maxOptions = size;
},
_getValueField: function(){
// summmary:
// Helper for postMixInProperties() to set this.value based on data inlined into the markup.
// Returns the attribute name in the item (in dijit.form._ComboBoxDataStore) to use as the value.
return this.searchAttr;
},
/////////////// Event handlers /////////////////////
// FIXME: For 2.0, rename to "_compositionEnd"
compositionend: function(/*Event*/ evt){
// summary:
// When inputting characters using an input method, such as
// Asian languages, it will generate this event instead of
// onKeyDown event.
// Note: this event is only triggered in FF (not in IE/safari)
// tags:
// private
// 229 is the code produced by IE and safari while pressing keys during
// IME input mode
this._onKeyPress({charOrCode: 229});
},
//////////// INITIALIZATION METHODS ///////////////////////////////////////
constructor: function(){
this.query={};
this.fetchProperties={};
},
postMixInProperties: function(){
if(!this.store){
var srcNodeRef = this.srcNodeRef;
// if user didn't specify store, then assume there are option tags
this.store = new dijit.form._ComboBoxDataStore(srcNodeRef);
// if there is no value set and there is an option list, set
// the value to the first value to be consistent with native
// Select
// Firefox and Safari set value
// IE6 and Opera set selectedIndex, which is automatically set
// by the selected attribute of an option tag
// IE6 does not set value, Opera sets value = selectedIndex
if(!("value" in this.params)){
var item = this.store.fetchSelectedItem();
if(item){
var valueField = this._getValueField();
this.value = valueField != this.searchAttr? this.store.getValue(item, valueField) : this.labelFunc(item, this.store);
}
}
}
this.inherited(arguments);
},
postCreate: function(){
// summary:
// Subclasses must call this method from their postCreate() methods
// tags:
// protected
if(!this.hasDownArrow){
this.downArrowNode.style.display = "none";
}
// find any associated label element and add to ComboBox node.
var label=dojo.query('label[for="'+this.id+'"]');
if(label.length){
label[0].id = (this.id+"_label");
var cn=this.comboNode;
dijit.setWaiState(cn, "labelledby", label[0].id);
}
this.inherited(arguments);
},
uninitialize: function(){
if(this._popupWidget && !this._popupWidget._destroyed){
this._hideResultList();
this._popupWidget.destroy();
}
this.inherited(arguments);
},
_getMenuLabelFromItem: function(/*Item*/ item){
var label = this.labelAttr? this.store.getValue(item, this.labelAttr) : this.labelFunc(item, this.store);
var labelType = this.labelType;
// If labelType is not "text" we don't want to screw any markup ot whatever.
if(this.highlightMatch != "none" && this.labelType == "text" && this._lastInput){
label = this.doHighlight(label, this._escapeHtml(this._lastInput));
labelType = "html";
}
return {html: labelType == "html", label: label};
},
doHighlight: function(/*String*/label, /*String*/find){
// summary:
// Highlights the string entered by the user in the menu. By default this
// highlights the first occurence found. Override this method
// to implement your custom highlighing.
// tags:
// protected
// Add greedy when this.highlightMatch == "all"
var modifiers = "i"+(this.highlightMatch == "all"?"g":"");
var escapedLabel = this._escapeHtml(label);
find = dojo.regexp.escapeString(find); // escape regexp special chars
var ret = escapedLabel.replace(new RegExp("(^|\\s)("+ find +")", modifiers),
'$1$2 ');
return ret;// returns String, (almost) valid HTML (entities encoded)
},
_escapeHtml: function(/*string*/str){
// TODO Should become dojo.html.entities(), when exists use instead
// summary:
// Adds escape sequences for special characters in XML: &<>"'
str = String(str).replace(/&/gm, "&").replace(//gm, ">").replace(/"/gm, """);
return str; // string
},
open: function(){
// summary:
// Opens the drop down menu. TODO: rename to _open.
// tags:
// private
this._isShowingNow=true;
return dijit.popup.open({
popup: this._popupWidget,
around: this.domNode,
parent: this
});
},
reset: function(){
// Overrides the _FormWidget.reset().
// Additionally reset the .item (to clean up).
this.item = null;
this.inherited(arguments);
},
labelFunc: function(/*item*/ item, /*dojo.data.store*/ store){
// summary:
// Computes the label to display based on the dojo.data store item.
// returns:
// The label that the ComboBox should display
// tags:
// private
// Use toString() because XMLStore returns an XMLItem whereas this
// method is expected to return a String (#9354)
return store.getValue(item, this.searchAttr).toString(); // String
}
}
);
dojo.declare(
"dijit.form._ComboBoxMenu",
[dijit._Widget, dijit._Templated, dijit._CssStateMixin],
{
// summary:
// Focus-less menu for internal use in `dijit.form.ComboBox`
// tags:
// private
templateString: "",
// _messages: Object
// Holds "next" and "previous" text for paging buttons on drop down
_messages: null,
baseClass: "dijitComboBoxMenu",
postMixInProperties: function(){
this._messages = dojo.i18n.getLocalization("dijit.form", "ComboBox", this.lang);
this.inherited(arguments);
},
_setValueAttr: function(/*Object*/ value){
this.value = value;
this.onChange(value);
},
// stubs
onChange: function(/*Object*/ value){
// summary:
// Notifies ComboBox/FilteringSelect that user clicked an option in the drop down menu.
// Probably should be called onSelect.
// tags:
// callback
},
onPage: function(/*Number*/ direction){
// summary:
// Notifies ComboBox/FilteringSelect that user clicked to advance to next/previous page.
// tags:
// callback
},
postCreate: function(){
// fill in template with i18n messages
this.previousButton.innerHTML = this._messages["previousMessage"];
this.nextButton.innerHTML = this._messages["nextMessage"];
this.inherited(arguments);
},
onClose: function(){
// summary:
// Callback from dijit.popup code to this widget, notifying it that it closed
// tags:
// private
this._blurOptionNode();
},
_createOption: function(/*Object*/ item, labelFunc){
// summary:
// Creates an option to appear on the popup menu subclassed by
// `dijit.form.FilteringSelect`.
var labelObject = labelFunc(item);
var menuitem = dojo.doc.createElement("li");
dijit.setWaiRole(menuitem, "option");
if(labelObject.html){
menuitem.innerHTML = labelObject.label;
}else{
menuitem.appendChild(
dojo.doc.createTextNode(labelObject.label)
);
}
// #3250: in blank options, assign a normal height
if(menuitem.innerHTML == ""){
menuitem.innerHTML = " ";
}
menuitem.item=item;
return menuitem;
},
createOptions: function(results, dataObject, labelFunc){
// summary:
// Fills in the items in the drop down list
// results:
// Array of dojo.data items
// dataObject:
// dojo.data store
// labelFunc:
// Function to produce a label in the drop down list from a dojo.data item
//this._dataObject=dataObject;
//this._dataObject.onComplete=dojo.hitch(comboBox, comboBox._openResultList);
// display "Previous . . ." button
this.previousButton.style.display = (dataObject.start == 0) ? "none" : "";
dojo.attr(this.previousButton, "id", this.id + "_prev");
// create options using _createOption function defined by parent
// ComboBox (or FilteringSelect) class
// #2309:
// iterate over cache nondestructively
dojo.forEach(results, function(item, i){
var menuitem = this._createOption(item, labelFunc);
menuitem.className = "dijitReset dijitMenuItem" +
(this.isLeftToRight() ? "" : " dijitMenuItemRtl");
dojo.attr(menuitem, "id", this.id + i);
this.domNode.insertBefore(menuitem, this.nextButton);
}, this);
// display "Next . . ." button
var displayMore = false;
//Try to determine if we should show 'more'...
if(dataObject._maxOptions && dataObject._maxOptions != -1){
if((dataObject.start + dataObject.count) < dataObject._maxOptions){
displayMore = true;
}else if((dataObject.start + dataObject.count) > dataObject._maxOptions && dataObject.count == results.length){
//Weird return from a datastore, where a start + count > maxOptions
// implies maxOptions isn't really valid and we have to go into faking it.
//And more or less assume more if count == results.length
displayMore = true;
}
}else if(dataObject.count == results.length){
//Don't know the size, so we do the best we can based off count alone.
//So, if we have an exact match to count, assume more.
displayMore = true;
}
this.nextButton.style.display = displayMore ? "" : "none";
dojo.attr(this.nextButton,"id", this.id + "_next");
return this.domNode.childNodes;
},
clearResultList: function(){
// summary:
// Clears the entries in the drop down list, but of course keeps the previous and next buttons.
while(this.domNode.childNodes.length>2){
this.domNode.removeChild(this.domNode.childNodes[this.domNode.childNodes.length-2]);
}
},
_onMouseDown: function(/*Event*/ evt){
dojo.stopEvent(evt);
},
_onMouseUp: function(/*Event*/ evt){
if(evt.target === this.domNode || !this._highlighted_option){
return;
}else if(evt.target == this.previousButton){
this.onPage(-1);
}else if(evt.target == this.nextButton){
this.onPage(1);
}else{
var tgt = evt.target;
// while the clicked node is inside the div
while(!tgt.item){
// recurse to the top
tgt = tgt.parentNode;
}
this._setValueAttr({ target: tgt }, true);
}
},
_onMouseOver: function(/*Event*/ evt){
if(evt.target === this.domNode){ return; }
var tgt = evt.target;
if(!(tgt == this.previousButton || tgt == this.nextButton)){
// while the clicked node is inside the div
while(!tgt.item){
// recurse to the top
tgt = tgt.parentNode;
}
}
this._focusOptionNode(tgt);
},
_onMouseOut: function(/*Event*/ evt){
if(evt.target === this.domNode){ return; }
this._blurOptionNode();
},
_focusOptionNode: function(/*DomNode*/ node){
// summary:
// Does the actual highlight.
if(this._highlighted_option != node){
this._blurOptionNode();
this._highlighted_option = node;
dojo.addClass(this._highlighted_option, "dijitMenuItemSelected");
}
},
_blurOptionNode: function(){
// summary:
// Removes highlight on highlighted option.
if(this._highlighted_option){
dojo.removeClass(this._highlighted_option, "dijitMenuItemSelected");
this._highlighted_option = null;
}
},
_highlightNextOption: function(){
// summary:
// Highlight the item just below the current selection.
// If nothing selected, highlight first option.
// because each press of a button clears the menu,
// the highlighted option sometimes becomes detached from the menu!
// test to see if the option has a parent to see if this is the case.
if(!this.getHighlightedOption()){
var fc = this.domNode.firstChild;
this._focusOptionNode(fc.style.display == "none" ? fc.nextSibling : fc);
}else{
var ns = this._highlighted_option.nextSibling;
if(ns && ns.style.display != "none"){
this._focusOptionNode(ns);
}else{
this.highlightFirstOption();
}
}
// scrollIntoView is called outside of _focusOptionNode because in IE putting it inside causes the menu to scroll up on mouseover
dojo.window.scrollIntoView(this._highlighted_option);
},
highlightFirstOption: function(){
// summary:
// Highlight the first real item in the list (not Previous Choices).
var first = this.domNode.firstChild;
var second = first.nextSibling;
this._focusOptionNode(second.style.display == "none" ? first : second); // remotely possible that Previous Choices is the only thing in the list
dojo.window.scrollIntoView(this._highlighted_option);
},
highlightLastOption: function(){
// summary:
// Highlight the last real item in the list (not More Choices).
this._focusOptionNode(this.domNode.lastChild.previousSibling);
dojo.window.scrollIntoView(this._highlighted_option);
},
_highlightPrevOption: function(){
// summary:
// Highlight the item just above the current selection.
// If nothing selected, highlight last option (if
// you select Previous and try to keep scrolling up the list).
if(!this.getHighlightedOption()){
var lc = this.domNode.lastChild;
this._focusOptionNode(lc.style.display == "none" ? lc.previousSibling : lc);
}else{
var ps = this._highlighted_option.previousSibling;
if(ps && ps.style.display != "none"){
this._focusOptionNode(ps);
}else{
this.highlightLastOption();
}
}
dojo.window.scrollIntoView(this._highlighted_option);
},
_page: function(/*Boolean*/ up){
// summary:
// Handles page-up and page-down keypresses
var scrollamount = 0;
var oldscroll = this.domNode.scrollTop;
var height = dojo.style(this.domNode, "height");
// if no item is highlighted, highlight the first option
if(!this.getHighlightedOption()){
this._highlightNextOption();
}
while(scrollamount
// | Alabama
// | ...
//
// Actually. just implements the subset of dojo.data.Read/Notification
// needed for ComboBox and FilteringSelect to work.
//
// Note that an item is just a pointer to the DomNode.
constructor: function( /*DomNode*/ root){
this.root = root;
if(root.tagName != "SELECT" && root.firstChild){
root = dojo.query("select", root);
if(root.length > 0){ // SELECT is a child of srcNodeRef
root = root[0];
}else{ // no select, so create 1 to parent the option tags to define selectedIndex
this.root.innerHTML = ""+this.root.innerHTML+" ";
root = this.root.firstChild;
}
this.root = root;
}
dojo.query("> option", root).forEach(function(node){
// TODO: this was added in #3858 but unclear why/if it's needed; doesn't seem to be.
// If it is needed then can we just hide the select itself instead?
//node.style.display="none";
node.innerHTML = dojo.trim(node.innerHTML);
});
},
getValue: function( /* item */ item,
/* attribute-name-string */ attribute,
/* value? */ defaultValue){
return (attribute == "value") ? item.value : (item.innerText || item.textContent || '');
},
isItemLoaded: function(/* anything */ something){
return true;
},
getFeatures: function(){
return {"dojo.data.api.Read": true, "dojo.data.api.Identity": true};
},
_fetchItems: function( /* Object */ args,
/* Function */ findCallback,
/* Function */ errorCallback){
// summary:
// See dojo.data.util.simpleFetch.fetch()
if(!args.query){ args.query = {}; }
if(!args.query.name){ args.query.name = ""; }
if(!args.queryOptions){ args.queryOptions = {}; }
var matcher = dojo.data.util.filter.patternToRegExp(args.query.name, args.queryOptions.ignoreCase),
items = dojo.query("> option", this.root).filter(function(option){
return (option.innerText || option.textContent || '').match(matcher);
} );
if(args.sort){
items.sort(dojo.data.util.sorter.createSortFunction(args.sort, this));
}
findCallback(items, args);
},
close: function(/*dojo.data.api.Request || args || null */ request){
return;
},
getLabel: function(/* item */ item){
return item.innerHTML;
},
getIdentity: function(/* item */ item){
return dojo.attr(item, "value");
},
fetchItemByIdentity: function(/* Object */ args){
// summary:
// Given the identity of an item, this method returns the item that has
// that identity through the onItem callback.
// Refer to dojo.data.api.Identity.fetchItemByIdentity() for more details.
//
// description:
// Given arguments like:
//
// | {identity: "CA", onItem: function(item){...}
//
// Call `onItem()` with the DOM node ` California `
var item = dojo.query("> option[value='" + args.identity + "']", this.root)[0];
args.onItem(item);
},
fetchSelectedItem: function(){
// summary:
// Get the option marked as selected, like ``.
// Not part of dojo.data API.
var root = this.root,
si = root.selectedIndex;
return typeof si == "number"
? dojo.query("> option:nth-child(" + (si != -1 ? si+1 : 1) + ")", root)[0]
: null; // dojo.data.Item
}
});
//Mix in the simple fetch implementation to this class.
dojo.extend(dijit.form._ComboBoxDataStore,dojo.data.util.simpleFetch);
}
if(!dojo._hasResource["dojo.data.ItemFileReadStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.data.ItemFileReadStore"] = true;
dojo.provide("dojo.data.ItemFileReadStore");
dojo.declare("dojo.data.ItemFileReadStore", null,{
// summary:
// The ItemFileReadStore implements the dojo.data.api.Read API and reads
// data from JSON files that have contents in this format --
// { items: [
// { name:'Kermit', color:'green', age:12, friends:['Gonzo', {_reference:{name:'Fozzie Bear'}}]},
// { name:'Fozzie Bear', wears:['hat', 'tie']},
// { name:'Miss Piggy', pets:'Foo-Foo'}
// ]}
// Note that it can also contain an 'identifer' property that specified which attribute on the items
// in the array of items that acts as the unique identifier for that item.
//
constructor: function(/* Object */ keywordParameters){
// summary: constructor
// keywordParameters: {url: String}
// keywordParameters: {data: jsonObject}
// keywordParameters: {typeMap: object)
// The structure of the typeMap object is as follows:
// {
// type0: function || object,
// type1: function || object,
// ...
// typeN: function || object
// }
// Where if it is a function, it is assumed to be an object constructor that takes the
// value of _value as the initialization parameters. If it is an object, then it is assumed
// to be an object of general form:
// {
// type: function, //constructor.
// deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
// }
this._arrayOfAllItems = [];
this._arrayOfTopLevelItems = [];
this._loadFinished = false;
this._jsonFileUrl = keywordParameters.url;
this._ccUrl = keywordParameters.url;
this.url = keywordParameters.url;
this._jsonData = keywordParameters.data;
this.data = null;
this._datatypeMap = keywordParameters.typeMap || {};
if(!this._datatypeMap['Date']){
//If no default mapping for dates, then set this as default.
//We use the dojo.date.stamp here because the ISO format is the 'dojo way'
//of generically representing dates.
this._datatypeMap['Date'] = {
type: Date,
deserialize: function(value){
return dojo.date.stamp.fromISOString(value);
}
};
}
this._features = {'dojo.data.api.Read':true, 'dojo.data.api.Identity':true};
this._itemsByIdentity = null;
this._storeRefPropName = "_S"; // Default name for the store reference to attach to every item.
this._itemNumPropName = "_0"; // Default Item Id for isItem to attach to every item.
this._rootItemPropName = "_RI"; // Default Item Id for isItem to attach to every item.
this._reverseRefMap = "_RRM"; // Default attribute for constructing a reverse reference map for use with reference integrity
this._loadInProgress = false; //Got to track the initial load to prevent duelling loads of the dataset.
this._queuedFetches = [];
if(keywordParameters.urlPreventCache !== undefined){
this.urlPreventCache = keywordParameters.urlPreventCache?true:false;
}
if(keywordParameters.hierarchical !== undefined){
this.hierarchical = keywordParameters.hierarchical?true:false;
}
if(keywordParameters.clearOnClose){
this.clearOnClose = true;
}
if("failOk" in keywordParameters){
this.failOk = keywordParameters.failOk?true:false;
}
},
url: "", // use "" rather than undefined for the benefit of the parser (#3539)
//Internal var, crossCheckUrl. Used so that setting either url or _jsonFileUrl, can still trigger a reload
//when clearOnClose and close is used.
_ccUrl: "",
data: null, // define this so that the parser can populate it
typeMap: null, //Define so parser can populate.
//Parameter to allow users to specify if a close call should force a reload or not.
//By default, it retains the old behavior of not clearing if close is called. But
//if set true, the store will be reset to default state. Note that by doing this,
//all item handles will become invalid and a new fetch must be issued.
clearOnClose: false,
//Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url.
//Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option.
//Added for tracker: #6072
urlPreventCache: false,
//Parameter for specifying that it is OK for the xhrGet call to fail silently.
failOk: false,
//Parameter to indicate to process data from the url as hierarchical
//(data items can contain other data items in js form). Default is true
//for backwards compatibility. False means only root items are processed
//as items, all child objects outside of type-mapped objects and those in
//specific reference format, are left straight JS data objects.
hierarchical: true,
_assertIsItem: function(/* item */ item){
// summary:
// This function tests whether the item passed in is indeed an item in the store.
// item:
// The item to test for being contained by the store.
if(!this.isItem(item)){
throw new Error("dojo.data.ItemFileReadStore: Invalid item argument.");
}
},
_assertIsAttribute: function(/* attribute-name-string */ attribute){
// summary:
// This function tests whether the item passed in is indeed a valid 'attribute' like type for the store.
// attribute:
// The attribute to test for being contained by the store.
if(typeof attribute !== "string"){
throw new Error("dojo.data.ItemFileReadStore: Invalid attribute argument.");
}
},
getValue: function( /* item */ item,
/* attribute-name-string */ attribute,
/* value? */ defaultValue){
// summary:
// See dojo.data.api.Read.getValue()
var values = this.getValues(item, attribute);
return (values.length > 0)?values[0]:defaultValue; // mixed
},
getValues: function(/* item */ item,
/* attribute-name-string */ attribute){
// summary:
// See dojo.data.api.Read.getValues()
this._assertIsItem(item);
this._assertIsAttribute(attribute);
// Clone it before returning. refs: #10474
return (item[attribute] || []).slice(0); // Array
},
getAttributes: function(/* item */ item){
// summary:
// See dojo.data.api.Read.getAttributes()
this._assertIsItem(item);
var attributes = [];
for(var key in item){
// Save off only the real item attributes, not the special id marks for O(1) isItem.
if((key !== this._storeRefPropName) && (key !== this._itemNumPropName) && (key !== this._rootItemPropName) && (key !== this._reverseRefMap)){
attributes.push(key);
}
}
return attributes; // Array
},
hasAttribute: function( /* item */ item,
/* attribute-name-string */ attribute){
// summary:
// See dojo.data.api.Read.hasAttribute()
this._assertIsItem(item);
this._assertIsAttribute(attribute);
return (attribute in item);
},
containsValue: function(/* item */ item,
/* attribute-name-string */ attribute,
/* anything */ value){
// summary:
// See dojo.data.api.Read.containsValue()
var regexp = undefined;
if(typeof value === "string"){
regexp = dojo.data.util.filter.patternToRegExp(value, false);
}
return this._containsValue(item, attribute, value, regexp); //boolean.
},
_containsValue: function( /* item */ item,
/* attribute-name-string */ attribute,
/* anything */ value,
/* RegExp?*/ regexp){
// summary:
// Internal function for looking at the values contained by the item.
// description:
// Internal function for looking at the values contained by the item. This
// function allows for denoting if the comparison should be case sensitive for
// strings or not (for handling filtering cases where string case should not matter)
//
// item:
// The data item to examine for attribute values.
// attribute:
// The attribute to inspect.
// value:
// The value to match.
// regexp:
// Optional regular expression generated off value if value was of string type to handle wildcarding.
// If present and attribute values are string, then it can be used for comparison instead of 'value'
return dojo.some(this.getValues(item, attribute), function(possibleValue){
if(possibleValue !== null && !dojo.isObject(possibleValue) && regexp){
if(possibleValue.toString().match(regexp)){
return true; // Boolean
}
}else if(value === possibleValue){
return true; // Boolean
}
});
},
isItem: function(/* anything */ something){
// summary:
// See dojo.data.api.Read.isItem()
if(something && something[this._storeRefPropName] === this){
if(this._arrayOfAllItems[something[this._itemNumPropName]] === something){
return true;
}
}
return false; // Boolean
},
isItemLoaded: function(/* anything */ something){
// summary:
// See dojo.data.api.Read.isItemLoaded()
return this.isItem(something); //boolean
},
loadItem: function(/* object */ keywordArgs){
// summary:
// See dojo.data.api.Read.loadItem()
this._assertIsItem(keywordArgs.item);
},
getFeatures: function(){
// summary:
// See dojo.data.api.Read.getFeatures()
return this._features; //Object
},
getLabel: function(/* item */ item){
// summary:
// See dojo.data.api.Read.getLabel()
if(this._labelAttr && this.isItem(item)){
return this.getValue(item,this._labelAttr); //String
}
return undefined; //undefined
},
getLabelAttributes: function(/* item */ item){
// summary:
// See dojo.data.api.Read.getLabelAttributes()
if(this._labelAttr){
return [this._labelAttr]; //array
}
return null; //null
},
_fetchItems: function( /* Object */ keywordArgs,
/* Function */ findCallback,
/* Function */ errorCallback){
// summary:
// See dojo.data.util.simpleFetch.fetch()
var self = this,
filter = function(requestArgs, arrayOfItems){
var items = [],
i, key;
if(requestArgs.query){
var value,
ignoreCase = requestArgs.queryOptions ? requestArgs.queryOptions.ignoreCase : false;
//See if there are any string values that can be regexp parsed first to avoid multiple regexp gens on the
//same value for each item examined. Much more efficient.
var regexpList = {};
for(key in requestArgs.query){
value = requestArgs.query[key];
if(typeof value === "string"){
regexpList[key] = dojo.data.util.filter.patternToRegExp(value, ignoreCase);
}else if(value instanceof RegExp){
regexpList[key] = value;
}
}
for(i = 0; i < arrayOfItems.length; ++i){
var match = true;
var candidateItem = arrayOfItems[i];
if(candidateItem === null){
match = false;
}else{
for(key in requestArgs.query){
value = requestArgs.query[key];
if(!self._containsValue(candidateItem, key, value, regexpList[key])){
match = false;
}
}
}
if(match){
items.push(candidateItem);
}
}
findCallback(items, requestArgs);
}else{
// We want a copy to pass back in case the parent wishes to sort the array.
// We shouldn't allow resort of the internal list, so that multiple callers
// can get lists and sort without affecting each other. We also need to
// filter out any null values that have been left as a result of deleteItem()
// calls in ItemFileWriteStore.
for(i = 0; i < arrayOfItems.length; ++i){
var item = arrayOfItems[i];
if(item !== null){
items.push(item);
}
}
findCallback(items, requestArgs);
}
};
if(this._loadFinished){
filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
}else{
//Do a check on the JsonFileUrl and crosscheck it.
//If it doesn't match the cross-check, it needs to be updated
//This allows for either url or _jsonFileUrl to he changed to
//reset the store load location. Done this way for backwards
//compatibility. People use _jsonFileUrl (even though officially
//private.
if(this._jsonFileUrl !== this._ccUrl){
dojo.deprecated("dojo.data.ItemFileReadStore: ",
"To change the url, set the url property of the store," +
" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
this._ccUrl = this._jsonFileUrl;
this.url = this._jsonFileUrl;
}else if(this.url !== this._ccUrl){
this._jsonFileUrl = this.url;
this._ccUrl = this.url;
}
//See if there was any forced reset of data.
if(this.data != null && this._jsonData == null){
this._jsonData = this.data;
this.data = null;
}
if(this._jsonFileUrl){
//If fetches come in before the loading has finished, but while
//a load is in progress, we have to defer the fetching to be
//invoked in the callback.
if(this._loadInProgress){
this._queuedFetches.push({args: keywordArgs, filter: filter});
}else{
this._loadInProgress = true;
var getArgs = {
url: self._jsonFileUrl,
handleAs: "json-comment-optional",
preventCache: this.urlPreventCache,
failOk: this.failOk
};
var getHandler = dojo.xhrGet(getArgs);
getHandler.addCallback(function(data){
try{
self._getItemsFromLoadedData(data);
self._loadFinished = true;
self._loadInProgress = false;
filter(keywordArgs, self._getItemsArray(keywordArgs.queryOptions));
self._handleQueuedFetches();
}catch(e){
self._loadFinished = true;
self._loadInProgress = false;
errorCallback(e, keywordArgs);
}
});
getHandler.addErrback(function(error){
self._loadInProgress = false;
errorCallback(error, keywordArgs);
});
//Wire up the cancel to abort of the request
//This call cancel on the deferred if it hasn't been called
//yet and then will chain to the simple abort of the
//simpleFetch keywordArgs
var oldAbort = null;
if(keywordArgs.abort){
oldAbort = keywordArgs.abort;
}
keywordArgs.abort = function(){
var df = getHandler;
if(df && df.fired === -1){
df.cancel();
df = null;
}
if(oldAbort){
oldAbort.call(keywordArgs);
}
};
}
}else if(this._jsonData){
try{
this._loadFinished = true;
this._getItemsFromLoadedData(this._jsonData);
this._jsonData = null;
filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
}catch(e){
errorCallback(e, keywordArgs);
}
}else{
errorCallback(new Error("dojo.data.ItemFileReadStore: No JSON source data was provided as either URL or a nested Javascript object."), keywordArgs);
}
}
},
_handleQueuedFetches: function(){
// summary:
// Internal function to execute delayed request in the store.
//Execute any deferred fetches now.
if(this._queuedFetches.length > 0){
for(var i = 0; i < this._queuedFetches.length; i++){
var fData = this._queuedFetches[i],
delayedQuery = fData.args,
delayedFilter = fData.filter;
if(delayedFilter){
delayedFilter(delayedQuery, this._getItemsArray(delayedQuery.queryOptions));
}else{
this.fetchItemByIdentity(delayedQuery);
}
}
this._queuedFetches = [];
}
},
_getItemsArray: function(/*object?*/queryOptions){
// summary:
// Internal function to determine which list of items to search over.
// queryOptions: The query options parameter, if any.
if(queryOptions && queryOptions.deep){
return this._arrayOfAllItems;
}
return this._arrayOfTopLevelItems;
},
close: function(/*dojo.data.api.Request || keywordArgs || null */ request){
// summary:
// See dojo.data.api.Read.close()
if(this.clearOnClose &&
this._loadFinished &&
!this._loadInProgress){
//Reset all internalsback to default state. This will force a reload
//on next fetch. This also checks that the data or url param was set
//so that the store knows it can get data. Without one of those being set,
//the next fetch will trigger an error.
if(((this._jsonFileUrl == "" || this._jsonFileUrl == null) &&
(this.url == "" || this.url == null)
) && this.data == null){
console.debug("dojo.data.ItemFileReadStore: WARNING! Data reload " +
" information has not been provided." +
" Please set 'url' or 'data' to the appropriate value before" +
" the next fetch");
}
this._arrayOfAllItems = [];
this._arrayOfTopLevelItems = [];
this._loadFinished = false;
this._itemsByIdentity = null;
this._loadInProgress = false;
this._queuedFetches = [];
}
},
_getItemsFromLoadedData: function(/* Object */ dataObject){
// summary:
// Function to parse the loaded data into item format and build the internal items array.
// description:
// Function to parse the loaded data into item format and build the internal items array.
//
// dataObject:
// The JS data object containing the raw data to convery into item format.
//
// returns: array
// Array of items in store item format.
// First, we define a couple little utility functions...
var addingArrays = false,
self = this;
function valueIsAnItem(/* anything */ aValue){
// summary:
// Given any sort of value that could be in the raw json data,
// return true if we should interpret the value as being an
// item itself, rather than a literal value or a reference.
// example:
// | false == valueIsAnItem("Kermit");
// | false == valueIsAnItem(42);
// | false == valueIsAnItem(new Date());
// | false == valueIsAnItem({_type:'Date', _value:'May 14, 1802'});
// | false == valueIsAnItem({_reference:'Kermit'});
// | true == valueIsAnItem({name:'Kermit', color:'green'});
// | true == valueIsAnItem({iggy:'pop'});
// | true == valueIsAnItem({foo:42});
var isItem = (
(aValue !== null) &&
(typeof aValue === "object") &&
(!dojo.isArray(aValue) || addingArrays) &&
(!dojo.isFunction(aValue)) &&
(aValue.constructor == Object || dojo.isArray(aValue)) &&
(typeof aValue._reference === "undefined") &&
(typeof aValue._type === "undefined") &&
(typeof aValue._value === "undefined") &&
self.hierarchical
);
return isItem;
}
function addItemAndSubItemsToArrayOfAllItems(/* Item */ anItem){
self._arrayOfAllItems.push(anItem);
for(var attribute in anItem){
var valueForAttribute = anItem[attribute];
if(valueForAttribute){
if(dojo.isArray(valueForAttribute)){
var valueArray = valueForAttribute;
for(var k = 0; k < valueArray.length; ++k){
var singleValue = valueArray[k];
if(valueIsAnItem(singleValue)){
addItemAndSubItemsToArrayOfAllItems(singleValue);
}
}
}else{
if(valueIsAnItem(valueForAttribute)){
addItemAndSubItemsToArrayOfAllItems(valueForAttribute);
}
}
}
}
}
this._labelAttr = dataObject.label;
// We need to do some transformations to convert the data structure
// that we read from the file into a format that will be convenient
// to work with in memory.
// Step 1: Walk through the object hierarchy and build a list of all items
var i,
item;
this._arrayOfAllItems = [];
this._arrayOfTopLevelItems = dataObject.items;
for(i = 0; i < this._arrayOfTopLevelItems.length; ++i){
item = this._arrayOfTopLevelItems[i];
if(dojo.isArray(item)){
addingArrays = true;
}
addItemAndSubItemsToArrayOfAllItems(item);
item[this._rootItemPropName]=true;
}
// Step 2: Walk through all the attribute values of all the items,
// and replace single values with arrays. For example, we change this:
// { name:'Miss Piggy', pets:'Foo-Foo'}
// into this:
// { name:['Miss Piggy'], pets:['Foo-Foo']}
//
// We also store the attribute names so we can validate our store
// reference and item id special properties for the O(1) isItem
var allAttributeNames = {},
key;
for(i = 0; i < this._arrayOfAllItems.length; ++i){
item = this._arrayOfAllItems[i];
for(key in item){
if(key !== this._rootItemPropName){
var value = item[key];
if(value !== null){
if(!dojo.isArray(value)){
item[key] = [value];
}
}else{
item[key] = [null];
}
}
allAttributeNames[key]=key;
}
}
// Step 3: Build unique property names to use for the _storeRefPropName and _itemNumPropName
// This should go really fast, it will generally never even run the loop.
while(allAttributeNames[this._storeRefPropName]){
this._storeRefPropName += "_";
}
while(allAttributeNames[this._itemNumPropName]){
this._itemNumPropName += "_";
}
while(allAttributeNames[this._reverseRefMap]){
this._reverseRefMap += "_";
}
// Step 4: Some data files specify an optional 'identifier', which is
// the name of an attribute that holds the identity of each item.
// If this data file specified an identifier attribute, then build a
// hash table of items keyed by the identity of the items.
var arrayOfValues;
var identifier = dataObject.identifier;
if(identifier){
this._itemsByIdentity = {};
this._features['dojo.data.api.Identity'] = identifier;
for(i = 0; i < this._arrayOfAllItems.length; ++i){
item = this._arrayOfAllItems[i];
arrayOfValues = item[identifier];
var identity = arrayOfValues[0];
if(!this._itemsByIdentity[identity]){
this._itemsByIdentity[identity] = item;
}else{
if(this._jsonFileUrl){
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 + "]");
}else if(this._jsonData){
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 + "]");
}
}
}
}else{
this._features['dojo.data.api.Identity'] = Number;
}
// Step 5: Walk through all the items, and set each item's properties
// for _storeRefPropName and _itemNumPropName, so that store.isItem() will return true.
for(i = 0; i < this._arrayOfAllItems.length; ++i){
item = this._arrayOfAllItems[i];
item[this._storeRefPropName] = this;
item[this._itemNumPropName] = i;
}
// Step 6: We walk through all the attribute values of all the items,
// looking for type/value literals and item-references.
//
// We replace item-references with pointers to items. For example, we change:
// { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
// into this:
// { name:['Kermit'], friends:[miss_piggy] }
// (where miss_piggy is the object representing the 'Miss Piggy' item).
//
// We replace type/value pairs with typed-literals. For example, we change:
// { name:['Nelson Mandela'], born:[{_type:'Date', _value:'July 18, 1918'}] }
// into this:
// { name:['Kermit'], born:(new Date('July 18, 1918')) }
//
// We also generate the associate map for all items for the O(1) isItem function.
for(i = 0; i < this._arrayOfAllItems.length; ++i){
item = this._arrayOfAllItems[i]; // example: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
for(key in item){
arrayOfValues = item[key]; // example: [{_reference:{name:'Miss Piggy'}}]
for(var j = 0; j < arrayOfValues.length; ++j){
value = arrayOfValues[j]; // example: {_reference:{name:'Miss Piggy'}}
if(value !== null && typeof value == "object"){
if(("_type" in value) && ("_value" in value)){
var type = value._type; // examples: 'Date', 'Color', or 'ComplexNumber'
var mappingObj = this._datatypeMap[type]; // examples: Date, dojo.Color, foo.math.ComplexNumber, {type: dojo.Color, deserialize(value){ return new dojo.Color(value)}}
if(!mappingObj){
throw new Error("dojo.data.ItemFileReadStore: in the typeMap constructor arg, no object class was specified for the datatype '" + type + "'");
}else if(dojo.isFunction(mappingObj)){
arrayOfValues[j] = new mappingObj(value._value);
}else if(dojo.isFunction(mappingObj.deserialize)){
arrayOfValues[j] = mappingObj.deserialize(value._value);
}else{
throw new Error("dojo.data.ItemFileReadStore: Value provided in typeMap was neither a constructor, nor a an object with a deserialize function");
}
}
if(value._reference){
var referenceDescription = value._reference; // example: {name:'Miss Piggy'}
if(!dojo.isObject(referenceDescription)){
// example: 'Miss Piggy'
// from an item like: { name:['Kermit'], friends:[{_reference:'Miss Piggy'}]}
arrayOfValues[j] = this._getItemByIdentity(referenceDescription);
}else{
// example: {name:'Miss Piggy'}
// from an item like: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
for(var k = 0; k < this._arrayOfAllItems.length; ++k){
var candidateItem = this._arrayOfAllItems[k],
found = true;
for(var refKey in referenceDescription){
if(candidateItem[refKey] != referenceDescription[refKey]){
found = false;
}
}
if(found){
arrayOfValues[j] = candidateItem;
}
}
}
if(this.referenceIntegrity){
var refItem = arrayOfValues[j];
if(this.isItem(refItem)){
this._addReferenceToMap(refItem, item, key);
}
}
}else if(this.isItem(value)){
//It's a child item (not one referenced through _reference).
//We need to treat this as a referenced item, so it can be cleaned up
//in a write store easily.
if(this.referenceIntegrity){
this._addReferenceToMap(value, item, key);
}
}
}
}
}
}
},
_addReferenceToMap: function(/*item*/ refItem, /*item*/ parentItem, /*string*/ attribute){
// summary:
// Method to add an reference map entry for an item and attribute.
// description:
// Method to add an reference map entry for an item and attribute. //
// refItem:
// The item that is referenced.
// parentItem:
// The item that holds the new reference to refItem.
// attribute:
// The attribute on parentItem that contains the new reference.
//Stub function, does nothing. Real processing is in ItemFileWriteStore.
},
getIdentity: function(/* item */ item){
// summary:
// See dojo.data.api.Identity.getIdentity()
var identifier = this._features['dojo.data.api.Identity'];
if(identifier === Number){
return item[this._itemNumPropName]; // Number
}else{
var arrayOfValues = item[identifier];
if(arrayOfValues){
return arrayOfValues[0]; // Object || String
}
}
return null; // null
},
fetchItemByIdentity: function(/* Object */ keywordArgs){
// summary:
// See dojo.data.api.Identity.fetchItemByIdentity()
// Hasn't loaded yet, we have to trigger the load.
var item,
scope;
if(!this._loadFinished){
var self = this;
//Do a check on the JsonFileUrl and crosscheck it.
//If it doesn't match the cross-check, it needs to be updated
//This allows for either url or _jsonFileUrl to he changed to
//reset the store load location. Done this way for backwards
//compatibility. People use _jsonFileUrl (even though officially
//private.
if(this._jsonFileUrl !== this._ccUrl){
dojo.deprecated("dojo.data.ItemFileReadStore: ",
"To change the url, set the url property of the store," +
" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
this._ccUrl = this._jsonFileUrl;
this.url = this._jsonFileUrl;
}else if(this.url !== this._ccUrl){
this._jsonFileUrl = this.url;
this._ccUrl = this.url;
}
//See if there was any forced reset of data.
if(this.data != null && this._jsonData == null){
this._jsonData = this.data;
this.data = null;
}
if(this._jsonFileUrl){
if(this._loadInProgress){
this._queuedFetches.push({args: keywordArgs});
}else{
this._loadInProgress = true;
var getArgs = {
url: self._jsonFileUrl,
handleAs: "json-comment-optional",
preventCache: this.urlPreventCache,
failOk: this.failOk
};
var getHandler = dojo.xhrGet(getArgs);
getHandler.addCallback(function(data){
var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
try{
self._getItemsFromLoadedData(data);
self._loadFinished = true;
self._loadInProgress = false;
item = self._getItemByIdentity(keywordArgs.identity);
if(keywordArgs.onItem){
keywordArgs.onItem.call(scope, item);
}
self._handleQueuedFetches();
}catch(error){
self._loadInProgress = false;
if(keywordArgs.onError){
keywordArgs.onError.call(scope, error);
}
}
});
getHandler.addErrback(function(error){
self._loadInProgress = false;
if(keywordArgs.onError){
var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
keywordArgs.onError.call(scope, error);
}
});
}
}else if(this._jsonData){
// Passed in data, no need to xhr.
self._getItemsFromLoadedData(self._jsonData);
self._jsonData = null;
self._loadFinished = true;
item = self._getItemByIdentity(keywordArgs.identity);
if(keywordArgs.onItem){
scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
keywordArgs.onItem.call(scope, item);
}
}
}else{
// Already loaded. We can just look it up and call back.
item = this._getItemByIdentity(keywordArgs.identity);
if(keywordArgs.onItem){
scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
keywordArgs.onItem.call(scope, item);
}
}
},
_getItemByIdentity: function(/* Object */ identity){
// summary:
// Internal function to look an item up by its identity map.
var item = null;
if(this._itemsByIdentity){
item = this._itemsByIdentity[identity];
}else{
item = this._arrayOfAllItems[identity];
}
if(item === undefined){
item = null;
}
return item; // Object
},
getIdentityAttributes: function(/* item */ item){
// summary:
// See dojo.data.api.Identity.getIdentifierAttributes()
var identifier = this._features['dojo.data.api.Identity'];
if(identifier === Number){
// If (identifier === Number) it means getIdentity() just returns
// an integer item-number for each item. The dojo.data.api.Identity
// spec says we need to return null if the identity is not composed
// of attributes
return null; // null
}else{
return [identifier]; // Array
}
},
_forceLoad: function(){
// summary:
// Internal function to force a load of the store if it hasn't occurred yet. This is required
// for specific functions to work properly.
var self = this;
//Do a check on the JsonFileUrl and crosscheck it.
//If it doesn't match the cross-check, it needs to be updated
//This allows for either url or _jsonFileUrl to he changed to
//reset the store load location. Done this way for backwards
//compatibility. People use _jsonFileUrl (even though officially
//private.
if(this._jsonFileUrl !== this._ccUrl){
dojo.deprecated("dojo.data.ItemFileReadStore: ",
"To change the url, set the url property of the store," +
" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
this._ccUrl = this._jsonFileUrl;
this.url = this._jsonFileUrl;
}else if(this.url !== this._ccUrl){
this._jsonFileUrl = this.url;
this._ccUrl = this.url;
}
//See if there was any forced reset of data.
if(this.data != null && this._jsonData == null){
this._jsonData = this.data;
this.data = null;
}
if(this._jsonFileUrl){
var getArgs = {
url: this._jsonFileUrl,
handleAs: "json-comment-optional",
preventCache: this.urlPreventCache,
failOk: this.failOk,
sync: true
};
var getHandler = dojo.xhrGet(getArgs);
getHandler.addCallback(function(data){
try{
//Check to be sure there wasn't another load going on concurrently
//So we don't clobber data that comes in on it. If there is a load going on
//then do not save this data. It will potentially clobber current data.
//We mainly wanted to sync/wait here.
//TODO: Revisit the loading scheme of this store to improve multi-initial
//request handling.
if(self._loadInProgress !== true && !self._loadFinished){
self._getItemsFromLoadedData(data);
self._loadFinished = true;
}else if(self._loadInProgress){
//Okay, we hit an error state we can't recover from. A forced load occurred
//while an async load was occurring. Since we cannot block at this point, the best
//that can be managed is to throw an error.
throw new Error("dojo.data.ItemFileReadStore: Unable to perform a synchronous load, an async load is in progress.");
}
}catch(e){
console.log(e);
throw e;
}
});
getHandler.addErrback(function(error){
throw error;
});
}else if(this._jsonData){
self._getItemsFromLoadedData(self._jsonData);
self._jsonData = null;
self._loadFinished = true;
}
}
});
//Mix in the simple fetch implementation to this class.
dojo.extend(dojo.data.ItemFileReadStore,dojo.data.util.simpleFetch);
}
if(!dojo._hasResource["dijit.form.ToggleButton"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.ToggleButton"] = true;
dojo.provide("dijit.form.ToggleButton");
}
if(!dojo._hasResource["dijit.form.CheckBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.CheckBox"] = true;
dojo.provide("dijit.form.CheckBox");
dojo.declare(
"dijit.form.CheckBox",
dijit.form.ToggleButton,
{
// summary:
// Same as an HTML checkbox, but with fancy styling.
//
// description:
// User interacts with real html inputs.
// On onclick (which occurs by mouse click, space-bar, or
// using the arrow keys to switch the selected radio button),
// we update the state of the checkbox/radio.
//
// There are two modes:
// 1. High contrast mode
// 2. Normal mode
//
// In case 1, the regular html inputs are shown and used by the user.
// In case 2, the regular html inputs are invisible but still used by
// the user. They are turned quasi-invisible and overlay the background-image.
templateString: dojo.cache("dijit.form", "templates/CheckBox.html", "
\n"),
baseClass: "dijitCheckBox",
// type: [private] String
// type attribute on node.
// Overrides `dijit.form.Button.type`. Users should not change this value.
type: "checkbox",
// value: String
// As an initialization parameter, equivalent to value field on normal checkbox
// (if checked, the value is passed as the value when form is submitted).
//
// However, attr('value') will return either the string or false depending on
// whether or not the checkbox is checked.
//
// attr('value', string) will check the checkbox and change the value to the
// specified string
//
// attr('value', boolean) will change the checked state.
value: "on",
// readOnly: Boolean
// Should this widget respond to user input?
// In markup, this is specified as "readOnly".
// Similar to disabled except readOnly form values are submitted.
readOnly: false,
// the attributeMap should inherit from dijit.form._FormWidget.prototype.attributeMap
// instead of ToggleButton as the icon mapping has no meaning for a CheckBox
attributeMap: dojo.delegate(dijit.form._FormWidget.prototype.attributeMap, {
readOnly: "focusNode"
}),
_setReadOnlyAttr: function(/*Boolean*/ value){
this.readOnly = value;
dojo.attr(this.focusNode, 'readOnly', value);
dijit.setWaiState(this.focusNode, "readonly", value);
},
_setValueAttr: function(/*String or Boolean*/ newValue, /*Boolean*/ priorityChange){
// summary:
// Handler for value= attribute to constructor, and also calls to
// attr('value', val).
// description:
// During initialization, just saves as attribute to the .
//
// After initialization,
// when passed a boolean, controls whether or not the CheckBox is checked.
// If passed a string, changes the value attribute of the CheckBox (the one
// specified as "value" when the CheckBox was constructed (ex: )
if(typeof newValue == "string"){
this.value = newValue;
dojo.attr(this.focusNode, 'value', newValue);
newValue = true;
}
if(this._created){
this.set('checked', newValue, priorityChange);
}
},
_getValueAttr: function(){
// summary:
// Hook so attr('value') works.
// description:
// If the CheckBox is checked, returns the value attribute.
// Otherwise returns false.
return (this.checked ? this.value : false);
},
// Override dijit.form.Button._setLabelAttr() since we don't even have a containerNode.
// Normally users won't try to set label, except when CheckBox or RadioButton is the child of a dojox.layout.TabContainer
_setLabelAttr: undefined,
postMixInProperties: function(){
if(this.value == ""){
this.value = "on";
}
// Need to set initial checked state as part of template, so that form submit works.
// dojo.attr(node, "checked", bool) doesn't work on IEuntil node has been attached
// to , see #8666
this.checkedAttrSetting = this.checked ? "checked" : "";
this.inherited(arguments);
},
_fillContent: function(/*DomNode*/ source){
// Override Button::_fillContent() since it doesn't make sense for CheckBox,
// since CheckBox doesn't even have a container
},
reset: function(){
// Override ToggleButton.reset()
this._hasBeenBlurred = false;
this.set('checked', this.params.checked || false);
// Handle unlikely event that the value attribute has changed
this.value = this.params.value || "on";
dojo.attr(this.focusNode, 'value', this.value);
},
_onFocus: function(){
if(this.id){
dojo.query("label[for='"+this.id+"']").addClass("dijitFocusedLabel");
}
this.inherited(arguments);
},
_onBlur: function(){
if(this.id){
dojo.query("label[for='"+this.id+"']").removeClass("dijitFocusedLabel");
}
this.inherited(arguments);
},
_onClick: function(/*Event*/ e){
// summary:
// Internal function to handle click actions - need to check
// readOnly, since button no longer does that check.
if(this.readOnly){
return false;
}
return this.inherited(arguments);
}
}
);
dojo.declare(
"dijit.form.RadioButton",
dijit.form.CheckBox,
{
// summary:
// Same as an HTML radio, but with fancy styling.
type: "radio",
baseClass: "dijitRadio",
_setCheckedAttr: function(/*Boolean*/ value){
// If I am being checked then have to deselect currently checked radio button
this.inherited(arguments);
if(!this._created){ return; }
if(value){
var _this = this;
// search for radio buttons with the same name that need to be unchecked
dojo.query("INPUT[type=radio]", this.focusNode.form || dojo.doc).forEach( // can't use name= since dojo.query doesn't support [] in the name
function(inputNode){
if(inputNode.name == _this.name && inputNode != _this.focusNode && inputNode.form == _this.focusNode.form){
var widget = dijit.getEnclosingWidget(inputNode);
if(widget && widget.checked){
widget.set('checked', false);
}
}
}
);
}
},
_clicked: function(/*Event*/ e){
if(!this.checked){
this.set('checked', true);
}
}
}
);
}
if(!dojo._hasResource["dijit.form._Spinner"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form._Spinner"] = true;
dojo.provide("dijit.form._Spinner");
dojo.declare(
"dijit.form._Spinner",
dijit.form.RangeBoundTextBox,
{
// summary:
// Mixin for validation widgets with a spinner.
// description:
// This class basically (conceptually) extends `dijit.form.ValidationTextBox`.
// It modifies the template to have up/down arrows, and provides related handling code.
// defaultTimeout: Number
// Number of milliseconds before a held arrow key or up/down button becomes typematic
defaultTimeout: 500,
// minimumTimeout: Number
// minimum number of milliseconds that typematic event fires when held key or button is held
minimumTimeout: 10,
// timeoutChangeRate: Number
// Fraction of time used to change the typematic timer between events.
// 1.0 means that each typematic event fires at defaultTimeout intervals.
// < 1.0 means that each typematic event fires at an increasing faster rate.
timeoutChangeRate: 0.90,
// smallDelta: Number
// Adjust the value by this much when spinning using the arrow keys/buttons
smallDelta: 1,
// largeDelta: Number
// Adjust the value by this much when spinning using the PgUp/Dn keys
largeDelta: 10,
templateString: dojo.cache("dijit.form", "templates/Spinner.html", "\n"),
baseClass: "dijitTextBox dijitSpinner",
// Set classes like dijitUpArrowButtonHover or dijitDownArrowButtonActive depending on
// mouse action over specified node
cssStateNodes: {
"upArrowNode": "dijitUpArrowButton",
"downArrowNode": "dijitDownArrowButton"
},
adjust: function(/* Object */ val, /*Number*/ delta){
// summary:
// Overridable function used to adjust a primitive value(Number/Date/...) by the delta amount specified.
// The val is adjusted in a way that makes sense to the object type.
// tags:
// protected extension
return val;
},
_arrowPressed: function(/*Node*/ nodePressed, /*Number*/ direction, /*Number*/ increment){
// summary:
// Handler for arrow button or arrow key being pressed
if(this.disabled || this.readOnly){ return; }
this._setValueAttr(this.adjust(this.get('value'), direction*increment), false);
dijit.selectInputText(this.textbox, this.textbox.value.length);
},
_arrowReleased: function(/*Node*/ node){
// summary:
// Handler for arrow button or arrow key being released
this._wheelTimer = null;
if(this.disabled || this.readOnly){ return; }
},
_typematicCallback: function(/*Number*/ count, /*DOMNode*/ node, /*Event*/ evt){
var inc=this.smallDelta;
if(node == this.textbox){
var k=dojo.keys;
var key = evt.charOrCode;
inc = (key == k.PAGE_UP || key == k.PAGE_DOWN) ? this.largeDelta : this.smallDelta;
node = (key == k.UP_ARROW || key == k.PAGE_UP) ? this.upArrowNode : this.downArrowNode;
}
if(count == -1){ this._arrowReleased(node); }
else{ this._arrowPressed(node, (node == this.upArrowNode) ? 1 : -1, inc); }
},
_wheelTimer: null,
_mouseWheeled: function(/*Event*/ evt){
// summary:
// Mouse wheel listener where supported
dojo.stopEvent(evt);
// FIXME: Safari bubbles
// be nice to DOH and scroll as much as the event says to
var scrollAmount = evt.detail ? (evt.detail * -1) : (evt.wheelDelta / 120);
if(scrollAmount !== 0){
var node = this[(scrollAmount > 0 ? "upArrowNode" : "downArrowNode" )];
this._arrowPressed(node, scrollAmount, this.smallDelta);
if(!this._wheelTimer){
clearTimeout(this._wheelTimer);
}
this._wheelTimer = setTimeout(dojo.hitch(this,"_arrowReleased",node), 50);
}
},
postCreate: function(){
this.inherited(arguments);
// extra listeners
this.connect(this.domNode, !dojo.isMozilla ? "onmousewheel" : 'DOMMouseScroll', "_mouseWheeled");
this._connects.push(dijit.typematic.addListener(this.upArrowNode, this.textbox, {charOrCode:dojo.keys.UP_ARROW,ctrlKey:false,altKey:false,shiftKey:false,metaKey:false}, this, "_typematicCallback", this.timeoutChangeRate, this.defaultTimeout, this.minimumTimeout));
this._connects.push(dijit.typematic.addListener(this.downArrowNode, this.textbox, {charOrCode:dojo.keys.DOWN_ARROW,ctrlKey:false,altKey:false,shiftKey:false,metaKey:false}, this, "_typematicCallback", this.timeoutChangeRate, this.defaultTimeout, this.minimumTimeout));
this._connects.push(dijit.typematic.addListener(this.upArrowNode, this.textbox, {charOrCode:dojo.keys.PAGE_UP,ctrlKey:false,altKey:false,shiftKey:false,metaKey:false}, this, "_typematicCallback", this.timeoutChangeRate, this.defaultTimeout, this.minimumTimeout));
this._connects.push(dijit.typematic.addListener(this.downArrowNode, this.textbox, {charOrCode:dojo.keys.PAGE_DOWN,ctrlKey:false,altKey:false,shiftKey:false,metaKey:false}, this, "_typematicCallback", this.timeoutChangeRate, this.defaultTimeout, this.minimumTimeout));
}
});
}
if(!dojo._hasResource["dojo.number"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.number"] = true;
dojo.provide("dojo.number");
/*=====
dojo.number = {
// summary: localized formatting and parsing routines for Number
}
dojo.number.__FormatOptions = function(){
// pattern: String?
// override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
// with this string. Default value is based on locale. Overriding this property will defeat
// localization. Literal characters in patterns are not supported.
// type: String?
// choose a format type based on the locale from the following:
// decimal, scientific (not yet supported), percent, currency. decimal by default.
// places: Number?
// fixed number of decimal places to show. This overrides any
// information in the provided pattern.
// round: Number?
// 5 rounds to nearest .5; 0 rounds to nearest whole (default). -1
// means do not round.
// locale: String?
// override the locale used to determine formatting rules
// fractional: Boolean?
// If false, show no decimal places, overriding places and pattern settings.
this.pattern = pattern;
this.type = type;
this.places = places;
this.round = round;
this.locale = locale;
this.fractional = fractional;
}
=====*/
dojo.number.format = function(/*Number*/value, /*dojo.number.__FormatOptions?*/options){
// summary:
// Format a Number as a String, using locale-specific settings
// description:
// Create a string from a Number using a known localized pattern.
// Formatting patterns appropriate to the locale are chosen from the
// [Common Locale Data Repository](http://unicode.org/cldr) as well as the appropriate symbols and
// delimiters.
// If value is Infinity, -Infinity, or is not a valid JavaScript number, return null.
// value:
// the number to be formatted
options = dojo.mixin({}, options || {});
var locale = dojo.i18n.normalizeLocale(options.locale),
bundle = dojo.i18n.getLocalization("dojo.cldr", "number", locale);
options.customs = bundle;
var pattern = options.pattern || bundle[(options.type || "decimal") + "Format"];
if(isNaN(value) || Math.abs(value) == Infinity){ return null; } // null
return dojo.number._applyPattern(value, pattern, options); // String
};
//dojo.number._numberPatternRE = /(?:[#0]*,?)*[#0](?:\.0*#*)?/; // not precise, but good enough
dojo.number._numberPatternRE = /[#0,]*[#0](?:\.0*#*)?/; // not precise, but good enough
dojo.number._applyPattern = function(/*Number*/value, /*String*/pattern, /*dojo.number.__FormatOptions?*/options){
// summary:
// Apply pattern to format value as a string using options. Gives no
// consideration to local customs.
// value:
// the number to be formatted.
// pattern:
// a pattern string as described by
// [unicode.org TR35](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
// options: dojo.number.__FormatOptions?
// _applyPattern is usually called via `dojo.number.format()` which
// populates an extra property in the options parameter, "customs".
// The customs object specifies group and decimal parameters if set.
//TODO: support escapes
options = options || {};
var group = options.customs.group,
decimal = options.customs.decimal,
patternList = pattern.split(';'),
positivePattern = patternList[0];
pattern = patternList[(value < 0) ? 1 : 0] || ("-" + positivePattern);
//TODO: only test against unescaped
if(pattern.indexOf('%') != -1){
value *= 100;
}else if(pattern.indexOf('\u2030') != -1){
value *= 1000; // per mille
}else if(pattern.indexOf('\u00a4') != -1){
group = options.customs.currencyGroup || group;//mixins instead?
decimal = options.customs.currencyDecimal || decimal;// Should these be mixins instead?
pattern = pattern.replace(/\u00a4{1,3}/, function(match){
var prop = ["symbol", "currency", "displayName"][match.length-1];
return options[prop] || options.currency || "";
});
}else if(pattern.indexOf('E') != -1){
throw new Error("exponential notation not supported");
}
//TODO: support @ sig figs?
var numberPatternRE = dojo.number._numberPatternRE;
var numberPattern = positivePattern.match(numberPatternRE);
if(!numberPattern){
throw new Error("unable to find a number expression in pattern: "+pattern);
}
if(options.fractional === false){ options.places = 0; }
return pattern.replace(numberPatternRE,
dojo.number._formatAbsolute(value, numberPattern[0], {decimal: decimal, group: group, places: options.places, round: options.round}));
}
dojo.number.round = function(/*Number*/value, /*Number?*/places, /*Number?*/increment){
// summary:
// Rounds to the nearest value with the given number of decimal places, away from zero
// description:
// Rounds to the nearest value with the given number of decimal places, away from zero if equal.
// Similar to Number.toFixed(), but compensates for browser quirks. Rounding can be done by
// fractional increments also, such as the nearest quarter.
// NOTE: Subject to floating point errors. See dojox.math.round for experimental workaround.
// value:
// The number to round
// places:
// The number of decimal places where rounding takes place. Defaults to 0 for whole rounding.
// Must be non-negative.
// increment:
// Rounds next place to nearest value of increment/10. 10 by default.
// example:
// >>> dojo.number.round(-0.5)
// -1
// >>> dojo.number.round(162.295, 2)
// 162.29 // note floating point error. Should be 162.3
// >>> dojo.number.round(10.71, 0, 2.5)
// 10.75
var factor = 10 / (increment || 10);
return (factor * +value).toFixed(places) / factor; // Number
}
if((0.9).toFixed() == 0){
// (isIE) toFixed() bug workaround: Rounding fails on IE when most significant digit
// is just after the rounding place and is >=5
(function(){
var round = dojo.number.round;
dojo.number.round = function(v, p, m){
var d = Math.pow(10, -p || 0), a = Math.abs(v);
if(!v || a >= d || a * Math.pow(10, p + 1) < 5){
d = 0;
}
return round(v, p, m) + (v > 0 ? d : -d);
}
})();
}
/*=====
dojo.number.__FormatAbsoluteOptions = function(){
// decimal: String?
// the decimal separator
// group: String?
// the group separator
// places: Number?|String?
// number of decimal places. the range "n,m" will format to m places.
// round: Number?
// 5 rounds to nearest .5; 0 rounds to nearest whole (default). -1
// means don't round.
this.decimal = decimal;
this.group = group;
this.places = places;
this.round = round;
}
=====*/
dojo.number._formatAbsolute = function(/*Number*/value, /*String*/pattern, /*dojo.number.__FormatAbsoluteOptions?*/options){
// summary:
// Apply numeric pattern to absolute value using options. Gives no
// consideration to local customs.
// value:
// the number to be formatted, ignores sign
// pattern:
// the number portion of a pattern (e.g. `#,##0.00`)
options = options || {};
if(options.places === true){options.places=0;}
if(options.places === Infinity){options.places=6;} // avoid a loop; pick a limit
var patternParts = pattern.split("."),
comma = typeof options.places == "string" && options.places.indexOf(","),
maxPlaces = options.places;
if(comma){
maxPlaces = options.places.substring(comma + 1);
}else if(!(maxPlaces >= 0)){
maxPlaces = (patternParts[1] || []).length;
}
if(!(options.round < 0)){
value = dojo.number.round(value, maxPlaces, options.round);
}
var valueParts = String(Math.abs(value)).split("."),
fractional = valueParts[1] || "";
if(patternParts[1] || options.places){
if(comma){
options.places = options.places.substring(0, comma);
}
// Pad fractional with trailing zeros
var pad = options.places !== undefined ? options.places : (patternParts[1] && patternParts[1].lastIndexOf("0") + 1);
if(pad > fractional.length){
valueParts[1] = dojo.string.pad(fractional, pad, '0', true);
}
// Truncate fractional
if(maxPlaces < fractional.length){
valueParts[1] = fractional.substr(0, maxPlaces);
}
}else{
if(valueParts[1]){ valueParts.pop(); }
}
// Pad whole with leading zeros
var patternDigits = patternParts[0].replace(',', '');
pad = patternDigits.indexOf("0");
if(pad != -1){
pad = patternDigits.length - pad;
if(pad > valueParts[0].length){
valueParts[0] = dojo.string.pad(valueParts[0], pad);
}
// Truncate whole
if(patternDigits.indexOf("#") == -1){
valueParts[0] = valueParts[0].substr(valueParts[0].length - pad);
}
}
// Add group separators
var index = patternParts[0].lastIndexOf(','),
groupSize, groupSize2;
if(index != -1){
groupSize = patternParts[0].length - index - 1;
var remainder = patternParts[0].substr(0, index);
index = remainder.lastIndexOf(',');
if(index != -1){
groupSize2 = remainder.length - index - 1;
}
}
var pieces = [];
for(var whole = valueParts[0]; whole;){
var off = whole.length - groupSize;
pieces.push((off > 0) ? whole.substr(off) : whole);
whole = (off > 0) ? whole.slice(0, off) : "";
if(groupSize2){
groupSize = groupSize2;
delete groupSize2;
}
}
valueParts[0] = pieces.reverse().join(options.group || ",");
return valueParts.join(options.decimal || ".");
};
/*=====
dojo.number.__RegexpOptions = function(){
// pattern: String?
// override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
// with this string. Default value is based on locale. Overriding this property will defeat
// localization.
// type: String?
// choose a format type based on the locale from the following:
// decimal, scientific (not yet supported), percent, currency. decimal by default.
// locale: String?
// override the locale used to determine formatting rules
// strict: Boolean?
// strict parsing, false by default. Strict parsing requires input as produced by the format() method.
// Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
// places: Number|String?
// number of decimal places to accept: Infinity, a positive number, or
// a range "n,m". Defined by pattern or Infinity if pattern not provided.
this.pattern = pattern;
this.type = type;
this.locale = locale;
this.strict = strict;
this.places = places;
}
=====*/
dojo.number.regexp = function(/*dojo.number.__RegexpOptions?*/options){
// summary:
// Builds the regular needed to parse a number
// description:
// Returns regular expression with positive and negative match, group
// and decimal separators
return dojo.number._parseInfo(options).regexp; // String
}
dojo.number._parseInfo = function(/*Object?*/options){
options = options || {};
var locale = dojo.i18n.normalizeLocale(options.locale),
bundle = dojo.i18n.getLocalization("dojo.cldr", "number", locale),
pattern = options.pattern || bundle[(options.type || "decimal") + "Format"],
//TODO: memoize?
group = bundle.group,
decimal = bundle.decimal,
factor = 1;
if(pattern.indexOf('%') != -1){
factor /= 100;
}else if(pattern.indexOf('\u2030') != -1){
factor /= 1000; // per mille
}else{
var isCurrency = pattern.indexOf('\u00a4') != -1;
if(isCurrency){
group = bundle.currencyGroup || group;
decimal = bundle.currencyDecimal || decimal;
}
}
//TODO: handle quoted escapes
var patternList = pattern.split(';');
if(patternList.length == 1){
patternList.push("-" + patternList[0]);
}
var re = dojo.regexp.buildGroupRE(patternList, function(pattern){
pattern = "(?:"+dojo.regexp.escapeString(pattern, '.')+")";
return pattern.replace(dojo.number._numberPatternRE, function(format){
var flags = {
signed: false,
separator: options.strict ? group : [group,""],
fractional: options.fractional,
decimal: decimal,
exponent: false
},
parts = format.split('.'),
places = options.places;
// special condition for percent (factor != 1)
// allow decimal places even if not specified in pattern
if(parts.length == 1 && factor != 1){
parts[1] = "###";
}
if(parts.length == 1 || places === 0){
flags.fractional = false;
}else{
if(places === undefined){ places = options.pattern ? parts[1].lastIndexOf('0') + 1 : Infinity; }
if(places && options.fractional == undefined){flags.fractional = true;} // required fractional, unless otherwise specified
if(!options.places && (places < parts[1].length)){ places += "," + parts[1].length; }
flags.places = places;
}
var groups = parts[0].split(',');
if(groups.length > 1){
flags.groupSize = groups.pop().length;
if(groups.length > 1){
flags.groupSize2 = groups.pop().length;
}
}
return "("+dojo.number._realNumberRegexp(flags)+")";
});
}, true);
if(isCurrency){
// substitute the currency symbol for the placeholder in the pattern
re = re.replace(/([\s\xa0]*)(\u00a4{1,3})([\s\xa0]*)/g, function(match, before, target, after){
var prop = ["symbol", "currency", "displayName"][target.length-1],
symbol = dojo.regexp.escapeString(options[prop] || options.currency || "");
before = before ? "[\\s\\xa0]" : "";
after = after ? "[\\s\\xa0]" : "";
if(!options.strict){
if(before){before += "*";}
if(after){after += "*";}
return "(?:"+before+symbol+after+")?";
}
return before+symbol+after;
});
}
//TODO: substitute localized sign/percent/permille/etc.?
// normalize whitespace and return
return {regexp: re.replace(/[\xa0 ]/g, "[\\s\\xa0]"), group: group, decimal: decimal, factor: factor}; // Object
}
/*=====
dojo.number.__ParseOptions = function(){
// pattern: String?
// override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
// with this string. Default value is based on locale. Overriding this property will defeat
// localization. Literal characters in patterns are not supported.
// type: String?
// choose a format type based on the locale from the following:
// decimal, scientific (not yet supported), percent, currency. decimal by default.
// locale: String?
// override the locale used to determine formatting rules
// strict: Boolean?
// strict parsing, false by default. Strict parsing requires input as produced by the format() method.
// Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
// fractional: Boolean?|Array?
// Whether to include the fractional portion, where the number of decimal places are implied by pattern
// or explicit 'places' parameter. The value [true,false] makes the fractional portion optional.
this.pattern = pattern;
this.type = type;
this.locale = locale;
this.strict = strict;
this.fractional = fractional;
}
=====*/
dojo.number.parse = function(/*String*/expression, /*dojo.number.__ParseOptions?*/options){
// summary:
// Convert a properly formatted string to a primitive Number, using
// locale-specific settings.
// description:
// Create a Number from a string using a known localized pattern.
// Formatting patterns are chosen appropriate to the locale
// and follow the syntax described by
// [unicode.org TR35](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
// Note that literal characters in patterns are not supported.
// expression:
// A string representation of a Number
var info = dojo.number._parseInfo(options),
results = (new RegExp("^"+info.regexp+"$")).exec(expression);
if(!results){
return NaN; //NaN
}
var absoluteMatch = results[1]; // match for the positive expression
if(!results[1]){
if(!results[2]){
return NaN; //NaN
}
// matched the negative pattern
absoluteMatch =results[2];
info.factor *= -1;
}
// Transform it to something Javascript can parse as a number. Normalize
// decimal point and strip out group separators or alternate forms of whitespace
absoluteMatch = absoluteMatch.
replace(new RegExp("["+info.group + "\\s\\xa0"+"]", "g"), "").
replace(info.decimal, ".");
// Adjust for negative sign, percent, etc. as necessary
return absoluteMatch * info.factor; //Number
};
/*=====
dojo.number.__RealNumberRegexpFlags = function(){
// places: Number?
// The integer number of decimal places or a range given as "n,m". If
// not given, the decimal part is optional and the number of places is
// unlimited.
// decimal: String?
// A string for the character used as the decimal point. Default
// is ".".
// fractional: Boolean?|Array?
// Whether decimal places are used. Can be true, false, or [true,
// false]. Default is [true, false] which means optional.
// exponent: Boolean?|Array?
// Express in exponential notation. Can be true, false, or [true,
// false]. Default is [true, false], (i.e. will match if the
// exponential part is present are not).
// eSigned: Boolean?|Array?
// The leading plus-or-minus sign on the exponent. Can be true,
// false, or [true, false]. Default is [true, false], (i.e. will
// match if it is signed or unsigned). flags in regexp.integer can be
// applied.
this.places = places;
this.decimal = decimal;
this.fractional = fractional;
this.exponent = exponent;
this.eSigned = eSigned;
}
=====*/
dojo.number._realNumberRegexp = function(/*dojo.number.__RealNumberRegexpFlags?*/flags){
// summary:
// Builds a regular expression to match a real number in exponential
// notation
// assign default values to missing parameters
flags = flags || {};
//TODO: use mixin instead?
if(!("places" in flags)){ flags.places = Infinity; }
if(typeof flags.decimal != "string"){ flags.decimal = "."; }
if(!("fractional" in flags) || /^0/.test(flags.places)){ flags.fractional = [true, false]; }
if(!("exponent" in flags)){ flags.exponent = [true, false]; }
if(!("eSigned" in flags)){ flags.eSigned = [true, false]; }
var integerRE = dojo.number._integerRegexp(flags),
decimalRE = dojo.regexp.buildGroupRE(flags.fractional,
function(q){
var re = "";
if(q && (flags.places!==0)){
re = "\\" + flags.decimal;
if(flags.places == Infinity){
re = "(?:" + re + "\\d+)?";
}else{
re += "\\d{" + flags.places + "}";
}
}
return re;
},
true
);
var exponentRE = dojo.regexp.buildGroupRE(flags.exponent,
function(q){
if(q){ return "([eE]" + dojo.number._integerRegexp({ signed: flags.eSigned}) + ")"; }
return "";
}
);
var realRE = integerRE + decimalRE;
// allow for decimals without integers, e.g. .25
if(decimalRE){realRE = "(?:(?:"+ realRE + ")|(?:" + decimalRE + "))";}
return realRE + exponentRE; // String
};
/*=====
dojo.number.__IntegerRegexpFlags = function(){
// signed: Boolean?
// The leading plus-or-minus sign. Can be true, false, or `[true,false]`.
// Default is `[true, false]`, (i.e. will match if it is signed
// or unsigned).
// separator: String?
// The character used as the thousands separator. Default is no
// separator. For more than one symbol use an array, e.g. `[",", ""]`,
// makes ',' optional.
// groupSize: Number?
// group size between separators
// groupSize2: Number?
// second grouping, where separators 2..n have a different interval than the first separator (for India)
this.signed = signed;
this.separator = separator;
this.groupSize = groupSize;
this.groupSize2 = groupSize2;
}
=====*/
dojo.number._integerRegexp = function(/*dojo.number.__IntegerRegexpFlags?*/flags){
// summary:
// Builds a regular expression that matches an integer
// assign default values to missing parameters
flags = flags || {};
if(!("signed" in flags)){ flags.signed = [true, false]; }
if(!("separator" in flags)){
flags.separator = "";
}else if(!("groupSize" in flags)){
flags.groupSize = 3;
}
var signRE = dojo.regexp.buildGroupRE(flags.signed,
function(q){ return q ? "[-+]" : ""; },
true
);
var numberRE = dojo.regexp.buildGroupRE(flags.separator,
function(sep){
if(!sep){
return "(?:\\d+)";
}
sep = dojo.regexp.escapeString(sep);
if(sep == " "){ sep = "\\s"; }
else if(sep == "\xa0"){ sep = "\\s\\xa0"; }
var grp = flags.groupSize, grp2 = flags.groupSize2;
//TODO: should we continue to enforce that numbers with separators begin with 1-9? See #6933
if(grp2){
var grp2RE = "(?:0|[1-9]\\d{0," + (grp2-1) + "}(?:[" + sep + "]\\d{" + grp2 + "})*[" + sep + "]\\d{" + grp + "})";
return ((grp-grp2) > 0) ? "(?:" + grp2RE + "|(?:0|[1-9]\\d{0," + (grp-1) + "}))" : grp2RE;
}
return "(?:0|[1-9]\\d{0," + (grp-1) + "}(?:[" + sep + "]\\d{" + grp + "})*)";
},
true
);
return signRE + numberRE; // String
}
}
if(!dojo._hasResource["dijit.form.NumberTextBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.NumberTextBox"] = true;
dojo.provide("dijit.form.NumberTextBox");
/*=====
dojo.declare(
"dijit.form.NumberTextBox.__Constraints",
[dijit.form.RangeBoundTextBox.__Constraints, dojo.number.__FormatOptions, dojo.number.__ParseOptions], {
// summary:
// Specifies both the rules on valid/invalid values (minimum, maximum,
// number of required decimal places), and also formatting options for
// displaying the value when the field is not focused.
// example:
// Minimum/maximum:
// To specify a field between 0 and 120:
// | {min:0,max:120}
// To specify a field that must be an integer:
// | {fractional:false}
// To specify a field where 0 to 3 decimal places are allowed on input,
// but after the field is blurred the value is displayed with 3 decimal places:
// | {places:'0,3'}
});
=====*/
dojo.declare("dijit.form.NumberTextBoxMixin",
null,
{
// summary:
// A mixin for all number textboxes
// tags:
// protected
// Override ValidationTextBox.regExpGen().... we use a reg-ex generating function rather
// than a straight regexp to deal with locale (plus formatting options too?)
regExpGen: dojo.number.regexp,
/*=====
// constraints: dijit.form.NumberTextBox.__Constraints
// Despite the name, this parameter specifies both constraints on the input
// (including minimum/maximum allowed values) as well as
// formatting options like places (the number of digits to display after
// the decimal point). See `dijit.form.NumberTextBox.__Constraints` for details.
constraints: {},
======*/
// value: Number
// The value of this NumberTextBox as a Javascript Number (i.e., not a String).
// If the displayed value is blank, the value is NaN, and if the user types in
// an gibberish value (like "hello world"), the value is undefined
// (i.e. attr('value') returns undefined).
//
// Symmetrically, attr('value', NaN) will clear the displayed value,
// whereas attr('value', undefined) will have no effect.
value: NaN,
// editOptions: [protected] Object
// Properties to mix into constraints when the value is being edited.
// This is here because we edit the number in the format "12345", which is
// different than the display value (ex: "12,345")
editOptions: { pattern: '#.######' },
/*=====
_formatter: function(value, options){
// summary:
// _formatter() is called by format(). It's the base routine for formatting a number,
// as a string, for example converting 12345 into "12,345".
// value: Number
// The number to be converted into a string.
// options: dojo.number.__FormatOptions?
// Formatting options
// tags:
// protected extension
return "12345"; // String
},
=====*/
_formatter: dojo.number.format,
_setConstraintsAttr: function(/* Object */ constraints){
var places = typeof constraints.places == "number"? constraints.places : 0;
if(places){ places++; } // decimal rounding errors take away another digit of precision
if(typeof constraints.max != "number"){
constraints.max = 9 * Math.pow(10, 15-places);
}
if(typeof constraints.min != "number"){
constraints.min = -9 * Math.pow(10, 15-places);
}
this.inherited(arguments, [ constraints ]);
if(this.focusNode && this.focusNode.value && !isNaN(this.value)){
this.set('value', this.value);
}
},
_onFocus: function(){
if(this.disabled){ return; }
var val = this.get('value');
if(typeof val == "number" && !isNaN(val)){
var formattedValue = this.format(val, this.constraints);
if(formattedValue !== undefined){
this.textbox.value = formattedValue;
}
}
this.inherited(arguments);
},
format: function(/*Number*/ value, /*dojo.number.__FormatOptions*/ constraints){
// summary:
// Formats the value as a Number, according to constraints.
// tags:
// protected
var formattedValue = String(value);
if(typeof value != "number"){ return formattedValue; }
if(isNaN(value)){ return ""; }
// check for exponential notation that dojo.number.format chokes on
if(!("rangeCheck" in this && this.rangeCheck(value, constraints)) && constraints.exponent !== false && /\de[-+]?\d/i.test(formattedValue)){
return formattedValue;
}
if(this.editOptions && this._focused){
constraints = dojo.mixin({}, constraints, this.editOptions);
}
return this._formatter(value, constraints);
},
/*=====
parse: function(value, constraints){
// summary:
// Parses the string value as a Number, according to constraints.
// value: String
// String representing a number
// constraints: dojo.number.__ParseOptions
// Formatting options
// tags:
// protected
return 123.45; // Number
},
=====*/
parse: dojo.number.parse,
_getDisplayedValueAttr: function(){
var v = this.inherited(arguments);
return isNaN(v) ? this.textbox.value : v;
},
filter: function(/*Number*/ value){
// summary:
// This is called with both the display value (string), and the actual value (a number).
// When called with the actual value it does corrections so that '' etc. are represented as NaN.
// Otherwise it dispatches to the superclass's filter() method.
//
// See `dijit.form.TextBox.filter` for more details.
return (value === null || value === '' || value === undefined) ? NaN : this.inherited(arguments); // attr('value', null||''||undefined) should fire onChange(NaN)
},
serialize: function(/*Number*/ value, /*Object?*/options){
// summary:
// Convert value (a Number) into a canonical string (ie, how the number literal is written in javascript/java/C/etc.)
// tags:
// protected
return (typeof value != "number" || isNaN(value)) ? '' : this.inherited(arguments);
},
_setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange, /*String?*/formattedValue){
// summary:
// Hook so attr('value', ...) works.
if(value !== undefined && formattedValue === undefined){
formattedValue = String(value);
if(typeof value == "number"){
if(isNaN(value)){ formattedValue = '' }
// check for exponential notation that dojo.number.format chokes on
else if(("rangeCheck" in this && this.rangeCheck(value, this.constraints)) || this.constraints.exponent === false || !/\de[-+]?\d/i.test(formattedValue)){
formattedValue = undefined; // lets format comnpute a real string value
}
}else if(!value){ // 0 processed in if branch above, ''|null|undefined flow thru here
formattedValue = '';
value = NaN;
}else{ // non-numeric values
value = undefined;
}
}
this.inherited(arguments, [value, priorityChange, formattedValue]);
},
_getValueAttr: function(){
// summary:
// Hook so attr('value') works.
// Returns Number, NaN for '', or undefined for unparsable text
var v = this.inherited(arguments); // returns Number for all values accepted by parse() or NaN for all other displayed values
// If the displayed value of the textbox is gibberish (ex: "hello world"), this.inherited() above
// returns NaN; this if() branch converts the return value to undefined.
// Returning undefined prevents user text from being overwritten when doing _setValueAttr(_getValueAttr()).
// A blank displayed value is still returned as NaN.
if(isNaN(v) && this.textbox.value !== ''){
if(this.constraints.exponent !== false && /\de[-+]?\d/i.test(this.textbox.value) && (new RegExp("^"+dojo.number._realNumberRegexp(dojo.mixin({}, this.constraints))+"$").test(this.textbox.value))){ // check for exponential notation that parse() rejected (erroneously?)
var n = Number(this.textbox.value);
return isNaN(n) ? undefined : n; // return exponential Number or undefined for random text (may not be possible to do with the above RegExp check)
}else{
return undefined; // gibberish
}
}else{
return v; // Number or NaN for ''
}
},
isValid: function(/*Boolean*/ isFocused){
// Overrides dijit.form.RangeBoundTextBox.isValid to check that the editing-mode value is valid since
// it may not be formatted according to the regExp vaidation rules
if(!this._focused || this._isEmpty(this.textbox.value)){
return this.inherited(arguments);
}else{
var v = this.get('value');
if(!isNaN(v) && this.rangeCheck(v, this.constraints)){
if(this.constraints.exponent !== false && /\de[-+]?\d/i.test(this.textbox.value)){ // exponential, parse doesn't like it
return true; // valid exponential number in range
}else{
return this.inherited(arguments);
}
}else{
return false;
}
}
}
}
);
dojo.declare("dijit.form.NumberTextBox",
[dijit.form.RangeBoundTextBox,dijit.form.NumberTextBoxMixin],
{
// summary:
// A TextBox for entering numbers, with formatting and range checking
// description:
// NumberTextBox is a textbox for entering and displaying numbers, supporting
// the following main features:
//
// 1. Enforce minimum/maximum allowed values (as well as enforcing that the user types
// a number rather than a random string)
// 2. NLS support (altering roles of comma and dot as "thousands-separator" and "decimal-point"
// depending on locale).
// 3. Separate modes for editing the value and displaying it, specifically that
// the thousands separator character (typically comma) disappears when editing
// but reappears after the field is blurred.
// 4. Formatting and constraints regarding the number of places (digits after the decimal point)
// allowed on input, and number of places displayed when blurred (see `constraints` parameter).
}
);
}
if(!dojo._hasResource["dijit.form.NumberSpinner"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.NumberSpinner"] = true;
dojo.provide("dijit.form.NumberSpinner");
dojo.declare("dijit.form.NumberSpinner",
[dijit.form._Spinner, dijit.form.NumberTextBoxMixin],
{
// summary:
// Extends NumberTextBox to add up/down arrows and pageup/pagedown for incremental change to the value
//
// description:
// A `dijit.form.NumberTextBox` extension to provide keyboard accessible value selection
// as well as icons for spinning direction. When using the keyboard, the typematic rules
// apply, meaning holding the key will gradually increase or decrease the value and
// accelerate.
//
// example:
// | new dijit.form.NumberSpinner({ constraints:{ max:300, min:100 }}, "someInput");
adjust: function(/* Object */val, /* Number*/delta){
// summary:
// Change Number val by the given amount
// tags:
// protected
var tc = this.constraints,
v = isNaN(val),
gotMax = !isNaN(tc.max),
gotMin = !isNaN(tc.min)
;
if(v && delta != 0){ // blank or invalid value and they want to spin, so create defaults
val = (delta > 0) ?
gotMin ? tc.min : gotMax ? tc.max : 0 :
gotMax ? this.constraints.max : gotMin ? tc.min : 0
;
}
var newval = val + delta;
if(v || isNaN(newval)){ return val; }
if(gotMax && (newval > tc.max)){
newval = tc.max;
}
if(gotMin && (newval < tc.min)){
newval = tc.min;
}
return newval;
},
_onKeyPress: function(e){
if((e.charOrCode == dojo.keys.HOME || e.charOrCode == dojo.keys.END) && !(e.ctrlKey || e.altKey || e.metaKey)
&& typeof this.get('value') != 'undefined' /* gibberish, so HOME and END are default editing keys*/){
var value = this.constraints[(e.charOrCode == dojo.keys.HOME ? "min" : "max")];
if(typeof value == "number"){
this._setValueAttr(value, false);
}
// eat home or end key whether we change the value or not
dojo.stopEvent(e);
}
}
});
}
if(!dojo._hasResource["dojo.cldr.monetary"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.cldr.monetary"] = true;
dojo.provide("dojo.cldr.monetary");
dojo.cldr.monetary.getData = function(/*String*/code){
// summary: A mapping of currency code to currency-specific formatting information. Returns a unique object with properties: places, round.
// code: an [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code
// from http://www.unicode.org/cldr/data/common/supplemental/supplementalData.xml:supplementalData/currencyData/fractions
var placesData = {
ADP:0,AFN:0,ALL:0,AMD:0,BHD:3,BIF:0,BYR:0,CLF:0,CLP:0,
COP:0,CRC:0,DJF:0,ESP:0,GNF:0,GYD:0,HUF:0,IDR:0,IQD:0,
IRR:3,ISK:0,ITL:0,JOD:3,JPY:0,KMF:0,KPW:0,KRW:0,KWD:3,
LAK:0,LBP:0,LUF:0,LYD:3,MGA:0,MGF:0,MMK:0,MNT:0,MRO:0,
MUR:0,OMR:3,PKR:0,PYG:0,RSD:0,RWF:0,SLL:0,SOS:0,STD:0,
SYP:0,TMM:0,TND:3,TRL:0,TZS:0,UGX:0,UZS:0,VND:0,VUV:0,
XAF:0,XOF:0,XPF:0,YER:0,ZMK:0,ZWD:0
};
var roundingData = {CHF:5};
var places = placesData[code], round = roundingData[code];
if(typeof places == "undefined"){ places = 2; }
if(typeof round == "undefined"){ round = 0; }
return {places: places, round: round}; // Object
};
}
if(!dojo._hasResource["dojo.currency"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.currency"] = true;
dojo.provide("dojo.currency");
/*=====
dojo.currency = {
// summary: localized formatting and parsing routines for currencies
//
// description: extends dojo.number to provide culturally-appropriate formatting of values
// in various world currencies, including use of a currency symbol. The currencies are specified
// by a three-letter international symbol in all uppercase, and support for the currencies is
// provided by the data in `dojo.cldr`. The scripts generating dojo.cldr specify which
// currency support is included. A fixed number of decimal places is determined based
// on the currency type and is not determined by the 'pattern' argument. The fractional
// portion is optional, by default, and variable length decimals are not supported.
}
=====*/
dojo.currency._mixInDefaults = function(options){
options = options || {};
options.type = "currency";
// Get locale-dependent currency data, like the symbol
var bundle = dojo.i18n.getLocalization("dojo.cldr", "currency", options.locale) || {};
// Mixin locale-independent currency data, like # of places
var iso = options.currency;
var data = dojo.cldr.monetary.getData(iso);
dojo.forEach(["displayName","symbol","group","decimal"], function(prop){
data[prop] = bundle[iso+"_"+prop];
});
data.fractional = [true, false];
// Mixin with provided options
return dojo.mixin(data, options);
}
/*=====
dojo.declare("dojo.currency.__FormatOptions", [dojo.number.__FormatOptions], {
// type: String?
// Should not be set. Value is assumed to be "currency".
// symbol: String?
// localized currency symbol. The default will be looked up in table of supported currencies in `dojo.cldr`
// A [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code will be used if not found.
// currency: String?
// an [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD".
// For use with dojo.currency only.
// places: Number?
// number of decimal places to show. Default is defined based on which currency is used.
type: "",
symbol: "",
currency: "",
places: ""
});
=====*/
dojo.currency.format = function(/*Number*/value, /*dojo.currency.__FormatOptions?*/options){
// summary:
// Format a Number as a currency, using locale-specific settings
//
// description:
// Create a string from a Number using a known, localized pattern.
// [Formatting patterns](http://www.unicode.org/reports/tr35/#Number_Elements)
// appropriate to the locale are chosen from the [CLDR](http://unicode.org/cldr)
// as well as the appropriate symbols and delimiters and number of decimal places.
//
// value:
// the number to be formatted.
return dojo.number.format(value, dojo.currency._mixInDefaults(options));
}
dojo.currency.regexp = function(/*dojo.number.__RegexpOptions?*/options){
//
// summary:
// Builds the regular needed to parse a currency value
//
// description:
// Returns regular expression with positive and negative match, group and decimal separators
// Note: the options.places default, the number of decimal places to accept, is defined by the currency type.
return dojo.number.regexp(dojo.currency._mixInDefaults(options)); // String
}
/*=====
dojo.declare("dojo.currency.__ParseOptions", [dojo.number.__ParseOptions], {
// type: String?
// Should not be set. Value is assumed to be currency.
// currency: String?
// an [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD".
// For use with dojo.currency only.
// symbol: String?
// localized currency symbol. The default will be looked up in table of supported currencies in `dojo.cldr`
// A [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code will be used if not found.
// places: Number?
// fixed number of decimal places to accept. The default is determined based on which currency is used.
// fractional: Boolean?|Array?
// Whether to include the fractional portion, where the number of decimal places are implied by the currency
// or explicit 'places' parameter. The value [true,false] makes the fractional portion optional.
// By default for currencies, it the fractional portion is optional.
type: "",
currency: "",
symbol: "",
places: "",
fractional: ""
});
=====*/
dojo.currency.parse = function(/*String*/expression, /*dojo.currency.__ParseOptions?*/options){
//
// summary:
// Convert a properly formatted currency string to a primitive Number,
// using locale-specific settings.
//
// description:
// Create a Number from a string using a known, localized pattern.
// [Formatting patterns](http://www.unicode.org/reports/tr35/#Number_Format_Patterns)
// are chosen appropriate to the locale, as well as the appropriate symbols and delimiters
// and number of decimal places.
//
// expression: A string representation of a currency value
return dojo.number.parse(expression, dojo.currency._mixInDefaults(options));
}
}
if(!dojo._hasResource["dijit.form.CurrencyTextBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.CurrencyTextBox"] = true;
dojo.provide("dijit.form.CurrencyTextBox");
/*=====
dojo.declare(
"dijit.form.CurrencyTextBox.__Constraints",
[dijit.form.NumberTextBox.__Constraints, dojo.currency.__FormatOptions, dojo.currency.__ParseOptions], {
// summary:
// Specifies both the rules on valid/invalid values (minimum, maximum,
// number of required decimal places), and also formatting options for
// displaying the value when the field is not focused (currency symbol,
// etc.)
// description:
// Follows the pattern of `dijit.form.NumberTextBox.constraints`.
// In general developers won't need to set this parameter
// example:
// To ensure that the user types in the cents (for example, 1.00 instead of just 1):
// | {fractional:true}
});
=====*/
dojo.declare(
"dijit.form.CurrencyTextBox",
dijit.form.NumberTextBox,
{
// summary:
// A validating currency textbox
// description:
// CurrencyTextBox is similar to `dijit.form.NumberTextBox` but has a few
// extra features related to currency:
//
// 1. After specifying the currency type (american dollars, euros, etc.) it automatically
// sets parse/format options such as how many decimal places to show.
// 2. The currency mark (dollar sign, euro mark, etc.) is displayed when the field is blurred
// but erased during editing, so that the user can just enter a plain number.
// currency: [const] String
// the [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD"
currency: "",
// constraints: dijit.form.CurrencyTextBox.__Constraints
// Despite the name, this parameter specifies both constraints on the input
// (including minimum/maximum allowed values) as well as
// formatting options. See `dijit.form.CurrencyTextBox.__Constraints` for details.
/*=====
constraints: {},
======*/
baseClass: "dijitTextBox dijitCurrencyTextBox",
// Override regExpGen ValidationTextBox.regExpGen().... we use a reg-ex generating function rather
// than a straight regexp to deal with locale (plus formatting options too?)
regExpGen: function(constraints){
// if focused, accept either currency data or NumberTextBox format
return '(' + (this._focused? this.inherited(arguments, [ dojo.mixin({}, constraints, this.editOptions) ]) + '|' : '')
+ dojo.currency.regexp(constraints) + ')';
},
// Override NumberTextBox._formatter to deal with currencies, ex: converts "123.45" to "$123.45"
_formatter: dojo.currency.format,
parse: function(/* String */ value, /* Object */ constraints){
// summary:
// Parses string value as a Currency, according to the constraints object
// tags:
// protected extension
var v = dojo.currency.parse(value, constraints);
if(isNaN(v) && /\d+/.test(value)){ // currency parse failed, but it could be because they are using NumberTextBox format so try its parse
return this.inherited(arguments, [ value, dojo.mixin({}, constraints, this.editOptions) ]);
}
return v;
},
_setConstraintsAttr: function(/* Object */ constraints){
if(!constraints.currency && this.currency){
constraints.currency = this.currency;
}
this.inherited(arguments, [ dojo.currency._mixInDefaults(dojo.mixin(constraints, { exponent: false })) ]); // get places
}
}
);
}
if(!dojo._hasResource["dijit.form.HorizontalSlider"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.HorizontalSlider"] = true;
dojo.provide("dijit.form.HorizontalSlider");
dojo.declare(
"dijit.form.HorizontalSlider",
[dijit.form._FormValueWidget, dijit._Container],
{
// summary:
// A form widget that allows one to select a value with a horizontally draggable handle
templateString: dojo.cache("dijit.form", "templates/HorizontalSlider.html", "\n"),
// Overrides FormValueWidget.value to indicate numeric value
value: 0,
// showButtons: Boolean
// Show increment/decrement buttons at the ends of the slider?
showButtons: true,
// minimum:: Integer
// The minimum value the slider can be set to.
minimum: 0,
// maximum: Integer
// The maximum value the slider can be set to.
maximum: 100,
// discreteValues: Integer
// If specified, indicates that the slider handle has only 'discreteValues' possible positions,
// and that after dragging the handle, it will snap to the nearest possible position.
// Thus, the slider has only 'discreteValues' possible values.
//
// For example, if minimum=10, maxiumum=30, and discreteValues=3, then the slider handle has
// three possible positions, representing values 10, 20, or 30.
//
// If discreteValues is not specified or if it's value is higher than the number of pixels
// in the slider bar, then the slider handle can be moved freely, and the slider's value will be
// computed/reported based on pixel position (in this case it will likely be fractional,
// such as 123.456789).
discreteValues: Infinity,
// pageIncrement: Integer
// If discreteValues is also specified, this indicates the amount of clicks (ie, snap positions)
// that the slider handle is moved via pageup/pagedown keys.
// If discreteValues is not specified, it indicates the number of pixels.
pageIncrement: 2,
// clickSelect: Boolean
// If clicking the slider bar changes the value or not
clickSelect: true,
// slideDuration: Number
// The time in ms to take to animate the slider handle from 0% to 100%,
// when clicking the slider bar to make the handle move.
slideDuration: dijit.defaultDuration,
// Flag to _Templated (TODO: why is this here? I see no widgets in the template.)
widgetsInTemplate: true,
attributeMap: dojo.delegate(dijit.form._FormWidget.prototype.attributeMap, {
id: ""
}),
baseClass: "dijitSlider",
// Apply CSS classes to up/down arrows and handle per mouse state
cssStateNodes: {
incrementButton: "dijitSliderIncrementButton",
decrementButton: "dijitSliderDecrementButton",
focusNode: "dijitSliderThumb"
},
_mousePixelCoord: "pageX",
_pixelCount: "w",
_startingPixelCoord: "x",
_startingPixelCount: "l",
_handleOffsetCoord: "left",
_progressPixelSize: "width",
_onKeyUp: function(/*Event*/ e){
if(this.disabled || this.readOnly || e.altKey || e.ctrlKey || e.metaKey){ return; }
this._setValueAttr(this.value, true);
},
_onKeyPress: function(/*Event*/ e){
if(this.disabled || this.readOnly || e.altKey || e.ctrlKey || e.metaKey){ return; }
switch(e.charOrCode){
case dojo.keys.HOME:
this._setValueAttr(this.minimum, false);
break;
case dojo.keys.END:
this._setValueAttr(this.maximum, false);
break;
// this._descending === false: if ascending vertical (min on top)
// (this._descending || this.isLeftToRight()): if left-to-right horizontal or descending vertical
case ((this._descending || this.isLeftToRight()) ? dojo.keys.RIGHT_ARROW : dojo.keys.LEFT_ARROW):
case (this._descending === false ? dojo.keys.DOWN_ARROW : dojo.keys.UP_ARROW):
case (this._descending === false ? dojo.keys.PAGE_DOWN : dojo.keys.PAGE_UP):
this.increment(e);
break;
case ((this._descending || this.isLeftToRight()) ? dojo.keys.LEFT_ARROW : dojo.keys.RIGHT_ARROW):
case (this._descending === false ? dojo.keys.UP_ARROW : dojo.keys.DOWN_ARROW):
case (this._descending === false ? dojo.keys.PAGE_UP : dojo.keys.PAGE_DOWN):
this.decrement(e);
break;
default:
return;
}
dojo.stopEvent(e);
},
_onHandleClick: function(e){
if(this.disabled || this.readOnly){ return; }
if(!dojo.isIE){
// make sure you get focus when dragging the handle
// (but don't do on IE because it causes a flicker on mouse up (due to blur then focus)
dijit.focus(this.sliderHandle);
}
dojo.stopEvent(e);
},
_isReversed: function(){
// summary:
// Returns true if direction is from right to left
// tags:
// protected extension
return !this.isLeftToRight();
},
_onBarClick: function(e){
if(this.disabled || this.readOnly || !this.clickSelect){ return; }
dijit.focus(this.sliderHandle);
dojo.stopEvent(e);
var abspos = dojo.position(this.sliderBarContainer, true);
var pixelValue = e[this._mousePixelCoord] - abspos[this._startingPixelCoord];
this._setPixelValue(this._isReversed() ? (abspos[this._pixelCount] - pixelValue) : pixelValue, abspos[this._pixelCount], true);
this._movable.onMouseDown(e);
},
_setPixelValue: function(/*Number*/ pixelValue, /*Number*/ maxPixels, /*Boolean, optional*/ priorityChange){
if(this.disabled || this.readOnly){ return; }
pixelValue = pixelValue < 0 ? 0 : maxPixels < pixelValue ? maxPixels : pixelValue;
var count = this.discreteValues;
if(count <= 1 || count == Infinity){ count = maxPixels; }
count--;
var pixelsPerValue = maxPixels / count;
var wholeIncrements = Math.round(pixelValue / pixelsPerValue);
this._setValueAttr((this.maximum-this.minimum)*wholeIncrements/count + this.minimum, priorityChange);
},
_setValueAttr: function(/*Number*/ value, /*Boolean, optional*/ priorityChange){
// summary:
// Hook so attr('value', value) works.
this.valueNode.value = this.value = value;
dijit.setWaiState(this.focusNode, "valuenow", value);
this.inherited(arguments);
var percent = (value - this.minimum) / (this.maximum - this.minimum);
var progressBar = (this._descending === false) ? this.remainingBar : this.progressBar;
var remainingBar = (this._descending === false) ? this.progressBar : this.remainingBar;
if(this._inProgressAnim && this._inProgressAnim.status != "stopped"){
this._inProgressAnim.stop(true);
}
if(priorityChange && this.slideDuration > 0 && progressBar.style[this._progressPixelSize]){
// animate the slider
var _this = this;
var props = {};
var start = parseFloat(progressBar.style[this._progressPixelSize]);
var duration = this.slideDuration * (percent-start/100);
if(duration == 0){ return; }
if(duration < 0){ duration = 0 - duration; }
props[this._progressPixelSize] = { start: start, end: percent*100, units:"%" };
this._inProgressAnim = dojo.animateProperty({ node: progressBar, duration: duration,
onAnimate: function(v){ remainingBar.style[_this._progressPixelSize] = (100-parseFloat(v[_this._progressPixelSize])) + "%"; },
onEnd: function(){ delete _this._inProgressAnim; },
properties: props
})
this._inProgressAnim.play();
}
else{
progressBar.style[this._progressPixelSize] = (percent*100) + "%";
remainingBar.style[this._progressPixelSize] = ((1-percent)*100) + "%";
}
},
_bumpValue: function(signedChange, /*Boolean, optional*/ priorityChange){
if(this.disabled || this.readOnly){ return; }
var s = dojo.getComputedStyle(this.sliderBarContainer);
var c = dojo._getContentBox(this.sliderBarContainer, s);
var count = this.discreteValues;
if(count <= 1 || count == Infinity){ count = c[this._pixelCount]; }
count--;
var value = (this.value - this.minimum) * count / (this.maximum - this.minimum) + signedChange;
if(value < 0){ value = 0; }
if(value > count){ value = count; }
value = value * (this.maximum - this.minimum) / count + this.minimum;
this._setValueAttr(value, priorityChange);
},
_onClkBumper: function(val){
if(this.disabled || this.readOnly || !this.clickSelect){ return; }
this._setValueAttr(val, true);
},
_onClkIncBumper: function(){
this._onClkBumper(this._descending === false ? this.minimum : this.maximum);
},
_onClkDecBumper: function(){
this._onClkBumper(this._descending === false ? this.maximum : this.minimum);
},
decrement: function(/*Event*/ e){
// summary:
// Decrement slider
// tags:
// private
this._bumpValue(e.charOrCode == dojo.keys.PAGE_DOWN ? -this.pageIncrement : -1);
},
increment: function(/*Event*/ e){
// summary:
// Increment slider
// tags:
// private
this._bumpValue(e.charOrCode == dojo.keys.PAGE_UP ? this.pageIncrement : 1);
},
_mouseWheeled: function(/*Event*/ evt){
// summary:
// Event handler for mousewheel where supported
dojo.stopEvent(evt);
var janky = !dojo.isMozilla;
var scroll = evt[(janky ? "wheelDelta" : "detail")] * (janky ? 1 : -1);
this._bumpValue(scroll < 0 ? -1 : 1, true); // negative scroll acts like a decrement
},
startup: function(){
if(this._started){ return; }
dojo.forEach(this.getChildren(), function(child){
if(this[child.container] != this.containerNode){
this[child.container].appendChild(child.domNode);
}
}, this);
this.inherited(arguments);
},
_typematicCallback: function(/*Number*/ count, /*Object*/ button, /*Event*/ e){
if(count == -1){
this._setValueAttr(this.value, true);
}else{
this[(button == (this._descending? this.incrementButton : this.decrementButton)) ? "decrement" : "increment"](e);
}
},
postCreate: function(){
if(this.showButtons){
this.incrementButton.style.display="";
this.decrementButton.style.display="";
this._connects.push(dijit.typematic.addMouseListener(
this.decrementButton, this, "_typematicCallback", 25, 500));
this._connects.push(dijit.typematic.addMouseListener(
this.incrementButton, this, "_typematicCallback", 25, 500));
}
this.connect(this.domNode, !dojo.isMozilla ? "onmousewheel" : "DOMMouseScroll", "_mouseWheeled");
// define a custom constructor for a SliderMover that points back to me
var mover = dojo.declare(dijit.form._SliderMover, {
widget: this
});
this._movable = new dojo.dnd.Moveable(this.sliderHandle, {mover: mover});
// find any associated label element and add to slider focusnode.
var label=dojo.query('label[for="'+this.id+'"]');
if(label.length){
label[0].id = (this.id+"_label");
dijit.setWaiState(this.focusNode, "labelledby", label[0].id);
}
dijit.setWaiState(this.focusNode, "valuemin", this.minimum);
dijit.setWaiState(this.focusNode, "valuemax", this.maximum);
this.inherited(arguments);
this._layoutHackIE7();
},
destroy: function(){
this._movable.destroy();
if(this._inProgressAnim && this._inProgressAnim.status != "stopped"){
this._inProgressAnim.stop(true);
}
this._supportingWidgets = dijit.findWidgets(this.domNode); // tells destroy about pseudo-child widgets (ruler/labels)
this.inherited(arguments);
}
});
dojo.declare("dijit.form._SliderMover",
dojo.dnd.Mover,
{
onMouseMove: function(e){
var widget = this.widget;
var abspos = widget._abspos;
if(!abspos){
abspos = widget._abspos = dojo.position(widget.sliderBarContainer, true);
widget._setPixelValue_ = dojo.hitch(widget, "_setPixelValue");
widget._isReversed_ = widget._isReversed();
}
var pixelValue = e[widget._mousePixelCoord] - abspos[widget._startingPixelCoord];
widget._setPixelValue_(widget._isReversed_ ? (abspos[widget._pixelCount]-pixelValue) : pixelValue, abspos[widget._pixelCount], false);
},
destroy: function(e){
dojo.dnd.Mover.prototype.destroy.apply(this, arguments);
var widget = this.widget;
widget._abspos = null;
widget._setValueAttr(widget.value, true);
}
});
}
if(!dojo._hasResource["dijit._editor.selection"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit._editor.selection"] = true;
dojo.provide("dijit._editor.selection");
// FIXME:
// all of these methods branch internally for IE. This is probably
// sub-optimal in terms of runtime performance. We should investigate the
// size difference for differentiating at definition time.
dojo.mixin(dijit._editor.selection, {
getType: function(){
// summary:
// Get the selection type (like dojo.doc.select.type in IE).
if(dojo.isIE){
return dojo.doc.selection.type.toLowerCase();
}else{
var stype = "text";
// Check if the actual selection is a CONTROL (IMG, TABLE, HR, etc...).
var oSel;
try{
oSel = dojo.global.getSelection();
}catch(e){ /*squelch*/ }
if(oSel && oSel.rangeCount == 1){
var oRange = oSel.getRangeAt(0);
if( (oRange.startContainer == oRange.endContainer) &&
((oRange.endOffset - oRange.startOffset) == 1) &&
(oRange.startContainer.nodeType != 3 /* text node*/)
){
stype = "control";
}
}
return stype; //String
}
},
getSelectedText: function(){
// summary:
// Return the text (no html tags) included in the current selection or null if no text is selected
if(dojo.isIE){
if(dijit._editor.selection.getType() == 'control'){
return null;
}
return dojo.doc.selection.createRange().text;
}else{
var selection = dojo.global.getSelection();
if(selection){
return selection.toString(); //String
}
}
return '';
},
getSelectedHtml: function(){
// summary:
// Return the html text of the current selection or null if unavailable
if(dojo.isIE){
if(dijit._editor.selection.getType() == 'control'){
return null;
}
return dojo.doc.selection.createRange().htmlText;
}else{
var selection = dojo.global.getSelection();
if(selection && selection.rangeCount){
var i;
var html = "";
for(i = 0; i < selection.rangeCount; i++){
//Handle selections spanning ranges, such as Opera
var frag = selection.getRangeAt(i).cloneContents();
var div = dojo.doc.createElement("div");
div.appendChild(frag);
html += div.innerHTML;
}
return html; //String
}
return null;
}
},
getSelectedElement: function(){
// summary:
// Retrieves the selected element (if any), just in the case that
// a single element (object like and image or a table) is
// selected.
if(dijit._editor.selection.getType() == "control"){
if(dojo.isIE){
var range = dojo.doc.selection.createRange();
if(range && range.item){
return dojo.doc.selection.createRange().item(0);
}
}else{
var selection = dojo.global.getSelection();
return selection.anchorNode.childNodes[ selection.anchorOffset ];
}
}
return null;
},
getParentElement: function(){
// summary:
// Get the parent element of the current selection
if(dijit._editor.selection.getType() == "control"){
var p = this.getSelectedElement();
if(p){ return p.parentNode; }
}else{
if(dojo.isIE){
var r = dojo.doc.selection.createRange();
r.collapse(true);
return r.parentElement();
}else{
var selection = dojo.global.getSelection();
if(selection){
var node = selection.anchorNode;
while(node && (node.nodeType != 1)){ // not an element
node = node.parentNode;
}
return node;
}
}
}
return null;
},
hasAncestorElement: function(/*String*/tagName /* ... */){
// summary:
// Check whether current selection has a parent element which is
// of type tagName (or one of the other specified tagName)
// tagName: String
// The tag name to determine if it has an ancestor of.
return this.getAncestorElement.apply(this, arguments) != null; //Boolean
},
getAncestorElement: function(/*String*/tagName /* ... */){
// summary:
// Return the parent element of the current selection which is of
// type tagName (or one of the other specified tagName)
// tagName: String
// The tag name to determine if it has an ancestor of.
var node = this.getSelectedElement() || this.getParentElement();
return this.getParentOfType(node, arguments); //DOMNode
},
isTag: function(/*DomNode*/ node, /*String[]*/ tags){
// summary:
// Function to determine if a node is one of an array of tags.
// node:
// The node to inspect.
// tags:
// An array of tag name strings to check to see if the node matches.
if(node && node.tagName){
var _nlc = node.tagName.toLowerCase();
for(var i=0; i nodes and possibly others ... so
//we use the W3C range API
if(selection.rangeCount){
range = selection.getRangeAt(0);
}else{
range = doc.createRange();
}
range.setStart(element, 0);
range.setEnd(element,(element.nodeType == 3)?element.length:element.childNodes.length);
selection.addRange(range);
}else{
selection.selectAllChildren(element);
}
}
},
selectElement: function(/*DomNode*/element,/*Boolean?*/nochangefocus){
// summary:
// clear previous selection and select element (including all its children)
// element: DOMNode
// The element to select.
// nochangefocus: Boolean
// Boolean indicating if the focus should be changed. IE only.
var range;
var doc = dojo.doc;
var win = dojo.global;
element = dojo.byId(element);
if(dojo.isIE && dojo.body().createTextRange){
try{
range = dojo.body().createControlRange();
range.addElement(element);
if(!nochangefocus){
range.select();
}
}catch(e){
this.selectElementChildren(element,nochangefocus);
}
}else if(dojo.global.getSelection){
var selection = win.getSelection();
range = doc.createRange();
if(selection.removeAllRanges){ // Mozilla
// FIXME: does this work on Safari?
if(dojo.isOpera){
//Opera works if you use the current range on
//the selection if present.
if(selection.getRangeAt(0)){
range = selection.getRangeAt(0);
}
}
range.selectNode(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
},
inSelection: function(node){
// summary:
// This function determines if 'node' is
// in the current selection.
// tags:
// public
if(node){
var newRange;
var doc = dojo.doc;
var range;
if(dojo.global.getSelection){
//WC3
var sel = dojo.global.getSelection();
if(sel && sel.rangeCount > 0){
range = sel.getRangeAt(0);
}
if(range && range.compareBoundaryPoints && doc.createRange){
try{
newRange = doc.createRange();
newRange.setStart(node, 0);
if(range.compareBoundaryPoints(range.START_TO_END, newRange) === 1){
return true;
}
}catch(e){ /* squelch */}
}
}else if(doc.selection){
// Probably IE, so we can't use the range object as the pseudo
// range doesn't implement the boundry checking, we have to
// use IE specific crud.
range = doc.selection.createRange();
try{
newRange = node.ownerDocument.body.createControlRange();
if(newRange){
newRange.addElement(node);
}
}catch(e1){
try{
newRange = node.ownerDocument.body.createTextRange();
newRange.moveToElementText(node);
}catch(e2){/* squelch */}
}
if(range && newRange){
// We can finally compare similar to W3C
if(range.compareEndPoints("EndToStart", newRange) === 1){
return true;
}
}
}
}
return false; // boolean
}
});
}
if(!dojo._hasResource["dijit._editor.range"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit._editor.range"] = true;
dojo.provide("dijit._editor.range");
dijit.range={};
dijit.range.getIndex=function(/*DomNode*/node, /*DomNode*/parent){
// dojo.profile.start("dijit.range.getIndex");
var ret=[], retR=[];
var stop = parent;
var onode = node;
var pnode, n;
while(node != stop){
var i = 0;
pnode = node.parentNode;
while((n=pnode.childNodes[i++])){
if(n === node){
--i;
break;
}
}
//if(i>=pnode.childNodes.length){
//dojo.debug("Error finding index of a node in dijit.range.getIndex");
//}
ret.unshift(i);
retR.unshift(i-pnode.childNodes.length);
node = pnode;
}
//normalized() can not be called so often to prevent
//invalidating selection/range, so we have to detect
//here that any text nodes in a row
if(ret.length > 0 && onode.nodeType == 3){
n = onode.previousSibling;
while(n && n.nodeType == 3){
ret[ret.length-1]--;
n = n.previousSibling;
}
n = onode.nextSibling;
while(n && n.nodeType == 3){
retR[retR.length-1]++;
n = n.nextSibling;
}
}
// dojo.profile.end("dijit.range.getIndex");
return {o: ret, r:retR};
}
dijit.range.getNode = function(/*Array*/index, /*DomNode*/parent){
if(!dojo.isArray(index) || index.length == 0){
return parent;
}
var node = parent;
// if(!node)debugger
dojo.every(index, function(i){
if(i >= 0 && i < node.childNodes.length){
node = node.childNodes[i];
}else{
node = null;
//console.debug('Error: can not find node with index',index,'under parent node',parent );
return false; //terminate dojo.every
}
return true; //carry on the every loop
});
return node;
}
dijit.range.getCommonAncestor = function(n1,n2,root){
root = root||n1.ownerDocument.body;
var getAncestors = function(n){
var as=[];
while(n){
as.unshift(n);
if(n !== root){
n = n.parentNode;
}else{
break;
}
}
return as;
};
var n1as = getAncestors(n1);
var n2as = getAncestors(n2);
var m = Math.min(n1as.length,n2as.length);
var com = n1as[0]; //at least, one element should be in the array: the root (BODY by default)
for(var i=1;i0){
dojo.every(parentNode.childNodes, function(node,i){
var calOffset;
if(node.nodeType != 3){
atmrange.moveToElementText(node);
if(atmrange.compareEndPoints(cmpstr,range) > 0){
//startnode = node.previousSibling;
if(lastNode && lastNode.nodeType == 3){
//where shall we put the start? in the text node or after?
startnode = lastNode;
calOffset = true;
}else{
startnode = parentNode;
startOffset = i;
return false;
}
}else{
if(i == parentNode.childNodes.length-1){
startnode = parentNode;
startOffset = parentNode.childNodes.length;
return false;
}
}
}else{
if(i == parentNode.childNodes.length-1){//at the end of this node
startnode = node;
calOffset = true;
}
}
// try{
if(calOffset && startnode){
var prevnode = dijit.range.adjacentNoneTextNode(startnode)[0];
if(prevnode){
startnode = prevnode.nextSibling;
}else{
startnode = parentNode.firstChild; //firstChild must be a text node
}
var prevnodeobj = dijit.range.adjacentNoneTextNode(startnode);
prevnode = prevnodeobj[0];
var lenoffset = prevnodeobj[1];
if(prevnode){
atmrange.moveToElementText(prevnode);
atmrange.collapse(false);
}else{
atmrange.moveToElementText(parentNode);
}
atmrange.setEndPoint(cmpstr, range);
startOffset = atmrange.text.length-lenoffset;
return false;
}
// }catch(e){ debugger }
lastNode = node;
return true;
});
}else{
startnode = parentNode;
startOffset = 0;
}
//if at the end of startnode and we are dealing with start container, then
//move the startnode to nextSibling if it is a text node
//TODO: do this for end container?
if(!end && startnode.nodeType == 1 && startOffset == startnode.childNodes.length){
var nextnode=startnode.nextSibling;
if(nextnode && nextnode.nodeType == 3){
startnode = nextnode;
startOffset = 0;
}
}
return [startnode, startOffset];
},
setEndPoint: function(range, container, offset){
//text node
var atmrange = range.duplicate(), node, len;
if(container.nodeType!=3){ //normal node
if(offset > 0){
node = container.childNodes[offset-1];
if(node){
if(node.nodeType == 3){
container = node;
offset = node.length;
//pass through
}else{
if(node.nextSibling && node.nextSibling.nodeType == 3){
container=node.nextSibling;
offset=0;
//pass through
}else{
atmrange.moveToElementText(node.nextSibling?node:container);
var parent = node.parentNode;
var tempNode = parent.insertBefore(node.ownerDocument.createTextNode(' '), node.nextSibling);
atmrange.collapse(false);
parent.removeChild(tempNode);
}
}
}
}else{
atmrange.moveToElementText(container);
atmrange.collapse(true);
}
}
if(container.nodeType == 3){
var prevnodeobj = dijit.range.adjacentNoneTextNode(container);
var prevnode = prevnodeobj[0];
len = prevnodeobj[1];
if(prevnode){
atmrange.moveToElementText(prevnode);
atmrange.collapse(false);
//if contentEditable is not inherit, the above collapse won't make the end point
//in the correctly position: it always has a -1 offset, so compensate it
if(prevnode.contentEditable!='inherit'){
len++;
}
}else{
atmrange.moveToElementText(container.parentNode);
atmrange.collapse(true);
}
offset += len;
if(offset>0){
if(atmrange.move('character',offset) != offset){
console.error('Error when moving!');
}
}
}
return atmrange;
},
decomposeTextRange: function(range){
var tmpary = dijit.range.ie.getEndPoint(range);
var startContainer = tmpary[0], startOffset = tmpary[1];
var endContainer = tmpary[0], endOffset = tmpary[1];
if(range.htmlText.length){
if(range.htmlText == range.text){ //in the same text node
endOffset = startOffset+range.text.length;
}else{
tmpary = dijit.range.ie.getEndPoint(range,true);
endContainer = tmpary[0], endOffset = tmpary[1];
// if(startContainer.tagName == "BODY"){
// startContainer = startContainer.firstChild;
// }
}
}
return [startContainer, startOffset, endContainer, endOffset];
},
setRange: function(range, startContainer,
startOffset, endContainer, endOffset, collapsed){
var start=dijit.range.ie.setEndPoint(range, startContainer, startOffset);
range.setEndPoint('StartToStart',start);
if(!collapsed){
var end=dijit.range.ie.setEndPoint(range, endContainer, endOffset);
}
range.setEndPoint('EndToEnd',end || start);
return range;
}
}
dojo.declare("dijit.range.W3CRange",null, {
constructor: function(){
if(arguments.length>0){
this.setStart(arguments[0][0],arguments[0][1]);
this.setEnd(arguments[0][2],arguments[0][3]);
}else{
this.commonAncestorContainer = null;
this.startContainer = null;
this.startOffset = 0;
this.endContainer = null;
this.endOffset = 0;
this.collapsed = true;
}
},
_updateInternal: function(){
if(this.startContainer !== this.endContainer){
this.commonAncestorContainer = dijit.range.getCommonAncestor(this.startContainer, this.endContainer);
}else{
this.commonAncestorContainer = this.startContainer;
}
this.collapsed = (this.startContainer === this.endContainer) && (this.startOffset == this.endOffset);
},
setStart: function(node, offset){
offset=parseInt(offset);
if(this.startContainer === node && this.startOffset == offset){
return;
}
delete this._cachedBookmark;
this.startContainer = node;
this.startOffset = offset;
if(!this.endContainer){
this.setEnd(node, offset);
}else{
this._updateInternal();
}
},
setEnd: function(node, offset){
offset=parseInt(offset);
if(this.endContainer === node && this.endOffset == offset){
return;
}
delete this._cachedBookmark;
this.endContainer = node;
this.endOffset = offset;
if(!this.startContainer){
this.setStart(node, offset);
}else{
this._updateInternal();
}
},
setStartAfter: function(node, offset){
this._setPoint('setStart', node, offset, 1);
},
setStartBefore: function(node, offset){
this._setPoint('setStart', node, offset, 0);
},
setEndAfter: function(node, offset){
this._setPoint('setEnd', node, offset, 1);
},
setEndBefore: function(node, offset){
this._setPoint('setEnd', node, offset, 0);
},
_setPoint: function(what, node, offset, ext){
var index = dijit.range.getIndex(node, node.parentNode).o;
this[what](node.parentNode, index.pop()+ext);
},
_getIERange: function(){
var r = (this._body || this.endContainer.ownerDocument.body).createTextRange();
dijit.range.ie.setRange(r, this.startContainer, this.startOffset, this.endContainer, this.endOffset, this.collapsed);
return r;
},
getBookmark: function(body){
this._getIERange();
return this._cachedBookmark;
},
_select: function(){
var r = this._getIERange();
r.select();
},
deleteContents: function(){
var r = this._getIERange();
r.pasteHTML('');
this.endContainer = this.startContainer;
this.endOffset = this.startOffset;
this.collapsed = true;
},
cloneRange: function(){
var r = new dijit.range.W3CRange([this.startContainer,this.startOffset,
this.endContainer,this.endOffset]);
r._body = this._body;
return r;
},
detach: function(){
this._body = null;
this.commonAncestorContainer = null;
this.startContainer = null;
this.startOffset = 0;
this.endContainer = null;
this.endOffset = 0;
this.collapsed = true;
}
});
} //if(!dijit.range._w3c)
}
if(!dojo._hasResource["dijit._editor.html"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit._editor.html"] = true;
dojo.provide("dijit._editor.html");
dijit._editor.escapeXml=function(/*String*/str, /*Boolean?*/noSingleQuotes){
// summary:
// Adds escape sequences for special characters in XML: &<>"'
// Optionally skips escapes for single quotes
str = str.replace(/&/gm, "&").replace(//gm, ">").replace(/"/gm, """);
if(!noSingleQuotes){
str = str.replace(/'/gm, "'");
}
return str; // string
};
dijit._editor.getNodeHtml=function(/* DomNode */node){
var output;
switch(node.nodeType){
case 1: //element node
var lName = node.nodeName.toLowerCase();
if(!lName || lName.charAt(0) == "/"){
// IE does some strange things with malformed HTML input, like
// treating a close tag without an open tag , as
// a new tag with tagName of /span. Corrupts output HTML, remove
// them. Other browsers don't prefix tags that way, so will
// never show up.
return "";
}
output = '<' + lName;
//store the list of attributes and sort it to have the
//attributes appear in the dictionary order
var attrarray = [];
var attr;
if(dojo.isIE && node.outerHTML){
var s = node.outerHTML;
s = s.substr(0, s.indexOf('>'))
.replace(/(['"])[^"']*\1/g, ''); //to make the following regexp safe
var reg = /(\b\w+)\s?=/g;
var m, key;
while((m = reg.exec(s))){
key = m[1];
if(key.substr(0,3) != '_dj'){
if(key == 'src' || key == 'href'){
if(node.getAttribute('_djrealurl')){
attrarray.push([key,node.getAttribute('_djrealurl')]);
continue;
}
}
var val, match;
switch(key){
case 'style':
val = node.style.cssText.toLowerCase();
break;
case 'class':
val = node.className;
break;
case 'width':
if(lName === "img"){
// This somehow gets lost on IE for IMG tags and the like
// and we have to find it in outerHTML, known IE oddity.
match=/width=(\S+)/i.exec(s);
if(match){
val = match[1];
}
break;
}
case 'height':
if(lName === "img"){
// This somehow gets lost on IE for IMG tags and the like
// and we have to find it in outerHTML, known IE oddity.
match=/height=(\S+)/i.exec(s);
if(match){
val = match[1];
}
break;
}
default:
val = node.getAttribute(key);
}
if(val != null){
attrarray.push([key, val.toString()]);
}
}
}
}else{
var i = 0;
while((attr = node.attributes[i++])){
//ignore all attributes starting with _dj which are
//internal temporary attributes used by the editor
var n = attr.name;
if(n.substr(0,3) != '_dj' /*&&
(attr.specified == undefined || attr.specified)*/){
var v = attr.value;
if(n == 'src' || n == 'href'){
if(node.getAttribute('_djrealurl')){
v = node.getAttribute('_djrealurl');
}
}
attrarray.push([n,v]);
}
}
}
attrarray.sort(function(a,b){
return a[0] < b[0] ? -1 : (a[0] == b[0] ? 0 : 1);
});
var j = 0;
while((attr = attrarray[j++])){
output += ' ' + attr[0] + '="' +
(dojo.isString(attr[1]) ? dijit._editor.escapeXml(attr[1], true) : attr[1]) + '"';
}
if(lName === "script"){
// Browsers handle script tags differently in how you get content,
// but innerHTML always seems to work, so insert its content that way
// Yes, it's bad to allow script tags in the editor code, but some people
// seem to want to do it, so we need to at least return them right.
// other plugins/filters can strip them.
output += '>' + node.innerHTML +'' + lName + '>';
}else{
if(node.childNodes.length){
output += '>' + dijit._editor.getChildrenHtml(node)+'' + lName +'>';
}else{
switch(lName){
case 'br':
case 'hr':
case 'img':
case 'input':
case 'base':
case 'meta':
case 'area':
case 'basefont':
// These should all be singly closed
output += ' />';
break;
default:
// Assume XML style separate closure for everything else.
output += '>' + lName + '>';
}
}
}
break;
case 4: // cdata
case 3: // text
// FIXME:
output = dijit._editor.escapeXml(node.nodeValue, true);
break;
case 8: //comment
// FIXME:
output = '';
break;
default:
output = "";
}
return output;
};
dijit._editor.getChildrenHtml = function(/* DomNode */dom){
// summary:
// Returns the html content of a DomNode and children
var out = "";
if(!dom){ return out; }
var nodes = dom["childNodes"] || dom;
//IE issue.
//If we have an actual node we can check parent relationships on for IE,
//We should check, as IE sometimes builds invalid DOMS. If no parent, we can't check
//And should just process it and hope for the best.
var checkParent = !dojo.isIE || nodes !== dom;
var node, i = 0;
while((node = nodes[i++])){
//IE is broken. DOMs are supposed to be a tree. But in the case of malformed HTML, IE generates a graph
//meaning one node ends up with multiple references (multiple parents). This is totally wrong and invalid, but
//such is what it is. We have to keep track and check for this because otherise the source output HTML will have dups.
//No other browser generates a graph. Leave it to IE to break a fundamental DOM rule. So, we check the parent if we can
//If we can't, nothing more we can do other than walk it.
if(!checkParent || node.parentNode == dom){
out += dijit._editor.getNodeHtml(node);
}
}
return out; // String
};
}
if(!dojo._hasResource["dijit._editor.RichText"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit._editor.RichText"] = true;
dojo.provide("dijit._editor.RichText");
// used to restore content when user leaves this page then comes back
// but do not try doing dojo.doc.write if we are using xd loading.
// dojo.doc.write will only work if RichText.js is included in the dojo.js
// file. If it is included in dojo.js and you want to allow rich text saving
// for back/forward actions, then set dojo.config.allowXdRichTextSave = true.
if(!dojo.config["useXDomain"] || dojo.config["allowXdRichTextSave"]){
if(dojo._postLoad){
(function(){
var savetextarea = dojo.doc.createElement('textarea');
savetextarea.id = dijit._scopeName + "._editor.RichText.savedContent";
dojo.style(savetextarea, {
display:'none',
position:'absolute',
top:"-100px",
height:"3px",
width:"3px"
});
dojo.body().appendChild(savetextarea);
})();
}else{
//dojo.body() is not available before onLoad is fired
try{
dojo.doc.write('');
}catch(e){ }
}
}
dojo.declare("dijit._editor.RichText", [dijit._Widget, dijit._CssStateMixin], {
constructor: function(params){
// summary:
// dijit._editor.RichText is the core of dijit.Editor, which provides basic
// WYSIWYG editing features.
//
// description:
// dijit._editor.RichText is the core of dijit.Editor, which provides basic
// WYSIWYG editing features. It also encapsulates the differences
// of different js engines for various browsers. Do not use this widget
// with an HTML <TEXTAREA> tag, since the browser unescapes XML escape characters,
// like <. This can have unexpected behavior and lead to security issues
// such as scripting attacks.
//
// tags:
// private
// contentPreFilters: Function(String)[]
// Pre content filter function register array.
// these filters will be executed before the actual
// editing area gets the html content.
this.contentPreFilters = [];
// contentPostFilters: Function(String)[]
// post content filter function register array.
// These will be used on the resulting html
// from contentDomPostFilters. The resulting
// content is the final html (returned by getValue()).
this.contentPostFilters = [];
// contentDomPreFilters: Function(DomNode)[]
// Pre content dom filter function register array.
// These filters are applied after the result from
// contentPreFilters are set to the editing area.
this.contentDomPreFilters = [];
// contentDomPostFilters: Function(DomNode)[]
// Post content dom filter function register array.
// These filters are executed on the editing area dom.
// The result from these will be passed to contentPostFilters.
this.contentDomPostFilters = [];
// editingAreaStyleSheets: dojo._URL[]
// array to store all the stylesheets applied to the editing area
this.editingAreaStyleSheets = [];
// Make a copy of this.events before we start writing into it, otherwise we
// will modify the prototype which leads to bad things on pages w/multiple editors
this.events = [].concat(this.events);
this._keyHandlers = {};
this.contentPreFilters.push(dojo.hitch(this, "_preFixUrlAttributes"));
if(dojo.isMoz){
this.contentPreFilters.push(this._normalizeFontStyle);
this.contentPostFilters.push(this._removeMozBogus);
}
if(dojo.isWebKit){
// Try to clean up WebKit bogus artifacts. The inserted classes
// made by WebKit sometimes messes things up.
this.contentPreFilters.push(this._removeWebkitBogus);
this.contentPostFilters.push(this._removeWebkitBogus);
}
if(dojo.isIE){
// IE generates and but we want to normalize to and
this.contentPostFilters.push(this._normalizeFontStyle);
}
//this.contentDomPostFilters.push(this._postDomFixUrlAttributes);
if(params && dojo.isString(params.value)){
this.value = params.value;
}
this.onLoadDeferred = new dojo.Deferred();
},
baseClass: "dijitEditor",
// inheritWidth: Boolean
// whether to inherit the parent's width or simply use 100%
inheritWidth: false,
// focusOnLoad: [deprecated] Boolean
// Focus into this widget when the page is loaded
focusOnLoad: false,
// name: String?
// Specifies the name of a (hidden)