next-ui
Version:
NeXt UI Toolkit npm distribution.
1,286 lines (1,154 loc) • 1.23 MB
JavaScript
/*NeXt @ ODL*/
/*Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
"Contributor" means any person or entity that distributes the Program.
"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance with this Agreement.
"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
a) it complies with the terms and conditions of this Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each copy of the Program.
Contributors may not remove or alter any copyright notices contained within the Program.
Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
*/
/**
* @module nx
*/
var nx = {
VERSION: '0.9.0',
DEBUG: false,
global: (function () {
return this;
}).call(null)
};
// prepare for cross browser
(function () {
if (!Function.prototype.bind) {
Function.prototype.bind = function (context) {
var f = this;
return function () {
return f.apply(context, arguments);
};
};
}
})();
(function (nx) {
/**
* @class nx
* @static
*/
var isArray = Array.isArray || function (target) {
return target && target.constructor === Array;
};
var isPojo = function (obj) {
var hasown = Object.prototype.hasOwnProperty;
if (!obj || Object.prototype.toString(obj) !== "[object Object]" || obj.nodeType || obj === window) {
return false;
}
try {
// Not own constructor property must be Object
if (obj.constructor && !hasown.call(obj, "constructor") && !hasown.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
var key;
for (key in obj) {}
return key === undefined || hasown.call(obj, key);
};
/**
* Extend target with properties from sources.
* @method extend
* @param target {Object} The target object to be extended.
* @param source* {Object} The source objects.
* @returns {Object}
*/
nx.extend = function (target) {
for (var i = 1, length = arguments.length; i < length; i++) {
var arg = arguments[i];
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
target[key] = arg[key];
}
}
}
return target;
};
/**
* Iterate over target and execute the callback with context.
* @method each
* @param target {Object|Array|Iterable} The target object to be iterate over.
* @param callback {Function} The callback function to execute.
* @param context {Object} The context object which act as 'this'.
*/
nx.each = function (target, callback, context) {
/* jshint -W014 */
if (target && callback) {
if (target.__each__) {
target.__each__(callback, context);
} else {
// FIXME maybe some other array-like things missed here
if (isArray(target) // normal Array
|| Object.prototype.toString.call(target) === "[object Arguments]" // array-like: arguments
|| nx.global.NodeList && target instanceof NodeList // array-like: NodeList
|| nx.global.HTMLCollection && target instanceof HTMLCollection // array-like: HTMLCollection
) {
for (var i = 0, length = target.length; i < length; i++) {
if (callback.call(context, target[i], i) === false) {
break;
}
}
} else {
for (var key in target) {
if (target.hasOwnProperty(key)) {
if (callback.call(context, target[key], key) === false) {
break;
}
}
}
}
}
}
};
/**
* Shallow clone target object.
* @method clone
* @param target {Object|Array} The target object to be cloned.
* @returns {Object} The cloned object.
*/
nx.clone = (function () {
var deepclone = (function () {
var get, put, top, keys, clone;
get = function (map, key) {
for (var i = 0; i < map.length; i++) {
if (map[i].key === key) {
return map[i].value;
}
}
return null;
};
put = function (map, key, value) {
var i;
for (i = 0; i < map.length; i++) {
if (map[i].key === key) {
map[i].value = value;
return;
}
}
map[i] = {
key: key,
value: value
};
};
top = function (stack) {
if (stack.length === 0) {
return null;
}
return stack[stack.length - 1];
};
keys = function (obj) {
var keys = [];
if (Object.prototype.toString.call(obj) == '[object Array]') {
for (var i = 0; i < obj.length; i++) {
keys.push(i);
}
} else {
for (var key in obj) {
keys.push(key);
}
}
return keys;
};
clone = function (self) {
// TODO clone DOM object
if (window === self || document === self) {
// window and document cannot be clone
return null;
}
if (["null", "undefined", "number", "string", "boolean", "function"].indexOf(typeof self) >= 0) {
return self;
}
if (!isArray(self) && !isPojo(self)) {
return self;
}
var map = [],
stack = [],
origin = self,
dest = (isArray(self) ? [] : {});
var stacktop, key, cached;
// initialize the map and stack
put(map, origin, dest);
stack.push({
origin: origin,
dest: dest,
keys: keys(origin),
idx: 0
});
while (true) {
stacktop = top(stack);
if (!stacktop) {
// the whole object is cloned
break;
}
origin = stacktop.origin;
dest = stacktop.dest;
if (stacktop.keys.length <= stacktop.idx) {
// object on the stack top is cloned
stack.pop();
continue;
}
key = stacktop.keys[stacktop.idx++];
// clone an object
if (isArray(origin[key])) {
dest[key] = [];
} else if (isPojo(origin[key])) {
dest[key] = {};
} else {
dest[key] = origin[key];
continue;
}
// check if needn't deep into or cloned already
cached = get(map, origin[key]);
if (cached) {
dest[key] = cached;
continue;
}
// deep into the object
put(map, origin[key], dest[key]);
stack.push({
origin: origin[key],
dest: dest[key],
keys: keys(origin[key]),
idx: 0
});
}
return dest;
};
return clone;
})();
return function (target, cfg) {
if (target) {
if (target.__clone__) {
return target.__clone__(cfg);
} else if (!cfg) {
if (nx.is(target, 'Array')) {
return target.slice(0);
} else {
var result = {};
for (var key in target) {
if (target.hasOwnProperty(key)) {
result[key] = target[key];
}
}
return result;
}
} else {
// TODO more config options
return deepclone(target);
}
} else {
return target;
}
};
})();
/**
* Check whether target is specified type.
* @method is
* @param target {Object} The target object to be checked.
* @param type {String|Function} The type could either be a string or a class object.
* @returns {Boolean}
*/
nx.is = function (target, type) {
if (target && target.__is__) {
return target.__is__(type);
} else {
switch (type) {
case 'Undefined':
return target === undefined;
case 'Null':
return target === null;
case 'Object':
return target && (typeof target === 'object');
case 'String':
case 'Boolean':
case 'Number':
case 'Function':
return typeof target === type.toLowerCase();
case 'Array':
return isArray(target);
case 'POJO':
return isPojo(target);
default:
return target instanceof type;
}
}
};
/**
* Get the specified property value of target.
* @method get
* @param target {Object} The target object.
* @param name {String} The property name.
* @returns {*} The value.
*/
nx.get = function (target, name) {
if (target) {
if (target.__get__) {
return target.__get__(name);
} else {
return target[name];
}
}
};
/**
* Set the specified property of target with value.
* @method set
* @param target {Object} The target object.
* @param name {String} The property name.
* @param value {*} The value to be set.
*/
nx.set = function (target, name, value) {
if (target) {
if (target.__set__) {
target.__set__(name);
} else {
target[name] = value;
}
}
};
/**
* Get all properties of target.
* @method gets
* @param target {Object} The target Object.
* @returns {Object} An object contains all keys and values of target.
*/
nx.gets = function (target) {
if (target) {
if (target.__gets__) {
return target.__gets__();
} else {
var result = {};
for (var key in target) {
if (target.hasOwnProperty(key)) {
result[key] = target[key];
}
}
return result;
}
}
};
/**
* Set a bunch of properties for target.
* @method sets
* @param target {Object} The target object.
* @param dict {Object} An object contains all keys and values to be set.
*/
nx.sets = function (target, dict) {
if (target && dict) {
if (target.__sets__) {
target.__sets__(dict);
} else {
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
target[key] = dict[key];
}
}
}
}
};
/**
* Check whether target has specified property.
* @method has
* @param target {Object} The target object.
* @param name {String} The property name.
* @returns {Boolean}
*/
nx.has = function (target, name) {
if (target) {
if (target.__has__) {
return target.__has__(name);
} else {
return name in target;
}
} else {
return false;
}
};
/**
* Compare target and source.
* @method compare
* @param target {Object} The target object.
* @param source {Object} The source object.
* @returns {Number} The result could be -1,0,1 which indicates the comparison result.
*/
nx.compare = function (target, source) {
if (target && target.__compare__) {
return target.__compare__(source);
} else {
if (target === source) {
return 0;
} else if (target > source) {
return 1;
} else if (target < source) {
return -1;
}
return 1;
}
};
/**
* Get value from target specified by a path and optionally set a value for it.
* @method path
* @param target {Object} The target object.
* @param path {String} The path.
* @param [value] {*} The value to be set.
* @returns {*}
*/
nx.path = function (target, path, value) {
var result = target;
if (path) {
var tokens, token, length, i = 0;
if (typeof path === "string") {
tokens = path.split(".");
} else if (isArray(path)) {
tokens = path;
} else {
return target;
}
length = tokens.length;
if (value === undefined) {
for (; result && i < length; i++) {
token = tokens[i];
if (result.__get__) {
result = result.__get__(token);
} else {
result = result[token];
}
}
} else {
length -= 1;
for (; result && i < length; i++) {
token = tokens[i];
if (result.__get__) {
result = result.__get__(token);
} else {
result = result[token] = result[token] || {};
}
}
token = tokens[i];
if (result) {
if (result.__set__) {
result.__set__(token, value);
} else {
result[token] = value;
}
result = value;
}
}
}
return result;
};
nx.idle = function () {};
nx.identity = function (i) {
return i;
};
nx.uuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).toUpperCase();
};
})(nx);
(function (nx) {
var classId = 1,
instanceId = 1,
metaPrefix = '@',
eventPrefix = 'on',
classes = {},
global = nx.global;
/**
* The base of any Classes defined in nx framework.
* @class nx.Object
* @constructor
*/
function NXObject() {}
var NXPrototype = NXObject.prototype = {
constructor: NXObject,
/**
* Dispose current object.
* @method dispose
*/
dispose: function () {
this.__listeners__ = {};
},
/**
* Destroy current object.
* @method destroy
*/
destroy: function () {
this.dispose();
},
/**
* Call overridden method from super class
* @method inherited
*/
inherited: function () {
var base = this.inherited.caller.__super__;
if (base) {
return base.apply(this, arguments);
}
},
/**
* Check whether current object is specified type.
* @method is
* @param type {String|Function}
* @returns {Boolean}
*/
is: function (type) {
if (typeof type === 'string') {
type = nx.path(global, type);
}
if (type) {
if (this instanceof type) {
return true;
} else {
var mixins = this.__mixins__;
for (var i = 0, len = mixins.length; i < len; i++) {
var mixin = mixins[i];
if (type === mixin) {
return true;
}
}
}
}
return false;
},
/**
* Check whether current object has specified property.
* @method has
* @param name {String}
* @returns {Boolean}
*/
has: function (name) {
var member = this[name];
return member && member.__type__ == 'property';
},
/**
* Get specified property value.
* @method get
* @param name {String}
* @returns {*}
*/
get: function (name) {
var member = this[name];
if (member !== undefined) {
if (member.__type__ == 'property') {
return member.call(this);
} else {
return member;
}
}
},
/**
* Set specified property value.
* @method set
* @param name {String}
* @param value {*}
*/
set: function (name, value) {
var member = this[name];
if (member !== undefined) {
if (member.__type__ == 'property') {
return member.call(this, value);
} else {
this[name] = value;
}
} else {
this[name] = value;
}
},
/**
* Get all properties.
* @method gets
* @returns {Object}
*/
gets: function () {
var result = {};
nx.each(this.__properties__, function (name) {
result[name] = this.get(name);
}, this);
return result;
},
/**
* Set a bunch of properties.
* @method sets
* @param dict {Object}
*/
sets: function (dict) {
if (dict) {
for (var name in dict) {
if (dict.hasOwnProperty(name)) {
this.set(name, dict[name]);
}
}
}
},
/**
* Check whether current object has specified event.
* @method can
* @param name {String}
* @returns {Boolean}
*/
can: function (name) {
var member = this[eventPrefix + name];
return member && member.__type__ == 'event';
},
/**
* Add an event handler.
* @method on
* @param name {String}
* @param handler {Function}
* @param [context] {Object}
*/
on: function (name, handler, context) {
var map = this.__listeners__;
var listeners = map[name] = map[name] || [{
owner: null,
handler: null,
context: null
}];
var listener = {
owner: this,
handler: handler,
context: context || this
};
listeners.push(listener);
return {
release: function () {
var idx = listeners.indexOf(listener);
if (idx >= 0) {
listeners.splice(idx, 1);
}
}
};
},
/**
* Remove an event handler.
* @method off
* @param name {String}
* @param [handler] {Function}
* @param [context] {Object}
*/
off: function (name, handler, context) {
var listeners = this.__listeners__[name],
listener;
if (listeners) {
if (handler) {
context = context || this;
for (var i = 0, length = listeners.length; i < length; i++) {
listener = listeners[i];
if (listener.handler == handler && listener.context == context) {
listeners.splice(i, 1);
break;
}
}
} else {
listeners.length = 1;
}
}
},
/**
* Add a single event handler.
* @method upon
* @param name {String}
* @param handler {Function}
* @param [context] {Object}
*/
upon: function (name, handler, context) {
var map = this.__listeners__;
var listeners = map[name] = map[name] || [{
owner: null,
handler: null,
context: null
}];
listeners[0] = {
owner: this,
handler: handler,
context: context
};
},
/**
* Trigger an event.
* @method fire
* @param name {String}
* @param [data] {*}
*/
fire: function (name, data) {
var i, length, listener, result, calling, existing = this.__listeners__[name];
calling = existing ? existing.slice() : [];
for (i = 0, length = calling.length; i < length; i++) {
listener = calling[i];
if (listener && listener.handler && (existing[i] === listener || existing.indexOf(listener) >= 0)) {
result = listener.handler.call(listener.context, listener.owner, data);
if (result === false) {
return false;
}
}
}
},
__is__: function (type) {
return this.is(type);
},
__has__: function (name) {
return this.has(name);
},
__get__: function (name) {
return this.get(name);
},
__set__: function (name, value) {
return this.set(name, value);
},
__gets__: function () {
return this.gets();
},
__sets__: function (dict) {
return this.sets(dict);
}
};
NXObject.__classId__ = NXPrototype.__classId__ = 0;
NXObject.__className__ = NXPrototype.__className__ = 'nx.Object';
NXObject.__events__ = NXPrototype.__events__ = [];
NXObject.__properties__ = NXPrototype.__properties__ = [];
NXObject.__methods__ = NXPrototype.__methods__ = [];
NXObject.__defaults__ = NXPrototype.__defaults__ = {};
NXObject.__mixins__ = NXPrototype.__mixins__ = [];
NXObject.extendEvent = extendEvent;
NXObject.extendProperty = extendProperty;
NXObject.extendMethod = extendMethod;
/**
* Define an event and attach to target.
* @method extendEvent
* @static
* @param target {Object}
* @param name {String}
*/
function extendEvent(target, name) {
var eventName = eventPrefix + name;
var exist = target[eventName] && target[eventName].__type__ == 'event';
var fn = target[eventName] = function (handler, context) {
var map = this.__listeners__;
var listeners = map[name] = map[name] || [{
owner: null,
handler: null,
context: null
}];
listeners[0] = {
owner: this,
handler: handler,
context: context
};
};
fn.__name__ = name;
fn.__type__ = 'event';
if (!exist) {
target.__events__.push(name);
}
return fn;
}
/**
* Define a property and attach to target.
* @method extendProperty
* @static
* @param target {Object}
* @param name {String}
* @param meta {Object}
*/
function extendProperty(target, name, meta) {
if (nx.is(meta, nx.keyword.internal.Keyword) || !nx.is(meta, "Object")) {
meta = {
value: meta
};
}
var defaultValue;
var exist = target[name] && target[name].__type__ == 'property';
if (meta.dependencies) {
if (nx.is(meta.dependencies, "String")) {
meta.dependencies = meta.dependencies.replace(/\s/g, "").split(",");
}
defaultValue = nx.keyword.binding({
source: meta.dependencies,
async: true,
callback: function () {
var owner = this.owner;
if (meta.update) {
meta.update.apply(owner, arguments);
}
if (nx.is(meta.value, "Function")) {
owner.set(name, meta.value.apply(owner, arguments));
} else if (!meta.update && !meta.value) {
owner.set(name, arguments[0]);
}
}
});
} else {
defaultValue = meta.value;
}
if (target[name] && meta.inherits) {
meta = nx.extend({}, target[name].__meta__, meta);
}
var fn = function (value, params) {
if (value === undefined && arguments.length === 0) {
return fn.__getter__.call(this, params);
} else {
return fn.__setter__.call(this, value, params);
}
};
fn.__name__ = name;
fn.__type__ = 'property';
fn.__meta__ = meta;
fn.__getter__ = meta.get || function () {
return this['_' + name];
};
fn.__setter__ = meta.set || function (value) {
this['_' + name] = value;
};
fn.getMeta = function (key) {
return key ? fn.__meta__[key] : fn.__meta__;
};
if (nx.is(target, "Function") && target.__properties__ && !target.__static__) {
target.prototype[name] = fn;
} else {
target[name] = fn;
}
if (defaultValue !== undefined) {
target.__defaults__[name] = defaultValue;
}
if (!exist) {
if (!nx.is(target, "Function") && target.__properties__ === target.constructor.__properties) {
target.__properties__ = target.__properties__.slice();
}
target.__properties__.push(name);
}
return fn;
}
/**
* Define a method and attach to target.
* @method extendMethod
* @static
* @param target {Object}
* @param name {String}
* @param method {Function}
*/
function extendMethod(target, name, method) {
var exist = target[name] && target[name].__type__ == 'method';
if (target[name] && target[name] !== method) {
method.__super__ = target[name];
}
method.__name__ = name;
method.__type__ = 'method';
method.__meta__ = {};
target[name] = method;
if (!exist) {
target.__methods__.push(name);
}
}
/**
* Define a class
* @method define
* @param [type] {String}
* @param [parent] {Function}
* @param [members] {Object}
* @returns {Function}
*/
function define(type, parent, members) {
if (!members) {
if (nx.is(parent, 'Object')) {
members = parent;
parent = null;
if (nx.is(type, 'Function')) {
parent = type;
type = null;
}
} else if (!parent) {
if (nx.is(type, 'Object')) {
members = type;
type = null;
} else if (nx.is(type, 'Function')) {
parent = type;
type = null;
}
}
}
members = members || {};
var sup = parent || NXObject;
var mixins = members.mixins || [];
var events = members.events || [];
var props = members.properties || {};
var methods = members.methods || {};
var static = members.static || false;
var statics = members.statics || {};
var prototype;
var key, i, length;
var Class, SuperClass;
if (nx.is(mixins, 'Function')) {
mixins = [mixins];
}
if (sup.__static__) {
throw new Error('Static class cannot be inherited.');
}
if (static) {
Class = function () {
throw new Error('Cannot instantiate static class.');
};
Class.__classId__ = classId++;
Class.__className__ = type ? type : 'Anonymous';
Class.__static__ = true;
Class.__events__ = [];
Class.__properties__ = [];
Class.__methods__ = [];
Class.__defaults__ = {};
for (i = 0, length = events.length; i < length; i++) {
extendEvent(Class, events[i]);
}
for (key in props) {
if (props.hasOwnProperty(key)) {
extendProperty(Class, key, props[key]);
}
}
for (key in methods) {
if (methods.hasOwnProperty(key)) {
extendMethod(Class, key, methods[key]);
}
}
for (key in statics) {
if (statics.hasOwnProperty(key)) {
Class[key] = statics[key];
}
}
nx.each(Class.__defaults__, function (value, name) {
if (nx.is(value, "Function")) {
this["_" + name] = value.call(this);
} else if (nx.is(value, nx.keyword.internal.Keyword)) {
switch (value.type) {
case "binding":
// FIXME memory leak
value.apply(this, name);
break;
}
} else {
this["_" + name] = value;
}
}, Class);
if (methods.init) {
methods.init.call(Class);
}
} else {
Class = function () {
// get the real arguments
var args = arguments[0];
if (Object.prototype.toString.call(args) !== "[object Arguments]") {
args = arguments;
}
var mixins = this.__mixins__;
this.__id__ = instanceId++;
this.__listeners__ = {};
this.__bindings__ = this.__bindings__ || {};
this.__watchers__ = this.__watchers__ || {};
this.__keyword_bindings__ = this.__keyword_bindings__ || [];
this.__keyword_watchers__ = this.__keyword_watchers__ || {};
this.__keyword_init__ = this.__keyword_init__ || [];
this.__initializing__ = true;
for (var i = 0, length = mixins.length; i < length; i++) {
var ctor = mixins[i].__ctor__;
if (ctor) {
ctor.call(this);
}
}
nx.each(Class.__defaults__, function (value, name) {
if (nx.is(value, "Function")) {
this["_" + name] = value.call(this);
} else if (nx.is(value, nx.keyword.internal.Keyword)) {
// FIXME memory leak
// FIXME bind order
this.__keyword_bindings__.push({
name: name,
definition: value
});
} else {
this["_" + name] = value;
}
}, this);
nx.each(Class.__properties__, function (name) {
var prop = this[name];
if (!prop || prop.__type__ !== "property") {
return;
}
var meta = prop.__meta__,
watcher = meta.watcher,
init = meta.init;
if (watcher && this.watch) {
if (nx.is(watcher, "String")) {
watcher = this[watcher];
}
this.watch(name, watcher.bind(this));
this.__keyword_watchers__[name] = watcher;
}
if (init) {
this.__keyword_init__.push(init);
}
}, this);
nx.each(this.__keyword_bindings__, function (binding) {
binding.instance = binding.definition.apply(this, binding.name);
}, this);
nx.each(this.__keyword_init__, function (init) {
init.apply(this, args);
}, this);
if (this.__ctor__) {
this.__ctor__.apply(this, args);
}
nx.each(this.__keyword_watchers__, function (watcher, name) {
watcher.call(this, name, this[name].call(this));
}, this);
nx.each(this.__keyword_bindings__, function (binding) {
binding.instance.notify();
}, this);
this.__initializing__ = false;
};
SuperClass = function () {};
SuperClass.prototype = sup.prototype;
prototype = new SuperClass();
prototype.constructor = Class;
prototype.__events__ = sup.__events__.slice(0);
prototype.__properties__ = sup.__properties__.slice(0);
prototype.__methods__ = sup.__methods__.slice(0);
prototype.__defaults__ = nx.clone(sup.__defaults__);
prototype.__mixins__ = sup.__mixins__.concat(mixins);
Class.__classId__ = classId++;
Class.__className__ = prototype.__className__ = type ? type : 'Anonymous';
Class.__super__ = prototype.__super__ = sup;
Class.prototype = prototype;
if (methods.init) {
prototype.__ctor__ = methods.init;
}
for (key in members) {
if (members.hasOwnProperty(key)) {
prototype[metaPrefix + key] = Class[metaPrefix + key] = members[key];
}
}
nx.each(mixins, function (mixin) {
var mixinPrototype = mixin.prototype;
nx.each(mixin.__events__, function (name) {
extendEvent(prototype, name);
});
nx.each(mixin.__properties__, function (name) {
extendProperty(prototype, name, mixinPrototype[name].__meta__);
});
nx.each(mixin.__methods__, function (name) {
if (name !== 'init' && name !== 'dispose') {
extendMethod(prototype, name, mixinPrototype[name]);
}
});
});
for (i = 0, length = events.length; i < length; i++) {
extendEvent(prototype, events[i]);
}
for (key in props) {
if (props.hasOwnProperty(key)) {
extendProperty(prototype, key, props[key]);
}
}
for (key in methods) {
if (methods.hasOwnProperty(key)) {
extendMethod(prototype, key, methods[key]);
}
}
for (key in statics) {
if (statics.hasOwnProperty(key)) {
Class[key] = statics[key];
}
}
Class.__ctor__ = prototype.__ctor__;
Class.__events__ = prototype.__events__;
Class.__properties__ = prototype.__properties__;
Class.__methods__ = prototype.__methods__;
Class.__defaults__ = prototype.__defaults__;
Class.__mixins__ = prototype.__mixins__;
}
if (type) {
nx.path(global, type, Class);
}
classes[Class.__classId__] = Class;
return Class;
}
nx.Object = NXObject;
nx.define = define;
nx.classes = classes;
})(nx);
(function (nx) {
var keyword = nx.keyword = nx.keyword || {
binding: function (source, callback, async) {
var context = false;
if (typeof source !== "string") {
context = !! source.context;
callback = source.callback;
async = source.async;
source = source.source;
}
return new nx.keyword.internal.Keyword({
type: "binding",
context: context,
source: source,
async: async,
callback: callback
});
},
internal: {
idle: function () {},
watch: (function () {
var single = function (o, path, listener, context) {
var keys = path.split(".");
function level(parent, idx) {
if (parent && idx < keys.length) {
var key = keys[idx];
// watch on the collection changes
if (key == "*" || key == "%") {
// TODO handler watching on collection changes
} else {
var child = nx.path(parent, key);
if (parent.watch) {
var pathRest = keys.slice(idx + 1).join("."),
childUnwatch = level(child,