WW-1855 Upgrade bundled Dojo to 0.4.2

git-svn-id: https://svn.apache.org/repos/asf/struts/struts2/trunk@523142 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Musachy Barroso
2007-03-28 02:20:03 +00:00
parent a665f05685
commit d04d3fa173
447 changed files with 50710 additions and 88369 deletions
@@ -5,7 +5,7 @@
<html>
<head>
<title>UI Tags Example</title>
<sx:head />
<sx:head extraLocales="en-us,nl-nl,de-de" />
</head>
<body>
<table>
@@ -16,8 +16,8 @@
<sx:datetimepicker label="US format, empty" name="dddp2" language="en-us" />
<sx:datetimepicker label="US format with initial date of 2006-06-26" name="dddp3" value="2006-06-26" language="en-us" />
<sx:datetimepicker label="With initial date of 1969-04-25 and a custom format dd/MM/yyyy" name="dddp5" value="25/04/1969" displayFormat="dd/MM/yyyy" />
<sx:datetimepicker label="In German" name="dddp7" value="2006-06-28" language="de" />
<sx:datetimepicker label="In Dutch" name="dddp8" value="2006-06-28" language="nl" />
<sx:datetimepicker label="In German" name="dddp7" value="2006-06-28" language="de-de" />
<sx:datetimepicker label="In Dutch" name="dddp8" value="2006-06-28" language="nl-nl" />
<sx:datetimepicker label="US format with initial date of 2006-06-26 and long formatting (parse not supported)" name="dddp12" value="2006-06-26" formatLength="long" language="en-us" />
<sx:datetimepicker label="German format with initial date of 2006-06-26 and long formatting (parse not supported)" name="dddp13" value="2006-06-26" formatLength="long" language="de" />
</table>
@@ -5,7 +5,7 @@
<html>
<head>
<title>UI Tags Example</title>
<sx:head />
<sx:head extraLocales="en-us,nl-nl,de-de"/>
</head>
<body>
<table>
@@ -13,20 +13,20 @@ The text of the AFL and BSD licenses is reproduced below.
The "New" BSD License:
**********************
Copyright (c) 2005, The Dojo Foundation
Copyright (c) 2005-2006, The Dojo Foundation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Dojo Foundation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@@ -100,7 +100,7 @@ problems. You're most likely to find them at:
irc.freenode.net #dojo
Note that 2PM Wed PST in this channel is reserved for a weekly meeting between
Note that 3PM Wed PST in #dojo-meeting is reserved for a weekly meeting between
project developers, although anyone is welcome to participate.
@@ -1,86 +1,35 @@
Files baked into this package:
dojoGuardStart.js,
../src/bootstrap1.js,
../src/loader.js,
dojoGuardEnd.js,
../src/hostenv_browser.js,
../src/bootstrap2.js,
../src/lang/common.js,
../src/lang.js,
../src/dom.js,
../src/html/common.js,
../src/uri/Uri.js,
../src/html/style.js,
../src/html/__package__.js,
../src/html/display.js,
../src/html/layout.js,
../src/html/util.js,
../src/lang/array.js,
../src/gfx/color.js,
../src/lang/func.js,
../src/lfx/Animation.js,
../src/html/color.js,
../src/lfx/html.js,
../src/lfx/__package__.js,
../src/lang/extras.js,
../src/event/common.js,
../src/event/topic.js,
../src/event/browser.js,
../src/event/__package__.js,
../src/logging/Logger.js,
../src/logging/__package__.js,
../src/string/common.js,
../src/string.js,
../src/io/common.js,
../src/string/extras.js,
../src/undo/browser.js,
../src/io/BrowserIO.js,
../src/io/cookie.js,
../src/io/__package__.js,
../src/uri/__package__.js,
../src/io/IframeIO.js,
../src/date.js,
../src/string/Builder.js,
../src/string/__package__.js,
../__package__.js,
../src/AdapterRegistry.js,
../src/json.js,
../src/Deferred.js,
../src/rpc/RpcService.js,
../src/rpc/JsonService.js,
../src/rpc/__package__.js,
../src/xml/Parse.js,
../src/xml/__package__.js,
../src/undo/Manager.js,
../src/undo/__package__.js,
../src/crypto.js,
../src/crypto/MD5.js,
../src/crypto/__package__.js,
../src/collections/Collections.js,
../src/collections/ArrayList.js,
../src/collections/Queue.js,
../src/collections/Stack.js,
../src/lang/declare.js,
../src/dnd/DragAndDrop.js,
../src/dnd/HtmlDragManager.js,
../src/html/selection.js,
../src/html/iframe.js,
../src/dnd/HtmlDragAndDrop.js,
../src/dnd/__package__.js,
../src/ns.js,
../src/widget/Manager.js,
../src/a11y.js,
../src/widget/Widget.js,
../src/widget/Parse.js,
../src/widget/DomWidget.js,
../src/lfx/toggle.js,
../src/widget/HtmlWidget.js,
../src/widget/__package__.js,
../src/math.js,
../src/math/curves.js,
../src/math/points.js,
../src/math/__package__.js
Files baked into this build:
dojoGuardStart.js
../src/bootstrap1.js
../src/loader.js
dojoGuardEnd.js
../src/hostenv_browser.js
../src/lang/common.js
../src/lang/array.js
../src/lang/extras.js
../src/lang/declare.js
../src/lang/func.js
../src/event/common.js
../src/event/topic.js
../src/event/browser.js
../src/event/__package__.js
../src/event.js
../src/string/common.js
../src/string/extras.js
../src/string.js
../src/io/common.js
../src/dom.js
../src/undo/browser.js
../src/io/BrowserIO.js
../src/io/cookie.js
../src/io/__package__.js
../src/io.js
../src/AdapterRegistry.js
../src/json.js
../src/html/common.js
../src/uri/Uri.js
../src/html/style.js
../src/html/__package__.js
../src/html/display.js
../src/html/layout.js
../src/html/util.js
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -10,14 +10,9 @@
var noInit = false;
var domain = "";
// document.domain = "localhost";
function init(){
// parse the query string if there is one to try to get args that
// we can act on
var sparams = document.location.search;
if(sparams.length >= 0){
if(sparams.charAt(0) == "?"){
sparams = sparams.substring(1);
}
function defineParams(sparams){
if(sparams){
var ss = (sparams.indexOf("&amp;") >= 0) ? "&amp;" : "&";
sparams = sparams.split(ss);
for(var x=0; x<sparams.length; x++){
@@ -27,12 +22,46 @@
}
}
}
}
function init(){
// parse the query string if there is one to try to get params that
// we can act on. Also allow params to be in a fragment identifier.
var query = null;
var frag = null;
var url = document.location.href;
var hashIndex = url.indexOf("#");
//Extract fragment identifier
if(hashIndex != -1){
frag = url.substring(hashIndex + 1, url.length);
url = url.substring(0, hashIndex);
}
//Extract querystring
var parts = url.split("?");
if(parts.length == 2){
query = parts[1];
}
defineParams(query);
defineParams(frag);
if(noInit){ return; }
if(domain.length > 0){
document.domain = domain;
}
if((window.parent != window)&&(window.parent["dojo"])){
var hasParentDojo = false;
try{
hasParentDojo = window.parent != window && window.parent["dojo"];
}catch(e){
alert("Initializing iframe_history.html failed. If you are using a cross-domain Dojo build,"
+ " please save iframe_history.html to your domain and set djConfig.dojoIframeHistoryUrl"
+ " to the path on your domain to iframe_history.html");
throw e;
}
if(hasParentDojo){
//Set the page title so IE history shows up with a somewhat correct name.
document.title = window.parent.document.title;
@@ -42,6 +71,7 @@
pdj.undo.browser.iframeLoaded(null, window.location);
}
}
}
// -->
</script>
@@ -10,80 +10,33 @@
dojo.provide("dojo.AdapterRegistry");
dojo.require("dojo.lang.func");
dojo.AdapterRegistry = function(/*boolean, optional*/returnWrappers){
// summary:
// A registry to make contextual calling/searching easier.
// description:
// Objects of this class keep list of arrays in the form [name, check,
// wrap, directReturn] that are used to determine what the contextual
// result of a set of checked arguments is. All check/wrap functions
// in this registry should be of the same arity.
dojo.AdapterRegistry = function (returnWrappers) {
this.pairs = [];
this.returnWrappers = returnWrappers || false;
}
dojo.lang.extend(dojo.AdapterRegistry, {
register: function( /*string*/ name, /*function*/ check, /*function*/ wrap,
/*boolean, optional*/ directReturn,
/*boolean, optional*/ override){
// summary:
// register a check function to determine if the wrap function or
// object gets selected
// name: a way to identify this matcher.
// check:
// a function that arguments are passed to from the adapter's
// match() function. The check function should return true if the
// given arguments are appropriate for the wrap function.
// directReturn:
// If directReturn is true, the value passed in for wrap will be
// returned instead of being called. Alternately, the
// AdapterRegistry can be set globally to "return not call" using
// the returnWrappers property. Either way, this behavior allows
// the registry to act as a "search" function instead of a
// function interception library.
// override:
// If override is given and true, the check function will be given
// highest priority. Otherwise, it will be the lowest priority
// adapter.
var type = (override) ? "unshift" : "push";
this.pairs[type]([name, check, wrap, directReturn]);
},
match: function(/* ... */){
// summary:
// Find an adapter for the given arguments. If no suitable adapter
// is found, throws an exception. match() accepts any number of
// arguments, all of which are passed to all matching functions
// from the registered pairs.
for(var i = 0; i < this.pairs.length; i++){
var pair = this.pairs[i];
if(pair[1].apply(this, arguments)){
if((pair[3])||(this.returnWrappers)){
return pair[2];
}else{
return pair[2].apply(this, arguments);
}
};
dojo.lang.extend(dojo.AdapterRegistry, {register:function (name, check, wrap, directReturn, override) {
var type = (override) ? "unshift" : "push";
this.pairs[type]([name, check, wrap, directReturn]);
}, match:function () {
for (var i = 0; i < this.pairs.length; i++) {
var pair = this.pairs[i];
if (pair[1].apply(this, arguments)) {
if ((pair[3]) || (this.returnWrappers)) {
return pair[2];
} else {
return pair[2].apply(this, arguments);
}
}
throw new Error("No match found");
// dojo.raise("No match found");
},
unregister: function(name){
// summary: Remove a named adapter from the registry
// FIXME: this is kind of a dumb way to handle this. On a large
// registry this will be slow-ish and we can use the name as a lookup
// should we choose to trade memory for speed.
for(var i = 0; i < this.pairs.length; i++){
var pair = this.pairs[i];
if(pair[0] == name){
this.pairs.splice(i, 1);
return true;
}
}
return false;
}
});
throw new Error("No match found");
}, unregister:function (name) {
for (var i = 0; i < this.pairs.length; i++) {
var pair = this.pairs[i];
if (pair[0] == name) {
this.pairs.splice(i, 1);
return true;
}
}
return false;
}});
@@ -10,98 +10,7 @@
dojo.provide("dojo.Deferred");
dojo.require("dojo.lang.func");
dojo.Deferred = function(/* optional */ canceller){
/*
NOTE: this namespace and documentation are imported wholesale
from MochiKit
Encapsulates a sequence of callbacks in response to a value that
may not yet be available. This is modeled after the Deferred class
from Twisted <http://twistedmatrix.com>.
Why do we want this? JavaScript has no threads, and even if it did,
threads are hard. Deferreds are a way of abstracting non-blocking
events, such as the final response to an XMLHttpRequest.
The sequence of callbacks is internally represented as a list
of 2-tuples containing the callback/errback pair. For example,
the following call sequence::
var d = new Deferred();
d.addCallback(myCallback);
d.addErrback(myErrback);
d.addBoth(myBoth);
d.addCallbacks(myCallback, myErrback);
is translated into a Deferred with the following internal
representation::
[
[myCallback, null],
[null, myErrback],
[myBoth, myBoth],
[myCallback, myErrback]
]
The Deferred also keeps track of its current status (fired).
Its status may be one of three things:
-1: no value yet (initial condition)
0: success
1: error
A Deferred will be in the error state if one of the following
three conditions are met:
1. The result given to callback or errback is "instanceof" Error
2. The previous callback or errback raised an exception while
executing
3. The previous callback or errback returned a value "instanceof"
Error
Otherwise, the Deferred will be in the success state. The state of
the Deferred determines the next element in the callback sequence to
run.
When a callback or errback occurs with the example deferred chain,
something equivalent to the following will happen (imagine that
exceptions are caught and returned)::
// d.callback(result) or d.errback(result)
if(!(result instanceof Error)){
result = myCallback(result);
}
if(result instanceof Error){
result = myErrback(result);
}
result = myBoth(result);
if(result instanceof Error){
result = myErrback(result);
}else{
result = myCallback(result);
}
The result is then stored away in case another step is added to the
callback sequence. Since the Deferred already has a value available,
any new callbacks added will be called immediately.
There are two other "advanced" details about this implementation that
are useful:
Callbacks are allowed to return Deferred instances themselves, so you
can build complicated sequences of events with ease.
The creator of the Deferred may specify a canceller. The canceller
is a function that will be called if Deferred.cancel is called before
the Deferred fires. You can use this to implement clean aborting of
an XMLHttpRequest, etc. Note that cancel will fire the deferred with
a CancelledError (unless your canceller returns another kind of
error), so the errbacks should be prepared to handle that error for
cancellable Deferreds.
*/
dojo.Deferred = function (canceller) {
this.chain = [];
this.id = this._nextId();
this.fired = -1;
@@ -110,206 +19,145 @@ dojo.Deferred = function(/* optional */ canceller){
this.canceller = canceller;
this.silentlyCancelled = false;
};
dojo.lang.extend(dojo.Deferred, {
getFunctionFromArgs: function(){
var a = arguments;
if((a[0])&&(!a[1])){
if(dojo.lang.isFunction(a[0])){
return a[0];
}else if(dojo.lang.isString(a[0])){
dojo.lang.extend(dojo.Deferred, {getFunctionFromArgs:function () {
var a = arguments;
if ((a[0]) && (!a[1])) {
if (dojo.lang.isFunction(a[0])) {
return a[0];
} else {
if (dojo.lang.isString(a[0])) {
return dj_global[a[0]];
}
}else if((a[0])&&(a[1])){
}
} else {
if ((a[0]) && (a[1])) {
return dojo.lang.hitch(a[0], a[1]);
}
return null;
},
makeCalled: function() {
var deferred = new dojo.Deferred();
deferred.callback();
return deferred;
},
repr: function(){
var state;
if(this.fired == -1){
state = 'unfired';
}else if(this.fired == 0){
state = 'success';
}
return null;
}, makeCalled:function () {
var deferred = new dojo.Deferred();
deferred.callback();
return deferred;
}, repr:function () {
var state;
if (this.fired == -1) {
state = "unfired";
} else {
if (this.fired == 0) {
state = "success";
} else {
state = 'error';
}
return 'Deferred(' + this.id + ', ' + state + ')';
},
toString: dojo.lang.forward("repr"),
_nextId: (function(){
var n = 1;
return function(){ return n++; };
})(),
cancel: function(){
/***
Cancels a Deferred that has not yet received a value, or is
waiting on another Deferred as its value.
If a canceller is defined, the canceller is called. If the
canceller did not return an error, or there was no canceller,
then the errback chain is started with CancelledError.
***/
if(this.fired == -1){
if (this.canceller){
this.canceller(this);
}else{
this.silentlyCancelled = true;
}
if(this.fired == -1){
this.errback(new Error(this.repr()));
}
}else if( (this.fired == 0)&&
(this.results[0] instanceof dojo.Deferred)){
this.results[0].cancel();
}
},
_pause: function(){
// Used internally to signal that it's waiting on another Deferred
this.paused++;
},
_unpause: function(){
// Used internally to signal that it's no longer waiting on
// another Deferred.
this.paused--;
if ((this.paused == 0) && (this.fired >= 0)) {
this._fire();
}
},
_continue: function(res){
// Used internally when a dependent deferred fires.
this._resback(res);
this._unpause();
},
_resback: function(res){
// The primitive that means either callback or errback
this.fired = ((res instanceof Error) ? 1 : 0);
this.results[this.fired] = res;
this._fire();
},
_check: function(){
if(this.fired != -1){
if(!this.silentlyCancelled){
dojo.raise("already called!");
}
this.silentlyCancelled = false;
return;
}
},
callback: function(res){
/*
Begin the callback sequence with a non-error value.
callback or errback should only be called once on a given
Deferred.
*/
this._check();
this._resback(res);
},
errback: function(res){
// Begin the callback sequence with an error result.
this._check();
if(!(res instanceof Error)){
res = new Error(res);
}
this._resback(res);
},
addBoth: function(cb, cbfn){
/*
Add the same function as both a callback and an errback as the
next element on the callback sequence. This is useful for code
that you want to guarantee to run, e.g. a finalizer.
*/
var enclosed = this.getFunctionFromArgs(cb, cbfn);
if(arguments.length > 2){
enclosed = dojo.lang.curryArguments(null, enclosed, arguments, 2);
}
return this.addCallbacks(enclosed, enclosed);
},
addCallback: function(cb, cbfn){
// Add a single callback to the end of the callback sequence.
var enclosed = this.getFunctionFromArgs(cb, cbfn);
if(arguments.length > 2){
enclosed = dojo.lang.curryArguments(null, enclosed, arguments, 2);
}
return this.addCallbacks(enclosed, null);
},
addErrback: function(cb, cbfn){
// Add a single callback to the end of the callback sequence.
var enclosed = this.getFunctionFromArgs(cb, cbfn);
if(arguments.length > 2){
enclosed = dojo.lang.curryArguments(null, enclosed, arguments, 2);
}
return this.addCallbacks(null, enclosed);
return this.addCallbacks(null, cbfn);
},
addCallbacks: function (cb, eb) {
// Add separate callback and errback to the end of the callback
// sequence.
this.chain.push([cb, eb])
if (this.fired >= 0) {
this._fire();
}
return this;
},
_fire: function(){
// Used internally to exhaust the callback sequence when a result
// is available.
var chain = this.chain;
var fired = this.fired;
var res = this.results[fired];
var self = this;
var cb = null;
while (chain.length > 0 && this.paused == 0) {
// Array
var pair = chain.shift();
var f = pair[fired];
if (f == null) {
continue;
}
try {
res = f(res);
fired = ((res instanceof Error) ? 1 : 0);
if(res instanceof dojo.Deferred) {
cb = function(res){
self._continue(res);
}
this._pause();
}
}catch(err){
fired = 1;
res = err;
}
}
this.fired = fired;
this.results[fired] = res;
if((cb)&&(this.paused)){
// this is for "tail recursion" in case the dependent
// deferred is already fired
res.addBoth(cb);
state = "error";
}
}
});
return "Deferred(" + this.id + ", " + state + ")";
}, toString:dojo.lang.forward("repr"), _nextId:(function () {
var n = 1;
return function () {
return n++;
};
})(), cancel:function () {
if (this.fired == -1) {
if (this.canceller) {
this.canceller(this);
} else {
this.silentlyCancelled = true;
}
if (this.fired == -1) {
this.errback(new Error(this.repr()));
}
} else {
if ((this.fired == 0) && (this.results[0] instanceof dojo.Deferred)) {
this.results[0].cancel();
}
}
}, _pause:function () {
this.paused++;
}, _unpause:function () {
this.paused--;
if ((this.paused == 0) && (this.fired >= 0)) {
this._fire();
}
}, _continue:function (res) {
this._resback(res);
this._unpause();
}, _resback:function (res) {
this.fired = ((res instanceof Error) ? 1 : 0);
this.results[this.fired] = res;
this._fire();
}, _check:function () {
if (this.fired != -1) {
if (!this.silentlyCancelled) {
dojo.raise("already called!");
}
this.silentlyCancelled = false;
return;
}
}, callback:function (res) {
this._check();
this._resback(res);
}, errback:function (res) {
this._check();
if (!(res instanceof Error)) {
res = new Error(res);
}
this._resback(res);
}, addBoth:function (cb, cbfn) {
var enclosed = this.getFunctionFromArgs(cb, cbfn);
if (arguments.length > 2) {
enclosed = dojo.lang.curryArguments(null, enclosed, arguments, 2);
}
return this.addCallbacks(enclosed, enclosed);
}, addCallback:function (cb, cbfn) {
var enclosed = this.getFunctionFromArgs(cb, cbfn);
if (arguments.length > 2) {
enclosed = dojo.lang.curryArguments(null, enclosed, arguments, 2);
}
return this.addCallbacks(enclosed, null);
}, addErrback:function (cb, cbfn) {
var enclosed = this.getFunctionFromArgs(cb, cbfn);
if (arguments.length > 2) {
enclosed = dojo.lang.curryArguments(null, enclosed, arguments, 2);
}
return this.addCallbacks(null, enclosed);
return this.addCallbacks(null, cbfn);
}, addCallbacks:function (cb, eb) {
this.chain.push([cb, eb]);
if (this.fired >= 0) {
this._fire();
}
return this;
}, _fire:function () {
var chain = this.chain;
var fired = this.fired;
var res = this.results[fired];
var self = this;
var cb = null;
while (chain.length > 0 && this.paused == 0) {
var pair = chain.shift();
var f = pair[fired];
if (f == null) {
continue;
}
try {
res = f(res);
fired = ((res instanceof Error) ? 1 : 0);
if (res instanceof dojo.Deferred) {
cb = function (res) {
self._continue(res);
};
this._pause();
}
}
catch (err) {
fired = 1;
res = err;
}
}
this.fired = fired;
this.results[fired] = res;
if ((cb) && (this.paused)) {
res.addBoth(cb);
}
}});
@@ -9,80 +9,67 @@
*/
dojo.require("dojo.Deferred");
dojo.provide("dojo.DeferredList");
dojo.DeferredList = function (list, /*bool?*/ fireOnOneCallback, /*bool?*/ fireOnOneErrback, /*bool?*/ consumeErrors, /*Function?*/ canceller) {
this.list = list;
this.resultList = new Array(this.list.length);
// Deferred init
this.chain = [];
this.id = this._nextId();
this.fired = -1;
this.paused = 0;
this.results = [null, null];
this.canceller = canceller;
this.silentlyCancelled = false;
if (this.list.length === 0 && !fireOnOneCallback) {
this.callback(this.resultList);
}
this.finishedCount = 0;
this.fireOnOneCallback = fireOnOneCallback;
this.fireOnOneErrback = fireOnOneErrback;
this.consumeErrors = consumeErrors;
var index = 0;
var _this = this;
dojo.lang.forEach(this.list, function(d) {
var _index = index;
//dojo.debug("add cb/errb index "+_index);
d.addCallback(function(r) { _this._cbDeferred(_index, true, r) });
d.addErrback(function(r) { _this._cbDeferred(_index, false, r) });
index++;
});
dojo.DeferredList = function (list, fireOnOneCallback, fireOnOneErrback, consumeErrors, canceller) {
this.list = list;
this.resultList = new Array(this.list.length);
this.chain = [];
this.id = this._nextId();
this.fired = -1;
this.paused = 0;
this.results = [null, null];
this.canceller = canceller;
this.silentlyCancelled = false;
if (this.list.length === 0 && !fireOnOneCallback) {
this.callback(this.resultList);
}
this.finishedCount = 0;
this.fireOnOneCallback = fireOnOneCallback;
this.fireOnOneErrback = fireOnOneErrback;
this.consumeErrors = consumeErrors;
var index = 0;
var _this = this;
dojo.lang.forEach(this.list, function (d) {
var _index = index;
d.addCallback(function (r) {
_this._cbDeferred(_index, true, r);
});
d.addErrback(function (r) {
_this._cbDeferred(_index, false, r);
});
index++;
});
};
dojo.inherits(dojo.DeferredList, dojo.Deferred);
dojo.lang.extend(dojo.DeferredList, {
_cbDeferred: function (index, succeeded, result) {
//dojo.debug("Fire "+index+" succ "+succeeded+" res "+result);
this.resultList[index] = [succeeded, result];
this.finishedCount += 1;
if (this.fired !== 0) {
if (succeeded && this.fireOnOneCallback) {
this.callback([index, result]);
} else if (!succeeded && this.fireOnOneErrback) {
this.errback(result);
} else if (this.finishedCount == this.list.length) {
this.callback(this.resultList);
}
}
if (!succeeded && this.consumeErrors) {
result = null;
}
return result;
},
gatherResults: function (deferredList) {
var d = new dojo.DeferredList(deferredList, false, true, false);
d.addCallback(function (results) {
var ret = [];
for (var i = 0; i < results.length; i++) {
ret.push(results[i][1]);
}
return ret;
});
return d;
}
});
dojo.lang.extend(dojo.DeferredList, {_cbDeferred:function (index, succeeded, result) {
this.resultList[index] = [succeeded, result];
this.finishedCount += 1;
if (this.fired !== 0) {
if (succeeded && this.fireOnOneCallback) {
this.callback([index, result]);
} else {
if (!succeeded && this.fireOnOneErrback) {
this.errback(result);
} else {
if (this.finishedCount == this.list.length) {
this.callback(this.resultList);
}
}
}
}
if (!succeeded && this.consumeErrors) {
result = null;
}
return result;
}, gatherResults:function (deferredList) {
var d = new dojo.DeferredList(deferredList, false, true, false);
d.addCallback(function (results) {
var ret = [];
for (var i = 0; i < results.length; i++) {
ret.push(results[i][1]);
}
return ret;
});
return d;
}});
@@ -9,95 +9,44 @@
*/
dojo.provide("dojo.a11y");
dojo.require("dojo.uri.*");
dojo.require("dojo.html.common");
dojo.a11y = {
// imgPath: String path to the test image for determining if images are displayed or not
// doAccessibleCheck: Boolean if true will perform check for need to create accessible widgets
// accessible: Boolean uninitialized when null (accessible check has not been performed)
// if true generate accessible widgets
imgPath:dojo.uri.dojoUri("src/widget/templates/images"),
doAccessibleCheck: true,
accessible: null,
checkAccessible: function(){
// summary:
// perform check for accessibility if accessibility checking is turned
// on and the accessibility test has not been performed yet
if(this.accessible === null){
this.accessible = false; //default
if(this.doAccessibleCheck == true){
this.accessible = this.testAccessible();
}
dojo.a11y = {imgPath:dojo.uri.moduleUri("dojo.widget", "templates/images"), doAccessibleCheck:true, accessible:null, checkAccessible:function () {
if (this.accessible === null) {
this.accessible = false;
if (this.doAccessibleCheck == true) {
this.accessible = this.testAccessible();
}
return this.accessible; /* Boolean */
},
testAccessible: function(){
// summary:
// Always perform the accessibility check to determine if high
// contrast mode is on or display of images are turned off. Currently only checks
// in IE and Mozilla.
this.accessible = false; //default
if (dojo.render.html.ie || dojo.render.html.mozilla){
var div = document.createElement("div");
//div.style.color="rgb(153,204,204)";
div.style.backgroundImage = "url(\"" + this.imgPath + "/tab_close.gif\")";
// must add to hierarchy before can view currentStyle below
dojo.body().appendChild(div);
// in FF and IE the value for the current background style of the added div
// will be "none" in high contrast mode
// in FF the return value will be url(invalid-url:) when running over http
var bkImg = null;
if (window.getComputedStyle ) {
var cStyle = getComputedStyle(div, "");
bkImg = cStyle.getPropertyValue("background-image");
}else{
bkImg = div.currentStyle.backgroundImage;
}
var bUseImgElem = false;
if (bkImg != null && (bkImg == "none" || bkImg == "url(invalid-url:)" )) {
this.accessible = true;
}
/*
if(this.accessible == false && document.images){
// test if images are off in IE
var testImg = new Image();
if(testImg.fileSize) {
testImg.src = this.imgPath + "/tab_close.gif";
if(testImg.fileSize < 0){
this.accessible = true;
}
}
}*/
dojo.body().removeChild(div);
}
return this.accessible; /* Boolean */
},
setCheckAccessible: function(/* Boolean */ bTest){
// summary:
// Set whether or not to check for accessibility mode. Default value
// of module is true - perform check for accessibility modes.
// bTest: Boolean - true to check; false to turn off checking
this.doAccessibleCheck = bTest;
},
setAccessibleMode: function(){
// summary:
// perform the accessibility check and sets the correct mode to load
// a11y widgets. Only runs if test for accessiiblity has not been performed yet.
// Call testAccessible() to force the test.
if (this.accessible === null){
if (this.checkAccessible()){
dojo.render.html.prefixes.unshift("a11y");
}
}
return this.accessible; /* Boolean */
}
};
return this.accessible;
}, testAccessible:function () {
this.accessible = false;
if (dojo.render.html.ie || dojo.render.html.mozilla) {
var div = document.createElement("div");
div.style.backgroundImage = "url(\"" + this.imgPath + "/tab_close.gif\")";
dojo.body().appendChild(div);
var bkImg = null;
if (window.getComputedStyle) {
var cStyle = getComputedStyle(div, "");
bkImg = cStyle.getPropertyValue("background-image");
} else {
bkImg = div.currentStyle.backgroundImage;
}
var bUseImgElem = false;
if (bkImg != null && (bkImg == "none" || bkImg == "url(invalid-url:)")) {
this.accessible = true;
}
dojo.body().removeChild(div);
}
return this.accessible;
}, setCheckAccessible:function (bTest) {
this.doAccessibleCheck = bTest;
}, setAccessibleMode:function () {
if (this.accessible === null) {
if (this.checkAccessible()) {
dojo.render.html.prefixes.unshift("a11y");
}
}
return this.accessible;
}};
//dojo.hostenv.modulesLoadedListeners.unshift(function() { dojo.a11y.setAccessibleMode(); });
//dojo.event.connect("before", dojo.hostenv, "makeWidgets", dojo.a11y, "setAccessibleMode");
@@ -10,5 +10,5 @@
dojo.provide("dojo.animation");
dojo.require("dojo.animation.Animation");
dojo.deprecated("dojo.animation is slated for removal in 0.5; use dojo.lfx instead.", "0.5");
@@ -10,236 +10,169 @@
dojo.provide("dojo.animation.Animation");
dojo.require("dojo.animation.AnimationEvent");
dojo.require("dojo.lang.func");
dojo.require("dojo.math");
dojo.require("dojo.math.curves");
dojo.deprecated("dojo.animation.Animation is slated for removal in 0.5; use dojo.lfx.* instead.", "0.5");
/*
Animation package based off of Dan Pupius' work on Animations:
http://pupius.co.uk/js/Toolkit.Drawing.js
*/
dojo.animation.Animation = function(/*dojo.math.curves.* */ curve, /*int*/ duration, /*Decimal?*/ accel, /*int?*/ repeatCount, /*int?*/ rate) {
// summary: Animation object iterates a set of numbers over a curve for a given amount of time, calling 'onAnimate' at each step.
// curve: Curve to animate over.
// duration: Duration of the animation, in milliseconds.
// accel: Either an integer or curve representing amount of acceleration. (?) Default is linear acceleration.
// repeatCount: Number of times to repeat the animation. Default is 0.
// rate: Time between animation steps, in milliseconds. Default is 25.
// description: Calls the following events: "onBegin", "onAnimate", "onEnd", "onPlay", "onPause", "onStop"
// If the animation implements a "handler" function, that will be called before each event is called.
if(dojo.lang.isArray(curve)) {
// curve: Array
// id: i
dojo.animation.Animation = function (curve, duration, accel, repeatCount, rate) {
if (dojo.lang.isArray(curve)) {
curve = new dojo.math.curves.Line(curve[0], curve[1]);
}
this.curve = curve;
this.duration = duration;
this.repeatCount = repeatCount || 0;
this.rate = rate || 25;
if(accel) {
// accel: Decimal
// id: j
if(dojo.lang.isFunction(accel.getValue)) {
// accel: dojo.math.curves.CatmullRom
// id: k
if (accel) {
if (dojo.lang.isFunction(accel.getValue)) {
this.accel = accel;
} else {
var i = 0.35*accel+0.5; // 0.15 <= i <= 0.85
var i = 0.35 * accel + 0.5;
this.accel = new dojo.math.curves.CatmullRom([[0], [i], [1]], 0.45);
}
}
}
dojo.lang.extend(dojo.animation.Animation, {
// public properties
curve: null,
duration: 0,
repeatCount: 0,
accel: null,
// events
onBegin: null,
onAnimate: null,
onEnd: null,
onPlay: null,
onPause: null,
onStop: null,
handler: null,
// "private" properties
_animSequence: null,
_startTime: null,
_endTime: null,
_lastFrame: null,
_timer: null,
_percent: 0,
_active: false,
_paused: false,
_startRepeatCount: 0,
// public methods
play: function(/*Boolean?*/ gotoStart) {
// summary: Play the animation.
// goToStart: If true, will restart the animation from the beginning.
// Otherwise, starts from current play counter.
// description: Sends an "onPlay" event to any observers.
// Also sends an "onBegin" event if starting from the beginning.
if( gotoStart ) {
clearTimeout(this._timer);
this._active = false;
this._paused = false;
this._percent = 0;
} else if( this._active && !this._paused ) {
return;
}
this._startTime = new Date().valueOf();
if( this._paused ) {
this._startTime -= (this.duration * this._percent / 100);
}
this._endTime = this._startTime + this.duration;
this._lastFrame = this._startTime;
var e = new dojo.animation.AnimationEvent(this, null, this.curve.getValue(this._percent),
this._startTime, this._startTime, this._endTime, this.duration, this._percent, 0);
this._active = true;
this._paused = false;
if( this._percent == 0 ) {
if(!this._startRepeatCount) {
this._startRepeatCount = this.repeatCount;
}
e.type = "begin";
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onBegin == "function") { this.onBegin(e); }
}
e.type = "play";
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onPlay == "function") { this.onPlay(e); }
if(this._animSequence) { this._animSequence._setCurrent(this); }
this._cycle();
},
pause: function() {
// summary: Temporarily stop the animation, leaving the play counter at the current location.
// Resume later with sequence.play()
// description: Sends an "onPause" AnimationEvent to any observers.
};
dojo.lang.extend(dojo.animation.Animation, {curve:null, duration:0, repeatCount:0, accel:null, onBegin:null, onAnimate:null, onEnd:null, onPlay:null, onPause:null, onStop:null, handler:null, _animSequence:null, _startTime:null, _endTime:null, _lastFrame:null, _timer:null, _percent:0, _active:false, _paused:false, _startRepeatCount:0, play:function (gotoStart) {
if (gotoStart) {
clearTimeout(this._timer);
if( !this._active ) { return; }
this._paused = true;
var e = new dojo.animation.AnimationEvent(this, "pause", this.curve.getValue(this._percent),
this._startTime, new Date().valueOf(), this._endTime, this.duration, this._percent, 0);
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onPause == "function") { this.onPause(e); }
},
playPause: function() {
// summary: Toggle between play and paused states.
if( !this._active || this._paused ) {
this.play();
} else {
this.pause();
}
},
gotoPercent: function(/*int*/ pct, /*Boolean*/ andPlay) {
// summary: Set the play counter at a certain point in the animation.
// pct: Point to set the play counter to, expressed as a percentage (0 to 100).
// andPlay: If true, will start the animation at the counter automatically.
clearTimeout(this._timer);
this._active = true;
this._paused = true;
this._percent = pct;
if( andPlay ) { this.play(); }
},
stop: function(/*Boolean?*/ gotoEnd) {
// summary: Stop the animation.
// gotoEnd: If true, will advance play counter to the end before sending the event.
// description: Sends an "onStop" AnimationEvent to any observers.
clearTimeout(this._timer);
var step = this._percent / 100;
if( gotoEnd ) {
step = 1;
}
var e = new dojo.animation.AnimationEvent(this, "stop", this.curve.getValue(step),
this._startTime, new Date().valueOf(), this._endTime, this.duration, this._percent);
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onStop == "function") { this.onStop(e); }
this._active = false;
this._paused = false;
},
status: function() {
// summary: Return the status of the animation.
// description: Returns one of "playing", "paused" or "stopped".
if( this._active ) {
return this._paused ? "paused" : "playing"; /* String */
} else {
return "stopped"; /* String */
this._percent = 0;
} else {
if (this._active && !this._paused) {
return;
}
},
// "private" methods
_cycle: function() {
// summary: Perform once 'cycle' or step of the animation.
clearTimeout(this._timer);
if( this._active ) {
var curr = new Date().valueOf();
var step = (curr - this._startTime) / (this._endTime - this._startTime);
var fps = 1000 / (curr - this._lastFrame);
this._lastFrame = curr;
if( step >= 1 ) {
step = 1;
this._percent = 100;
} else {
this._percent = step * 100;
}
this._startTime = new Date().valueOf();
if (this._paused) {
this._startTime -= (this.duration * this._percent / 100);
}
this._endTime = this._startTime + this.duration;
this._lastFrame = this._startTime;
var e = new dojo.animation.AnimationEvent(this, null, this.curve.getValue(this._percent), this._startTime, this._startTime, this._endTime, this.duration, this._percent, 0);
this._active = true;
this._paused = false;
if (this._percent == 0) {
if (!this._startRepeatCount) {
this._startRepeatCount = this.repeatCount;
}
e.type = "begin";
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onBegin == "function") {
this.onBegin(e);
}
}
e.type = "play";
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onPlay == "function") {
this.onPlay(e);
}
if (this._animSequence) {
this._animSequence._setCurrent(this);
}
this._cycle();
}, pause:function () {
clearTimeout(this._timer);
if (!this._active) {
return;
}
this._paused = true;
var e = new dojo.animation.AnimationEvent(this, "pause", this.curve.getValue(this._percent), this._startTime, new Date().valueOf(), this._endTime, this.duration, this._percent, 0);
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onPause == "function") {
this.onPause(e);
}
}, playPause:function () {
if (!this._active || this._paused) {
this.play();
} else {
this.pause();
}
}, gotoPercent:function (pct, andPlay) {
clearTimeout(this._timer);
this._active = true;
this._paused = true;
this._percent = pct;
if (andPlay) {
this.play();
}
}, stop:function (gotoEnd) {
clearTimeout(this._timer);
var step = this._percent / 100;
if (gotoEnd) {
step = 1;
}
var e = new dojo.animation.AnimationEvent(this, "stop", this.curve.getValue(step), this._startTime, new Date().valueOf(), this._endTime, this.duration, this._percent);
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onStop == "function") {
this.onStop(e);
}
this._active = false;
this._paused = false;
}, status:function () {
if (this._active) {
return this._paused ? "paused" : "playing";
} else {
return "stopped";
}
}, _cycle:function () {
clearTimeout(this._timer);
if (this._active) {
var curr = new Date().valueOf();
var step = (curr - this._startTime) / (this._endTime - this._startTime);
var fps = 1000 / (curr - this._lastFrame);
this._lastFrame = curr;
if (step >= 1) {
step = 1;
this._percent = 100;
} else {
this._percent = step * 100;
}
if (this.accel && this.accel.getValue) {
step = this.accel.getValue(step);
}
var e = new dojo.animation.AnimationEvent(this, "animate", this.curve.getValue(step), this._startTime, curr, this._endTime, this.duration, this._percent, Math.round(fps));
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onAnimate == "function") {
this.onAnimate(e);
}
if (step < 1) {
this._timer = setTimeout(dojo.lang.hitch(this, "_cycle"), this.rate);
} else {
e.type = "end";
this._active = false;
if (typeof this.handler == "function") {
this.handler(e);
}
// Perform accelleration
if(this.accel && this.accel.getValue) {
step = this.accel.getValue(step);
if (typeof this.onEnd == "function") {
this.onEnd(e);
}
var e = new dojo.animation.AnimationEvent(this, "animate", this.curve.getValue(step),
this._startTime, curr, this._endTime, this.duration, this._percent, Math.round(fps));
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onAnimate == "function") { this.onAnimate(e); }
if( step < 1 ) {
this._timer = setTimeout(dojo.lang.hitch(this, "_cycle"), this.rate);
if (this.repeatCount > 0) {
this.repeatCount--;
this.play(true);
} else {
e.type = "end";
this._active = false;
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onEnd == "function") { this.onEnd(e); }
if( this.repeatCount > 0 ) {
this.repeatCount--;
this.play(true);
} else if( this.repeatCount == -1 ) {
if (this.repeatCount == -1) {
this.play(true);
} else {
if(this._startRepeatCount) {
if (this._startRepeatCount) {
this.repeatCount = this._startRepeatCount;
this._startRepeatCount = 0;
}
if( this._animSequence ) {
if (this._animSequence) {
this._animSequence._playNext();
}
}
}
}
}
});
}});
@@ -10,55 +10,26 @@
dojo.provide("dojo.animation.AnimationEvent");
dojo.require("dojo.lang.common");
dojo.deprecated("dojo.animation.AnimationEvent is slated for removal in 0.5; use dojo.lfx.* instead.", "0.5");
dojo.animation.AnimationEvent = function(
/*dojo.animation.Animation*/ animation,
/*String*/type,
/*int[] */ coords,
/*int*/ startTime,
/*int*/ currentTime,
/*int*/ endTime,
/*int*/ duration,
/*int*/ percent,
/*int?*/ fps) {
// summary: Event sent at various points during an Animation.
// animation: Animation throwing the event.
// type: One of: "animate", "begin", "end", "play", "pause" or "stop".
// coords: Current coordinates of the animation.
// startTime: Time the animation was started, as milliseconds.
// currentTime: Time the event was thrown, as milliseconds.
// endTime: Time the animation is expected to complete, as milliseconds.
// duration: Duration of the animation, in milliseconds.
// percent: Percent of the animation that has completed, between 0 and 100.
// fps: Frames currently shown per second. (Only sent for "animate" event).
// description: The AnimationEvent has public properties of the same name as
// all constructor arguments, plus "x", "y" and "z".
this.type = type; // "animate", "begin", "end", "play", "pause", "stop"
dojo.animation.AnimationEvent = function (animation, type, coords, startTime, currentTime, endTime, duration, percent, fps) {
this.type = type;
this.animation = animation;
this.coords = coords;
this.x = coords[0];
this.y = coords[1];
this.z = coords[2];
this.startTime = startTime;
this.currentTime = currentTime;
this.endTime = endTime;
this.duration = duration;
this.percent = percent;
this.fps = fps;
};
dojo.extend(dojo.animation.AnimationEvent, {
coordsAsInts: function() {
// summary: Coerce the coordinates into integers.
var cints = new Array(this.coords.length);
for(var i = 0; i < this.coords.length; i++) {
cints[i] = Math.round(this.coords[i]);
}
return cints;
dojo.extend(dojo.animation.AnimationEvent, {coordsAsInts:function () {
var cints = new Array(this.coords.length);
for (var i = 0; i < this.coords.length; i++) {
cints[i] = Math.round(this.coords[i]);
}
});
return cints;
}});
@@ -11,147 +11,110 @@
dojo.provide("dojo.animation.AnimationSequence");
dojo.require("dojo.animation.AnimationEvent");
dojo.require("dojo.animation.Animation");
dojo.deprecated("dojo.animation.AnimationSequence is slated for removal in 0.5; use dojo.lfx.* instead.", "0.5");
dojo.animation.AnimationSequence = function(/*int?*/ repeatCount){
// summary: Sequence of Animations, played one after the other.
// repeatCount: Number of times to repeat the entire sequence. Default is 0 (play once only).
// description: Calls the following events: "onBegin", "onEnd", "onNext"
// If the animation implements a "handler" function, that will be called before each event is called.
dojo.animation.AnimationSequence = function (repeatCount) {
this._anims = [];
this.repeatCount = repeatCount || 0;
}
dojo.lang.extend(dojo.animation.AnimationSequence, {
repeatCount: 0,
_anims: [],
_currAnim: -1,
onBegin: null,
onEnd: null,
onNext: null,
handler: null,
add: function() {
// summary: Add one or more Animations to the sequence.
// description: args: Animations (dojo.animation.Animation) to add to the sequence.
for(var i = 0; i < arguments.length; i++) {
this._anims.push(arguments[i]);
arguments[i]._animSequence = this;
}
},
remove: function(/*dojo.animation.Animation*/ anim) {
// summary: Remove one particular animation from the sequence.
// amim: Animation to remove.
for(var i = 0; i < this._anims.length; i++) {
if( this._anims[i] == anim ) {
this._anims[i]._animSequence = null;
this._anims.splice(i, 1);
break;
}
}
},
removeAll: function() {
// summary: Remove all animations from the sequence.
for(var i = 0; i < this._anims.length; i++) {
};
dojo.lang.extend(dojo.animation.AnimationSequence, {repeatCount:0, _anims:[], _currAnim:-1, onBegin:null, onEnd:null, onNext:null, handler:null, add:function () {
for (var i = 0; i < arguments.length; i++) {
this._anims.push(arguments[i]);
arguments[i]._animSequence = this;
}
}, remove:function (anim) {
for (var i = 0; i < this._anims.length; i++) {
if (this._anims[i] == anim) {
this._anims[i]._animSequence = null;
this._anims.splice(i, 1);
break;
}
this._anims = [];
this._currAnim = -1;
},
clear: function() {
// summary: Remove all animations from the sequence.
this.removeAll();
},
play: function(/*Boolean?*/ gotoStart) {
// summary: Play the animation sequence.
// gotoStart: If true, will start at the beginning of the first sequence.
// Otherwise, starts at the current play counter of the current animation.
// description: Sends an "onBegin" event to any observers.
if( this._anims.length == 0 ) { return; }
if( gotoStart || !this._anims[this._currAnim] ) {
}
}, removeAll:function () {
for (var i = 0; i < this._anims.length; i++) {
this._anims[i]._animSequence = null;
}
this._anims = [];
this._currAnim = -1;
}, clear:function () {
this.removeAll();
}, play:function (gotoStart) {
if (this._anims.length == 0) {
return;
}
if (gotoStart || !this._anims[this._currAnim]) {
this._currAnim = 0;
}
if (this._anims[this._currAnim]) {
if (this._currAnim == 0) {
var e = {type:"begin", animation:this._anims[this._currAnim]};
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onBegin == "function") {
this.onBegin(e);
}
}
this._anims[this._currAnim].play(gotoStart);
}
}, pause:function () {
if (this._anims[this._currAnim]) {
this._anims[this._currAnim].pause();
}
}, playPause:function () {
if (this._anims.length == 0) {
return;
}
if (this._currAnim == -1) {
this._currAnim = 0;
}
if (this._anims[this._currAnim]) {
this._anims[this._currAnim].playPause();
}
}, stop:function () {
if (this._anims[this._currAnim]) {
this._anims[this._currAnim].stop();
}
}, status:function () {
if (this._anims[this._currAnim]) {
return this._anims[this._currAnim].status();
} else {
return "stopped";
}
}, _setCurrent:function (anim) {
for (var i = 0; i < this._anims.length; i++) {
if (this._anims[i] == anim) {
this._currAnim = i;
break;
}
}
}, _playNext:function () {
if (this._currAnim == -1 || this._anims.length == 0) {
return;
}
this._currAnim++;
if (this._anims[this._currAnim]) {
var e = {type:"next", animation:this._anims[this._currAnim]};
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onNext == "function") {
this.onNext(e);
}
this._anims[this._currAnim].play(true);
} else {
var e = {type:"end", animation:this._anims[this._anims.length - 1]};
if (typeof this.handler == "function") {
this.handler(e);
}
if (typeof this.onEnd == "function") {
this.onEnd(e);
}
if (this.repeatCount > 0) {
this._currAnim = 0;
}
if( this._anims[this._currAnim] ) {
if( this._currAnim == 0 ) {
var e = {type: "begin", animation: this._anims[this._currAnim]};
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onBegin == "function") { this.onBegin(e); }
}
this._anims[this._currAnim].play(gotoStart);
}
},
pause: function() {
// summary: temporarily stop the current animation. Resume later with sequence.play()
if( this._anims[this._currAnim] ) {
this._anims[this._currAnim].pause();
}
},
playPause: function() {
// summary: Toggle between play and paused states.
if( this._anims.length == 0 ) { return; }
if( this._currAnim == -1 ) { this._currAnim = 0; }
if( this._anims[this._currAnim] ) {
this._anims[this._currAnim].playPause();
}
},
stop: function() {
// summary: Stop the current animation.
if( this._anims[this._currAnim] ) {
this._anims[this._currAnim].stop();
}
},
status: function() {
// summary: Return the status of the current animation.
// description: Returns one of "playing", "paused" or "stopped".
if( this._anims[this._currAnim] ) {
return this._anims[this._currAnim].status();
} else {
return "stopped";
}
},
_setCurrent: function(/*dojo.animation.Animation*/ anim) {
// summary: Set the current animation.
// anim: Animation to make current, must have already been added to the sequence.
for(var i = 0; i < this._anims.length; i++) {
if( this._anims[i] == anim ) {
this._currAnim = i;
break;
}
}
},
_playNext: function() {
// summary: Play the next animation in the sequence.
// description: Sends an "onNext" event to any observers.
// Also sends "onEnd" if the last animation is finished.
if( this._currAnim == -1 || this._anims.length == 0 ) { return; }
this._currAnim++;
if( this._anims[this._currAnim] ) {
var e = {type: "next", animation: this._anims[this._currAnim]};
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onNext == "function") { this.onNext(e); }
this.repeatCount--;
this._anims[this._currAnim].play(true);
} else {
var e = {type: "end", animation: this._anims[this._anims.length-1]};
if(typeof this.handler == "function") { this.handler(e); }
if(typeof this.onEnd == "function") { this.onEnd(e); }
if(this.repeatCount > 0) {
this._currAnim = 0;
this.repeatCount--;
this._anims[this._currAnim].play(true);
} else if(this.repeatCount == -1) {
if (this.repeatCount == -1) {
this._currAnim = 0;
this._anims[this._currAnim].play(true);
} else {
@@ -159,4 +122,5 @@ dojo.lang.extend(dojo.animation.AnimationSequence, {
}
}
}
});
}});
@@ -10,7 +10,6 @@
dojo.provide("dojo.animation.Timer");
dojo.require("dojo.lang.timing.Timer");
dojo.deprecated("dojo.animation.Timer is now dojo.lang.timing.Timer", "0.5");
dojo.animation.Timer = dojo.lang.timing.Timer;
@@ -8,13 +8,7 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.kwCompoundRequire({
common: [
"dojo.animation.AnimationEvent",
"dojo.animation.Animation",
"dojo.animation.AnimationSequence"
]
});
dojo.kwCompoundRequire({common:["dojo.animation.AnimationEvent", "dojo.animation.Animation", "dojo.animation.AnimationSequence"]});
dojo.provide("dojo.animation.*");
dojo.deprecated("dojo.Animation.* is slated for removal in 0.5; use dojo.lfx.* instead.", "0.5");
@@ -10,161 +10,66 @@
dojo.provide("dojo.behavior");
dojo.require("dojo.event.*");
dojo.require("dojo.experimental");
dojo.experimental("dojo.behavior");
dojo.behavior = new function(){
function arrIn(obj, name){
if(!obj[name]){ obj[name] = []; }
dojo.behavior = new function () {
function arrIn(obj, name) {
if (!obj[name]) {
obj[name] = [];
}
return obj[name];
}
function forIn(obj, scope, func){
function forIn(obj, scope, func) {
var tmpObj = {};
for(var x in obj){
if(typeof tmpObj[x] == "undefined"){
if(!func){
for (var x in obj) {
if (typeof tmpObj[x] == "undefined") {
if (!func) {
scope(obj[x], x);
}else{
} else {
func.call(scope, obj[x], x);
}
}
}
}
// FIXME: need a better test so we don't exclude nightly Safari's!
this.behaviors = {};
this.add = function(behaviorObj){
/* behavior objects are specified in the following format:
*
* {
* "#id": {
* "found": function(element){
* // ...
* },
*
* "onblah": {targetObj: foo, targetFunc: "bar"},
*
* "onblarg": "/foo/bar/baz/blarg",
*
* "onevent": function(evt){
* },
*
* "onotherevent: function(evt){
* // ...
* }
* },
*
* "#id2": {
* // ...
* },
*
* "#id3": function(element){
* // ...
* },
*
* // publish the match on a topic
* "#id4": "/found/topic/name",
*
* // match all direct descendants
* "#id4 > *": function(element){
* // ...
* },
*
* // match the first child node that's an element
* "#id4 > @firstElement": { ... },
*
* // match the last child node that's an element
* "#id4 > @lastElement": { ... },
*
* // all elements of type tagname
* "tagname": {
* // ...
* },
*
* // maps to roughly:
* // dojo.lang.forEach(body.getElementsByTagName("tagname1"), function(node){
* // dojo.lang.forEach(node.getElementsByTagName("tagname2"), function(node2){
* // dojo.lang.forEach(node2.getElementsByTagName("tagname3", function(node3){
* // // apply rules
* // });
* // });
* // });
* "tagname1 tagname2 tagname3": {
* // ...
* },
*
* ".classname": {
* // ...
* },
*
* "tagname.classname": {
* // ...
* },
* }
*
* The "found" method is a generalized handler that's called as soon
* as the node matches the selector. Rules for values that follow also
* apply to the "found" key.
*
* The "on*" handlers are attached with dojo.event.connect(). If the
* value is not a function but is rather an object, it's assumed to be
* the "other half" of a dojo.event.kwConnect() argument object. It
* may contain any/all properties of such a connection modifier save
* for the sourceObj and sourceFunc properties which are filled in by
* the system automatically. If a string is instead encountered, the
* node publishes the specified event on the topic contained in the
* string value.
*
* If the value corresponding to the ID key is a function and not a
* list, it's treated as though it was the value of "found".
*
*/
this.add = function (behaviorObj) {
var tmpObj = {};
forIn(behaviorObj, this, function(behavior, name){
forIn(behaviorObj, this, function (behavior, name) {
var tBehavior = arrIn(this.behaviors, name);
if((dojo.lang.isString(behavior))||(dojo.lang.isFunction(behavior))){
behavior = { found: behavior };
if ((dojo.lang.isString(behavior)) || (dojo.lang.isFunction(behavior))) {
behavior = {found:behavior};
}
forIn(behavior, function(rule, ruleName){
forIn(behavior, function (rule, ruleName) {
arrIn(tBehavior, ruleName).push(rule);
});
});
}
this.apply = function(){
};
this.apply = function () {
dojo.profile.start("dojo.behavior.apply");
var r = dojo.render.html;
// note, we apply one way for fast queries and one way for slow
// iteration. So be it.
var safariGoodEnough = (!r.safari);
if(r.safari){
// Anything over release #420 should work the fast way
if (r.safari) {
var uas = r.UA.split("AppleWebKit/")[1];
if(parseInt(uas.match(/[0-9.]{3,}/)) >= 420){
if (parseInt(uas.match(/[0-9.]{3,}/)) >= 420) {
safariGoodEnough = true;
}
}
if((dj_undef("behaviorFastParse", djConfig) ? (safariGoodEnough) : djConfig["behaviorFastParse"])){
if ((dj_undef("behaviorFastParse", djConfig) ? (safariGoodEnough) : djConfig["behaviorFastParse"])) {
this.applyFast();
}else{
} else {
this.applySlow();
}
dojo.profile.end("dojo.behavior.apply");
}
};
this.matchCache = {};
this.elementsById = function(id, handleRemoved){
this.elementsById = function (id, handleRemoved) {
var removed = [];
var added = [];
arrIn(this.matchCache, id);
if(handleRemoved){
if (handleRemoved) {
var nodes = this.matchCache[id];
for(var x=0; x<nodes.length; x++){
if(nodes[x].id != ""){
for (var x = 0; x < nodes.length; x++) {
if (nodes[x].id != "") {
removed.push(nodes[x]);
nodes.splice(x, 1);
x--;
@@ -172,69 +77,64 @@ dojo.behavior = new function(){
}
}
var tElem = dojo.byId(id);
while(tElem){
if(!tElem["idcached"]){
while (tElem) {
if (!tElem["idcached"]) {
added.push(tElem);
}
tElem.id = "";
tElem = dojo.byId(id);
}
this.matchCache[id] = this.matchCache[id].concat(added);
dojo.lang.forEach(this.matchCache[id], function(node){
dojo.lang.forEach(this.matchCache[id], function (node) {
node.id = id;
node.idcached = true;
});
return { "removed": removed, "added": added, "match": this.matchCache[id] };
}
this.applyToNode = function(node, action, ruleSetName){
if(typeof action == "string"){
return {"removed":removed, "added":added, "match":this.matchCache[id]};
};
this.applyToNode = function (node, action, ruleSetName) {
if (typeof action == "string") {
dojo.event.topic.registerPublisher(action, node, ruleSetName);
}else if(typeof action == "function"){
if(ruleSetName == "found"){
action(node);
}else{
dojo.event.connect(node, ruleSetName, action);
}
}else{
action.srcObj = node;
action.srcFunc = ruleSetName;
dojo.event.kwConnect(action);
}
}
this.applyFast = function(){
dojo.profile.start("dojo.behavior.applyFast");
// fast DOM queries...wheeee!
forIn(this.behaviors, function(tBehavior, id){
var elems = dojo.behavior.elementsById(id);
dojo.lang.forEach(elems.added,
function(elem){
forIn(tBehavior, function(ruleSet, ruleSetName){
if(dojo.lang.isArray(ruleSet)){
dojo.lang.forEach(ruleSet, function(action){
dojo.behavior.applyToNode(elem, action, ruleSetName);
});
}
});
} else {
if (typeof action == "function") {
if (ruleSetName == "found") {
action(node);
} else {
dojo.event.connect(node, ruleSetName, action);
}
);
} else {
action.srcObj = node;
action.srcFunc = ruleSetName;
dojo.event.kwConnect(action);
}
}
};
this.applyFast = function () {
dojo.profile.start("dojo.behavior.applyFast");
forIn(this.behaviors, function (tBehavior, id) {
var elems = dojo.behavior.elementsById(id);
dojo.lang.forEach(elems.added, function (elem) {
forIn(tBehavior, function (ruleSet, ruleSetName) {
if (dojo.lang.isArray(ruleSet)) {
dojo.lang.forEach(ruleSet, function (action) {
dojo.behavior.applyToNode(elem, action, ruleSetName);
});
}
});
});
});
dojo.profile.end("dojo.behavior.applyFast");
}
this.applySlow = function(){
// iterate. Ugg.
};
this.applySlow = function () {
dojo.profile.start("dojo.behavior.applySlow");
var all = document.getElementsByTagName("*");
var allLen = all.length;
for(var x=0; x<allLen; x++){
for (var x = 0; x < allLen; x++) {
var elem = all[x];
if((elem.id)&&(!elem["behaviorAdded"])&&(this.behaviors[elem.id])){
if ((elem.id) && (!elem["behaviorAdded"]) && (this.behaviors[elem.id])) {
elem["behaviorAdded"] = true;
forIn(this.behaviors[elem.id], function(ruleSet, ruleSetName){
if(dojo.lang.isArray(ruleSet)){
dojo.lang.forEach(ruleSet, function(action){
forIn(this.behaviors[elem.id], function (ruleSet, ruleSetName) {
if (dojo.lang.isArray(ruleSet)) {
dojo.lang.forEach(ruleSet, function (action) {
dojo.behavior.applyToNode(elem, action, ruleSetName);
});
}
@@ -242,7 +142,7 @@ dojo.behavior = new function(){
}
}
dojo.profile.end("dojo.behavior.applySlow");
}
}
};
};
dojo.addOnLoad(dojo.behavior, "apply");
@@ -1,343 +1,158 @@
/**
* @file bootstrap1.js
*
* summary: First file that is loaded that 'bootstraps' the entire dojo library suite.
* note: Must run before hostenv_*.js file.
*
* @author Copyright 2004 Mark D. Anderson (mda@discerning.com)
* TODOC: should the copyright be changed to Dojo Foundation?
* @license Licensed under the Academic Free License 2.1 http://www.opensource.org/licenses/afl-2.1.php
*
* $Id: bootstrap1.js 6258 2006-10-20 03:12:36Z jburke $
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
// TODOC: HOW TO DOC THE BELOW?
// @global: djConfig
// summary:
// Application code can set the global 'djConfig' prior to loading
// the library to override certain global settings for how dojo works.
// description: The variables that can be set are as follows:
// - isDebug: false
// - allowQueryConfig: false
// - baseScriptUri: ""
// - baseRelativePath: ""
// - libraryScriptUri: ""
// - iePreventClobber: false
// - ieClobberMinimal: true
// - locale: undefined
// - extraLocale: undefined
// - preventBackButtonFix: true
// - searchIds: []
// - parseWidgets: true
// TODOC: HOW TO DOC THESE VARIABLES?
// TODOC: IS THIS A COMPLETE LIST?
// note:
// 'djConfig' does not exist under 'dojo.*' so that it can be set before the
// 'dojo' variable exists.
// note:
// Setting any of these variables *after* the library has loaded does nothing at all.
// TODOC: is this still true? Release notes for 0.3 indicated they could be set after load.
//
//TODOC: HOW TO DOC THIS?
// @global: dj_global
// summary:
// an alias for the top-level global object in the host environment
// (e.g., the window object in a browser).
// description:
// Refer to 'dj_global' rather than referring to window to ensure your
// code runs correctly in contexts other than web browsers (eg: Rhino on a server).
var dj_global = this;
//TODOC: HOW TO DOC THIS?
// @global: dj_currentContext
// summary:
// Private global context object. Where 'dj_global' always refers to the boot-time
// global context, 'dj_currentContext' can be modified for temporary context shifting.
// dojo.global() returns dj_currentContext.
// description:
// Refer to dojo.global() rather than referring to dj_global to ensure your
// code runs correctly in managed contexts.
var dj_currentContext = this;
// ****************************************************************
// global public utils
// TODOC: DO WE WANT TO NOTE THAT THESE ARE GLOBAL PUBLIC UTILS?
// ****************************************************************
function dj_undef(/*String*/ name, /*Object?*/ object){
//summary: Returns true if 'name' is defined on 'object' (or globally if 'object' is null).
//description: Note that 'defined' and 'exists' are not the same concept.
return (typeof (object || dj_currentContext)[name] == "undefined"); // Boolean
function dj_undef(name, object) {
return (typeof (object || dj_currentContext)[name] == "undefined");
}
// make sure djConfig is defined
if(dj_undef("djConfig", this)){
var djConfig = {};
if (dj_undef("djConfig", this)) {
var djConfig = {};
}
//TODOC: HOW TO DOC THIS?
// dojo is the root variable of (almost all) our public symbols -- make sure it is defined.
if(dj_undef("dojo", this)){
var dojo = {};
if (dj_undef("dojo", this)) {
var dojo = {};
}
dojo.global = function(){
// summary:
// return the current global context object
// (e.g., the window object in a browser).
// description:
// Refer to 'dojo.global()' rather than referring to window to ensure your
// code runs correctly in contexts other than web browsers (eg: Rhino on a server).
dojo.global = function () {
return dj_currentContext;
}
// Override locale setting, if specified
dojo.locale = djConfig.locale;
//TODOC: HOW TO DOC THIS?
dojo.version = {
// summary: version number of this instance of dojo.
major: 0, minor: 3, patch: 1, flag: "+",
revision: Number("$Rev: 6258 $".match(/[0-9]+/)[0]),
toString: function(){
with(dojo.version){
return major + "." + minor + "." + patch + flag + " (" + revision + ")"; // String
}
};
dojo.locale = djConfig.locale;
dojo.version = {major:0, minor:4, patch:2, flag:"", revision:Number("$Rev: 7616 $".match(/[0-9]+/)[0]), toString:function () {
with (dojo.version) {
return major + "." + minor + "." + patch + flag + " (" + revision + ")";
}
}
dojo.evalProp = function(/*String*/ name, /*Object*/ object, /*Boolean?*/ create){
// summary: Returns 'object[name]'. If not defined and 'create' is true, will return a new Object.
// description:
// Returns null if 'object[name]' is not defined and 'create' is not true.
// Note: 'defined' and 'exists' are not the same concept.
if((!object)||(!name)) return undefined; // undefined
if(!dj_undef(name, object)) return object[name]; // mixed
return (create ? (object[name]={}) : undefined); // mixed
}
dojo.parseObjPath = function(/*String*/ path, /*Object?*/ context, /*Boolean?*/ create){
// summary: Parse string path to an object, and return corresponding object reference and property name.
// description:
// Returns an object with two properties, 'obj' and 'prop'.
// 'obj[prop]' is the reference indicated by 'path'.
// path: Path to an object, in the form "A.B.C".
// context: Object to use as root of path. Defaults to 'dojo.global()'.
// create: If true, Objects will be created at any point along the 'path' that is undefined.
}};
dojo.evalProp = function (name, object, create) {
if ((!object) || (!name)) {
return undefined;
}
if (!dj_undef(name, object)) {
return object[name];
}
return (create ? (object[name] = {}) : undefined);
};
dojo.parseObjPath = function (path, context, create) {
var object = (context || dojo.global());
var names = path.split('.');
var names = path.split(".");
var prop = names.pop();
for (var i=0,l=names.length;i<l && object;i++){
for (var i = 0, l = names.length; i < l && object; i++) {
object = dojo.evalProp(names[i], object, create);
}
return {obj: object, prop: prop}; // Object: {obj: Object, prop: String}
}
dojo.evalObjPath = function(/*String*/ path, /*Boolean?*/ create){
// summary: Return the value of object at 'path' in the global scope, without using 'eval()'.
// path: Path to an object, in the form "A.B.C".
// create: If true, Objects will be created at any point along the 'path' that is undefined.
if(typeof path != "string"){
return dojo.global();
return {obj:object, prop:prop};
};
dojo.evalObjPath = function (path, create) {
if (typeof path != "string") {
return dojo.global();
}
// fast path for no periods
if(path.indexOf('.') == -1){
return dojo.evalProp(path, dojo.global(), create); // mixed
if (path.indexOf(".") == -1) {
return dojo.evalProp(path, dojo.global(), create);
}
//MOW: old 'with' syntax was confusing and would throw an error if parseObjPath returned null.
var ref = dojo.parseObjPath(path, dojo.global(), create);
if(ref){
return dojo.evalProp(ref.prop, ref.obj, create); // mixed
if (ref) {
return dojo.evalProp(ref.prop, ref.obj, create);
}
return null;
}
dojo.errorToString = function(/*Error*/ exception){
// summary: Return an exception's 'message', 'description' or text.
// TODO: overriding Error.prototype.toString won't accomplish this?
// ... since natively generated Error objects do not always reflect such things?
if(!dj_undef("message", exception)){
return exception.message; // String
}else if(!dj_undef("description", exception)){
return exception.description; // String
}else{
return exception; // Error
};
dojo.errorToString = function (exception) {
if (!dj_undef("message", exception)) {
return exception.message;
} else {
if (!dj_undef("description", exception)) {
return exception.description;
} else {
return exception;
}
}
}
dojo.raise = function(/*String*/ message, /*Error?*/ exception){
// summary: Common point for raising exceptions in Dojo to enable logging.
// Throws an error message with text of 'exception' if provided, or
// rethrows exception object.
if(exception){
message = message + ": "+dojo.errorToString(exception);
};
dojo.raise = function (message, exception) {
if (exception) {
message = message + ": " + dojo.errorToString(exception);
} else {
message = dojo.errorToString(message);
}
try {
if (djConfig.isDebug) {
dojo.hostenv.println("FATAL exception raised: " + message);
}
}
catch (e) {
}
// print the message to the user if hostenv.println is defined
try { if(djConfig.isDebug){ dojo.hostenv.println("FATAL exception raised: "+message); } } catch (e) {}
throw exception || Error(message);
};
dojo.debug = function () {
};
dojo.debugShallow = function (obj) {
};
dojo.profile = {start:function () {
}, end:function () {
}, stop:function () {
}, dump:function () {
}};
function dj_eval(scriptFragment) {
return dj_global.eval ? dj_global.eval(scriptFragment) : eval(scriptFragment);
}
//Stub functions so things don't break.
//TODOC: HOW TO DOC THESE?
dojo.debug = function(){};
dojo.debugShallow = function(obj){};
dojo.profile = { start: function(){}, end: function(){}, stop: function(){}, dump: function(){} };
function dj_eval(/*String*/ scriptFragment){
// summary: Perform an evaluation in the global scope. Use this rather than calling 'eval()' directly.
// description: Placed in a separate function to minimize size of trapped evaluation context.
// note:
// - JSC eval() takes an optional second argument which can be 'unsafe'.
// - Mozilla/SpiderMonkey eval() takes an optional second argument which is the
// scope object for new symbols.
return dj_global.eval ? dj_global.eval(scriptFragment) : eval(scriptFragment); // mixed
}
dojo.unimplemented = function(/*String*/ funcname, /*String?*/ extra){
// summary: Throw an exception because some function is not implemented.
// extra: Text to append to the exception message.
dojo.unimplemented = function (funcname, extra) {
var message = "'" + funcname + "' not implemented";
if (extra != null) { message += " " + extra; }
if (extra != null) {
message += " " + extra;
}
dojo.raise(message);
}
dojo.deprecated = function(/*String*/ behaviour, /*String?*/ extra, /*String?*/ removal){
// summary: Log a debug message to indicate that a behavior has been deprecated.
// extra: Text to append to the message.
// removal: Text to indicate when in the future the behavior will be removed.
};
dojo.deprecated = function (behaviour, extra, removal) {
var message = "DEPRECATED: " + behaviour;
if(extra){ message += " " + extra; }
if(removal){ message += " -- will be removed in version: " + removal; }
if (extra) {
message += " " + extra;
}
if (removal) {
message += " -- will be removed in version: " + removal;
}
dojo.debug(message);
}
dojo.render = (function(){
//TODOC: HOW TO DOC THIS?
// summary: Details rendering support, OS and browser of the current environment.
// TODOC: is this something many folks will interact with? If so, we should doc the structure created...
function vscaffold(prefs, names){
var tmp = {
capable: false,
support: {
builtin: false,
plugin: false
},
prefixes: prefs
};
for(var i=0; i<names.length; i++){
};
dojo.render = (function () {
function vscaffold(prefs, names) {
var tmp = {capable:false, support:{builtin:false, plugin:false}, prefixes:prefs};
for (var i = 0; i < names.length; i++) {
tmp[names[i]] = false;
}
return tmp;
}
return {
name: "",
ver: dojo.version,
os: { win: false, linux: false, osx: false },
html: vscaffold(["html"], ["ie", "opera", "khtml", "safari", "moz"]),
svg: vscaffold(["svg"], ["corel", "adobe", "batik"]),
vml: vscaffold(["vml"], ["ie"]),
swf: vscaffold(["Swf", "Flash", "Mm"], ["mm"]),
swt: vscaffold(["Swt"], ["ibm"])
};
return {name:"", ver:dojo.version, os:{win:false, linux:false, osx:false}, html:vscaffold(["html"], ["ie", "opera", "khtml", "safari", "moz"]), svg:vscaffold(["svg"], ["corel", "adobe", "batik"]), vml:vscaffold(["vml"], ["ie"]), swf:vscaffold(["Swf", "Flash", "Mm"], ["mm"]), swt:vscaffold(["Swt"], ["ibm"])};
})();
// ****************************************************************
// dojo.hostenv methods that must be defined in hostenv_*.js
// ****************************************************************
/**
* The interface definining the interaction with the EcmaScript host environment.
*/
/*
* None of these methods should ever be called directly by library users.
* Instead public methods such as loadModule should be called instead.
*/
dojo.hostenv = (function(){
// TODOC: HOW TO DOC THIS?
// summary: Provides encapsulation of behavior that changes across different 'host environments'
// (different browsers, server via Rhino, etc).
// description: None of these methods should ever be called directly by library users.
// Use public methods such as 'loadModule' instead.
// default configuration options
var config = {
isDebug: false,
allowQueryConfig: false,
baseScriptUri: "",
baseRelativePath: "",
libraryScriptUri: "",
iePreventClobber: false,
ieClobberMinimal: true,
preventBackButtonFix: true,
delayMozLoadingFix: false,
searchIds: [],
parseWidgets: true
};
if (typeof djConfig == "undefined") { djConfig = config; }
else {
dojo.hostenv = (function () {
var config = {isDebug:false, allowQueryConfig:false, baseScriptUri:"", baseRelativePath:"", libraryScriptUri:"", iePreventClobber:false, ieClobberMinimal:true, preventBackButtonFix:true, delayMozLoadingFix:false, searchIds:[], parseWidgets:true};
if (typeof djConfig == "undefined") {
djConfig = config;
} else {
for (var option in config) {
if (typeof djConfig[option] == "undefined") {
djConfig[option] = config[option];
}
}
}
return {
name_: '(unset)',
version_: '(unset)',
getName: function(){
// sumary: Return the name of the host environment.
return this.name_; // String
},
getVersion: function(){
// summary: Return the version of the hostenv.
return this.version_; // String
},
getText: function(/*String*/ uri){
// summary: Read the plain/text contents at the specified 'uri'.
// description:
// If 'getText()' is not implemented, then it is necessary to override
// 'loadUri()' with an implementation that doesn't rely on it.
dojo.unimplemented('getText', "uri=" + uri);
}
};
return {name_:"(unset)", version_:"(unset)", getName:function () {
return this.name_;
}, getVersion:function () {
return this.version_;
}, getText:function (uri) {
dojo.unimplemented("getText", "uri=" + uri);
}};
})();
dojo.hostenv.getBaseScriptUri = function(){
// summary: Return the base script uri that other scripts are found relative to.
// TODOC: HUH? This comment means nothing to me. What other scripts? Is this the path to other dojo libraries?
// MAYBE: Return the base uri to scripts in the dojo library. ???
// return: Empty string or a path ending in '/'.
if(djConfig.baseScriptUri.length){
dojo.hostenv.getBaseScriptUri = function () {
if (djConfig.baseScriptUri.length) {
return djConfig.baseScriptUri;
}
// MOW: Why not:
// uri = djConfig.libraryScriptUri || djConfig.baseRelativePath
// ??? Why 'new String(...)'
var uri = new String(djConfig.libraryScriptUri||djConfig.baseRelativePath);
if (!uri) { dojo.raise("Nothing returned by getLibraryScriptUri(): " + uri); }
// MOW: uri seems to not be actually used. Seems to be hard-coding to djConfig.baseRelativePath... ???
var lastslash = uri.lastIndexOf('/'); // MOW ???
var uri = new String(djConfig.libraryScriptUri || djConfig.baseRelativePath);
if (!uri) {
dojo.raise("Nothing returned by getLibraryScriptUri(): " + uri);
}
var lastslash = uri.lastIndexOf("/");
djConfig.baseScriptUri = djConfig.baseRelativePath;
return djConfig.baseScriptUri; // String
}
return djConfig.baseScriptUri;
};
@@ -8,129 +8,90 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.browser_debug");
dojo.hostenv.loadedUris.push("../src/bootstrap1.js");
dojo.hostenv.loadedUris.push("../src/loader.js");
dojo.hostenv.loadedUris.push("../src/hostenv_browser.js");
dojo.hostenv.loadedUris.push("../src/bootstrap2.js");
dojo.hostenv._loadedUrisListStart = dojo.hostenv.loadedUris.length;
function removeComments(contents){
function removeComments(contents) {
contents = new String((!contents) ? "" : contents);
// clobber all comments
// FIXME broken if // or /* inside quotes or regexp
contents = contents.replace( /^(.*?)\/\/(.*)$/mg , "$1");
contents = contents.replace( /(\n)/mg , "__DOJONEWLINE");
contents = contents.replace( /\/\*(.*?)\*\//g , "");
return contents.replace( /__DOJONEWLINE/mg , "\n");
contents = contents.replace(/^(.*?)\/\/(.*)$/mg, "$1");
contents = contents.replace(/(\n)/mg, "__DOJONEWLINE");
contents = contents.replace(/\/\*(.*?)\*\//g, "");
return contents.replace(/__DOJONEWLINE/mg, "\n");
}
dojo.hostenv.getRequiresAndProvides = function(contents){
// FIXME: should probably memoize this!
if(!contents){ return []; }
// check to see if we need to load anything else first. Ugg.
dojo.hostenv.getRequiresAndProvides = function (contents) {
if (!contents) {
return [];
}
var deps = [];
var tmp;
RegExp.lastIndex = 0;
var testExp = /dojo.(hostenv.loadModule|hostenv.require|require|requireIf|kwCompoundRequire|hostenv.conditionalLoadModule|hostenv.startPackage|provide)\([\w\W]*?\)/mg;
while((tmp = testExp.exec(contents)) != null){
while ((tmp = testExp.exec(contents)) != null) {
deps.push(tmp[0]);
}
return deps;
}
dojo.hostenv.getDelayRequiresAndProvides = function(contents){
// FIXME: should probably memoize this!
if(!contents){ return []; }
// check to see if we need to load anything else first. Ugg.
};
dojo.hostenv.getDelayRequiresAndProvides = function (contents) {
if (!contents) {
return [];
}
var deps = [];
var tmp;
RegExp.lastIndex = 0;
var testExp = /dojo.(requireAfterIf)\([\w\W]*?\)/mg;
while((tmp = testExp.exec(contents)) != null){
while ((tmp = testExp.exec(contents)) != null) {
deps.push(tmp[0]);
}
return deps;
}
/*
dojo.getNonExistantDescendants = function(objpath){
var ret = [];
// fast path for no periods
if(typeof objpath != "string"){ return dj_global; }
if(objpath.indexOf('.') == -1){
if(dj_undef(objpath, dj_global)){
ret.push[objpath];
}
return ret;
}
var syms = objpath.split(/\./);
var obj = dj_global;
for(var i=0;i<syms.length;++i){
if(dj_undef(syms[i], obj)){
for(var j=i; j<syms.length; j++){
ret.push(syms.slice(0, j+1).join("."));
}
break;
}
}
return ret;
}
*/
dojo.clobberLastObject = function(objpath){
if(objpath.indexOf('.') == -1){
if(!dj_undef(objpath, dj_global)){
};
dojo.clobberLastObject = function (objpath) {
if (objpath.indexOf(".") == -1) {
if (!dj_undef(objpath, dj_global)) {
delete dj_global[objpath];
}
return true;
}
var syms = objpath.split(/\./);
var base = dojo.evalObjPath(syms.slice(0, -1).join("."), false);
var child = syms[syms.length-1];
if(!dj_undef(child, base)){
// alert(objpath);
var child = syms[syms.length - 1];
if (!dj_undef(child, base)) {
delete base[child];
return true;
}
return false;
}
};
var removals = [];
function zip(arr){
function zip(arr) {
var ret = [];
var seen = {};
for(var x=0; x<arr.length; x++){
if(!seen[arr[x]]){
for (var x = 0; x < arr.length; x++) {
if (!seen[arr[x]]) {
ret.push(arr[x]);
seen[arr[x]] = true;
}
}
return ret;
}
// over-write dj_eval to prevent actual loading of subsequent files
var old_dj_eval = dj_eval;
dj_eval = function(){ return true; }
dj_eval = function () {
return true;
};
dojo.hostenv.oldLoadUri = dojo.hostenv.loadUri;
dojo.hostenv.loadUri = function(uri, cb /*optional*/){
if(dojo.hostenv.loadedUris[uri]){
return true; // fixes endless recursion opera trac 471
dojo.hostenv.loadUri = function (uri, cb) {
if (dojo.hostenv.loadedUris[uri]) {
return true;
}
try{
try {
var text = this.getText(uri, null, true);
if(!text) { return false; }
if(cb){
// No way to load i18n bundles but to eval them, and they usually
// don't have script needing to be debugged anyway
var expr = old_dj_eval('('+text+')');
if (!text) {
return false;
}
if (cb) {
var expr = old_dj_eval("(" + text + ")");
cb(expr);
}else {
} else {
var requires = dojo.hostenv.getRequiresAndProvides(text);
eval(requires.join(";"));
dojo.hostenv.loadedUris.push(uri);
@@ -138,39 +99,35 @@ dojo.hostenv.loadUri = function(uri, cb /*optional*/){
var delayRequires = dojo.hostenv.getDelayRequiresAndProvides(text);
eval(delayRequires.join(";"));
}
}catch(e){
}
catch (e) {
alert(e);
}
return true;
}
};
dojo.hostenv._writtenIncludes = {};
dojo.hostenv.writeIncludes = function(willCallAgain){
for(var x=removals.length-1; x>=0; x--){
dojo.hostenv.writeIncludes = function (willCallAgain) {
for (var x = removals.length - 1; x >= 0; x--) {
dojo.clobberLastObject(removals[x]);
}
var depList = [];
var seen = dojo.hostenv._writtenIncludes;
for(var x=0; x<dojo.hostenv.loadedUris.length; x++){
for (var x = 0; x < dojo.hostenv.loadedUris.length; x++) {
var curi = dojo.hostenv.loadedUris[x];
// dojo.debug(curi);
if(!seen[curi]){
if (!seen[curi]) {
seen[curi] = true;
depList.push(curi);
}
}
dojo.hostenv._global_omit_module_check = true;
for(var x= dojo.hostenv._loadedUrisListStart; x<depList.length; x++){
document.write("<script type='text/javascript' src='"+depList[x]+"'></script>");
for (var x = dojo.hostenv._loadedUrisListStart; x < depList.length; x++) {
document.write("<script type='text/javascript' src='" + depList[x] + "'></script>");
}
document.write("<script type='text/javascript'>dojo.hostenv._global_omit_module_check = false;</script>");
dojo.hostenv._loadedUrisListStart = 0;
if (!willCallAgain) {
// turn off debugAtAllCosts, so that dojo.require() calls inside of ContentPane hrefs
// work correctly
dj_eval = old_dj_eval;
dojo.hostenv.loadUri = dojo.hostenv.oldLoadUri;
}
}
};
@@ -0,0 +1,36 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.browser_debug_xd");
dojo.nonDebugProvide = dojo.provide;
dojo.provide = function (resourceName) {
var dbgQueue = dojo.hostenv["xdDebugQueue"];
if (dbgQueue && dbgQueue.length > 0 && resourceName == dbgQueue["currentResourceName"]) {
window.setTimeout("dojo.hostenv.xdDebugFileLoaded('" + resourceName + "')", 1);
}
dojo.nonDebugProvide.apply(dojo, arguments);
};
dojo.hostenv.xdDebugFileLoaded = function (resourceName) {
var dbgQueue = this.xdDebugQueue;
if (resourceName && resourceName == dbgQueue.currentResourceName) {
dbgQueue.shift();
}
if (dbgQueue.length == 0) {
dbgQueue.currentResourceName = null;
this.xdNotifyLoaded();
} else {
dbgQueue.currentResourceName = dbgQueue[0].resourceName;
var element = document.createElement("script");
element.type = "text/javascript";
element.src = dbgQueue[0].resourcePath;
document.getElementsByTagName("head")[0].appendChild(element);
}
};
File diff suppressed because it is too large Load Diff
@@ -10,66 +10,46 @@
dojo.provide("dojo.cal.textDirectory");
dojo.require("dojo.string");
/*
* This class parses a single line from a text/directory file
* and returns an object with four named values; name, group, params
* and value. name, group and value are strings containing the original
* tokens unaltered and values is an array containing name/value pairs
* or a single name token packed into arrays.
*/
dojo.cal.textDirectory.Property = function (line) {
// split into name/value pair
var left = dojo.string.trim(line.substring(0, line.indexOf(':')));
var right = dojo.string.trim(line.substr(line.indexOf(':') + 1));
// seperate name and paramters
var parameters = dojo.string.splitEscaped(left,';');
this.name = parameters[0]
var left = dojo.string.trim(line.substring(0, line.indexOf(":")));
var right = dojo.string.trim(line.substr(line.indexOf(":") + 1));
var parameters = dojo.string.splitEscaped(left, ";");
this.name = parameters[0];
parameters.splice(0, 1);
// parse paramters
this.params = [];
var arr;
for (var i = 0; i < parameters.length; i++) {
var arr = parameters[i].split("=");
arr = parameters[i].split("=");
var key = dojo.string.trim(arr[0].toUpperCase());
if (arr.length == 1) { this.params.push([key]); continue; }
var values = dojo.string.splitEscaped(arr[1],',');
if (arr.length == 1) {
this.params.push([key]);
continue;
}
var values = dojo.string.splitEscaped(arr[1], ",");
for (var j = 0; j < values.length; j++) {
if (dojo.string.trim(values[j]) != '') {
if (dojo.string.trim(values[j]) != "") {
this.params.push([key, dojo.string.trim(values[j])]);
}
}
}
// seperate group
if (this.name.indexOf('.') > 0) {
var arr = this.name.split('.');
if (this.name.indexOf(".") > 0) {
arr = this.name.split(".");
this.group = arr[0];
this.name = arr[1];
}
// don't do any parsing, leave to implementation
this.value = right;
}
// tokeniser, parses into an array of properties.
};
dojo.cal.textDirectory.tokenise = function (text) {
// normlize to one propterty per line and parse
var nText = dojo.string.normalizeNewlines(text,"\n");
nText = nText.replace(/\n[ \t]/g, '');
nText = nText.replace(/\x00/g, '');
var nText = dojo.string.normalizeNewlines(text, "\n").replace(/\n[ \t]/g, "").replace(/\x00/g, "");
var lines = nText.split("\n");
var properties = []
var properties = [];
for (var i = 0; i < lines.length; i++) {
if (dojo.string.trim(lines[i]) == '') { continue; }
if (dojo.string.trim(lines[i]) == "") {
continue;
}
var prop = new dojo.cal.textDirectory.Property(lines[i]);
properties.push(prop);
}
return properties;
}
};
@@ -8,139 +8,123 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.Axis");
dojo.require("dojo.lang.common");
dojo.charting.Axis = function(/* string? */label, /* string? */scale, /* array? */labels){
var id = "dojo-charting-axis-"+dojo.charting.Axis.count++;
this.getId=function(){ return id; };
this.setId=function(key){ id = key; };
this.scale = scale || "linear"; // linear || log
this.label = label || "";
this.showLabel = true; // show axis label.
this.showLabels = true; // show interval ticks.
this.showLines = false; // if you want lines over the range of the plot area
this.showTicks = false; // if you want tick marks on the axis.
this.range = { upper : 0, lower : 0 }; // range of individual axis.
this.origin = "min"; // this can be any number, "min" or "max". min/max is translated on init.
this.labels = labels || [];
this._labels = []; // what we really use to draw things.
this.nodes={ main: null, axis: null, label: null, labels: null, lines: null, ticks: null };
};
dojo.charting.Axis.count = 0;
dojo.extend(dojo.charting.Axis, {
// TODO: implement log scaling.
getCoord: function(
/* float */val,
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot
){
// summary
// returns the coordinate of val based on this axis range, plot area and plot.
val = parseFloat(val, 10);
var area = plotArea.getArea();
if(plot.axisX == this){
var offset = 0 - this.range.lower;
var min = this.range.lower + offset; // FIXME: check this.
var max = this.range.upper + offset;
val += offset;
return (val*((area.right-area.left)/max))+area.left; // float
} else {
var max = this.range.upper;
var min = this.range.lower;
var offset = 0;
if(min<0){
offset += Math.abs(min);
}
max += offset; min += offset; val += offset;
var pmin = area.bottom;
var pmax = area.top;
return (((pmin-pmax)/(max-min))*(max-val))+pmax;
}
},
initializeOrigin: function(drawAgainst, plane){
// figure out the origin value.
if(isNaN(this.origin)){
if(this.origin.toLowerCase() == "max"){
this.origin = drawAgainst.range[(plane=="y")?"upper":"lower"];
}
else if (this.origin.toLowerCase() == "min"){
this.origin = drawAgainst.range[(plane=="y")?"lower":"upper"];
}
else { this.origin=0; }
}
},
initializeLabels: function(){
// Translate the labels if needed.
if(this.labels.length == 0){
this.showLabels = false;
this.showLines = false;
this.showTicks = false;
} else {
if(this.labels[0].label && this.labels[0].value != null){
for(var i=0; i<this.labels.length; i++){
this._labels.push(this.labels[i]);
}
}
else if(!isNaN(this.labels[0])){
for(var i=0; i<this.labels.length; i++){
this._labels.push({ label: this.labels[i], value: this.labels[i] });
}
}
else {
// clone me
var a = [];
for(var i=0; i<this.labels.length; i++){
a.push(this.labels[i]);
}
// do the bottom one.
var s=a.shift();
this._labels.push({ label: s, value: this.range.lower });
// do the top one.
if(a.length>0){
var s=a.pop();
this._labels.push({ label: s, value: this.range.upper });
}
// do the rest.
if(a.length>0){
var range = this.range.upper - this.range.lower;
var step = range / (this.labels.length-1);
for(var i=1; i<=a.length; i++){
this._labels.push({
label: a[i-1],
value: this.range.lower+(step*i)
});
}
}
}
}
},
initialize: function(plotArea, plot, drawAgainst, plane){
// summary
// Initialize the passed axis descriptor. Note that this should always
// be the result of plotArea.getAxes, and not the axis directly!
this.destroy();
this.initializeOrigin(drawAgainst, plane);
this.initializeLabels();
var node = this.render(plotArea, plot, drawAgainst, plane);
return node;
},
destroy: function(){
for(var p in this.nodes){
while(this.nodes[p] && this.nodes[p].childNodes.length > 0){
this.nodes[p].removeChild(this.nodes[p].childNodes[0]);
}
if(this.nodes[p] && this.nodes[p].parentNode){
this.nodes[p].parentNode.removeChild(this.nodes[p]);
}
this.nodes[p] = null;
}
}
});
dojo["requireIf"](dojo.render.svg.capable, "dojo.charting.svg.Axis");
dojo["requireIf"](!dojo.render.svg.capable && dojo.render.vml.capable, "dojo.charting.vml.Axis");
dojo.provide("dojo.charting.Axis");
dojo.require("dojo.lang.common");
dojo.charting.Axis = function (label, scale, labels) {
var id = "dojo-charting-axis-" + dojo.charting.Axis.count++;
this.getId = function () {
return id;
};
this.setId = function (key) {
id = key;
};
this.scale = scale || "linear";
this.label = label || "";
this.showLabel = true;
this.showLabels = true;
this.showLines = false;
this.showTicks = false;
this.range = {upper:100, lower:0};
this.origin = "min";
this._origin = null;
this.labels = labels || [];
this._labels = [];
this.nodes = {main:null, axis:null, label:null, labels:null, lines:null, ticks:null};
this._rerender = false;
};
dojo.charting.Axis.count = 0;
dojo.extend(dojo.charting.Axis, {getCoord:function (val, plotArea, plot) {
val = parseFloat(val, 10);
var area = plotArea.getArea();
if (plot.axisX == this) {
var offset = 0 - this.range.lower;
var min = this.range.lower + offset;
var max = this.range.upper + offset;
val += offset;
return (val * ((area.right - area.left) / max)) + area.left;
} else {
var max = this.range.upper;
var min = this.range.lower;
var offset = 0;
if (min < 0) {
offset += Math.abs(min);
}
max += offset;
min += offset;
val += offset;
var pmin = area.bottom;
var pmax = area.top;
return (((pmin - pmax) / (max - min)) * (max - val)) + pmax;
}
}, initializeOrigin:function (drawAgainst, plane) {
if (this._origin == null) {
this._origin = this.origin;
}
if (isNaN(this._origin)) {
if (this._origin.toLowerCase() == "max") {
this.origin = drawAgainst.range[(plane == "y") ? "upper" : "lower"];
} else {
if (this._origin.toLowerCase() == "min") {
this.origin = drawAgainst.range[(plane == "y") ? "lower" : "upper"];
} else {
this.origin = 0;
}
}
}
}, initializeLabels:function () {
this._labels = [];
if (this.labels.length == 0) {
this.showLabels = false;
this.showLines = false;
this.showTicks = false;
} else {
if (this.labels[0].label && this.labels[0].value != null) {
for (var i = 0; i < this.labels.length; i++) {
this._labels.push(this.labels[i]);
}
} else {
if (!isNaN(this.labels[0])) {
for (var i = 0; i < this.labels.length; i++) {
this._labels.push({label:this.labels[i], value:this.labels[i]});
}
} else {
var a = [];
for (var i = 0; i < this.labels.length; i++) {
a.push(this.labels[i]);
}
var s = a.shift();
this._labels.push({label:s, value:this.range.lower});
if (a.length > 0) {
var s = a.pop();
this._labels.push({label:s, value:this.range.upper});
}
if (a.length > 0) {
var range = this.range.upper - this.range.lower;
var step = range / (this.labels.length - 1);
for (var i = 1; i <= a.length; i++) {
this._labels.push({label:a[i - 1], value:this.range.lower + (step * i)});
}
}
}
}
}
}, initialize:function (plotArea, plot, drawAgainst, plane) {
this.destroy();
this.initializeOrigin(drawAgainst, plane);
this.initializeLabels();
var node = this.render(plotArea, plot, drawAgainst, plane);
return node;
}, destroy:function () {
for (var p in this.nodes) {
while (this.nodes[p] && this.nodes[p].childNodes.length > 0) {
this.nodes[p].removeChild(this.nodes[p].childNodes[0]);
}
if (this.nodes[p] && this.nodes[p].parentNode) {
this.nodes[p].parentNode.removeChild(this.nodes[p]);
}
this.nodes[p] = null;
}
}});
dojo.requireIf(dojo.render.svg.capable, "dojo.charting.svg.Axis");
dojo.requireIf(dojo.render.vml.capable, "dojo.charting.vml.Axis");
@@ -8,78 +8,55 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.Chart");
dojo.require("dojo.lang.common");
dojo.require("dojo.charting.PlotArea");
dojo.charting.Chart = function(
/* HTMLElement? */node,
/* string? */title,
/* string? */description
){
// summary
// Create the basic Chart object.
this.node = node || null;
this.title = title || "Chart"; // pure string.
this.description = description || ""; // HTML is allowed.
this.plotAreas = [];
};
dojo.extend(dojo.charting.Chart, {
// methods
addPlotArea: function(/* object */obj, /* bool? */doRender){
// summary
// Add a PlotArea to this chart; object should be in the
// form of: { plotArea, (x, y) or (top, left) }
if(obj.x && !obj.left){ obj.left = obj.x; }
if(obj.y && !obj.top){ obj.top = obj.y; }
this.plotAreas.push(obj);
if(doRender){ this.render(); }
},
// events
onInitialize:function(chart){ },
onRender:function(chart){ },
onDestroy:function(chart){ },
// standard build methods
initialize: function(){
// summary
// Initialize the Chart by rendering it.
if(!this.node){
dojo.raise("dojo.charting.Chart.initialize: there must be a root node defined for the Chart.");
}
this.destroy();
this.render();
this.onInitialize(this);
},
render:function(){
// summary
// Render the chart in its entirety.
if(this.node.style.position != "absolute"){
this.node.style.position = "relative";
}
for(var i=0; i<this.plotAreas.length; i++){
var area = this.plotAreas[i].plotArea;
var node = area.initialize();
node.style.position = "absolute";
node.style.top = this.plotAreas[i].top + "px";
node.style.left = this.plotAreas[i].left + "px";
this.node.appendChild(node);
area.render();
}
},
destroy: function(){
// summary
// Destroy any nodes that have maintained references.
// kill any existing plotAreas
for(var i=0; i<this.plotAreas.length; i++){
this.plotAreas[i].plotArea.destroy();
};
// clean out any child nodes.
while(this.node && this.node.childNodes && this.node.childNodes.length > 0){
this.node.removeChild(this.node.childNodes[0]);
}
}
});
dojo.provide("dojo.charting.Chart");
dojo.require("dojo.lang.common");
dojo.require("dojo.charting.PlotArea");
dojo.charting.Chart = function (node, title, description) {
this.node = node || null;
this.title = title || "Chart";
this.description = description || "";
this.plotAreas = [];
};
dojo.extend(dojo.charting.Chart, {addPlotArea:function (obj, doRender) {
if (obj.x != null && obj.left == null) {
obj.left = obj.x;
}
if (obj.y != null && obj.top == null) {
obj.top = obj.y;
}
this.plotAreas.push(obj);
if (doRender) {
this.render();
}
}, onInitialize:function (chart) {
}, onRender:function (chart) {
}, onDestroy:function (chart) {
}, initialize:function () {
if (!this.node) {
dojo.raise("dojo.charting.Chart.initialize: there must be a root node defined for the Chart.");
}
this.destroy();
this.render();
this.onInitialize(this);
}, render:function () {
if (this.node.style.position != "absolute") {
this.node.style.position = "relative";
}
for (var i = 0; i < this.plotAreas.length; i++) {
var area = this.plotAreas[i].plotArea;
var node = area.initialize();
node.style.position = "absolute";
node.style.top = this.plotAreas[i].top + "px";
node.style.left = this.plotAreas[i].left + "px";
this.node.appendChild(node);
area.render();
}
}, destroy:function () {
for (var i = 0; i < this.plotAreas.length; i++) {
this.plotAreas[i].plotArea.destroy();
}
while (this.node && this.node.childNodes && this.node.childNodes.length > 0) {
this.node.removeChild(this.node.childNodes[0]);
}
}});
@@ -8,96 +8,73 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.Plot");
dojo.require("dojo.lang.common");
dojo.require("dojo.charting.Axis");
dojo.require("dojo.charting.Series");
dojo.charting.RenderPlotSeries = { Singly:"single", Grouped:"grouped" };
dojo.charting.Plot = function(
/* dojo.charting.Axis? */xaxis,
/* dojo.charting.Axis? */yaxis,
/* dojo.charting.Series[]? */series
){
// summary
// Creates a new instance of a Plot (X/Y Axis + n Series).
var id = "dojo-charting-plot-"+dojo.charting.Plot.count++;
this.getId=function(){ return id; };
this.setId=function(key){ id = key; };
this.axisX = null;
this.axisY = null;
this.series = [];
this.dataNode = null;
// for bar charts, pie charts and stacked charts, change to Grouped.
this.renderType = dojo.charting.RenderPlotSeries.Singly;
if(xaxis){
this.setAxis(xaxis,"x");
}
if(yaxis){
this.setAxis(yaxis,"y");
}
if(series){
for(var i=0; i<series.length; i++){ this.addSeries(series[i]); }
}
}
dojo.charting.Plot.count=0;
dojo.extend(dojo.charting.Plot, {
addSeries: function(
/* dojo.charting.Series || object */series,
/* function? */plotter
){
// summary
// Add a new Series to this plot. Can take the form of a Series, or an object
// of the form { series, plotter }
if(series.plotter){
this.series.push(series);
} else {
this.series.push({
data: series,
plotter: plotter || dojo.charting.Plotters["Default"]
});
}
},
setAxis: function(/* dojo.charting.Axis */axis, /* string */which){
// summary
// Set the axis on which plane.
if(which.toLowerCase()=="x"){ this.axisX = axis; }
else if(which.toLowerCase()=="y"){ this.axisY = axis; }
},
getRanges: function(){
// summary
// set the ranges on these axes.
var xmin, xmax, ymin, ymax;
xmin=ymin=Number.MAX_VALUE;
xmax=ymax=Number.MIN_VALUE;
for(var i=0; i<this.series.length; i++){
var values = this.series[i].data.evaluate(); // full data range.
for(var j=0; j<values.length; j++){
var comp=values[j];
xmin=Math.min(comp.x, xmin);
ymin=Math.min(comp.y, ymin);
xmax=Math.max(comp.x, xmax);
ymax=Math.max(comp.y, ymax);
}
}
return {
x:{ upper: xmax, lower:xmin },
y:{ upper: ymax, lower:ymin },
toString:function(){
return "[ x:"+xmax+" - "+xmin+", y:"+ymax+" - "+ymin+"]";
}
}; // object
},
destroy: function(){
// summary
// Clean out any existing DOM node references.
var node=this.dataNode;
while(node && node.childNodes && node.childNodes.length > 0){
node.removeChild(node.childNodes[0]);
}
this.dataNode=null;
}
});
dojo.provide("dojo.charting.Plot");
dojo.require("dojo.lang.common");
dojo.require("dojo.charting.Axis");
dojo.require("dojo.charting.Series");
dojo.charting.RenderPlotSeries = {Singly:"single", Grouped:"grouped"};
dojo.charting.Plot = function (xaxis, yaxis, series) {
var id = "dojo-charting-plot-" + dojo.charting.Plot.count++;
this.getId = function () {
return id;
};
this.setId = function (key) {
id = key;
};
this.axisX = null;
this.axisY = null;
this.series = [];
this.dataNode = null;
this.renderType = dojo.charting.RenderPlotSeries.Singly;
if (xaxis) {
this.setAxis(xaxis, "x");
}
if (yaxis) {
this.setAxis(yaxis, "y");
}
if (series) {
for (var i = 0; i < series.length; i++) {
this.addSeries(series[i]);
}
}
};
dojo.charting.Plot.count = 0;
dojo.extend(dojo.charting.Plot, {addSeries:function (series, plotter) {
if (series.plotter) {
this.series.push(series);
} else {
this.series.push({data:series, plotter:plotter || dojo.charting.Plotters["Default"]});
}
}, setAxis:function (axis, which) {
if (which.toLowerCase() == "x") {
this.axisX = axis;
} else {
if (which.toLowerCase() == "y") {
this.axisY = axis;
}
}
}, getRanges:function () {
var xmin, xmax, ymin, ymax;
xmin = ymin = Number.MAX_VALUE;
xmax = ymax = Number.MIN_VALUE;
for (var i = 0; i < this.series.length; i++) {
var values = this.series[i].data.evaluate();
for (var j = 0; j < values.length; j++) {
var comp = values[j];
xmin = Math.min(comp.x, xmin);
ymin = Math.min(comp.y, ymin);
xmax = Math.max(comp.x, xmax);
ymax = Math.max(comp.y, ymax);
}
}
return {x:{upper:xmax, lower:xmin}, y:{upper:ymax, lower:ymin}, toString:function () {
return "[ x:" + xmax + " - " + xmin + ", y:" + ymax + " - " + ymin + "]";
}};
}, destroy:function () {
var node = this.dataNode;
while (node && node.childNodes && node.childNodes.length > 0) {
node.removeChild(node.childNodes[0]);
}
this.dataNode = null;
}});
@@ -8,186 +8,128 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.PlotArea");
dojo.require("dojo.lang.common");
dojo.require("dojo.gfx.color");
dojo.require("dojo.gfx.color.hsl");
dojo.require("dojo.charting.Plot");
dojo.charting.PlotArea = function(){
// summary
// Creates a new PlotArea for drawing onto a Chart.
var id="dojo-charting-plotarea-"+dojo.charting.PlotArea.count++;
this.getId=function(){ return id; };
this.setId=function(key){ id = key; };
this.areaType = "standard"; // standard || radar
this.plots = []; // plots that will be drawn on this area
this.size={ width:600, height:400 };
this.padding={ top:10, right:10, bottom:20, left:20 };
// drawing node references.
this.nodes = {
main:null,
area:null,
background: null,
axes: null,
plots: null
};
// this is preset for a limited color range (green to purple),
// anticipating a max of 32 series on this plot area.
// if you need more flexibility, override these numbers.
this._color = { h: 140, s: 120, l: 120, step: 27 };
};
dojo.charting.PlotArea.count = 0;
dojo.extend(dojo.charting.PlotArea, {
nextColor: function(){
// summary
// Advances the internal HSV cursor and returns the next generated color.
var rgb=dojo.gfx.color.hsl2rgb(this._color.h, this._color.s, this._color.l);
this._color.h = (this._color.h + this._color.step)%360;
while(this._color.h < 140){
this._color.h += this._color.step;
}
return dojo.gfx.color.rgb2hex(rgb[0], rgb[1], rgb[2]); // string
},
getArea:function(){
// summary
// Return an object describing the coordinates of the available area to plot on.
return {
left: this.padding.left,
right: this.size.width - this.padding.right,
top: this.padding.top,
bottom: this.size.height - this.padding.bottom,
toString:function(){
var a=[ this.top, this.right, this.bottom, this.left ];
return "["+a.join()+"]";
}
}; // object
},
getAxes: function(){
// summary
// get the unique axes for this plot area.
var axes={};
for(var i=0; i<this.plots.length; i++){
var plot=this.plots[i];
axes[plot.axisX.getId()] = {
axis: plot.axisX,
drawAgainst: plot.axisY,
plot: plot,
plane: "x"
};
axes[plot.axisY.getId()] = {
axis: plot.axisY,
drawAgainst: plot.axisX,
plot: plot,
plane: "y"
};
}
return axes; // object
},
getLegendInfo: function(){
// summary
// return an array describing all data series on this plot area.
var a=[];
for(var i=0; i<this.plots.length; i++){
for(var j=0; j<this.plots[i].series.length; j++){
var data = this.plots[i].series[j].data;
a.push({ label:data.label, color:data.color });
}
}
return a; // array
},
setAxesRanges: function(){
// summary
// Find and set the ranges on all axes on this plotArea.
// We do this because plots may have axes in common; if you
// want to use this, make sure you do it *before* initialization.
var ranges={};
var axes={};
for(var i=0; i<this.plots.length; i++){
var plot = this.plots[i];
var ranges=plot.getRanges();
var x=ranges.x;
var y=ranges.y;
var ax, ay;
if(!axes[plot.axisX.getId()]){
axes[plot.axisX.getId()]=plot.axisX;
ranges[plot.axisX.getId()]={upper: x.upper, lower:x.lower};
}
ax=ranges[plot.axisX.getId()];
ax.upper=Math.max(ax.upper, x.upper);
ax.lower=Math.min(ax.lower, x.lower);
if(!axes[plot.axisY.getId()]){
axes[plot.axisY.getId()]=plot.axisY;
ranges[plot.axisY.getId()]={upper: y.upper, lower:y.lower};
}
ay=ranges[plot.axisY.getId()];
ay.upper=Math.max(ay.upper, y.upper);
ay.lower=Math.min(ay.lower, y.lower);
}
// now that we have all the max/min ranges, set the axes
for(var p in axes){
axes[p].range=ranges[p];
}
},
render: function(/* object? */kwArgs, /* function? */applyToData){
// summary
// Render this plotArea. Optional kwArgs are the same as that taken for Series.evaluate;
// applyToData is a callback function used by plotters for customization.
if(!this.nodes.main
|| !this.nodes.area
|| !this.nodes.background
|| !this.nodes.plots
|| !this.nodes.axes
){ this.initialize(); }
// plot it.
for(var i=0; i<this.plots.length; i++){
var plot=this.plots[i];
this.nodes.plots.removeChild(plot.dataNode);
var target = this.initializePlot(plot);
switch(plot.renderType){
case dojo.charting.RenderPlotSeries.Grouped: {
// ALWAYS plot using the first plotter, ignore any others.
target.appendChild(plot.series[0].plotter(this, plot, kwArgs, applyToData));
break;
}
case dojo.charting.RenderPlotSeries.Singly:
default: {
for(var j=0; j<plot.series.length; j++){
var series = plot.series[j];
var data = series.data.evaluate(kwArgs);
target.appendChild(series.plotter(data, this, plot, applyToData));
}
}
}
this.nodes.plots.appendChild(target);
}
},
destroy: function(){
// summary
// Clean out any existing DOM references.
for(var i=0; i<this.plots.length; i++){
this.plots[i].destroy();
};
// clean out any child nodes.
for(var p in this.nodes){
var node=this.nodes[p];
if(!node) continue;
if(!node.childNodes) continue;
while(node.childNodes.length > 0){
node.removeChild(node.childNodes[0]);
}
this.nodes[p]=null;
}
}
});
dojo["requireIf"](dojo.render.svg.capable, "dojo.charting.svg.PlotArea");
dojo["requireIf"](!dojo.render.svg.capable && dojo.render.vml.capable, "dojo.charting.vml.PlotArea");
dojo.provide("dojo.charting.PlotArea");
dojo.require("dojo.lang.common");
dojo.require("dojo.gfx.color");
dojo.require("dojo.gfx.color.hsl");
dojo.require("dojo.charting.Plot");
dojo.charting.PlotArea = function () {
var id = "dojo-charting-plotarea-" + dojo.charting.PlotArea.count++;
this.getId = function () {
return id;
};
this.setId = function (key) {
id = key;
};
this.areaType = "standard";
this.plots = [];
this.size = {width:600, height:400};
this.padding = {top:10, right:10, bottom:20, left:20};
this.nodes = {main:null, area:null, background:null, axes:null, plots:null};
this._color = {h:140, s:120, l:120, step:27};
};
dojo.charting.PlotArea.count = 0;
dojo.extend(dojo.charting.PlotArea, {nextColor:function () {
var rgb = dojo.gfx.color.hsl2rgb(this._color.h, this._color.s, this._color.l);
this._color.h = (this._color.h + this._color.step) % 360;
while (this._color.h < 140) {
this._color.h += this._color.step;
}
return dojo.gfx.color.rgb2hex(rgb[0], rgb[1], rgb[2]);
}, getArea:function () {
return {left:this.padding.left, right:this.size.width - this.padding.right, top:this.padding.top, bottom:this.size.height - this.padding.bottom, toString:function () {
var a = [this.top, this.right, this.bottom, this.left];
return "[" + a.join() + "]";
}};
}, getAxes:function () {
var axes = {};
for (var i = 0; i < this.plots.length; i++) {
var plot = this.plots[i];
axes[plot.axisX.getId()] = {axis:plot.axisX, drawAgainst:plot.axisY, plot:plot, plane:"x"};
axes[plot.axisY.getId()] = {axis:plot.axisY, drawAgainst:plot.axisX, plot:plot, plane:"y"};
}
return axes;
}, getLegendInfo:function () {
var a = [];
for (var i = 0; i < this.plots.length; i++) {
for (var j = 0; j < this.plots[i].series.length; j++) {
var data = this.plots[i].series[j].data;
a.push({label:data.label, color:data.color});
}
}
return a;
}, setAxesRanges:function () {
var ranges = {};
var axes = {};
for (var i = 0; i < this.plots.length; i++) {
var plot = this.plots[i];
var ranges = plot.getRanges();
var x = ranges.x;
var y = ranges.y;
var ax, ay;
if (!axes[plot.axisX.getId()]) {
axes[plot.axisX.getId()] = plot.axisX;
ranges[plot.axisX.getId()] = {upper:x.upper, lower:x.lower};
}
ax = ranges[plot.axisX.getId()];
ax.upper = Math.max(ax.upper, x.upper);
ax.lower = Math.min(ax.lower, x.lower);
if (!axes[plot.axisY.getId()]) {
axes[plot.axisY.getId()] = plot.axisY;
ranges[plot.axisY.getId()] = {upper:y.upper, lower:y.lower};
}
ay = ranges[plot.axisY.getId()];
ay.upper = Math.max(ay.upper, y.upper);
ay.lower = Math.min(ay.lower, y.lower);
}
for (var p in axes) {
axes[p].range = ranges[p];
}
}, render:function (kwArgs, applyToData) {
if (!this.nodes.main || !this.nodes.area || !this.nodes.background || !this.nodes.plots || !this.nodes.axes) {
this.initialize();
}
this.resize();
for (var i = 0; i < this.plots.length; i++) {
var plot = this.plots[i];
if (plot.dataNode) {
this.nodes.plots.removeChild(plot.dataNode);
}
var target = this.initializePlot(plot);
switch (plot.renderType) {
case dojo.charting.RenderPlotSeries.Grouped:
if (plot.series[0]) {
target.appendChild(plot.series[0].plotter(this, plot, kwArgs, applyToData));
}
break;
case dojo.charting.RenderPlotSeries.Singly:
default:
for (var j = 0; j < plot.series.length; j++) {
var series = plot.series[j];
var data = series.data.evaluate(kwArgs);
target.appendChild(series.plotter(data, this, plot, applyToData));
}
}
this.nodes.plots.appendChild(target);
}
}, destroy:function () {
for (var i = 0; i < this.plots.length; i++) {
this.plots[i].destroy();
}
for (var p in this.nodes) {
var node = this.nodes[p];
if (!node) {
continue;
}
if (!node.childNodes) {
continue;
}
while (node.childNodes.length > 0) {
node.removeChild(node.childNodes[0]);
}
this.nodes[p] = null;
}
}});
dojo.requireIf(dojo.render.svg.capable, "dojo.charting.svg.PlotArea");
dojo.requireIf(dojo.render.vml.capable, "dojo.charting.vml.PlotArea");
@@ -8,12 +8,7 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.Plotters");
/*
* Plotters is the placeholder; what will happen is that the proper renderer types
* will be mixed into this object (as opposed to creating a new one).
*/
dojo["requireIf"](dojo.render.svg.capable, "dojo.charting.svg.Plotters");
dojo["requireIf"](!dojo.render.svg.capable && dojo.render.vml.capable, "dojo.charting.vml.Plotters");
dojo.provide("dojo.charting.Plotters");
dojo.requireIf(dojo.render.svg.capable, "dojo.charting.svg.Plotters");
dojo.requireIf(dojo.render.vml.capable, "dojo.charting.vml.Plotters");
@@ -1,46 +1,46 @@
Dojo Charting Engine
=========================================================================
The Dojo Charting Engine is a (fairly) complex object structure, designed
to provide as much flexibility as possible in terms of chart construction.
To this end, the engine details the following structure:
Chart
---PlotArea[]
------Plot[]
---------Axis (axisX)
---------Axis (axisY)
---------Series[]
A Chart object is the main entity; it is the entire graphic. A Chart may
have any number of PlotArea objects, which are the basic canvas against
which data is plotted. A PlotArea may have any number of Plot objects,
which is a container representing up to 2 axes and any number of series
to be plotted against those axes; a Series represents a binding against
two fields from a data source (initial rev, this data source is always of
type dojo.collections.Store but this will probably change once dojo.data
is in production).
The point of this structure is to allow for as much flexibility as possible
in terms of what kinds of charts can be represented by the engine. The
current plan is to accomodate up to analytical financial charts, which tend
to have 3 plot areas and any number of different types of axes on each one.
The main exception to this is the pie chart, which will have it's own
custom codebase. Also, 3D charts are not accounted for at this time,
although the only thing that will probably need to be altered to make
that work would be Plot and Series (to accomodate the additional Z axis).
Finally, a Plot will render its series[] through the use of Plotters, which
are custom methods to render specific types of charts.
-------------------------------------------------------------------------
In terms of widgets, the basic concept is that there is a central, super-
flexible Chart widget (Chart, oddly enough), and then any number of preset
chart type widgets, that are basically built to serve a simple, easy
purpose. For instance, if someone just needs to plot a series of lines,
they would be better off using the LineChart widget; but if someone needed
to plot a combo chart, that has 2 Y Axes (one linear, one log) against the
same X Axis, using lines and areas, then they will want to use a Chart widget.
Note also that unlike other widgets, the Charting engine *can* be called
directly from script *without* the need for the actual widget engine to be
Dojo Charting Engine
=========================================================================
The Dojo Charting Engine is a (fairly) complex object structure, designed
to provide as much flexibility as possible in terms of chart construction.
To this end, the engine details the following structure:
Chart
---PlotArea[]
------Plot[]
---------Axis (axisX)
---------Axis (axisY)
---------Series[]
A Chart object is the main entity; it is the entire graphic. A Chart may
have any number of PlotArea objects, which are the basic canvas against
which data is plotted. A PlotArea may have any number of Plot objects,
which is a container representing up to 2 axes and any number of series
to be plotted against those axes; a Series represents a binding against
two fields from a data source (initial rev, this data source is always of
type dojo.collections.Store but this will probably change once dojo.data
is in production).
The point of this structure is to allow for as much flexibility as possible
in terms of what kinds of charts can be represented by the engine. The
current plan is to accomodate up to analytical financial charts, which tend
to have 3 plot areas and any number of different types of axes on each one.
The main exception to this is the pie chart, which will have it's own
custom codebase. Also, 3D charts are not accounted for at this time,
although the only thing that will probably need to be altered to make
that work would be Plot and Series (to accomodate the additional Z axis).
Finally, a Plot will render its series[] through the use of Plotters, which
are custom methods to render specific types of charts.
-------------------------------------------------------------------------
In terms of widgets, the basic concept is that there is a central, super-
flexible Chart widget (Chart, oddly enough), and then any number of preset
chart type widgets, that are basically built to serve a simple, easy
purpose. For instance, if someone just needs to plot a series of lines,
they would be better off using the LineChart widget; but if someone needed
to plot a combo chart, that has 2 Y Axes (one linear, one log) against the
same X Axis, using lines and areas, then they will want to use a Chart widget.
Note also that unlike other widgets, the Charting engine *can* be called
directly from script *without* the need for the actual widget engine to be
loaded; the Chart widgets are thin wrappers around the charting engine.
@@ -8,208 +8,185 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.Series");
dojo.require("dojo.lang.common");
dojo.require("dojo.charting.Plotters");
dojo.charting.Series = function(/* object? */kwArgs){
// summary
// Create an instance of data series for plotting.
var args = kwArgs || { length:1 };
this.dataSource = args.dataSource || null;
this.bindings = { };
this.color = args.color;
this.label = args.label;
if(args.bindings){
for(var p in args.bindings){
this.addBinding(p, args.bindings[p]);
}
}
};
dojo.extend(dojo.charting.Series, {
bind:function(/* dojo.collections.Store */src, /* object */bindings){
// summary
// Bind this series to src, with bindings.
this.dataSource = src;
this.bindings = bindings;
},
addBinding:function(/* string */name, /* string */binding){
// summary
// Bind to field "binding" using "name".
this.bindings[name] = binding;
},
evaluate:function(/* object? */kwArgs){
// summary
// Evaluate all bindings and return an array of objects describing the bind.
var ret = [];
var a = this.dataSource.getData();
var l = a.length;
var start = 0;
var end = l;
/* Allow for ranges. Can be done in one of two ways:
* 1. { from, to } as 0-based indices
* 2. { length } as num of data points to get; a negative
* value will start from the end of the data set.
* No kwArg object means the full data set will be evaluated
* and returned.
*/
if(kwArgs){
if(kwArgs.from){
start = Math.max(kwArgs.from,0);
if(kwArgs.to){
end = Math.min(kwArgs.to, end);
}
}
else if(kwArgs.length){
if(kwArgs.length < 0){
// length points from end
start = Math.max((end + length),0);
} else {
end = Math.min((start + length), end);
}
}
}
for(var i=start; i<end; i++){
var o = { src: a[i], series: this };
for(var p in this.bindings){
o[p] = this.dataSource.getField(a[i], this.bindings[p]);
}
ret.push(o);
}
// sort by the x axis, if available.
if(typeof(ret[0].x) != "undefined"){
ret.sort(function(a,b){
if(a.x > b.x) return 1;
if(a.x < b.x) return -1;
return 0;
});
}
return ret; // array
},
// trends
trends:{
createRange: function(/* array */values, /* int */len){
// summary
// Creates the data range used for all trends.
var idx = values.length-1;
var length = (len||values.length);
return { "index": idx, "length": length, "start":Math.max(idx-length,0) }; // object
},
mean: function(/* array */values, /* int */len){
// summary
// Returns the mean or average over the set of values.
var range = this.createRange(values, len);
if(range.index<0){ return 0; }
var total = 0;
var count = 0;
for(var i=range.index; i>=range.start; i--){
total += values[i].y;
count++;
}
total /= Math.max(count,1);
return total; // float
},
variance: function(/* array */values,/* int */len){
// summary
// Returns the variance of the set of values.
var range = this.createRange(values,len);
if(range.index < 0){ return 0; }
var total = 0;
var square = 0;
var count = 0;
for(var i=range.index; i>=range.start; i--){
total += values[i].y;
square += Math.pow(values[i].y, 2);
count++;
}
return (square/count)-Math.pow(total/count,2); // float
},
standardDeviation: function(/* array */values, /* int */len){
// summary
// Returns the standard deviation of the set of values.
return Math.sqrt(this.getVariance(values, len)); // float
},
max: function(/* array */values, /* int */len){
// summary
// Returns the max number in the set of values.
var range = this.createRange(values, len);
if(range.index < 0){ return 0; }
var max = Number.MIN_VALUE;
for (var i=range.index; i>=range.start; i--){
max = Math.max(values[i].y,max);
}
return max; // float
},
min: function(/* array */values, /* int */len){
// summary
// Returns the lowest number in the set of values.
var range=this.createRange(values, len);
if(range.index < 0){ return 0; }
var min = Number.MAX_VALUE;
for(var i=range.index; i>=range.start; i--){
min = Math.min(values[i].y, min);
}
return min; // float
},
median: function(/* array */values, /* int */len){
// summary
// Returns the median in the set of values (number closest to the middle of a sorted set).
var range = this.createRange(values, len);
if(range.index<0){ return 0; }
var a = [];
for (var i=range.index; i>=range.start; i--){
var b=false;
for(var j=0; j<a.length; j++){
if(values[i].y == a[j]){
b = true;
break;
}
}
if(!b){
a.push(values[i].y);
}
}
a.sort();
if(a.length > 0){
return a[Math.ceil(a.length / 2)]; // float
}
return 0; // float
},
mode: function(/* array */values, /* int */len){
// summary
// Returns the mode in the set of values
var range=this.createRange(values, len);
if(range.index<0){ return 0; }
var o = {};
var ret = 0
var median = Number.MIN_VALUE;
for(var i=range.index; i>=range.start; i--){
if (!o[values[i].y]){
o[values[i].y] = 1;
} else {
o[values[i].y]++;
}
}
for(var p in o){
if(median < o[p]){
median = o[p];
ret=p;
}
}
return ret;
}
}
});
dojo.provide("dojo.charting.Series");
dojo.require("dojo.lang.common");
dojo.require("dojo.charting.Plotters");
dojo.charting.Series = function (kwArgs) {
var args = kwArgs || {length:1};
this.dataSource = args.dataSource || null;
this.bindings = {};
this.color = args.color;
this.label = args.label;
if (args.bindings) {
for (var p in args.bindings) {
this.addBinding(p, args.bindings[p]);
}
}
};
dojo.extend(dojo.charting.Series, {bind:function (src, bindings) {
this.dataSource = src;
this.bindings = bindings;
}, addBinding:function (name, binding) {
this.bindings[name] = binding;
}, evaluate:function (kwArgs) {
var ret = [];
var a = this.dataSource.getData();
var l = a.length;
var start = 0;
var end = l;
if (kwArgs) {
if (kwArgs.between) {
for (var i = 0; i < l; i++) {
var fld = this.dataSource.getField(a[i], kwArgs.between.field);
if (fld >= kwArgs.between.low && fld <= kwArgs.between.high) {
var o = {src:a[i], series:this};
for (var p in this.bindings) {
o[p] = this.dataSource.getField(a[i], this.bindings[p]);
}
ret.push(o);
}
}
} else {
if (kwArgs.from || kwArgs.length) {
if (kwArgs.from) {
start = Math.max(kwArgs.from, 0);
if (kwArgs.to) {
end = Math.min(kwArgs.to, end);
}
} else {
if (kwArgs.length < 0) {
start = Math.max((end + length), 0);
} else {
end = Math.min((start + length), end);
}
}
for (var i = start; i < end; i++) {
var o = {src:a[i], series:this};
for (var p in this.bindings) {
o[p] = this.dataSource.getField(a[i], this.bindings[p]);
}
ret.push(o);
}
}
}
} else {
for (var i = start; i < end; i++) {
var o = {src:a[i], series:this};
for (var p in this.bindings) {
o[p] = this.dataSource.getField(a[i], this.bindings[p]);
}
ret.push(o);
}
}
if (ret.length > 0 && typeof (ret[0].x) != "undefined") {
ret.sort(function (a, b) {
if (a.x > b.x) {
return 1;
}
if (a.x < b.x) {
return -1;
}
return 0;
});
}
return ret;
}, trends:{createRange:function (values, len) {
var idx = values.length - 1;
var length = (len || values.length);
return {"index":idx, "length":length, "start":Math.max(idx - length, 0)};
}, mean:function (values, len) {
var range = this.createRange(values, len);
if (range.index < 0) {
return 0;
}
var total = 0;
var count = 0;
for (var i = range.index; i >= range.start; i--) {
total += values[i].y;
count++;
}
total /= Math.max(count, 1);
return total;
}, variance:function (values, len) {
var range = this.createRange(values, len);
if (range.index < 0) {
return 0;
}
var total = 0;
var square = 0;
var count = 0;
for (var i = range.index; i >= range.start; i--) {
total += values[i].y;
square += Math.pow(values[i].y, 2);
count++;
}
return (square / count) - Math.pow(total / count, 2);
}, standardDeviation:function (values, len) {
return Math.sqrt(this.getVariance(values, len));
}, max:function (values, len) {
var range = this.createRange(values, len);
if (range.index < 0) {
return 0;
}
var max = Number.MIN_VALUE;
for (var i = range.index; i >= range.start; i--) {
max = Math.max(values[i].y, max);
}
return max;
}, min:function (values, len) {
var range = this.createRange(values, len);
if (range.index < 0) {
return 0;
}
var min = Number.MAX_VALUE;
for (var i = range.index; i >= range.start; i--) {
min = Math.min(values[i].y, min);
}
return min;
}, median:function (values, len) {
var range = this.createRange(values, len);
if (range.index < 0) {
return 0;
}
var a = [];
for (var i = range.index; i >= range.start; i--) {
var b = false;
for (var j = 0; j < a.length; j++) {
if (values[i].y == a[j]) {
b = true;
break;
}
}
if (!b) {
a.push(values[i].y);
}
}
a.sort();
if (a.length > 0) {
return a[Math.ceil(a.length / 2)];
}
return 0;
}, mode:function (values, len) {
var range = this.createRange(values, len);
if (range.index < 0) {
return 0;
}
var o = {};
var ret = 0;
var median = Number.MIN_VALUE;
for (var i = range.index; i >= range.start; i--) {
if (!o[values[i].y]) {
o[values[i].y] = 1;
} else {
o[values[i].y]++;
}
}
for (var p in o) {
if (median < o[p]) {
median = o[p];
ret = p;
}
}
return ret;
}}});
@@ -8,4 +8,5 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.*");
dojo.provide("dojo.charting.*");
@@ -8,217 +8,179 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.svg.Axis");
dojo.require("dojo.lang.common");
dojo.extend(dojo.charting.Axis, {
renderLines: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* string */plane
){
// summary
// Renders any reference lines for this axis.
if(this.nodes.lines){
while(this.nodes.lines.childNodes.length > 0){
this.nodes.lines.removeChild(this.nodes.lines.childNodes[0]);
}
if(this.nodes.lines.parentNode){
this.nodes.lines.parentNode.removeChild(this.nodes.lines);
this.nodes.lines = null;
}
}
var area = plotArea.getArea();
var g = this.nodes.lines = document.createElementNS(dojo.svg.xmlns.svg, "g");
g.setAttribute("id", this.getId()+"-lines");
for(var i=0; i<this._labels.length; i++){
if (this._labels[i].value == this.origin){ continue; }
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l=document.createElementNS(dojo.svg.xmlns.svg, "line");
l.setAttribute("style","stroke:#999;stroke-width:1px;stroke-dasharray:1,4;");
if(plane == "x"){
l.setAttribute("y1",area.top);
l.setAttribute("y2",area.bottom);
l.setAttribute("x1",v);
l.setAttribute("x2",v);
}
else if (plane == "y"){
l.setAttribute("y1",v);
l.setAttribute("y2",v);
l.setAttribute("x1",area.left);
l.setAttribute("x2",area.right);
}
g.appendChild(l);
}
return g; // SVGGElement
},
renderTicks: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* string */plane,
/* float */coord
){
// summary
// Renders any tick lines for this axis.
if(this.nodes.ticks){
while(this.nodes.ticks.childNodes.length > 0){
this.nodes.ticks.removeChild(this.nodes.ticks.childNodes[0]);
}
if(this.nodes.ticks.parentNode){
this.nodes.ticks.parentNode.removeChild(this.nodes.ticks);
this.nodes.ticks = null;
}
}
var g = this.nodes.ticks = document.createElementNS(dojo.svg.xmlns.svg, "g");
g.setAttribute("id", this.getId()+"-ticks");
for(var i=0; i<this._labels.length; i++){
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l=document.createElementNS(dojo.svg.xmlns.svg, "line");
l.setAttribute("style","stroke:#000;stroke-width:1pt;");
if(plane == "x"){
l.setAttribute("y1",coord);
l.setAttribute("y2",coord+3);
l.setAttribute("x1",v);
l.setAttribute("x2",v);
}
else if (plane == "y"){
l.setAttribute("y1",v);
l.setAttribute("y2",v);
l.setAttribute("x1",coord-2);
l.setAttribute("x2",coord+2);
}
g.appendChild(l);
}
return g; // SVGGElement
},
renderLabels: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* string */plane,
/* float */coord,
/* int */textSize,
/* string */anchor
){
// summary
// Render all labels for this axis.
function createLabel(label, x, y, textSize, anchor){
var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
text.setAttribute("x", x);
text.setAttribute("y", (plane=="x"?y:y+2));
text.setAttribute("style", "text-anchor:"+anchor+";font-family:sans-serif;font-size:"+textSize+"px;fill:#000;");
text.appendChild(document.createTextNode(label));
return text;
};
// wipe if needed
if(this.nodes.labels){
while(this.nodes.labels.childNodes.length > 0){
this.nodes.labels.removeChild(this.nodes.labels.childNodes[0]);
}
if(this.nodes.labels.parentNode){
this.nodes.labels.parentNode.removeChild(this.nodes.labels);
this.nodes.labels = null;
}
}
var g = this.nodes.labels = document.createElementNS(dojo.svg.xmlns.svg, "g");
g.setAttribute("id", this.getId()+"-labels");
for(var i=0; i<this._labels.length; i++){
var v = this.getCoord(this._labels[i].value, plotArea, plot);
if(plane == "x"){
g.appendChild(createLabel(this._labels[i].label, v, coord, textSize, anchor));
}
else if (plane == "y"){
g.appendChild(createLabel(this._labels[i].label, coord, v, textSize, anchor));
}
}
return g; // SVGGelement
},
render: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* dojo.charting.Axis */drawAgainst,
/* string */plane
){
// summary
// Renders this axis to the given plot.
// get the origin plot point.
var area = plotArea.getArea();
var stroke = 1;
var style = "stroke:#000;stroke-width:"+stroke+"px;";
var textSize=10;
var coord = drawAgainst.getCoord(this.origin, plotArea, plot);
// draw the axis.
this.nodes.main = document.createElementNS(dojo.svg.xmlns.svg, "g");
var g = this.nodes.main;
g.setAttribute("id", this.getId()); // need a handle if we have to kill parts of the axis def.
var line = this.nodes.axis = document.createElementNS(dojo.svg.xmlns.svg, "line");
if(plane == "x"){
line.setAttribute("y1", coord);
line.setAttribute("y2", coord);
line.setAttribute("x1", area.left-stroke);
line.setAttribute("x2", area.right+stroke);
line.setAttribute("style", style);
// set up the labels
var y = coord+textSize+2;
if(this.showLines){
g.appendChild(this.renderLines(plotArea, plot, plane, y));
}
if(this.showTicks){
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if(this.showLabels){
g.appendChild(this.renderLabels(plotArea, plot, plane, y, textSize, "middle"));
}
if(this.showLabel && this.label){
var x = plotArea.size.width/2;
var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
text.setAttribute("x", x);
text.setAttribute("y", (coord + (textSize*2) + (textSize/2)));
text.setAttribute("style", "text-anchor:middle;font-family:sans-serif;font-weight:bold;font-size:"+(textSize+2)+"px;fill:#000;");
text.appendChild(document.createTextNode(this.label));
g.appendChild(text);
}
} else {
line.setAttribute("x1", coord);
line.setAttribute("x2", coord);
line.setAttribute("y1", area.top);
line.setAttribute("y2", area.bottom);
line.setAttribute("style", style);
// set up the labels
var isMax = this.origin == drawAgainst.range.upper;
var x = coord + (isMax?4:-4);
var anchor = isMax?"start":"end";
if(this.showLines){
g.appendChild(this.renderLines(plotArea, plot, plane, x));
}
if(this.showTicks){
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if(this.showLabels){
g.appendChild(this.renderLabels(plotArea, plot, plane, x, textSize, anchor));
}
if(this.showLabel && this.label){
var x = isMax?(coord+(textSize*2)+(textSize/2)):(coord-(textSize*4));
var y = plotArea.size.height / 2;
var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
text.setAttribute("x", x);
text.setAttribute("y", y);
text.setAttribute("transform", "rotate(90, " + x + ", " + y + ")");
text.setAttribute("style", "text-anchor:middle;font-family:sans-serif;font-weight:bold;font-size:"+(textSize+2)+"px;fill:#000;");
text.appendChild(document.createTextNode(this.label));
g.appendChild(text);
}
}
g.appendChild(line);
return g; // SVGGElement
}
});
dojo.provide("dojo.charting.svg.Axis");
dojo.require("dojo.lang.common");
if (dojo.render.svg.capable) {
dojo.extend(dojo.charting.Axis, {renderLines:function (plotArea, plot, plane) {
if (this.nodes.lines) {
while (this.nodes.lines.childNodes.length > 0) {
this.nodes.lines.removeChild(this.nodes.lines.childNodes[0]);
}
if (this.nodes.lines.parentNode) {
this.nodes.lines.parentNode.removeChild(this.nodes.lines);
this.nodes.lines = null;
}
}
var area = plotArea.getArea();
var g = this.nodes.lines = document.createElementNS(dojo.svg.xmlns.svg, "g");
g.setAttribute("id", this.getId() + "-lines");
for (var i = 0; i < this._labels.length; i++) {
if (this._labels[i].value == this.origin) {
continue;
}
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l = document.createElementNS(dojo.svg.xmlns.svg, "line");
l.setAttribute("style", "stroke:#999;stroke-width:1px;stroke-dasharray:1,4;");
if (plane == "x") {
l.setAttribute("y1", area.top);
l.setAttribute("y2", area.bottom);
l.setAttribute("x1", v);
l.setAttribute("x2", v);
} else {
if (plane == "y") {
l.setAttribute("y1", v);
l.setAttribute("y2", v);
l.setAttribute("x1", area.left);
l.setAttribute("x2", area.right);
}
}
g.appendChild(l);
}
return g;
}, renderTicks:function (plotArea, plot, plane, coord) {
if (this.nodes.ticks) {
while (this.nodes.ticks.childNodes.length > 0) {
this.nodes.ticks.removeChild(this.nodes.ticks.childNodes[0]);
}
if (this.nodes.ticks.parentNode) {
this.nodes.ticks.parentNode.removeChild(this.nodes.ticks);
this.nodes.ticks = null;
}
}
var g = this.nodes.ticks = document.createElementNS(dojo.svg.xmlns.svg, "g");
g.setAttribute("id", this.getId() + "-ticks");
for (var i = 0; i < this._labels.length; i++) {
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l = document.createElementNS(dojo.svg.xmlns.svg, "line");
l.setAttribute("style", "stroke:#000;stroke-width:1pt;");
if (plane == "x") {
l.setAttribute("y1", coord);
l.setAttribute("y2", coord + 3);
l.setAttribute("x1", v);
l.setAttribute("x2", v);
} else {
if (plane == "y") {
l.setAttribute("y1", v);
l.setAttribute("y2", v);
l.setAttribute("x1", coord - 2);
l.setAttribute("x2", coord + 2);
}
}
g.appendChild(l);
}
return g;
}, renderLabels:function (plotArea, plot, plane, coord, textSize, anchor) {
function createLabel(label, x, y, textSize, anchor) {
var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
text.setAttribute("x", x);
text.setAttribute("y", (plane == "x" ? y : y + 2));
text.setAttribute("style", "text-anchor:" + anchor + ";font-family:sans-serif;font-size:" + textSize + "px;fill:#000;");
text.appendChild(document.createTextNode(label));
return text;
}
if (this.nodes.labels) {
while (this.nodes.labels.childNodes.length > 0) {
this.nodes.labels.removeChild(this.nodes.labels.childNodes[0]);
}
if (this.nodes.labels.parentNode) {
this.nodes.labels.parentNode.removeChild(this.nodes.labels);
this.nodes.labels = null;
}
}
var g = this.nodes.labels = document.createElementNS(dojo.svg.xmlns.svg, "g");
g.setAttribute("id", this.getId() + "-labels");
for (var i = 0; i < this._labels.length; i++) {
var v = this.getCoord(this._labels[i].value, plotArea, plot);
if (plane == "x") {
g.appendChild(createLabel(this._labels[i].label, v, coord, textSize, anchor));
} else {
if (plane == "y") {
g.appendChild(createLabel(this._labels[i].label, coord, v, textSize, anchor));
}
}
}
return g;
}, render:function (plotArea, plot, drawAgainst, plane) {
if (!this._rerender && this.nodes.main) {
return this.nodes.main;
}
this._rerender = false;
var area = plotArea.getArea();
var stroke = 1;
var style = "stroke:#000;stroke-width:" + stroke + "px;";
var textSize = 10;
var coord = drawAgainst.getCoord(this.origin, plotArea, plot);
this.nodes.main = document.createElementNS(dojo.svg.xmlns.svg, "g");
var g = this.nodes.main;
g.setAttribute("id", this.getId());
var line = this.nodes.axis = document.createElementNS(dojo.svg.xmlns.svg, "line");
if (plane == "x") {
line.setAttribute("y1", coord);
line.setAttribute("y2", coord);
line.setAttribute("x1", area.left - stroke);
line.setAttribute("x2", area.right + stroke);
line.setAttribute("style", style);
var y = coord + textSize + 2;
if (this.showLines) {
g.appendChild(this.renderLines(plotArea, plot, plane, y));
}
if (this.showTicks) {
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if (this.showLabels) {
g.appendChild(this.renderLabels(plotArea, plot, plane, y, textSize, "middle"));
}
if (this.showLabel && this.label) {
var x = plotArea.size.width / 2;
var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
text.setAttribute("x", x);
text.setAttribute("y", (coord + (textSize * 2) + (textSize / 2)));
text.setAttribute("style", "text-anchor:middle;font-family:sans-serif;font-weight:bold;font-size:" + (textSize + 2) + "px;fill:#000;");
text.appendChild(document.createTextNode(this.label));
g.appendChild(text);
}
} else {
line.setAttribute("x1", coord);
line.setAttribute("x2", coord);
line.setAttribute("y1", area.top);
line.setAttribute("y2", area.bottom);
line.setAttribute("style", style);
var isMax = this.origin == drawAgainst.range.upper;
var x = coord + (isMax ? 4 : -4);
var anchor = isMax ? "start" : "end";
if (this.showLines) {
g.appendChild(this.renderLines(plotArea, plot, plane, x));
}
if (this.showTicks) {
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if (this.showLabels) {
g.appendChild(this.renderLabels(plotArea, plot, plane, x, textSize, anchor));
}
if (this.showLabel && this.label) {
var x = isMax ? (coord + (textSize * 2) + (textSize / 2)) : (coord - (textSize * 4));
var y = plotArea.size.height / 2;
var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
text.setAttribute("x", x);
text.setAttribute("y", y);
text.setAttribute("transform", "rotate(90, " + x + ", " + y + ")");
text.setAttribute("style", "text-anchor:middle;font-family:sans-serif;font-weight:bold;font-size:" + (textSize + 2) + "px;fill:#000;");
text.appendChild(document.createTextNode(this.label));
g.appendChild(text);
}
}
g.appendChild(line);
return g;
}});
}
@@ -8,72 +8,68 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.svg.PlotArea");
dojo.require("dojo.lang.common");
dojo.require("dojo.svg");
dojo.extend(dojo.charting.PlotArea, {
initializePlot: function(plot){
// summary
// Initialize the plot node for data rendering.
plot.destroy();
plot.dataNode = document.createElementNS(dojo.svg.xmlns.svg, "g");
plot.dataNode.setAttribute("id", plot.getId());
return plot.dataNode; // SVGGElement
},
initialize: function(){
// summary
// Initialize the PlotArea.
this.destroy(); // kill everything first.
// start with the background
this.nodes.main = document.createElement("div");
this.nodes.area = document.createElementNS(dojo.svg.xmlns.svg, "svg");
this.nodes.area.setAttribute("id", this.getId());
this.nodes.area.setAttribute("width", this.size.width);
this.nodes.area.setAttribute("height", this.size.height);
this.nodes.main.appendChild(this.nodes.area);
var area=this.getArea();
var defs = document.createElementNS(dojo.svg.xmlns.svg, "defs");
var clip = document.createElementNS(dojo.svg.xmlns.svg, "clipPath");
clip.setAttribute("id",this.getId()+"-clip");
var rect = document.createElementNS(dojo.svg.xmlns.svg, "rect");
rect.setAttribute("x", area.left);
rect.setAttribute("y", area.top);
rect.setAttribute("width", area.right-area.left);
rect.setAttribute("height", area.bottom-area.top);
clip.appendChild(rect);
defs.appendChild(clip);
this.nodes.area.appendChild(defs);
this.nodes.background = document.createElementNS(dojo.svg.xmlns.svg, "rect");
this.nodes.background.setAttribute("id", this.getId()+"-background");
this.nodes.background.setAttribute("width", this.size.width);
this.nodes.background.setAttribute("height", this.size.height);
this.nodes.background.setAttribute("fill", "#fff");
this.nodes.area.appendChild(this.nodes.background);
this.nodes.plots = document.createElementNS(dojo.svg.xmlns.svg, "g");
this.nodes.plots.setAttribute("id", this.getId()+"-plots");
this.nodes.plots.setAttribute("style","clip-path:url(#"+this.getId()+"-clip);");
this.nodes.area.appendChild(this.nodes.plots);
for(var i=0; i<this.plots.length; i++){
this.nodes.plots.appendChild(this.initializePlot(this.plots[i]));
}
// do the axes
this.nodes.axes = document.createElementNS(dojo.svg.xmlns.svg, "g");
this.nodes.axes.setAttribute("id", this.getId()+"-axes");
this.nodes.area.appendChild(this.nodes.axes);
var axes = this.getAxes();
for(var p in axes){
var obj = axes[p];
this.nodes.axes.appendChild(obj.axis.initialize(this, obj.plot, obj.drawAgainst, obj.plane));
}
return this.nodes.main; // HTMLDivElement
}
});
dojo.provide("dojo.charting.svg.PlotArea");
dojo.require("dojo.lang.common");
if (dojo.render.svg.capable) {
dojo.require("dojo.svg");
dojo.extend(dojo.charting.PlotArea, {resize:function () {
var area = this.getArea();
this.nodes.area.setAttribute("width", this.size.width);
this.nodes.area.setAttribute("height", this.size.height);
var rect = this.nodes.area.getElementsByTagName("rect")[0];
rect.setAttribute("x", area.left);
rect.setAttribute("y", area.top);
rect.setAttribute("width", area.right - area.left);
rect.setAttribute("height", area.bottom - area.top);
this.nodes.background.setAttribute("width", this.size.width);
this.nodes.background.setAttribute("height", this.size.height);
if (this.nodes.plots) {
this.nodes.area.removeChild(this.nodes.plots);
this.nodes.plots = null;
}
this.nodes.plots = document.createElementNS(dojo.svg.xmlns.svg, "g");
this.nodes.plots.setAttribute("id", this.getId() + "-plots");
this.nodes.plots.setAttribute("style", "clip-path:url(#" + this.getId() + "-clip);");
this.nodes.area.appendChild(this.nodes.plots);
for (var i = 0; i < this.plots.length; i++) {
this.nodes.plots.appendChild(this.initializePlot(this.plots[i]));
}
if (this.nodes.axes) {
this.nodes.area.removeChild(this.nodes.axes);
this.nodes.axes = null;
}
this.nodes.axes = document.createElementNS(dojo.svg.xmlns.svg, "g");
this.nodes.axes.setAttribute("id", this.getId() + "-axes");
this.nodes.area.appendChild(this.nodes.axes);
var axes = this.getAxes();
for (var p in axes) {
var obj = axes[p];
this.nodes.axes.appendChild(obj.axis.initialize(this, obj.plot, obj.drawAgainst, obj.plane));
}
}, initializePlot:function (plot) {
plot.destroy();
plot.dataNode = document.createElementNS(dojo.svg.xmlns.svg, "g");
plot.dataNode.setAttribute("id", plot.getId());
return plot.dataNode;
}, initialize:function () {
this.destroy();
this.nodes.main = document.createElement("div");
this.nodes.area = document.createElementNS(dojo.svg.xmlns.svg, "svg");
this.nodes.area.setAttribute("id", this.getId());
this.nodes.main.appendChild(this.nodes.area);
var defs = document.createElementNS(dojo.svg.xmlns.svg, "defs");
var clip = document.createElementNS(dojo.svg.xmlns.svg, "clipPath");
clip.setAttribute("id", this.getId() + "-clip");
var rect = document.createElementNS(dojo.svg.xmlns.svg, "rect");
clip.appendChild(rect);
defs.appendChild(clip);
this.nodes.area.appendChild(defs);
this.nodes.background = document.createElementNS(dojo.svg.xmlns.svg, "rect");
this.nodes.background.setAttribute("id", this.getId() + "-background");
this.nodes.background.setAttribute("fill", "#fff");
this.nodes.area.appendChild(this.nodes.background);
this.resize();
return this.nodes.main;
}});
}
@@ -8,263 +8,230 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.vml.Axis");
dojo.require("dojo.lang.common");
dojo.extend(dojo.charting.Axis, {
renderLines: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* string */plane
){
// summary
// Renders any reference lines for this axis.
if(this.nodes.lines){
while(this.nodes.lines.childNodes.length > 0){
this.nodes.lines.removeChild(this.nodes.lines.childNodes[0]);
}
if(this.nodes.lines.parentNode){
this.nodes.lines.parentNode.removeChild(this.nodes.lines);
this.nodes.lines = null;
}
}
var area = plotArea.getArea();
var g = this.nodes.lines = document.createElement("div");
g.setAttribute("id", this.getId()+"-lines");
for(var i=0; i<this._labels.length; i++){
if (this._labels[i].value == this.origin){ continue; }
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l=document.createElement("v:line");
var str=document.createElement("v:stroke");
str.dashstyle="dot";
l.appendChild(str);
l.setAttribute("strokecolor", "#666");
l.setAttribute("strokeweight", "1px");
var s=l.style;
s.position="absolute";
s.top="0px";
s.left="0px";
s.antialias="false";
if(plane == "x"){
l.setAttribute("from", v+"px,"+area.top+"px");
l.setAttribute("to", v+"px,"+area.bottom+"px");
}
else if (plane == "y"){
l.setAttribute("from", area.left+"px,"+v+"px");
l.setAttribute("to", area.right+"px,"+v+"px");
}
g.appendChild(l);
}
return g; // HTMLDivElement
},
renderTicks: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* string */plane,
/* float */coord
){
// summary
// Renders any tick lines for this axis.
if(this.nodes.ticks){
while(this.nodes.ticks.childNodes.length > 0){
this.nodes.ticks.removeChild(this.nodes.ticks.childNodes[0]);
}
if(this.nodes.ticks.parentNode){
this.nodes.ticks.parentNode.removeChild(this.nodes.ticks);
this.nodes.ticks = null;
}
}
var g = this.nodes.ticks = document.createElement("div");
g.setAttribute("id", this.getId()+"-ticks");
for(var i=0; i<this._labels.length; i++){
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l=document.createElement("v:line");
l.setAttribute("strokecolor", "#000");
l.setAttribute("strokeweight", "1px");
var s=l.style;
s.position="absolute";
s.top="0px";
s.left="0px";
s.antialias="false";
if(plane == "x"){
l.setAttribute("from", v+"px,"+coord+"px");
l.setAttribute("to", v+"px,"+(coord+3)+"px");
}
else if (plane == "y"){
l.setAttribute("from", (coord-2)+"px,"+v+"px");
l.setAttribute("to", (coord+2)+"px,"+v+"px");
}
g.appendChild(l);
}
return g; // HTMLDivElement
},
renderLabels: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* string */plane,
/* float */coord,
/* int */textSize,
/* string */anchor
){
// summary
// Render all labels for this axis.
function createLabel(label, x, y, textSize, anchor){
var text = document.createElement("div");
var s=text.style;
text.innerHTML=label;
s.fontSize=textSize+"px";
s.fontFamily="sans-serif";
s.position="absolute";
s.top = y+"px";
if(anchor == "center"){
s.left = x + "px";
s.textAlign="center";
} else if (anchor == "left"){
s.left = x + "px";
s.textAlign="left";
} else if (anchor == "right"){
s.right = x + "px";
s.textAlign="right";
}
return text;
};
// wipe if needed
if(this.nodes.labels){
while(this.nodes.labels.childNodes.length > 0){
this.nodes.labels.removeChild(this.nodes.labels.childNodes[0]);
}
if(this.nodes.labels.parentNode){
this.nodes.labels.parentNode.removeChild(this.nodes.labels);
this.nodes.labels = null;
}
}
var g = this.nodes.labels = document.createElement("div");
g.setAttribute("id", this.getId()+"-labels");
for(var i=0; i<this._labels.length; i++){
var v = this.getCoord(this._labels[i].value, plotArea, plot);
if(plane == "x"){
// ugly hack but it works.
var node=createLabel(this._labels[i].label, v, coord, textSize, anchor);
document.body.appendChild(node);
node.style.left = v-(node.offsetWidth/2)+"px";
g.appendChild(node);
}
else if (plane == "y"){
var node = createLabel(this._labels[i].label, coord, v, textSize, anchor);
document.body.appendChild(node);
node.style.top = v-(node.offsetHeight/2)+"px";
g.appendChild(node);
}
}
return g; // HTMLDivElement
},
render: function(
/* dojo.charting.PlotArea */plotArea,
/* dojo.charting.Plot */plot,
/* dojo.charting.Axis */drawAgainst,
/* string */plane
){
// summary
// Renders this axis to the given plot.
// get the origin plot point.
var area = plotArea.getArea();
var stroke = 1;
var style = "stroke:#000;stroke-width:"+stroke+"px;";
var textSize=10;
var coord = drawAgainst.getCoord(this.origin, plotArea, plot);
// draw the axis.
var g = this.nodes.main = document.createElement("div");
g.setAttribute("id", this.getId()); // need a handle if we have to kill parts of the axis def.
var line = this.nodes.axis = document.createElement("v:line");
line.setAttribute("strokecolor", "#000");
line.setAttribute("strokeweight", stroke+"px");
var s=line.style;
s.position="absolute";
s.top="0px";
s.left="0px";
s.antialias="false";
if(plane == "x"){
line.setAttribute("from", area.left+"px,"+coord+"px");
line.setAttribute("to", area.right+"px,"+coord+"px");
// set up the labels
var y = coord + Math.floor(textSize/2);
if(this.showLines){
g.appendChild(this.renderLines(plotArea, plot, plane, y));
}
if(this.showTicks){
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if(this.showLabels){
g.appendChild(this.renderLabels(plotArea, plot, plane, y, textSize, "center"));
}
if(this.showLabel && this.label){
var x = plotArea.size.width/2;
var y = coord + Math.round(textSize*1.5);
var text = document.createElement("div");
var s=text.style;
text.innerHTML=this.label;
s.fontSize=(textSize+2)+"px";
s.fontFamily="sans-serif";
s.fontWeight="bold";
s.position="absolute";
s.top = y+"px";
s.left = x + "px";
s.textAlign="center";
document.body.appendChild(text);
text.style.left = x-(text.offsetWidth/2)+"px";
g.appendChild(text);
}
} else {
line.setAttribute("from", coord+"px,"+area.top+"px");
line.setAttribute("to", coord+"px,"+area.bottom+"px");
// set up the labels
var isMax = this.origin == drawAgainst.range.upper;
var x = coord+4;
var anchor = "left";
if(!isMax){
x = area.right-coord+textSize+4;
anchor = "right";
if(coord == area.left){ x += (textSize*2)-(textSize/2); }
}
if(this.showLines){
g.appendChild(this.renderLines(plotArea, plot, plane, x));
}
if(this.showTicks){
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if(this.showLabels){
g.appendChild(this.renderLabels(plotArea, plot, plane, x, textSize, anchor));
}
if(this.showLabel && this.label){
x += (textSize*2)-2;
var y = plotArea.size.height/2;
var text = document.createElement("div");
var s=text.style;
text.innerHTML=this.label;
s.fontSize=(textSize+2)+"px";
s.fontFamily="sans-serif";
s.fontWeight="bold";
s.position="absolute";
s.height = plotArea.size.height+"px";
s.writingMode = "tb-rl";
s.textAlign="center";
s[anchor] = x+"px";
document.body.appendChild(text);
s.top = y-(text.offsetHeight/2)+"px";
g.appendChild(text);
}
}
g.appendChild(line);
return g; // HTMLDivElement
}
});
dojo.provide("dojo.charting.vml.Axis");
dojo.require("dojo.lang.common");
if (dojo.render.vml.capable) {
dojo.extend(dojo.charting.Axis, {renderLines:function (plotArea, plot, plane) {
if (this.nodes.lines) {
while (this.nodes.lines.childNodes.length > 0) {
this.nodes.lines.removeChild(this.nodes.lines.childNodes[0]);
}
if (this.nodes.lines.parentNode) {
this.nodes.lines.parentNode.removeChild(this.nodes.lines);
this.nodes.lines = null;
}
}
var area = plotArea.getArea();
var g = this.nodes.lines = document.createElement("div");
g.setAttribute("id", this.getId() + "-lines");
for (var i = 0; i < this._labels.length; i++) {
if (this._labels[i].value == this.origin) {
continue;
}
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l = document.createElement("v:line");
var str = document.createElement("v:stroke");
str.dashstyle = "dot";
l.appendChild(str);
l.setAttribute("strokecolor", "#666");
l.setAttribute("strokeweight", "1px");
var s = l.style;
s.position = "absolute";
s.top = "0px";
s.left = "0px";
s.antialias = "false";
if (plane == "x") {
l.setAttribute("from", v + "px," + area.top + "px");
l.setAttribute("to", v + "px," + area.bottom + "px");
} else {
if (plane == "y") {
l.setAttribute("from", area.left + "px," + v + "px");
l.setAttribute("to", area.right + "px," + v + "px");
}
}
g.appendChild(l);
}
return g;
}, renderTicks:function (plotArea, plot, plane, coord) {
if (this.nodes.ticks) {
while (this.nodes.ticks.childNodes.length > 0) {
this.nodes.ticks.removeChild(this.nodes.ticks.childNodes[0]);
}
if (this.nodes.ticks.parentNode) {
this.nodes.ticks.parentNode.removeChild(this.nodes.ticks);
this.nodes.ticks = null;
}
}
var g = this.nodes.ticks = document.createElement("div");
g.setAttribute("id", this.getId() + "-ticks");
for (var i = 0; i < this._labels.length; i++) {
var v = this.getCoord(this._labels[i].value, plotArea, plot);
var l = document.createElement("v:line");
l.setAttribute("strokecolor", "#000");
l.setAttribute("strokeweight", "1px");
var s = l.style;
s.position = "absolute";
s.top = "0px";
s.left = "0px";
s.antialias = "false";
if (plane == "x") {
l.setAttribute("from", v + "px," + coord + "px");
l.setAttribute("to", v + "px," + (coord + 3) + "px");
} else {
if (plane == "y") {
l.setAttribute("from", (coord - 2) + "px," + v + "px");
l.setAttribute("to", (coord + 2) + "px," + v + "px");
}
}
g.appendChild(l);
}
return g;
}, renderLabels:function (plotArea, plot, plane, coord, textSize, anchor) {
function createLabel(label, x, y, textSize, anchor) {
var text = document.createElement("div");
var s = text.style;
text.innerHTML = label;
s.fontSize = textSize + "px";
s.fontFamily = "sans-serif";
s.position = "absolute";
s.top = y + "px";
if (anchor == "center") {
s.left = x + "px";
s.textAlign = "center";
} else {
if (anchor == "left") {
s.left = x + "px";
s.textAlign = "left";
} else {
if (anchor == "right") {
s.right = x + "px";
s.textAlign = "right";
}
}
}
return text;
}
if (this.nodes.labels) {
while (this.nodes.labels.childNodes.length > 0) {
this.nodes.labels.removeChild(this.nodes.labels.childNodes[0]);
}
if (this.nodes.labels.parentNode) {
this.nodes.labels.parentNode.removeChild(this.nodes.labels);
this.nodes.labels = null;
}
}
var g = this.nodes.labels = document.createElement("div");
g.setAttribute("id", this.getId() + "-labels");
for (var i = 0; i < this._labels.length; i++) {
var v = this.getCoord(this._labels[i].value, plotArea, plot);
if (plane == "x") {
var node = createLabel(this._labels[i].label, v, coord, textSize, anchor);
document.body.appendChild(node);
node.style.left = v - (node.offsetWidth / 2) + "px";
g.appendChild(node);
} else {
if (plane == "y") {
var node = createLabel(this._labels[i].label, coord, v, textSize, anchor);
document.body.appendChild(node);
node.style.top = v - (node.offsetHeight / 2) + "px";
g.appendChild(node);
}
}
}
return g;
}, render:function (plotArea, plot, drawAgainst, plane) {
if (!this._rerender && this.nodes.main) {
return this.nodes.main;
}
this._rerender = false;
var area = plotArea.getArea();
var stroke = 1;
var style = "stroke:#000;stroke-width:" + stroke + "px;";
var textSize = 10;
var coord = drawAgainst.getCoord(this.origin, plotArea, plot);
var g = this.nodes.main = document.createElement("div");
g.setAttribute("id", this.getId());
var line = this.nodes.axis = document.createElement("v:line");
line.setAttribute("strokecolor", "#000");
line.setAttribute("strokeweight", stroke + "px");
var s = line.style;
s.position = "absolute";
s.top = "0px";
s.left = "0px";
s.antialias = "false";
if (plane == "x") {
line.setAttribute("from", area.left + "px," + coord + "px");
line.setAttribute("to", area.right + "px," + coord + "px");
var y = coord + Math.floor(textSize / 2);
if (this.showLines) {
g.appendChild(this.renderLines(plotArea, plot, plane, y));
}
if (this.showTicks) {
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if (this.showLabels) {
g.appendChild(this.renderLabels(plotArea, plot, plane, y, textSize, "center"));
}
if (this.showLabel && this.label) {
var x = plotArea.size.width / 2;
var y = coord + Math.round(textSize * 1.5);
var text = document.createElement("div");
var s = text.style;
text.innerHTML = this.label;
s.fontSize = (textSize + 2) + "px";
s.fontFamily = "sans-serif";
s.fontWeight = "bold";
s.position = "absolute";
s.top = y + "px";
s.left = x + "px";
s.textAlign = "center";
document.body.appendChild(text);
text.style.left = x - (text.offsetWidth / 2) + "px";
g.appendChild(text);
}
} else {
line.setAttribute("from", coord + "px," + area.top + "px");
line.setAttribute("to", coord + "px," + area.bottom + "px");
var isMax = this.origin == drawAgainst.range.upper;
var x = coord + 4;
var anchor = "left";
if (!isMax) {
x = area.right - coord + textSize + 4;
anchor = "right";
if (coord == area.left) {
x += (textSize * 2) - (textSize / 2);
}
}
if (this.showLines) {
g.appendChild(this.renderLines(plotArea, plot, plane, x));
}
if (this.showTicks) {
g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
}
if (this.showLabels) {
g.appendChild(this.renderLabels(plotArea, plot, plane, x, textSize, anchor));
}
if (this.showLabel && this.label) {
x += (textSize * 2) - 2;
var y = plotArea.size.height / 2;
var text = document.createElement("div");
var s = text.style;
text.innerHTML = this.label;
s.fontSize = (textSize + 2) + "px";
s.fontFamily = "sans-serif";
s.fontWeight = "bold";
s.position = "absolute";
s.height = plotArea.size.height + "px";
s.writingMode = "tb-rl";
s.textAlign = "center";
s[anchor] = x + "px";
document.body.appendChild(text);
s.top = y - (text.offsetHeight / 2) + "px";
g.appendChild(text);
}
}
g.appendChild(line);
return g;
}});
}
@@ -8,71 +8,60 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.charting.vml.PlotArea");
dojo.require("dojo.lang.common");
dojo.extend(dojo.charting.PlotArea, {
initializePlot: function(plot){
// summary
// Initialize the plot node for data rendering.
plot.destroy();
plot.dataNode = document.createElement("div");
plot.dataNode.id = plot.getId();
return plot.dataNode; // HTMLDivElement
},
initialize:function(){
// summary
// Initialize the PlotArea.
this.destroy(); // kill everything first.
var main = this.nodes.main = document.createElement("div");
// start with the background
var area = this.nodes.area = document.createElement("div");
area.id = this.getId();
area.style.width=this.size.width+"px";
area.style.height=this.size.height+"px";
area.style.position="absolute";
main.appendChild(area);
var bg = this.nodes.background = document.createElement("div");
bg.id = this.getId()+"-background";
bg.style.width=this.size.width+"px";
bg.style.height=this.size.height+"px";
bg.style.position="absolute";
bg.style.top="0px";
bg.style.left="0px";
bg.style.backgroundColor="#fff";
area.appendChild(bg);
// the plot group
var a=this.getArea();
var plots = this.nodes.plots = document.createElement("div");
plots.id = this.getId()+"-plots";
plots.style.width=this.size.width+"px";
plots.style.height=this.size.height+"px";
plots.style.position="absolute";
plots.style.top="0px";
plots.style.left="0px";
plots.style.clip="rect("
+ a.top+" "
+ a.right+" "
+ a.bottom+" "
+ a.left
+")";
area.appendChild(plots);
for(var i=0; i<this.plots.length; i++){
plots.appendChild(this.initializePlot(this.plots[i]));
}
var axes = this.nodes.axes = document.createElement("div");
axes.id = this.getId() + "-axes";
area.appendChild(axes);
var ax = this.getAxes();
for(var p in ax){
var obj = ax[p];
axes.appendChild(obj.axis.initialize(this, obj.plot, obj.drawAgainst, obj.plane));
}
return main; // HTMLDivElement
}
});
dojo.provide("dojo.charting.vml.PlotArea");
dojo.require("dojo.lang.common");
if (dojo.render.vml.capable) {
dojo.extend(dojo.charting.PlotArea, {resize:function () {
var a = this.getArea();
this.nodes.area.style.width = this.size.width + "px";
this.nodes.area.style.height = this.size.height + "px";
this.nodes.background.style.width = this.size.width + "px";
this.nodes.background.style.height = this.size.height + "px";
this.nodes.plots.width = this.size.width + "px";
this.nodes.plots.height = this.size.height + "px";
this.nodes.plots.style.clip = "rect(" + a.top + " " + a.right + " " + a.bottom + " " + a.left + ")";
if (this.nodes.axes) {
this.nodes.area.removeChild(this.nodes.axes);
}
var axes = this.nodes.axes = document.createElement("div");
axes.id = this.getId() + "-axes";
this.nodes.area.appendChild(axes);
var ax = this.getAxes();
for (var p in ax) {
var obj = ax[p];
axes.appendChild(obj.axis.initialize(this, obj.plot, obj.drawAgainst, obj.plane));
}
}, initializePlot:function (plot) {
plot.destroy();
plot.dataNode = document.createElement("div");
plot.dataNode.id = plot.getId();
return plot.dataNode;
}, initialize:function () {
this.destroy();
var main = this.nodes.main = document.createElement("div");
var area = this.nodes.area = document.createElement("div");
area.id = this.getId();
area.style.position = "absolute";
main.appendChild(area);
var bg = this.nodes.background = document.createElement("div");
bg.id = this.getId() + "-background";
bg.style.position = "absolute";
bg.style.top = "0px";
bg.style.left = "0px";
bg.style.backgroundColor = "#fff";
area.appendChild(bg);
var a = this.getArea();
var plots = this.nodes.plots = document.createElement("div");
plots.id = this.getId() + "-plots";
plots.style.position = "absolute";
plots.style.top = "0px";
plots.style.left = "0px";
area.appendChild(plots);
for (var i = 0; i < this.plots.length; i++) {
plots.appendChild(this.initializePlot(this.plots[i]));
}
this.resize();
return main;
}});
}
@@ -10,137 +10,103 @@
dojo.provide("dojo.collections.ArrayList");
dojo.require("dojo.collections.Collections");
dojo.collections.ArrayList=function(/* array? */arr){
// summary
// Returns a new object of type dojo.collections.ArrayList
var items=[];
if(arr) items=items.concat(arr);
this.count=items.length;
this.add=function(/* object */obj){
// summary
// Add an element to the collection.
dojo.collections.ArrayList = function (arr) {
var items = [];
if (arr) {
items = items.concat(arr);
}
this.count = items.length;
this.add = function (obj) {
items.push(obj);
this.count=items.length;
this.count = items.length;
};
this.addRange=function(/* array */a){
// summary
// Add a range of objects to the ArrayList
if(a.getIterator){
var e=a.getIterator();
while(!e.atEnd()){
this.addRange = function (a) {
if (a.getIterator) {
var e = a.getIterator();
while (!e.atEnd()) {
this.add(e.get());
}
this.count=items.length;
}else{
for(var i=0; i<a.length; i++){
this.count = items.length;
} else {
for (var i = 0; i < a.length; i++) {
items.push(a[i]);
}
this.count=items.length;
this.count = items.length;
}
};
this.clear=function(){
// summary
// Clear all elements out of the collection, and reset the count.
this.clear = function () {
items.splice(0, items.length);
this.count=0;
this.count = 0;
};
this.clone=function(){
// summary
// Clone the array list
return new dojo.collections.ArrayList(items); // dojo.collections.ArrayList
this.clone = function () {
return new dojo.collections.ArrayList(items);
};
this.contains=function(/* object */obj){
// summary
// Check to see if the passed object is a member in the ArrayList
for(var i=0; i < items.length; i++){
if(items[i] == obj) {
return true; // bool
this.contains = function (obj) {
for (var i = 0; i < items.length; i++) {
if (items[i] == obj) {
return true;
}
}
return false; // bool
return false;
};
this.forEach=function(/* function */ fn, /* object? */ scope){
// summary
// functional iterator, following the mozilla spec.
var s=scope||dj_global;
if(Array.forEach){
this.forEach = function (fn, scope) {
var s = scope || dj_global;
if (Array.forEach) {
Array.forEach(items, fn, s);
}else{
for(var i=0; i<items.length; i++){
} else {
for (var i = 0; i < items.length; i++) {
fn.call(s, items[i], i, items);
}
}
};
this.getIterator=function(){
// summary
// Get an Iterator for this object
return new dojo.collections.Iterator(items); // dojo.collections.Iterator
this.getIterator = function () {
return new dojo.collections.Iterator(items);
};
this.indexOf=function(/* object */obj){
// summary
// Return the numeric index of the passed object; will return -1 if not found.
for(var i=0; i < items.length; i++){
if(items[i] == obj) {
return i; // int
this.indexOf = function (obj) {
for (var i = 0; i < items.length; i++) {
if (items[i] == obj) {
return i;
}
}
return -1; // int
return -1;
};
this.insert=function(/* int */ i, /* object */ obj){
// summary
// Insert the passed object at index i
items.splice(i,0,obj);
this.count=items.length;
this.insert = function (i, obj) {
items.splice(i, 0, obj);
this.count = items.length;
};
this.item=function(/* int */ i){
// summary
// return the element at index i
return items[i]; // object
this.item = function (i) {
return items[i];
};
this.remove=function(/* object */obj){
// summary
// Look for the passed object, and if found, remove it from the internal array.
var i=this.indexOf(obj);
if(i >=0) {
items.splice(i,1);
this.remove = function (obj) {
var i = this.indexOf(obj);
if (i >= 0) {
items.splice(i, 1);
}
this.count=items.length;
this.count = items.length;
};
this.removeAt=function(/* int */ i){
// summary
// return an array with function applied to all elements
items.splice(i,1);
this.count=items.length;
this.removeAt = function (i) {
items.splice(i, 1);
this.count = items.length;
};
this.reverse=function(){
// summary
// Reverse the internal array
this.reverse = function () {
items.reverse();
};
this.sort=function(/* function? */ fn){
// summary
// sort the internal array
if(fn){
this.sort = function (fn) {
if (fn) {
items.sort(fn);
}else{
} else {
items.sort();
}
};
this.setByIndex=function(/* int */ i, /* object */ obj){
// summary
// Set an element in the array by the passed index.
items[i]=obj;
this.count=items.length;
this.setByIndex = function (i, obj) {
items[i] = obj;
this.count = items.length;
};
this.toArray=function(){
// summary
// Return a new array with all of the items of the internal array concatenated.
this.toArray = function () {
return [].concat(items);
}
this.toString=function(/* string */ delim){
// summary
// implementation of toString, follows [].toString();
return items.join((delim||","));
};
this.toString = function (delim) {
return items.join((delim || ","));
};
};
@@ -11,193 +11,245 @@
dojo.provide("dojo.collections.BinaryTree");
dojo.require("dojo.collections.Collections");
dojo.require("dojo.experimental");
dojo.experimental("dojo.collections.BinaryTree");
dojo.collections.BinaryTree=function(data){
function node(data, rnode, lnode){
this.value=data||null;
this.right=rnode||null;
this.left=lnode||null;
this.clone=function(){
var c=new node();
if (this.value.value) c.value=this.value.clone();
else c.value=this.value;
if (this.left) c.left=this.left.clone();
if (this.right) c.right=this.right.clone();
}
this.compare=function(n){
if (this.value > n.value) return 1;
if (this.value < n.value) return -1;
dojo.collections.BinaryTree = function (data) {
function node(data, rnode, lnode) {
this.value = data || null;
this.right = rnode || null;
this.left = lnode || null;
this.clone = function () {
var c = new node();
if (this.value.value) {
c.value = this.value.clone();
} else {
c.value = this.value;
}
if (this.left) {
c.left = this.left.clone();
}
if (this.right) {
c.right = this.right.clone();
}
};
this.compare = function (n) {
if (this.value > n.value) {
return 1;
}
if (this.value < n.value) {
return -1;
}
return 0;
}
this.compareData=function(d){
if (this.value > d) return 1;
if (this.value < d) return -1;
};
this.compareData = function (d) {
if (this.value > d) {
return 1;
}
if (this.value < d) {
return -1;
}
return 0;
}
};
}
function inorderTraversalBuildup(current, a){
if (current){
function inorderTraversalBuildup(current, a) {
if (current) {
inorderTraversalBuildup(current.left, a);
a.add(current);
inorderTraversalBuildup(current.right, a);
}
}
function preorderTraversal(current, sep){
var s="";
if (current){
s=current.value.toString() + sep;
function preorderTraversal(current, sep) {
var s = "";
if (current) {
s = current.value.toString() + sep;
s += preorderTraversal(current.left, sep);
s += preorderTraversal(current.right, sep);
}
return s;
}
function inorderTraversal(current, sep){
var s="";
if (current){
s=inorderTraversal(current.left, sep);
function inorderTraversal(current, sep) {
var s = "";
if (current) {
s = inorderTraversal(current.left, sep);
s += current.value.toString() + sep;
s += inorderTraversal(current.right, sep);
}
return s;
}
function postorderTraversal(current, sep){
var s="";
if (current){
s=postorderTraversal(current.left, sep);
function postorderTraversal(current, sep) {
var s = "";
if (current) {
s = postorderTraversal(current.left, sep);
s += postorderTraversal(current.right, sep);
s += current.value.toString() + sep;
}
return s;
}
function searchHelper(current, data){
if (!current) return null;
var i=current.compareData(data);
if (i==0) return current;
if (i>0) return searchHelper(current.left, data);
else return searchHelper(current.right, data);
function searchHelper(current, data) {
if (!current) {
return null;
}
var i = current.compareData(data);
if (i == 0) {
return current;
}
if (i > 0) {
return searchHelper(current.left, data);
} else {
return searchHelper(current.right, data);
}
}
this.add=function(data){
var n=new node(data);
this.add = function (data) {
var n = new node(data);
var i;
var current=root;
var parent=null;
while (current){
i=current.compare(n);
if (i == 0) return;
parent=current;
if (i > 0) current=current.left;
else current=current.right;
var current = root;
var parent = null;
while (current) {
i = current.compare(n);
if (i == 0) {
return;
}
parent = current;
if (i > 0) {
current = current.left;
} else {
current = current.right;
}
}
this.count++;
if (!parent) root=n;
else {
i=parent.compare(n);
if (i > 0) parent.left=n;
else parent.right=n;
if (!parent) {
root = n;
} else {
i = parent.compare(n);
if (i > 0) {
parent.left = n;
} else {
parent.right = n;
}
}
};
this.clear=function(){
root=null;
this.count=0;
this.clear = function () {
root = null;
this.count = 0;
};
this.clone=function(){
var c=new dojo.collections.BinaryTree();
c.root=root.clone();
c.count=this.count;
this.clone = function () {
var c = new dojo.collections.BinaryTree();
c.root = root.clone();
c.count = this.count;
return c;
};
this.contains=function(data){
this.contains = function (data) {
return this.search(data) != null;
};
this.deleteData=function(data){
var current=root;
var parent=null;
var i=current.compareData(data);
while (i != 0 && current != null){
if (i > 0){
parent=current;
current=current.left;
} else if (i < 0) {
parent=current;
current=current.right;
this.deleteData = function (data) {
var current = root;
var parent = null;
var i = current.compareData(data);
while (i != 0 && current != null) {
if (i > 0) {
parent = current;
current = current.left;
} else {
if (i < 0) {
parent = current;
current = current.right;
}
}
i=current.compareData(data);
i = current.compareData(data);
}
if (!current) {
return;
}
if (!current) return;
this.count--;
if (!current.right) {
if (!parent) root=current.left;
else {
i=parent.compare(current);
if (i > 0) parent.left=current.left;
else if (i < 0) parent.right=current.left;
}
} else if (!current.right.left){
if (!parent) root=current.right;
else {
i=parent.compare(current);
if (i > 0) parent.left=current.right;
else if (i < 0) parent.right=current.right;
if (!parent) {
root = current.left;
} else {
i = parent.compare(current);
if (i > 0) {
parent.left = current.left;
} else {
if (i < 0) {
parent.right = current.left;
}
}
}
} else {
var leftmost=current.right.left;
var lmParent=current.right;
while (leftmost.left != null){
lmParent=leftmost;
leftmost=leftmost.left;
}
lmParent.left=leftmost.right;
leftmost.left=current.left;
leftmost.right=current.right;
if (!parent) root=leftmost;
else {
i=parent.compare(current);
if (i > 0) parent.left=leftmost;
else if (i < 0) parent.right=leftmost;
if (!current.right.left) {
if (!parent) {
root = current.right;
} else {
i = parent.compare(current);
if (i > 0) {
parent.left = current.right;
} else {
if (i < 0) {
parent.right = current.right;
}
}
}
} else {
var leftmost = current.right.left;
var lmParent = current.right;
while (leftmost.left != null) {
lmParent = leftmost;
leftmost = leftmost.left;
}
lmParent.left = leftmost.right;
leftmost.left = current.left;
leftmost.right = current.right;
if (!parent) {
root = leftmost;
} else {
i = parent.compare(current);
if (i > 0) {
parent.left = leftmost;
} else {
if (i < 0) {
parent.right = leftmost;
}
}
}
}
}
};
this.getIterator=function(){
var a=[];
this.getIterator = function () {
var a = [];
inorderTraversalBuildup(root, a);
return new dojo.collections.Iterator(a);
};
this.search=function(data){
this.search = function (data) {
return searchHelper(root, data);
};
this.toString=function(order, sep){
if (!order) var order=dojo.collections.BinaryTree.TraversalMethods.Inorder;
if (!sep) var sep=" ";
var s="";
switch (order){
case dojo.collections.BinaryTree.TraversalMethods.Preorder:
s=preorderTraversal(root, sep);
break;
case dojo.collections.BinaryTree.TraversalMethods.Inorder:
s=inorderTraversal(root, sep);
break;
case dojo.collections.BinaryTree.TraversalMethods.Postorder:
s=postorderTraversal(root, sep);
break;
};
if (s.length == 0) return "";
else return s.substring(0, s.length - sep.length);
this.toString = function (order, sep) {
if (!order) {
var order = dojo.collections.BinaryTree.TraversalMethods.Inorder;
}
if (!sep) {
var sep = " ";
}
var s = "";
switch (order) {
case dojo.collections.BinaryTree.TraversalMethods.Preorder:
s = preorderTraversal(root, sep);
break;
case dojo.collections.BinaryTree.TraversalMethods.Inorder:
s = inorderTraversal(root, sep);
break;
case dojo.collections.BinaryTree.TraversalMethods.Postorder:
s = postorderTraversal(root, sep);
break;
}
if (s.length == 0) {
return "";
} else {
return s.substring(0, s.length - sep.length);
}
};
this.count=0;
var root=this.root=null;
this.count = 0;
var root = this.root = null;
if (data) {
this.add(data);
}
}
dojo.collections.BinaryTree.TraversalMethods={
Preorder : 1,
Inorder : 2,
Postorder : 3
};
dojo.collections.BinaryTree.TraversalMethods = {Preorder:1, Inorder:2, Postorder:3};
@@ -9,116 +9,82 @@
*/
dojo.provide("dojo.collections.Collections");
dojo.collections.DictionaryEntry=function(/* string */k, /* object */v){
// summary
// return an object of type dojo.collections.DictionaryEntry
this.key=k;
this.value=v;
this.valueOf=function(){
return this.value; // object
dojo.collections.DictionaryEntry = function (k, v) {
this.key = k;
this.value = v;
this.valueOf = function () {
return this.value;
};
this.toString=function(){
return String(this.value); // string
};
}
/* Iterators
* The collections.Iterators (Iterator and DictionaryIterator) are built to
* work with the Collections included in this module. However, they *can*
* be used with arrays and objects, respectively, should one choose to do so.
*/
dojo.collections.Iterator=function(/* array */arr){
// summary
// return an object of type dojo.collections.Iterator
var a=arr;
var position=0;
this.element=a[position]||null;
this.atEnd=function(){
// summary
// Test to see if the internal cursor has reached the end of the internal collection.
return (position>=a.length); // bool
};
this.get=function(){
// summary
// Test to see if the internal cursor has reached the end of the internal collection.
if(this.atEnd()){
return null; // object
}
this.element=a[position++];
return this.element; // object
};
this.map=function(/* function */fn, /* object? */scope){
// summary
// Functional iteration with optional scope.
var s=scope||dj_global;
if(Array.map){
return Array.map(a,fn,s); // array
}else{
var arr=[];
for(var i=0; i<a.length; i++){
arr.push(fn.call(s,a[i]));
}
return arr; // array
}
};
this.reset=function(){
// summary
// reset the internal cursor.
position=0;
this.element=a[position];
};
}
/* Notes:
* The DictionaryIterator no longer supports a key and value property;
* the reality is that you can use this to iterate over a JS object
* being used as a hashtable.
*/
dojo.collections.DictionaryIterator=function(/* object */obj){
// summary
// return an object of type dojo.collections.DictionaryIterator
var a=[]; // Create an indexing array
var testObject={};
for(var p in obj){
if(!testObject[p]){
a.push(obj[p]); // fill it up
}
}
var position=0;
this.element=a[position]||null;
this.atEnd=function(){
// summary
// Test to see if the internal cursor has reached the end of the internal collection.
return (position>=a.length); // bool
};
this.get=function(){
// summary
// Test to see if the internal cursor has reached the end of the internal collection.
if(this.atEnd()){
return null; // object
}
this.element=a[position++];
return this.element; // object
};
this.map=function(/* function */fn, /* object? */scope){
// summary
// Functional iteration with optional scope.
var s=scope||dj_global;
if(Array.map){
return Array.map(a,fn,s); // array
}else{
var arr=[];
for(var i=0; i<a.length; i++){
arr.push(fn.call(s,a[i]));
}
return arr; // array
}
};
this.reset=function() {
// summary
// reset the internal cursor.
position=0;
this.element=a[position];
this.toString = function () {
return String(this.value);
};
};
dojo.collections.Iterator = function (arr) {
var a = arr;
var position = 0;
this.element = a[position] || null;
this.atEnd = function () {
return (position >= a.length);
};
this.get = function () {
if (this.atEnd()) {
return null;
}
this.element = a[position++];
return this.element;
};
this.map = function (fn, scope) {
var s = scope || dj_global;
if (Array.map) {
return Array.map(a, fn, s);
} else {
var arr = [];
for (var i = 0; i < a.length; i++) {
arr.push(fn.call(s, a[i]));
}
return arr;
}
};
this.reset = function () {
position = 0;
this.element = a[position];
};
};
dojo.collections.DictionaryIterator = function (obj) {
var a = [];
var testObject = {};
for (var p in obj) {
if (!testObject[p]) {
a.push(obj[p]);
}
}
var position = 0;
this.element = a[position] || null;
this.atEnd = function () {
return (position >= a.length);
};
this.get = function () {
if (this.atEnd()) {
return null;
}
this.element = a[position++];
return this.element;
};
this.map = function (fn, scope) {
var s = scope || dj_global;
if (Array.map) {
return Array.map(a, fn, s);
} else {
var arr = [];
for (var i = 0; i < a.length; i++) {
arr.push(fn.call(s, a[i]));
}
return arr;
}
};
this.reset = function () {
position = 0;
this.element = a[position];
};
};
@@ -10,120 +10,90 @@
dojo.provide("dojo.collections.Dictionary");
dojo.require("dojo.collections.Collections");
dojo.collections.Dictionary=function(/* dojo.collections.Dictionary? */dictionary){
// summary
// Returns an object of type dojo.collections.Dictionary
var items={};
this.count=0;
// comparator for property addition and access.
var testObject={};
this.add=function(/* string */k, /* object */v){
// summary
// Add a new item to the Dictionary.
var b=(k in items);
items[k]=new dojo.collections.DictionaryEntry(k,v);
if(!b){
dojo.collections.Dictionary = function (dictionary) {
var items = {};
this.count = 0;
var testObject = {};
this.add = function (k, v) {
var b = (k in items);
items[k] = new dojo.collections.DictionaryEntry(k, v);
if (!b) {
this.count++;
}
};
this.clear=function(){
// summary
// Clears the internal dictionary.
items={};
this.count=0;
this.clear = function () {
items = {};
this.count = 0;
};
this.clone=function(){
// summary
// Returns a new instance of dojo.collections.Dictionary; note the the dictionary is a clone but items might not be.
return new dojo.collections.Dictionary(this); // dojo.collections.Dictionary
this.clone = function () {
return new dojo.collections.Dictionary(this);
};
this.contains=this.containsKey=function(/* string */k){
// summary
// Check to see if the dictionary has an entry at key "k".
if(testObject[k]){
return false; // bool
this.contains = this.containsKey = function (k) {
if (testObject[k]) {
return false;
}
return (items[k]!=null); // bool
return (items[k] != null);
};
this.containsValue=function(/* object */v){
// summary
// Check to see if the dictionary has an entry with value "v".
var e=this.getIterator();
while(e.get()){
if(e.element.value==v){
return true; // bool
this.containsValue = function (v) {
var e = this.getIterator();
while (e.get()) {
if (e.element.value == v) {
return true;
}
}
return false; // bool
return false;
};
this.entry=function(/* string */k){
// summary
// Accessor method; similar to dojo.collections.Dictionary.item but returns the actual Entry object.
return items[k]; // dojo.collections.DictionaryEntry
this.entry = function (k) {
return items[k];
};
this.forEach=function(/* function */ fn, /* object? */ scope){
// summary
// functional iterator, following the mozilla spec.
var a=[]; // Create an indexing array
for(var p in items) {
if(!testObject[p]){
a.push(items[p]); // fill it up
this.forEach = function (fn, scope) {
var a = [];
for (var p in items) {
if (!testObject[p]) {
a.push(items[p]);
}
}
var s=scope||dj_global;
if(Array.forEach){
var s = scope || dj_global;
if (Array.forEach) {
Array.forEach(a, fn, s);
}else{
for(var i=0; i<a.length; i++){
} else {
for (var i = 0; i < a.length; i++) {
fn.call(s, a[i], i, a);
}
}
};
this.getKeyList=function(){
// summary
// Returns an array of the keys in the dictionary.
return (this.getIterator()).map(function(entry){
return entry.key;
}); // array
this.getKeyList = function () {
return (this.getIterator()).map(function (entry) {
return entry.key;
});
};
this.getValueList=function(){
// summary
// Returns an array of the values in the dictionary.
return (this.getIterator()).map(function(entry){
return entry.value;
}); // array
this.getValueList = function () {
return (this.getIterator()).map(function (entry) {
return entry.value;
});
};
this.item=function(/* string */k){
// summary
// Accessor method.
if(k in items){
return items[k].valueOf(); // object
this.item = function (k) {
if (k in items) {
return items[k].valueOf();
}
return undefined; // object
return undefined;
};
this.getIterator=function(){
// summary
// Gets a dojo.collections.DictionaryIterator for iteration purposes.
return new dojo.collections.DictionaryIterator(items); // dojo.collections.DictionaryIterator
this.getIterator = function () {
return new dojo.collections.DictionaryIterator(items);
};
this.remove=function(/* string */k){
// summary
// Removes the item at k from the internal collection.
if(k in items && !testObject[k]){
this.remove = function (k) {
if (k in items && !testObject[k]) {
delete items[k];
this.count--;
return true; // bool
return true;
}
return false; // bool
return false;
};
if (dictionary){
var e=dictionary.getIterator();
while(e.get()) {
this.add(e.element.key, e.element.value);
if (dictionary) {
var e = dictionary.getIterator();
while (e.get()) {
this.add(e.element.key, e.element.value);
}
}
};
@@ -10,144 +10,140 @@
dojo.provide("dojo.collections.Graph");
dojo.require("dojo.collections.Collections");
dojo.experimental("dojo.collections.Graph");
dojo.collections.Graph=function(nodes){
dojo.collections.Graph = function (nodes) {
function node(key, data, neighbors) {
this.key=key;
this.data=data;
this.neighbors=neighbors||new adjacencyList();
this.addDirected=function(){
if (arguments[0].constructor==edgeToNeighbor){
this.key = key;
this.data = data;
this.neighbors = neighbors || new adjacencyList();
this.addDirected = function () {
if (arguments[0].constructor == edgeToNeighbor) {
this.neighbors.add(arguments[0]);
}else{
var n=arguments[0];
var cost=arguments[1]||0;
} else {
var n = arguments[0];
var cost = arguments[1] || 0;
this.neighbors.add(new edgeToNeighbor(n, cost));
}
}
};
}
function nodeList(){
var d=new dojo.collections.Dictionary();
function nodelistiterator(){
var o=[] ; // Create an indexing array
var e=d.getIterator();
while(e.get()){
o[o.length]=e.element;
function nodeList() {
var d = new dojo.collections.Dictionary();
function nodelistiterator() {
var o = [];
var e = d.getIterator();
while (e.get()) {
o[o.length] = e.element;
}
var position=0;
this.element=o[position]||null;
this.atEnd=function(){
return (position>=o.length);
}
this.get=function(){
if(this.atEnd()){
return null; // object
}
this.element=o[position++];
return this.element; // object
var position = 0;
this.element = o[position] || null;
this.atEnd = function () {
return (position >= o.length);
};
this.map=function(/* function */fn, /* object? */scope){
var s=scope||dj_global;
if(Array.map){
return Array.map(o,fn,s); // array
}else{
var arr=[];
for(var i=0; i<o.length; i++){
arr.push(fn.call(s,o[i]));
this.get = function () {
if (this.atEnd()) {
return null;
}
this.element = o[position++];
return this.element;
};
this.map = function (fn, scope) {
var s = scope || dj_global;
if (Array.map) {
return Array.map(o, fn, s);
} else {
var arr = [];
for (var i = 0; i < o.length; i++) {
arr.push(fn.call(s, o[i]));
}
return arr; // array
return arr;
}
};
this.reset=function(){
position=0;
this.element=o[position];
this.reset = function () {
position = 0;
this.element = o[position];
};
}
this.add=function(node){
this.add = function (node) {
d.add(node.key, node);
};
this.clear=function(){
this.clear = function () {
d.clear();
};
this.containsKey=function(key){
this.containsKey = function (key) {
return d.containsKey(key);
};
this.getIterator=function(){
this.getIterator = function () {
return new nodelistiterator(this);
};
this.item=function(key){
this.item = function (key) {
return d.item(key);
};
this.remove=function(node){
this.remove = function (node) {
d.remove(node.key);
};
}
function edgeToNeighbor(node, cost){
this.neighbor=node;
this.cost=cost;
function edgeToNeighbor(node, cost) {
this.neighbor = node;
this.cost = cost;
}
function adjacencyList(){
var d=[];
this.add=function(o){
function adjacencyList() {
var d = [];
this.add = function (o) {
d.push(o);
};
this.item=function(i){
this.item = function (i) {
return d[i];
};
this.getIterator=function(){
this.getIterator = function () {
return new dojo.collections.Iterator([].concat(d));
};
}
this.nodes=nodes||new nodeList();
this.count=this.nodes.count;
this.clear=function(){
this.nodes = nodes || new nodeList();
this.count = this.nodes.count;
this.clear = function () {
this.nodes.clear();
this.count=0;
this.count = 0;
};
this.addNode=function(){
var n=arguments[0];
if(arguments.length > 1){
n=new node(arguments[0],arguments[1]);
this.addNode = function () {
var n = arguments[0];
if (arguments.length > 1) {
n = new node(arguments[0], arguments[1]);
}
if(!this.nodes.containsKey(n.key)){
if (!this.nodes.containsKey(n.key)) {
this.nodes.add(n);
this.count++;
}
};
this.addDirectedEdge=function(uKey, vKey, cost){
var uNode,vNode;
if(uKey.constructor!= node){
uNode=this.nodes.item(uKey);
vNode=this.nodes.item(vKey);
}else{
uNode=uKey;
vNode=vKey;
}
var c=cost||0;
uNode.addDirected(vNode,c);
};
this.addUndirectedEdge=function(uKey, vKey, cost){
this.addDirectedEdge = function (uKey, vKey, cost) {
var uNode, vNode;
if(uKey.constructor!=node){
uNode=this.nodes.item(uKey);
vNode=this.nodes.item(vKey);
}else{
uNode=uKey;
vNode=vKey;
if (uKey.constructor != node) {
uNode = this.nodes.item(uKey);
vNode = this.nodes.item(vKey);
} else {
uNode = uKey;
vNode = vKey;
}
var c=cost||0;
uNode.addDirected(vNode,c);
vNode.addDirected(uNode,c);
var c = cost || 0;
uNode.addDirected(vNode, c);
};
this.contains=function(n){
this.addUndirectedEdge = function (uKey, vKey, cost) {
var uNode, vNode;
if (uKey.constructor != node) {
uNode = this.nodes.item(uKey);
vNode = this.nodes.item(vKey);
} else {
uNode = uKey;
vNode = vKey;
}
var c = cost || 0;
uNode.addDirected(vNode, c);
vNode.addDirected(uNode, c);
};
this.contains = function (n) {
return this.nodes.containsKey(n.key);
};
this.containsKey=function(k){
this.containsKey = function (k) {
return this.nodes.containsKey(k);
};
}
};
@@ -10,78 +10,56 @@
dojo.provide("dojo.collections.Queue");
dojo.require("dojo.collections.Collections");
dojo.collections.Queue=function(/* array? */arr){
// summary
// return an object of type dojo.collections.Queue
var q=[];
if (arr){
q=q.concat(arr);
dojo.collections.Queue = function (arr) {
var q = [];
if (arr) {
q = q.concat(arr);
}
this.count=q.length;
this.clear=function(){
// summary
// clears the internal collection
q=[];
this.count=q.length;
this.count = q.length;
this.clear = function () {
q = [];
this.count = q.length;
};
this.clone=function(){
// summary
// creates a new Queue based on this one
return new dojo.collections.Queue(q); // dojo.collections.Queue
this.clone = function () {
return new dojo.collections.Queue(q);
};
this.contains=function(/* object */ o){
// summary
// Check to see if the passed object is an element in this queue
for(var i=0; i<q.length; i++){
if (q[i]==o){
return true; // bool
this.contains = function (o) {
for (var i = 0; i < q.length; i++) {
if (q[i] == o) {
return true;
}
}
return false; // bool
return false;
};
this.copyTo=function(/* array */ arr, /* int */ i){
// summary
// Copy the contents of this queue into the passed array at index i.
arr.splice(i,0,q);
this.copyTo = function (arr, i) {
arr.splice(i, 0, q);
};
this.dequeue=function(){
// summary
// shift the first element off the queue and return it
var r=q.shift();
this.count=q.length;
return r; // object
this.dequeue = function () {
var r = q.shift();
this.count = q.length;
return r;
};
this.enqueue=function(/* object */ o){
// summary
// put the passed object at the end of the queue
this.count=q.push(o);
this.enqueue = function (o) {
this.count = q.push(o);
};
this.forEach=function(/* function */ fn, /* object? */ scope){
// summary
// functional iterator, following the mozilla spec.
var s=scope||dj_global;
if(Array.forEach){
this.forEach = function (fn, scope) {
var s = scope || dj_global;
if (Array.forEach) {
Array.forEach(q, fn, s);
}else{
for(var i=0; i<q.length; i++){
} else {
for (var i = 0; i < q.length; i++) {
fn.call(s, q[i], i, q);
}
}
};
this.getIterator=function(){
// summary
// get an Iterator based on this queue.
return new dojo.collections.Iterator(q); // dojo.collections.Iterator
this.getIterator = function () {
return new dojo.collections.Iterator(q);
};
this.peek=function(){
// summary
// get the next element in the queue without altering the queue.
this.peek = function () {
return q[0];
};
this.toArray=function(){
// summary
// return an array based on the internal array of the queue.
this.toArray = function () {
return [].concat(q);
};
};
@@ -11,84 +11,102 @@
dojo.provide("dojo.collections.Set");
dojo.require("dojo.collections.Collections");
dojo.require("dojo.collections.ArrayList");
dojo.collections.Set = new function(){
// summary
// Singleton for dealing with common set operations.
this.union = function(/* array */setA, /* array */setB){
// summary
// Return the union of the two passed sets.
if (setA.constructor == Array) var setA = new dojo.collections.ArrayList(setA);
if (setB.constructor == Array) var setB = new dojo.collections.ArrayList(setB);
if (!setA.toArray || !setB.toArray) dojo.raise("Set operations can only be performed on array-based collections.");
dojo.collections.Set = new function () {
this.union = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var result = new dojo.collections.ArrayList(setA.toArray());
var e = setB.getIterator();
while(!e.atEnd()){
var item=e.get();
if(!result.contains(item)){
while (!e.atEnd()) {
var item = e.get();
if (!result.contains(item)) {
result.add(item);
}
}
return result; // dojo.collections.ArrayList
return result;
};
this.intersection = function(/* array */setA, /* array */setB){
// summary
// Return the intersection of the two passed sets.
if (setA.constructor == Array) var setA = new dojo.collections.ArrayList(setA);
if (setB.constructor == Array) var setB = new dojo.collections.ArrayList(setB);
if (!setA.toArray || !setB.toArray) dojo.raise("Set operations can only be performed on array-based collections.");
this.intersection = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var result = new dojo.collections.ArrayList();
var e = setB.getIterator();
while(!e.atEnd()){
var item=e.get();
if(setA.contains(item)){
while (!e.atEnd()) {
var item = e.get();
if (setA.contains(item)) {
result.add(item);
}
}
return result; // dojo.collections.ArrayList
return result;
};
this.difference = function(/* array */setA, /* array */setB){
// summary
// Returns everything in setA that is not in setB.
if (setA.constructor == Array) var setA = new dojo.collections.ArrayList(setA);
if (setB.constructor == Array) var setB = new dojo.collections.ArrayList(setB);
if (!setA.toArray || !setB.toArray) dojo.raise("Set operations can only be performed on array-based collections.");
this.difference = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var result = new dojo.collections.ArrayList();
var e=setA.getIterator();
while(!e.atEnd()){
var item=e.get();
if(!setB.contains(item)){
result.add(item);
}
}
return result; // dojo.collections.ArrayList
};
this.isSubSet = function(/* array */setA, /* array */setB) {
// summary
// Returns if set B is a subset of set A.
if (setA.constructor == Array) var setA = new dojo.collections.ArrayList(setA);
if (setB.constructor == Array) var setB = new dojo.collections.ArrayList(setB);
if (!setA.toArray || !setB.toArray) dojo.raise("Set operations can only be performed on array-based collections.");
var e = setA.getIterator();
while(!e.atEnd()){
if(!setB.contains(e.get())){
return false; // boolean
while (!e.atEnd()) {
var item = e.get();
if (!setB.contains(item)) {
result.add(item);
}
}
return true; // boolean
return result;
};
this.isSuperSet = function(/* array */setA, /* array */setB){
// summary
// Returns if set B is a superset of set A.
if (setA.constructor == Array) var setA = new dojo.collections.ArrayList(setA);
if (setB.constructor == Array) var setB = new dojo.collections.ArrayList(setB);
if (!setA.toArray || !setB.toArray) dojo.raise("Set operations can only be performed on array-based collections.");
var e = setB.getIterator();
while(!e.atEnd()){
if(!setA.contains(e.get())){
return false; // boolean
this.isSubSet = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var e = setA.getIterator();
while (!e.atEnd()) {
if (!setB.contains(e.get())) {
return false;
}
}
return true; // boolean
return true;
};
this.isSuperSet = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var e = setB.getIterator();
while (!e.atEnd()) {
if (!setA.contains(e.get())) {
return false;
}
}
return true;
};
}();
@@ -11,139 +11,157 @@
dojo.provide("dojo.collections.SkipList");
dojo.require("dojo.collections.Collections");
dojo.require("dojo.experimental");
dojo.experimental("dojo.collections.SkipList");
dojo.collections.SkipList = function(){
function node(height, val){
dojo.collections.SkipList = function () {
function node(height, val) {
this.value = val;
this.height = height;
this.nodes = new nodeList(height);
this.compare = function(val){
if (this.value > val) return 1;
if (this.value < val) return -1;
this.compare = function (val) {
if (this.value > val) {
return 1;
}
if (this.value < val) {
return -1;
}
return 0;
}
this.incrementHeight = function(){
};
this.incrementHeight = function () {
this.nodes.incrementHeight();
this.height++;
};
this.decrementHeight = function(){
this.decrementHeight = function () {
this.nodes.decrementHeight();
this.height--;
};
}
function nodeList(height){
function nodeList(height) {
var arr = [];
this.height = height;
for (var i = 0; i < height; i++) arr[i] = null;
this.item = function(i){
for (var i = 0; i < height; i++) {
arr[i] = null;
}
this.item = function (i) {
return arr[i];
};
this.incrementHeight = function(){
this.incrementHeight = function () {
this.height++;
arr[this.height] = null;
};
this.decrementHeight = function(){
this.decrementHeight = function () {
arr.splice(arr.length - 1, 1);
this.height--;
};
}
function iterator(list){
function iterator(list) {
this.element = list.head;
this.atEnd = function(){
return (this.element==null);
}
this.get = function(){
if(this.atEnd()){
this.atEnd = function () {
return (this.element == null);
};
this.get = function () {
if (this.atEnd()) {
return null;
}
this.element=this.element.nodes[0];
this.element = this.element.nodes[0];
return this.element;
}
this.reset = function(){
};
this.reset = function () {
this.element = list.head;
}
};
}
function chooseRandomHeight(max){
function chooseRandomHeight(max) {
var level = 1;
while (Math.random() < PROB && level < max) level++;
while (Math.random() < PROB && level < max) {
level++;
}
return level;
}
var PROB = 0.5;
var comparisons = 0;
this.head = new node(1);
this.count = 0;
this.add = function(val){
this.add = function (val) {
var updates = [];
var current = this.head;
for (var i = this.head.height; i >= 0; i--){
if (!(current.nodes[i] != null && current.nodes[i].compare(val) < 0)) comparisons++;
while (current.nodes[i] != null && current.nodes[i].compare(val) < 0){
current = current.nodes[i];
for (var i = this.head.height; i >= 0; i--) {
if (!(current.nodes[i] != null && current.nodes[i].compare(val) < 0)) {
comparisons++;
}
updates[i] = current;
}
if (current.nodes[0] != null && current.nodes[0].compare(val) == 0) return;
var n = new node(val, chooseRandomHeight(this.head.height + 1));
this.count++;
if (n.height > this.head.height){
this.head.incrementHeight();
this.head.nodes[this.head.height - 1] = n;
}
for (i = 0; i < n.height; i++){
if (i < updates.length) {
n.nodes[i] = updates[i].nodes[i];
updates[i].nodes[i] = n;
}
}
};
this.contains = function(val){
var current = this.head;
var i;
for (i = this.head.height - 1; i >= 0; i--) {
while (current.item(i) != null) {
comparisons++;
var result = current.nodes[i].compare(val);
if (result == 0) return true;
else if (result < 0) current = current.nodes[i];
else break;
}
}
return false;
};
this.getIterator = function(){
return new iterator(this);
};
this.remove = function(val){
var updates = [];
var current = this.head;
for (var i = this.head.height - 1; i >= 0; i--){
if (!(current.nodes[i] != null && current.nodes[i].compare(val) < 0)) comparisons++;
while (current.nodes[i] != null && current.nodes[i].compare(val) < 0) {
current = current.nodes[i];
comparisons++;
}
updates[i] = current;
}
current = current.nodes[0];
if (current != null && current.compare(val) == 0){
this.count--;
for (var i = 0; i < this.head.height; i++){
if (updates[i].nodes[i] != current) break;
else updates[i].nodes[i] = current.nodes[i];
if (current.nodes[0] != null && current.nodes[0].compare(val) == 0) {
return;
}
var n = new node(val, chooseRandomHeight(this.head.height + 1));
this.count++;
if (n.height > this.head.height) {
this.head.incrementHeight();
this.head.nodes[this.head.height - 1] = n;
}
for (i = 0; i < n.height; i++) {
if (i < updates.length) {
n.nodes[i] = updates[i].nodes[i];
updates[i].nodes[i] = n;
}
if (this.head.nodes[this.head.height - 1] == null) this.head.decrementHeight();
}
};
this.resetComparisons = function(){
comparisons = 0;
this.contains = function (val) {
var current = this.head;
var i;
for (i = this.head.height - 1; i >= 0; i--) {
while (current.item(i) != null) {
comparisons++;
var result = current.nodes[i].compare(val);
if (result == 0) {
return true;
} else {
if (result < 0) {
current = current.nodes[i];
} else {
break;
}
}
}
}
return false;
};
}
this.getIterator = function () {
return new iterator(this);
};
this.remove = function (val) {
var updates = [];
var current = this.head;
for (var i = this.head.height - 1; i >= 0; i--) {
if (!(current.nodes[i] != null && current.nodes[i].compare(val) < 0)) {
comparisons++;
}
while (current.nodes[i] != null && current.nodes[i].compare(val) < 0) {
current = current.nodes[i];
comparisons++;
}
updates[i] = current;
}
current = current.nodes[0];
if (current != null && current.compare(val) == 0) {
this.count--;
for (var i = 0; i < this.head.height; i++) {
if (updates[i].nodes[i] != current) {
break;
} else {
updates[i].nodes[i] = current.nodes[i];
}
}
if (this.head.nodes[this.head.height - 1] == null) {
this.head.decrementHeight();
}
}
};
this.resetComparisons = function () {
comparisons = 0;
};
};
@@ -10,202 +10,160 @@
dojo.provide("dojo.collections.SortedList");
dojo.require("dojo.collections.Collections");
dojo.collections.SortedList=function(/* object? */ dictionary){
// summary
// creates a collection that acts like a dictionary but is also internally sorted.
// Note that the act of adding any elements forces an internal resort, making this object potentially slow.
var _this=this;
var items={};
var q=[];
var sorter=function(a,b){
if (a.key > b.key) return 1;
if (a.key < b.key) return -1;
dojo.collections.SortedList = function (dictionary) {
var _this = this;
var items = {};
var q = [];
var sorter = function (a, b) {
if (a.key > b.key) {
return 1;
}
if (a.key < b.key) {
return -1;
}
return 0;
};
var build=function(){
q=[];
var e=_this.getIterator();
while (!e.atEnd()){
var build = function () {
q = [];
var e = _this.getIterator();
while (!e.atEnd()) {
q.push(e.get());
}
q.sort(sorter);
};
var testObject={};
this.count=q.length;
this.add=function(/* string */ k,/* object */v){
// summary
// add the passed value to the dictionary at location k
var testObject = {};
this.count = q.length;
this.add = function (k, v) {
if (!items[k]) {
items[k]=new dojo.collections.DictionaryEntry(k,v);
this.count=q.push(items[k]);
items[k] = new dojo.collections.DictionaryEntry(k, v);
this.count = q.push(items[k]);
q.sort(sorter);
}
};
this.clear=function(){
// summary
// clear the internal collections
items={};
q=[];
this.count=q.length;
this.clear = function () {
items = {};
q = [];
this.count = q.length;
};
this.clone=function(){
// summary
// create a clone of this sorted list
return new dojo.collections.SortedList(this); // dojo.collections.SortedList
this.clone = function () {
return new dojo.collections.SortedList(this);
};
this.contains=this.containsKey=function(/* string */ k){
// summary
// Check to see if the list has a location k
if(testObject[k]){
return false; // bool
this.contains = this.containsKey = function (k) {
if (testObject[k]) {
return false;
}
return (items[k]!=null); // bool
return (items[k] != null);
};
this.containsValue=function(/* object */ o){
// summary
// Check to see if this list contains the passed object
var e=this.getIterator();
while (!e.atEnd()){
var item=e.get();
if(item.value==o){
return true; // bool
this.containsValue = function (o) {
var e = this.getIterator();
while (!e.atEnd()) {
var item = e.get();
if (item.value == o) {
return true;
}
}
return false; // bool
return false;
};
this.copyTo=function(/* array */ arr, /* int */ i){
// summary
// copy the contents of the list into array arr at index i
var e=this.getIterator();
var idx=i;
while(!e.atEnd()){
arr.splice(idx,0,e.get());
this.copyTo = function (arr, i) {
var e = this.getIterator();
var idx = i;
while (!e.atEnd()) {
arr.splice(idx, 0, e.get());
idx++;
}
};
this.entry=function(/* string */ k){
// summary
// return the object at location k
return items[k]; // dojo.collections.DictionaryEntry
this.entry = function (k) {
return items[k];
};
this.forEach=function(/* function */ fn, /* object? */ scope){
// summary
// functional iterator, following the mozilla spec.
var s=scope||dj_global;
if(Array.forEach){
this.forEach = function (fn, scope) {
var s = scope || dj_global;
if (Array.forEach) {
Array.forEach(q, fn, s);
}else{
for(var i=0; i<q.length; i++){
} else {
for (var i = 0; i < q.length; i++) {
fn.call(s, q[i], i, q);
}
}
};
this.getByIndex=function(/* int */ i){
// summary
// return the item at index i
return q[i].valueOf(); // object
this.getByIndex = function (i) {
return q[i].valueOf();
};
this.getIterator=function(){
// summary
// get an iterator for this object
return new dojo.collections.DictionaryIterator(items); // dojo.collections.DictionaryIterator
this.getIterator = function () {
return new dojo.collections.DictionaryIterator(items);
};
this.getKey=function(/* int */ i){
// summary
// return the key of the item at index i
this.getKey = function (i) {
return q[i].key;
};
this.getKeyList=function(){
// summary
// return an array of the keys set in this list
var arr=[];
var e=this.getIterator();
while (!e.atEnd()){
this.getKeyList = function () {
var arr = [];
var e = this.getIterator();
while (!e.atEnd()) {
arr.push(e.get().key);
}
return arr; // array
return arr;
};
this.getValueList=function(){
// summary
// return an array of values in this list
var arr=[];
var e=this.getIterator();
while (!e.atEnd()){
this.getValueList = function () {
var arr = [];
var e = this.getIterator();
while (!e.atEnd()) {
arr.push(e.get().value);
}
return arr; // array
return arr;
};
this.indexOfKey=function(/* string */ k){
// summary
// return the index of the passed key.
for (var i=0; i<q.length; i++){
if (q[i].key==k){
return i; // int
this.indexOfKey = function (k) {
for (var i = 0; i < q.length; i++) {
if (q[i].key == k) {
return i;
}
}
return -1; // int
return -1;
};
this.indexOfValue=function(/* object */ o){
// summary
// return the first index of object o
for (var i=0; i<q.length; i++){
if (q[i].value==o){
return i; // int
this.indexOfValue = function (o) {
for (var i = 0; i < q.length; i++) {
if (q[i].value == o) {
return i;
}
}
return -1; // int
return -1;
};
this.item=function(/* string */ k){
// summary
// return the value of the object at location k.
if(k in items && !testObject[k]){
return items[k].valueOf(); // object
this.item = function (k) {
if (k in items && !testObject[k]) {
return items[k].valueOf();
}
return undefined; // object
return undefined;
};
this.remove=function(/* string */k){
// summary
// remove the item at location k and rebuild the internal collections.
this.remove = function (k) {
delete items[k];
build();
this.count=q.length;
this.count = q.length;
};
this.removeAt=function(/* int */ i){
// summary
// remove the item at index i, and rebuild the internal collections.
this.removeAt = function (i) {
delete items[q[i].key];
build();
this.count=q.length;
this.count = q.length;
};
this.replace=function(/* string */ k, /* object */ v){
// summary
// Replace an existing item if it's there, and add a new one if not.
if (!items[k]){
// we're adding a new object, return false
this.add(k,v);
return false; // bool
}else{
// we're replacing an object, return true
items[k]=new dojo.collections.DictionaryEntry(k,v);
this.replace = function (k, v) {
if (!items[k]) {
this.add(k, v);
return false;
} else {
items[k] = new dojo.collections.DictionaryEntry(k, v);
q.sort(sorter);
return true; // bool
return true;
}
};
this.setByIndex=function(/* int */ i, /* object */ o){
// summary
// set an item by index
items[q[i].key].value=o;
this.setByIndex = function (i, o) {
items[q[i].key].value = o;
build();
this.count=q.length;
this.count = q.length;
};
if (dictionary){
var e=dictionary.getIterator();
while (!e.atEnd()){
var item=e.get();
q[q.length]=items[item.key]=new dojo.collections.DictionaryEntry(item.key,item.value);
if (dictionary) {
var e = dictionary.getIterator();
while (!e.atEnd()) {
var item = e.get();
q[q.length] = items[item.key] = new dojo.collections.DictionaryEntry(item.key, item.value);
}
q.sort(sorter);
}
}
};
@@ -10,76 +10,56 @@
dojo.provide("dojo.collections.Stack");
dojo.require("dojo.collections.Collections");
dojo.collections.Stack=function(/* array? */arr){
// summary
// returns an object of type dojo.collections.Stack
var q=[];
if (arr) q=q.concat(arr);
this.count=q.length;
this.clear=function(){
// summary
// Clear the internal array and reset the count
q=[];
this.count=q.length;
dojo.collections.Stack = function (arr) {
var q = [];
if (arr) {
q = q.concat(arr);
}
this.count = q.length;
this.clear = function () {
q = [];
this.count = q.length;
};
this.clone=function(){
// summary
// Create and return a clone of this Stack
this.clone = function () {
return new dojo.collections.Stack(q);
};
this.contains=function(/* object */o){
// summary
// check to see if the stack contains object o
for (var i=0; i<q.length; i++){
if (q[i] == o){
return true; // bool
this.contains = function (o) {
for (var i = 0; i < q.length; i++) {
if (q[i] == o) {
return true;
}
}
return false; // bool
return false;
};
this.copyTo=function(/* array */ arr, /* int */ i){
// summary
// copy the stack into array arr at index i
arr.splice(i,0,q);
this.copyTo = function (arr, i) {
arr.splice(i, 0, q);
};
this.forEach=function(/* function */ fn, /* object? */ scope){
// summary
// functional iterator, following the mozilla spec.
var s=scope||dj_global;
if(Array.forEach){
this.forEach = function (fn, scope) {
var s = scope || dj_global;
if (Array.forEach) {
Array.forEach(q, fn, s);
}else{
for(var i=0; i<q.length; i++){
} else {
for (var i = 0; i < q.length; i++) {
fn.call(s, q[i], i, q);
}
}
};
this.getIterator=function(){
// summary
// get an iterator for this collection
return new dojo.collections.Iterator(q); // dojo.collections.Iterator
this.getIterator = function () {
return new dojo.collections.Iterator(q);
};
this.peek=function(){
// summary
// Return the next item without altering the stack itself.
return q[(q.length-1)]; // object
this.peek = function () {
return q[(q.length - 1)];
};
this.pop=function(){
// summary
// pop and return the next item on the stack
var r=q.pop();
this.count=q.length;
return r; // object
this.pop = function () {
var r = q.pop();
this.count = q.length;
return r;
};
this.push=function(/* object */ o){
// summary
// Push object o onto the stack
this.count=q.push(o);
this.push = function (o) {
this.count = q.push(o);
};
this.toArray=function(){
// summary
// create and return an array based on the internal collection
return [].concat(q); // array
this.toArray = function () {
return [].concat(q);
};
}
};
@@ -8,272 +8,284 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.collections.Store");
dojo.require("dojo.lang.common");
/* Store
* Designed to be a simple store of data with access methods...
* specifically to be mixed into other objects (such as widgets).
*/
dojo.collections.Store = function(/* array? */jsonArray){
// summary
// Data Store with accessor methods.
var data = [];
this.keyField = "Id";
this.get = function(){
// summary
// Get the internal data array, should not be used.
return data; // array
};
this.getByKey = function(/* string */key){
// summary
// Find the internal data object by key.
for(var i=0; i<data.length; i++){
if(data[i].key==key){
return data[i]; // object
}
}
return null; // null
};
this.getByIndex = function(/*number*/idx){
// summary
// Get the internal data object by index.
return data[idx]; // object
};
this.getData = function(){
// summary
// Get an array of source objects.
var arr = [];
for(var i=0; i<data.length; i++){
arr.push(data[i].src);
}
return arr; // array
};
this.getDataByKey = function(/*string*/key){
// summary
// Get the source object by key.
for(var i=0; i<data.length; i++){
if(data[i].key==key){
return data[i].src; // object
}
}
return null; // null
};
this.getDataByIndex = function(/*number*/idx){
// summary
// Get the source object at index idx.
return data[idx].src; // object
};
this.update = function(/* Object */obj, /* string */fieldPath, /* Object */val){
var parts=fieldPath.split("."), i=0, o=obj, field;
if(parts.length>1) {
field = parts.pop();
do{
if(parts[i].indexOf("()")>-1){
var temp=parts[i++].split("()")[0];
if(!o[temp]){
dojo.raise("dojo.collections.Store.getField(obj, '" + field + "'): '" + temp + "' is not a property of the passed object.");
} else {
// this *will* throw an error if the method in question can't be invoked without arguments.
o = o[temp]();
}
} else {
o = o[parts[i++]];
}
} while (i<parts.length && o != null);
} else {
field = parts[0];
}
obj[field] = val;
this.onUpdateField(obj, fieldPath, val);
};
this.forEach = function(/* function */fn){
// summary
// Functional iteration directly on the internal data array.
if(Array.forEach){
Array.forEach(data, fn, this);
}else{
for(var i=0; i<data.length; i++){
fn.call(this, data[i]);
}
}
};
this.forEachData = function(/* function */fn){
// summary
// Functional iteration on source objects in internal data array.
if(Array.forEach){
Array.forEach(this.getData(), fn, this);
}else{
var a=this.getData();
for(var i=0; i<a.length; i++){
fn.call(this, a[i]);
}
}
};
this.setData = function(/*array*/arr){
// summary
// Set up the internal data.
data = []; // don't fire onClearData
for(var i=0; i<arr.length; i++){
data.push({
key:arr[i][this.keyField],
src:arr[i]
});
}
this.onSetData();
};
this.clearData = function(){
// summary
// Clears the internal data array.
data = [];
this.onClearData();
};
this.addData = function(/*obj*/obj,/*string?*/key){
// summary
// Add an object with optional key to the internal data array.
var k = key || obj[this.keyField];
if(this.getByKey(k)){
var o = this.getByKey(k);
o.src = obj;
} else {
var o={ key:k, src:obj };
data.push(o);
}
this.onAddData(o);
};
this.addDataRange = function(/*array*/arr){
// summary
// Add a range of objects to the internal data array.
var objects=[];
for(var i=0; i<arr.length; i++){
var k = arr[i][this.keyField];
if(this.getByKey(k)){
var o = this.getByKey(k);
o.src = obj;
} else {
var o = { key:k, src:arr[i] };
data.push(o);
}
objects.push(o);
}
this.onAddDataRange(objects);
};
this.removeData = function(/*obj*/obj){
// summary
// remove the passed object from the internal data array.
var idx=-1;
var o=null;
for(var i=0; i<data.length; i++){
if(data[i].src==obj){
idx=i;
o=data[i];
break;
}
}
this.onRemoveData(o);
if(idx>-1){
data.splice(idx,1);
}
};
this.removeDataByKey = function(/*string*/key){
// summary
// remove the object at key from the internal data array.
this.removeData(this.getDataByKey(key));
};
this.removeDataByIndex = function(/*number*/idx){
// summary
// remove the object at idx from the internal data array.
this.removeData(this.getDataByIndex(idx));
};
if(jsonArray && jsonArray.length && jsonArray[0]){
this.setData(jsonArray);
}
};
dojo.extend(dojo.collections.Store, {
getField:function(/*object*/obj, /*string*/field){
// helper to get the nested value if needed.
var parts=field.split("."), i=0, o=obj;
do{
if(parts[i].indexOf("()")>-1){
var temp=parts[i++].split("()")[0];
if(!o[temp]){
dojo.raise("dojo.collections.Store.getField(obj, '" + field + "'): '" + temp + "' is not a property of the passed object.");
} else {
// this *will* throw an error if the method in question can't be invoked without arguments.
o = o[temp]();
}
} else {
o = o[parts[i++]];
}
} while (i<parts.length && o != null);
if(i < parts.length){
dojo.raise("dojo.collections.Store.getField(obj, '" + field + "'): '" + field + "' is not a property of the passed object.");
}
return o; // object
},
getFromHtml:function(/* array */meta, /* HTMLTableBody */body, /* function? */fnMod){
// summary
// Parse HTML data into native JSON structure for the store.
var rows = body.rows;
// create a data constructor.
var ctor=function(row){
var obj = {};
for(var i=0; i<meta.length; i++){
var o = obj;
var data = row.cells[i].innerHTML;
var p = meta[i].getField();
if(p.indexOf(".") > -1){
p = p.split(".");
while(p.length>1){
var pr = p.shift();
o[pr] = {};
o = o[pr];
}
p = p[0];
}
var type = meta[i].getType();
if(type == String){
o[p] = data;
} else {
if(data){
o[p] = new type(data);
} else {
o[p] = new type();
}
}
}
return obj;
};
// we have initialization data, let's parse it.
var arr=[];
for(var i=0; i<rows.length; i++){
var o = ctor(rows[i]);
if(fnMod){
fnMod(o, rows[i]); // apply any modifiers.
}
arr.push(o);
}
return arr; // array
},
onSetData:function(){ },
onClearData:function(){ },
onAddData:function(obj){ },
onAddDataRange:function(arr){ },
onRemoveData:function(obj){ },
onUpdateField:function(obj, field, val){ }
});
dojo.provide("dojo.collections.Store");
dojo.require("dojo.lang.common");
dojo.collections.Store = function (jsonArray) {
var data = [];
var items = {};
this.keyField = "Id";
this.get = function () {
return data;
};
this.getByKey = function (key) {
return items[key];
};
this.getByIndex = function (idx) {
return data[idx];
};
this.getIndexOf = function (key) {
for (var i = 0; i < data.length; i++) {
if (data[i].key == key) {
return i;
}
}
return -1;
};
this.getData = function () {
var arr = [];
for (var i = 0; i < data.length; i++) {
arr.push(data[i].src);
}
return arr;
};
this.getDataByKey = function (key) {
if (items[key] != null) {
return items[key].src;
}
return null;
};
this.getIndexOfData = function (obj) {
for (var i = 0; i < data.length; i++) {
if (data[i].src == obj) {
return i;
}
}
return -1;
};
this.getDataByIndex = function (idx) {
if (data[idx]) {
return data[idx].src;
}
return null;
};
this.update = function (obj, fieldPath, val, bDontFire) {
var parts = fieldPath.split("."), i = 0, o = obj, field;
if (parts.length > 1) {
field = parts.pop();
do {
if (parts[i].indexOf("()") > -1) {
var temp = parts[i++].split("()")[0];
if (!o[temp]) {
dojo.raise("dojo.collections.Store.getField(obj, '" + field + "'): '" + temp + "' is not a property of the passed object.");
} else {
o = o[temp]();
}
} else {
o = o[parts[i++]];
}
} while (i < parts.length && o != null);
} else {
field = parts[0];
}
obj[field] = val;
if (!bDontFire) {
this.onUpdateField(obj, fieldPath, val);
}
};
this.forEach = function (fn) {
if (Array.forEach) {
Array.forEach(data, fn, this);
} else {
for (var i = 0; i < data.length; i++) {
fn.call(this, data[i]);
}
}
};
this.forEachData = function (fn) {
if (Array.forEach) {
Array.forEach(this.getData(), fn, this);
} else {
var a = this.getData();
for (var i = 0; i < a.length; i++) {
fn.call(this, a[i]);
}
}
};
this.setData = function (arr, bDontFire) {
data = [];
for (var i = 0; i < arr.length; i++) {
var o = {key:arr[i][this.keyField], src:arr[i]};
data.push(o);
items[o.key] = o;
}
if (!bDontFire) {
this.onSetData();
}
};
this.clearData = function (bDontFire) {
data = [];
items = {};
if (!bDontFire) {
this.onClearData();
}
};
this.addData = function (obj, key, bDontFire) {
var k = key || obj[this.keyField];
if (items[k] != null) {
var o = items[k];
o.src = obj;
} else {
var o = {key:k, src:obj};
data.push(o);
items[o.key] = o;
}
if (!bDontFire) {
this.onAddData(o);
}
};
this.addDataRange = function (arr, bDontFire) {
var objects = [];
for (var i = 0; i < arr.length; i++) {
var k = arr[i][this.keyField];
if (items[k] != null) {
var o = items[k];
o.src = arr[i];
} else {
var o = {key:k, src:arr[i]};
data.push(o);
items[k] = o;
}
objects.push(o);
}
if (!bDontFire) {
this.onAddDataRange(objects);
}
};
this.addDataByIndex = function (obj, idx, key, bDontFire) {
var k = key || obj[this.keyField];
if (items[k] != null) {
var i = this.getIndexOf(k);
var o = data.splice(i, 1);
o.src = obj;
} else {
var o = {key:k, src:obj};
items[k] = o;
}
data.splice(idx, 0, o);
if (!bDontFire) {
this.onAddData(o);
}
};
this.addDataRangeByIndex = function (arr, idx, bDontFire) {
var objects = [];
for (var i = 0; i < arr.length; i++) {
var k = arr[i][this.keyField];
if (items[k] != null) {
var j = this.getIndexOf(k);
var o = data.splice(j, 1);
o.src = arr[i];
} else {
var o = {key:k, src:arr[i]};
items[k] = o;
}
objects.push(o);
}
data.splice(idx, 0, objects);
if (!bDontFire) {
this.onAddDataRange(objects);
}
};
this.removeData = function (obj, bDontFire) {
var idx = -1;
var o = null;
for (var i = 0; i < data.length; i++) {
if (data[i].src == obj) {
idx = i;
o = data[i];
break;
}
}
if (!bDontFire) {
this.onRemoveData(o);
}
if (idx > -1) {
data.splice(idx, 1);
delete items[o.key];
}
};
this.removeDataRange = function (idx, range, bDontFire) {
var ret = data.splice(idx, range);
for (var i = 0; i < ret.length; i++) {
delete items[ret[i].key];
}
if (!bDontFire) {
this.onRemoveDataRange(ret);
}
return ret;
};
this.removeDataByKey = function (key, bDontFire) {
this.removeData(this.getDataByKey(key), bDontFire);
};
this.removeDataByIndex = function (idx, bDontFire) {
this.removeData(this.getDataByIndex(idx), bDontFire);
};
if (jsonArray && jsonArray.length && jsonArray[0]) {
this.setData(jsonArray, true);
}
};
dojo.extend(dojo.collections.Store, {getField:function (obj, field) {
var parts = field.split("."), i = 0, o = obj;
do {
if (parts[i].indexOf("()") > -1) {
var temp = parts[i++].split("()")[0];
if (!o[temp]) {
dojo.raise("dojo.collections.Store.getField(obj, '" + field + "'): '" + temp + "' is not a property of the passed object.");
} else {
o = o[temp]();
}
} else {
o = o[parts[i++]];
}
} while (i < parts.length && o != null);
if (i < parts.length) {
dojo.raise("dojo.collections.Store.getField(obj, '" + field + "'): '" + field + "' is not a property of the passed object.");
}
return o;
}, getFromHtml:function (meta, body, fnMod) {
var rows = body.rows;
var ctor = function (row) {
var obj = {};
for (var i = 0; i < meta.length; i++) {
var o = obj;
var data = row.cells[i].innerHTML;
var p = meta[i].getField();
if (p.indexOf(".") > -1) {
p = p.split(".");
while (p.length > 1) {
var pr = p.shift();
o[pr] = {};
o = o[pr];
}
p = p[0];
}
var type = meta[i].getType();
if (type == String) {
o[p] = data;
} else {
if (data) {
o[p] = new type(data);
} else {
o[p] = new type();
}
}
}
return obj;
};
var arr = [];
for (var i = 0; i < rows.length; i++) {
var o = ctor(rows[i]);
if (fnMod) {
fnMod(o, rows[i]);
}
arr.push(o);
}
return arr;
}, onSetData:function () {
}, onClearData:function () {
}, onAddData:function (obj) {
}, onAddDataRange:function (arr) {
}, onRemoveData:function (obj) {
}, onRemoveDataRange:function (arr) {
}, onUpdateField:function (obj, field, val) {
}});
@@ -8,15 +8,6 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.kwCompoundRequire({
common: [
"dojo.collections.Collections",
"dojo.collections.SortedList",
"dojo.collections.Dictionary",
"dojo.collections.Queue",
"dojo.collections.ArrayList",
"dojo.collections.Stack",
"dojo.collections.Set"
]
});
dojo.kwCompoundRequire({common:["dojo.collections.Collections", "dojo.collections.SortedList", "dojo.collections.Dictionary", "dojo.collections.Queue", "dojo.collections.ArrayList", "dojo.collections.Stack", "dojo.collections.Set"]});
dojo.provide("dojo.collections.*");
@@ -9,23 +9,6 @@
*/
dojo.provide("dojo.crypto");
dojo.crypto.cipherModes = {ECB:0, CBC:1, PCBC:2, CFB:3, OFB:4, CTR:5};
dojo.crypto.outputTypes = {Base64:0, Hex:1, String:2, Raw:3};
dojo.crypto.cipherModes={
// summary
// Enumeration for various cipher modes.
ECB:0,
CBC:1,
PCBC:2,
CFB:3,
OFB:4,
CTR:5
};
dojo.crypto.outputTypes={
// summary
// Enumeration for input and output encodings.
Base64:0,
Hex:1,
String:2,
Raw:3
};
File diff suppressed because one or more lines are too long
@@ -1,6 +1,3 @@
dojo.require("dojo.crypto");
dojo.provide("dojo.crypto.MD5");
/* Return to a port of Paul Johnstone's MD5 implementation
* http://pajhome.org.uk/crypt/md5/index.html
*
@@ -14,186 +11,190 @@ dojo.provide("dojo.crypto.MD5");
* All conversions are internalized (no dependencies)
* implemented getHMAC for message digest auth.
*/
dojo.crypto.MD5 = new function(){
// summary
// object for creating digests using the MD5 algorithm
var chrsz=8;
var mask=(1<<chrsz)-1;
dojo.require("dojo.crypto");
dojo.provide("dojo.crypto.MD5");
dojo.crypto.MD5 = new function () {
var chrsz = 8;
var mask = (1 << chrsz) - 1;
function toWord(s) {
var wa=[];
for(var i=0; i<s.length*chrsz; i+=chrsz)
wa[i>>5]|=(s.charCodeAt(i/chrsz)&mask)<<(i%32);
return wa;
var wa = [];
for (var i = 0; i < s.length * chrsz; i += chrsz) {
wa[i >> 5] |= (s.charCodeAt(i / chrsz) & mask) << (i % 32);
}
return wa;
}
function toString(wa){
var s=[];
for(var i=0; i<wa.length*32; i+=chrsz)
s.push(String.fromCharCode((wa[i>>5]>>>(i%32))&mask));
function toString(wa) {
var s = [];
for (var i = 0; i < wa.length * 32; i += chrsz) {
s.push(String.fromCharCode((wa[i >> 5] >>> (i % 32)) & mask));
}
return s.join("");
}
function toHex(wa) {
var h="0123456789abcdef";
var s=[];
for(var i=0; i<wa.length*4; i++){
s.push(h.charAt((wa[i>>2]>>((i%4)*8+4))&0xF)+h.charAt((wa[i>>2]>>((i%4)*8))&0xF));
var h = "0123456789abcdef";
var s = [];
for (var i = 0; i < wa.length * 4; i++) {
s.push(h.charAt((wa[i >> 2] >> ((i % 4) * 8 + 4)) & 15) + h.charAt((wa[i >> 2] >> ((i % 4) * 8)) & 15));
}
return s.join("");
}
function toBase64(wa){
var p="=";
var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var s=[];
for(var i=0; i<wa.length*4; i+=3){
var t=(((wa[i>>2]>>8*(i%4))&0xFF)<<16)|(((wa[i+1>>2]>>8*((i+1)%4))&0xFF)<<8)|((wa[i+2>>2]>>8*((i+2)%4))&0xFF);
for(var j=0; j<4; j++){
if(i*8+j*6>wa.length*32) s.push(p);
else s.push(tab.charAt((t>>6*(3-j))&0x3F));
function toBase64(wa) {
var p = "=";
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var s = [];
for (var i = 0; i < wa.length * 4; i += 3) {
var t = (((wa[i >> 2] >> 8 * (i % 4)) & 255) << 16) | (((wa[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 255) << 8) | ((wa[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 255);
for (var j = 0; j < 4; j++) {
if (i * 8 + j * 6 > wa.length * 32) {
s.push(p);
} else {
s.push(tab.charAt((t >> 6 * (3 - j)) & 63));
}
}
}
return s.join("");
}
function add(x,y) {
var l=(x&0xFFFF)+(y&0xFFFF);
var m=(x>>16)+(y>>16)+(l>>16);
return (m<<16)|(l&0xFFFF);
function add(x, y) {
var l = (x & 65535) + (y & 65535);
var m = (x >> 16) + (y >> 16) + (l >> 16);
return (m << 16) | (l & 65535);
}
function R(n,c){ return (n<<c)|(n>>>(32-c)); }
function C(q,a,b,x,s,t){ return add(R(add(add(a,q),add(x,t)),s),b); }
function FF(a,b,c,d,x,s,t){ return C((b&c)|((~b)&d),a,b,x,s,t); }
function GG(a,b,c,d,x,s,t){ return C((b&d)|(c&(~d)),a,b,x,s,t); }
function HH(a,b,c,d,x,s,t){ return C(b^c^d,a,b,x,s,t); }
function II(a,b,c,d,x,s,t){ return C(c^(b|(~d)),a,b,x,s,t); }
function core(x,len){
x[len>>5]|=0x80<<((len)%32);
x[(((len+64)>>>9)<<4)+14]=len;
var a= 1732584193;
var b=-271733879;
var c=-1732584194;
var d= 271733878;
for(var i=0; i<x.length; i+=16){
var olda=a;
var oldb=b;
var oldc=c;
var oldd=d;
a=FF(a,b,c,d,x[i+ 0],7 ,-680876936);
d=FF(d,a,b,c,x[i+ 1],12,-389564586);
c=FF(c,d,a,b,x[i+ 2],17, 606105819);
b=FF(b,c,d,a,x[i+ 3],22,-1044525330);
a=FF(a,b,c,d,x[i+ 4],7 ,-176418897);
d=FF(d,a,b,c,x[i+ 5],12, 1200080426);
c=FF(c,d,a,b,x[i+ 6],17,-1473231341);
b=FF(b,c,d,a,x[i+ 7],22,-45705983);
a=FF(a,b,c,d,x[i+ 8],7 , 1770035416);
d=FF(d,a,b,c,x[i+ 9],12,-1958414417);
c=FF(c,d,a,b,x[i+10],17,-42063);
b=FF(b,c,d,a,x[i+11],22,-1990404162);
a=FF(a,b,c,d,x[i+12],7 , 1804603682);
d=FF(d,a,b,c,x[i+13],12,-40341101);
c=FF(c,d,a,b,x[i+14],17,-1502002290);
b=FF(b,c,d,a,x[i+15],22, 1236535329);
a=GG(a,b,c,d,x[i+ 1],5 ,-165796510);
d=GG(d,a,b,c,x[i+ 6],9 ,-1069501632);
c=GG(c,d,a,b,x[i+11],14, 643717713);
b=GG(b,c,d,a,x[i+ 0],20,-373897302);
a=GG(a,b,c,d,x[i+ 5],5 ,-701558691);
d=GG(d,a,b,c,x[i+10],9 , 38016083);
c=GG(c,d,a,b,x[i+15],14,-660478335);
b=GG(b,c,d,a,x[i+ 4],20,-405537848);
a=GG(a,b,c,d,x[i+ 9],5 , 568446438);
d=GG(d,a,b,c,x[i+14],9 ,-1019803690);
c=GG(c,d,a,b,x[i+ 3],14,-187363961);
b=GG(b,c,d,a,x[i+ 8],20, 1163531501);
a=GG(a,b,c,d,x[i+13],5 ,-1444681467);
d=GG(d,a,b,c,x[i+ 2],9 ,-51403784);
c=GG(c,d,a,b,x[i+ 7],14, 1735328473);
b=GG(b,c,d,a,x[i+12],20,-1926607734);
a=HH(a,b,c,d,x[i+ 5],4 ,-378558);
d=HH(d,a,b,c,x[i+ 8],11,-2022574463);
c=HH(c,d,a,b,x[i+11],16, 1839030562);
b=HH(b,c,d,a,x[i+14],23,-35309556);
a=HH(a,b,c,d,x[i+ 1],4 ,-1530992060);
d=HH(d,a,b,c,x[i+ 4],11, 1272893353);
c=HH(c,d,a,b,x[i+ 7],16,-155497632);
b=HH(b,c,d,a,x[i+10],23,-1094730640);
a=HH(a,b,c,d,x[i+13],4 , 681279174);
d=HH(d,a,b,c,x[i+ 0],11,-358537222);
c=HH(c,d,a,b,x[i+ 3],16,-722521979);
b=HH(b,c,d,a,x[i+ 6],23, 76029189);
a=HH(a,b,c,d,x[i+ 9],4 ,-640364487);
d=HH(d,a,b,c,x[i+12],11,-421815835);
c=HH(c,d,a,b,x[i+15],16, 530742520);
b=HH(b,c,d,a,x[i+ 2],23,-995338651);
a=II(a,b,c,d,x[i+ 0],6 ,-198630844);
d=II(d,a,b,c,x[i+ 7],10, 1126891415);
c=II(c,d,a,b,x[i+14],15,-1416354905);
b=II(b,c,d,a,x[i+ 5],21,-57434055);
a=II(a,b,c,d,x[i+12],6 , 1700485571);
d=II(d,a,b,c,x[i+ 3],10,-1894986606);
c=II(c,d,a,b,x[i+10],15,-1051523);
b=II(b,c,d,a,x[i+ 1],21,-2054922799);
a=II(a,b,c,d,x[i+ 8],6 , 1873313359);
d=II(d,a,b,c,x[i+15],10,-30611744);
c=II(c,d,a,b,x[i+ 6],15,-1560198380);
b=II(b,c,d,a,x[i+13],21, 1309151649);
a=II(a,b,c,d,x[i+ 4],6 ,-145523070);
d=II(d,a,b,c,x[i+11],10,-1120210379);
c=II(c,d,a,b,x[i+ 2],15, 718787259);
b=II(b,c,d,a,x[i+ 9],21,-343485551);
a = add(a,olda);
b = add(b,oldb);
c = add(c,oldc);
d = add(d,oldd);
function R(n, c) {
return (n << c) | (n >>> (32 - c));
}
function C(q, a, b, x, s, t) {
return add(R(add(add(a, q), add(x, t)), s), b);
}
function FF(a, b, c, d, x, s, t) {
return C((b & c) | ((~b) & d), a, b, x, s, t);
}
function GG(a, b, c, d, x, s, t) {
return C((b & d) | (c & (~d)), a, b, x, s, t);
}
function HH(a, b, c, d, x, s, t) {
return C(b ^ c ^ d, a, b, x, s, t);
}
function II(a, b, c, d, x, s, t) {
return C(c ^ (b | (~d)), a, b, x, s, t);
}
function core(x, len) {
x[len >> 5] |= 128 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = FF(a, b, c, d, x[i + 0], 7, -680876936);
d = FF(d, a, b, c, x[i + 1], 12, -389564586);
c = FF(c, d, a, b, x[i + 2], 17, 606105819);
b = FF(b, c, d, a, x[i + 3], 22, -1044525330);
a = FF(a, b, c, d, x[i + 4], 7, -176418897);
d = FF(d, a, b, c, x[i + 5], 12, 1200080426);
c = FF(c, d, a, b, x[i + 6], 17, -1473231341);
b = FF(b, c, d, a, x[i + 7], 22, -45705983);
a = FF(a, b, c, d, x[i + 8], 7, 1770035416);
d = FF(d, a, b, c, x[i + 9], 12, -1958414417);
c = FF(c, d, a, b, x[i + 10], 17, -42063);
b = FF(b, c, d, a, x[i + 11], 22, -1990404162);
a = FF(a, b, c, d, x[i + 12], 7, 1804603682);
d = FF(d, a, b, c, x[i + 13], 12, -40341101);
c = FF(c, d, a, b, x[i + 14], 17, -1502002290);
b = FF(b, c, d, a, x[i + 15], 22, 1236535329);
a = GG(a, b, c, d, x[i + 1], 5, -165796510);
d = GG(d, a, b, c, x[i + 6], 9, -1069501632);
c = GG(c, d, a, b, x[i + 11], 14, 643717713);
b = GG(b, c, d, a, x[i + 0], 20, -373897302);
a = GG(a, b, c, d, x[i + 5], 5, -701558691);
d = GG(d, a, b, c, x[i + 10], 9, 38016083);
c = GG(c, d, a, b, x[i + 15], 14, -660478335);
b = GG(b, c, d, a, x[i + 4], 20, -405537848);
a = GG(a, b, c, d, x[i + 9], 5, 568446438);
d = GG(d, a, b, c, x[i + 14], 9, -1019803690);
c = GG(c, d, a, b, x[i + 3], 14, -187363961);
b = GG(b, c, d, a, x[i + 8], 20, 1163531501);
a = GG(a, b, c, d, x[i + 13], 5, -1444681467);
d = GG(d, a, b, c, x[i + 2], 9, -51403784);
c = GG(c, d, a, b, x[i + 7], 14, 1735328473);
b = GG(b, c, d, a, x[i + 12], 20, -1926607734);
a = HH(a, b, c, d, x[i + 5], 4, -378558);
d = HH(d, a, b, c, x[i + 8], 11, -2022574463);
c = HH(c, d, a, b, x[i + 11], 16, 1839030562);
b = HH(b, c, d, a, x[i + 14], 23, -35309556);
a = HH(a, b, c, d, x[i + 1], 4, -1530992060);
d = HH(d, a, b, c, x[i + 4], 11, 1272893353);
c = HH(c, d, a, b, x[i + 7], 16, -155497632);
b = HH(b, c, d, a, x[i + 10], 23, -1094730640);
a = HH(a, b, c, d, x[i + 13], 4, 681279174);
d = HH(d, a, b, c, x[i + 0], 11, -358537222);
c = HH(c, d, a, b, x[i + 3], 16, -722521979);
b = HH(b, c, d, a, x[i + 6], 23, 76029189);
a = HH(a, b, c, d, x[i + 9], 4, -640364487);
d = HH(d, a, b, c, x[i + 12], 11, -421815835);
c = HH(c, d, a, b, x[i + 15], 16, 530742520);
b = HH(b, c, d, a, x[i + 2], 23, -995338651);
a = II(a, b, c, d, x[i + 0], 6, -198630844);
d = II(d, a, b, c, x[i + 7], 10, 1126891415);
c = II(c, d, a, b, x[i + 14], 15, -1416354905);
b = II(b, c, d, a, x[i + 5], 21, -57434055);
a = II(a, b, c, d, x[i + 12], 6, 1700485571);
d = II(d, a, b, c, x[i + 3], 10, -1894986606);
c = II(c, d, a, b, x[i + 10], 15, -1051523);
b = II(b, c, d, a, x[i + 1], 21, -2054922799);
a = II(a, b, c, d, x[i + 8], 6, 1873313359);
d = II(d, a, b, c, x[i + 15], 10, -30611744);
c = II(c, d, a, b, x[i + 6], 15, -1560198380);
b = II(b, c, d, a, x[i + 13], 21, 1309151649);
a = II(a, b, c, d, x[i + 4], 6, -145523070);
d = II(d, a, b, c, x[i + 11], 10, -1120210379);
c = II(c, d, a, b, x[i + 2], 15, 718787259);
b = II(b, c, d, a, x[i + 9], 21, -343485551);
a = add(a, olda);
b = add(b, oldb);
c = add(c, oldc);
d = add(d, oldd);
}
return [a,b,c,d];
return [a, b, c, d];
}
function hmac(data,key){
var wa=toWord(key);
if(wa.length>16) wa=core(wa,key.length*chrsz);
var l=[], r=[];
for(var i=0; i<16; i++){
l[i]=wa[i]^0x36363636;
r[i]=wa[i]^0x5c5c5c5c;
function hmac(data, key) {
var wa = toWord(key);
if (wa.length > 16) {
wa = core(wa, key.length * chrsz);
}
var h=core(l.concat(toWord(data)),512+data.length*chrsz);
return core(r.concat(h),640);
var l = [], r = [];
for (var i = 0; i < 16; i++) {
l[i] = wa[i] ^ 909522486;
r[i] = wa[i] ^ 1549556828;
}
var h = core(l.concat(toWord(data)), 512 + data.length * chrsz);
return core(r.concat(h), 640);
}
// Public functions
this.compute=function(/* string */data, /* dojo.crypto.outputTypes */outputType){
// summary
// computes the digest of data, and returns the result as a string of type outputType
var out=outputType||dojo.crypto.outputTypes.Base64;
switch(out){
case dojo.crypto.outputTypes.Hex:{
return toHex(core(toWord(data),data.length*chrsz)); // string
}
case dojo.crypto.outputTypes.String:{
return toString(core(toWord(data),data.length*chrsz)); // string
}
default:{
return toBase64(core(toWord(data),data.length*chrsz)); // string
}
this.compute = function (data, outputType) {
var out = outputType || dojo.crypto.outputTypes.Base64;
switch (out) {
case dojo.crypto.outputTypes.Hex:
return toHex(core(toWord(data), data.length * chrsz));
case dojo.crypto.outputTypes.String:
return toString(core(toWord(data), data.length * chrsz));
default:
return toBase64(core(toWord(data), data.length * chrsz));
}
};
this.getHMAC=function(/* string */data, /* string */key, /* dojo.crypto.outputTypes */outputType){
// summary
// computes a digest of data using key, and returns the result as a string of outputType
var out=outputType||dojo.crypto.outputTypes.Base64;
switch(out){
case dojo.crypto.outputTypes.Hex:{
return toHex(hmac(data,key)); // string
}
case dojo.crypto.outputTypes.String:{
return toString(hmac(data,key)); // string
}
default:{
return toBase64(hmac(data,key)); // string
}
this.getHMAC = function (data, key, outputType) {
var out = outputType || dojo.crypto.outputTypes.Base64;
switch (out) {
case dojo.crypto.outputTypes.Hex:
return toHex(hmac(data, key));
case dojo.crypto.outputTypes.String:
return toString(hmac(data, key));
default:
return toBase64(hmac(data, key));
}
};
}();
@@ -11,12 +11,11 @@
dojo.provide("dojo.crypto.Rijndael");
dojo.require("dojo.crypto");
dojo.require("dojo.experimental");
dojo.experimental("dojo.crypto.Rijndael");
dojo.crypto.Rijndael = new function(){
this.encrypt=function(plaintext, key){
dojo.crypto.Rijndael = new function () {
this.encrypt = function (plaintext, key) {
};
this.decrypt=function(ciphertext, key){
this.decrypt = function (ciphertext, key) {
};
}();
@@ -1,7 +1,3 @@
dojo.require("dojo.crypto");
dojo.provide("dojo.crypto.SHA1");
dojo.require("dojo.experimental");
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
@@ -13,142 +9,163 @@ dojo.require("dojo.experimental");
*
* Dojo port by Tom Trenka
*/
dojo.experimental("dojo.crypto.SHA1");
dojo.crypto.SHA1 = new function(){
var chrsz=8;
var mask=(1<<chrsz)-1;
dojo.require("dojo.crypto");
dojo.provide("dojo.crypto.SHA1");
dojo.require("dojo.experimental");
dojo.experimental("dojo.crypto.SHA1");
dojo.crypto.SHA1 = new function () {
var chrsz = 8;
var mask = (1 << chrsz) - 1;
function toWord(s) {
var wa=[];
for(var i=0; i<s.length*chrsz; i+=chrsz)
wa[i>>5]|=(s.charCodeAt(i/chrsz)&mask)<<(i%32);
return wa;
var wa = [];
for (var i = 0; i < s.length * chrsz; i += chrsz) {
wa[i >> 5] |= (s.charCodeAt(i / chrsz) & mask) << (i % 32);
}
return wa;
}
function toString(wa){
var s=[];
for(var i=0; i<wa.length*32; i+=chrsz)
s.push(String.fromCharCode((wa[i>>5]>>>(i%32))&mask));
function toString(wa) {
var s = [];
for (var i = 0; i < wa.length * 32; i += chrsz) {
s.push(String.fromCharCode((wa[i >> 5] >>> (i % 32)) & mask));
}
return s.join("");
}
function toHex(wa) {
var h="0123456789abcdef";
var s=[];
for(var i=0; i<wa.length*4; i++){
s.push(h.charAt((wa[i>>2]>>((i%4)*8+4))&0xF)+h.charAt((wa[i>>2]>>((i%4)*8))&0xF));
var h = "0123456789abcdef";
var s = [];
for (var i = 0; i < wa.length * 4; i++) {
s.push(h.charAt((wa[i >> 2] >> ((i % 4) * 8 + 4)) & 15) + h.charAt((wa[i >> 2] >> ((i % 4) * 8)) & 15));
}
return s.join("");
}
function toBase64(wa){
var p="=";
var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var s=[];
for(var i=0; i<wa.length*4; i+=3){
var t=(((wa[i>>2]>>8*(i%4))&0xFF)<<16)|(((wa[i+1>>2]>>8*((i+1)%4))&0xFF)<<8)|((wa[i+2>>2]>>8*((i+2)%4))&0xFF);
for(var j=0; j<4; j++){
if(i*8+j*6>wa.length*32) s.push(p);
else s.push(tab.charAt((t>>6*(3-j))&0x3F));
function toBase64(wa) {
var p = "=";
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var s = [];
for (var i = 0; i < wa.length * 4; i += 3) {
var t = (((wa[i >> 2] >> 8 * (i % 4)) & 255) << 16) | (((wa[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 255) << 8) | ((wa[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 255);
for (var j = 0; j < 4; j++) {
if (i * 8 + j * 6 > wa.length * 32) {
s.push(p);
} else {
s.push(tab.charAt((t >> 6 * (3 - j)) & 63));
}
}
}
return s.join("");
}
// math
function add(x,y){
var l=(x&0xffff)+(y&0xffff);
var m=(x>>16)+(y>>16)+(l>>16);
return (m<<16)|(l&0xffff);
function add(x, y) {
var l = (x & 65535) + (y & 65535);
var m = (x >> 16) + (y >> 16) + (l >> 16);
return (m << 16) | (l & 65535);
}
function r(x,n){ return (x<<n)|(x>>>(32-n)); }
// SHA rounds
function f(u,v,w){ return ((u&v)|(~u&w)); }
function g(u,v,w){ return ((u&v)|(u&w)|(v&w)); }
function h(u,v,w){ return (u^v^w); }
function fn(i,u,v,w){
if(i<20) return f(u,v,w);
if(i<40) return h(u,v,w);
if(i<60) return g(u,v,w);
return h(u,v,w);
function r(x, n) {
return (x << n) | (x >>> (32 - n));
}
function cnst(i){
if(i<20) return 1518500249;
if(i<40) return 1859775393;
if(i<60) return -1894007588;
function f(u, v, w) {
return ((u & v) | (~u & w));
}
function g(u, v, w) {
return ((u & v) | (u & w) | (v & w));
}
function h(u, v, w) {
return (u ^ v ^ w);
}
function fn(i, u, v, w) {
if (i < 20) {
return f(u, v, w);
}
if (i < 40) {
return h(u, v, w);
}
if (i < 60) {
return g(u, v, w);
}
return h(u, v, w);
}
function cnst(i) {
if (i < 20) {
return 1518500249;
}
if (i < 40) {
return 1859775393;
}
if (i < 60) {
return -1894007588;
}
return -899497514;
}
function core(x,len){
x[len>>5]|=0x80<<(24-len%32);
x[((len+64>>9)<<4)+15]=len;
var w=[];
var a= 1732584193; // 0x67452301
var b=-271733879; // 0xefcdab89
var c=-1732584194; // 0x98badcfe
var d= 271733878; // 0x10325476
var e=-1009589776; // 0xc3d2e1f0
for(var i=0; i<x.length; i+=16){
var olda=a;
var oldb=b;
var oldc=c;
var oldd=d;
var olde=e;
for(var j=0; j<80; j++){
if(j<16) w[j]=x[i+j];
else w[j]=r(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);
var t=add(add(r(a,5),fn(j,b,c,d)),add(add(e,w[j]),cnst(j)));
e=d; d=c; c=r(b,30); b=a; a=t;
function core(x, len) {
x[len >> 5] |= 128 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = [];
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for (var j = 0; j < 80; j++) {
if (j < 16) {
w[j] = x[i + j];
} else {
w[j] = r(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
var t = add(add(r(a, 5), fn(j, b, c, d)), add(add(e, w[j]), cnst(j)));
e = d;
d = c;
c = r(b, 30);
b = a;
a = t;
}
a=add(a,olda);
b=add(b,oldb);
c=add(c,oldc);
d=add(d,oldd);
e=add(e,olde);
a = add(a, olda);
b = add(b, oldb);
c = add(c, oldc);
d = add(d, oldd);
e = add(e, olde);
}
return [a,b,c,d,e];
return [a, b, c, d, e];
}
function hmac(data,key){
var wa=toWord(key);
if(wa.length>16) wa=core(wa,key.length*chrsz);
var l=[], r=[];
for(var i=0; i<16; i++){
l[i]=wa[i]^0x36363636;
r[i]=wa[i]^0x5c5c5c5c;
function hmac(data, key) {
var wa = toWord(key);
if (wa.length > 16) {
wa = core(wa, key.length * chrsz);
}
var h=core(l.concat(toWord(data)),512+data.length*chrsz);
return core(r.concat(h),640);
var l = [], r = [];
for (var i = 0; i < 16; i++) {
l[i] = wa[i] ^ 909522486;
r[i] = wa[i] ^ 1549556828;
}
var h = core(l.concat(toWord(data)), 512 + data.length * chrsz);
return core(r.concat(h), 640);
}
this.compute=function(data,outputType){
var out=outputType||dojo.crypto.outputTypes.Base64;
switch(out){
case dojo.crypto.outputTypes.Hex:{
return toHex(core(toWord(data),data.length*chrsz));
}
case dojo.crypto.outputTypes.String:{
return toString(core(toWord(data),data.length*chrsz));
}
default:{
return toBase64(core(toWord(data),data.length*chrsz));
}
this.compute = function (data, outputType) {
var out = outputType || dojo.crypto.outputTypes.Base64;
switch (out) {
case dojo.crypto.outputTypes.Hex:
return toHex(core(toWord(data), data.length * chrsz));
case dojo.crypto.outputTypes.String:
return toString(core(toWord(data), data.length * chrsz));
default:
return toBase64(core(toWord(data), data.length * chrsz));
}
};
this.getHMAC=function(data,key,outputType){
var out=outputType||dojo.crypto.outputTypes.Base64;
switch(out){
case dojo.crypto.outputTypes.Hex:{
return toHex(hmac(data,key));
}
case dojo.crypto.outputTypes.String:{
return toString(hmac(data,key));
}
default:{
return toBase64(hmac(data,key));
}
this.getHMAC = function (data, key, outputType) {
var out = outputType || dojo.crypto.outputTypes.Base64;
switch (out) {
case dojo.crypto.outputTypes.Hex:
return toHex(hmac(data, key));
case dojo.crypto.outputTypes.String:
return toString(hmac(data, key));
default:
return toBase64(hmac(data, key));
}
};
}();
@@ -11,10 +11,9 @@
dojo.provide("dojo.crypto.SHA256");
dojo.require("dojo.crypto");
dojo.require("dojo.experimental");
dojo.experimental("dojo.crypto.SHA256");
dojo.crypto.SHA256 = new function(){
this.compute=function(s){
dojo.crypto.SHA256 = new function () {
this.compute = function (s) {
};
}();
@@ -8,10 +8,6 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.kwCompoundRequire({
common: [
"dojo.crypto",
"dojo.crypto.MD5"
]
});
dojo.kwCompoundRequire({common:["dojo.crypto", "dojo.crypto.MD5"]});
dojo.provide("dojo.crypto.*");
@@ -9,7 +9,5 @@
*/
dojo.provide("dojo.data");
// currently a stub for dojo.data
dojo.data = {};
@@ -0,0 +1,113 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.CsvStore");
dojo.require("dojo.data.core.RemoteStore");
dojo.require("dojo.lang.assert");
dojo.declare("dojo.data.CsvStore", dojo.data.core.RemoteStore, {_setupQueryRequest:function (result, requestKw) {
var serverQueryUrl = this._serverQueryUrl ? this._serverQueryUrl : "";
var queryUrl = result.query ? result.query : "";
requestKw.url = serverQueryUrl + queryUrl;
requestKw.method = "get";
}, _resultToQueryData:function (serverResponseData) {
var csvFileContentString = serverResponseData;
var arrayOfArrays = this._getArrayOfArraysFromCsvFileContents(csvFileContentString);
var arrayOfObjects = this._getArrayOfObjectsFromArrayOfArrays(arrayOfArrays);
var remoteStoreData = this._getRemoteStoreDataFromArrayOfObjects(arrayOfObjects);
return remoteStoreData;
}, _setupSaveRequest:function (saveKeywordArgs, requestKw) {
}, _getArrayOfArraysFromCsvFileContents:function (csvFileContents) {
dojo.lang.assertType(csvFileContents, String);
var lineEndingCharacters = new RegExp("\r\n|\n|\r");
var leadingWhiteSpaceCharacters = new RegExp("^\\s+", "g");
var trailingWhiteSpaceCharacters = new RegExp("\\s+$", "g");
var doubleQuotes = new RegExp("\"\"", "g");
var arrayOfOutputRecords = [];
var arrayOfInputLines = csvFileContents.split(lineEndingCharacters);
for (var i in arrayOfInputLines) {
var singleLine = arrayOfInputLines[i];
if (singleLine.length > 0) {
var listOfFields = singleLine.split(",");
var j = 0;
while (j < listOfFields.length) {
var space_field_space = listOfFields[j];
var field_space = space_field_space.replace(leadingWhiteSpaceCharacters, "");
var field = field_space.replace(trailingWhiteSpaceCharacters, "");
var firstChar = field.charAt(0);
var lastChar = field.charAt(field.length - 1);
var secondToLastChar = field.charAt(field.length - 2);
var thirdToLastChar = field.charAt(field.length - 3);
if ((firstChar == "\"") && ((lastChar != "\"") || ((lastChar == "\"") && (secondToLastChar == "\"") && (thirdToLastChar != "\"")))) {
if (j + 1 === listOfFields.length) {
return null;
}
var nextField = listOfFields[j + 1];
listOfFields[j] = field_space + "," + nextField;
listOfFields.splice(j + 1, 1);
} else {
if ((firstChar == "\"") && (lastChar == "\"")) {
field = field.slice(1, (field.length - 1));
field = field.replace(doubleQuotes, "\"");
}
listOfFields[j] = field;
j += 1;
}
}
arrayOfOutputRecords.push(listOfFields);
}
}
return arrayOfOutputRecords;
}, _getArrayOfObjectsFromArrayOfArrays:function (arrayOfArrays) {
dojo.lang.assertType(arrayOfArrays, Array);
var arrayOfItems = [];
if (arrayOfArrays.length > 1) {
var arrayOfKeys = arrayOfArrays[0];
for (var i = 1; i < arrayOfArrays.length; ++i) {
var row = arrayOfArrays[i];
var item = {};
for (var j in row) {
var value = row[j];
var key = arrayOfKeys[j];
item[key] = value;
}
arrayOfItems.push(item);
}
}
return arrayOfItems;
}, _getRemoteStoreDataFromArrayOfObjects:function (arrayOfObjects) {
dojo.lang.assertType(arrayOfObjects, Array);
var output = {};
for (var i = 0; i < arrayOfObjects.length; ++i) {
var object = arrayOfObjects[i];
for (var key in object) {
var value = object[key];
object[key] = [value];
}
output[i] = object;
}
return output;
}, newItem:function (attributes, keywordArgs) {
dojo.unimplemented("dojo.data.CsvStore.newItem");
}, deleteItem:function (item) {
dojo.unimplemented("dojo.data.CsvStore.deleteItem");
}, setValues:function (item, attribute, values) {
dojo.unimplemented("dojo.data.CsvStore.setValues");
}, set:function (item, attribute, value) {
dojo.unimplemented("dojo.data.CsvStore.set");
}, unsetAttribute:function (item, attribute) {
dojo.unimplemented("dojo.data.CsvStore.unsetAttribute");
}, save:function (keywordArgs) {
dojo.unimplemented("dojo.data.CsvStore.save");
}, revert:function () {
dojo.unimplemented("dojo.data.CsvStore.revert");
}, isDirty:function (item) {
dojo.unimplemented("dojo.data.CsvStore.isDirty");
}});
@@ -0,0 +1,164 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.OpmlStore");
dojo.require("dojo.data.core.Read");
dojo.require("dojo.data.core.Result");
dojo.require("dojo.lang.assert");
dojo.require("dojo.json");
dojo.require("dojo.experimental");
dojo.experimental("dojo.data.OpmlStore");
dojo.declare("dojo.data.OpmlStore", dojo.data.core.Read, {initializer:function (keywordParameters) {
this._arrayOfTopLevelItems = [];
this._metadataNodes = null;
this._loadFinished = false;
this._opmlFileUrl = keywordParameters["url"];
}, _assertIsItem:function (item) {
if (!this.isItem(item)) {
throw new Error("dojo.data.OpmlStore: a function was passed an item argument that was not an item");
}
}, _removeChildNodesThatAreNotElementNodes:function (node, recursive) {
var childNodes = node.childNodes;
if (childNodes.length == 0) {
return;
}
var nodesToRemove = [];
var i, childNode;
for (i = 0; i < childNodes.length; ++i) {
childNode = childNodes[i];
if (childNode.nodeType != Node.ELEMENT_NODE) {
nodesToRemove.push(childNode);
}
}
for (i = 0; i < nodesToRemove.length; ++i) {
childNode = nodesToRemove[i];
node.removeChild(childNode);
}
if (recursive) {
for (i = 0; i < childNodes.length; ++i) {
childNode = childNodes[i];
this._removeChildNodesThatAreNotElementNodes(childNode, recursive);
}
}
}, _processRawXmlTree:function (rawXmlTree) {
var headNodes = rawXmlTree.getElementsByTagName("head");
var headNode = headNodes[0];
this._removeChildNodesThatAreNotElementNodes(headNode);
this._metadataNodes = headNode.childNodes;
var bodyNodes = rawXmlTree.getElementsByTagName("body");
var bodyNode = bodyNodes[0];
this._removeChildNodesThatAreNotElementNodes(bodyNode, true);
var bodyChildNodes = bodyNodes[0].childNodes;
for (var i = 0; i < bodyChildNodes.length; ++i) {
var node = bodyChildNodes[i];
if (node.tagName == "outline") {
this._arrayOfTopLevelItems.push(node);
}
}
}, get:function (item, attribute, defaultValue) {
this._assertIsItem(item);
if (attribute == "children") {
return (item.firstChild || defaultValue);
} else {
var value = item.getAttribute(attribute);
value = (value != undefined) ? value : defaultValue;
return value;
}
}, getValues:function (item, attribute) {
this._assertIsItem(item);
if (attribute == "children") {
var array = [];
for (var i = 0; i < item.childNodes.length; ++i) {
array.push(item.childNodes[i]);
}
return array;
} else {
return [item.getAttribute(attribute)];
}
}, getAttributes:function (item) {
this._assertIsItem(item);
var attributes = [];
var xmlNode = item;
var xmlAttributes = xmlNode.attributes;
for (var i = 0; i < xmlAttributes.length; ++i) {
var xmlAttribute = xmlAttributes.item(i);
attributes.push(xmlAttribute.nodeName);
}
if (xmlNode.childNodes.length > 0) {
attributes.push("children");
}
return attributes;
}, hasAttribute:function (item, attribute) {
return (this.getValues(item, attribute).length > 0);
}, containsValue:function (item, attribute, value) {
var values = this.getValues(item, attribute);
for (var i = 0; i < values.length; ++i) {
var possibleValue = values[i];
if (value == possibleValue) {
return true;
}
}
return false;
}, isItem:function (something) {
return (something && something.nodeType == Node.ELEMENT_NODE && something.tagName == "outline");
}, isItemAvailable:function (something) {
return this.isItem(something);
}, find:function (keywordArgs) {
var result = null;
if (keywordArgs instanceof dojo.data.core.Result) {
result = keywordArgs;
result.store = this;
} else {
result = new dojo.data.core.Result(keywordArgs, this);
}
var self = this;
var bindHandler = function (type, data, evt) {
var scope = result.scope || dj_global;
if (type == "load") {
self._processRawXmlTree(data);
if (result.saveResult) {
result.items = self._arrayOfTopLevelItems;
}
if (result.onbegin) {
result.onbegin.call(scope, result);
}
for (var i = 0; i < self._arrayOfTopLevelItems.length; i++) {
var item = self._arrayOfTopLevelItems[i];
if (result.onnext && !result._aborted) {
result.onnext.call(scope, item, result);
}
}
if (result.oncompleted && !result._aborted) {
result.oncompleted.call(scope, result);
}
} else {
if (type == "error" || type == "timeout") {
var errorObject = data;
if (result.onerror) {
result.onerror.call(scope, data);
}
}
}
};
if (!this._loadFinished) {
if (this._opmlFileUrl) {
var bindRequest = dojo.io.bind({url:this._opmlFileUrl, handle:bindHandler, mimetype:"text/xml", sync:(result.sync || false)});
result._abortFunc = bindRequest.abort;
}
}
return result;
}, getIdentity:function (item) {
dojo.unimplemented("dojo.data.OpmlStore.getIdentity()");
return null;
}, findByIdentity:function (identity) {
dojo.unimplemented("dojo.data.OpmlStore.findByIdentity()");
return null;
}});
@@ -0,0 +1,183 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.RdfStore");
dojo.provide("dojo.data.RhizomeStore");
dojo.require("dojo.lang.declare");
dojo.require("dojo.data.core.RemoteStore");
dojo.require("dojo.experimental");
dojo.data.RdfDatatypeSerializer = function (type, convertFunc, uri) {
this.type = type;
this._converter = convertFunc;
this.uri = uri;
this.serialize = function (value) {
return this._converter.call(value, value);
};
};
dojo.declare("dojo.data.RdfStore", dojo.data.core.RemoteStore, {_datatypeMap:{literal:function (value) {
var literal = value.value;
if (value["xml:lang"]) {
literal.lang = value["xml:lang"];
}
return literal;
}, uri:function (value) {
return {id:value.value};
}, bnode:function (value) {
return {id:"_:" + value.value};
}, "http://www.w3.org/2001/XMLSchema#int":function (value) {
return parseInt(value.value);
}, "http://www.w3.org/2001/XMLSchema#integer":function (value) {
return parseInt(value.value);
}, "http://www.w3.org/2001/XMLSchema#long":function (value) {
return parseInt(value.value);
}, "http://www.w3.org/2001/XMLSchema#float":function (value) {
return parseFloat(value.value);
}, "http://www.w3.org/2001/XMLSchema#double":function (value) {
return parseFloat(value.value);
}, "http://www.w3.org/2001/XMLSchema#boolean":function (value) {
return !value || value == "false" || value == "0" ? false : true;
}}, _datatypeSerializers:[new dojo.data.RdfDatatypeSerializer(Number, Number.toString, "http://www.w3.org/2001/XMLSchema#float"), new dojo.data.RdfDatatypeSerializer(Boolean, Boolean.toString, "http://www.w3.org/2001/XMLSchema#boolean")], _findDatatypeSerializer:function (value) {
var length = this._datatypeSerializers.length;
for (var i = 0; i < length; i++) {
var datatype = this._datatypeSerializers[i];
if (value instanceof datatype.type) {
return datatype;
}
}
}, _toRDFValue:function (value) {
var rdfvalue = {};
if (value.id) {
if (value.id.slice(0, 2) == "_:") {
rdfvalue.type = "bnode";
rdfvalue.value = value.id.substring(2);
} else {
rdfvalue.type = "uri";
rdfvalue.value = value.id;
}
} else {
if (typeof value == "string" || value instanceof String) {
rdfvalue.type = "literal";
rdfvalue.value = value;
if (value.lang) {
rdfvalue["xml:lang"] = value.lang;
}
} else {
if (typeof value == "number") {
value = new Number(value);
} else {
if (typeof value == "boolean") {
value = new Boolean(value);
}
}
var datatype = this._findDatatypeSerializer(value);
if (datatype) {
rdfvalue = {"type":"typed-literal", "datatype":datatype.uri, "value":value.toString()};
} else {
rdfvalue = {"type":"literal", "value":value.toString()};
}
}
}
return rdfvalue;
}, _setupSaveRequest:function (saveKeywordArgs, requestKw) {
var rdfResult = {"head":{"vars":["s", "p", "o"]}, "results":{"bindings":[]}};
var resources = [];
for (var key in this._deleted) {
resources.push(key);
}
rdfResult.results.deleted = resources;
for (key in this._changed) {
var subject = this._toRDFValue(this.getIdentity(key));
var attributes = this._changed[key];
for (var attr in attributes) {
var predicate = {type:"uri", value:attr};
var values = attributes[attr];
if (!values.length) {
continue;
}
var rdfvalues = [];
for (var i = 0; i < values.length; i++) {
var rdfvalue = this._toRDFValue(values[i]);
rdfResult.results.bindings.push({s:subject, p:predicate, o:rdfvalue});
}
}
}
var oldRegistry = dojo.json.jsonRegistry;
dojo.json.jsonRegistry = this._jsonRegistry;
var jsonString = dojo.json.serialize(rdfResult);
dojo.json.jsonRegistry = oldRegistry;
requestKw.postContent = jsonString;
}, _resultToQueryMetadata:function (json) {
return json.head;
}, _resultToQueryData:function (json) {
var items = {};
var stmts = json.results.bindings;
for (var i = 0; i < stmts.length; i++) {
var stmt = stmts[i];
var subject = stmt.s.value;
if (stmt.s.type == "bnode") {
subject = "_:" + subject;
}
var attributes = data[subject];
if (!attributes) {
attributes = {};
data[stmt.s] = attributes;
}
var attr = attributes[stmt.p.value];
if (!attr) {
attributes[stmt.p.value] = [stmt.o];
} else {
attr.push(stmt.o);
}
}
return items;
}});
dojo.declare("dojo.data.RhizomeStore", dojo.data.RdfStore, {initializer:function (kwArgs) {
this._serverQueryUrl = kwArgs.baseUrl + "search?view=json&searchType=RxPath&search=";
this._serverSaveUrl = kwArgs.baseUrl + "save-metadata";
}, _resultToQueryMetadata:function (json) {
return json;
}, _resultToQueryData:function (json) {
return json;
}, _setupSaveRequest:function (saveKeywordArgs, requestKw) {
requestKw.url = this._serverSaveUrl;
requestKw.method = "post";
requestKw.mimetype = "text/plain";
var resources = [];
for (var key in this._deleted) {
resources.push(key);
}
var changes = {};
for (key in this._changed) {
if (!this._added[key]) {
resources.push(key);
}
var attributes = this._changed[key];
var rdfattributes = {};
for (var attr in attributes) {
var values = attributes[attr];
if (!values.length) {
continue;
}
var rdfvalues = [];
for (var i = 0; i < values.length; i++) {
var rdfvalue = this._toRDFValue(values[i]);
rdfvalues.push(rdfvalue);
}
rdfattributes[attr] = rdfvalues;
}
changes[key] = rdfattributes;
}
var oldRegistry = dojo.json.jsonRegistry;
dojo.json.jsonRegistry = this._jsonRegistry;
var jsonString = dojo.json.serialize(changes);
dojo.json.jsonRegistry = oldRegistry;
requestKw.content = {rdfFormat:"json", resource:resources, metadata:jsonString};
}});
@@ -0,0 +1,42 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.YahooStore");
dojo.require("dojo.data.core.RemoteStore");
dojo.require("dojo.lang.declare");
dojo.require("dojo.io.ScriptSrcIO");
dojo.declare("dojo.data.YahooStore", dojo.data.core.RemoteStore, {_setupQueryRequest:function (result, requestKw) {
var start = 1;
var count = 1;
if (result) {
start = result.start || start;
count = result.count || count;
}
var sourceUrl = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=dojo&language=en&query=" + result.query + "&start=" + start + "&results=" + count + "&output=json";
requestKw.url = sourceUrl;
requestKw.transport = "ScriptSrcTransport";
requestKw.mimetype = "text/json";
requestKw.jsonParamName = "callback";
}, _resultToQueryMetadata:function (json) {
return json.ResultSet;
}, _resultToQueryData:function (json) {
var data = {};
for (var i = 0; i < json.ResultSet.totalResultsReturned; ++i) {
var record = json.ResultSet.Result[i];
var item = {};
item["Url"] = [record.Url];
item["Title"] = [record.Title];
item["Summary"] = [record.Summary];
var arrayIndex = (json.ResultSet.firstResultPosition - 1) + i;
data[arrayIndex.toString()] = item;
}
return data;
}});
@@ -0,0 +1,53 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.core.Read");
dojo.require("dojo.data.core.Result");
dojo.require("dojo.lang.declare");
dojo.require("dojo.experimental");
dojo.experimental("dojo.data.core.Read");
dojo.declare("dojo.data.core.Read", null, {get:function (item, attribute, defaultValue) {
dojo.unimplemented("dojo.data.core.Read.get");
var attributeValue = null;
return attributeValue;
}, getValues:function (item, attribute) {
dojo.unimplemented("dojo.data.core.Read.getValues");
var array = null;
return array;
}, getAttributes:function (item) {
dojo.unimplemented("dojo.data.core.Read.getAttributes");
var array = null;
return array;
}, hasAttribute:function (item, attribute) {
dojo.unimplemented("dojo.data.core.Read.hasAttribute");
return false;
}, containsValue:function (item, attribute, value) {
dojo.unimplemented("dojo.data.core.Read.containsValue");
return false;
}, isItem:function (something) {
dojo.unimplemented("dojo.data.core.Read.isItem");
return false;
}, isItemAvailable:function (something) {
dojo.unimplemented("dojo.data.core.Read.isItemAvailable");
return false;
}, find:function (keywordArgs) {
dojo.unimplemented("dojo.data.core.Read.find");
var result = null;
return result;
}, getIdentity:function (item) {
dojo.unimplemented("dojo.data.core.Read.getIdentity");
var itemIdentifyString = null;
return itemIdentifyString;
}, findByIdentity:function (identity) {
dojo.unimplemented("dojo.data.core.Read.getByIdentity");
var item = null;
return item;
}});
@@ -0,0 +1,352 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.core.RemoteStore");
dojo.require("dojo.data.core.Read");
dojo.require("dojo.data.core.Write");
dojo.require("dojo.data.core.Result");
dojo.require("dojo.experimental");
dojo.require("dojo.Deferred");
dojo.require("dojo.lang.declare");
dojo.require("dojo.json");
dojo.require("dojo.io.*");
dojo.experimental("dojo.data.core.RemoteStore");
dojo.lang.declare("dojo.data.core.RemoteStore", [dojo.data.core.Read, dojo.data.core.Write], {_datatypeMap:{}, _jsonRegistry:dojo.json.jsonRegistry, initializer:function (kwArgs) {
if (!kwArgs) {
kwArgs = {};
}
this._serverQueryUrl = kwArgs.queryUrl || "";
this._serverSaveUrl = kwArgs.saveUrl || "";
this._deleted = {};
this._changed = {};
this._added = {};
this._results = {};
this._data = {};
this._numItems = 0;
}, _setupQueryRequest:function (result, requestKw) {
result.query = result.query || "";
requestKw.url = this._serverQueryUrl + encodeURIComponent(result.query);
requestKw.method = "get";
requestKw.mimetype = "text/json";
}, _resultToQueryMetadata:function (serverResponseData) {
return serverResponseData;
}, _resultToQueryData:function (serverResponseData) {
return serverResponseData.data;
}, _remoteToLocalValues:function (attributes) {
for (var key in attributes) {
var values = attributes[key];
for (var i = 0; i < values.length; i++) {
var value = values[i];
var type = value.datatype || value.type;
if (type) {
var localValue = value.value;
if (this._datatypeMap[type]) {
localValue = this._datatypeMap[type](value);
}
values[i] = localValue;
}
}
}
return attributes;
}, _queryToQueryKey:function (query) {
if (typeof query == "string") {
return query;
} else {
return dojo.json.serialize(query);
}
}, _assertIsItem:function (item) {
if (!this.isItem(item)) {
throw new Error("dojo.data.RemoteStore: a function was passed an item argument that was not an item");
}
}, get:function (item, attribute, defaultValue) {
var valueArray = this.getValues(item, attribute);
if (valueArray.length == 0) {
return defaultValue;
}
return valueArray[0];
}, getValues:function (item, attribute) {
var itemIdentity = this.getIdentity(item);
this._assertIsItem(itemIdentity);
var changes = this._changed[itemIdentity];
if (changes) {
var newvalues = changes[attribute];
if (newvalues !== undefined) {
return newvalues;
} else {
return [];
}
}
return this._data[itemIdentity][0][attribute];
}, getAttributes:function (item) {
var itemIdentity = this.getIdentity(item);
if (!itemIdentity) {
return undefined;
}
var atts = [];
var attrDict = this._data[itemIdentity][0];
for (var att in attrDict) {
atts.push(att);
}
return atts;
}, hasAttribute:function (item, attribute) {
var valueArray = this.getValues(item, attribute);
return valueArray.length ? true : false;
}, containsValue:function (item, attribute, value) {
var valueArray = this.getValues(item, attribute);
for (var i = 0; i < valueArray.length; i++) {
if (valueArray[i] == value) {
return true;
}
}
return false;
}, isItem:function (something) {
if (!something) {
return false;
}
var itemIdentity = something;
if (this._deleted[itemIdentity]) {
return false;
}
if (this._data[itemIdentity]) {
return true;
}
if (this._added[itemIdentity]) {
return true;
}
return false;
}, find:function (keywordArgs) {
var result = null;
if (keywordArgs instanceof dojo.data.core.Result) {
result = keywordArgs;
result.store = this;
} else {
result = new dojo.data.core.Result(keywordArgs, this);
}
var query = result.query;
var self = this;
var bindfunc = function (type, data, evt) {
var scope = result.scope || dj_global;
if (type == "load") {
result.resultMetadata = self._resultToQueryMetadata(data);
var dataDict = self._resultToQueryData(data);
if (result.onbegin) {
result.onbegin.call(scope, result);
}
var count = 0;
var resultData = [];
var newItemCount = 0;
for (var key in dataDict) {
if (result._aborted) {
break;
}
if (!self._deleted[key]) {
var values = dataDict[key];
var attributeDict = self._remoteToLocalValues(values);
var existingValue = self._data[key];
var refCount = 1;
if (existingValue) {
refCount = ++existingValue[1];
} else {
newItemCount++;
}
self._data[key] = [attributeDict, refCount];
resultData.push(key);
count++;
if (result.onnext) {
result.onnext.call(scope, key, result);
}
}
}
self._results[self._queryToQueryKey(query)] = resultData;
self._numItems += newItemCount;
result.length = count;
if (result.saveResult) {
result.items = resultData;
}
if (!result._aborted && result.oncompleted) {
result.oncompleted.call(scope, result);
}
} else {
if (type == "error" || type == "timeout") {
dojo.debug("find error: " + dojo.json.serialize(data));
if (result.onerror) {
result.onerror.call(scope, data);
}
}
}
};
var bindKw = keywordArgs.bindArgs || {};
bindKw.sync = result.sync;
bindKw.handle = bindfunc;
this._setupQueryRequest(result, bindKw);
var request = dojo.io.bind(bindKw);
result._abortFunc = request.abort;
return result;
}, getIdentity:function (item) {
if (!this.isItem(item)) {
return null;
}
return (item.id ? item.id : item);
}, newItem:function (attributes, keywordArgs) {
var itemIdentity = keywordArgs["identity"];
if (this._deleted[itemIdentity]) {
delete this._deleted[itemIdentity];
} else {
this._added[itemIdentity] = 1;
}
if (attributes) {
for (var attribute in attributes) {
var valueOrArrayOfValues = attributes[attribute];
if (dojo.lang.isArray(valueOrArrayOfValues)) {
this.setValues(itemIdentity, attribute, valueOrArrayOfValues);
} else {
this.set(itemIdentity, attribute, valueOrArrayOfValues);
}
}
}
return {id:itemIdentity};
}, deleteItem:function (item) {
var identity = this.getIdentity(item);
if (!identity) {
return false;
}
if (this._added[identity]) {
delete this._added[identity];
} else {
this._deleted[identity] = 1;
}
if (this._changed[identity]) {
delete this._changed[identity];
}
return true;
}, setValues:function (item, attribute, values) {
var identity = this.getIdentity(item);
if (!identity) {
return undefined;
}
var changes = this._changed[identity];
if (!changes) {
changes = {};
this._changed[identity] = changes;
}
changes[attribute] = values;
return true;
}, set:function (item, attribute, value) {
return this.setValues(item, attribute, [value]);
}, unsetAttribute:function (item, attribute) {
return this.setValues(item, attribute, []);
}, _initChanges:function () {
this._deleted = {};
this._changed = {};
this._added = {};
}, _setupSaveRequest:function (saveKeywordArgs, requestKw) {
requestKw.url = this._serverSaveUrl;
requestKw.method = "post";
requestKw.mimetype = "text/plain";
var deleted = [];
for (var key in this._deleted) {
deleted.push(key);
}
var saveStruct = {"changed":this._changed, "deleted":deleted};
var oldRegistry = dojo.json.jsonRegistry;
dojo.json.jsonRegistry = this._jsonRegistry;
var jsonString = dojo.json.serialize(saveStruct);
dojo.json.jsonRegistry = oldRegistry;
requestKw.postContent = jsonString;
}, save:function (keywordArgs) {
keywordArgs = keywordArgs || {};
var result = new dojo.Deferred();
var self = this;
var bindfunc = function (type, data, evt) {
if (type == "load") {
if (result.fired == 1) {
return;
}
var key = null;
for (key in self._added) {
if (!self._data[key]) {
self._data[key] = [{}, 1];
}
}
for (key in self._changed) {
var existing = self._data[key];
var changes = self._changed[key];
if (existing) {
existing[0] = changes;
} else {
self._data[key] = [changes, 1];
}
}
for (key in self._deleted) {
if (self._data[key]) {
delete self._data[key];
}
}
self._initChanges();
result.callback(true);
} else {
if (type == "error" || type == "timeout") {
result.errback(data);
}
}
};
var bindKw = {sync:keywordArgs["sync"], handle:bindfunc};
this._setupSaveRequest(keywordArgs, bindKw);
var request = dojo.io.bind(bindKw);
result.canceller = function (deferred) {
request.abort();
};
return result;
}, revert:function () {
this._initChanges();
return true;
}, isDirty:function (item) {
if (item) {
var identity = item.id || item;
return this._deleted[identity] || this._changed[identity];
} else {
var key = null;
for (key in this._changed) {
return true;
}
for (key in this._deleted) {
return true;
}
for (key in this._added) {
return true;
}
return false;
}
}, createReference:function (idstring) {
return {id:idstring};
}, getSize:function () {
return this._numItems;
}, forgetResults:function (query) {
var queryKey = this._queryToQueryKey(query);
var results = this._results[queryKey];
if (!results) {
return false;
}
var removed = 0;
for (var i = 0; i < results.length; i++) {
var key = results[i];
var existingValue = this._data[key];
if (existingValue[1] <= 1) {
delete this._data[key];
removed++;
} else {
existingValue[1] = --existingValue[1];
}
}
delete this._results[queryKey];
this._numItems -= removed;
return true;
}});
@@ -0,0 +1,34 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.core.Result");
dojo.require("dojo.lang.declare");
dojo.require("dojo.experimental");
dojo.experimental("dojo.data.core.Result");
dojo.declare("dojo.data.core.Result", null, {initializer:function (keywordArgs, store) {
this.fromKwArgs(keywordArgs || {});
this.items = null;
this.resultMetadata = null;
this.length = -1;
this.store = store;
this._aborted = false;
this._abortFunc = null;
}, sync:true, abort:function () {
this._aborted = true;
if (this._abortFunc) {
this._abortFunc();
}
}, fromKwArgs:function (kwArgs) {
if (typeof kwArgs.saveResult == "undefined") {
this.saveResult = kwArgs.onnext ? false : true;
}
dojo.lang.mixin(this, kwArgs);
}});
@@ -0,0 +1,42 @@
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.core.Write");
dojo.require("dojo.data.core.Read");
dojo.require("dojo.lang.declare");
dojo.require("dojo.experimental");
dojo.experimental("dojo.data.core.Write");
dojo.declare("dojo.data.core.Write", dojo.data.core.Read, {newItem:function (keywordArgs) {
var newItem;
dojo.unimplemented("dojo.data.core.Write.newItem");
return newItem;
}, deleteItem:function (item) {
dojo.unimplemented("dojo.data.core.Write.deleteItem");
return false;
}, set:function (item, attribute, value) {
dojo.unimplemented("dojo.data.core.Write.set");
return false;
}, setValues:function (item, attribute, values) {
dojo.unimplemented("dojo.data.core.Write.setValues");
return false;
}, unsetAttribute:function (item, attribute) {
dojo.unimplemented("dojo.data.core.Write.clear");
return false;
}, save:function () {
dojo.unimplemented("dojo.data.core.Write.save");
return false;
}, revert:function () {
dojo.unimplemented("dojo.data.core.Write.revert");
return false;
}, isDirty:function (item) {
dojo.unimplemented("dojo.data.core.Write.isDirty");
return false;
}});
@@ -11,52 +11,23 @@
dojo.provide("dojo.data.old.Attribute");
dojo.require("dojo.data.old.Item");
dojo.require("dojo.lang.assert");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.Attribute = function(/* dojo.data.old.provider.Base */ dataProvider, /* string */ attributeId) {
/**
* summary:
* An Attribute object represents something like a column in
* a relational database.
*/
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional: true});
dojo.data.old.Attribute = function (dataProvider, attributeId) {
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional:true});
dojo.lang.assertType(attributeId, String);
dojo.data.old.Item.call(this, dataProvider);
this._attributeId = attributeId;
};
dojo.inherits(dojo.data.old.Attribute, dojo.data.old.Item);
// -------------------------------------------------------------------
// Public instance methods
// -------------------------------------------------------------------
dojo.data.old.Attribute.prototype.toString = function() {
return this._attributeId; // string
dojo.data.old.Attribute.prototype.toString = function () {
return this._attributeId;
};
dojo.data.old.Attribute.prototype.getAttributeId = function () {
return this._attributeId;
};
dojo.data.old.Attribute.prototype.getType = function () {
return this.get("type");
};
dojo.data.old.Attribute.prototype.setType = function (type) {
this.set("type", type);
};
dojo.data.old.Attribute.prototype.getAttributeId = function() {
/**
* summary:
* Returns the string token that uniquely identifies this
* attribute within the context of a data provider.
* For a data provider that accesses relational databases,
* typical attributeIds might be tokens like "name", "age",
* "ssn", or "dept_key".
*/
return this._attributeId; // string
};
dojo.data.old.Attribute.prototype.getType = function() {
/**
* summary: Returns the data type of the values of this attribute.
*/
return this.get('type'); // dojo.data.old.Type or null
};
dojo.data.old.Attribute.prototype.setType = function(/* dojo.data.old.Type or null */ type) {
/**
* summary: Sets the data type for this attribute.
*/
this.set('type', type);
};
@@ -13,44 +13,14 @@ dojo.require("dojo.data.old.Observable");
dojo.require("dojo.data.old.Value");
dojo.require("dojo.lang.common");
dojo.require("dojo.lang.assert");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.Item = function(/* dojo.data.old.provider.Base */ dataProvider) {
/**
* summary:
* An Item has attributes and attribute values, sort of like
* a record in a database, or a 'struct' in C. Instances of
* the Item class know how to store and retrieve their
* attribute values.
*/
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional: true});
dojo.data.old.Item = function (dataProvider) {
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional:true});
dojo.data.old.Observable.call(this);
this._dataProvider = dataProvider;
this._dictionaryOfAttributeValues = {};
};
dojo.inherits(dojo.data.old.Item, dojo.data.old.Observable);
// -------------------------------------------------------------------
// Public class methods
// -------------------------------------------------------------------
dojo.data.old.Item.compare = function(/* dojo.data.old.Item */ itemOne, /* dojo.data.old.Item */ itemTwo) {
/**
* summary:
* Given two Items to compare, this method returns 0, 1, or -1.
* This method is designed to be used by sorting routines, like
* the JavaScript built-in Array sort() method.
*
* Example:
* <pre>
* var a = dataProvider.newItem("kermit");
* var b = dataProvider.newItem("elmo");
* var c = dataProvider.newItem("grover");
* var array = new Array(a, b, c);
* array.sort(dojo.data.old.Item.compare);
* </pre>
*/
dojo.data.old.Item.compare = function (itemOne, itemTwo) {
dojo.lang.assertType(itemOne, dojo.data.old.Item);
if (!dojo.lang.isOfType(itemTwo, dojo.data.old.Item)) {
return -1;
@@ -62,7 +32,7 @@ dojo.data.old.Item.compare = function(/* dojo.data.old.Item */ itemOne, /* dojo.
var attributeArrayTwo = itemTwo.getAttributes();
if (attributeArrayOne.length != attributeArrayTwo.length) {
if (attributeArrayOne.length > attributeArrayTwo.length) {
return 1;
return 1;
} else {
return -1;
}
@@ -77,7 +47,7 @@ dojo.data.old.Item.compare = function(/* dojo.data.old.Item */ itemOne, /* dojo.
}
if (arrayOfValuesOne.length != arrayOfValuesTwo.length) {
if (arrayOfValuesOne.length > arrayOfValuesTwo.length) {
return 1;
return 1;
} else {
return -1;
}
@@ -92,20 +62,13 @@ dojo.data.old.Item.compare = function(/* dojo.data.old.Item */ itemOne, /* dojo.
}
} else {
if (nameOne > nameTwo) {
return 1;
return 1;
} else {
return -1; // 0, 1, or -1
return -1;
}
}
};
// -------------------------------------------------------------------
// Public instance methods
// -------------------------------------------------------------------
dojo.data.old.Item.prototype.toString = function() {
/**
* Returns a simple string representation of the item.
*/
dojo.data.old.Item.prototype.toString = function () {
var arrayOfStrings = [];
var attributes = this.getAttributes();
for (var i in attributes) {
@@ -115,109 +78,77 @@ dojo.data.old.Item.prototype.toString = function() {
if (arrayOfValues.length == 1) {
valueString = arrayOfValues[0];
} else {
valueString = '[';
valueString += arrayOfValues.join(', ');
valueString += ']';
valueString = "[";
valueString += arrayOfValues.join(", ");
valueString += "]";
}
arrayOfStrings.push(' ' + attribute + ': ' + valueString);
arrayOfStrings.push(" " + attribute + ": " + valueString);
}
var returnString = '{ ';
returnString += arrayOfStrings.join(',\n');
returnString += ' }';
return returnString; // string
var returnString = "{ ";
returnString += arrayOfStrings.join(",\n");
returnString += " }";
return returnString;
};
dojo.data.old.Item.prototype.compare = function(/* dojo.data.old.Item */ otherItem) {
/**
* summary: Compares this Item to another Item, and returns 0, 1, or -1.
*/
return dojo.data.old.Item.compare(this, otherItem); // 0, 1, or -1
dojo.data.old.Item.prototype.compare = function (otherItem) {
return dojo.data.old.Item.compare(this, otherItem);
};
dojo.data.old.Item.prototype.isEqual = function(/* dojo.data.old.Item */ otherItem) {
/**
* summary: Returns true if this Item is equal to the otherItem, or false otherwise.
*/
return (this.compare(otherItem) == 0); // boolean
dojo.data.old.Item.prototype.isEqual = function (otherItem) {
return (this.compare(otherItem) == 0);
};
dojo.data.old.Item.prototype.getName = function() {
return this.get('name');
dojo.data.old.Item.prototype.getName = function () {
return this.get("name");
};
dojo.data.old.Item.prototype.get = function(/* string or dojo.data.old.Attribute */ attributeId) {
/**
* summary: Returns a single literal value, like "foo" or 33.
*/
// dojo.lang.assertType(attributeId, [String, dojo.data.old.Attribute]);
dojo.data.old.Item.prototype.get = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null; // null
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
return literalOrValueOrArray.getValue(); // literal
return literalOrValueOrArray.getValue();
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
var dojoDataValue = literalOrValueOrArray[0];
return dojoDataValue.getValue(); // literal
return dojoDataValue.getValue();
}
return literalOrValueOrArray; // literal
return literalOrValueOrArray;
};
dojo.data.old.Item.prototype.getValue = function(/* string or dojo.data.old.Attribute */ attributeId) {
/**
* summary: Returns a single instance of dojo.data.old.Value.
*/
// dojo.lang.assertType(attributeId, [String, dojo.data.old.Attribute]);
dojo.data.old.Item.prototype.getValue = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null; // null
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
return literalOrValueOrArray; // dojo.data.old.Value
return literalOrValueOrArray;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
var dojoDataValue = literalOrValueOrArray[0];
return dojoDataValue; // dojo.data.old.Value
return dojoDataValue;
}
var literal = literalOrValueOrArray;
dojoDataValue = new dojo.data.old.Value(literal);
this._dictionaryOfAttributeValues[attributeId] = dojoDataValue;
return dojoDataValue; // dojo.data.old.Value
return dojoDataValue;
};
dojo.data.old.Item.prototype.getValues = function(/* string or dojo.data.old.Attribute */ attributeId) {
/**
* summary: Returns an array of dojo.data.old.Value objects.
*/
// dojo.lang.assertType(attributeId, [String, dojo.data.old.Attribute]);
dojo.data.old.Item.prototype.getValues = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null; // null
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
var array = [literalOrValueOrArray];
this._dictionaryOfAttributeValues[attributeId] = array;
return array; // Array
return array;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
return literalOrValueOrArray; // Array
return literalOrValueOrArray;
}
var literal = literalOrValueOrArray;
var dojoDataValue = new dojo.data.old.Value(literal);
array = [dojoDataValue];
this._dictionaryOfAttributeValues[attributeId] = array;
return array; // Array
return array;
};
dojo.data.old.Item.prototype.load = function(/* string or dojo.data.old.Attribute */ attributeId, /* anything */ value) {
/**
* summary:
* Used for loading an attribute value into an item when
* the item is first being loaded into memory from some
* data store (such as a file).
*/
// dojo.lang.assertType(attributeId, [String, dojo.data.old.Attribute]);
dojo.data.old.Item.prototype.load = function (attributeId, value) {
this._dataProvider.registerAttribute(attributeId);
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
@@ -241,40 +172,19 @@ dojo.data.old.Item.prototype.load = function(/* string or dojo.data.old.Attribut
array = [dojoDataValue, value];
this._dictionaryOfAttributeValues[attributeId] = array;
};
dojo.data.old.Item.prototype.set = function(/* string or dojo.data.old.Attribute */ attributeId, /* anything */ value) {
/**
* summary:
* Used for setting an attribute value as a result of a
* user action.
*/
// dojo.lang.assertType(attributeId, [String, dojo.data.old.Attribute]);
dojo.data.old.Item.prototype.set = function (attributeId, value) {
this._dataProvider.registerAttribute(attributeId);
this._dictionaryOfAttributeValues[attributeId] = value;
this._dataProvider.noteChange(this, attributeId, value);
};
dojo.data.old.Item.prototype.setValue = function(/* string or dojo.data.old.Attribute */ attributeId, /* dojo.data.old.Value */ value) {
dojo.data.old.Item.prototype.setValue = function (attributeId, value) {
this.set(attributeId, value);
};
dojo.data.old.Item.prototype.addValue = function(/* string or dojo.data.old.Attribute */ attributeId, /* anything */ value) {
/**
* summary:
* Used for adding an attribute value as a result of a
* user action.
*/
dojo.data.old.Item.prototype.addValue = function (attributeId, value) {
this.load(attributeId, value);
this._dataProvider.noteChange(this, attributeId, value);
};
dojo.data.old.Item.prototype.setValues = function(/* string or dojo.data.old.Attribute */ attributeId, /* Array */ arrayOfValues) {
/**
* summary:
* Used for setting an array of attribute values as a result of a
* user action.
*/
// dojo.lang.assertType(attributeId, [String, dojo.data.old.Attribute]);
dojo.data.old.Item.prototype.setValues = function (attributeId, arrayOfValues) {
dojo.lang.assertType(arrayOfValues, Array);
this._dataProvider.registerAttribute(attributeId);
var finalArray = [];
@@ -288,40 +198,24 @@ dojo.data.old.Item.prototype.setValues = function(/* string or dojo.data.old.Att
this._dataProvider.noteChange(this, attributeId, value);
}
};
dojo.data.old.Item.prototype.getAttributes = function() {
/**
* summary:
* Returns an array containing all of the attributes for which
* this item has attribute values.
*/
dojo.data.old.Item.prototype.getAttributes = function () {
var arrayOfAttributes = [];
for (var key in this._dictionaryOfAttributeValues) {
arrayOfAttributes.push(this._dataProvider.getAttribute(key));
}
return arrayOfAttributes; // Array
return arrayOfAttributes;
};
dojo.data.old.Item.prototype.hasAttribute = function(/* string or dojo.data.old.Attribute */ attributeId) {
/**
* summary: Returns true if the given attribute of the item has been assigned any value.
*/
// dojo.lang.assertType(attributeId, [String, dojo.data.old.Attribute]);
return (attributeId in this._dictionaryOfAttributeValues); // boolean
dojo.data.old.Item.prototype.hasAttribute = function (attributeId) {
return (attributeId in this._dictionaryOfAttributeValues);
};
dojo.data.old.Item.prototype.hasAttributeValue = function(/* string or dojo.data.old.Attribute */ attributeId, /* anything */ value) {
/**
* summary: Returns true if the given attribute of the item has been assigned the given value.
*/
dojo.data.old.Item.prototype.hasAttributeValue = function (attributeId, value) {
var arrayOfValues = this.getValues(attributeId);
for (var i in arrayOfValues) {
var candidateValue = arrayOfValues[i];
if (candidateValue.isEqual(value)) {
return true; // boolean
return true;
}
}
return false; // boolean
return false;
};
@@ -10,19 +10,8 @@
dojo.provide("dojo.data.old.Kind");
dojo.require("dojo.data.old.Item");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.Kind = function(/* dojo.data.old.provider.Base */ dataProvider) {
/**
* summary:
* A Kind represents a kind of item. In the dojo data model
* the item Snoopy might belong to the 'kind' Dog, where in
* a Java program the object Snoopy would belong to the 'class'
* Dog, and in MySQL the record for Snoopy would be in the
* table Dog.
*/
dojo.data.old.Kind = function (dataProvider) {
dojo.data.old.Item.call(this, dataProvider);
};
dojo.inherits(dojo.data.old.Kind, dojo.data.old.Item);
@@ -11,21 +11,9 @@
dojo.provide("dojo.data.old.Observable");
dojo.require("dojo.lang.common");
dojo.require("dojo.lang.assert");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.Observable = function() {
dojo.data.old.Observable = function () {
};
// -------------------------------------------------------------------
// Public instance methods
// -------------------------------------------------------------------
dojo.data.old.Observable.prototype.addObserver = function(/* object */ observer) {
/**
* summary: Registers an object as an observer of this item,
* so that the object will be notified when the item changes.
*/
dojo.data.old.Observable.prototype.addObserver = function (observer) {
dojo.lang.assertType(observer, Object);
dojo.lang.assertType(observer.observedObjectHasChanged, Function);
if (!this._arrayOfObservers) {
@@ -35,12 +23,7 @@ dojo.data.old.Observable.prototype.addObserver = function(/* object */ observer)
this._arrayOfObservers.push(observer);
}
};
dojo.data.old.Observable.prototype.removeObserver = function(/* object */ observer) {
/**
* summary: Removes the observer registration for a previously
* registered object.
*/
dojo.data.old.Observable.prototype.removeObserver = function (observer) {
if (!this._arrayOfObservers) {
return;
}
@@ -49,11 +32,7 @@ dojo.data.old.Observable.prototype.removeObserver = function(/* object */ observ
this._arrayOfObservers.splice(index, 1);
}
};
dojo.data.old.Observable.prototype.getObservers = function() {
/**
* summary: Returns an array with all the observers of this item.
*/
return this._arrayOfObservers; // Array or undefined
dojo.data.old.Observable.prototype.getObservers = function () {
return this._arrayOfObservers;
};
@@ -11,19 +11,9 @@
dojo.provide("dojo.data.old.ResultSet");
dojo.require("dojo.lang.assert");
dojo.require("dojo.collections.Collections");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.ResultSet = function(/* dojo.data.old.provider.Base */ dataProvider, /* Array */ arrayOfItems) {
/**
* summary:
* A ResultSet holds a collection of Items. A data provider
* returns a ResultSet in reponse to a query.
* (The name "Result Set" comes from the MySQL terminology.)
*/
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional: true});
dojo.lang.assertType(arrayOfItems, Array, {optional: true});
dojo.data.old.ResultSet = function (dataProvider, arrayOfItems) {
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional:true});
dojo.lang.assertType(arrayOfItems, Array, {optional:true});
dojo.data.old.Observable.call(this);
this._dataProvider = dataProvider;
this._arrayOfItems = [];
@@ -32,39 +22,29 @@ dojo.data.old.ResultSet = function(/* dojo.data.old.provider.Base */ dataProvide
}
};
dojo.inherits(dojo.data.old.ResultSet, dojo.data.old.Observable);
// -------------------------------------------------------------------
// Public instance methods
// -------------------------------------------------------------------
dojo.data.old.ResultSet.prototype.toString = function() {
var returnString = this._arrayOfItems.join(', ');
return returnString; // string
dojo.data.old.ResultSet.prototype.toString = function () {
var returnString = this._arrayOfItems.join(", ");
return returnString;
};
dojo.data.old.ResultSet.prototype.toArray = function() {
return this._arrayOfItems; // Array
dojo.data.old.ResultSet.prototype.toArray = function () {
return this._arrayOfItems;
};
dojo.data.old.ResultSet.prototype.getIterator = function() {
dojo.data.old.ResultSet.prototype.getIterator = function () {
return new dojo.collections.Iterator(this._arrayOfItems);
};
dojo.data.old.ResultSet.prototype.getLength = function() {
return this._arrayOfItems.length; // integer
dojo.data.old.ResultSet.prototype.getLength = function () {
return this._arrayOfItems.length;
};
dojo.data.old.ResultSet.prototype.getItemAt = function(/* numeric */ index) {
dojo.data.old.ResultSet.prototype.getItemAt = function (index) {
return this._arrayOfItems[index];
};
dojo.data.old.ResultSet.prototype.indexOf = function(/* dojo.data.old.Item */ item) {
return dojo.lang.indexOf(this._arrayOfItems, item); // integer
dojo.data.old.ResultSet.prototype.indexOf = function (item) {
return dojo.lang.indexOf(this._arrayOfItems, item);
};
dojo.data.old.ResultSet.prototype.contains = function (item) {
return dojo.lang.inArray(this._arrayOfItems, item);
};
dojo.data.old.ResultSet.prototype.getDataProvider = function () {
return this._dataProvider;
};
dojo.data.old.ResultSet.prototype.contains = function(/* dojo.data.old.Item */ item) {
return dojo.lang.inArray(this._arrayOfItems, item); // boolean
};
dojo.data.old.ResultSet.prototype.getDataProvider = function() {
return this._dataProvider; // dojo.data.old.provider.Base
};
@@ -10,16 +10,8 @@
dojo.provide("dojo.data.old.Type");
dojo.require("dojo.data.old.Item");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.Type = function(/* dojo.data.old.provider.Base */ dataProvider) {
/**
* summary:
* A Type represents a type of value, like Text, Number, Picture,
* or Varchar.
*/
dojo.data.old.Type = function (dataProvider) {
dojo.data.old.Item.call(this, dataProvider);
};
dojo.inherits(dojo.data.old.Type, dojo.data.old.Item);
@@ -10,46 +10,24 @@
dojo.provide("dojo.data.old.Value");
dojo.require("dojo.lang.assert");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.Value = function(/* anything */ value) {
/**
* summary:
* A Value represents a simple literal value (like "foo" or 334),
* or a reference value (a pointer to an Item).
*/
dojo.data.old.Value = function (value) {
this._value = value;
this._type = null;
};
// -------------------------------------------------------------------
// Public instance methods
// -------------------------------------------------------------------
dojo.data.old.Value.prototype.toString = function() {
return this._value.toString(); // string
dojo.data.old.Value.prototype.toString = function () {
return this._value.toString();
};
dojo.data.old.Value.prototype.getValue = function () {
return this._value;
};
dojo.data.old.Value.prototype.getType = function () {
dojo.unimplemented("dojo.data.old.Value.prototype.getType");
return this._type;
};
dojo.data.old.Value.prototype.compare = function () {
dojo.unimplemented("dojo.data.old.Value.prototype.compare");
};
dojo.data.old.Value.prototype.isEqual = function () {
dojo.unimplemented("dojo.data.old.Value.prototype.isEqual");
};
dojo.data.old.Value.prototype.getValue = function() {
/**
* summary: Returns the value itself.
*/
return this._value; // anything
};
dojo.data.old.Value.prototype.getType = function() {
/**
* summary: Returns the data type of the value.
*/
dojo.unimplemented('dojo.data.old.Value.prototype.getType');
return this._type; // dojo.data.old.Type
};
dojo.data.old.Value.prototype.compare = function() {
dojo.unimplemented('dojo.data.old.Value.prototype.compare');
};
dojo.data.old.Value.prototype.isEqual = function() {
dojo.unimplemented('dojo.data.old.Value.prototype.isEqual');
};
@@ -9,14 +9,7 @@
*/
dojo.require("dojo.experimental");
dojo.experimental("dojo.data.old.*");
dojo.kwCompoundRequire({
common: [
"dojo.data.old.Item",
"dojo.data.old.ResultSet",
"dojo.data.old.provider.FlatFile"
]
});
dojo.kwCompoundRequire({common:["dojo.data.old.Item", "dojo.data.old.ResultSet", "dojo.data.old.provider.FlatFile"]});
dojo.provide("dojo.data.old.*");
@@ -10,70 +10,39 @@
dojo.provide("dojo.data.old.format.Csv");
dojo.require("dojo.lang.assert");
dojo.data.old.format.Csv = new function() {
// -------------------------------------------------------------------
// Public functions
// -------------------------------------------------------------------
this.getArrayStructureFromCsvFileContents = function(/* string */ csvFileContents) {
/**
* Given a string containing CSV records, this method parses
* the string and returns a data structure containing the parsed
* content. The data structure we return is an array of length
* R, where R is the number of rows (lines) in the CSV data. The
* return array contains one sub-array for each CSV line, and each
* sub-array contains C string values, where C is the number of
* columns in the CSV data.
*
* For example, given this CSV string as input:
* <pre>
* "Title, Year, Producer \n Alien, 1979, Ridley Scott \n Blade Runner, 1982, Ridley Scott"
* </pre>
* We will return this data structure:
* <pre>
* [["Title", "Year", "Producer"]
* ["Alien", "1979", "Ridley Scott"],
* ["Blade Runner", "1982", "Ridley Scott"]]
* </pre>
*/
dojo.data.old.format.Csv = new function () {
this.getArrayStructureFromCsvFileContents = function (csvFileContents) {
dojo.lang.assertType(csvFileContents, String);
var lineEndingCharacters = new RegExp("\r\n|\n|\r");
var leadingWhiteSpaceCharacters = new RegExp("^\\s+",'g');
var trailingWhiteSpaceCharacters = new RegExp("\\s+$",'g');
var doubleQuotes = new RegExp('""','g');
var leadingWhiteSpaceCharacters = new RegExp("^\\s+", "g");
var trailingWhiteSpaceCharacters = new RegExp("\\s+$", "g");
var doubleQuotes = new RegExp("\"\"", "g");
var arrayOfOutputRecords = [];
var arrayOfInputLines = csvFileContents.split(lineEndingCharacters);
for (var i in arrayOfInputLines) {
var singleLine = arrayOfInputLines[i];
if (singleLine.length > 0) {
var listOfFields = singleLine.split(',');
var listOfFields = singleLine.split(",");
var j = 0;
while (j < listOfFields.length) {
var space_field_space = listOfFields[j];
var field_space = space_field_space.replace(leadingWhiteSpaceCharacters, ''); // trim leading whitespace
var field = field_space.replace(trailingWhiteSpaceCharacters, ''); // trim trailing whitespace
var field_space = space_field_space.replace(leadingWhiteSpaceCharacters, "");
var field = field_space.replace(trailingWhiteSpaceCharacters, "");
var firstChar = field.charAt(0);
var lastChar = field.charAt(field.length - 1);
var secondToLastChar = field.charAt(field.length - 2);
var thirdToLastChar = field.charAt(field.length - 3);
if ((firstChar == '"') &&
((lastChar != '"') ||
((lastChar == '"') && (secondToLastChar == '"') && (thirdToLastChar != '"')) )) {
if (j+1 === listOfFields.length) {
// alert("The last field in record " + i + " is corrupted:\n" + field);
if ((firstChar == "\"") && ((lastChar != "\"") || ((lastChar == "\"") && (secondToLastChar == "\"") && (thirdToLastChar != "\"")))) {
if (j + 1 === listOfFields.length) {
return null;
}
var nextField = listOfFields[j+1];
listOfFields[j] = field_space + ',' + nextField;
listOfFields.splice(j+1, 1); // delete element [j+1] from the list
var nextField = listOfFields[j + 1];
listOfFields[j] = field_space + "," + nextField;
listOfFields.splice(j + 1, 1);
} else {
if ((firstChar == '"') && (lastChar == '"')) {
field = field.slice(1, (field.length - 1)); // trim the " characters off the ends
field = field.replace(doubleQuotes, '"'); // replace "" with "
if ((firstChar == "\"") && (lastChar == "\"")) {
field = field.slice(1, (field.length - 1));
field = field.replace(doubleQuotes, "\"");
}
listOfFields[j] = field;
j += 1;
@@ -82,10 +51,9 @@ dojo.data.old.format.Csv = new function() {
arrayOfOutputRecords.push(listOfFields);
}
}
return arrayOfOutputRecords; // Array
return arrayOfOutputRecords;
};
this.loadDataProviderFromFileContents = function(/* dojo.data.old.provider.Base */ dataProvider, /* string */ csvFileContents) {
this.loadDataProviderFromFileContents = function (dataProvider, csvFileContents) {
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base);
dojo.lang.assertType(csvFileContents, String);
var arrayOfArrays = this.getArrayStructureFromCsvFileContents(csvFileContents);
@@ -102,11 +70,10 @@ dojo.data.old.format.Csv = new function() {
}
}
};
this.getCsvStringFromResultSet = function(/* dojo.data.old.ResultSet */ resultSet) {
dojo.unimplemented('dojo.data.old.format.Csv.getCsvStringFromResultSet');
this.getCsvStringFromResultSet = function (resultSet) {
dojo.unimplemented("dojo.data.old.format.Csv.getCsvStringFromResultSet");
var csvString = null;
return csvString; // String
return csvString;
};
}();
@@ -10,21 +10,15 @@
dojo.provide("dojo.data.old.format.Json");
dojo.require("dojo.lang.assert");
dojo.data.old.format.Json = new function() {
// -------------------------------------------------------------------
// Public functions
// -------------------------------------------------------------------
this.loadDataProviderFromFileContents = function(/* dojo.data.old.provider.Base */ dataProvider, /* string */ jsonFileContents) {
dojo.data.old.format.Json = new function () {
this.loadDataProviderFromFileContents = function (dataProvider, jsonFileContents) {
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base);
dojo.lang.assertType(jsonFileContents, String);
var arrayOfJsonData = eval("(" + jsonFileContents + ")");
this.loadDataProviderFromArrayOfJsonData(dataProvider, arrayOfJsonData);
};
this.loadDataProviderFromArrayOfJsonData = function(/* dojo.data.old.provider.Base */ dataProvider, /* Array */ arrayOfJsonData) {
dojo.lang.assertType(arrayOfJsonData, Array, {optional: true});
this.loadDataProviderFromArrayOfJsonData = function (dataProvider, arrayOfJsonData) {
dojo.lang.assertType(arrayOfJsonData, Array, {optional:true});
if (arrayOfJsonData && (arrayOfJsonData.length > 0)) {
var firstRow = arrayOfJsonData[0];
dojo.lang.assertType(firstRow, [Array, "pureobject"]);
@@ -36,27 +30,12 @@ dojo.data.old.format.Json = new function() {
}
}
};
this.getJsonStringFromResultSet = function(/* dojo.data.old.ResultSet */ resultSet) {
dojo.unimplemented('dojo.data.old.format.Json.getJsonStringFromResultSet');
this.getJsonStringFromResultSet = function (resultSet) {
dojo.unimplemented("dojo.data.old.format.Json.getJsonStringFromResultSet");
var jsonString = null;
return jsonString; // String
return jsonString;
};
// -------------------------------------------------------------------
// Private functions
// -------------------------------------------------------------------
function _loadDataProviderFromArrayOfArrays(/* dojo.data.old.provider.Base */ dataProvider, /* Array */ arrayOfJsonData) {
/**
* Example:
* var arrayOfJsonStates = [
* [ "abbr", "population", "name" ]
* [ "WA", 5894121, "Washington" ],
* [ "WV", 1808344, "West Virginia" ],
* [ "WI", 5453896, "Wisconsin" ],
* [ "WY", 493782, "Wyoming" ] ];
* this._loadFromArrayOfArrays(arrayOfJsonStates);
*/
function _loadDataProviderFromArrayOfArrays(dataProvider, arrayOfJsonData) {
var arrayOfKeys = arrayOfJsonData[0];
for (var i = 1; i < arrayOfJsonData.length; ++i) {
var row = arrayOfJsonData[i];
@@ -68,18 +47,7 @@ dojo.data.old.format.Json = new function() {
}
}
}
function _loadDataProviderFromArrayOfObjects(/* dojo.data.old.provider.Base */ dataProvider, /* Array */ arrayOfJsonData) {
/**
* Example:
* var arrayOfJsonStates = [
* { abbr: "WA", name: "Washington" },
* { abbr: "WV", name: "West Virginia" },
* { abbr: "WI", name: "Wisconsin", song: "On, Wisconsin!" },
* { abbr: "WY", name: "Wyoming", cities: ["Lander", "Cheyenne", "Laramie"] } ];
* this._loadFromArrayOfArrays(arrayOfJsonStates);
*/
// dojo.debug("_loadDataProviderFromArrayOfObjects");
function _loadDataProviderFromArrayOfObjects(dataProvider, arrayOfJsonData) {
for (var i in arrayOfJsonData) {
var row = arrayOfJsonData[i];
var item = dataProvider.getNewItemToLoad();
@@ -90,7 +58,6 @@ dojo.data.old.format.Json = new function() {
for (var j in arrayOfValues) {
value = arrayOfValues[j];
item.load(key, value);
// dojo.debug("loaded: " + key + " = " + value);
}
} else {
item.load(key, value);
@@ -98,6 +65,5 @@ dojo.data.old.format.Json = new function() {
}
}
}
}();
@@ -10,106 +10,63 @@
dojo.provide("dojo.data.old.provider.Base");
dojo.require("dojo.lang.assert");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.provider.Base = function() {
/**
* summary:
* A Data Provider serves as a connection to some data source,
* like a relational database. This data provider Base class
* serves as an abstract superclass for other data provider
* classes.
*/
dojo.data.old.provider.Base = function () {
this._countOfNestedTransactions = 0;
this._changesInCurrentTransaction = null;
};
// -------------------------------------------------------------------
// Public instance methods
// -------------------------------------------------------------------
dojo.data.old.provider.Base.prototype.beginTransaction = function() {
/**
* Marks the beginning of a transaction.
*
* Each time you call beginTransaction() you open a new transaction,
* which you need to close later using endTransaction(). Transactions
* may be nested, but the beginTransaction and endTransaction calls
* always need to come in pairs.
*/
dojo.data.old.provider.Base.prototype.beginTransaction = function () {
if (this._countOfNestedTransactions === 0) {
this._changesInCurrentTransaction = [];
}
this._countOfNestedTransactions += 1;
};
dojo.data.old.provider.Base.prototype.endTransaction = function() {
/**
* Marks the end of a transaction.
*/
dojo.data.old.provider.Base.prototype.endTransaction = function () {
this._countOfNestedTransactions -= 1;
dojo.lang.assert(this._countOfNestedTransactions >= 0);
if (this._countOfNestedTransactions === 0) {
var listOfChangesMade = this._saveChanges();
this._changesInCurrentTransaction = null;
if (listOfChangesMade.length > 0) {
// dojo.debug("endTransaction: " + listOfChangesMade.length + " changes made");
this._notifyObserversOfChanges(listOfChangesMade);
}
}
};
dojo.data.old.provider.Base.prototype.getNewItemToLoad = function() {
return this._newItem(); // dojo.data.old.Item
dojo.data.old.provider.Base.prototype.getNewItemToLoad = function () {
return this._newItem();
};
dojo.data.old.provider.Base.prototype.newItem = function(/* string */ itemName) {
/**
* Creates a new item.
*/
dojo.lang.assertType(itemName, String, {optional: true});
dojo.data.old.provider.Base.prototype.newItem = function (itemName) {
dojo.lang.assertType(itemName, String, {optional:true});
var item = this._newItem();
if (itemName) {
item.set('name', itemName);
item.set("name", itemName);
}
return item; // dojo.data.old.Item
return item;
};
dojo.data.old.provider.Base.prototype.newAttribute = function(/* string */ attributeId) {
/**
* Creates a new attribute.
*/
dojo.lang.assertType(attributeId, String, {optional: true});
dojo.data.old.provider.Base.prototype.newAttribute = function (attributeId) {
dojo.lang.assertType(attributeId, String, {optional:true});
var attribute = this._newAttribute(attributeId);
return attribute; // dojo.data.old.Attribute
return attribute;
};
dojo.data.old.provider.Base.prototype.getAttribute = function(/* string */ attributeId) {
dojo.unimplemented('dojo.data.old.provider.Base');
dojo.data.old.provider.Base.prototype.getAttribute = function (attributeId) {
dojo.unimplemented("dojo.data.old.provider.Base");
var attribute;
return attribute; // dojo.data.old.Attribute
return attribute;
};
dojo.data.old.provider.Base.prototype.getAttributes = function() {
dojo.unimplemented('dojo.data.old.provider.Base');
return this._arrayOfAttributes; // Array
dojo.data.old.provider.Base.prototype.getAttributes = function () {
dojo.unimplemented("dojo.data.old.provider.Base");
return this._arrayOfAttributes;
};
dojo.data.old.provider.Base.prototype.fetchArray = function() {
dojo.unimplemented('dojo.data.old.provider.Base');
return []; // Array
dojo.data.old.provider.Base.prototype.fetchArray = function () {
dojo.unimplemented("dojo.data.old.provider.Base");
return [];
};
dojo.data.old.provider.Base.prototype.fetchResultSet = function() {
dojo.unimplemented('dojo.data.old.provider.Base');
dojo.data.old.provider.Base.prototype.fetchResultSet = function () {
dojo.unimplemented("dojo.data.old.provider.Base");
var resultSet;
return resultSet; // dojo.data.old.ResultSet
return resultSet;
};
dojo.data.old.provider.Base.prototype.noteChange = function(/* dojo.data.old.Item */ item, /* string or dojo.data.old.Attribute */ attribute, /* anything */ value) {
var change = {item: item, attribute: attribute, value: value};
dojo.data.old.provider.Base.prototype.noteChange = function (item, attribute, value) {
var change = {item:item, attribute:attribute, value:value};
if (this._countOfNestedTransactions === 0) {
this.beginTransaction();
this._changesInCurrentTransaction.push(change);
@@ -118,44 +75,27 @@ dojo.data.old.provider.Base.prototype.noteChange = function(/* dojo.data.old.Ite
this._changesInCurrentTransaction.push(change);
}
};
dojo.data.old.provider.Base.prototype.addItemObserver = function(/* dojo.data.old.Item */ item, /* object */ observer) {
/**
* summary: Registers an object as an observer of an item,
* so that the object will be notified when the item changes.
*/
dojo.data.old.provider.Base.prototype.addItemObserver = function (item, observer) {
dojo.lang.assertType(item, dojo.data.old.Item);
item.addObserver(observer);
};
dojo.data.old.provider.Base.prototype.removeItemObserver = function(/* dojo.data.old.Item */ item, /* object */ observer) {
/**
* summary: Removes the observer registration for a previously
* registered object.
*/
dojo.data.old.provider.Base.prototype.removeItemObserver = function (item, observer) {
dojo.lang.assertType(item, dojo.data.old.Item);
item.removeObserver(observer);
};
// -------------------------------------------------------------------
// Private instance methods
// -------------------------------------------------------------------
dojo.data.old.provider.Base.prototype._newItem = function() {
dojo.data.old.provider.Base.prototype._newItem = function () {
var item = new dojo.data.old.Item(this);
return item; // dojo.data.old.Item
return item;
};
dojo.data.old.provider.Base.prototype._newAttribute = function(/* String */ attributeId) {
dojo.data.old.provider.Base.prototype._newAttribute = function (attributeId) {
var attribute = new dojo.data.old.Attribute(this);
return attribute; // dojo.data.old.Attribute
return attribute;
};
dojo.data.old.provider.Base.prototype._saveChanges = function() {
dojo.data.old.provider.Base.prototype._saveChanges = function () {
var arrayOfChangesMade = this._changesInCurrentTransaction;
return arrayOfChangesMade; // Array
return arrayOfChangesMade;
};
dojo.data.old.provider.Base.prototype._notifyObserversOfChanges = function(/* Array */ arrayOfChanges) {
dojo.data.old.provider.Base.prototype._notifyObserversOfChanges = function (arrayOfChanges) {
var arrayOfResultSets = this._getResultSets();
for (var i in arrayOfChanges) {
var change = arrayOfChanges[i];
@@ -175,9 +115,8 @@ dojo.data.old.provider.Base.prototype._notifyObserversOfChanges = function(/* Ar
}
}
};
dojo.data.old.provider.Base.prototype._getResultSets = function() {
dojo.unimplemented('dojo.data.old.provider.Base');
return []; // Array
dojo.data.old.provider.Base.prototype._getResultSets = function () {
dojo.unimplemented("dojo.data.old.provider.Base");
return [];
};
@@ -11,75 +11,21 @@
dojo.provide("dojo.data.old.provider.Delicious");
dojo.require("dojo.data.old.provider.FlatFile");
dojo.require("dojo.data.old.format.Json");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.provider.Delicious = function() {
/**
* summary:
* The Delicious Data Provider can be used to take data from
* del.icio.us and make it available as dojo.data.old.Items
* In order to use the Delicious Data Provider, you need
* to have loaded a script tag that looks like this:
* <script type="text/javascript" src="http://del.icio.us/feeds/json/gumption?count=8"></script>
*/
dojo.data.old.provider.Delicious = function () {
dojo.data.old.provider.FlatFile.call(this);
// Delicious = null;
if (Delicious && Delicious.posts) {
dojo.data.old.format.Json.loadDataProviderFromArrayOfJsonData(this, Delicious.posts);
} else {
// document.write("<script type='text/javascript'>dojo.data.old.provider.Delicious._fetchComplete()</script>");
/*
document.write("<script type='text/javascript'>alert('boo!');</script>");
document.write("<script type='text/javascript'>var foo = 'not dojo'; alert('dojo == ' + foo);</script>");
document.write("<script type='text/javascript'>var foo = fetchComplete; alert('dojo == ' + foo);</script>");
fetchComplete();
*/
// dojo.debug("Delicious line 29: constructor");
}
var u = this.registerAttribute('u');
var d = this.registerAttribute('d');
var t = this.registerAttribute('t');
u.load('name', 'Bookmark');
d.load('name', 'Description');
t.load('name', 'Tags');
u.load('type', 'String');
d.load('type', 'String');
t.load('type', 'String');
var u = this.registerAttribute("u");
var d = this.registerAttribute("d");
var t = this.registerAttribute("t");
u.load("name", "Bookmark");
d.load("name", "Description");
t.load("name", "Tags");
u.load("type", "String");
d.load("type", "String");
t.load("type", "String");
};
dojo.inherits(dojo.data.old.provider.Delicious, dojo.data.old.provider.FlatFile);
/********************************************************************
* FIXME: the rest of this is work in progress
*
dojo.data.old.provider.Delicious.prototype.getNewItemToLoad = function() {
var newItem = this._newItem();
this._currentArray.push(newItem);
return newItem; // dojo.data.old.Item
};
dojo.data.old.provider.Delicious.prototype.fetchArray = function(query) {
if (!query) {
query = "gumption";
}
this._currentArray = [];
alert("Delicious line 60: loadDataProviderFromArrayOfJsonData");
alert("Delicious line 61: " + dojo);
var sourceUrl = "http://del.icio.us/feeds/json/" + query + "?count=8";
document.write("<script type='text/javascript' src='" + sourceUrl + "'></script>");
document.write("<script type='text/javascript'>alert('line 63: ' + Delicious.posts[0].u);</script>");
document.write("<script type='text/javascript'>callMe();</script>");
alert("line 66");
dojo.data.old.format.Json.loadDataProviderFromArrayOfJsonData(this, Delicious.posts);
return this._currentArray; // Array
};
callMe = function() {
alert("callMe!");
};
*/
@@ -16,26 +16,16 @@ dojo.require("dojo.data.old.ResultSet");
dojo.require("dojo.data.old.format.Json");
dojo.require("dojo.data.old.format.Csv");
dojo.require("dojo.lang.assert");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.provider.FlatFile = function(/* keywords */ keywordParameters) {
/**
* summary:
* A Json Data Provider knows how to read in simple JSON data
* tables and make their contents accessable as Items.
*/
dojo.lang.assertType(keywordParameters, "pureobject", {optional: true});
dojo.data.old.provider.FlatFile = function (keywordParameters) {
dojo.lang.assertType(keywordParameters, "pureobject", {optional:true});
dojo.data.old.provider.Base.call(this);
this._arrayOfItems = [];
this._resultSet = null;
this._dictionaryOfAttributes = {};
if (keywordParameters) {
var jsonObjects = keywordParameters["jsonObjects"];
var jsonString = keywordParameters["jsonString"];
var fileUrl = keywordParameters["url"];
var jsonString = keywordParameters["jsonString"];
var fileUrl = keywordParameters["url"];
if (jsonObjects) {
dojo.data.old.format.Json.loadDataProviderFromArrayOfJsonData(this, jsonObjects);
}
@@ -43,7 +33,7 @@ dojo.data.old.provider.FlatFile = function(/* keywords */ keywordParameters) {
dojo.data.old.format.Json.loadDataProviderFromFileContents(this, jsonString);
}
if (fileUrl) {
var arrayOfParts = fileUrl.split('.');
var arrayOfParts = fileUrl.split(".");
var lastPart = arrayOfParts[(arrayOfParts.length - 1)];
var formatParser = null;
if (lastPart == "json") {
@@ -62,25 +52,10 @@ dojo.data.old.provider.FlatFile = function(/* keywords */ keywordParameters) {
}
};
dojo.inherits(dojo.data.old.provider.FlatFile, dojo.data.old.provider.Base);
// -------------------------------------------------------------------
// Public instance methods
// -------------------------------------------------------------------
dojo.data.old.provider.FlatFile.prototype.getProviderCapabilities = function(/* string */ keyword) {
dojo.lang.assertType(keyword, String, {optional: true});
dojo.data.old.provider.FlatFile.prototype.getProviderCapabilities = function (keyword) {
dojo.lang.assertType(keyword, String, {optional:true});
if (!this._ourCapabilities) {
this._ourCapabilities = {
transactions: false,
undo: false,
login: false,
versioning: false,
anonymousRead: true,
anonymousWrite: false,
permissions: false,
queries: false,
strongTyping: false,
datatypes: [String, Date, Number]
};
this._ourCapabilities = {transactions:false, undo:false, login:false, versioning:false, anonymousRead:true, anonymousWrite:false, permissions:false, queries:false, strongTyping:false, datatypes:[String, Date, Number]};
}
if (keyword) {
return this._ourCapabilities[keyword];
@@ -88,66 +63,49 @@ dojo.data.old.provider.FlatFile.prototype.getProviderCapabilities = function(/*
return this._ourCapabilities;
}
};
dojo.data.old.provider.FlatFile.prototype.registerAttribute = function(/* string or dojo.data.old.Attribute */ attributeId) {
dojo.data.old.provider.FlatFile.prototype.registerAttribute = function (attributeId) {
var registeredAttribute = this.getAttribute(attributeId);
if (!registeredAttribute) {
var newAttribute = new dojo.data.old.Attribute(this, attributeId);
this._dictionaryOfAttributes[attributeId] = newAttribute;
registeredAttribute = newAttribute;
}
return registeredAttribute; // dojo.data.old.Attribute
return registeredAttribute;
};
dojo.data.old.provider.FlatFile.prototype.getAttribute = function(/* string or dojo.data.old.Attribute */ attributeId) {
dojo.data.old.provider.FlatFile.prototype.getAttribute = function (attributeId) {
var attribute = (this._dictionaryOfAttributes[attributeId] || null);
return attribute; // dojo.data.old.Attribute or null
return attribute;
};
dojo.data.old.provider.FlatFile.prototype.getAttributes = function() {
dojo.data.old.provider.FlatFile.prototype.getAttributes = function () {
var arrayOfAttributes = [];
for (var key in this._dictionaryOfAttributes) {
var attribute = this._dictionaryOfAttributes[key];
arrayOfAttributes.push(attribute);
}
return arrayOfAttributes; // Array
return arrayOfAttributes;
};
dojo.data.old.provider.FlatFile.prototype.fetchArray = function(query) {
/**
* summary: Returns an Array containing all of the Items.
*/
return this._arrayOfItems; // Array
dojo.data.old.provider.FlatFile.prototype.fetchArray = function (query) {
return this._arrayOfItems;
};
dojo.data.old.provider.FlatFile.prototype.fetchResultSet = function(query) {
/**
* summary: Returns a ResultSet containing all of the Items.
*/
dojo.data.old.provider.FlatFile.prototype.fetchResultSet = function (query) {
if (!this._resultSet) {
this._resultSet = new dojo.data.old.ResultSet(this, this.fetchArray(query));
}
return this._resultSet; // dojo.data.old.ResultSet
return this._resultSet;
};
// -------------------------------------------------------------------
// Private instance methods
// -------------------------------------------------------------------
dojo.data.old.provider.FlatFile.prototype._newItem = function() {
dojo.data.old.provider.FlatFile.prototype._newItem = function () {
var item = new dojo.data.old.Item(this);
this._arrayOfItems.push(item);
return item; // dojo.data.old.Item
return item;
};
dojo.data.old.provider.FlatFile.prototype._newAttribute = function(/* String */ attributeId) {
dojo.data.old.provider.FlatFile.prototype._newAttribute = function (attributeId) {
dojo.lang.assertType(attributeId, String);
dojo.lang.assert(this.getAttribute(attributeId) === null);
var attribute = new dojo.data.old.Attribute(this, attributeId);
this._dictionaryOfAttributes[attributeId] = attribute;
return attribute; // dojo.data.old.Attribute
};
dojo.data.old.provider.Base.prototype._getResultSets = function() {
return [this._resultSet]; // Array
return attribute;
};
dojo.data.old.provider.Base.prototype._getResultSets = function () {
return [this._resultSet];
};
@@ -10,18 +10,8 @@
dojo.provide("dojo.data.old.provider.JotSpot");
dojo.require("dojo.data.old.provider.Base");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.provider.JotSpot = function() {
/**
* summary:
* A JotSpot Data Provider knows how to read data from a JotSpot data
* store and make the contents accessable as dojo.data.old.Items.
*/
dojo.unimplemented('dojo.data.old.provider.JotSpot');
dojo.data.old.provider.JotSpot = function () {
dojo.unimplemented("dojo.data.old.provider.JotSpot");
};
dojo.inherits(dojo.data.old.provider.JotSpot, dojo.data.old.provider.Base);
@@ -10,18 +10,8 @@
dojo.provide("dojo.data.old.provider.MySql");
dojo.require("dojo.data.old.provider.Base");
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
dojo.data.old.provider.MySql = function() {
/**
* summary:
* A MySql Data Provider knows how to connect to a MySQL database
* on a server and and make the content records available as
* dojo.data.old.Items.
*/
dojo.unimplemented('dojo.data.old.provider.MySql');
dojo.data.old.provider.MySql = function () {
dojo.unimplemented("dojo.data.old.provider.MySql");
};
dojo.inherits(dojo.data.old.provider.MySql, dojo.data.old.provider.Base);
@@ -9,5 +9,5 @@
*/
dojo.provide("dojo.date");
dojo.deprecated("dojo.date", "use one of the modules in dojo.date.* instead", "0.5");
@@ -9,488 +9,306 @@
*/
dojo.provide("dojo.date.common");
/* Supplementary Date Functions
*******************************/
dojo.date.setDayOfYear = function(/*Date*/dateObject, /*Number*/dayOfYear){
// summary: sets dateObject according to day of the year (1..366)
dojo.date.setDayOfYear = function (dateObject, dayOfYear) {
dateObject.setMonth(0);
dateObject.setDate(dayOfYear);
return dateObject; // Date
}
dojo.date.getDayOfYear = function(/*Date*/dateObject){
// summary: gets the day of the year as represented by dateObject
return dateObject;
};
dojo.date.getDayOfYear = function (dateObject) {
var fullYear = dateObject.getFullYear();
var lastDayOfPrevYear = new Date(fullYear-1, 11, 31);
return Math.floor((dateObject.getTime() -
lastDayOfPrevYear.getTime()) / 86400000); // Number
}
dojo.date.setWeekOfYear = function(/*Date*/dateObject, /*Number*/week, /*Number*/firstDay){
if(arguments.length == 1){ firstDay = 0; } // Sunday
var lastDayOfPrevYear = new Date(fullYear - 1, 11, 31);
return Math.floor((dateObject.getTime() - lastDayOfPrevYear.getTime()) / 86400000);
};
dojo.date.setWeekOfYear = function (dateObject, week, firstDay) {
if (arguments.length == 1) {
firstDay = 0;
}
dojo.unimplemented("dojo.date.setWeekOfYear");
}
dojo.date.getWeekOfYear = function(/*Date*/dateObject, /*Number*/firstDay){
if(arguments.length == 1){ firstDay = 0; } // Sunday
// work out the first day of the year corresponding to the week
};
dojo.date.getWeekOfYear = function (dateObject, firstDay) {
if (arguments.length == 1) {
firstDay = 0;
}
var firstDayOfYear = new Date(dateObject.getFullYear(), 0, 1);
var day = firstDayOfYear.getDay();
firstDayOfYear.setDate(firstDayOfYear.getDate() -
day + firstDay - (day > firstDay ? 7 : 0));
return Math.floor((dateObject.getTime() -
firstDayOfYear.getTime()) / 604800000);
}
dojo.date.setIsoWeekOfYear = function(/*Date*/dateObject, /*Number*/week, /*Number*/firstDay){
// summary: unimplemented
if (arguments.length == 1) { firstDay = 1; } // Monday
firstDayOfYear.setDate(firstDayOfYear.getDate() - day + firstDay - (day > firstDay ? 7 : 0));
return Math.floor((dateObject.getTime() - firstDayOfYear.getTime()) / 604800000);
};
dojo.date.setIsoWeekOfYear = function (dateObject, week, firstDay) {
if (arguments.length == 1) {
firstDay = 1;
}
dojo.unimplemented("dojo.date.setIsoWeekOfYear");
}
dojo.date.getIsoWeekOfYear = function(/*Date*/dateObject, /*Number*/firstDay) {
// summary: unimplemented
if (arguments.length == 1) { firstDay = 1; } // Monday
};
dojo.date.getIsoWeekOfYear = function (dateObject, firstDay) {
if (arguments.length == 1) {
firstDay = 1;
}
dojo.unimplemented("dojo.date.getIsoWeekOfYear");
}
/* Informational Functions
**************************/
//DEPRECATED: These timezone arrays will be deprecated in 0.5
dojo.date.shortTimezones = ["IDLW", "BET", "HST", "MART", "AKST", "PST", "MST",
"CST", "EST", "AST", "NFT", "BST", "FST", "AT", "GMT", "CET", "EET", "MSK",
"IRT", "GST", "AFT", "AGTT", "IST", "NPT", "ALMT", "MMT", "JT", "AWST",
"JST", "ACST", "AEST", "LHST", "VUT", "NFT", "NZT", "CHAST", "PHOT",
"LINT"];
dojo.date.timezoneOffsets = [-720, -660, -600, -570, -540, -480, -420, -360,
-300, -240, -210, -180, -120, -60, 0, 60, 120, 180, 210, 240, 270, 300,
330, 345, 360, 390, 420, 480, 540, 570, 600, 630, 660, 690, 720, 765, 780,
840];
/*
dojo.date.timezones = ["International Date Line West", "Bering Standard Time",
"Hawaiian Standard Time", "Marquesas Time", "Alaska Standard Time",
"Pacific Standard Time (USA)", "Mountain Standard Time",
"Central Standard Time (USA)", "Eastern Standard Time (USA)",
"Atlantic Standard Time", "Newfoundland Time", "Brazil Standard Time",
"Fernando de Noronha Standard Time (Brazil)", "Azores Time",
"Greenwich Mean Time", "Central Europe Time", "Eastern Europe Time",
"Moscow Time", "Iran Standard Time", "Gulf Standard Time",
"Afghanistan Time", "Aqtobe Time", "Indian Standard Time", "Nepal Time",
"Almaty Time", "Myanmar Time", "Java Time",
"Australian Western Standard Time", "Japan Standard Time",
"Australian Central Standard Time", "Lord Hove Standard Time (Australia)",
"Vanuata Time", "Norfolk Time (Australia)", "New Zealand Standard Time",
"Chatham Standard Time (New Zealand)", "Phoenix Islands Time (Kribati)",
"Line Islands Time (Kribati)"];
*/
dojo.date.getDaysInMonth = function(/*Date*/dateObject){
// summary: returns the number of days in the month used by dateObject
};
dojo.date.shortTimezones = ["IDLW", "BET", "HST", "MART", "AKST", "PST", "MST", "CST", "EST", "AST", "NFT", "BST", "FST", "AT", "GMT", "CET", "EET", "MSK", "IRT", "GST", "AFT", "AGTT", "IST", "NPT", "ALMT", "MMT", "JT", "AWST", "JST", "ACST", "AEST", "LHST", "VUT", "NFT", "NZT", "CHAST", "PHOT", "LINT"];
dojo.date.timezoneOffsets = [-720, -660, -600, -570, -540, -480, -420, -360, -300, -240, -210, -180, -120, -60, 0, 60, 120, 180, 210, 240, 270, 300, 330, 345, 360, 390, 420, 480, 540, 570, 600, 630, 660, 690, 720, 765, 780, 840];
dojo.date.getDaysInMonth = function (dateObject) {
var month = dateObject.getMonth();
var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month == 1 && dojo.date.isLeapYear(dateObject)) { return 29; } // Number
else { return days[month]; } // Number
}
dojo.date.isLeapYear = function(/*Date*/dateObject){
// summary:
// Determines if the year of the dateObject is a leap year
//
// description:
// Leap years are years with an additional day YYYY-02-29, where the year
// number is a multiple of four with the following exception: If a year
// is a multiple of 100, then it is only a leap year if it is also a
// multiple of 400. For example, 1900 was not a leap year, but 2000 is one.
if (month == 1 && dojo.date.isLeapYear(dateObject)) {
return 29;
} else {
return days[month];
}
};
dojo.date.isLeapYear = function (dateObject) {
var year = dateObject.getFullYear();
return (year%400 == 0) ? true : (year%100 == 0) ? false : (year%4 == 0) ? true : false; // Boolean
}
// FIXME: This is not localized
dojo.date.getTimezoneName = function(/*Date*/dateObject){
// summary:
// Get the user's time zone as provided by the browser
//
// dateObject: needed because the timezone may vary with time (daylight savings)
//
// description:
// Try to get time zone info from toString or toLocaleString
// method of the Date object -- UTC offset is not a time zone.
// See http://www.twinsun.com/tz/tz-link.htm
// Note: results may be inconsistent across browsers.
var str = dateObject.toString(); // Start looking in toString
var tz = ''; // The result -- return empty string if nothing found
return (year % 400 == 0) ? true : (year % 100 == 0) ? false : (year % 4 == 0) ? true : false;
};
dojo.date.getTimezoneName = function (dateObject) {
var str = dateObject.toString();
var tz = "";
var match;
// First look for something in parentheses -- fast lookup, no regex
var pos = str.indexOf('(');
var pos = str.indexOf("(");
if (pos > -1) {
pos++;
tz = str.substring(pos, str.indexOf(')'));
}
// If at first you don't succeed ...
else{
// If IE knows about the TZ, it appears before the year
// Capital letters or slash before a 4-digit year
// at the end of string
tz = str.substring(pos, str.indexOf(")"));
} else {
var pat = /([A-Z\/]+) \d{4}$/;
if((match = str.match(pat))) {
if ((match = str.match(pat))) {
tz = match[1];
}
// Some browsers (e.g. Safari) glue the TZ on the end
// of toLocaleString instead of putting it in toString
else{
} else {
str = dateObject.toLocaleString();
// Capital letters or slash -- end of string,
// after space
pat = / ([A-Z\/]+)$/;
if((match = str.match(pat))) {
if ((match = str.match(pat))) {
tz = match[1];
}
}
}
// Make sure it doesn't somehow end up return AM or PM
return tz == 'AM' || tz == 'PM' ? '' : tz; //String
}
//FIXME: not localized
dojo.date.getOrdinal = function(dateObject){
// summary: returns the appropriate suffix (English only) for the day of the month, e.g. 'st' for 1, 'nd' for 2, etc.)
return tz == "AM" || tz == "PM" ? "" : tz;
};
dojo.date.getOrdinal = function (dateObject) {
var date = dateObject.getDate();
if(date%100 != 11 && date%10 == 1){ return "st"; } // String
else if(date%100 != 12 && date%10 == 2){ return "nd"; } // String
else if(date%100 != 13 && date%10 == 3){ return "rd"; } // String
else{ return "th"; } // String
}
/* compare and add
******************/
dojo.date.compareTypes={
// summary
// bitmask for comparison operations.
DATE:1, TIME:2
if (date % 100 != 11 && date % 10 == 1) {
return "st";
} else {
if (date % 100 != 12 && date % 10 == 2) {
return "nd";
} else {
if (date % 100 != 13 && date % 10 == 3) {
return "rd";
} else {
return "th";
}
}
}
};
dojo.date.compare=function(/* Date */ dateA, /* Date */ dateB, /* dojo.date.compareTypes */ options){
// summary
// Compare two date objects by date, time, or both. Returns 0 if equal, positive if a > b, else negative.
var dA=dateA;
var dB=dateB||new Date();
var now=new Date();
//FIXME: shorten this code
with(dojo.date.compareTypes){
var opt=options||(DATE|TIME);
var d1=new Date(
(opt&DATE)?dA.getFullYear():now.getFullYear(),
(opt&DATE)?dA.getMonth():now.getMonth(),
(opt&DATE)?dA.getDate():now.getDate(),
(opt&TIME)?dA.getHours():0,
(opt&TIME)?dA.getMinutes():0,
(opt&TIME)?dA.getSeconds():0
);
var d2=new Date(
(opt&DATE)?dB.getFullYear():now.getFullYear(),
(opt&DATE)?dB.getMonth():now.getMonth(),
(opt&DATE)?dB.getDate():now.getDate(),
(opt&TIME)?dB.getHours():0,
(opt&TIME)?dB.getMinutes():0,
(opt&TIME)?dB.getSeconds():0
);
dojo.date.compareTypes = {DATE:1, TIME:2};
dojo.date.compare = function (dateA, dateB, options) {
var dA = dateA;
var dB = dateB || new Date();
var now = new Date();
with (dojo.date.compareTypes) {
var opt = options || (DATE | TIME);
var d1 = new Date((opt & DATE) ? dA.getFullYear() : now.getFullYear(), (opt & DATE) ? dA.getMonth() : now.getMonth(), (opt & DATE) ? dA.getDate() : now.getDate(), (opt & TIME) ? dA.getHours() : 0, (opt & TIME) ? dA.getMinutes() : 0, (opt & TIME) ? dA.getSeconds() : 0);
var d2 = new Date((opt & DATE) ? dB.getFullYear() : now.getFullYear(), (opt & DATE) ? dB.getMonth() : now.getMonth(), (opt & DATE) ? dB.getDate() : now.getDate(), (opt & TIME) ? dB.getHours() : 0, (opt & TIME) ? dB.getMinutes() : 0, (opt & TIME) ? dB.getSeconds() : 0);
}
if(d1.valueOf()>d2.valueOf()){
return 1; // int
if (d1.valueOf() > d2.valueOf()) {
return 1;
}
if(d1.valueOf()<d2.valueOf()){
return -1; // int
if (d1.valueOf() < d2.valueOf()) {
return -1;
}
return 0; // int
}
dojo.date.dateParts={
// summary
// constants for use in dojo.date.add
YEAR:0, MONTH:1, DAY:2, HOUR:3, MINUTE:4, SECOND:5, MILLISECOND:6, QUARTER:7, WEEK:8, WEEKDAY:9
return 0;
};
dojo.date.add = function(/* Date */ dt, /* dojo.date.dateParts */ interv, /* int */ incr){
// summary:
// Add to a Date in intervals of different size, from milliseconds to years
//
// dt:
// A Javascript Date object to start with
//
// interv:
// A constant representing the interval, e.g. YEAR, MONTH, DAY. See dojo.date.dateParts.
//
// incr:
// How much to add to the date
if(typeof dt == 'number'){dt = new Date(dt);} // Allow timestamps
//FIXME: what's the reason behind this? incr = incr || 1;
function fixOvershoot(){
if (sum.getDate() < dt.getDate()){
dojo.date.dateParts = {YEAR:0, MONTH:1, DAY:2, HOUR:3, MINUTE:4, SECOND:5, MILLISECOND:6, QUARTER:7, WEEK:8, WEEKDAY:9};
dojo.date.add = function (dt, interv, incr) {
if (typeof dt == "number") {
dt = new Date(dt);
}
function fixOvershoot() {
if (sum.getDate() < dt.getDate()) {
sum.setDate(0);
}
}
var sum = new Date(dt);
with(dojo.date.dateParts){
switch(interv){
case YEAR:
sum.setFullYear(dt.getFullYear()+incr);
// Keep increment/decrement from 2/29 out of March
fixOvershoot();
break;
case QUARTER:
// Naive quarter is just three months
incr*=3;
// fallthrough...
case MONTH:
sum.setMonth(dt.getMonth()+incr);
// Reset to last day of month if you overshoot
fixOvershoot();
break;
case WEEK:
incr*=7;
// fallthrough...
case DAY:
sum.setDate(dt.getDate() + incr);
break;
case WEEKDAY:
//FIXME: assumes Saturday/Sunday weekend, but even this is not fixed. There are CLDR entries to localize this.
var dat = dt.getDate();
var weeks = 0;
var days = 0;
var strt = 0;
var trgt = 0;
var adj = 0;
// Divide the increment time span into weekspans plus leftover days
// e.g., 8 days is one 5-day weekspan / and two leftover days
// Can't have zero leftover days, so numbers divisible by 5 get
// a days value of 5, and the remaining days make up the number of weeks
var mod = incr % 5;
if (mod == 0) {
days = (incr > 0) ? 5 : -5;
weeks = (incr > 0) ? ((incr-5)/5) : ((incr+5)/5);
}
else {
days = mod;
weeks = parseInt(incr/5);
}
// Get weekday value for orig date param
strt = dt.getDay();
// Orig date is Sat / positive incrementer
// Jump over Sun
if (strt == 6 && incr > 0) {
adj = 1;
}
// Orig date is Sun / negative incrementer
// Jump back over Sat
else if (strt == 0 && incr < 0) {
with (dojo.date.dateParts) {
switch (interv) {
case YEAR:
sum.setFullYear(dt.getFullYear() + incr);
fixOvershoot();
break;
case QUARTER:
incr *= 3;
case MONTH:
sum.setMonth(dt.getMonth() + incr);
fixOvershoot();
break;
case WEEK:
incr *= 7;
case DAY:
sum.setDate(dt.getDate() + incr);
break;
case WEEKDAY:
var dat = dt.getDate();
var weeks = 0;
var days = 0;
var strt = 0;
var trgt = 0;
var adj = 0;
var mod = incr % 5;
if (mod == 0) {
days = (incr > 0) ? 5 : -5;
weeks = (incr > 0) ? ((incr - 5) / 5) : ((incr + 5) / 5);
} else {
days = mod;
weeks = parseInt(incr / 5);
}
strt = dt.getDay();
if (strt == 6 && incr > 0) {
adj = 1;
} else {
if (strt == 0 && incr < 0) {
adj = -1;
}
// Get weekday val for the new date
trgt = (strt + days);
// New date is on Sat or Sun
if (trgt == 0 || trgt == 6) {
adj = (incr > 0) ? 2 : -2;
}
// Increment by number of weeks plus leftover days plus
// weekend adjustments
sum.setDate(dat + (7*weeks) + days + adj);
break;
case HOUR:
sum.setHours(sum.getHours()+incr);
break;
case MINUTE:
sum.setMinutes(sum.getMinutes()+incr);
break;
case SECOND:
sum.setSeconds(sum.getSeconds()+incr);
break;
case MILLISECOND:
sum.setMilliseconds(sum.getMilliseconds()+incr);
break;
default:
// Do nothing
break;
}
trgt = (strt + days);
if (trgt == 0 || trgt == 6) {
adj = (incr > 0) ? 2 : -2;
}
sum.setDate(dat + (7 * weeks) + days + adj);
break;
case HOUR:
sum.setHours(sum.getHours() + incr);
break;
case MINUTE:
sum.setMinutes(sum.getMinutes() + incr);
break;
case SECOND:
sum.setSeconds(sum.getSeconds() + incr);
break;
case MILLISECOND:
sum.setMilliseconds(sum.getMilliseconds() + incr);
break;
default:
break;
}
}
return sum; // Date
return sum;
};
dojo.date.diff = function(/* Date */ dtA, /* Date */ dtB, /* dojo.date.dateParts */ interv){
// summary:
// Get the difference in a specific unit of time (e.g., number of months, weeks,
// days, etc.) between two dates.
//
// dtA:
// A Javascript Date object
//
// dtB:
// A Javascript Date object
//
// interv:
// A constant representing the interval, e.g. YEAR, MONTH, DAY. See dojo.date.dateParts.
// Accept timestamp input
if(typeof dtA == 'number'){dtA = new Date(dtA);}
if(typeof dtB == 'number'){dtB = new Date(dtB);}
dojo.date.diff = function (dtA, dtB, interv) {
if (typeof dtA == "number") {
dtA = new Date(dtA);
}
if (typeof dtB == "number") {
dtB = new Date(dtB);
}
var yeaDiff = dtB.getFullYear() - dtA.getFullYear();
var monDiff = (dtB.getMonth() - dtA.getMonth()) + (yeaDiff * 12);
var msDiff = dtB.getTime() - dtA.getTime(); // Millisecs
var secDiff = msDiff/1000;
var minDiff = secDiff/60;
var houDiff = minDiff/60;
var dayDiff = houDiff/24;
var weeDiff = dayDiff/7;
var delta = 0; // Integer return value
with(dojo.date.dateParts){
switch(interv){
case YEAR:
delta = yeaDiff;
break;
case QUARTER:
var mA = dtA.getMonth();
var mB = dtB.getMonth();
// Figure out which quarter the months are in
var qA = Math.floor(mA/3) + 1;
var qB = Math.floor(mB/3) + 1;
// Add quarters for any year difference between the dates
qB += (yeaDiff * 4);
delta = qB - qA;
break;
case MONTH:
delta = monDiff;
break;
case WEEK:
// Truncate instead of rounding
// Don't use Math.floor -- value may be negative
delta = parseInt(weeDiff);
break;
case DAY:
delta = dayDiff;
break;
case WEEKDAY:
var days = Math.round(dayDiff);
var weeks = parseInt(days/7);
var mod = days % 7;
// Even number of weeks
if (mod == 0) {
days = weeks*5;
}
// Weeks plus spare change (< 7 days)
else {
var adj = 0;
var aDay = dtA.getDay();
var bDay = dtB.getDay();
weeks = parseInt(days/7);
mod = days % 7;
// Mark the date advanced by the number of
// round weeks (may be zero)
var dtMark = new Date(dtA);
dtMark.setDate(dtMark.getDate()+(weeks*7));
var dayMark = dtMark.getDay();
// Spare change days -- 6 or less
// ----------
// Positive diff
if (dayDiff > 0) {
var msDiff = dtB.getTime() - dtA.getTime();
var secDiff = msDiff / 1000;
var minDiff = secDiff / 60;
var houDiff = minDiff / 60;
var dayDiff = houDiff / 24;
var weeDiff = dayDiff / 7;
var delta = 0;
with (dojo.date.dateParts) {
switch (interv) {
case YEAR:
delta = yeaDiff;
break;
case QUARTER:
var mA = dtA.getMonth();
var mB = dtB.getMonth();
var qA = Math.floor(mA / 3) + 1;
var qB = Math.floor(mB / 3) + 1;
qB += (yeaDiff * 4);
delta = qB - qA;
break;
case MONTH:
delta = monDiff;
break;
case WEEK:
delta = parseInt(weeDiff);
break;
case DAY:
delta = dayDiff;
break;
case WEEKDAY:
var days = Math.round(dayDiff);
var weeks = parseInt(days / 7);
var mod = days % 7;
if (mod == 0) {
days = weeks * 5;
} else {
var adj = 0;
var aDay = dtA.getDay();
var bDay = dtB.getDay();
weeks = parseInt(days / 7);
mod = days % 7;
var dtMark = new Date(dtA);
dtMark.setDate(dtMark.getDate() + (weeks * 7));
var dayMark = dtMark.getDay();
if (dayDiff > 0) {
switch (true) {
case aDay == 6:
adj = -1;
break;
case aDay == 0:
adj = 0;
break;
case bDay == 6:
adj = -1;
break;
case bDay == 0:
adj = -2;
break;
case (dayMark + mod) > 5:
adj = -2;
break;
default:
break;
}
} else {
if (dayDiff < 0) {
switch (true) {
// Range starts on Sat
case aDay == 6:
adj = -1;
break;
// Range starts on Sun
case aDay == 0:
adj = 0;
break;
// Range ends on Sat
case bDay == 6:
adj = -1;
break;
// Range ends on Sun
case bDay == 0:
adj = -2;
break;
// Range contains weekend
case (dayMark + mod) > 5:
adj = -2;
break;
default:
// Do nothing
break;
case aDay == 6:
adj = 0;
break;
case aDay == 0:
adj = 1;
break;
case bDay == 6:
adj = 2;
break;
case bDay == 0:
adj = 1;
break;
case (dayMark + mod) < 0:
adj = 2;
break;
default:
break;
}
}
// Negative diff
else if (dayDiff < 0) {
switch (true) {
// Range starts on Sat
case aDay == 6:
adj = 0;
break;
// Range starts on Sun
case aDay == 0:
adj = 1;
break;
// Range ends on Sat
case bDay == 6:
adj = 2;
break;
// Range ends on Sun
case bDay == 0:
adj = 1;
break;
// Range contains weekend
case (dayMark + mod) < 0:
adj = 2;
break;
default:
// Do nothing
break;
}
}
days += adj;
days -= (weeks*2);
}
delta = days;
break;
case HOUR:
delta = houDiff;
break;
case MINUTE:
delta = minDiff;
break;
case SECOND:
delta = secDiff;
break;
case MILLISECOND:
delta = msDiff;
break;
default:
// Do nothing
break;
days += adj;
days -= (weeks * 2);
}
delta = days;
break;
case HOUR:
delta = houDiff;
break;
case MINUTE:
delta = minDiff;
break;
case SECOND:
delta = secDiff;
break;
case MILLISECOND:
delta = msDiff;
break;
default:
break;
}
}
// Round for fractional values and DST leaps
return Math.round(delta); // Number (integer)
return Math.round(delta);
};
File diff suppressed because it is too large Load Diff
@@ -9,33 +9,24 @@
*/
dojo.provide("dojo.date.serialize");
dojo.require("dojo.string.common");
/* ISO 8601 Functions
*********************/
dojo.date.setIso8601 = function(/*Date*/dateObject, /*String*/formattedString){
// summary: sets a Date object based on an ISO 8601 formatted string (uses date and time)
dojo.date.setIso8601 = function (dateObject, formattedString) {
var comps = (formattedString.indexOf("T") == -1) ? formattedString.split(" ") : formattedString.split("T");
dateObject = dojo.date.setIso8601Date(dateObject, comps[0]);
if(comps.length == 2){ dateObject = dojo.date.setIso8601Time(dateObject, comps[1]); }
return dateObject; /* Date or null */
if (comps.length == 2) {
dateObject = dojo.date.setIso8601Time(dateObject, comps[1]);
}
return dateObject;
};
dojo.date.fromIso8601 = function(/*String*/formattedString){
// summary: returns a Date object based on an ISO 8601 formatted string (uses date and time)
dojo.date.fromIso8601 = function (formattedString) {
return dojo.date.setIso8601(new Date(0, 0), formattedString);
};
dojo.date.setIso8601Date = function(/*String*/dateObject, /*String*/formattedString){
// summary: sets a Date object based on an ISO 8601 formatted string (date only)
var regexp = "^([0-9]{4})((-?([0-9]{2})(-?([0-9]{2}))?)|" +
"(-?([0-9]{3}))|(-?W([0-9]{2})(-?([1-7]))?))?$";
dojo.date.setIso8601Date = function (dateObject, formattedString) {
var regexp = "^([0-9]{4})((-?([0-9]{2})(-?([0-9]{2}))?)|" + "(-?([0-9]{3}))|(-?W([0-9]{2})(-?([1-7]))?))?$";
var d = formattedString.match(new RegExp(regexp));
if(!d){
if (!d) {
dojo.debug("invalid date string: " + formattedString);
return null; // null
return null;
}
var year = d[1];
var month = d[4];
@@ -43,133 +34,94 @@ dojo.date.setIso8601Date = function(/*String*/dateObject, /*String*/formattedStr
var dayofyear = d[8];
var week = d[10];
var dayofweek = d[12] ? d[12] : 1;
dateObject.setFullYear(year);
if(dayofyear){
if (dayofyear) {
dateObject.setMonth(0);
dateObject.setDate(Number(dayofyear));
}
else if(week){
dateObject.setMonth(0);
dateObject.setDate(1);
var gd = dateObject.getDay();
var day = gd ? gd : 7;
var offset = Number(dayofweek) + (7 * Number(week));
if(day <= 4){ dateObject.setDate(offset + 1 - day); }
else{ dateObject.setDate(offset + 8 - day); }
} else{
if(month){
} else {
if (week) {
dateObject.setMonth(0);
dateObject.setDate(1);
dateObject.setMonth(month - 1);
var gd = dateObject.getDay();
var day = gd ? gd : 7;
var offset = Number(dayofweek) + (7 * Number(week));
if (day <= 4) {
dateObject.setDate(offset + 1 - day);
} else {
dateObject.setDate(offset + 8 - day);
}
} else {
if (month) {
dateObject.setDate(1);
dateObject.setMonth(month - 1);
}
if (date) {
dateObject.setDate(date);
}
}
if(date){ dateObject.setDate(date); }
}
return dateObject; // Date
return dateObject;
};
dojo.date.fromIso8601Date = function(/*String*/formattedString){
// summary: returns a Date object based on an ISO 8601 formatted string (date only)
dojo.date.fromIso8601Date = function (formattedString) {
return dojo.date.setIso8601Date(new Date(0, 0), formattedString);
};
dojo.date.setIso8601Time = function(/*Date*/dateObject, /*String*/formattedString){
// summary: sets a Date object based on an ISO 8601 formatted string (time only)
// first strip timezone info from the end
dojo.date.setIso8601Time = function (dateObject, formattedString) {
var timezone = "Z|(([-+])([0-9]{2})(:?([0-9]{2}))?)$";
var d = formattedString.match(new RegExp(timezone));
var offset = 0; // local time if no tz info
if(d){
if(d[0] != 'Z'){
var offset = 0;
if (d) {
if (d[0] != "Z") {
offset = (Number(d[3]) * 60) + Number(d[5]);
offset *= ((d[2] == '-') ? 1 : -1);
offset *= ((d[2] == "-") ? 1 : -1);
}
offset -= dateObject.getTimezoneOffset();
formattedString = formattedString.substr(0, formattedString.length - d[0].length);
}
// then work out the time
var regexp = "^([0-9]{2})(:?([0-9]{2})(:?([0-9]{2})(\.([0-9]+))?)?)?$";
var regexp = "^([0-9]{2})(:?([0-9]{2})(:?([0-9]{2})(.([0-9]+))?)?)?$";
d = formattedString.match(new RegExp(regexp));
if(!d){
if (!d) {
dojo.debug("invalid time string: " + formattedString);
return null; // null
return null;
}
var hours = d[1];
var mins = Number((d[3]) ? d[3] : 0);
var secs = (d[5]) ? d[5] : 0;
var ms = d[7] ? (Number("0." + d[7]) * 1000) : 0;
dateObject.setHours(hours);
dateObject.setMinutes(mins);
dateObject.setSeconds(secs);
dateObject.setMilliseconds(ms);
if(offset !== 0){
if (offset !== 0) {
dateObject.setTime(dateObject.getTime() + offset * 60000);
}
return dateObject; // Date
}
return dateObject;
};
dojo.date.fromIso8601Time = function(/*String*/formattedString){
// summary: returns a Date object based on an ISO 8601 formatted string (date only)
dojo.date.fromIso8601Time = function (formattedString) {
return dojo.date.setIso8601Time(new Date(0, 0), formattedString);
};
/* RFC-3339 Date Functions
*************************/
dojo.date.toRfc3339 = function(/*Date?*/dateObject, /*String?*/selector){
// summary:
// Format a JavaScript Date object as a string according to RFC 3339
//
// dateObject:
// A JavaScript date, or the current date and time, by default
//
// selector:
// "dateOnly" or "timeOnly" to format selected portions of the Date object.
// Date and time will be formatted by default.
//FIXME: tolerate Number, string input?
if(!dateObject){
dojo.date.toRfc3339 = function (dateObject, selector) {
if (!dateObject) {
dateObject = new Date();
}
var _ = dojo.string.pad;
var formattedDate = [];
if(selector != "timeOnly"){
var date = [_(dateObject.getFullYear(),4), _(dateObject.getMonth()+1,2), _(dateObject.getDate(),2)].join('-');
if (selector != "timeOnly") {
var date = [_(dateObject.getFullYear(), 4), _(dateObject.getMonth() + 1, 2), _(dateObject.getDate(), 2)].join("-");
formattedDate.push(date);
}
if(selector != "dateOnly"){
var time = [_(dateObject.getHours(),2), _(dateObject.getMinutes(),2), _(dateObject.getSeconds(),2)].join(':');
if (selector != "dateOnly") {
var time = [_(dateObject.getHours(), 2), _(dateObject.getMinutes(), 2), _(dateObject.getSeconds(), 2)].join(":");
var timezoneOffset = dateObject.getTimezoneOffset();
time += (timezoneOffset > 0 ? "-" : "+") +
_(Math.floor(Math.abs(timezoneOffset)/60),2) + ":" +
_(Math.abs(timezoneOffset)%60,2);
time += (timezoneOffset > 0 ? "-" : "+") + _(Math.floor(Math.abs(timezoneOffset) / 60), 2) + ":" + _(Math.abs(timezoneOffset) % 60, 2);
formattedDate.push(time);
}
return formattedDate.join('T'); // String
return formattedDate.join("T");
};
dojo.date.fromRfc3339 = function(/*String*/rfcDate){
// summary:
// Create a JavaScript Date object from a string formatted according to RFC 3339
//
// rfcDate:
// A string such as 2005-06-30T08:05:00-07:00
// "any" is also supported in place of a time.
// backwards compatible support for use of "any" instead of just not
// including the time
if(rfcDate.indexOf("Tany")!=-1){
rfcDate = rfcDate.replace("Tany","");
dojo.date.fromRfc3339 = function (rfcDate) {
if (rfcDate.indexOf("Tany") != -1) {
rfcDate = rfcDate.replace("Tany", "");
}
var dateObject = new Date();
return dojo.date.setIso8601(dateObject, rfcDate); // Date or null
return dojo.date.setIso8601(dateObject, rfcDate);
};
@@ -9,68 +9,37 @@
*/
dojo.provide("dojo.date.supplemental");
dojo.date.getFirstDayOfWeek = function(/*String?*/locale){
// summary: Returns a zero-based index for first day of the week
// description:
// Returns a zero-based index for first day of the week, as used by the local (Gregorian) calendar.
// e.g. Sunday (returns 0), or Monday (returns 1)
// from http://www.unicode.org/cldr/data/common/supplemental/supplementalData.xml:supplementalData/weekData/firstDay
var firstDay = {/*default is 1=Monday*/
mv:5,
ae:6,af:6,bh:6,dj:6,dz:6,eg:6,er:6,et:6,iq:6,ir:6,jo:6,ke:6,kw:6,lb:6,ly:6,ma:6,om:6,qa:6,sa:6,
sd:6,so:6,tn:6,ye:6,
as:0,au:0,az:0,bw:0,ca:0,cn:0,fo:0,ge:0,gl:0,gu:0,hk:0,ie:0,il:0,is:0,jm:0,jp:0,kg:0,kr:0,la:0,
mh:0,mo:0,mp:0,mt:0,nz:0,ph:0,pk:0,sg:0,th:0,tt:0,tw:0,um:0,us:0,uz:0,vi:0,za:0,zw:0,
et:0,mw:0,ng:0,tj:0,
gb:0,
sy:4
};
dojo.date.getFirstDayOfWeek = function (locale) {
var firstDay = {mv:5, ae:6, af:6, bh:6, dj:6, dz:6, eg:6, er:6, et:6, iq:6, ir:6, jo:6, ke:6, kw:6, lb:6, ly:6, ma:6, om:6, qa:6, sa:6, sd:6, so:6, tn:6, ye:6, as:0, au:0, az:0, bw:0, ca:0, cn:0, fo:0, ge:0, gl:0, gu:0, hk:0, ie:0, il:0, is:0, jm:0, jp:0, kg:0, kr:0, la:0, mh:0, mo:0, mp:0, mt:0, nz:0, ph:0, pk:0, sg:0, th:0, tt:0, tw:0, um:0, us:0, uz:0, vi:0, za:0, zw:0, et:0, mw:0, ng:0, tj:0, gb:0, sy:4};
locale = dojo.hostenv.normalizeLocale(locale);
var country = locale.split("-")[1];
var dow = firstDay[country];
return (typeof dow == 'undefined') ? 1 : dow; /*Number*/
return (typeof dow == "undefined") ? 1 : dow;
};
dojo.date.getWeekend = function(/*String?*/locale){
// summary: Returns a hash containing the start and end days of the weekend
// description:
// Returns a hash containing the start and end days of the weekend according to local custom using locale,
// or by default in the user's locale.
// e.g. {start:6, end:0}
// from http://www.unicode.org/cldr/data/common/supplemental/supplementalData.xml:supplementalData/weekData/weekend{Start,End}
var weekendStart = {/*default is 6=Saturday*/
eg:5,il:5,sy:5,
'in':0,
ae:4,bh:4,dz:4,iq:4,jo:4,kw:4,lb:4,ly:4,ma:4,om:4,qa:4,sa:4,sd:4,tn:4,ye:4
};
var weekendEnd = {/*default is 0=Sunday*/
ae:5,bh:5,dz:5,iq:5,jo:5,kw:5,lb:5,ly:5,ma:5,om:5,qa:5,sa:5,sd:5,tn:5,ye:5,af:5,ir:5,
eg:6,il:6,sy:6
};
dojo.date.getWeekend = function (locale) {
var weekendStart = {eg:5, il:5, sy:5, "in":0, ae:4, bh:4, dz:4, iq:4, jo:4, kw:4, lb:4, ly:4, ma:4, om:4, qa:4, sa:4, sd:4, tn:4, ye:4};
var weekendEnd = {ae:5, bh:5, dz:5, iq:5, jo:5, kw:5, lb:5, ly:5, ma:5, om:5, qa:5, sa:5, sd:5, tn:5, ye:5, af:5, ir:5, eg:6, il:6, sy:6};
locale = dojo.hostenv.normalizeLocale(locale);
var country = locale.split("-")[1];
var start = weekendStart[country];
var end = weekendEnd[country];
if(typeof start == 'undefined'){start=6;}
if(typeof end == 'undefined'){end=0;}
return {start:start, end:end}; /*Object {start,end}*/
if (typeof start == "undefined") {
start = 6;
}
if (typeof end == "undefined") {
end = 0;
}
return {start:start, end:end};
};
dojo.date.isWeekend = function(/*Date?*/dateObj, /*String?*/locale){
// summary:
// Determines if the date falls on a weekend, according to local custom.
dojo.date.isWeekend = function (dateObj, locale) {
var weekend = dojo.date.getWeekend(locale);
var day = (dateObj || new Date()).getDay();
if(weekend.end<weekend.start){
weekend.end+=7;
if(day<weekend.start){ day+=7; }
if (weekend.end < weekend.start) {
weekend.end += 7;
if (day < weekend.start) {
day += 7;
}
}
return day >= weekend.start && day <= weekend.end; // Boolean
return day >= weekend.start && day <= weekend.end;
};
@@ -8,29 +8,26 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.debug = function(/*...*/){
// summary:
// Produce a line of debug output. Does nothing unless
// djConfig.isDebug is true. Accepts any nubmer of args, joined with
// '' to produce a single line of debugging output. Caller should not
// supply a trailing "\n".
if (!djConfig.isDebug) { return; }
dojo.provide("dojo.debug");
dojo.debug = function () {
if (!djConfig.isDebug) {
return;
}
var args = arguments;
if(dj_undef("println", dojo.hostenv)){
if (dj_undef("println", dojo.hostenv)) {
dojo.raise("dojo.debug not available (yet?)");
}
var isJUM = dj_global["jum"] && !dj_global["jum"].isBrowser;
var s = [(isJUM ? "": "DEBUG: ")];
for(var i=0;i<args.length;++i){
if(!false && args[i] && args[i] instanceof Error){
var msg = "[" + args[i].name + ": " + dojo.errorToString(args[i]) +
(args[i].fileName ? ", file: " + args[i].fileName : "") +
(args[i].lineNumber ? ", line: " + args[i].lineNumber : "") + "]";
var s = [(isJUM ? "" : "DEBUG: ")];
for (var i = 0; i < args.length; ++i) {
if (!false && args[i] && args[i] instanceof Error) {
var msg = "[" + args[i].name + ": " + dojo.errorToString(args[i]) + (args[i].fileName ? ", file: " + args[i].fileName : "") + (args[i].lineNumber ? ", line: " + args[i].lineNumber : "") + "]";
} else {
try {
var msg = String(args[i]);
} catch(e) {
if(dojo.render.html.ie) {
}
catch (e) {
if (dojo.render.html.ie) {
var msg = "[ActiveXObject]";
} else {
var msg = "[unknown]";
@@ -39,53 +36,48 @@ dojo.debug = function(/*...*/){
}
s.push(msg);
}
dojo.hostenv.println(s.join(" "));
}
/**
* this is really hacky for now - just
* display the properties of the object
**/
dojo.debugShallow = function(/*Object*/obj){
// summary:
// outputs a "name: value" style listing of all enumerable properties
// in obj. Does nothing if djConfig.isDebug == false.
// obj: the object to be enumerated
if (!djConfig.isDebug) { return; }
dojo.debug('------------------------------------------------------------');
dojo.debug('Object: '+obj);
};
dojo.debugShallow = function (obj) {
if (!djConfig.isDebug) {
return;
}
dojo.debug("------------------------------------------------------------");
dojo.debug("Object: " + obj);
var props = [];
for(var prop in obj){
for (var prop in obj) {
try {
props.push(prop + ': ' + obj[prop]);
} catch(E) {
props.push(prop + ': ERROR - ' + E.message);
props.push(prop + ": " + obj[prop]);
}
catch (E) {
props.push(prop + ": ERROR - " + E.message);
}
}
props.sort();
for(var i = 0; i < props.length; i++) {
for (var i = 0; i < props.length; i++) {
dojo.debug(props[i]);
}
dojo.debug('------------------------------------------------------------');
}
dojo.debugDeep = function(/*Object*/obj){
// summary:
// provides an "object explorer" view of the passed obj in a popup
// window.
// obj: the object to be examined
if (!djConfig.isDebug) { return; }
if (!dojo.uri || !dojo.uri.dojoUri){ return dojo.debug("You'll need to load dojo.uri.* for deep debugging - sorry!"); }
if (!window.open){ return dojo.debug('Deep debugging is only supported in host environments with window.open'); }
dojo.debug("------------------------------------------------------------");
};
dojo.debugDeep = function (obj) {
if (!djConfig.isDebug) {
return;
}
if (!dojo.uri || !dojo.uri.dojoUri) {
return dojo.debug("You'll need to load dojo.uri.* for deep debugging - sorry!");
}
if (!window.open) {
return dojo.debug("Deep debugging is only supported in host environments with window.open");
}
var idx = dojo.debugDeep.debugVars.length;
dojo.debugDeep.debugVars.push(obj);
// dojo.undo.browser back and forward breaks relpaths
var url = new dojo.uri.Uri(location, dojo.uri.dojoUri("src/debug/deep.html?var="+idx)).toString();
var win = window.open(url, '_blank', 'width=600, height=400, resizable=yes, scrollbars=yes, status=yes');
try{
var url = (djConfig["dojoDebugDeepHtmlUrl"] || new dojo.uri.Uri(location, dojo.uri.moduleUri("dojo.debug", "deep.html")).toString()) + "?var=" + idx;
var win = window.open(url, "_blank", "width=600, height=400, resizable=yes, scrollbars=yes, status=yes");
try {
win.debugVar = obj;
}catch(e){}
}
}
catch (e) {
}
};
dojo.debugDeep.debugVars = [];
@@ -10,53 +10,46 @@
dojo.provide("dojo.debug.Firebug");
dojo.deprecated("dojo.debug.Firebug is slated for removal in 0.5; use dojo.debug.console instead.", "0.5");
// summary
// Firebug Console logger.
// This package redirects the normal dojo debugging output to the firebug console. It does
// so by sending the entire object to the console, rather than just overriding dojo.hostenv.println
// so that firebugs object inspector can be taken advantage of.
if (dojo.render.html.moz) {
if (console && console.log) {
var consoleLog = function() {
if (!djConfig.isDebug) { return ; }
var consoleLog = function () {
if (!djConfig.isDebug) {
return;
}
var args = dojo.lang.toArray(arguments);
args.splice(0,0, "DEBUG: ");
args.splice(0, 0, "DEBUG: ");
console.log.apply(console, args);
}
};
dojo.debug = consoleLog;
dojo.debugDeep=consoleLog;
dojo.debugShallow=function(obj) {
if (!djConfig.isDebug) { return; }
dojo.debugDeep = consoleLog;
dojo.debugShallow = function (obj) {
if (!djConfig.isDebug) {
return;
}
if (dojo.lang.isArray(obj)) {
console.log('Array: ', obj);
for (var i=0; x<obj.length; i++) {
console.log(' ', '['+i+']', obj[i]);
console.log("Array: ", obj);
for (var i = 0; x < obj.length; i++) {
console.log(" ", "[" + i + "]", obj[i]);
}
} else {
console.log('Object: ', obj);
console.log("Object: ", obj);
var propNames = [];
for (var prop in obj) {
propNames.push(prop);
}
propNames.sort();
dojo.lang.forEach(propNames, function(prop) {
dojo.lang.forEach(propNames, function (prop) {
try {
console.log(' ', prop, obj[prop]);
} catch(e) {
console.log(' ', prop, 'ERROR', e.message, e);
console.log(" ", prop, obj[prop]);
}
catch (e) {
console.log(" ", prop, "ERROR", e.message, e);
}
});
}
}
};
} else {
dojo.debug("dojo.debug.Firebug requires Firebug > 0.4");
}
}
@@ -10,106 +10,86 @@
dojo.provide("dojo.debug.console");
dojo.require("dojo.logging.ConsoleLogger");
// summary:
// Console logger, for use with FireFox Firebug, Safari and Opera's consoles.
// description:
// This package redirects the normal dojo debugging output to the console log in modern browsers.
// When using Firebug, it does this by sending the entire object to the console,
// rather than just overriding dojo.hostenv.println, so that Firebug's interactive
// object inspector is available.
// see: http://www.joehewitt.com/software/firebug/docs.php
if (window.console) {
if (console.info != null) {
// using a later version of Firebug -- lots of fun stuff!
dojo.hostenv.println = function() {
// summary: Write all of the arguments to the Firebug console
// description: Uses console.info() so that the (i) icon prints next to the debug line
// rather than munging the arguments by adding "DEBUG:" in front of them.
// This allows us to use Firebug's string handling to do interesting things
if (!djConfig.isDebug) { return; }
dojo.hostenv.println = function () {
if (!djConfig.isDebug) {
return;
}
console.info.apply(console, arguments);
}
dojo.debug=dojo.hostenv.println;
};
dojo.debug = dojo.hostenv.println;
dojo.debugDeep = dojo.debug;
dojo.debugShallow = function(/*Object*/ obj, /*Boolean?*/showMethods, /*Boolean?*/sort) {
// summary: Write first-level properties of obj to the console.
// obj: Object or Array to debug
// showMethods: Pass false to skip outputing methods of object, any other value will output them.
// sort: Pass false to skip sorting properties, any other value will sort.
if (!djConfig.isDebug) { return; }
dojo.debugShallow = function (obj, showMethods, sort) {
if (!djConfig.isDebug) {
return;
}
showMethods = (showMethods != false);
sort = (sort != false);
// handle null or something without a constructor (in which case we don't know the type)
if (obj == null || obj.constructor == null) {
return dojo.debug(obj);
}
// figure out type via a standard constructor (Object, String, Date, etc)
var type = obj.declaredClass;
if (type == null) {
type = obj.constructor.toString().match(/function\s*(.*)\(/);
if (type) { type = type[1] };
if (type) {
type = type[1];
}
}
// if we got a viable type, use Firebug's interactive property dump feature
if (type) {
if (type == "String" || type == "Number") {
return dojo.debug(type+": ", obj);
return dojo.debug(type + ": ", obj);
}
if (showMethods && !sort) {
var sortedObj = obj;
} else {
var propNames = [];
if (showMethods) {
for (var prop in obj) {
for (var prop in obj) {
propNames.push(prop);
}
} else {
for (var prop in obj) {
if (typeof obj[prop] != "function") { propNames.push(prop); }
else dojo.debug(prop);
}
for (var prop in obj) {
if (typeof obj[prop] != "function") {
propNames.push(prop);
} else {
dojo.debug(prop);
}
}
}
if (sort) {
propNames.sort();
}
if (sort) propNames.sort();
var sortedObj = {};
dojo.lang.forEach(propNames, function(prop) {
dojo.lang.forEach(propNames, function (prop) {
sortedObj[prop] = obj[prop];
});
}
return dojo.debug(type+": %o\n%2.o",obj,sortedObj);
return dojo.debug(type + ": %o\n%2.o", obj, sortedObj);
}
// otherwise just output the constructor + object,
// which is nice for a DOM element, etc
return dojo.debug(obj.constructor + ": ", obj);
}
} else if (console.log != null) {
// using Safari or an old version of Firebug
dojo.hostenv.println=function() {
if (!djConfig.isDebug) { return ; }
// make sure we're only writing a single string to Safari's console
var args = dojo.lang.toArray(arguments);
console.log("DEBUG: " + args.join(" "));
}
dojo.debug=dojo.hostenv.println;
};
} else {
// not supported
dojo.debug("dojo.debug.console requires Firebug > 0.4");
if (console.log != null) {
dojo.hostenv.println = function () {
if (!djConfig.isDebug) {
return;
}
var args = dojo.lang.toArray(arguments);
console.log("DEBUG: " + args.join(" "));
};
dojo.debug = dojo.hostenv.println;
} else {
dojo.debug("dojo.debug.console requires Firebug > 0.4");
}
}
} else if (dojo.render.html.opera) {
// using Opera 8.0 or later
if (opera && opera.postError) {
dojo.hostenv.println=opera.postError;
// summary: hook debugging up to Opera's postError routine
} else {
dojo.debug("dojo.debug.Opera requires Opera > 8.0");
} else {
if (dojo.render.html.opera) {
if (opera && opera.postError) {
dojo.hostenv.println = opera.postError;
} else {
dojo.debug("dojo.debug.Opera requires Opera > 8.0");
}
}
}
@@ -9,165 +9,66 @@
*/
dojo.require("dojo.lang.common");
dojo.require("dojo.lang.func");
dojo.require("dojo.lang.declare");
dojo.provide("dojo.dnd.DragAndDrop");
dojo.declare("dojo.dnd.DragSource", null, {
type: "",
onDragEnd: function(){
},
onDragStart: function(){
},
/*
* This function gets called when the DOM element was
* selected for dragging by the HtmlDragAndDropManager.
*/
onSelected: function(){
},
unregister: function(){
dojo.dnd.dragManager.unregisterDragSource(this);
},
reregister: function(){
dojo.dnd.dragManager.registerDragSource(this);
}
}, function(){
//dojo.profile.start("DragSource");
dojo.declare("dojo.dnd.DragSource", null, {type:"", onDragEnd:function (evt) {
}, onDragStart:function (evt) {
}, onSelected:function (evt) {
}, unregister:function () {
dojo.dnd.dragManager.unregisterDragSource(this);
}, reregister:function () {
dojo.dnd.dragManager.registerDragSource(this);
}});
dojo.declare("dojo.dnd.DragObject", null, {type:"", register:function () {
var dm = dojo.dnd.dragManager;
if(dm["registerDragSource"]){ // side-effect prevention
dm.registerDragSource(this);
}
//dojo.profile.end("DragSource");
});
dojo.declare("dojo.dnd.DragObject", null, {
type: "",
onDragStart: function(){
// gets called directly after being created by the DragSource
// default action is to clone self as icon
},
onDragMove: function(){
// this changes the UI for the drag icon
// "it moves itself"
},
onDragOver: function(){
},
onDragOut: function(){
},
onDragEnd: function(){
},
// normal aliases
onDragLeave: this.onDragOut,
onDragEnter: this.onDragOver,
// non-camel aliases
ondragout: this.onDragOut,
ondragover: this.onDragOver
}, function(){
var dm = dojo.dnd.dragManager;
if(dm["registerDragObject"]){ // side-effect prevention
if (dm["registerDragObject"]) {
dm.registerDragObject(this);
}
});
dojo.declare("dojo.dnd.DropTarget", null, {
acceptsType: function(type){
if(!dojo.lang.inArray(this.acceptedTypes, "*")){ // wildcard
if(!dojo.lang.inArray(this.acceptedTypes, type)) { return false; }
}, onDragStart:function (evt) {
}, onDragMove:function (evt) {
}, onDragOver:function (evt) {
}, onDragOut:function (evt) {
}, onDragEnd:function (evt) {
}, onDragLeave:dojo.lang.forward("onDragOut"), onDragEnter:dojo.lang.forward("onDragOver"), ondragout:dojo.lang.forward("onDragOut"), ondragover:dojo.lang.forward("onDragOver")});
dojo.declare("dojo.dnd.DropTarget", null, {acceptsType:function (type) {
if (!dojo.lang.inArray(this.acceptedTypes, "*")) {
if (!dojo.lang.inArray(this.acceptedTypes, type)) {
return false;
}
return true;
},
accepts: function(dragObjects){
if(!dojo.lang.inArray(this.acceptedTypes, "*")){ // wildcard
for (var i = 0; i < dragObjects.length; i++) {
if (!dojo.lang.inArray(this.acceptedTypes,
dragObjects[i].type)) { return false; }
}
return true;
}, accepts:function (dragObjects) {
if (!dojo.lang.inArray(this.acceptedTypes, "*")) {
for (var i = 0; i < dragObjects.length; i++) {
if (!dojo.lang.inArray(this.acceptedTypes, dragObjects[i].type)) {
return false;
}
}
return true;
},
unregister: function(){
dojo.dnd.dragManager.unregisterDropTarget(this);
},
onDragOver: function(){
},
onDragOut: function(){
},
onDragMove: function(){
},
onDropStart: function(){
},
onDrop: function(){
},
onDropEnd: function(){
}
}, function(){
if (this.constructor == dojo.dnd.DropTarget) { return; } // need to be subclassed
return true;
}, unregister:function () {
dojo.dnd.dragManager.unregisterDropTarget(this);
}, onDragOver:function (evt) {
}, onDragOut:function (evt) {
}, onDragMove:function (evt) {
}, onDropStart:function (evt) {
}, onDrop:function (evt) {
}, onDropEnd:function () {
}}, function () {
this.acceptedTypes = [];
dojo.dnd.dragManager.registerDropTarget(this);
});
// NOTE: this interface is defined here for the convenience of the DragManager
// implementor. It is expected that in most cases it will be satisfied by
// extending a native event (DOM event in HTML and SVG).
dojo.dnd.DragEvent = function(){
dojo.dnd.DragEvent = function () {
this.dragSource = null;
this.dragObject = null;
this.target = null;
this.eventStatus = "success";
//
// can be one of:
// [ "dropSuccess", "dropFailure", "dragMove",
// "dragStart", "dragEnter", "dragLeave"]
//
}
/*
* The DragManager handles listening for low-level events and dispatching
* them to higher-level primitives like drag sources and drop targets. In
* order to do this, it must keep a list of the items.
*/
dojo.declare("dojo.dnd.DragManager", null, {
selectedSources: [],
dragObjects: [],
dragSources: [],
registerDragSource: function(){},
dropTargets: [],
registerDropTarget: function(){},
lastDragTarget: null,
currentDragTarget: null,
onKeyDown: function(){},
onMouseOut: function(){},
onMouseMove: function(){},
onMouseUp: function(){}
});
};
dojo.declare("dojo.dnd.DragManager", null, {selectedSources:[], dragObjects:[], dragSources:[], registerDragSource:function (source) {
}, dropTargets:[], registerDropTarget:function (target) {
}, lastDragTarget:null, currentDragTarget:null, onKeyDown:function () {
}, onMouseOut:function () {
}, onMouseMove:function () {
}, onMouseUp:function () {
}});
// NOTE: despite the existance of the DragManager class, there will be a
// singleton drag manager provided by the renderer-specific D&D support code.
// It is therefore sane for us to assign instance variables to the DragManager
// prototype
// The renderer-specific file will define the following object:
// dojo.dnd.dragManager = null;
@@ -9,10 +9,8 @@
*/
dojo.provide("dojo.dnd.HtmlDragAndDrop");
dojo.require("dojo.dnd.HtmlDragManager");
dojo.require("dojo.dnd.DragAndDrop");
dojo.require("dojo.html.*");
dojo.require("dojo.html.display");
dojo.require("dojo.html.util");
@@ -21,488 +19,349 @@ dojo.require("dojo.html.iframe");
dojo.require("dojo.lang.extras");
dojo.require("dojo.lfx.*");
dojo.require("dojo.event.*");
dojo.declare("dojo.dnd.HtmlDragSource", dojo.dnd.DragSource, {
dragClass: "", // CSS classname(s) applied to node when it is being dragged
onDragStart: function(){
var dragObj = new dojo.dnd.HtmlDragObject(this.dragObject, this.type);
if(this.dragClass) { dragObj.dragClass = this.dragClass; }
if (this.constrainToContainer) {
dragObj.constrainTo(this.constrainingContainer || this.domNode.parentNode);
}
return dragObj;
},
setDragHandle: function(node){
node = dojo.byId(node);
dojo.dnd.dragManager.unregisterDragSource(this);
this.domNode = node;
dojo.dnd.dragManager.registerDragSource(this);
},
setDragTarget: function(node){
this.dragObject = node;
},
constrainTo: function(container) {
this.constrainToContainer = true;
if (container) {
this.constrainingContainer = container;
}
},
/*
*
* see dojo.dnd.DragSource.onSelected
*/
onSelected: function() {
for (var i=0; i<this.dragObjects.length; i++) {
dojo.dnd.dragManager.selectedSources.push(new dojo.dnd.HtmlDragSource(this.dragObjects[i]));
}
},
/**
* Register elements that should be dragged along with
* the actual DragSource.
*
* Example usage:
* var dragSource = new dojo.dnd.HtmlDragSource(...);
* // add a single element
* dragSource.addDragObjects(dojo.byId('id1'));
* // add multiple elements to drag along
* dragSource.addDragObjects(dojo.byId('id2'), dojo.byId('id3'));
*
* el A dom node to add to the drag list.
*/
addDragObjects: function(/*DOMNode*/ el) {
for (var i=0; i<arguments.length; i++) {
this.dragObjects.push(arguments[i]);
}
dojo.declare("dojo.dnd.HtmlDragSource", dojo.dnd.DragSource, {dragClass:"", onDragStart:function () {
var dragObj = new dojo.dnd.HtmlDragObject(this.dragObject, this.type);
if (this.dragClass) {
dragObj.dragClass = this.dragClass;
}
}, function(node, type){
if (this.constrainToContainer) {
dragObj.constrainTo(this.constrainingContainer || this.domNode.parentNode);
}
return dragObj;
}, setDragHandle:function (node) {
node = dojo.byId(node);
dojo.dnd.dragManager.unregisterDragSource(this);
this.domNode = node;
dojo.dnd.dragManager.registerDragSource(this);
}, setDragTarget:function (node) {
this.dragObject = node;
}, constrainTo:function (container) {
this.constrainToContainer = true;
if (container) {
this.constrainingContainer = container;
}
}, onSelected:function () {
for (var i = 0; i < this.dragObjects.length; i++) {
dojo.dnd.dragManager.selectedSources.push(new dojo.dnd.HtmlDragSource(this.dragObjects[i]));
}
}, addDragObjects:function (el) {
for (var i = 0; i < arguments.length; i++) {
this.dragObjects.push(dojo.byId(arguments[i]));
}
}}, function (node, type) {
node = dojo.byId(node);
this.dragObjects = [];
this.constrainToContainer = false;
if(node){
if (node) {
this.domNode = node;
this.dragObject = node;
// register us
dojo.dnd.DragSource.call(this);
// set properties that might have been clobbered by the mixin
this.type = (type)||(this.domNode.nodeName.toLowerCase());
this.type = (type) || (this.domNode.nodeName.toLowerCase());
dojo.dnd.DragSource.prototype.reregister.call(this);
}
});
dojo.declare("dojo.dnd.HtmlDragObject", dojo.dnd.DragObject, {
dragClass: "",
opacity: 0.5,
createIframe: true, // workaround IE6 bug
// if true, node will not move in X and/or Y direction
disableX: false,
disableY: false,
createDragNode: function() {
var node = this.domNode.cloneNode(true);
if(this.dragClass) { dojo.html.addClass(node, this.dragClass); }
if(this.opacity < 1) { dojo.html.setOpacity(node, this.opacity); }
if(node.tagName.toLowerCase() == "tr"){
// dojo.debug("Dragging table row")
// Create a table for the cloned row
var doc = this.domNode.ownerDocument;
var table = doc.createElement("table");
dojo.declare("dojo.dnd.HtmlDragObject", dojo.dnd.DragObject, {dragClass:"", opacity:0.5, createIframe:true, disableX:false, disableY:false, createDragNode:function () {
var node = this.domNode.cloneNode(true);
if (this.dragClass) {
dojo.html.addClass(node, this.dragClass);
}
if (this.opacity < 1) {
dojo.html.setOpacity(node, this.opacity);
}
var ltn = node.tagName.toLowerCase();
var isTr = (ltn == "tr");
if ((isTr) || (ltn == "tbody")) {
var doc = this.domNode.ownerDocument;
var table = doc.createElement("table");
if (isTr) {
var tbody = doc.createElement("tbody");
table.appendChild(tbody);
tbody.appendChild(node);
// Set a fixed width to the cloned TDs
var domTds = this.domNode.childNodes;
var cloneTds = node.childNodes;
for(var i = 0; i < domTds.length; i++){
if((cloneTds[i])&&(cloneTds[i].style)){
cloneTds[i].style.width = dojo.html.getContentBox(domTds[i]).width + "px";
}
}
node = table;
}
if((dojo.render.html.ie55||dojo.render.html.ie60) && this.createIframe){
with(node.style) {
top="0px";
left="0px";
}
var outer = document.createElement("div");
outer.appendChild(node);
this.bgIframe = new dojo.html.BackgroundIframe(outer);
outer.appendChild(this.bgIframe.iframe);
node = outer;
}
node.style.zIndex = 999;
return node;
},
onDragStart: function(e){
dojo.html.clearSelection();
this.scrollOffset = dojo.html.getScroll().offset;
this.dragStartPosition = dojo.html.getAbsolutePosition(this.domNode, true);
this.dragOffset = {y: this.dragStartPosition.y - e.pageY,
x: this.dragStartPosition.x - e.pageX};
this.dragClone = this.createDragNode();
this.containingBlockPosition = this.domNode.offsetParent ?
dojo.html.getAbsolutePosition(this.domNode.offsetParent, true) : {x:0, y:0};
if (this.constrainToContainer) {
this.constraints = this.getConstraints();
}
// set up for dragging
with(this.dragClone.style){
position = "absolute";
top = this.dragOffset.y + e.pageY + "px";
left = this.dragOffset.x + e.pageX + "px";
}
dojo.body().appendChild(this.dragClone);
// shortly the browser will fire an onClick() event,
// but since this was really a drag, just squelch it
dojo.event.connect(this.domNode, "onclick", this, "squelchOnClick");
dojo.event.topic.publish('dragStart', { source: this } );
},
/** Return min/max x/y (relative to document.body) for this object) **/
getConstraints: function() {
if (this.constrainingContainer.nodeName.toLowerCase() == 'body') {
var viewport = dojo.html.getViewport();
var width = viewport.width;
var height = viewport.height;
var x = 0;
var y = 0;
} else {
var content = dojo.html.getContentBox(this.constrainingContainer);
width = content.width;
height = content.height;
x =
this.containingBlockPosition.x +
dojo.html.getPixelValue(this.constrainingContainer, "padding-left", true) +
dojo.html.getBorderExtent(this.constrainingContainer, "left");
y =
this.containingBlockPosition.y +
dojo.html.getPixelValue(this.constrainingContainer, "padding-top", true) +
dojo.html.getBorderExtent(this.constrainingContainer, "top");
table.appendChild(node);
}
var mb = dojo.html.getMarginBox(this.domNode);
return {
minX: x,
minY: y,
maxX: x + width - mb.width,
maxY: y + height - mb.height
var tmpSrcTr = ((isTr) ? this.domNode : this.domNode.firstChild);
var tmpDstTr = ((isTr) ? node : node.firstChild);
var domTds = tmpSrcTr.childNodes;
var cloneTds = tmpDstTr.childNodes;
for (var i = 0; i < domTds.length; i++) {
if ((cloneTds[i]) && (cloneTds[i].style)) {
cloneTds[i].style.width = dojo.html.getContentBox(domTds[i]).width + "px";
}
}
},
updateDragOffset: function() {
node = table;
}
if ((dojo.render.html.ie55 || dojo.render.html.ie60) && this.createIframe) {
with (node.style) {
top = "0px";
left = "0px";
}
var outer = document.createElement("div");
outer.appendChild(node);
this.bgIframe = new dojo.html.BackgroundIframe(outer);
outer.appendChild(this.bgIframe.iframe);
node = outer;
}
node.style.zIndex = 999;
return node;
}, onDragStart:function (e) {
dojo.html.clearSelection();
this.scrollOffset = dojo.html.getScroll().offset;
this.dragStartPosition = dojo.html.getAbsolutePosition(this.domNode, true);
this.dragOffset = {y:this.dragStartPosition.y - e.pageY, x:this.dragStartPosition.x - e.pageX};
this.dragClone = this.createDragNode();
this.containingBlockPosition = this.domNode.offsetParent ? dojo.html.getAbsolutePosition(this.domNode.offsetParent, true) : {x:0, y:0};
if (this.constrainToContainer) {
this.constraints = this.getConstraints();
}
with (this.dragClone.style) {
position = "absolute";
top = this.dragOffset.y + e.pageY + "px";
left = this.dragOffset.x + e.pageX + "px";
}
dojo.body().appendChild(this.dragClone);
dojo.event.topic.publish("dragStart", {source:this});
}, getConstraints:function () {
if (this.constrainingContainer.nodeName.toLowerCase() == "body") {
var viewport = dojo.html.getViewport();
var width = viewport.width;
var height = viewport.height;
var scroll = dojo.html.getScroll().offset;
if(scroll.y != this.scrollOffset.y) {
var diff = scroll.y - this.scrollOffset.y;
this.dragOffset.y += diff;
this.scrollOffset.y = scroll.y;
var x = scroll.x;
var y = scroll.y;
} else {
var content = dojo.html.getContentBox(this.constrainingContainer);
width = content.width;
height = content.height;
x = this.containingBlockPosition.x + dojo.html.getPixelValue(this.constrainingContainer, "padding-left", true) + dojo.html.getBorderExtent(this.constrainingContainer, "left");
y = this.containingBlockPosition.y + dojo.html.getPixelValue(this.constrainingContainer, "padding-top", true) + dojo.html.getBorderExtent(this.constrainingContainer, "top");
}
var mb = dojo.html.getMarginBox(this.domNode);
return {minX:x, minY:y, maxX:x + width - mb.width, maxY:y + height - mb.height};
}, updateDragOffset:function () {
var scroll = dojo.html.getScroll().offset;
if (scroll.y != this.scrollOffset.y) {
var diff = scroll.y - this.scrollOffset.y;
this.dragOffset.y += diff;
this.scrollOffset.y = scroll.y;
}
if (scroll.x != this.scrollOffset.x) {
var diff = scroll.x - this.scrollOffset.x;
this.dragOffset.x += diff;
this.scrollOffset.x = scroll.x;
}
}, onDragMove:function (e) {
this.updateDragOffset();
var x = this.dragOffset.x + e.pageX;
var y = this.dragOffset.y + e.pageY;
if (this.constrainToContainer) {
if (x < this.constraints.minX) {
x = this.constraints.minX;
}
if(scroll.x != this.scrollOffset.x) {
var diff = scroll.x - this.scrollOffset.x;
this.dragOffset.x += diff;
this.scrollOffset.x = scroll.x;
if (y < this.constraints.minY) {
y = this.constraints.minY;
}
},
/** Moves the node to follow the mouse */
onDragMove: function(e){
this.updateDragOffset();
var x = this.dragOffset.x + e.pageX;
var y = this.dragOffset.y + e.pageY;
if (this.constrainToContainer) {
if (x < this.constraints.minX) { x = this.constraints.minX; }
if (y < this.constraints.minY) { y = this.constraints.minY; }
if (x > this.constraints.maxX) { x = this.constraints.maxX; }
if (y > this.constraints.maxY) { y = this.constraints.maxY; }
if (x > this.constraints.maxX) {
x = this.constraints.maxX;
}
this.setAbsolutePosition(x, y);
dojo.event.topic.publish('dragMove', { source: this } );
},
/**
* Set the position of the drag clone. (x,y) is relative to <body>.
*/
setAbsolutePosition: function(x, y){
// The drag clone is attached to document.body so this is trivial
if(!this.disableY) { this.dragClone.style.top = y + "px"; }
if(!this.disableX) { this.dragClone.style.left = x + "px"; }
},
/**
* If the drag operation returned a success we reomve the clone of
* ourself from the original position. If the drag operation returned
* failure we slide back over to where we came from and end the operation
* with a little grace.
*/
onDragEnd: function(e){
switch(e.dragStatus){
case "dropSuccess":
dojo.html.removeNode(this.dragClone);
this.dragClone = null;
break;
case "dropFailure": // slide back to the start
var startCoords = dojo.html.getAbsolutePosition(this.dragClone, true);
// offset the end so the effect can be seen
var endCoords = { left: this.dragStartPosition.x + 1,
top: this.dragStartPosition.y + 1};
// animate
var anim = dojo.lfx.slideTo(this.dragClone, endCoords, 500, dojo.lfx.easeOut);
var dragObject = this;
dojo.event.connect(anim, "onEnd", function (e) {
// pause for a second (not literally) and disappear
dojo.lang.setTimeout(function() {
dojo.html.removeNode(dragObject.dragClone);
// Allow drag clone to be gc'ed
dragObject.dragClone = null;
},
200);
});
anim.play();
break;
}
dojo.event.topic.publish('dragEnd', { source: this } );
},
squelchOnClick: function(e){
// squelch this onClick() event because it's the result of a drag (it's not a real click)
dojo.event.browser.stopEvent(e);
// disconnect after a short delay to prevent "Null argument to unrollAdvice()" warning
dojo.lang.setTimeout(function() {
dojo.event.disconnect(this.domNode, "onclick", this, "squelchOnClick");
},50);
},
constrainTo: function(container) {
this.constrainToContainer=true;
if (container) {
this.constrainingContainer = container;
} else {
this.constrainingContainer = this.domNode.parentNode;
if (y > this.constraints.maxY) {
y = this.constraints.maxY;
}
}
}, function(node, type){
this.setAbsolutePosition(x, y);
dojo.event.topic.publish("dragMove", {source:this});
}, setAbsolutePosition:function (x, y) {
if (!this.disableY) {
this.dragClone.style.top = y + "px";
}
if (!this.disableX) {
this.dragClone.style.left = x + "px";
}
}, onDragEnd:function (e) {
switch (e.dragStatus) {
case "dropSuccess":
dojo.html.removeNode(this.dragClone);
this.dragClone = null;
break;
case "dropFailure":
var startCoords = dojo.html.getAbsolutePosition(this.dragClone, true);
var endCoords = {left:this.dragStartPosition.x + 1, top:this.dragStartPosition.y + 1};
var anim = dojo.lfx.slideTo(this.dragClone, endCoords, 300);
var dragObject = this;
dojo.event.connect(anim, "onEnd", function (e) {
dojo.html.removeNode(dragObject.dragClone);
dragObject.dragClone = null;
});
anim.play();
break;
}
dojo.event.topic.publish("dragEnd", {source:this});
}, constrainTo:function (container) {
this.constrainToContainer = true;
if (container) {
this.constrainingContainer = container;
} else {
this.constrainingContainer = this.domNode.parentNode;
}
}}, function (node, type) {
this.domNode = dojo.byId(node);
this.type = type;
this.constrainToContainer = false;
this.dragSource = null;
dojo.dnd.DragObject.prototype.register.call(this);
});
dojo.declare("dojo.dnd.HtmlDropTarget", dojo.dnd.DropTarget, {
vertical: false,
onDragOver: function(e){
if(!this.accepts(e.dragObjects)){ return false; }
// cache the positions of the child nodes
this.childBoxes = [];
for (var i = 0, child; i < this.domNode.childNodes.length; i++) {
child = this.domNode.childNodes[i];
if (child.nodeType != dojo.html.ELEMENT_NODE) { continue; }
var pos = dojo.html.getAbsolutePosition(child, true);
var inner = dojo.html.getBorderBox(child);
this.childBoxes.push({top: pos.y, bottom: pos.y+inner.height,
left: pos.x, right: pos.x+inner.width, height: inner.height,
width: inner.width, node: child});
}
// TODO: use dummy node
return true;
},
_getNodeUnderMouse: function(e){
// find the child
for (var i = 0, child; i < this.childBoxes.length; i++) {
with (this.childBoxes[i]) {
if (e.pageX >= left && e.pageX <= right &&
e.pageY >= top && e.pageY <= bottom) { return i; }
}
}
return -1;
},
createDropIndicator: function() {
this.dropIndicator = document.createElement("div");
with (this.dropIndicator.style) {
position = "absolute";
zIndex = 999;
if(this.vertical){
borderLeftWidth = "1px";
borderLeftColor = "black";
borderLeftStyle = "solid";
height = dojo.html.getBorderBox(this.domNode).height + "px";
top = dojo.html.getAbsolutePosition(this.domNode, true).y + "px";
}else{
borderTopWidth = "1px";
borderTopColor = "black";
borderTopStyle = "solid";
width = dojo.html.getBorderBox(this.domNode).width + "px";
left = dojo.html.getAbsolutePosition(this.domNode, true).x + "px";
}
}
},
onDragMove: function(e, dragObjects){
var i = this._getNodeUnderMouse(e);
if(!this.dropIndicator){
this.createDropIndicator();
}
var gravity = this.vertical ? dojo.html.gravity.WEST : dojo.html.gravity.NORTH;
var hide = false;
if(i < 0) {
if(this.childBoxes.length) {
var before = (dojo.html.gravity(this.childBoxes[0].node, e) & gravity);
if(before){ hide = true; }
} else {
var before = true;
}
} else {
var child = this.childBoxes[i];
var before = (dojo.html.gravity(child.node, e) & gravity);
if(child.node === dragObjects[0].dragSource.domNode){
hide = true;
}else{
var currentPosChild = before ?
(i>0?this.childBoxes[i-1]:child) :
(i<this.childBoxes.length-1?this.childBoxes[i+1]:child);
if(currentPosChild.node === dragObjects[0].dragSource.domNode){
hide = true;
}
}
}
if(hide){
this.dropIndicator.style.display="none";
return;
}else{
this.dropIndicator.style.display="";
}
this.placeIndicator(e, dragObjects, i, before);
if(!dojo.html.hasParent(this.dropIndicator)) {
dojo.body().appendChild(this.dropIndicator);
}
},
/**
* Position the horizontal line that indicates "insert between these two items"
*/
placeIndicator: function(e, dragObjects, boxIndex, before) {
var targetProperty = this.vertical ? "left" : "top";
var child;
if (boxIndex < 0) {
if (this.childBoxes.length) {
child = before ? this.childBoxes[0]
: this.childBoxes[this.childBoxes.length - 1];
} else {
this.dropIndicator.style[targetProperty] = dojo.html.getAbsolutePosition(this.domNode, true)[this.vertical?"x":"y"] + "px";
}
} else {
child = this.childBoxes[boxIndex];
}
if(child){
this.dropIndicator.style[targetProperty] = (before ? child[targetProperty] : child[this.vertical?"right":"bottom"]) + "px";
if(this.vertical){
this.dropIndicator.style.height = child.height + "px";
this.dropIndicator.style.top = child.top + "px";
}else{
this.dropIndicator.style.width = child.width + "px";
this.dropIndicator.style.left = child.left + "px";
}
}
},
onDragOut: function(e) {
if(this.dropIndicator) {
dojo.html.removeNode(this.dropIndicator);
delete this.dropIndicator;
}
},
/**
* Inserts the DragObject as a child of this node relative to the
* position of the mouse.
*
* @return true if the DragObject was inserted, false otherwise
*/
onDrop: function(e){
this.onDragOut(e);
var i = this._getNodeUnderMouse(e);
var gravity = this.vertical ? dojo.html.gravity.WEST : dojo.html.gravity.NORTH;
if (i < 0) {
if (this.childBoxes.length) {
if (dojo.html.gravity(this.childBoxes[0].node, e) & gravity) {
return this.insert(e, this.childBoxes[0].node, "before");
} else {
return this.insert(e, this.childBoxes[this.childBoxes.length-1].node, "after");
}
}
return this.insert(e, this.domNode, "append");
}
var child = this.childBoxes[i];
if (dojo.html.gravity(child.node, e) & gravity) {
return this.insert(e, child.node, "before");
} else {
return this.insert(e, child.node, "after");
}
},
insert: function(e, refNode, position) {
var node = e.dragObject.domNode;
if(position == "before") {
return dojo.html.insertBefore(node, refNode);
} else if(position == "after") {
return dojo.html.insertAfter(node, refNode);
} else if(position == "append") {
refNode.appendChild(node);
return true;
}
dojo.declare("dojo.dnd.HtmlDropTarget", dojo.dnd.DropTarget, {vertical:false, onDragOver:function (e) {
if (!this.accepts(e.dragObjects)) {
return false;
}
}, function(node, types){
if (arguments.length == 0) { return; }
this.childBoxes = [];
for (var i = 0, child; i < this.domNode.childNodes.length; i++) {
child = this.domNode.childNodes[i];
if (child.nodeType != dojo.html.ELEMENT_NODE) {
continue;
}
var pos = dojo.html.getAbsolutePosition(child, true);
var inner = dojo.html.getBorderBox(child);
this.childBoxes.push({top:pos.y, bottom:pos.y + inner.height, left:pos.x, right:pos.x + inner.width, height:inner.height, width:inner.width, node:child});
}
return true;
}, _getNodeUnderMouse:function (e) {
for (var i = 0, child; i < this.childBoxes.length; i++) {
with (this.childBoxes[i]) {
if (e.pageX >= left && e.pageX <= right && e.pageY >= top && e.pageY <= bottom) {
return i;
}
}
}
return -1;
}, createDropIndicator:function () {
this.dropIndicator = document.createElement("div");
with (this.dropIndicator.style) {
position = "absolute";
zIndex = 999;
if (this.vertical) {
borderLeftWidth = "1px";
borderLeftColor = "black";
borderLeftStyle = "solid";
height = dojo.html.getBorderBox(this.domNode).height + "px";
top = dojo.html.getAbsolutePosition(this.domNode, true).y + "px";
} else {
borderTopWidth = "1px";
borderTopColor = "black";
borderTopStyle = "solid";
width = dojo.html.getBorderBox(this.domNode).width + "px";
left = dojo.html.getAbsolutePosition(this.domNode, true).x + "px";
}
}
}, onDragMove:function (e, dragObjects) {
var i = this._getNodeUnderMouse(e);
if (!this.dropIndicator) {
this.createDropIndicator();
}
var gravity = this.vertical ? dojo.html.gravity.WEST : dojo.html.gravity.NORTH;
var hide = false;
if (i < 0) {
if (this.childBoxes.length) {
var before = (dojo.html.gravity(this.childBoxes[0].node, e) & gravity);
if (before) {
hide = true;
}
} else {
var before = true;
}
} else {
var child = this.childBoxes[i];
var before = (dojo.html.gravity(child.node, e) & gravity);
if (child.node === dragObjects[0].dragSource.domNode) {
hide = true;
} else {
var currentPosChild = before ? (i > 0 ? this.childBoxes[i - 1] : child) : (i < this.childBoxes.length - 1 ? this.childBoxes[i + 1] : child);
if (currentPosChild.node === dragObjects[0].dragSource.domNode) {
hide = true;
}
}
}
if (hide) {
this.dropIndicator.style.display = "none";
return;
} else {
this.dropIndicator.style.display = "";
}
this.placeIndicator(e, dragObjects, i, before);
if (!dojo.html.hasParent(this.dropIndicator)) {
dojo.body().appendChild(this.dropIndicator);
}
}, placeIndicator:function (e, dragObjects, boxIndex, before) {
var targetProperty = this.vertical ? "left" : "top";
var child;
if (boxIndex < 0) {
if (this.childBoxes.length) {
child = before ? this.childBoxes[0] : this.childBoxes[this.childBoxes.length - 1];
} else {
this.dropIndicator.style[targetProperty] = dojo.html.getAbsolutePosition(this.domNode, true)[this.vertical ? "x" : "y"] + "px";
}
} else {
child = this.childBoxes[boxIndex];
}
if (child) {
this.dropIndicator.style[targetProperty] = (before ? child[targetProperty] : child[this.vertical ? "right" : "bottom"]) + "px";
if (this.vertical) {
this.dropIndicator.style.height = child.height + "px";
this.dropIndicator.style.top = child.top + "px";
} else {
this.dropIndicator.style.width = child.width + "px";
this.dropIndicator.style.left = child.left + "px";
}
}
}, onDragOut:function (e) {
if (this.dropIndicator) {
dojo.html.removeNode(this.dropIndicator);
delete this.dropIndicator;
}
}, onDrop:function (e) {
this.onDragOut(e);
var i = this._getNodeUnderMouse(e);
var gravity = this.vertical ? dojo.html.gravity.WEST : dojo.html.gravity.NORTH;
if (i < 0) {
if (this.childBoxes.length) {
if (dojo.html.gravity(this.childBoxes[0].node, e) & gravity) {
return this.insert(e, this.childBoxes[0].node, "before");
} else {
return this.insert(e, this.childBoxes[this.childBoxes.length - 1].node, "after");
}
}
return this.insert(e, this.domNode, "append");
}
var child = this.childBoxes[i];
if (dojo.html.gravity(child.node, e) & gravity) {
return this.insert(e, child.node, "before");
} else {
return this.insert(e, child.node, "after");
}
}, insert:function (e, refNode, position) {
var node = e.dragObject.domNode;
if (position == "before") {
return dojo.html.insertBefore(node, refNode);
} else {
if (position == "after") {
return dojo.html.insertAfter(node, refNode);
} else {
if (position == "append") {
refNode.appendChild(node);
return true;
}
}
}
return false;
}}, function (node, types) {
if (arguments.length == 0) {
return;
}
this.domNode = dojo.byId(node);
dojo.dnd.DropTarget.call(this);
if(types && dojo.lang.isString(types)) {
if (types && dojo.lang.isString(types)) {
types = [types];
}
this.acceptedTypes = types || [];
dojo.dnd.dragManager.registerDropTarget(this);
});
@@ -10,76 +10,59 @@
dojo.provide("dojo.dnd.HtmlDragCopy");
dojo.require("dojo.dnd.*");
dojo.declare("dojo.dnd.HtmlDragCopySource", dojo.dnd.HtmlDragSource,
function(node, type, copyOnce){
this.copyOnce = copyOnce;
this.makeCopy = true;
},
{
onDragStart: function(){
var dragObj = new dojo.dnd.HtmlDragCopyObject(this.dragObject, this.type, this);
if(this.dragClass) { dragObj.dragClass = this.dragClass; }
if (this.constrainToContainer) {
dragObj.constrainTo(this.constrainingContainer || this.domNode.parentNode);
}
return dragObj;
},
onSelected: function() {
for (var i=0; i<this.dragObjects.length; i++) {
dojo.dnd.dragManager.selectedSources.push(new dojo.dnd.HtmlDragCopySource(this.dragObjects[i]));
}
dojo.declare("dojo.dnd.HtmlDragCopySource", dojo.dnd.HtmlDragSource, function (node, type, copyOnce) {
this.copyOnce = copyOnce;
this.makeCopy = true;
}, {onDragStart:function () {
var dragObj = new dojo.dnd.HtmlDragCopyObject(this.dragObject, this.type, this);
if (this.dragClass) {
dragObj.dragClass = this.dragClass;
}
});
dojo.declare("dojo.dnd.HtmlDragCopyObject", dojo.dnd.HtmlDragObject,
function(dragObject, type, source){
this.copySource = source;
},
{
onDragStart: function(e) {
dojo.dnd.HtmlDragCopyObject.superclass.onDragStart.apply(this, arguments);
if(this.copySource.makeCopy) {
this.sourceNode = this.domNode;
this.domNode = this.domNode.cloneNode(true);
}
},
onDragEnd: function(e){
switch(e.dragStatus){
case "dropFailure": // slide back to the start
var startCoords = dojo.html.getAbsolutePosition(this.dragClone, true);
// offset the end so the effect can be seen
var endCoords = { left: this.dragStartPosition.x + 1,
top: this.dragStartPosition.y + 1};
// animate
var anim = dojo.lfx.slideTo(this.dragClone, endCoords, 500, dojo.lfx.easeOut);
var dragObject = this;
dojo.event.connect(anim, "onEnd", function (e) {
// pause for a second (not literally) and disappear
dojo.lang.setTimeout(function() {
dojo.html.removeNode(dragObject.dragClone);
dragObject.dragClone = null;
if(dragObject.copySource.makeCopy) {
dojo.html.removeNode(dragObject.domNode);
dragObject.domNode = dragObject.sourceNode;
dragObject.sourceNode = null;
}
},
200);
});
anim.play();
dojo.event.topic.publish('dragEnd', { source: this } );
return;
}
dojo.dnd.HtmlDragCopyObject.superclass.onDragEnd.apply(this, arguments);
this.copySource.dragObject = this.domNode;
if(this.copySource.copyOnce){
this.copySource.makeCopy = false;
}
new dojo.dnd.HtmlDragCopySource(this.sourceNode, this.type, this.copySource.copyOnce);
this.sourceNode = null;
if (this.constrainToContainer) {
dragObj.constrainTo(this.constrainingContainer || this.domNode.parentNode);
}
});
return dragObj;
}, onSelected:function () {
for (var i = 0; i < this.dragObjects.length; i++) {
dojo.dnd.dragManager.selectedSources.push(new dojo.dnd.HtmlDragCopySource(this.dragObjects[i]));
}
}});
dojo.declare("dojo.dnd.HtmlDragCopyObject", dojo.dnd.HtmlDragObject, function (dragObject, type, source) {
this.copySource = source;
}, {onDragStart:function (e) {
dojo.dnd.HtmlDragCopyObject.superclass.onDragStart.apply(this, arguments);
if (this.copySource.makeCopy) {
this.sourceNode = this.domNode;
this.domNode = this.domNode.cloneNode(true);
}
}, onDragEnd:function (e) {
switch (e.dragStatus) {
case "dropFailure":
var startCoords = dojo.html.getAbsolutePosition(this.dragClone, true);
var endCoords = {left:this.dragStartPosition.x + 1, top:this.dragStartPosition.y + 1};
var anim = dojo.lfx.slideTo(this.dragClone, endCoords, 500, dojo.lfx.easeOut);
var dragObject = this;
dojo.event.connect(anim, "onEnd", function (e) {
dojo.lang.setTimeout(function () {
dojo.html.removeNode(dragObject.dragClone);
dragObject.dragClone = null;
if (dragObject.copySource.makeCopy) {
dojo.html.removeNode(dragObject.domNode);
dragObject.domNode = dragObject.sourceNode;
dragObject.sourceNode = null;
}
}, 200);
});
anim.play();
dojo.event.topic.publish("dragEnd", {source:this});
return;
}
dojo.dnd.HtmlDragCopyObject.superclass.onDragEnd.apply(this, arguments);
this.copySource.dragObject = this.domNode;
if (this.copySource.copyOnce) {
this.copySource.makeCopy = false;
}
new dojo.dnd.HtmlDragCopySource(this.sourceNode, this.type, this.copySource.copyOnce);
this.sourceNode = null;
}});
@@ -14,492 +14,280 @@ dojo.require("dojo.event.*");
dojo.require("dojo.lang.array");
dojo.require("dojo.html.common");
dojo.require("dojo.html.layout");
// NOTE: there will only ever be a single instance of HTMLDragManager, so it's
// safe to use prototype properties for book-keeping.
dojo.declare("dojo.dnd.HtmlDragManager", dojo.dnd.DragManager, {
/**
* There are several sets of actions that the DnD code cares about in the
* HTML context:
* 1.) mouse-down ->
* (draggable selection)
* (dragObject generation)
* mouse-move ->
* (draggable movement)
* (droppable detection)
* (inform droppable)
* (inform dragObject)
* mouse-up
* (inform/destroy dragObject)
* (inform draggable)
* (inform droppable)
* 2.) mouse-down -> mouse-down
* (click-hold context menu)
* 3.) mouse-click ->
* (draggable selection)
* shift-mouse-click ->
* (augment draggable selection)
* mouse-down ->
* (dragObject generation)
* mouse-move ->
* (draggable movement)
* (droppable detection)
* (inform droppable)
* (inform dragObject)
* mouse-up
* (inform draggable)
* (inform droppable)
* 4.) mouse-up
* (clobber draggable selection)
*/
disabled: false, // to kill all dragging!
nestedTargets: false,
mouseDownTimer: null, // used for click-hold operations
dsCounter: 0,
dsPrefix: "dojoDragSource",
// dimension calculation cache for use durring drag
dropTargetDimensions: [],
currentDropTarget: null,
// currentDropTargetPoints: null,
previousDropTarget: null,
_dragTriggered: false,
selectedSources: [],
dragObjects: [],
// mouse position properties
currentX: null,
currentY: null,
lastX: null,
lastY: null,
mouseDownX: null,
mouseDownY: null,
threshold: 7,
dropAcceptable: false,
cancelEvent: function(e){ e.stopPropagation(); e.preventDefault();},
// method over-rides
registerDragSource: function(ds){
//dojo.profile.start("register DragSource");
if(ds["domNode"]){
// FIXME: dragSource objects SHOULD have some sort of property that
// references their DOM node, we shouldn't just be passing nodes and
// expecting it to work.
//dojo.profile.start("register DragSource 1");
var dp = this.dsPrefix;
var dpIdx = dp+"Idx_"+(this.dsCounter++);
ds.dragSourceId = dpIdx;
this.dragSources[dpIdx] = ds;
ds.domNode.setAttribute(dp, dpIdx);
//dojo.profile.end("register DragSource 1");
//dojo.profile.start("register DragSource 2");
// so we can drag links
if(dojo.render.html.ie){
//dojo.profile.start("register DragSource IE");
dojo.event.browser.addListener(ds.domNode, "ondragstart", this.cancelEvent);
// terribly slow
//dojo.event.connect(ds.domNode, "ondragstart", this.cancelEvent);
//dojo.profile.end("register DragSource IE");
}
//dojo.profile.end("register DragSource 2");
dojo.declare("dojo.dnd.HtmlDragManager", dojo.dnd.DragManager, {disabled:false, nestedTargets:false, mouseDownTimer:null, dsCounter:0, dsPrefix:"dojoDragSource", dropTargetDimensions:[], currentDropTarget:null, previousDropTarget:null, _dragTriggered:false, selectedSources:[], dragObjects:[], dragSources:[], dropTargets:[], currentX:null, currentY:null, lastX:null, lastY:null, mouseDownX:null, mouseDownY:null, threshold:7, dropAcceptable:false, cancelEvent:function (e) {
e.stopPropagation();
e.preventDefault();
}, registerDragSource:function (ds) {
if (ds["domNode"]) {
var dp = this.dsPrefix;
var dpIdx = dp + "Idx_" + (this.dsCounter++);
ds.dragSourceId = dpIdx;
this.dragSources[dpIdx] = ds;
ds.domNode.setAttribute(dp, dpIdx);
if (dojo.render.html.ie) {
dojo.event.browser.addListener(ds.domNode, "ondragstart", this.cancelEvent);
}
//dojo.profile.end("register DragSource");
},
unregisterDragSource: function(ds){
if (ds["domNode"]){
var dp = this.dsPrefix;
var dpIdx = ds.dragSourceId;
delete ds.dragSourceId;
delete this.dragSources[dpIdx];
ds.domNode.setAttribute(dp, null);
if(dojo.render.html.ie){
dojo.event.browser.removeListener(ds.domNode, "ondragstart", this.cancelEvent);
}
}
}, unregisterDragSource:function (ds) {
if (ds["domNode"]) {
var dp = this.dsPrefix;
var dpIdx = ds.dragSourceId;
delete ds.dragSourceId;
delete this.dragSources[dpIdx];
ds.domNode.setAttribute(dp, null);
if (dojo.render.html.ie) {
dojo.event.browser.removeListener(ds.domNode, "ondragstart", this.cancelEvent);
}
},
registerDropTarget: function(dt){
this.dropTargets.push(dt);
},
unregisterDropTarget: function(dt){
var index = dojo.lang.find(this.dropTargets, dt, true);
if (index>=0) {
this.dropTargets.splice(index, 1);
}
},
/**
* Get the DOM element that is meant to drag.
* Loop through the parent nodes of the event target until
* the element is found that was created as a DragSource and
* return it.
*
* @param event object The event for which to get the drag source.
*/
getDragSource: function(e){
var tn = e.target;
if(tn === dojo.body()){ return; }
var ta = dojo.html.getAttribute(tn, this.dsPrefix);
while((!ta)&&(tn)){
tn = tn.parentNode;
if((!tn)||(tn === dojo.body())){ return; }
ta = dojo.html.getAttribute(tn, this.dsPrefix);
}
return this.dragSources[ta];
},
onKeyDown: function(e){
},
onMouseDown: function(e){
if(this.disabled) { return; }
// only begin on left click
if(dojo.render.html.ie) {
if(e.button != 1) { return; }
} else if(e.which != 1) {
}
}, registerDropTarget:function (dt) {
this.dropTargets.push(dt);
}, unregisterDropTarget:function (dt) {
var index = dojo.lang.find(this.dropTargets, dt, true);
if (index >= 0) {
this.dropTargets.splice(index, 1);
}
}, getDragSource:function (e) {
var tn = e.target;
if (tn === dojo.body()) {
return;
}
var ta = dojo.html.getAttribute(tn, this.dsPrefix);
while ((!ta) && (tn)) {
tn = tn.parentNode;
if ((!tn) || (tn === dojo.body())) {
return;
}
var target = e.target.nodeType == dojo.html.TEXT_NODE ?
e.target.parentNode : e.target;
// do not start drag involvement if the user is interacting with
// a form element.
if(dojo.html.isTag(target, "button", "textarea", "input", "select", "option")) {
ta = dojo.html.getAttribute(tn, this.dsPrefix);
}
return this.dragSources[ta];
}, onKeyDown:function (e) {
}, onMouseDown:function (e) {
if (this.disabled) {
return;
}
if (dojo.render.html.ie) {
if (e.button != 1) {
return;
}
// find a selection object, if one is a parent of the source node
var ds = this.getDragSource(e);
// this line is important. if we aren't selecting anything then
// we need to return now, so preventDefault() isn't called, and thus
// the event is propogated to other handling code
if(!ds){ return; }
if(!dojo.lang.inArray(this.selectedSources, ds)){
this.selectedSources.push(ds);
ds.onSelected();
}
this.mouseDownX = e.pageX;
this.mouseDownY = e.pageY;
// Must stop the mouse down from being propogated, or otherwise can't
// drag links in firefox.
// WARNING: preventing the default action on all mousedown events
// prevents user interaction with the contents.
e.preventDefault();
dojo.event.connect(document, "onmousemove", this, "onMouseMove");
},
onMouseUp: function(e, cancel){
// if we aren't dragging then ignore the mouse-up
// (in particular, don't call preventDefault(), because other
// code may need to process this event)
if(this.selectedSources.length==0){
} else {
if (e.which != 1) {
return;
}
this.mouseDownX = null;
this.mouseDownY = null;
this._dragTriggered = false;
// e.preventDefault();
e.dragSource = this.dragSource;
// let ctrl be used for multiselect or another action
// if I use same key to trigger treeV3 node selection and here,
// I have bugs with drag'n'drop. why ?? no idea..
if((!e.shiftKey)&&(!e.ctrlKey)){
//if(!e.shiftKey){
if(this.currentDropTarget) {
this.currentDropTarget.onDropStart();
}
dojo.lang.forEach(this.dragObjects, function(tempDragObj){
var ret = null;
if(!tempDragObj){ return; }
if(this.currentDropTarget) {
e.dragObject = tempDragObj;
// NOTE: we can't get anything but the current drop target
// here since the drag shadow blocks mouse-over events.
// This is probelematic for dropping "in" something
var ce = this.currentDropTarget.domNode.childNodes;
if(ce.length > 0){
e.dropTarget = ce[0];
while(e.dropTarget == tempDragObj.domNode){
e.dropTarget = e.dropTarget.nextSibling;
}
}else{
e.dropTarget = this.currentDropTarget.domNode;
}
if(this.dropAcceptable){
ret = this.currentDropTarget.onDrop(e);
}else{
this.currentDropTarget.onDragOut(e);
}
}
e.dragStatus = this.dropAcceptable && ret ? "dropSuccess" : "dropFailure";
// decouple the calls for onDragEnd, so they don't block the execution here
// ie. if the onDragEnd would call an alert, the execution here is blocked until the
// user has confirmed the alert box and then the rest of the dnd code is executed
// while the mouse doesnt "hold" the dragged object anymore ... and so on
dojo.lang.delayThese([
function() {
// in FF1.5 this throws an exception, see
// http://dojotoolkit.org/pipermail/dojo-interest/2006-April/006751.html
try{
tempDragObj.dragSource.onDragEnd(e)
} catch(err) {
// since the problem seems passing e, we just copy all
// properties and try the copy ...
var ecopy = {};
for (var i in e) {
if (i=="type") { // the type property contains the exception, no idea why...
ecopy.type = "mouseup";
continue;
}
ecopy[i] = e[i];
}
tempDragObj.dragSource.onDragEnd(ecopy);
}
}
, function() {tempDragObj.onDragEnd(e)}]);
}, this);
this.selectedSources = [];
this.dragObjects = [];
this.dragSource = null;
if(this.currentDropTarget) {
this.currentDropTarget.onDropEnd();
}
} else {
//dojo.debug("special click");
}
var target = e.target.nodeType == dojo.html.TEXT_NODE ? e.target.parentNode : e.target;
if (dojo.html.isTag(target, "button", "textarea", "input", "select", "option")) {
return;
}
var ds = this.getDragSource(e);
if (!ds) {
return;
}
if (!dojo.lang.inArray(this.selectedSources, ds)) {
this.selectedSources.push(ds);
ds.onSelected();
}
this.mouseDownX = e.pageX;
this.mouseDownY = e.pageY;
e.preventDefault();
dojo.event.connect(document, "onmousemove", this, "onMouseMove");
}, onMouseUp:function (e, cancel) {
if (this.selectedSources.length == 0) {
return;
}
this.mouseDownX = null;
this.mouseDownY = null;
this._dragTriggered = false;
e.dragSource = this.dragSource;
if ((!e.shiftKey) && (!e.ctrlKey)) {
if (this.currentDropTarget) {
this.currentDropTarget.onDropStart();
}
dojo.event.disconnect(document, "onmousemove", this, "onMouseMove");
this.currentDropTarget = null;
},
onScroll: function(){
//dojo.profile.start("DNDManager updateoffset");
for(var i = 0; i < this.dragObjects.length; i++) {
if(this.dragObjects[i].updateDragOffset) {
this.dragObjects[i].updateDragOffset();
}
}
//dojo.profile.end("DNDManager updateoffset");
// TODO: do not recalculate, only adjust coordinates
if (this.dragObjects.length) {
this.cacheTargetLocations();
}
},
_dragStartDistance: function(x, y){
if((!this.mouseDownX)||(!this.mouseDownX)){
return;
}
var dx = Math.abs(x-this.mouseDownX);
var dx2 = dx*dx;
var dy = Math.abs(y-this.mouseDownY);
var dy2 = dy*dy;
return parseInt(Math.sqrt(dx2+dy2), 10);
},
cacheTargetLocations: function(){
dojo.profile.start("cacheTargetLocations");
this.dropTargetDimensions = [];
dojo.lang.forEach(this.dropTargets, function(tempTarget){
var tn = tempTarget.domNode;
//only cache dropTarget which can accept current dragSource
if(!tn || dojo.lang.find(tempTarget.acceptedTypes, this.dragSource.type) < 0){ return; }
var abs = dojo.html.getAbsolutePosition(tn, true);
var bb = dojo.html.getBorderBox(tn);
this.dropTargetDimensions.push([
[abs.x, abs.y], // upper-left
// lower-right
[ abs.x+bb.width, abs.y+bb.height ],
tempTarget
]);
//dojo.debug("Cached for "+tempTarget)
}, this);
dojo.profile.end("cacheTargetLocations");
//dojo.debug("Cache locations")
},
onMouseMove: function(e){
if((dojo.render.html.ie)&&(e.button != 1)){
// Oooops - mouse up occurred - e.g. when mouse was not over the
// window. I don't think we can detect this for FF - but at least
// we can be nice in IE.
this.currentDropTarget = null;
this.onMouseUp(e, true);
return;
}
// if we've got some sources, but no drag objects, we need to send
// onDragStart to all the right parties and get things lined up for
// drop target detection
if( (this.selectedSources.length)&&
(!this.dragObjects.length) ){
var dx;
var dy;
if(!this._dragTriggered){
this._dragTriggered = (this._dragStartDistance(e.pageX, e.pageY) > this.threshold);
if(!this._dragTriggered){ return; }
dx = e.pageX - this.mouseDownX;
dy = e.pageY - this.mouseDownY;
}
// the first element is always our dragSource, if there are multiple
// selectedSources (elements that move along) then the first one is the master
// and for it the events will be fired etc.
this.dragSource = this.selectedSources[0];
dojo.lang.forEach(this.selectedSources, function(tempSource){
if(!tempSource){ return; }
var tdo = tempSource.onDragStart(e);
if(tdo){
tdo.onDragStart(e);
// "bump" the drag object to account for the drag threshold
tdo.dragOffset.y += dy;
tdo.dragOffset.x += dx;
tdo.dragSource = tempSource;
this.dragObjects.push(tdo);
}
}, this);
/* clean previous drop target in dragStart */
this.previousDropTarget = null;
this.cacheTargetLocations();
}
// FIXME: we need to add dragSources and dragObjects to e
dojo.lang.forEach(this.dragObjects, function(dragObj){
if(dragObj){ dragObj.onDragMove(e); }
});
// if we have a current drop target, check to see if we're outside of
// it. If so, do all the actions that need doing.
if(this.currentDropTarget){
//dojo.debug(dojo.html.hasParent(this.currentDropTarget.domNode))
var c = dojo.html.toCoordinateObject(this.currentDropTarget.domNode, true);
// var dtp = this.currentDropTargetPoints;
var dtp = [
[c.x,c.y], [c.x+c.width, c.y+c.height]
];
}
if((!this.nestedTargets)&&(dtp)&&(this.isInsideBox(e, dtp))){
if(this.dropAcceptable){
this.currentDropTarget.onDragMove(e, this.dragObjects);
}
}else{
// FIXME: need to fix the event object!
// see if we can find a better drop target
var bestBox = this.findBestTarget(e);
if(bestBox.target === null){
if(this.currentDropTarget){
this.currentDropTarget.onDragOut(e);
this.previousDropTarget = this.currentDropTarget;
this.currentDropTarget = null;
// this.currentDropTargetPoints = null;
}
this.dropAcceptable = false;
dojo.lang.forEach(this.dragObjects, function (tempDragObj) {
var ret = null;
if (!tempDragObj) {
return;
}
if(this.currentDropTarget !== bestBox.target){
if(this.currentDropTarget){
this.previousDropTarget = this.currentDropTarget;
if (this.currentDropTarget) {
e.dragObject = tempDragObj;
var ce = this.currentDropTarget.domNode.childNodes;
if (ce.length > 0) {
e.dropTarget = ce[0];
while (e.dropTarget == tempDragObj.domNode) {
e.dropTarget = e.dropTarget.nextSibling;
}
} else {
e.dropTarget = this.currentDropTarget.domNode;
}
if (this.dropAcceptable) {
ret = this.currentDropTarget.onDrop(e);
} else {
this.currentDropTarget.onDragOut(e);
}
this.currentDropTarget = bestBox.target;
// this.currentDropTargetPoints = bestBox.points;
e.dragObjects = this.dragObjects;
this.dropAcceptable = this.currentDropTarget.onDragOver(e);
}else{
if(this.dropAcceptable){
this.currentDropTarget.onDragMove(e, this.dragObjects);
}
e.dragStatus = this.dropAcceptable && ret ? "dropSuccess" : "dropFailure";
dojo.lang.delayThese([function () {
try {
tempDragObj.dragSource.onDragEnd(e);
}
catch (err) {
var ecopy = {};
for (var i in e) {
if (i == "type") {
ecopy.type = "mouseup";
continue;
}
ecopy[i] = e[i];
}
tempDragObj.dragSource.onDragEnd(ecopy);
}
}, function () {
tempDragObj.onDragEnd(e);
}]);
}, this);
this.selectedSources = [];
this.dragObjects = [];
this.dragSource = null;
if (this.currentDropTarget) {
this.currentDropTarget.onDropEnd();
}
} else {
}
dojo.event.disconnect(document, "onmousemove", this, "onMouseMove");
this.currentDropTarget = null;
}, onScroll:function () {
for (var i = 0; i < this.dragObjects.length; i++) {
if (this.dragObjects[i].updateDragOffset) {
this.dragObjects[i].updateDragOffset();
}
}
if (this.dragObjects.length) {
this.cacheTargetLocations();
}
}, _dragStartDistance:function (x, y) {
if ((!this.mouseDownX) || (!this.mouseDownX)) {
return;
}
var dx = Math.abs(x - this.mouseDownX);
var dx2 = dx * dx;
var dy = Math.abs(y - this.mouseDownY);
var dy2 = dy * dy;
return parseInt(Math.sqrt(dx2 + dy2), 10);
}, cacheTargetLocations:function () {
dojo.profile.start("cacheTargetLocations");
this.dropTargetDimensions = [];
dojo.lang.forEach(this.dropTargets, function (tempTarget) {
var tn = tempTarget.domNode;
if (!tn || !tempTarget.accepts([this.dragSource])) {
return;
}
var abs = dojo.html.getAbsolutePosition(tn, true);
var bb = dojo.html.getBorderBox(tn);
this.dropTargetDimensions.push([[abs.x, abs.y], [abs.x + bb.width, abs.y + bb.height], tempTarget]);
}, this);
dojo.profile.end("cacheTargetLocations");
}, onMouseMove:function (e) {
if ((dojo.render.html.ie) && (e.button != 1)) {
this.currentDropTarget = null;
this.onMouseUp(e, true);
return;
}
if ((this.selectedSources.length) && (!this.dragObjects.length)) {
var dx;
var dy;
if (!this._dragTriggered) {
this._dragTriggered = (this._dragStartDistance(e.pageX, e.pageY) > this.threshold);
if (!this._dragTriggered) {
return;
}
dx = e.pageX - this.mouseDownX;
dy = e.pageY - this.mouseDownY;
}
this.dragSource = this.selectedSources[0];
dojo.lang.forEach(this.selectedSources, function (tempSource) {
if (!tempSource) {
return;
}
var tdo = tempSource.onDragStart(e);
if (tdo) {
tdo.onDragStart(e);
tdo.dragOffset.y += dy;
tdo.dragOffset.x += dx;
tdo.dragSource = tempSource;
this.dragObjects.push(tdo);
}
}, this);
this.previousDropTarget = null;
this.cacheTargetLocations();
}
dojo.lang.forEach(this.dragObjects, function (dragObj) {
if (dragObj) {
dragObj.onDragMove(e);
}
});
if (this.currentDropTarget) {
var c = dojo.html.toCoordinateObject(this.currentDropTarget.domNode, true);
var dtp = [[c.x, c.y], [c.x + c.width, c.y + c.height]];
}
if ((!this.nestedTargets) && (dtp) && (this.isInsideBox(e, dtp))) {
if (this.dropAcceptable) {
this.currentDropTarget.onDragMove(e, this.dragObjects);
}
} else {
var bestBox = this.findBestTarget(e);
if (bestBox.target === null) {
if (this.currentDropTarget) {
this.currentDropTarget.onDragOut(e);
this.previousDropTarget = this.currentDropTarget;
this.currentDropTarget = null;
}
this.dropAcceptable = false;
return;
}
if (this.currentDropTarget !== bestBox.target) {
if (this.currentDropTarget) {
this.previousDropTarget = this.currentDropTarget;
this.currentDropTarget.onDragOut(e);
}
this.currentDropTarget = bestBox.target;
e.dragObjects = this.dragObjects;
this.dropAcceptable = this.currentDropTarget.onDragOver(e);
} else {
if (this.dropAcceptable) {
this.currentDropTarget.onDragMove(e, this.dragObjects);
}
}
},
findBestTarget: function(e) {
var _this = this;
var bestBox = new Object();
bestBox.target = null;
bestBox.points = null;
dojo.lang.every(this.dropTargetDimensions, function(tmpDA) {
if(!_this.isInsideBox(e, tmpDA)){
return true;
}
bestBox.target = tmpDA[2];
bestBox.points = tmpDA;
// continue iterating only if _this.nestedTargets == true
return Boolean(_this.nestedTargets);
});
return bestBox;
},
isInsideBox: function(e, coords){
if( (e.pageX > coords[0][0])&&
(e.pageX < coords[1][0])&&
(e.pageY > coords[0][1])&&
(e.pageY < coords[1][1]) ){
}
}, findBestTarget:function (e) {
var _this = this;
var bestBox = new Object();
bestBox.target = null;
bestBox.points = null;
dojo.lang.every(this.dropTargetDimensions, function (tmpDA) {
if (!_this.isInsideBox(e, tmpDA)) {
return true;
}
return false;
},
onMouseOver: function(e){
},
onMouseOut: function(e){
bestBox.target = tmpDA[2];
bestBox.points = tmpDA;
return Boolean(_this.nestedTargets);
});
return bestBox;
}, isInsideBox:function (e, coords) {
if ((e.pageX > coords[0][0]) && (e.pageX < coords[1][0]) && (e.pageY > coords[0][1]) && (e.pageY < coords[1][1])) {
return true;
}
});
return false;
}, onMouseOver:function (e) {
}, onMouseOut:function (e) {
}});
dojo.dnd.dragManager = new dojo.dnd.HtmlDragManager();
// global namespace protection closure
(function(){
(function () {
var d = document;
var dm = dojo.dnd.dragManager;
//TODO: when focus manager is ready, dragManager should be rewritten to use it
// set up event handlers on the document (or no?)
dojo.event.connect(d, "onkeydown", dm, "onKeyDown");
dojo.event.connect(d, "onmouseover", dm, "onMouseOver");
dojo.event.connect(d, "onmouseout", dm, "onMouseOut");
dojo.event.connect(d, "onmousedown", dm, "onMouseDown");
dojo.event.connect(d, "onmouseup", dm, "onMouseUp");
// TODO: process scrolling of elements, not only window (focus manager would
// probably come to rescue here as well)
dojo.event.connect(window, "onscroll", dm, "onScroll");
})();
@@ -10,57 +10,43 @@
dojo.provide("dojo.dnd.HtmlDragMove");
dojo.require("dojo.dnd.*");
dojo.declare("dojo.dnd.HtmlDragMoveSource", dojo.dnd.HtmlDragSource, {
onDragStart: function(){
var dragObj = new dojo.dnd.HtmlDragMoveObject(this.dragObject, this.type);
if (this.constrainToContainer) {
dragObj.constrainTo(this.constrainingContainer);
}
return dragObj;
},
/*
* see dojo.dnd.HtmlDragSource.onSelected
*/
onSelected: function() {
for (var i=0; i<this.dragObjects.length; i++) {
dojo.dnd.dragManager.selectedSources.push(new dojo.dnd.HtmlDragMoveSource(this.dragObjects[i]));
}
dojo.declare("dojo.dnd.HtmlDragMoveSource", dojo.dnd.HtmlDragSource, {onDragStart:function () {
var dragObj = new dojo.dnd.HtmlDragMoveObject(this.dragObject, this.type);
if (this.constrainToContainer) {
dragObj.constrainTo(this.constrainingContainer);
}
});
dojo.declare("dojo.dnd.HtmlDragMoveObject", dojo.dnd.HtmlDragObject, {
onDragEnd: function(e){
// shortly the browser will fire an onClick() event,
// but since this was really a drag, just squelch it
dojo.event.connect(this.domNode, "onclick", this, "squelchOnClick");
},
onDragStart: function(e){
dojo.html.clearSelection();
this.dragClone = this.domNode;
this.scrollOffset = dojo.html.getScroll().offset;
this.dragStartPosition = dojo.html.abs(this.domNode, true);
this.dragOffset = {y: this.dragStartPosition.y - e.pageY,
x: this.dragStartPosition.x - e.pageX};
this.containingBlockPosition = this.domNode.offsetParent ?
dojo.html.abs(this.domNode.offsetParent, true) : {x:0, y:0};
this.dragClone.style.position = "absolute";
if (this.constrainToContainer) {
this.constraints = this.getConstraints();
}
},
/**
* Set the position of the drag node. (x,y) is relative to <body>.
*/
setAbsolutePosition: function(x, y){
// The drag clone is attached to it's constraining container so offset for that
if(!this.disableY) { this.domNode.style.top = (y-this.containingBlockPosition.y) + "px"; }
if(!this.disableX) { this.domNode.style.left = (x-this.containingBlockPosition.x) + "px"; }
return dragObj;
}, onSelected:function () {
for (var i = 0; i < this.dragObjects.length; i++) {
dojo.dnd.dragManager.selectedSources.push(new dojo.dnd.HtmlDragMoveSource(this.dragObjects[i]));
}
});
}});
dojo.declare("dojo.dnd.HtmlDragMoveObject", dojo.dnd.HtmlDragObject, {onDragStart:function (e) {
dojo.html.clearSelection();
this.dragClone = this.domNode;
if (dojo.html.getComputedStyle(this.domNode, "position") != "absolute") {
this.domNode.style.position = "relative";
}
var left = parseInt(dojo.html.getComputedStyle(this.domNode, "left"));
var top = parseInt(dojo.html.getComputedStyle(this.domNode, "top"));
this.dragStartPosition = {x:isNaN(left) ? 0 : left, y:isNaN(top) ? 0 : top};
this.scrollOffset = dojo.html.getScroll().offset;
this.dragOffset = {y:this.dragStartPosition.y - e.pageY, x:this.dragStartPosition.x - e.pageX};
this.containingBlockPosition = {x:0, y:0};
if (this.constrainToContainer) {
this.constraints = this.getConstraints();
}
dojo.event.connect(this.domNode, "onclick", this, "_squelchOnClick");
}, onDragEnd:function (e) {
}, setAbsolutePosition:function (x, y) {
if (!this.disableY) {
this.domNode.style.top = y + "px";
}
if (!this.disableX) {
this.domNode.style.left = x + "px";
}
}, _squelchOnClick:function (e) {
dojo.event.browser.stopEvent(e);
dojo.event.disconnect(this.domNode, "onclick", this, "_squelchOnClick");
}});
@@ -10,19 +10,13 @@
dojo.provide("dojo.dnd.Sortable");
dojo.require("dojo.dnd.*");
dojo.dnd.Sortable = function () {}
dojo.lang.extend(dojo.dnd.Sortable, {
ondragstart: function (e) {
var dragObject = e.target;
while (dragObject.parentNode && dragObject.parentNode != this) {
dragObject = dragObject.parentNode;
}
// TODO: should apply HtmlDropTarget interface to self
// TODO: should apply HtmlDragObject interface?
return dragObject;
dojo.dnd.Sortable = function () {
};
dojo.lang.extend(dojo.dnd.Sortable, {ondragstart:function (e) {
var dragObject = e.target;
while (dragObject.parentNode && dragObject.parentNode != this) {
dragObject = dragObject.parentNode;
}
return dragObject;
}});
});
@@ -8,468 +8,244 @@
http://dojotoolkit.org/community/licensing.shtml
*/
/**
* TreeDrag* specialized on managing subtree drags
* It selects nodes and visualises what's going on,
* but delegates real actions upon tree to the controller
*
* This code is considered a part of controller
*/
dojo.provide("dojo.dnd.TreeDragAndDrop");
dojo.require("dojo.dnd.HtmlDragAndDrop");
dojo.require("dojo.lang.func");
dojo.require("dojo.lang.array");
dojo.require("dojo.lang.extras");
dojo.require("dojo.html.layout");
dojo.dnd.TreeDragSource = function(node, syncController, type, treeNode){
dojo.dnd.TreeDragSource = function (node, syncController, type, treeNode) {
this.controller = syncController;
this.treeNode = treeNode;
dojo.dnd.HtmlDragSource.call(this, node, type);
}
};
dojo.inherits(dojo.dnd.TreeDragSource, dojo.dnd.HtmlDragSource);
dojo.lang.extend(dojo.dnd.TreeDragSource, {
onDragStart: function(){
/* extend adds functions to prototype */
var dragObject = dojo.dnd.HtmlDragSource.prototype.onDragStart.call(this);
//dojo.debugShallow(dragObject)
dragObject.treeNode = this.treeNode;
dragObject.onDragStart = dojo.lang.hitch(dragObject, function(e) {
/* save selection */
this.savedSelectedNode = this.treeNode.tree.selector.selectedNode;
if (this.savedSelectedNode) {
this.savedSelectedNode.unMarkSelected();
}
var result = dojo.dnd.HtmlDragObject.prototype.onDragStart.apply(this, arguments);
/* remove background grid from cloned object */
var cloneGrid = this.dragClone.getElementsByTagName('img');
for(var i=0; i<cloneGrid.length; i++) {
cloneGrid.item(i).style.backgroundImage='url()';
}
return result;
});
dragObject.onDragEnd = function(e) {
/* restore selection */
if (this.savedSelectedNode) {
this.savedSelectedNode.markSelected();
}
//dojo.debug(e.dragStatus);
return dojo.dnd.HtmlDragObject.prototype.onDragEnd.apply(this, arguments);
dojo.lang.extend(dojo.dnd.TreeDragSource, {onDragStart:function () {
var dragObject = dojo.dnd.HtmlDragSource.prototype.onDragStart.call(this);
dragObject.treeNode = this.treeNode;
dragObject.onDragStart = dojo.lang.hitch(dragObject, function (e) {
this.savedSelectedNode = this.treeNode.tree.selector.selectedNode;
if (this.savedSelectedNode) {
this.savedSelectedNode.unMarkSelected();
}
//dojo.debug(dragObject.domNode.outerHTML)
return dragObject;
},
onDragEnd: function(e){
var res = dojo.dnd.HtmlDragSource.prototype.onDragEnd.call(this, e);
return res;
}
});
// .......................................
dojo.dnd.TreeDropTarget = function(domNode, controller, type, treeNode){
var result = dojo.dnd.HtmlDragObject.prototype.onDragStart.apply(this, arguments);
var cloneGrid = this.dragClone.getElementsByTagName("img");
for (var i = 0; i < cloneGrid.length; i++) {
cloneGrid.item(i).style.backgroundImage = "url()";
}
return result;
});
dragObject.onDragEnd = function (e) {
if (this.savedSelectedNode) {
this.savedSelectedNode.markSelected();
}
return dojo.dnd.HtmlDragObject.prototype.onDragEnd.apply(this, arguments);
};
return dragObject;
}, onDragEnd:function (e) {
var res = dojo.dnd.HtmlDragSource.prototype.onDragEnd.call(this, e);
return res;
}});
dojo.dnd.TreeDropTarget = function (domNode, controller, type, treeNode) {
this.treeNode = treeNode;
this.controller = controller; // I will sync-ly process drops
this.controller = controller;
dojo.dnd.HtmlDropTarget.apply(this, [domNode, type]);
}
};
dojo.inherits(dojo.dnd.TreeDropTarget, dojo.dnd.HtmlDropTarget);
dojo.lang.extend(dojo.dnd.TreeDropTarget, {
autoExpandDelay: 1500,
autoExpandTimer: null,
position: null,
indicatorStyle: "2px black solid",
showIndicator: function(position) {
// do not change style too often, cause of blinking possible
if (this.position == position) {
return;
}
//dojo.debug(position)
this.hideIndicator();
this.position = position;
if (position == "before") {
this.treeNode.labelNode.style.borderTop = this.indicatorStyle;
} else if (position == "after") {
dojo.lang.extend(dojo.dnd.TreeDropTarget, {autoExpandDelay:1500, autoExpandTimer:null, position:null, indicatorStyle:"2px black solid", showIndicator:function (position) {
if (this.position == position) {
return;
}
this.hideIndicator();
this.position = position;
if (position == "before") {
this.treeNode.labelNode.style.borderTop = this.indicatorStyle;
} else {
if (position == "after") {
this.treeNode.labelNode.style.borderBottom = this.indicatorStyle;
} else if (position == "onto") {
this.treeNode.markSelected();
}
},
hideIndicator: function() {
this.treeNode.labelNode.style.borderBottom="";
this.treeNode.labelNode.style.borderTop="";
this.treeNode.unMarkSelected();
this.position = null;
},
// is the target possibly ok ?
// This function is run on dragOver, but drop possibility is also determined by position over node
// that's why acceptsWithPosition is called
// doesnt take index into account ( can change while moving mouse w/o changing target )
/**
* Coarse (tree-level) access check.
* We can't determine real accepts status w/o position
*/
onDragOver: function(e){
//dojo.debug("onDragOver for "+e);
var accepts = dojo.dnd.HtmlDropTarget.prototype.onDragOver.apply(this, arguments);
//dojo.debug("TreeDropTarget.onDragOver accepts:"+accepts)
if (accepts && this.treeNode.isFolder && !this.treeNode.isExpanded) {
this.setAutoExpandTimer();
}
return accepts;
},
/* Parent.onDragOver calls this function to get accepts status */
accepts: function(dragObjects) {
var accepts = dojo.dnd.HtmlDropTarget.prototype.accepts.apply(this, arguments);
if (!accepts) return false;
var sourceTreeNode = dragObjects[0].treeNode;
if (dojo.lang.isUndefined(sourceTreeNode) || !sourceTreeNode || !sourceTreeNode.isTreeNode) {
dojo.raise("Source is not TreeNode or not found");
}
if (sourceTreeNode === this.treeNode) return false;
return true;
},
setAutoExpandTimer: function() {
// set up autoexpand timer
var _this = this;
var autoExpand = function () {
if (dojo.dnd.dragManager.currentDropTarget === _this) {
_this.controller.expand(_this.treeNode);
} else {
if (position == "onto") {
this.treeNode.markSelected();
}
}
this.autoExpandTimer = dojo.lang.setTimeout(autoExpand, _this.autoExpandDelay);
},
getDNDMode: function() {
return this.treeNode.tree.DNDMode;
},
getAcceptPosition: function(e, sourceTreeNode) {
var DNDMode = this.getDNDMode();
if (DNDMode & dojo.widget.Tree.prototype.DNDModes.ONTO &&
// check if ONTO is allowed localy
!(
!this.treeNode.actionIsDisabled(dojo.widget.TreeNode.prototype.actions.ADDCHILD) // check dynamically cause may change w/o regeneration of dropTarget
&& sourceTreeNode.parent !== this.treeNode
&& this.controller.canMove(sourceTreeNode, this.treeNode)
)
) {
// disable ONTO if can't move
DNDMode &= ~dojo.widget.Tree.prototype.DNDModes.ONTO;
}
var position = this.getPosition(e, DNDMode);
//dojo.debug(DNDMode & +" : "+position);
// if onto is here => it was allowed before, no accept check is needed
if (position=="onto" ||
(!this.isAdjacentNode(sourceTreeNode, position)
&& this.controller.canMove(sourceTreeNode, this.treeNode.parent)
)
) {
return position;
} else {
return false;
}
},
onDragOut: function(e) {
this.clearAutoExpandTimer();
this.hideIndicator();
},
clearAutoExpandTimer: function() {
if (this.autoExpandTimer) {
clearTimeout(this.autoExpandTimer);
this.autoExpandTimer = null;
}
},
onDragMove: function(e, dragObjects){
var sourceTreeNode = dragObjects[0].treeNode;
var position = this.getAcceptPosition(e, sourceTreeNode);
if (position) {
this.showIndicator(position);
}
},
isAdjacentNode: function(sourceNode, position) {
if (sourceNode === this.treeNode) return true;
if (sourceNode.getNextSibling() === this.treeNode && position=="before") return true;
if (sourceNode.getPreviousSibling() === this.treeNode && position=="after") return true;
}
}, hideIndicator:function () {
this.treeNode.labelNode.style.borderBottom = "";
this.treeNode.labelNode.style.borderTop = "";
this.treeNode.unMarkSelected();
this.position = null;
}, onDragOver:function (e) {
var accepts = dojo.dnd.HtmlDropTarget.prototype.onDragOver.apply(this, arguments);
if (accepts && this.treeNode.isFolder && !this.treeNode.isExpanded) {
this.setAutoExpandTimer();
}
return accepts;
}, accepts:function (dragObjects) {
var accepts = dojo.dnd.HtmlDropTarget.prototype.accepts.apply(this, arguments);
if (!accepts) {
return false;
},
/* get DNDMode and see which position e fits */
getPosition: function(e, DNDMode) {
var node = dojo.byId(this.treeNode.labelNode);
var mousey = e.pageY || e.clientY + dojo.body().scrollTop;
var nodey = dojo.html.getAbsolutePosition(node).y;
var height = dojo.html.getBorderBox(node).height;
var relY = mousey - nodey;
var p = relY / height;
var position = ""; // "" <=> forbidden
if (DNDMode & dojo.widget.Tree.prototype.DNDModes.ONTO
&& DNDMode & dojo.widget.Tree.prototype.DNDModes.BETWEEN) {
if (p<=0.3) {
position = "before";
} else if (p<=0.7) {
}
var sourceTreeNode = dragObjects[0].treeNode;
if (dojo.lang.isUndefined(sourceTreeNode) || !sourceTreeNode || !sourceTreeNode.isTreeNode) {
dojo.raise("Source is not TreeNode or not found");
}
if (sourceTreeNode === this.treeNode) {
return false;
}
return true;
}, setAutoExpandTimer:function () {
var _this = this;
var autoExpand = function () {
if (dojo.dnd.dragManager.currentDropTarget === _this) {
_this.controller.expand(_this.treeNode);
}
};
this.autoExpandTimer = dojo.lang.setTimeout(autoExpand, _this.autoExpandDelay);
}, getDNDMode:function () {
return this.treeNode.tree.DNDMode;
}, getAcceptPosition:function (e, sourceTreeNode) {
var DNDMode = this.getDNDMode();
if (DNDMode & dojo.widget.Tree.prototype.DNDModes.ONTO && !(!this.treeNode.actionIsDisabled(dojo.widget.TreeNode.prototype.actions.ADDCHILD) && sourceTreeNode.parent !== this.treeNode && this.controller.canMove(sourceTreeNode, this.treeNode))) {
DNDMode &= ~dojo.widget.Tree.prototype.DNDModes.ONTO;
}
var position = this.getPosition(e, DNDMode);
if (position == "onto" || (!this.isAdjacentNode(sourceTreeNode, position) && this.controller.canMove(sourceTreeNode, this.treeNode.parent))) {
return position;
} else {
return false;
}
}, onDragOut:function (e) {
this.clearAutoExpandTimer();
this.hideIndicator();
}, clearAutoExpandTimer:function () {
if (this.autoExpandTimer) {
clearTimeout(this.autoExpandTimer);
this.autoExpandTimer = null;
}
}, onDragMove:function (e, dragObjects) {
var sourceTreeNode = dragObjects[0].treeNode;
var position = this.getAcceptPosition(e, sourceTreeNode);
if (position) {
this.showIndicator(position);
}
}, isAdjacentNode:function (sourceNode, position) {
if (sourceNode === this.treeNode) {
return true;
}
if (sourceNode.getNextSibling() === this.treeNode && position == "before") {
return true;
}
if (sourceNode.getPreviousSibling() === this.treeNode && position == "after") {
return true;
}
return false;
}, getPosition:function (e, DNDMode) {
var node = dojo.byId(this.treeNode.labelNode);
var mousey = e.pageY || e.clientY + dojo.body().scrollTop;
var nodey = dojo.html.getAbsolutePosition(node).y;
var height = dojo.html.getBorderBox(node).height;
var relY = mousey - nodey;
var p = relY / height;
var position = "";
if (DNDMode & dojo.widget.Tree.prototype.DNDModes.ONTO && DNDMode & dojo.widget.Tree.prototype.DNDModes.BETWEEN) {
if (p <= 0.3) {
position = "before";
} else {
if (p <= 0.7) {
position = "onto";
} else {
position = "after";
}
} else if (DNDMode & dojo.widget.Tree.prototype.DNDModes.BETWEEN) {
if (p<=0.5) {
}
} else {
if (DNDMode & dojo.widget.Tree.prototype.DNDModes.BETWEEN) {
if (p <= 0.5) {
position = "before";
} else {
position = "after";
}
}
else if (DNDMode & dojo.widget.Tree.prototype.DNDModes.ONTO) {
position = "onto";
}
return position;
},
getTargetParentIndex: function(sourceTreeNode, position) {
var index = position == "before" ? this.treeNode.getParentIndex() : this.treeNode.getParentIndex()+1;
if (this.treeNode.parent === sourceTreeNode.parent
&& this.treeNode.getParentIndex() > sourceTreeNode.getParentIndex()) {
index--; // dragging a node is different for simple move bacause of before-after issues
}
return index;
},
onDrop: function(e){
// onDragOut will clean position
var position = this.position;
//dojo.debug(position);
this.onDragOut(e);
var sourceTreeNode = e.dragObject.treeNode;
if (!dojo.lang.isObject(sourceTreeNode)) {
dojo.raise("TreeNode not found in dragObject")
}
if (position == "onto") {
return this.controller.move(sourceTreeNode, this.treeNode, 0);
} else {
var index = this.getTargetParentIndex(sourceTreeNode, position);
return this.controller.move(sourceTreeNode, this.treeNode.parent, index);
if (DNDMode & dojo.widget.Tree.prototype.DNDModes.ONTO) {
position = "onto";
}
}
//dojo.debug('drop2');
}
});
dojo.dnd.TreeDNDController = function(treeController) {
// I use this controller to perform actions
return position;
}, getTargetParentIndex:function (sourceTreeNode, position) {
var index = position == "before" ? this.treeNode.getParentIndex() : this.treeNode.getParentIndex() + 1;
if (this.treeNode.parent === sourceTreeNode.parent && this.treeNode.getParentIndex() > sourceTreeNode.getParentIndex()) {
index--;
}
return index;
}, onDrop:function (e) {
var position = this.position;
this.onDragOut(e);
var sourceTreeNode = e.dragObject.treeNode;
if (!dojo.lang.isObject(sourceTreeNode)) {
dojo.raise("TreeNode not found in dragObject");
}
if (position == "onto") {
return this.controller.move(sourceTreeNode, this.treeNode, 0);
} else {
var index = this.getTargetParentIndex(sourceTreeNode, position);
return this.controller.move(sourceTreeNode, this.treeNode.parent, index);
}
}});
dojo.dnd.TreeDNDController = function (treeController) {
this.treeController = treeController;
this.dragSources = {};
this.dropTargets = {};
}
dojo.lang.extend(dojo.dnd.TreeDNDController, {
listenTree: function(tree) {
//dojo.debug("Listen tree "+tree);
dojo.event.topic.subscribe(tree.eventNames.createDOMNode, this, "onCreateDOMNode");
dojo.event.topic.subscribe(tree.eventNames.moveFrom, this, "onMoveFrom");
dojo.event.topic.subscribe(tree.eventNames.moveTo, this, "onMoveTo");
dojo.event.topic.subscribe(tree.eventNames.addChild, this, "onAddChild");
dojo.event.topic.subscribe(tree.eventNames.removeNode, this, "onRemoveNode");
dojo.event.topic.subscribe(tree.eventNames.treeDestroy, this, "onTreeDestroy");
},
unlistenTree: function(tree) {
//dojo.debug("Listen tree "+tree);
dojo.event.topic.unsubscribe(tree.eventNames.createDOMNode, this, "onCreateDOMNode");
dojo.event.topic.unsubscribe(tree.eventNames.moveFrom, this, "onMoveFrom");
dojo.event.topic.unsubscribe(tree.eventNames.moveTo, this, "onMoveTo");
dojo.event.topic.unsubscribe(tree.eventNames.addChild, this, "onAddChild");
dojo.event.topic.unsubscribe(tree.eventNames.removeNode, this, "onRemoveNode");
dojo.event.topic.unsubscribe(tree.eventNames.treeDestroy, this, "onTreeDestroy");
},
onTreeDestroy: function(message) {
this.unlistenTree(message.source);
// I'm not widget so don't use destroy() call and dieWithTree
},
onCreateDOMNode: function(message) {
this.registerDNDNode(message.source);
},
onAddChild: function(message) {
this.registerDNDNode(message.child);
},
onMoveFrom: function(message) {
var _this = this;
dojo.lang.forEach(
message.child.getDescendants(),
function(node) { _this.unregisterDNDNode(node); }
);
},
onMoveTo: function(message) {
var _this = this;
dojo.lang.forEach(
message.child.getDescendants(),
function(node) { _this.registerDNDNode(node); }
);
},
/**
* Controller(node model) creates DNDNodes because it passes itself to node for synchroneous drops processing
* I can't process DnD with events cause an event can't return result success/false
*/
registerDNDNode: function(node) {
if (!node.tree.DNDMode) return;
//dojo.debug("registerDNDNode "+node);
/* I drag label, not domNode, because large domNodes are very slow to copy and large to drag */
var source = null;
var target = null;
if (!node.actionIsDisabled(node.actions.MOVE)) {
//dojo.debug("reg source")
var source = new dojo.dnd.TreeDragSource(node.labelNode, this, node.tree.widgetId, node);
this.dragSources[node.widgetId] = source;
}
var target = new dojo.dnd.TreeDropTarget(node.labelNode, this.treeController, node.tree.DNDAcceptTypes, node);
this.dropTargets[node.widgetId] = target;
},
unregisterDNDNode: function(node) {
if (this.dragSources[node.widgetId]) {
dojo.dnd.dragManager.unregisterDragSource(this.dragSources[node.widgetId]);
delete this.dragSources[node.widgetId];
}
if (this.dropTargets[node.widgetId]) {
dojo.dnd.dragManager.unregisterDropTarget(this.dropTargets[node.widgetId]);
delete this.dropTargets[node.widgetId];
}
};
dojo.lang.extend(dojo.dnd.TreeDNDController, {listenTree:function (tree) {
dojo.event.topic.subscribe(tree.eventNames.createDOMNode, this, "onCreateDOMNode");
dojo.event.topic.subscribe(tree.eventNames.moveFrom, this, "onMoveFrom");
dojo.event.topic.subscribe(tree.eventNames.moveTo, this, "onMoveTo");
dojo.event.topic.subscribe(tree.eventNames.addChild, this, "onAddChild");
dojo.event.topic.subscribe(tree.eventNames.removeNode, this, "onRemoveNode");
dojo.event.topic.subscribe(tree.eventNames.treeDestroy, this, "onTreeDestroy");
}, unlistenTree:function (tree) {
dojo.event.topic.unsubscribe(tree.eventNames.createDOMNode, this, "onCreateDOMNode");
dojo.event.topic.unsubscribe(tree.eventNames.moveFrom, this, "onMoveFrom");
dojo.event.topic.unsubscribe(tree.eventNames.moveTo, this, "onMoveTo");
dojo.event.topic.unsubscribe(tree.eventNames.addChild, this, "onAddChild");
dojo.event.topic.unsubscribe(tree.eventNames.removeNode, this, "onRemoveNode");
dojo.event.topic.unsubscribe(tree.eventNames.treeDestroy, this, "onTreeDestroy");
}, onTreeDestroy:function (message) {
this.unlistenTree(message.source);
}, onCreateDOMNode:function (message) {
this.registerDNDNode(message.source);
}, onAddChild:function (message) {
this.registerDNDNode(message.child);
}, onMoveFrom:function (message) {
var _this = this;
dojo.lang.forEach(message.child.getDescendants(), function (node) {
_this.unregisterDNDNode(node);
});
}, onMoveTo:function (message) {
var _this = this;
dojo.lang.forEach(message.child.getDescendants(), function (node) {
_this.registerDNDNode(node);
});
}, registerDNDNode:function (node) {
if (!node.tree.DNDMode) {
return;
}
var source = null;
var target = null;
if (!node.actionIsDisabled(node.actions.MOVE)) {
var source = new dojo.dnd.TreeDragSource(node.labelNode, this, node.tree.widgetId, node);
this.dragSources[node.widgetId] = source;
}
var target = new dojo.dnd.TreeDropTarget(node.labelNode, this.treeController, node.tree.DNDAcceptTypes, node);
this.dropTargets[node.widgetId] = target;
}, unregisterDNDNode:function (node) {
if (this.dragSources[node.widgetId]) {
dojo.dnd.dragManager.unregisterDragSource(this.dragSources[node.widgetId]);
delete this.dragSources[node.widgetId];
}
if (this.dropTargets[node.widgetId]) {
dojo.dnd.dragManager.unregisterDropTarget(this.dropTargets[node.widgetId]);
delete this.dropTargets[node.widgetId];
}
}});
});
@@ -8,397 +8,209 @@
http://dojotoolkit.org/community/licensing.shtml
*/
/**
* TreeDrag* specialized on managing subtree drags
* It selects nodes and visualises what's going on,
* but delegates real actions upon tree to the controller
*
* This code is considered a part of controller
*/
dojo.provide("dojo.dnd.TreeDragAndDropV3");
dojo.require("dojo.dnd.HtmlDragAndDrop");
dojo.require("dojo.lang.func");
dojo.require("dojo.lang.array");
dojo.require("dojo.lang.extras");
dojo.require("dojo.Deferred");
dojo.require("dojo.html.layout");
// FIXME: if controller can't move then skip node on move start
dojo.dnd.TreeDragSourceV3 = function(node, syncController, type, treeNode){
//dojo.profile.start("TreeDragSourceV3 "+treeNode);
dojo.dnd.TreeDragSourceV3 = function (node, syncController, type, treeNode) {
this.controller = syncController;
this.treeNode = treeNode;
dojo.dnd.HtmlDragSource.call(this, node, type);
//dojo.profile.end("TreeDragSourceV3 "+treeNode);
}
};
dojo.inherits(dojo.dnd.TreeDragSourceV3, dojo.dnd.HtmlDragSource);
// .......................................
dojo.dnd.TreeDropTargetV3 = function(domNode, controller, type, treeNode){
dojo.dnd.TreeDropTargetV3 = function (domNode, controller, type, treeNode) {
this.treeNode = treeNode;
this.controller = controller; // I will sync-ly process drops
this.controller = controller;
dojo.dnd.HtmlDropTarget.call(this, domNode, type);
}
};
dojo.inherits(dojo.dnd.TreeDropTargetV3, dojo.dnd.HtmlDropTarget);
dojo.lang.extend(dojo.dnd.TreeDropTargetV3, {
autoExpandDelay: 1500,
autoExpandTimer: null,
position: null,
indicatorStyle: "2px black groove",
showIndicator: function(position) {
// do not change style too often, cause of blinking possible
if (this.position == position) {
return;
}
//dojo.debug("set position for "+this.treeNode)
this.hideIndicator();
this.position = position;
var node = this.treeNode;
node.contentNode.style.width = dojo.html.getBorderBox(node.labelNode).width + "px";
if (position == "onto") {
node.contentNode.style.border = this.indicatorStyle;
dojo.lang.extend(dojo.dnd.TreeDropTargetV3, {autoExpandDelay:1500, autoExpandTimer:null, position:null, indicatorStyle:"2px black groove", showIndicator:function (position) {
if (this.position == position) {
return;
}
this.hideIndicator();
this.position = position;
var node = this.treeNode;
node.contentNode.style.width = dojo.html.getBorderBox(node.labelNode).width + "px";
if (position == "onto") {
node.contentNode.style.border = this.indicatorStyle;
} else {
if (position == "before") {
node.contentNode.style.borderTop = this.indicatorStyle;
} else {
// FIXME: bottom-top or highlight should cover ONLY top/bottom or div itself,
// not span whole line (try Dnd)
// FAILURE: Can't put span inside div: multiline bottom-top will span multiple lines
if (position == "before") {
node.contentNode.style.borderTop = this.indicatorStyle;
} else if (position == "after") {
if (position == "after") {
node.contentNode.style.borderBottom = this.indicatorStyle;
}
}
},
hideIndicator: function() {
this.treeNode.contentNode.style.borderBottom = "";
this.treeNode.contentNode.style.borderTop = "";
this.treeNode.contentNode.style.border = "";
this.treeNode.contentNode.style.width=""
this.position = null;
},
// is the target possibly ok ?
// This function is run on dragOver, but drop possibility is also determined by position over node
// that's why acceptsWithPosition is called
// doesnt take index into account ( can change while moving mouse w/o changing target )
/**
* Coarse (tree-level) access check.
* We can't determine real accepts status w/o position
*/
onDragOver: function(e){
//dojo.debug("onDragOver for "+e);
var accepts = dojo.dnd.HtmlDropTarget.prototype.onDragOver.apply(this, arguments);
//dojo.debug("TreeDropTarget.onDragOver accepts:"+accepts)
if (accepts && this.treeNode.isFolder && !this.treeNode.isExpanded) {
this.setAutoExpandTimer();
}
if (accepts) {
this.cacheNodeCoords();
}
return accepts;
},
/* Parent.onDragOver calls this function to get accepts status */
accepts: function(dragObjects) {
var accepts = dojo.dnd.HtmlDropTarget.prototype.accepts.apply(this, arguments);
//dojo.debug("accepts "+accepts);
if (!accepts) return false;
for(var i=0; i<dragObjects.length; i++) {
// there may be NO treeNode
var sourceTreeNode = dragObjects[i].dragSource.treeNode;
if (sourceTreeNode === this.treeNode) return false;
}
return true;
},
setAutoExpandTimer: function() {
// set up autoexpand timer
var _this = this;
var autoExpand = function () {
if (dojo.dnd.dragManager.currentDropTarget === _this) {
_this.controller.expand(_this.treeNode);
// SLOW. Coordinates will not be recalculated if collapse occurs, or
// other (generic) resize. So that's a kind of hack.
dojo.dnd.dragManager.cacheTargetLocations();
}
}
this.autoExpandTimer = dojo.lang.setTimeout(autoExpand, _this.autoExpandDelay);
},
getAcceptPosition: function(e, dragObjects) {
var DndMode = this.treeNode.tree.DndMode;
// disable ONTO mode possibility if impossible
if (DndMode & dojo.widget.TreeV3.prototype.DndModes.ONTO &&
// check if ONTO is allowed localy
// check dynamically cause may change w/o regeneration of dropTarget
this.treeNode.actionIsDisabledNow(this.treeNode.actions.ADDCHILD)
) {
// disable ONTO if can't move
DndMode &= ~dojo.widget.TreeV3.prototype.DndModes.ONTO;
}
var position = this.getPosition(e, DndMode);
//dojo.debug(DndMode & +" : "+position);
// if onto is here => it was allowed before, no accept check is needed
if (position=="onto") {
return position;
}
for(var i=0; i<dragObjects.length; i++) {
var source = dragObjects[i].dragSource;
if (source.treeNode && this.isAdjacentNode(source.treeNode, position)) { // skip check if same parent
continue;
}
if (!this.controller.canMove(source.treeNode ? source.treeNode : source, this.treeNode.parent)) {
return false;
}
}
return position;
},
onDropEnd: function(e) {
this.clearAutoExpandTimer();
this.hideIndicator();
},
onDragOut: function(e) {
this.clearAutoExpandTimer();
this.hideIndicator();
},
clearAutoExpandTimer: function() {
if (this.autoExpandTimer) {
clearTimeout(this.autoExpandTimer);
this.autoExpandTimer = null;
}
},
onDragMove: function(e, dragObjects){
var position = this.getAcceptPosition(e, dragObjects);
if (position) {
this.showIndicator(position);
}
},
isAdjacentNode: function(sourceNode, position) {
if (sourceNode === this.treeNode) return true;
if (sourceNode.getNextSibling() === this.treeNode && position=="before") return true;
if (sourceNode.getPreviousSibling() === this.treeNode && position=="after") return true;
}
}, hideIndicator:function () {
this.treeNode.contentNode.style.borderBottom = "";
this.treeNode.contentNode.style.borderTop = "";
this.treeNode.contentNode.style.border = "";
this.treeNode.contentNode.style.width = "";
this.position = null;
}, onDragOver:function (e) {
var accepts = dojo.dnd.HtmlDropTarget.prototype.onDragOver.apply(this, arguments);
if (accepts && this.treeNode.isFolder && !this.treeNode.isExpanded) {
this.setAutoExpandTimer();
}
if (accepts) {
this.cacheNodeCoords();
}
return accepts;
}, accepts:function (dragObjects) {
var accepts = dojo.dnd.HtmlDropTarget.prototype.accepts.apply(this, arguments);
if (!accepts) {
return false;
},
/**
* cache node coordinates to speed up onDragMove
*/
cacheNodeCoords: function() {
var node = this.treeNode.contentNode;
this.cachedNodeY = dojo.html.getAbsolutePosition(node).y;
this.cachedNodeHeight = dojo.html.getBorderBox(node).height;
},
/* get DndMode and see which position e fits */
getPosition: function(e, DndMode) {
var mousey = e.pageY || e.clientY + dojo.body().scrollTop;
var relY = mousey - this.cachedNodeY;
var p = relY / this.cachedNodeHeight;
var position = ""; // "" <=> forbidden
if (DndMode & dojo.widget.TreeV3.prototype.DndModes.ONTO
&& DndMode & dojo.widget.TreeV3.prototype.DndModes.BETWEEN) {
//dojo.debug("BOTH");
if (p<=0.33) {
position = "before";
// if children are expanded then I ignore understrike, cause it is confusing with firstChild
// but for last nodes I put understrike there
} else if (p<=0.66 || this.treeNode.isExpanded && this.treeNode.children.length && !this.treeNode.isLastChild()) {
}
for (var i = 0; i < dragObjects.length; i++) {
var sourceTreeNode = dragObjects[i].treeNode;
if (sourceTreeNode === this.treeNode) {
return false;
}
}
return true;
}, setAutoExpandTimer:function () {
var _this = this;
var autoExpand = function () {
if (dojo.dnd.dragManager.currentDropTarget === _this) {
_this.controller.expand(_this.treeNode);
dojo.dnd.dragManager.cacheTargetLocations();
}
};
this.autoExpandTimer = dojo.lang.setTimeout(autoExpand, _this.autoExpandDelay);
}, getAcceptPosition:function (e, dragObjects) {
var DndMode = this.treeNode.tree.DndMode;
if (DndMode & dojo.widget.TreeV3.prototype.DndModes.ONTO && this.treeNode.actionIsDisabledNow(this.treeNode.actions.ADDCHILD)) {
DndMode &= ~dojo.widget.TreeV3.prototype.DndModes.ONTO;
}
var position = this.getPosition(e, DndMode);
if (position == "onto") {
return position;
}
for (var i = 0; i < dragObjects.length; i++) {
var source = dragObjects[i].dragSource;
if (source.treeNode && this.isAdjacentNode(source.treeNode, position)) {
continue;
}
if (!this.controller.canMove(source.treeNode ? source.treeNode : source, this.treeNode.parent)) {
return false;
}
}
return position;
}, onDropEnd:function (e) {
this.clearAutoExpandTimer();
this.hideIndicator();
}, onDragOut:function (e) {
this.clearAutoExpandTimer();
this.hideIndicator();
}, clearAutoExpandTimer:function () {
if (this.autoExpandTimer) {
clearTimeout(this.autoExpandTimer);
this.autoExpandTimer = null;
}
}, onDragMove:function (e, dragObjects) {
var position = this.getAcceptPosition(e, dragObjects);
if (position) {
this.showIndicator(position);
}
}, isAdjacentNode:function (sourceNode, position) {
if (sourceNode === this.treeNode) {
return true;
}
if (sourceNode.getNextSibling() === this.treeNode && position == "before") {
return true;
}
if (sourceNode.getPreviousSibling() === this.treeNode && position == "after") {
return true;
}
return false;
}, cacheNodeCoords:function () {
var node = this.treeNode.contentNode;
this.cachedNodeY = dojo.html.getAbsolutePosition(node).y;
this.cachedNodeHeight = dojo.html.getBorderBox(node).height;
}, getPosition:function (e, DndMode) {
var mousey = e.pageY || e.clientY + dojo.body().scrollTop;
var relY = mousey - this.cachedNodeY;
var p = relY / this.cachedNodeHeight;
var position = "";
if (DndMode & dojo.widget.TreeV3.prototype.DndModes.ONTO && DndMode & dojo.widget.TreeV3.prototype.DndModes.BETWEEN) {
if (p <= 0.33) {
position = "before";
} else {
if (p <= 0.66 || this.treeNode.isExpanded && this.treeNode.children.length && !this.treeNode.isLastChild()) {
position = "onto";
} else {
position = "after";
}
} else if (DndMode & dojo.widget.TreeV3.prototype.DndModes.BETWEEN) {
//dojo.debug("BETWEEN");
if (p<=0.5 || this.treeNode.isExpanded && this.treeNode.children.length && !this.treeNode.isLastChild()) {
}
} else {
if (DndMode & dojo.widget.TreeV3.prototype.DndModes.BETWEEN) {
if (p <= 0.5 || this.treeNode.isExpanded && this.treeNode.children.length && !this.treeNode.isLastChild()) {
position = "before";
} else {
position = "after";
}
}
else if (DndMode & dojo.widget.TreeV3.prototype.DndModes.ONTO) {
//dojo.debug("ONTO");
position = "onto";
}
//dojo.debug(position);
return position;
},
getTargetParentIndex: function(source, position) {
var index = position == "before" ? this.treeNode.getParentIndex() : this.treeNode.getParentIndex()+1;
if (source.treeNode
&& this.treeNode.parent === source.treeNode.parent
&& this.treeNode.getParentIndex() > source.treeNode.getParentIndex()) {
index--; // dragging a node is different for simple move bacause of before-after issues
}
return index;
},
onDrop: function(e) {
// onDropEnd will clean position
var position = this.position;
//dojo.debug(position);
var source = e.dragObject.dragSource;
//dojo.debug("onDrop "+source.treeNode+" " + position + " "+this.treeNode);
var targetParent, targetIndex;
if (position == "onto") {
targetParent = this.treeNode;
targetIndex = 0;
} else {
targetIndex = this.getTargetParentIndex(source, position);
targetParent = this.treeNode.parent;
}
//dojo.profile.start("onDrop "+sourceTreeNode);
var r = this.getDropHandler(e, source, targetParent, targetIndex)();
//dojo.profile.end("onDrop "+sourceTreeNode);
return r;
},
/**
* determine, which action I should perform with nodes
* e.g move, clone..
*/
getDropHandler: function(e, source, targetParent, targetIndex) {
var handler;
var _this = this;
handler = function () {
var result;
//dojo.debug("Move "+source.treeNode+" to parent "+targetParent+":"+targetIndex);
if (source.treeNode) {
result = _this.controller.move(source.treeNode, targetParent, targetIndex, true);
//dojo.debug("moved "+result);
} else {
if (dojo.lang.isFunction(source.onDrop)) {
source.onDrop(targetParent, targetIndex);
}
var treeNode = source.getTreeNode();
if (treeNode) {
result = _this.controller.createChild(targetParent, targetIndex, treeNode, true);
} else {
result = true;
}
}
if (result instanceof dojo.Deferred) {
// this Deferred is always sync
var isSuccess = result.fired == 0;
if (!isSuccess) {
_this.handleDropError(source, targetParent, targetIndex, result);
}
return isSuccess;
} else {
return result;
if (DndMode & dojo.widget.TreeV3.prototype.DndModes.ONTO) {
position = "onto";
}
}
return handler;
},
handleDropError: function(source, parent, index, result) {
dojo.debug("TreeDropTargetV3.handleDropError: DND error occured");
dojo.debugShallow(result);
}
});
return position;
}, getTargetParentIndex:function (source, position) {
var index = position == "before" ? this.treeNode.getParentIndex() : this.treeNode.getParentIndex() + 1;
if (source.treeNode && this.treeNode.parent === source.treeNode.parent && this.treeNode.getParentIndex() > source.treeNode.getParentIndex()) {
index--;
}
return index;
}, onDrop:function (e) {
var position = this.position;
var source = e.dragObject.dragSource;
var targetParent, targetIndex;
if (position == "onto") {
targetParent = this.treeNode;
targetIndex = 0;
} else {
targetIndex = this.getTargetParentIndex(source, position);
targetParent = this.treeNode.parent;
}
var r = this.getDropHandler(e, source, targetParent, targetIndex)();
return r;
}, getDropHandler:function (e, source, targetParent, targetIndex) {
var handler;
var _this = this;
handler = function () {
var result;
if (source.treeNode) {
result = _this.controller.move(source.treeNode, targetParent, targetIndex, true);
} else {
if (dojo.lang.isFunction(source.onDrop)) {
source.onDrop(targetParent, targetIndex);
}
var treeNode = source.getTreeNode();
if (treeNode) {
result = _this.controller.createChild(targetParent, targetIndex, treeNode, true);
} else {
result = true;
}
}
if (result instanceof dojo.Deferred) {
var isSuccess = result.fired == 0;
if (!isSuccess) {
_this.handleDropError(source, targetParent, targetIndex, result);
}
return isSuccess;
} else {
return result;
}
};
return handler;
}, handleDropError:function (source, parent, index, result) {
dojo.debug("TreeDropTargetV3.handleDropError: DND error occured");
dojo.debugShallow(result);
}});
@@ -8,9 +8,6 @@
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.kwCompoundRequire({
common: ["dojo.dnd.DragAndDrop"],
browser: ["dojo.dnd.HtmlDragAndDrop"],
dashboard: ["dojo.dnd.HtmlDragAndDrop"]
});
dojo.kwCompoundRequire({common:["dojo.dnd.DragAndDrop"], browser:["dojo.dnd.HtmlDragAndDrop"], dashboard:["dojo.dnd.HtmlDragAndDrop"]});
dojo.provide("dojo.dnd.*");
@@ -40,12 +40,13 @@ dojo.lang.mixin(dojo.docs, {
require: function(/*String*/ require, /*bool*/ sync) {
dojo.debug("require(): " + require);
var parts = require.split("/");
var size = parts.length;
var deferred = new dojo.Deferred;
var args = {
mimetype: "text/json",
load: function(type, data){
dojo.debug("require(): loaded");
dojo.debug("require(): loaded for " + require);
if(parts[0] != "function_names") {
for(var i = 0, part; part = parts[i]; i++){
@@ -58,13 +59,13 @@ dojo.lang.mixin(dojo.docs, {
deferred.errback();
}
};
if (sync) {
args.sync = true;
}
if(location.protocol == "file:"){
if(size){
if(parts[parts.length - 1] == "documentation"){
parts[parts.length - 1] = "meta";
}
if(parts[0] == "function_names"){
args.url = [this._url, "local_json", "function_names"].join("/");
}else{
@@ -90,7 +91,7 @@ dojo.lang.mixin(dojo.docs, {
}
return fString;
},
getMeta: function(/*mixed*/ selectKey, /*String*/ pkg, /*String*/ name, /*Function*/ callback, /*String?*/ id){
getMeta: function(/*String*/ pkg, /*String*/ name, /*Function*/ callback, /*String?*/ id){
// summary: Gets information about a function in regards to its meta data
if(typeof name == "function"){
// pId: a
@@ -107,35 +108,12 @@ dojo.lang.mixin(dojo.docs, {
if(!id){
id = "_";
}
if(!selectKey){
selectKey = ++dojo.docs._count;
}
var input;
if(typeof selectKey == "object" && selectKey.selectKey){
input = selectKey;
selectKey = selectKey.selectKey;
}else{
input = {};
}
dojo.docs._buildCache({
type: "meta",
callbacks: [dojo.docs._gotMeta, callback],
pkg: pkg,
name: name,
id: id,
selectKey: selectKey,
input: input
});
},
_withPkg: function(/*String*/ type, /*Object*/ data, /*Object*/ evt, /*Object*/ input, /*String*/ newType){
dojo.debug("_withPkg(" + evt.name + ") has package: " + data[0]);
evt.pkg = data[0];
if("load" == type && evt.pkg){
evt.type = newType;
dojo.docs._buildCache(evt);
}else{
if(evt.callbacks && evt.callbacks.length){
evt.callbacks.shift()("error", {}, evt, evt.input);
@@ -153,34 +131,14 @@ dojo.lang.mixin(dojo.docs, {
evt.callbacks.shift()(type, data, evt, evt.input);
}
},
getSrc: function(/*mixed*/ selectKey, /*String*/ name, /*Function*/ callback, /*String?*/ id){
getSrc: function(/*String*/ name, /*Function*/ callback, /*String?*/ id){
// summary: Gets src file (created by the doc parser)
dojo.debug("getSrc(" + name + ")");
if(!id){
id = "_";
}
if(!selectKey){
selectKey = ++dojo.docs._count;
}
var input;
if(typeof selectKey == "object" && selectKey.selectKey){
input = selectKey;
selectKey = selectKey.selectKey;
}else{
input = {};
}
dojo.docs._buildCache({
type: "src",
callbacks: [callback],
name: name,
id: id,
input: input,
selectKey: selectKey
});
},
getDoc: function(/*mixed*/ selectKey, /*String*/ name, /*Function*/ callback, /*String?*/ id){
getDoc: function(/*String*/ name, /*Function*/ callback, /*String?*/ id){
// summary: Gets external documentation stored on Jot for a given function
dojo.debug("getDoc(" + name + ")");
@@ -188,23 +146,11 @@ dojo.lang.mixin(dojo.docs, {
id = "_";
}
if(!selectKey){
selectKey = ++dojo.docs._count;
}
var input = {};
if(typeof selectKey == "object" && selectKey.selectKey){
input.input = selectKey;
selectKey = selectKey.selectKey;
}
input.type = "doc";
input.name = name;
input.selectKey = selectKey;
input.callbacks = [callback];
input.selectKey = selectKey;
dojo.docs._buildCache(input);
},
_gotDoc: function(/*String*/ type, /*Array*/ data, /*Object*/ evt, /*Object*/ input){
dojo.debug("_gotDoc(" + evt.type + ")");
@@ -226,8 +172,7 @@ dojo.lang.mixin(dojo.docs, {
data = {
returns: evt.fn.returns,
id: evt.id,
variables: [],
selectKey: evt.selectKey
variables: []
}
if(!cache.parameters){
cache.parameters = {};
@@ -249,34 +194,16 @@ dojo.lang.mixin(dojo.docs, {
evt.callbacks.shift()("load", data, evt, input);
}
},
getPkgDoc: function(/*mixed*/ selectKey, /*String*/ name, /*Function*/ callback){
getPkgDoc: function(/*String*/ name, /*Function*/ callback){
// summary: Gets external documentation stored on Jot for a given package
dojo.debug("getPkgDoc(" + name + ")");
var input = {};
if(typeof selectKey == "object" && selectKey.selectKey){
input = selectKey;
selectKey = selectKey.selectKey;
}
if(!selectKey){
selectKey = ++dojo.docs._count;
}
dojo.docs._buildCache({
type: "pkgdoc",
callbacks: [callback],
name: name,
selectKey: selectKey,
input: input
});
},
getPkgInfo: function(/*mixed*/ selectKey, /*String*/ name, /*Function*/ callback){
getPkgInfo: function(/*String*/ name, /*Function*/ callback){
// summary: Gets a combination of the metadata and external documentation for a given package
dojo.debug("getPkgInfo(" + name + ")");
if(!selectKey){
selectKey = ++dojo.docs._count;
}
var input = {
selectKey: selectKey,
expects: {
pkginfo: ["pkgmeta", "pkgdoc"]
},
@@ -287,12 +214,10 @@ dojo.lang.mixin(dojo.docs, {
},
_getPkgInfo: function(/*String*/ type, /*Object*/ data, /*Object*/ evt){
dojo.debug("_getPkgInfo() for " + evt.type);
var key = evt.selectKey;
var input = {};
var results = {};
if(typeof key == "object"){
input = key;
key = key.selectKey;
input[evt.type] = data;
if(input.expects && input.expects.pkginfo){
for(var i = 0, expect; expect = input.expects.pkginfo[i]; i++){
@@ -310,13 +235,12 @@ dojo.lang.mixin(dojo.docs, {
input.callback("load", results, evt);
}
},
getInfo: function(/*mixed*/ selectKey, /*String*/ name, /*Function*/ callback){
getInfo: function(/*String*/ name, /*Function*/ callback){
dojo.debug("getInfo(" + name + ")");
var input = {
expects: {
"info": ["meta", "doc"]
},
selectKey: selectKey,
callback: callback
}
dojo.docs.getMeta(input, name, dojo.docs._getInfo);
@@ -344,30 +268,34 @@ dojo.lang.mixin(dojo.docs, {
return text.replace(/^<html[^<]*>/, "").replace(/<\/html>$/, "").replace(/<\w+\s*\/>/g, "");
},
getPackageMeta: function(/*Object*/ input){
dojo.debug("getPackageMeta(): " + input.pkg);
return this.require(input.pkg + "/meta", input.sync);
dojo.debug("getPackageMeta(): " + input.package);
return this.require(input.package + "/meta", input.sync);
},
OLDgetPkgMeta: function(/*mixed*/ selectKey, /*String*/ name, /*Function*/ callback){
dojo.debug("getPkgMeta(" + name + ")");
var input = {};
if(typeof selectKey == "object" && selectKey.selectKey){
input = selectKey;
selectKey = selectKey.selectKey;
}else if(!selectKey){
selectKey = ++dojo.docs._count;
getFunctionMeta: function(/*Object*/ input){
var package = input.package || "";
var name = input.name;
var id = input.id || "_";
dojo.debug("getFunctionMeta(): " + name);
if(!name) return;
if(package){
return this.require(package + "/meta/functions/" + name + "/" + id + "/meta");
}else{
this.getFunctionNames();
}
dojo.docs._buildCache({
type: "pkgmeta",
callbacks: [callback],
name: name,
selectKey: selectKey,
input: input
});
},
OLD_getPkgMeta: function(/*Object*/ input){
dojo.debug("_getPkgMeta(" + input.name + ")");
input.type = "pkgmeta";
dojo.docs._buildCache(input);
getFunctionDocumentation: function(/*Object*/ input){
var package = input.package || "";
var name = input.name;
var id = input.id || "_";
dojo.debug("getFunctionDocumentation(): " + name);
if(!name) return;
if(package){
return this.require(package + "/meta/functions/" + name + "/" + id + "/documentation");
}
},
_onDocSearch: function(/*Object*/ input){
var _this = this;
@@ -414,7 +342,7 @@ dojo.lang.mixin(dojo.docs, {
for(var i = 0, fn; fn = data[pkg][i]; i++){
if(fn.toLowerCase().indexOf(name) != -1){
dojo.debug("_onDocSearch(): Search matched " + fn);
var meta = _this.getPackageMeta({pkg: pkg});
var meta = _this.getPackageMeta({package: pkg});
meta.addCallback(closure(pkg, fn));
list.push(meta);
@@ -473,7 +401,6 @@ dojo.lang.mixin(dojo.docs, {
size: 0,
methods: [],
pkg: pkg,
selectKey: evt.selectKey,
requires: requires
}
var rePrivate = /_[^.]+$/;
@@ -499,7 +426,7 @@ dojo.lang.mixin(dojo.docs, {
if(input.loaded == input.pkgs.length){
var pkgs = input.pkgs;
var name = input.pkg;
var results = {selectKey: evt.selectKey, methods: []};
var results = {methods: []};
var rePrivate = /_[^.]+$/;
data = dojo.docs._cache;
@@ -540,28 +467,30 @@ dojo.lang.mixin(dojo.docs, {
_onDocSelectFunction: function(/*Object*/ input){
// summary: Get doc, meta, and src
var name = input.name;
var pkg = input.pkg;
var package = input.package || "";
var id = input.id || "_";
dojo.debug("_onDocSelectFunction(" + name + ")");
if(!name){
return false;
}
if(!input.selectKey){
input.selectKey = ++dojo.docs._count;
}
input.expects = {
"docresults": ["meta", "doc", "pkgmeta"]
}
dojo.docs.getMeta(input, pkg, name, dojo.docs._onDocSelectResults);
dojo.docs.getDoc(input, pkg, name, dojo.docs._onDocSelectResults);
if(!name || !package) return false;
var pkgMeta = this.getPackageMeta({package: package});
var meta = this.getFunctionMeta({package: package, name: name, id: id});
var doc = this.getFunctionDocumentation({package: package, name: name, id: id});
var list = new dojo.DeferredList([pkgMeta, meta, doc]);
list.addCallback(function(results){
dojo.debug("_onDocSelectFunction() loaded");
for(var i = 0, result; result = results[i]; i++){
dojo.debugShallow(result[1]);
}
});
return list;
},
_onDocSelectPackage: function(/*Object*/ input){
dojo.debug("_onDocSelectPackage(" + input.name + ")")
input.expects = {
"pkgresults": ["pkgmeta", "pkgdoc"]
};
if(!input.selectKey){
input.selectKey = ++dojo.docs._count;
}
dojo.docs.getPkgMeta(input, input.name, dojo.docs._onPkgResults);
dojo.docs.getPkgDoc(input, input.name, dojo.docs._onPkgResults);
},
@@ -589,311 +518,6 @@ dojo.lang.mixin(dojo.docs, {
// summary: Call this function to send the /docs/function/detail topic event
},
_buildCache: function(/*Object*/ input){
dojo.debug("_buildCache(" + input.type + ", " + input.name + ")");
// Get stuff from the input object
var type = input.type;
var pkg = input.pkg;
var callbacks = input.callbacks;
var id = input.id;
if(!id){
id = input.id = "_";
}
var name = input.name;
var selectKey = input.selectKey;
var META = "meta";
var METHODS = "methods";
var SRC = "src";
var DESCRIPTION = "description";
var INPUT = "input";
var LOAD = "load";
var ERROR = "error";
var docs = dojo.docs;
var getCache = docs._getCache;
// Stuff to pass to RPC
var search = [];
if(type == "doc"){
if(!pkg){
docs.functionPackages(selectKey, name, function(){ var a = arguments; docs._withPkg.call(this, a[0], a[1], a[2], a[3], "doc"); }, input);
return;
}else{
var cached = getCache(pkg, META, METHODS, name, id, META);
if(cached[DESCRIPTION]){
callbacks.shift()(LOAD, cached[DESCRIPTION], input, input[INPUT]);
return;
}
var obj = {};
obj.forFormName = "DocFnForm";
obj.limit = 1;
obj.filter = "it/DocFnForm/require = '" + pkg + "' and it/DocFnForm/name = '" + name + "' and ";
if(id == "_"){
obj.filter += " not(it/DocFnForm/id)";
}else{
obj.filter += " it/DocFnForm/id = '" + id + "'";
}
obj.load = function(data){
var cached = getCache(pkg, META, METHODS, name, id, META);
var description = "";
var returns = "";
if(data.list && data.list.length){
description = docs._getMainText(data.list[0]["main/text"]);
returns = data.list[0]["DocFnForm/returns"];
}
cached[DESCRIPTION] = description;
if(!cached.returns){
cached.returns = {};
}
cached.returns.summary = returns;
input.type = "fn";
docs._gotDoc(LOAD, cached, input, input[INPUT]);
}
obj.error = function(data){
input.type = "fn";
docs._gotDoc(ERROR, {}, input, input[INPUT]);
}
search.push(obj);
obj = {};
obj.forFormName = "DocParamForm";
obj.filter = "it/DocParamForm/fns = '" + pkg + "=>" + name;
if(id != "_"){
obj.filter += "=>" + id;
}
obj.filter += "'";
obj.load = function(data){
var cache = getCache(pkg, META, METHODS, name, id, META);
for(var i = 0, param; param = data.list[i]; i++){
var pName = param["DocParamForm/name"];
if(!cache.parameters[pName]){
cache.parameters[pName] = {};
}
cache.parameters[pName].summary = param["DocParamForm/desc"];
}
input.type = "param";
docs._gotDoc(LOAD, cache.parameters, input);
}
obj.error = function(data){
input.type = "param";
docs._gotDoc(ERROR, {}, input);
}
search.push(obj);
}
}else if(type == "pkgdoc"){
var cached = getCache(name, META);
if(cached[DESCRIPTION]){
callbacks.shift()(LOAD, {description: cached[DESCRIPTION], path: cached.path}, input, input.input);
return;
}
var obj = {};
obj.forFormName = "DocPkgForm";
obj.limit = 1;
obj.filter = "it/DocPkgForm/require = '" + name + "'";
obj.load = function(data){
var description = "";
var list = data.list;
if(list && list.length && list[0]["main/text"]){
description = docs._getMainText(list[0]["main/text"]);
cached[DESCRIPTION] = description;
cached.path = list[0].name;
}
if(callbacks && callbacks.length){
callbacks.shift()(LOAD, {description: description, path: cached.path}, input, input.input);
}
}
obj.error = function(data){
if(callbacks && callbacks.length){
callbacks.shift()(ERROR, "", input, input.input);
}
}
search.push(obj);
}else if(type == "function_names"){
var cached = getCache();
if(!cached.function_names){
dojo.debug("_buildCache() new cache");
if(callbacks && callbacks.length){
docs._callbacks.function_names.push([input, callbacks.shift()]);
}
cached.function_names = {loading: true};
var obj = {};
obj.url = "function_names";
obj.load = function(type, data, evt){
cached.function_names = data;
while(docs._callbacks.function_names.length){
var parts = docs._callbacks.function_names.pop();
parts[1](LOAD, data, parts[0]);
}
}
obj.error = function(type, data, evt){
while(docs._callbacks.function_names.length){
var parts = docs._callbacks.function_names.pop();
parts[1](LOAD, {}, parts[0]);
}
}
search.push(obj);
}else if(cached.function_names.loading){
dojo.debug("_buildCache() loading cache, adding to callback list");
if(callbacks && callbacks.length){
docs._callbacks.function_names.push([input, callbacks.shift()]);
}
return;
}else{
dojo.debug("_buildCache() loading from cache");
if(callbacks && callbacks.length){
callbacks.shift()(LOAD, cached.function_names, input);
}
return;
}
}else if(type == META || type == SRC){
if(!pkg){
if(type == META){
docs.functionPackages(selectKey, name, function(){ var a = arguments; docs._withPkg.call(this, a[0], a[1], a[2], a[3], META); }, input);
return;
}else{
docs.functionPackages(selectKey, name, function(){ var a = arguments; docs._withPkg.call(this, a[0], a[1], a[2], a[3], SRC); }, input);
return;
}
}else{
var cached = getCache(pkg, META, METHODS, name, id);
if(cached[type] && cached[type].returns){
if(callbacks && callbacks.length){
callbacks.shift()(LOAD, cached[type], input);
return;
}
}
dojo.debug("Finding " + type + " for: " + pkg + ", function: " + name + ", id: " + id);
var obj = {};
if(type == SRC){
obj.mimetype = "text/plain"
}
obj.url = pkg + "/" + name + "/" + id + "/" + type;
obj.load = function(type, data, evt){
dojo.debug("_buildCache() loaded " + input.type);
if(input.type == SRC){
getCache(pkg, META, METHODS, name, id).src = data;
if(callbacks && callbacks.length){
callbacks.shift()(LOAD, data, input, input[INPUT]);
}
}else{
var cache = getCache(pkg, META, METHODS, name, id, META);
if(!cache.parameters){
cache.parameters = {};
}
for(var i = 0, param; param = data.parameters[i]; i++){
if(!cache.parameters[param[1]]){
cache.parameters[param[1]] = {};
}
cache.parameters[param[1]].type = param[0];
}
if(!cache.returns){
cache.returns = {};
}
cache.returns.type = data.returns;
}
if(callbacks && callbacks.length){
callbacks.shift()(LOAD, cache, input, input[INPUT]);
}
}
obj.error = function(type, data, evt){
if(callbacks && callbacks.length){
callbacks.shift()(ERROR, {}, input, input[INPUT]);
}
}
}
search.push(obj);
}else if(type == "pkgmeta"){
var cached = getCache(name, "meta");
if(cached.requires){
if(callbacks && callbacks.length){
callbacks.shift()(LOAD, cached, input, input[INPUT]);
return;
}
}
dojo.debug("Finding package meta for: " + name);
var obj = {};
obj.url = name + "/meta";
obj.load = function(type, data, evt){
dojo.debug("_buildCache() loaded for: " + name);
var methods = data.methods;
if(methods){
for(var method in methods){
if (method == "is") {
continue;
}
for(var pId in methods[method]){
getCache(name, META, METHODS, method, pId, META).summary = methods[method][pId];
}
}
}
var requires = data.requires;
var cache = getCache(name, META);
if(requires){
cache.requires = requires;
}
if(callbacks && callbacks.length){
callbacks.shift()(LOAD, cache, input, input[INPUT]);
}
}
obj.error = function(type, data, evt){
if(callbacks && callbacks.length){
callbacks.shift()(ERROR, {}, input, input[INPUT]);
}
}
search.push(obj);
}
for(var i = 0, obj; obj = search[i]; i++){
var load = obj.load;
var error = obj.error;
delete obj.load;
delete obj.error;
var mimetype = obj.mimetype;
if(!mimetype){
mimetype = "text/json"
}
if(obj.url){
dojo.io.bind({
url: new dojo.uri.Uri(docs._url, obj.url),
input: input,
mimetype: mimetype,
error: error,
load: load
});
}else{
docs._rpc.callRemote("search", obj).addCallbacks(load, error);
}
}
},
selectFunction: function(/*String*/ name, /*String?*/ id){
// summary: The combined information
},
@@ -939,7 +563,7 @@ dojo.lang.mixin(dojo.docs, {
},
_savedPkgRpc: function(type){
},
functionPackages: function(/*mixed*/ selectKey, /*String*/ name, /*Function*/ callback, /*Object*/ input){
functionPackages: function(/*String*/ name, /*Function*/ callback, /*Object*/ input){
// summary: Gets the package associated with a function and stores it in the .pkg value of input
dojo.debug("functionPackages() name: " + name);
@@ -954,7 +578,6 @@ dojo.lang.mixin(dojo.docs, {
input.name = name;
input.callbacks.unshift(callback);
input.callbacks.unshift(dojo.docs._functionPackages);
dojo.docs._buildCache(input);
},
_functionPackages: function(/*String*/ type, /*Array*/ data, /*Object*/ evt){
dojo.debug("_functionPackages() name: " + evt.name);
@@ -1045,4 +668,4 @@ dojo.event.topic.subscribe("/docs/package/select", dojo.docs, "_onDocSelectPacka
dojo.event.topic.registerPublisher("/docs/function/results", dojo.docs, "_printFunctionResults");
dojo.event.topic.registerPublisher("/docs/function/detail", dojo.docs, "_printFunctionDetail");
dojo.event.topic.registerPublisher("/docs/package/detail", dojo.docs, "_printPkgResult");
dojo.event.topic.registerPublisher("/docs/package/detail", dojo.docs, "_printPkgResult");
@@ -9,514 +9,371 @@
*/
dojo.provide("dojo.dom");
dojo.dom.ELEMENT_NODE = 1;
dojo.dom.ATTRIBUTE_NODE = 2;
dojo.dom.TEXT_NODE = 3;
dojo.dom.CDATA_SECTION_NODE = 4;
dojo.dom.ENTITY_REFERENCE_NODE = 5;
dojo.dom.ENTITY_NODE = 6;
dojo.dom.PROCESSING_INSTRUCTION_NODE = 7;
dojo.dom.COMMENT_NODE = 8;
dojo.dom.DOCUMENT_NODE = 9;
dojo.dom.DOCUMENT_TYPE_NODE = 10;
dojo.dom.DOCUMENT_FRAGMENT_NODE = 11;
dojo.dom.NOTATION_NODE = 12;
dojo.dom.ELEMENT_NODE = 1;
dojo.dom.ATTRIBUTE_NODE = 2;
dojo.dom.TEXT_NODE = 3;
dojo.dom.CDATA_SECTION_NODE = 4;
dojo.dom.ENTITY_REFERENCE_NODE = 5;
dojo.dom.ENTITY_NODE = 6;
dojo.dom.PROCESSING_INSTRUCTION_NODE = 7;
dojo.dom.COMMENT_NODE = 8;
dojo.dom.DOCUMENT_NODE = 9;
dojo.dom.DOCUMENT_TYPE_NODE = 10;
dojo.dom.DOCUMENT_FRAGMENT_NODE = 11;
dojo.dom.NOTATION_NODE = 12;
dojo.dom.dojoml = "http://www.dojotoolkit.org/2004/dojoml";
/**
* comprehensive list of XML namespaces
**/
dojo.dom.xmlns = {
// summary
// aliases for various common XML namespaces
svg : "http://www.w3.org/2000/svg",
smil : "http://www.w3.org/2001/SMIL20/",
mml : "http://www.w3.org/1998/Math/MathML",
cml : "http://www.xml-cml.org",
xlink : "http://www.w3.org/1999/xlink",
xhtml : "http://www.w3.org/1999/xhtml",
xul : "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
xbl : "http://www.mozilla.org/xbl",
fo : "http://www.w3.org/1999/XSL/Format",
xsl : "http://www.w3.org/1999/XSL/Transform",
xslt : "http://www.w3.org/1999/XSL/Transform",
xi : "http://www.w3.org/2001/XInclude",
xforms : "http://www.w3.org/2002/01/xforms",
saxon : "http://icl.com/saxon",
xalan : "http://xml.apache.org/xslt",
xsd : "http://www.w3.org/2001/XMLSchema",
dt: "http://www.w3.org/2001/XMLSchema-datatypes",
xsi : "http://www.w3.org/2001/XMLSchema-instance",
rdf : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
rdfs : "http://www.w3.org/2000/01/rdf-schema#",
dc : "http://purl.org/dc/elements/1.1/",
dcq: "http://purl.org/dc/qualifiers/1.0",
"soap-env" : "http://schemas.xmlsoap.org/soap/envelope/",
wsdl : "http://schemas.xmlsoap.org/wsdl/",
AdobeExtensions : "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
};
dojo.dom.isNode = function(/* object */wh){
// summary
// checks to see if wh is actually a node.
if(typeof Element == "function") {
dojo.dom.xmlns = {svg:"http://www.w3.org/2000/svg", smil:"http://www.w3.org/2001/SMIL20/", mml:"http://www.w3.org/1998/Math/MathML", cml:"http://www.xml-cml.org", xlink:"http://www.w3.org/1999/xlink", xhtml:"http://www.w3.org/1999/xhtml", xul:"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", xbl:"http://www.mozilla.org/xbl", fo:"http://www.w3.org/1999/XSL/Format", xsl:"http://www.w3.org/1999/XSL/Transform", xslt:"http://www.w3.org/1999/XSL/Transform", xi:"http://www.w3.org/2001/XInclude", xforms:"http://www.w3.org/2002/01/xforms", saxon:"http://icl.com/saxon", xalan:"http://xml.apache.org/xslt", xsd:"http://www.w3.org/2001/XMLSchema", dt:"http://www.w3.org/2001/XMLSchema-datatypes", xsi:"http://www.w3.org/2001/XMLSchema-instance", rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#", rdfs:"http://www.w3.org/2000/01/rdf-schema#", dc:"http://purl.org/dc/elements/1.1/", dcq:"http://purl.org/dc/qualifiers/1.0", "soap-env":"http://schemas.xmlsoap.org/soap/envelope/", wsdl:"http://schemas.xmlsoap.org/wsdl/", AdobeExtensions:"http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"};
dojo.dom.isNode = function (wh) {
if (typeof Element == "function") {
try {
return wh instanceof Element; // boolean
} catch(E) {}
return wh instanceof Element;
}
catch (e) {
}
} else {
// best-guess
return wh && !isNaN(wh.nodeType); // boolean
return wh && !isNaN(wh.nodeType);
}
}
dojo.dom.getUniqueId = function(){
// summary
// returns a unique string for use with any DOM element
};
dojo.dom.getUniqueId = function () {
var _document = dojo.doc();
do {
var id = "dj_unique_" + (++arguments.callee._idIncrement);
}while(_document.getElementById(id));
return id; // string
}
} while (_document.getElementById(id));
return id;
};
dojo.dom.getUniqueId._idIncrement = 0;
dojo.dom.firstElement = dojo.dom.getFirstChildElement = function(/* Element */parentNode, /* string? */tagName){
// summary
// returns the first child element matching tagName
dojo.dom.firstElement = dojo.dom.getFirstChildElement = function (parentNode, tagName) {
var node = parentNode.firstChild;
while(node && node.nodeType != dojo.dom.ELEMENT_NODE){
while (node && node.nodeType != dojo.dom.ELEMENT_NODE) {
node = node.nextSibling;
}
if(tagName && node && node.tagName && node.tagName.toLowerCase() != tagName.toLowerCase()) {
if (tagName && node && node.tagName && node.tagName.toLowerCase() != tagName.toLowerCase()) {
node = dojo.dom.nextElement(node, tagName);
}
return node; // Element
}
dojo.dom.lastElement = dojo.dom.getLastChildElement = function(/* Element */parentNode, /* string? */tagName){
// summary
// returns the last child element matching tagName
return node;
};
dojo.dom.lastElement = dojo.dom.getLastChildElement = function (parentNode, tagName) {
var node = parentNode.lastChild;
while(node && node.nodeType != dojo.dom.ELEMENT_NODE) {
while (node && node.nodeType != dojo.dom.ELEMENT_NODE) {
node = node.previousSibling;
}
if(tagName && node && node.tagName && node.tagName.toLowerCase() != tagName.toLowerCase()) {
if (tagName && node && node.tagName && node.tagName.toLowerCase() != tagName.toLowerCase()) {
node = dojo.dom.prevElement(node, tagName);
}
return node; // Element
}
dojo.dom.nextElement = dojo.dom.getNextSiblingElement = function(/* Node */node, /* string? */tagName){
// summary
// returns the next sibling element matching tagName
if(!node) { return null; }
return node;
};
dojo.dom.nextElement = dojo.dom.getNextSiblingElement = function (node, tagName) {
if (!node) {
return null;
}
do {
node = node.nextSibling;
} while(node && node.nodeType != dojo.dom.ELEMENT_NODE);
if(node && tagName && tagName.toLowerCase() != node.tagName.toLowerCase()) {
} while (node && node.nodeType != dojo.dom.ELEMENT_NODE);
if (node && tagName && tagName.toLowerCase() != node.tagName.toLowerCase()) {
return dojo.dom.nextElement(node, tagName);
}
return node; // Element
}
dojo.dom.prevElement = dojo.dom.getPreviousSiblingElement = function(/* Node */node, /* string? */tagName){
// summary
// returns the previous sibling element matching tagName
if(!node) { return null; }
if(tagName) { tagName = tagName.toLowerCase(); }
return node;
};
dojo.dom.prevElement = dojo.dom.getPreviousSiblingElement = function (node, tagName) {
if (!node) {
return null;
}
if (tagName) {
tagName = tagName.toLowerCase();
}
do {
node = node.previousSibling;
} while(node && node.nodeType != dojo.dom.ELEMENT_NODE);
if(node && tagName && tagName.toLowerCase() != node.tagName.toLowerCase()) {
} while (node && node.nodeType != dojo.dom.ELEMENT_NODE);
if (node && tagName && tagName.toLowerCase() != node.tagName.toLowerCase()) {
return dojo.dom.prevElement(node, tagName);
}
return node; // Element
}
// TODO: hmph
/*this.forEachChildTag = function(node, unaryFunc) {
var child = this.getFirstChildTag(node);
while(child) {
if(unaryFunc(child) == "break") { break; }
child = this.getNextSiblingTag(child);
}
}*/
dojo.dom.moveChildren = function(/* Element */srcNode, /* Element */destNode, /* boolean? */trim){
// summary
// Moves children from srcNode to destNode and returns the count of children moved;
// will trim off text nodes if trim == true
return node;
};
dojo.dom.moveChildren = function (srcNode, destNode, trim) {
var count = 0;
if(trim) {
while(srcNode.hasChildNodes() &&
srcNode.firstChild.nodeType == dojo.dom.TEXT_NODE) {
if (trim) {
while (srcNode.hasChildNodes() && srcNode.firstChild.nodeType == dojo.dom.TEXT_NODE) {
srcNode.removeChild(srcNode.firstChild);
}
while(srcNode.hasChildNodes() &&
srcNode.lastChild.nodeType == dojo.dom.TEXT_NODE) {
while (srcNode.hasChildNodes() && srcNode.lastChild.nodeType == dojo.dom.TEXT_NODE) {
srcNode.removeChild(srcNode.lastChild);
}
}
while(srcNode.hasChildNodes()){
while (srcNode.hasChildNodes()) {
destNode.appendChild(srcNode.firstChild);
count++;
}
return count; // number
}
dojo.dom.copyChildren = function(/* Element */srcNode, /* Element */destNode, /* boolean? */trim){
// summary
// Copies children from srcNde to destNode and returns the count of children copied;
// will trim off text nodes if trim == true
return count;
};
dojo.dom.copyChildren = function (srcNode, destNode, trim) {
var clonedNode = srcNode.cloneNode(true);
return this.moveChildren(clonedNode, destNode, trim); // number
}
dojo.dom.removeChildren = function(/* Element */node){
// summary
// removes all children from node and returns the count of children removed.
var count = node.childNodes.length;
while(node.hasChildNodes()){ node.removeChild(node.firstChild); }
return count; // number
}
dojo.dom.replaceChildren = function(/* Element */node, /* Node */newChild){
// summary
// Removes all children of node and appends newChild
// FIXME: what if newChild is an array-like object?
return this.moveChildren(clonedNode, destNode, trim);
};
dojo.dom.replaceChildren = function (node, newChild) {
var nodes = [];
if (dojo.render.html.ie) {
for (var i = 0; i < node.childNodes.length; i++) {
nodes.push(node.childNodes[i]);
}
}
dojo.dom.removeChildren(node);
node.appendChild(newChild);
}
dojo.dom.removeNode = function(/* Node */node){
// summary
// if node has a parent, removes node from parent and returns a reference to the removed child.
if(node && node.parentNode){
// return a ref to the removed child
return node.parentNode.removeChild(node); // Node
for (var i = 0; i < nodes.length; i++) {
dojo.dom.destroyNode(nodes[i]);
}
}
dojo.dom.getAncestors = function(/* Node */node, /* function? */filterFunction, /* boolean? */returnFirstHit) {
// summary
// returns all ancestors matching optional filterFunction; will return only the first if returnFirstHit
};
dojo.dom.removeChildren = function (node) {
var count = node.childNodes.length;
while (node.hasChildNodes()) {
dojo.dom.removeNode(node.firstChild);
}
return count;
};
dojo.dom.replaceNode = function (node, newNode) {
return node.parentNode.replaceChild(newNode, node);
};
dojo.dom.destroyNode = function (node) {
if (node.parentNode) {
node = dojo.dom.removeNode(node);
}
if (node.nodeType != 3) {
if (dojo.evalObjPath("dojo.event.browser.clean", false)) {
dojo.event.browser.clean(node);
}
if (dojo.render.html.ie) {
node.outerHTML = "";
}
}
};
dojo.dom.removeNode = function (node) {
if (node && node.parentNode) {
return node.parentNode.removeChild(node);
}
};
dojo.dom.getAncestors = function (node, filterFunction, returnFirstHit) {
var ancestors = [];
var isFunction = (filterFunction && (filterFunction instanceof Function || typeof filterFunction == "function"));
while(node) {
while (node) {
if (!isFunction || filterFunction(node)) {
ancestors.push(node);
}
if (returnFirstHit && ancestors.length > 0) {
return ancestors[0]; // Node
if (returnFirstHit && ancestors.length > 0) {
return ancestors[0];
}
node = node.parentNode;
}
if (returnFirstHit) { return null; }
return ancestors; // array
}
dojo.dom.getAncestorsByTag = function(/* Node */node, /* string */tag, /* boolean? */returnFirstHit) {
// summary
// returns all ancestors matching tag (as tagName), will only return first one if returnFirstHit
if (returnFirstHit) {
return null;
}
return ancestors;
};
dojo.dom.getAncestorsByTag = function (node, tag, returnFirstHit) {
tag = tag.toLowerCase();
return dojo.dom.getAncestors(node, function(el){
return ((el.tagName)&&(el.tagName.toLowerCase() == tag));
}, returnFirstHit); // Node || array
}
dojo.dom.getFirstAncestorByTag = function(/* Node */node, /* string */tag) {
// summary
// Returns first ancestor of node with tag tagName
return dojo.dom.getAncestorsByTag(node, tag, true); // Node
}
dojo.dom.isDescendantOf = function(/* Node */node, /* Node */ancestor, /* boolean? */guaranteeDescendant){
// summary
// Returns boolean if node is a descendant of ancestor
// guaranteeDescendant allows us to be a "true" isDescendantOf function
if(guaranteeDescendant && node) { node = node.parentNode; }
while(node) {
if(node == ancestor){
return true; // boolean
return dojo.dom.getAncestors(node, function (el) {
return ((el.tagName) && (el.tagName.toLowerCase() == tag));
}, returnFirstHit);
};
dojo.dom.getFirstAncestorByTag = function (node, tag) {
return dojo.dom.getAncestorsByTag(node, tag, true);
};
dojo.dom.isDescendantOf = function (node, ancestor, guaranteeDescendant) {
if (guaranteeDescendant && node) {
node = node.parentNode;
}
while (node) {
if (node == ancestor) {
return true;
}
node = node.parentNode;
}
return false; // boolean
}
dojo.dom.innerXML = function(/* Node */node){
// summary
// Implementation of MS's innerXML function.
if(node.innerXML){
return node.innerXML; // string
}else if (node.xml){
return node.xml; // string
}else if(typeof XMLSerializer != "undefined"){
return (new XMLSerializer()).serializeToString(node); // string
return false;
};
dojo.dom.innerXML = function (node) {
if (node.innerXML) {
return node.innerXML;
} else {
if (node.xml) {
return node.xml;
} else {
if (typeof XMLSerializer != "undefined") {
return (new XMLSerializer()).serializeToString(node);
}
}
}
}
dojo.dom.createDocument = function(){
// summary
// cross-browser implementation of creating an XML document object.
};
dojo.dom.createDocument = function () {
var doc = null;
var _document = dojo.doc();
if(!dj_undef("ActiveXObject")){
var prefixes = [ "MSXML2", "Microsoft", "MSXML", "MSXML3" ];
for(var i = 0; i<prefixes.length; i++){
try{
doc = new ActiveXObject(prefixes[i]+".XMLDOM");
}catch(e){ /* squelch */ };
if(doc){ break; }
}
}else if((_document.implementation)&&
(_document.implementation.createDocument)){
doc = _document.implementation.createDocument("", "", null);
}
return doc; // DOMDocument
}
dojo.dom.createDocumentFromText = function(/* string */str, /* string? */mimetype){
// summary
// attempts to create a Document object based on optional mime-type, using str as the contents of the document
if(!mimetype){ mimetype = "text/xml"; }
if(!dj_undef("DOMParser")){
var parser = new DOMParser();
return parser.parseFromString(str, mimetype); // DOMDocument
}else if(!dj_undef("ActiveXObject")){
var domDoc = dojo.dom.createDocument();
if(domDoc){
domDoc.async = false;
domDoc.loadXML(str);
return domDoc; // DOMDocument
}else{
dojo.debug("toXml didn't work?");
}
/*
}else if((dojo.render.html.capable)&&(dojo.render.html.safari)){
// FIXME: this doesn't appear to work!
// from: http://web-graphics.com/mtarchive/001606.php
// var xml = '<?xml version="1.0"?>'+str;
var mtype = "text/xml";
var xml = '<?xml version="1.0"?>'+str;
var url = "data:"+mtype+";charset=utf-8,"+encodeURIComponent(xml);
var req = new XMLHttpRequest();
req.open("GET", url, false);
req.overrideMimeType(mtype);
req.send(null);
return req.responseXML;
*/
}else{
var _document = dojo.doc();
if(_document.createElement){
// FIXME: this may change all tags to uppercase!
var tmp = _document.createElement("xml");
tmp.innerHTML = str;
if(_document.implementation && _document.implementation.createDocument) {
var xmlDoc = _document.implementation.createDocument("foo", "", null);
for(var i = 0; i < tmp.childNodes.length; i++) {
xmlDoc.importNode(tmp.childNodes.item(i), true);
}
return xmlDoc; // DOMDocument
if (!dj_undef("ActiveXObject")) {
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
for (var i = 0; i < prefixes.length; i++) {
try {
doc = new ActiveXObject(prefixes[i] + ".XMLDOM");
}
catch (e) {
}
if (doc) {
break;
}
}
} else {
if ((_document.implementation) && (_document.implementation.createDocument)) {
doc = _document.implementation.createDocument("", "", null);
}
}
return doc;
};
dojo.dom.createDocumentFromText = function (str, mimetype) {
if (!mimetype) {
mimetype = "text/xml";
}
if (!dj_undef("DOMParser")) {
var parser = new DOMParser();
return parser.parseFromString(str, mimetype);
} else {
if (!dj_undef("ActiveXObject")) {
var domDoc = dojo.dom.createDocument();
if (domDoc) {
domDoc.async = false;
domDoc.loadXML(str);
return domDoc;
} else {
dojo.debug("toXml didn't work?");
}
} else {
var _document = dojo.doc();
if (_document.createElement) {
var tmp = _document.createElement("xml");
tmp.innerHTML = str;
if (_document.implementation && _document.implementation.createDocument) {
var xmlDoc = _document.implementation.createDocument("foo", "", null);
for (var i = 0; i < tmp.childNodes.length; i++) {
xmlDoc.importNode(tmp.childNodes.item(i), true);
}
return xmlDoc;
}
return ((tmp.document) && (tmp.document.firstChild ? tmp.document.firstChild : tmp));
}
// FIXME: probably not a good idea to have to return an HTML fragment
// FIXME: the tmp.doc.firstChild is as tested from IE, so it may not
// work that way across the board
return ((tmp.document)&&
(tmp.document.firstChild ? tmp.document.firstChild : tmp)); // DOMDocument
}
}
return null;
}
dojo.dom.prependChild = function(/* Element */node, /* Element */parent) {
// summary
// prepends node to parent's children nodes
if(parent.firstChild) {
};
dojo.dom.prependChild = function (node, parent) {
if (parent.firstChild) {
parent.insertBefore(node, parent.firstChild);
} else {
parent.appendChild(node);
}
return true; // boolean
}
dojo.dom.insertBefore = function(/* Node */node, /* Node */ref, /* boolean? */force){
// summary
// Try to insert node before ref
if (force != true &&
(node === ref || node.nextSibling === ref)){ return false; }
return true;
};
dojo.dom.insertBefore = function (node, ref, force) {
if ((force != true) && (node === ref || node.nextSibling === ref)) {
return false;
}
var parent = ref.parentNode;
parent.insertBefore(node, ref);
return true; // boolean
}
dojo.dom.insertAfter = function(/* Node */node, /* Node */ref, /* boolean? */force){
// summary
// Try to insert node after ref
return true;
};
dojo.dom.insertAfter = function (node, ref, force) {
var pn = ref.parentNode;
if(ref == pn.lastChild){
if((force != true)&&(node === ref)){
return false; // boolean
if (ref == pn.lastChild) {
if ((force != true) && (node === ref)) {
return false;
}
pn.appendChild(node);
}else{
return this.insertBefore(node, ref.nextSibling, force); // boolean
} else {
return this.insertBefore(node, ref.nextSibling, force);
}
return true; // boolean
}
dojo.dom.insertAtPosition = function(/* Node */node, /* Node */ref, /* string */position){
// summary
// attempt to insert node in relation to ref based on position
if((!node)||(!ref)||(!position)){
return false; // boolean
return true;
};
dojo.dom.insertAtPosition = function (node, ref, position) {
if ((!node) || (!ref) || (!position)) {
return false;
}
switch(position.toLowerCase()){
case "before":
return dojo.dom.insertBefore(node, ref); // boolean
case "after":
return dojo.dom.insertAfter(node, ref); // boolean
case "first":
if(ref.firstChild){
return dojo.dom.insertBefore(node, ref.firstChild); // boolean
}else{
ref.appendChild(node);
return true; // boolean
}
break;
default: // aka: last
switch (position.toLowerCase()) {
case "before":
return dojo.dom.insertBefore(node, ref);
case "after":
return dojo.dom.insertAfter(node, ref);
case "first":
if (ref.firstChild) {
return dojo.dom.insertBefore(node, ref.firstChild);
} else {
ref.appendChild(node);
return true; // boolean
}
}
dojo.dom.insertAtIndex = function(/* Node */node, /* Element */containingNode, /* number */insertionIndex){
// summary
// insert node into child nodes nodelist of containingNode at insertionIndex.
var siblingNodes = containingNode.childNodes;
// if there aren't any kids yet, just add it to the beginning
if (!siblingNodes.length){
containingNode.appendChild(node);
return true; // boolean
}
// otherwise we need to walk the childNodes
// and find our spot
var after = null;
for(var i=0; i<siblingNodes.length; i++){
var sibling_index = siblingNodes.item(i)["getAttribute"] ? parseInt(siblingNodes.item(i).getAttribute("dojoinsertionindex")) : -1;
if (sibling_index < insertionIndex){
after = siblingNodes.item(i);
return true;
}
break;
default:
ref.appendChild(node);
return true;
}
if (after){
// add it after the node in {after}
return dojo.dom.insertAfter(node, after); // boolean
}else{
// add it to the start
return dojo.dom.insertBefore(node, siblingNodes.item(0)); // boolean
};
dojo.dom.insertAtIndex = function (node, containingNode, insertionIndex) {
var siblingNodes = containingNode.childNodes;
if (!siblingNodes.length || siblingNodes.length == insertionIndex) {
containingNode.appendChild(node);
return true;
}
}
dojo.dom.textContent = function(/* Node */node, /* string */text){
// summary
// implementation of the DOM Level 3 attribute; scan node for text
if (arguments.length>1) {
if (insertionIndex == 0) {
return dojo.dom.prependChild(node, containingNode);
}
return dojo.dom.insertAfter(node, siblingNodes[insertionIndex - 1]);
};
dojo.dom.textContent = function (node, text) {
if (arguments.length > 1) {
var _document = dojo.doc();
dojo.dom.replaceChildren(node, _document.createTextNode(text));
return text; // string
return text;
} else {
if(node.textContent != undefined){ //FF 1.5
return node.textContent; // string
if (node.textContent != undefined) {
return node.textContent;
}
var _result = "";
if (node == null) { return _result; }
if (node == null) {
return _result;
}
for (var i = 0; i < node.childNodes.length; i++) {
switch (node.childNodes[i].nodeType) {
case 1: // ELEMENT_NODE
case 5: // ENTITY_REFERENCE_NODE
_result += dojo.dom.textContent(node.childNodes[i]);
break;
case 3: // TEXT_NODE
case 2: // ATTRIBUTE_NODE
case 4: // CDATA_SECTION_NODE
_result += node.childNodes[i].nodeValue;
break;
default:
break;
case 1:
case 5:
_result += dojo.dom.textContent(node.childNodes[i]);
break;
case 3:
case 2:
case 4:
_result += node.childNodes[i].nodeValue;
break;
default:
break;
}
}
return _result; // string
return _result;
}
}
dojo.dom.hasParent = function (/* Node */node) {
// summary
// returns whether or not node is a child of another node.
return node && node.parentNode && dojo.dom.isNode(node.parentNode); // boolean
}
/**
* Examples:
*
* myFooNode = <foo />
* isTag(myFooNode, "foo"); // returns "foo"
* isTag(myFooNode, "bar"); // returns ""
* isTag(myFooNode, "FOO"); // returns ""
* isTag(myFooNode, "hey", "foo", "bar"); // returns "foo"
**/
dojo.dom.isTag = function(/* Node */node /* ... */) {
// summary
// determines if node has any of the provided tag names and returns the tag name that matches, empty string otherwise.
if(node && node.tagName) {
for(var i=1; i<arguments.length; i++){
if(node.tagName==String(arguments[i])){
return String(arguments[i]); // string
};
dojo.dom.hasParent = function (node) {
return Boolean(node && node.parentNode && dojo.dom.isNode(node.parentNode));
};
dojo.dom.isTag = function (node) {
if (node && node.tagName) {
for (var i = 1; i < arguments.length; i++) {
if (node.tagName == String(arguments[i])) {
return String(arguments[i]);
}
}
}
return ""; // string
}
dojo.dom.setAttributeNS = function(/* Element */elem, /* string */namespaceURI, /* string */attrName, /* string */attrValue){
// summary
// implementation of DOM2 setAttributeNS that works cross browser.
if(elem == null || ((elem == undefined)&&(typeof elem == "undefined"))){
return "";
};
dojo.dom.setAttributeNS = function (elem, namespaceURI, attrName, attrValue) {
if (elem == null || ((elem == undefined) && (typeof elem == "undefined"))) {
dojo.raise("No element given to dojo.dom.setAttributeNS");
}
if(!((elem.setAttributeNS == undefined)&&(typeof elem.setAttributeNS == "undefined"))){ // w3c
if (!((elem.setAttributeNS == undefined) && (typeof elem.setAttributeNS == "undefined"))) {
elem.setAttributeNS(namespaceURI, attrName, attrValue);
}else{ // IE
// get a root XML document
} else {
var ownerDoc = elem.ownerDocument;
var attribute = ownerDoc.createNode(
2, // node type
attrName,
namespaceURI
);
// set value
var attribute = ownerDoc.createNode(2, attrName, namespaceURI);
attribute.nodeValue = attrValue;
// attach to element
elem.setAttributeNode(attribute);
}
}
};

Some files were not shown because too many files have changed in this diff Show More