repo
stringlengths 5
75
| commit
stringlengths 40
40
| message
stringlengths 6
18.2k
| diff
stringlengths 60
262k
|
---|---|---|---|
dancrew32/AWESOME-JS | 816c83b28209e579e4139aba645d3fe5537a9a5e | move isX tests to private, expose save 1kb | diff --git a/awesome.js b/awesome.js
index ce1c680..7c174d3 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,980 +1,977 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
+
+ // PRIVATE
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
- var CANATTACH = typeof BODY.addEventListener === 'function'
- && typeof BODY.attachEvent === 'undefined';
- var QUEUE = [];
- var QUEUE_TIMER = null;
+ var CANATTACH = isFunction(BODY.addEventListener) && isUndefined(BODY.attachEvent);
var RXP = {
ready: /loaded|complete/,
template: /#{([^}]*)}/g,
amp: /&/g,
lt: /</g,
gt: />/g,
quote: /"/g,
apos: /'/g,
number: '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)',
oneChar: '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))',
- jsonEscapeSeq: /\\\\(?:([^u])|u(.{4}))/g,
+ jsonEscapeSeq: /\\\\(?:([^u])|u(.{4}))/g
};
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
+ // isTest's
+ function isObject(val) {
+ return typeof val === 'object';
+ }
+ function isArray(val) {
+ return isObject(val) && !isUndefined(val.length);
+ }
+ function isString(val) {
+ return typeof val === 'string';
+ }
+ function isFunction(val) {
+ return typeof val === 'function';
+ }
+ function isUndefined(val) {
+ return typeof val === 'undefined';
+ }
+ function isNull(val) {
+ return typeof val === 'null';
+ }
+ function isNullOrUndefined(val) {
+ return isNull(val) || isUndefined(val);
+ }
+
+ // PUBLIC
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((RXP.ready).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (CANATTACH)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (CANATTACH) DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data, type) {
if (typeof console === 'undefined') return;
type = type || 'log'
- if (this.isUndefined(console)) return;
+ if (isUndefined(console)) return;
console[type](data);
},
noop: function() {},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
event = event || WIN.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, capture) {
- if (this.isNullOrUndefined(obj)) return;
+ if (isNullOrUndefined(obj)) return;
capture = capture || false; // bubble
obj = this.toArray(obj);
var i = obj.length;
while (i--) {
if (CANATTACH) {
obj[i].addEventListener(type, handler, capture);
} else if (obj[i].attachEvent) {
obj[i].attachEvent('on'+ type, handler);
} else {
obj[i]['on'+ type] = handler;
}
}
},
unbind: function (obj, type, handler, capture) {
- if (this.isNullOrUndefined(obj)) return;
+ if (isNullOrUndefined(obj)) return;
capture = capture || false;
obj = this.toArray(obj);
var i = obj.length;
while (i--) {
if (CANATTACH) {
obj[i].removeEventListener(type, handler, capture);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on'+ type, handler);
} else {
obj[i]['on'+ type] = null;
}
}
},
fire: function(obj, ev, capture, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
capture = capture || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, capture, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, capture) {
- if (this.isUndefined(obj)) {return;}
+ if (isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, capture);
- if (out)
- $this.bind(obj, 'mouseout', out, capture);
+ if (out) $this.bind(obj, 'mouseout', out, capture);
},
toArray: function(obj) {
- if (!this.isArray(obj)) {
- obj = [obj];
- }
+ if (!isArray(obj)) obj = [obj];
return obj;
},
- isObject: function(val) {
- return typeof val === 'object';
- },
- isArray: function(val) {
- return this.isObject(val) && !this.isUndefined(val.length);
- },
- isString: function() {
- return typeof val === 'string';
- },
- isUndefined: function(val) {
- return typeof val === 'undefined';
- },
- isNull: function(val) {
- return typeof val === 'null';
- },
- isNullOrUndefined: function(val) {
- return this.isNull(val) || this.isUndefined(val);
- },
+ isObject: isObject,
+ isArray: isArray,
+ isString: isString,
+ isUndefined: isUndefined,
+ isNull: isNull,
+ isNullOrUndefined: isNullOrUndefined,
hasClass: function (el, cls) {
var re = el.className.split(' ');
- if (this.isUndefined(re)) { return false; }
+ if (isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls)) el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
- if (this.isUndefined(re)) return;
+ if (isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while (i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('^|\\s' + searchClass + '\\s|$');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
is: function(el, type) {
- if (this.isUndefined(type)) return el.nodeName;
+ if (isUndefined(type)) return el.nodeName;
return el.nodeName === type.toUpperCase();
},
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
- if (!this.isUndefined(el))
- if (this.isUndefined(prop)) {
+ if (!isUndefined(el))
+ if (isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
- if (this.isNull(x) && !this.isNull(event.clientX)) {
+ if (isNull(x) && !isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
- if (!this.isNullOrUndefined(relativeTo)) {
+ if (!isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
- if (!this.isUndefined(WIN.pageYOffset)) {
+ if (!isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
- if (!this.isUndefined(WIN.innerHeight)) {
+ if (!isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
- } else if (!this.isUndefined(DOCEL)
- && !this.isUndefined(DOCEL.clientHeight)
+ } else if (!isUndefined(DOCEL)
+ && !isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
- if (!this.isUndefined(WIN.innerWidth)) {
+ if (!isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
- } else if (!this.isUndefined(DOCEL)
- && !this.isUndefined(DOCEL.clientWidth)
+ } else if (!isUndefined(DOCEL)
+ && !isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
template: function(template, obj){
var cache = {};
var strCache = template;
var matches = 0;
template.replace(RXP.template, function(tmpl, val) { // #{oKey}
cache[tmpl] = val;
});
for (var key in cache) {
strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
}
return strCache;
},
html: function(obj, str, coerce, coercePar) {
coerse = coerce || false;
if (coerce) {
var temp = obj.ownerDocument.createElement('DIV');
temp.innerHTML = '<'+ coercePar +'>'+ str +'</'+ coercePar +'>';
this.swap(temp.firstChild.firstChild, obj);
} else {
obj.innerHTML = str;
}
},
encodeHTML: function (str) {
return str.replace(RXP.amp, '&')
.replace(RXP.lt, '<')
.replace(RXP.gt, '>')
.replace(RXP.quote, '"')
.replace(RXP.apos, ''');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
- if (this.isUndefined(obj)) return;
+ if (isUndefined(obj)) return;
if (txt) {
- if (!this.isUndefined(obj.innerText)) {
+ if (!isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
return;
}
return obj.innerText || obj.textContent || obj.text;
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(this.toNode(newNode), node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(this.toNode(newNode));
},
before: function (newNode, node) {
//if (node.parentNode === BODY) {
//this.prepend(this.toNode(newNode), BODY);
//return;
//}
node.parentNode.insertBefore(this.toNode(newNode), node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(this.toNode(newNode), node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
recursive = recursive || true;
ele = this.toArray(ele);
var i = ele.length;
while (i--) {
- if (!this.isUndefined(ele[i].parentNode)) {
+ if (!isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
- if (this.isUndefined(el)) return;
+ if (isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
toNode: function(text) {
- if (!this.isString(text)) return text;
+ if (!isString(text)) return text;
return this.create(text);
},
create: function (tag) {
return DOC.createElement(tag.toUpperCase());
},
frag: function(str) {
var frag = DOC.createDocumentFragment();
var temp = this.create('DIV');
temp.innerHTML = str;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
},
- // Execution Queue
- queue: function(fn, time) {
- var timer = function(time) {
- QUEUE_TIMER = setTimeout(function() {
- fn();
- }, time || 2);
- };
- },
- clearQueue: function() {
- clearTimeout(QUEUE_TIMER);
- QUEUE = [];
- },
+ // TODO: Execution Queue
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
- while (!this.isNull(node)) {
+ while (!isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: $this.noop
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duration, to, callback) {
callback = callback || this.noop;
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
- if (this.isNull(obj)) {return '';}
+ if (isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
- if (this.isUndefined(options[index])) {
+ if (isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
return parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.loadXML(str);
return xmlDoc;
}
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var string = '(?:\"' + RXP.oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + RXP.number
+ '|' + string
+ ')', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf('\\') !== -1) {
tok = tok.replace(RXP.jsonEscapeSeq, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || ''; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
var $this = this;
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: $this.noop,
sendPrepared: $this.noop,
afterSend: $this.noop,
complete: $this.noop,
failure: $this.noop
}, options);
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
this.postRequest(options);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
this.getRequest(options);
}
},
openRequest: function(options, method) {
var req = this.getHttpRequest();
- if (this.isNull(req)) return;
+ if (isNull(req)) return;
var $this = this;
var d = new Date();
var aborted = 'abort';
req.open(method, options.url, true);
if (method === 'POST') {
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (!options.disguise) {
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
req.setRequestHeader('X-Request-Id', d.getTime());
req.onreadystatechange = function(e) {
var data = '';
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 4:
- if (!$this.isNull(options.dataType)) {
+ if (!isNull(options.dataType)) {
try {
data = $this.parse(req.responseText, options.dataType);
} catch (erD) { data = aborted; }
} else {
try {
data = req.responseText;
} catch (erT) { data = aborted; }
}
if (data !== aborted && req.status >= 200 && req.status < 300) {
options.complete(data);
} else if (data !== aborted && req.status === 0) { // file:/// ajax
options.complete(data);
} else {
options.failure(data);
}
break;
}
};
return req;
},
postRequest: function(options) {
var req = this.openRequest(options, 'POST');
req.send(this.formatParams(options.data));
return req;
},
getRequest: function(options) {
var req = this.openRequest(options, 'GET');
req.send('');
return req;
},
getHttpRequest: function() {
if (typeof XMLHttpRequest !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
};
}(window, document));
|
dancrew32/AWESOME-JS | 0f1d714720d7f7b79b1195e61a9b2f27dfdd8d86 | move regex to top to speed up init closes #35 | diff --git a/awesome.js b/awesome.js
index 674bbab..ce1c680 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,985 +1,980 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var CANATTACH = typeof BODY.addEventListener === 'function'
&& typeof BODY.attachEvent === 'undefined';
var QUEUE = [];
var QUEUE_TIMER = null;
var RXP = {
ready: /loaded|complete/,
template: /#{([^}]*)}/g,
amp: /&/g,
lt: /</g,
gt: />/g,
quote: /"/g,
- apos: /'/g
+ apos: /'/g,
+ number: '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)',
+ oneChar: '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))',
+ jsonEscapeSeq: /\\\\(?:([^u])|u(.{4}))/g,
};
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((RXP.ready).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (CANATTACH)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (CANATTACH) DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data, type) {
if (typeof console === 'undefined') return;
type = type || 'log'
if (this.isUndefined(console)) return;
console[type](data);
},
noop: function() {},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
event = event || WIN.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, capture) {
if (this.isNullOrUndefined(obj)) return;
capture = capture || false; // bubble
obj = this.toArray(obj);
var i = obj.length;
while (i--) {
if (CANATTACH) {
obj[i].addEventListener(type, handler, capture);
} else if (obj[i].attachEvent) {
obj[i].attachEvent('on'+ type, handler);
} else {
obj[i]['on'+ type] = handler;
}
}
},
unbind: function (obj, type, handler, capture) {
if (this.isNullOrUndefined(obj)) return;
capture = capture || false;
obj = this.toArray(obj);
var i = obj.length;
while (i--) {
if (CANATTACH) {
obj[i].removeEventListener(type, handler, capture);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on'+ type, handler);
} else {
obj[i]['on'+ type] = null;
}
}
},
fire: function(obj, ev, capture, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
capture = capture || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, capture, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, capture) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, capture);
if (out)
$this.bind(obj, 'mouseout', out, capture);
},
toArray: function(obj) {
if (!this.isArray(obj)) {
obj = [obj];
}
return obj;
},
isObject: function(val) {
return typeof val === 'object';
},
isArray: function(val) {
return this.isObject(val) && !this.isUndefined(val.length);
},
isString: function() {
return typeof val === 'string';
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls)) el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while (i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('^|\\s' + searchClass + '\\s|$');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
is: function(el, type) {
if (this.isUndefined(type)) return el.nodeName;
return el.nodeName === type.toUpperCase();
},
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
template: function(template, obj){
var cache = {};
var strCache = template;
var matches = 0;
template.replace(RXP.template, function(tmpl, val) { // #{oKey}
cache[tmpl] = val;
});
for (var key in cache) {
strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
}
return strCache;
},
html: function(obj, str, coerce, coercePar) {
coerse = coerce || false;
if (coerce) {
var temp = obj.ownerDocument.createElement('DIV');
temp.innerHTML = '<'+ coercePar +'>'+ str +'</'+ coercePar +'>';
this.swap(temp.firstChild.firstChild, obj);
} else {
obj.innerHTML = str;
}
},
encodeHTML: function (str) {
return str.replace(RXP.amp, '&')
.replace(RXP.lt, '<')
.replace(RXP.gt, '>')
.replace(RXP.quote, '"')
.replace(RXP.apos, ''');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (this.isUndefined(obj)) return;
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
return;
}
return obj.innerText || obj.textContent || obj.text;
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(this.toNode(newNode), node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(this.toNode(newNode));
},
before: function (newNode, node) {
//if (node.parentNode === BODY) {
//this.prepend(this.toNode(newNode), BODY);
//return;
//}
node.parentNode.insertBefore(this.toNode(newNode), node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(this.toNode(newNode), node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
recursive = recursive || true;
ele = this.toArray(ele);
var i = ele.length;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
toNode: function(text) {
if (!this.isString(text)) return text;
return this.create(text);
},
create: function (tag) {
return DOC.createElement(tag.toUpperCase());
},
frag: function(str) {
var frag = DOC.createDocumentFragment();
var temp = this.create('DIV');
temp.innerHTML = str;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
},
// Execution Queue
queue: function(fn, time) {
var timer = function(time) {
QUEUE_TIMER = setTimeout(function() {
fn();
}, time || 2);
};
},
clearQueue: function() {
clearTimeout(QUEUE_TIMER);
QUEUE = [];
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: $this.noop
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duration, to, callback) {
callback = callback || this.noop;
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
return parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.loadXML(str);
return xmlDoc;
}
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
- var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
- var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
- + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
- var string = '(?:\"' + oneChar + '*\")';
+ var string = '(?:\"' + RXP.oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
- + '|' + number
+ + '|' + RXP.number
+ '|' + string
+ ')', 'g');
- var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
- var EMPTY_STRING = '';
- var SLASH = '\\';
- var firstTokenCtors = { '{': Object, '[': Array };
- var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
- if (tok.indexOf(SLASH) !== -1) {
- tok = tok.replace(escapeSequence, unescapeOne);
+ if (tok.indexOf('\\') !== -1) {
+ tok = tok.replace(RXP.jsonEscapeSeq, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
- key = tok || EMPTY_STRING; // Use as key for next value seen.
+ key = tok || ''; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
var $this = this;
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: $this.noop,
sendPrepared: $this.noop,
afterSend: $this.noop,
complete: $this.noop,
failure: $this.noop
}, options);
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
this.postRequest(options);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
this.getRequest(options);
}
},
openRequest: function(options, method) {
var req = this.getHttpRequest();
if (this.isNull(req)) return;
var $this = this;
var d = new Date();
var aborted = 'abort';
req.open(method, options.url, true);
if (method === 'POST') {
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (!options.disguise) {
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
req.setRequestHeader('X-Request-Id', d.getTime());
req.onreadystatechange = function(e) {
var data = '';
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 4:
if (!$this.isNull(options.dataType)) {
try {
data = $this.parse(req.responseText, options.dataType);
} catch (erD) { data = aborted; }
} else {
try {
data = req.responseText;
} catch (erT) { data = aborted; }
}
if (data !== aborted && req.status >= 200 && req.status < 300) {
options.complete(data);
} else if (data !== aborted && req.status === 0) { // file:/// ajax
options.complete(data);
} else {
options.failure(data);
}
break;
}
};
return req;
},
postRequest: function(options) {
var req = this.openRequest(options, 'POST');
req.send(this.formatParams(options.data));
return req;
},
getRequest: function(options) {
var req = this.openRequest(options, 'GET');
req.send('');
return req;
},
getHttpRequest: function() {
if (typeof XMLHttpRequest !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
};
}(window, document));
|
dancrew32/AWESOME-JS | bd1d6b6705fa767e920f539efa340c64a806e0d2 | catch back up with ie6/7/8/9 compat closes #34 | diff --git a/awesome.js b/awesome.js
index eddf9ea..674bbab 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,924 +1,985 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
- var canAttach = typeof BODY.addEventListener === undefined;
+ var CANATTACH = typeof BODY.addEventListener === 'function'
+ && typeof BODY.attachEvent === 'undefined';
+ var QUEUE = [];
+ var QUEUE_TIMER = null;
+ var RXP = {
+ ready: /loaded|complete/,
+ template: /#{([^}]*)}/g,
+ amp: /&/g,
+ lt: /</g,
+ gt: />/g,
+ quote: /"/g,
+ apos: /'/g
+ };
+
+ if (!Array.indexOf) {
+ Array.prototype.indexOf = function(obj) {
+ for(var i = 0; i < this.length; i++) {
+ if (this[i] === obj){
+ return i;
+ }
+ }
+ return -1;
+ };
+ }
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
- if ((/loaded|complete/).test(DOC.readyState)) {
+ if ((RXP.ready).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
- if (canAttach)
+ if (CANATTACH)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
- if (canAttach)
- DOC.addEventListener(contentLoaded, onStateChange, false);
+ if (CANATTACH) DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
- log: function (data) {
- if (!this.isUndefined(console)) {
- console.log(data);
- }
+ log: function (data, type) {
+ if (typeof console === 'undefined') return;
+ type = type || 'log'
+ if (this.isUndefined(console)) return;
+ console[type](data);
},
+ noop: function() {},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
+ event = event || WIN.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
- bind: function (obj, type, handler, delegate) {
- if (this.isUndefined(obj) || this.isNull(obj)) {return;}
- delegate = delegate || false;
- if (this.isUndefined(obj.length)) {
- obj = [obj];
- }
+ bind: function (obj, type, handler, capture) {
+ if (this.isNullOrUndefined(obj)) return;
+ capture = capture || false; // bubble
+ obj = this.toArray(obj);
var i = obj.length;
while (i--) {
- if (canAttach) {
- obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
- } else if (obj.attachEvent) {
- obj[i].attachEvent('on' + type, handler);
+ if (CANATTACH) {
+ obj[i].addEventListener(type, handler, capture);
+ } else if (obj[i].attachEvent) {
+ obj[i].attachEvent('on'+ type, handler);
} else {
- obj[i]['on' + type] = handler;
+ obj[i]['on'+ type] = handler;
}
}
},
- unbind: function (obj, type, handler, delegate) {
- if (this.isUndefined(obj) || this.isNull(obj)) {return;}
- delegate = delegate || false;
- if (this.isUndefined(obj.length)) {
- obj = [obj];
- }
+ unbind: function (obj, type, handler, capture) {
+ if (this.isNullOrUndefined(obj)) return;
+ capture = capture || false;
+ obj = this.toArray(obj);
var i = obj.length;
while (i--) {
- if (canAttach) {
- obj[i].removeEventListener(type, handler, delegate);
+ if (CANATTACH) {
+ obj[i].removeEventListener(type, handler, capture);
} else if (obj[i].detachEvent) {
- obj[i].detachEvent('on' + type, handler);
+ obj[i].detachEvent('on'+ type, handler);
} else {
- obj[i]['on' + type] = null;
+ obj[i]['on'+ type] = null;
}
}
},
- fire: function(obj, ev, delegate, cancelable) {
+ fire: function(obj, ev, capture, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
- delegate = delegate || false;
+ capture = capture || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
- evt.initEvent(ev, delegate, cancelable);
+ evt.initEvent(ev, capture, cancelable);
return !obj.dispatchEvent(evt);
},
- hover: function (obj, over, out, delegate) {
+ hover: function (obj, over, out, capture) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
- $this.bind(obj, 'mouseover', over, delegate);
+ $this.bind(obj, 'mouseover', over, capture);
if (out)
- $this.bind(obj, 'mouseout', out, delegate);
+ $this.bind(obj, 'mouseout', out, capture);
+ },
+ toArray: function(obj) {
+ if (!this.isArray(obj)) {
+ obj = [obj];
+ }
+ return obj;
+ },
+ isObject: function(val) {
+ return typeof val === 'object';
+ },
+ isArray: function(val) {
+ return this.isObject(val) && !this.isUndefined(val.length);
+ },
+ isString: function() {
+ return typeof val === 'string';
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
- if (!Array.indexOf) {
- Array.prototype.indexOf = function(obj) {
- for(var i = 0; i < this.length; i++) {
- if (this[i] === obj){
- return i;
- }
- }
- return -1;
- };
- }
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
- if (!this.hasClass(el, cls))
- el.className += ' '+ cls;
+ if (!this.hasClass(el, cls)) el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
- while(i--) { // reload
+ while (i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
- var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
+ var pattern = new RegExp('^|\\s' + searchClass + '\\s|$');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
+ is: function(el, type) {
+ if (this.isUndefined(type)) return el.nodeName;
+ return el.nodeName === type.toUpperCase();
+ },
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
template: function(template, obj){
var cache = {};
var strCache = template;
var matches = 0;
- template.replace(/#{([^}]*)}/g, function(tmpl, val) { // #{oKey}
+ template.replace(RXP.template, function(tmpl, val) { // #{oKey}
cache[tmpl] = val;
});
for (var key in cache) {
strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
}
return strCache;
},
+ html: function(obj, str, coerce, coercePar) {
+ coerse = coerce || false;
+ if (coerce) {
+ var temp = obj.ownerDocument.createElement('DIV');
+ temp.innerHTML = '<'+ coercePar +'>'+ str +'</'+ coercePar +'>';
+ this.swap(temp.firstChild.firstChild, obj);
+ } else {
+ obj.innerHTML = str;
+ }
+ },
encodeHTML: function (str) {
- return str.replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"');
+ return str.replace(RXP.amp, '&')
+ .replace(RXP.lt, '<')
+ .replace(RXP.gt, '>')
+ .replace(RXP.quote, '"')
+ .replace(RXP.apos, ''');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (this.isUndefined(obj)) return;
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
return;
}
- return obj.innerText || obj.textContent;
+ return obj.innerText || obj.textContent || obj.text;
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
- node.insertBefore(newNode, node.childNodes[0]);
+ node.insertBefore(this.toNode(newNode), node.childNodes[0]);
},
append: function (newNode, node) {
- node.appendChild(newNode);
+ node.appendChild(this.toNode(newNode));
},
before: function (newNode, node) {
- node.parentNode.insertBefore(newNode, node);
+ //if (node.parentNode === BODY) {
+ //this.prepend(this.toNode(newNode), BODY);
+ //return;
+ //}
+ node.parentNode.insertBefore(this.toNode(newNode), node);
},
after: function (newNode, node) {
- node.parentNode.insertBefore(newNode, node.nextSibling);
+ node.parentNode.insertBefore(this.toNode(newNode), node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
- if (!('length' in ele)) {
- ele = [ele];
- }
- var i = ele.length;
recursive = recursive || true;
+ ele = this.toArray(ele);
+ var i = ele.length;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
+ toNode: function(text) {
+ if (!this.isString(text)) return text;
+ return this.create(text);
+ },
create: function (tag) {
- return DOC.createElement(tag);
+ return DOC.createElement(tag.toUpperCase());
+ },
+ frag: function(str) {
+ var frag = DOC.createDocumentFragment();
+ var temp = this.create('DIV');
+ temp.innerHTML = str;
+ while (temp.firstChild) {
+ frag.appendChild(temp.firstChild);
+ }
+ return frag;
+ },
+ // Execution Queue
+ queue: function(fn, time) {
+ var timer = function(time) {
+ QUEUE_TIMER = setTimeout(function() {
+ fn();
+ }, time || 2);
+ };
},
- frag: function() {
- return DOC.createDocumentFragment();
+ clearQueue: function() {
+ clearTimeout(QUEUE_TIMER);
+ QUEUE = [];
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
- callback: function() {}
+ callback: $this.noop
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duration, to, callback) {
- callback = callback || function() {};
+ callback = callback || this.noop;
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
- result = parser.parseFromString(str, 'text/xml');
+ return parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
- result = xmlDoc.loadXML(str); }
+ xmlDoc.loadXML(str);
+ return xmlDoc;
+ }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
+ var $this = this;
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
- beforeSend: function() {},
- sendPrepared: function() {},
- afterSend: function() {},
- preComplete: function() {},
- complete: function() {},
- failure: function() {}
+ beforeSend: $this.noop,
+ sendPrepared: $this.noop,
+ afterSend: $this.noop,
+ complete: $this.noop,
+ failure: $this.noop
}, options);
- var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
- post(options.url, options.data);
+ this.postRequest(options);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
- get(options.url, options.data);
+ this.getRequest(options);
}
+ },
+ openRequest: function(options, method) {
+ var req = this.getHttpRequest();
+ if (this.isNull(req)) return;
+ var $this = this;
+ var d = new Date();
+ var aborted = 'abort';
- //private
- function open(method, url) {
- var req = getRequest();
- if ($this.isNull(req)) {return;}
- var d = new Date();
-
- req.open(method, url, true);
-
- if (method === 'POST') {
- req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- }
- if (!options.disguise) {
- req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
- }
- req.setRequestHeader("X-Request-Id", d.getTime());
-
- req.onreadystatechange = function(e) {
- var data = req;
- if (!$this.isNull(options.dataType)) {
- switch (options.dataType) {
- case 'text':
- data = req.responseText;
- break;
- default:
- data = $this.parse(req.responseText, options.dataType);
- }
- }
-
- switch (req.readyState) {
- case 0:
- options.beforeSend();
- break;
- case 1:
- options.sendPrepared();
- break;
- case 2:
- options.afterSend();
- break;
- case 3:
- options.preComplete(data);
- break;
- case 4:
- if (req.status >= 200 && req.status < 300) {
- options.complete(data);
- } else if (req.status === 0) { // file:/// ajax
- options.complete(data);
- } else {
- options.failure(data);
- }
- break;
- }
- };
- return req;
- }
+ req.open(method, options.url, true);
- function get(url, data) {
- var req = open('GET', url + $this.formatParams(options.data));
- req.send('');
- return req;
+ if (method === 'POST') {
+ req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
-
- function post(url, data) {
- var req = open('POST', url);
- req.send($this.formatParams(options.data));
- return req;
+ if (!options.disguise) {
+ req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
+ req.setRequestHeader('X-Request-Id', d.getTime());
+
+ req.onreadystatechange = function(e) {
+ var data = '';
- function getRequest() {
- if (!$this.isUndefined(XMLHttpRequest))
- return new XMLHttpRequest();
- try {
- return new ActiveXObject(MSxml +'.6.0');
- } catch(e1) {}
- try {
- return new ActiveXObject(MSxml +'.3.0');
- } catch(e2) {}
- try {
- return new ActiveXObject(MSxml);
- } catch(e3) {}
- try {
- return new ActiveXObject('Microsoft.XMLHTTP');
- } catch(e4) {}
- }
+ switch (req.readyState) {
+ case 0:
+ options.beforeSend();
+ break;
+ case 1:
+ options.sendPrepared();
+ break;
+ case 2:
+ options.afterSend();
+ break;
+ case 4:
+
+ if (!$this.isNull(options.dataType)) {
+ try {
+ data = $this.parse(req.responseText, options.dataType);
+ } catch (erD) { data = aborted; }
+ } else {
+ try {
+ data = req.responseText;
+ } catch (erT) { data = aborted; }
+ }
+
+ if (data !== aborted && req.status >= 200 && req.status < 300) {
+ options.complete(data);
+ } else if (data !== aborted && req.status === 0) { // file:/// ajax
+ options.complete(data);
+ } else {
+ options.failure(data);
+ }
+ break;
+ }
+ };
+ return req;
+ },
+ postRequest: function(options) {
+ var req = this.openRequest(options, 'POST');
+ req.send(this.formatParams(options.data));
+ return req;
+ },
+ getRequest: function(options) {
+ var req = this.openRequest(options, 'GET');
+ req.send('');
+ return req;
+ },
+ getHttpRequest: function() {
+ if (typeof XMLHttpRequest !== 'undefined')
+ return new XMLHttpRequest();
+ try {
+ return new ActiveXObject(MSxml +'.6.0');
+ } catch(e1) {}
+ try {
+ return new ActiveXObject(MSxml +'.3.0');
+ } catch(e2) {}
+ try {
+ return new ActiveXObject(MSxml);
+ } catch(e3) {}
+ try {
+ return new ActiveXObject('Microsoft.XMLHTTP');
+ } catch(e4) {}
}
};
}(window, document));
diff --git a/test/awesome.test.js b/test/awesome.test.js
index 50bdbc2..caf3e03 100644
--- a/test/awesome.test.js
+++ b/test/awesome.test.js
@@ -1,187 +1,224 @@
(function($) {
+ $.log('ready', 'time');
unitTest = {
pass : true,
flag : []
};
$.ready(function() {
+ $.log('ready', 'timeEnd');
+ $.log('a', 'time');
var info = $.create('DIV');
- $.attr(info, 'id', 'info');
+ info.id = 'info';
+ $.attr(info, 'rel', 'yee');
$.append(info, document.body);
+ var pass = function(method, test) {
+ test = $.isUndefined(test) ? true : test;
+ if (test) {
+ info.innerHTML += method +' works.<BR>';
+ } else {
+ info.innerHTML += '<b>'+ method +' FAILED</b>.<BR>';
+ }
+ };
pass('ready');
pass('create');
- pass('attr');
+ pass('attr', $.attr($.getId('info'), 'rel') === 'yee');
$.log('Safe Log Works.');
pass('log');
var a = $.create('DIV');
var b = $.create('DIV');
var c = $.create('DIV');
- $.attr(a, 'id', 'a');
- $.attr(b, 'id', 'b');
- $.attr(c, 'id', 'c');
+ a.id = 'a';
+ b.id = 'b';
+ c.id = 'c';
$.before(a, info);
pass('before');
$.prepend(b, info);
pass('prepend');
pass('append'); // see beginning
$.after(c, info);
pass('after');
var bindTest = {
prop : false,
pass : false
};
- var bindMethod = function() {
+ function bindMethod() {
bindTest.pass = true;
};
$.bind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === true) {
pass('bind');
pass('fire');
pass('hover');// it's just using bind.. i'll pass it
bindTest.pass = false;// reset
$.unbind(a, 'click', bindMethod);
$.fire(a, 'click');
- if (bindTest.pass === false) {
- pass('unbind');
- }
+ pass('unbind', (bindTest.pass === false));
}
var linkTest = $.create('A');
linkTest.id = 'link';
linkTest.href = 'http://www.google.com';
- $.append(linkTest, $.getId('c'));
+ $.append(linkTest, $.getId('b'));
var propCanceled = true;
var propCanceled = true;
var linkPropCancelTest = function(e) {
propCanceled = false;
};
var linkCancelTest = function(e) {
$.cancelEvent(e);
$.cancelPropagation(e);
};
$.bind(linkTest, 'click', function(e) {
linkCancelTest(e);
});
$.bind(document.body, 'click', function(e) {
linkPropCancelTest(e);
});
$.fire(linkTest, 'click');
setTimeout(function() {
pass('cancelEvent');
if (propCanceled === true) {
pass('cancelPropagation');
}
}, 500);
-
if (typeof $.getId('a') === 'object') {
pass('getId');
}
if (typeof $.getTag('div')[0] === 'object') {
pass('getTag');
}
- $.attr($.getId('a'), 'class', 'test');
+ $.addClass($.getId('a'), 'test');
if (typeof $.getClass('test', document.body, 'DIV')[0] === 'object') {
pass('getClass');
}
+ if ($.hasClass($.getId('a'), 'fuuuuu')) {
+ pass('hasClass', false);
+ }
+
if ($.hasClass($.getId('a'), 'test')) {
pass('hasClass');
$.removeClass($.getId('a'), 'test');
if (!$.hasClass($.getId('a'), 'test')) {
pass('removeClass');
$.addClass($.getId('a'), 'testing');
if ($.hasClass($.getId('a'), 'testing')) {
pass('addClass');
}
}
}
$.remove($.getId('b'));
if ($.getId('b') === null) {
pass('remove');
}
- var text = info.innerHTML.split('<br>');
+ var text = info.innerHTML.split('<BR>');
+ if (text.length === 1) {
+ text = info.innerHTML.split('<br>');
+ }
text.pop(); // clear end empty node
info.innerHTML = '';
var arr = $.sort({
arr: text
});
var arrLen = arr.length;
while (arrLen--) {
- info.innerHTML += arr[arrLen] +'<br>';
+ info.innerHTML += arr[arrLen] +'<BR>';
}
$.style(info, 'display', 'block');
if ($.style(info, 'display') === 'block') {
pass('style');
pass('toCamelCase');
}
if ($.docHeight() > 0) {
pass('docHeight');
}
if ($.docWidth() > 0) {
pass('docWidth');
}
var htmlStr = '<div>"hi there\'</div>';
htmlStr = $.encodeHTML(htmlStr);
- if (htmlStr === "<div>"hi there'</div>") {
+ if (htmlStr === "<div>"hi there'</div>") {
pass('encodeHTML');
}
$.text(linkTest, 'test');
if ($.text(linkTest) === 'test') {
pass('text');
}
$.remove(linkTest);
$.ajax({
url: 'test.json',
type: 'get',
dataType: 'json',
complete: function(data) {
- if (typeof data.glossary.title === 'string') {
+ if (data.glossary.title === 'example glossary') {
pass('ajax');
pass('parse(json)');
}
}
});
$.ajax({
url: 'test.xml',
type: 'get',
dataType: 'xml',
complete: function(data) {
var output = $.getTag('to', data)[0];
if (typeof $.text(output) === 'string') {
pass('parse(xml)');
}
}
});
var formArray = $.serialize($.getId('test_form'));
if (formArray.a === 'test' && formArray.d[0] === '1') {
pass('form serialize (to array)');
}
var params = $.formatParams(formArray);
if (params = 'a=test&c=3&d=1%2C3&b=1') {
pass('format params');
}
var template = "hey, #{name}. Your name is #{name} #{last}.";
var greeting = $.template(template, {name: 'dan', last: 'masq'});
if (greeting === 'hey, dan. Your name is dan masq.') {
pass('templating');
}
- function pass(method) {
- info.innerHTML += method +' works.<br>';
+ var IS_TEST = [$.create('P'), $.create('optgroup'), $.create('div'), $.create('link')];
+ var IS_TEST_LEN = IS_TEST.length;
+ while (IS_TEST_LEN--) {
+ if ($.is(IS_TEST[IS_TEST_LEN], 'p')) {
+ pass('is');
+ }
}
+
+ var inarraytest = ['1', 2, '34', 'dan'];
+ if ($.inArray(2, inarraytest) && $.inArray('34', inarraytest)) {
+ pass('inArray');
+ }
+
+
+ var passcount = info.innerHTML.split('<BR>');
+ if (passcount.length === 1) {
+ passcount = info.innerHTML.split('<br>');
+ }
+
+
+ var finalResults = $.create('b')
+ finalResults.innerHTML = passcount.length +' passed.<br>';
+ $.prepend(finalResults, info);
+ $.log('a', 'timeEnd');
});
}(AWESOME));
|
dancrew32/AWESOME-JS | 7f1a09ab36d86af05d7e86230cb414429659e93e | duration typo | diff --git a/awesome.js b/awesome.js
index a793db3..eddf9ea 100644
--- a/awesome.js
+++ b/awesome.js
@@ -59,866 +59,866 @@ var AWESOME = (function (WIN, DOC) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
template: function(template, obj){
var cache = {};
var strCache = template;
var matches = 0;
template.replace(/#{([^}]*)}/g, function(tmpl, val) { // #{oKey}
cache[tmpl] = val;
});
for (var key in cache) {
strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
}
return strCache;
},
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (this.isUndefined(obj)) return;
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
return;
}
return obj.innerText || obj.textContent;
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
frag: function() {
return DOC.createDocumentFragment();
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
- fade: function(el, duraction, to, callback) {
+ fade: function(el, duration, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
get(options.url, options.data);
}
//private
function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
var data = req;
if (!$this.isNull(options.dataType)) {
switch (options.dataType) {
case 'text':
data = req.responseText;
break;
default:
data = $this.parse(req.responseText, options.dataType);
}
}
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(data);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(data);
} else if (req.status === 0) { // file:/// ajax
options.complete(data);
} else {
options.failure(data);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (!$this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
}
};
}(window, document));
|
dancrew32/AWESOME-JS | ce5c8e2c062302d5cdc68c2db5b80334c8d9db79 | document.createDocumentFragment() shortcut with $.frag() | diff --git a/awesome.js b/awesome.js
index b2b5b05..a793db3 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,917 +1,920 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
template: function(template, obj){
var cache = {};
var strCache = template;
var matches = 0;
template.replace(/#{([^}]*)}/g, function(tmpl, val) { // #{oKey}
cache[tmpl] = val;
});
for (var key in cache) {
strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
}
return strCache;
},
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (this.isUndefined(obj)) return;
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
return;
}
return obj.innerText || obj.textContent;
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
+ frag: function() {
+ return DOC.createDocumentFragment();
+ },
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duraction, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
get(options.url, options.data);
}
//private
function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
var data = req;
if (!$this.isNull(options.dataType)) {
switch (options.dataType) {
case 'text':
data = req.responseText;
break;
default:
data = $this.parse(req.responseText, options.dataType);
}
}
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(data);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(data);
} else if (req.status === 0) { // file:/// ajax
options.complete(data);
} else {
options.failure(data);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (!$this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
|
dancrew32/AWESOME-JS | ae78ae05636439fe01a8e9a7ca20488f95144eb5 | reduce $.text() nested complexity | diff --git a/awesome.js b/awesome.js
index 7256da0..b2b5b05 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,870 +1,869 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
template: function(template, obj){
var cache = {};
var strCache = template;
var matches = 0;
template.replace(/#{([^}]*)}/g, function(tmpl, val) { // #{oKey}
cache[tmpl] = val;
});
for (var key in cache) {
strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
}
return strCache;
},
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
- if (!this.isUndefined(obj)) {
- if (txt) {
- if (!this.isUndefined(obj.innerText)) {
- obj.innerText = txt;
- }
- obj.textContent = txt;
- } else {
- return obj.innerText || obj.textContent;
+ if (this.isUndefined(obj)) return;
+ if (txt) {
+ if (!this.isUndefined(obj.innerText)) {
+ obj.innerText = txt;
}
+ obj.textContent = txt;
+ return;
}
+ return obj.innerText || obj.textContent;
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duraction, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
get(options.url, options.data);
}
//private
function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
var data = req;
if (!$this.isNull(options.dataType)) {
switch (options.dataType) {
case 'text':
data = req.responseText;
break;
default:
data = $this.parse(req.responseText, options.dataType);
}
}
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
|
dancrew32/AWESOME-JS | bc0c3badf7f53265a718e1a6dc2118064da26ae2 | label template style #{oKey} | diff --git a/awesome.js b/awesome.js
index b4ff951..7256da0 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,843 +1,843 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
template: function(template, obj){
var cache = {};
var strCache = template;
var matches = 0;
- template.replace(/#{([^}]*)}/g, function(tmpl, val) {
+ template.replace(/#{([^}]*)}/g, function(tmpl, val) { // #{oKey}
cache[tmpl] = val;
});
for (var key in cache) {
strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
}
return strCache;
},
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duraction, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
get(options.url, options.data);
}
//private
function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
|
dancrew32/AWESOME-JS | c21b26f3a7e8e03dfc3ab8a0f0f21b196e189d19 | templates. could definitely use optimization, but it works pretty sweet imo | diff --git a/awesome.js b/awesome.js
index 3d2b155..b4ff951 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,838 +1,850 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var strs = string.split('-');
if (strs.length === 1) return strs[0];
var ccstr = string.indexOf('-') === 0
? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
: strs[0];
for (var i = 1, len = strs.length; i < len; ++i) {
var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
+ template: function(template, obj){
+ var cache = {};
+ var strCache = template;
+ var matches = 0;
+ template.replace(/#{([^}]*)}/g, function(tmpl, val) {
+ cache[tmpl] = val;
+ });
+ for (var key in cache) {
+ strCache = strCache.replace(new RegExp(key, 'g'), obj[cache[key]]);
+ }
+ return strCache;
+ },
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duraction, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
get(options.url, options.data);
}
//private
function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
diff --git a/test/awesome.test.js b/test/awesome.test.js
index f0d912b..50bdbc2 100644
--- a/test/awesome.test.js
+++ b/test/awesome.test.js
@@ -1,182 +1,187 @@
(function($) {
unitTest = {
pass : true,
flag : []
};
$.ready(function() {
var info = $.create('DIV');
$.attr(info, 'id', 'info');
$.append(info, document.body);
pass('ready');
pass('create');
pass('attr');
$.log('Safe Log Works.');
pass('log');
var a = $.create('DIV');
var b = $.create('DIV');
var c = $.create('DIV');
$.attr(a, 'id', 'a');
$.attr(b, 'id', 'b');
$.attr(c, 'id', 'c');
$.before(a, info);
pass('before');
$.prepend(b, info);
pass('prepend');
pass('append'); // see beginning
$.after(c, info);
pass('after');
var bindTest = {
prop : false,
pass : false
};
var bindMethod = function() {
bindTest.pass = true;
};
$.bind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === true) {
pass('bind');
pass('fire');
pass('hover');// it's just using bind.. i'll pass it
bindTest.pass = false;// reset
$.unbind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === false) {
pass('unbind');
}
}
var linkTest = $.create('A');
linkTest.id = 'link';
linkTest.href = 'http://www.google.com';
$.append(linkTest, $.getId('c'));
var propCanceled = true;
var propCanceled = true;
var linkPropCancelTest = function(e) {
propCanceled = false;
};
var linkCancelTest = function(e) {
$.cancelEvent(e);
$.cancelPropagation(e);
};
$.bind(linkTest, 'click', function(e) {
linkCancelTest(e);
});
$.bind(document.body, 'click', function(e) {
linkPropCancelTest(e);
});
$.fire(linkTest, 'click');
setTimeout(function() {
pass('cancelEvent');
if (propCanceled === true) {
pass('cancelPropagation');
}
}, 500);
if (typeof $.getId('a') === 'object') {
pass('getId');
}
if (typeof $.getTag('div')[0] === 'object') {
pass('getTag');
}
$.attr($.getId('a'), 'class', 'test');
if (typeof $.getClass('test', document.body, 'DIV')[0] === 'object') {
pass('getClass');
}
if ($.hasClass($.getId('a'), 'test')) {
pass('hasClass');
$.removeClass($.getId('a'), 'test');
if (!$.hasClass($.getId('a'), 'test')) {
pass('removeClass');
$.addClass($.getId('a'), 'testing');
if ($.hasClass($.getId('a'), 'testing')) {
pass('addClass');
}
}
}
$.remove($.getId('b'));
if ($.getId('b') === null) {
pass('remove');
}
var text = info.innerHTML.split('<br>');
text.pop(); // clear end empty node
info.innerHTML = '';
var arr = $.sort({
arr: text
});
var arrLen = arr.length;
while (arrLen--) {
info.innerHTML += arr[arrLen] +'<br>';
}
$.style(info, 'display', 'block');
if ($.style(info, 'display') === 'block') {
pass('style');
pass('toCamelCase');
}
if ($.docHeight() > 0) {
pass('docHeight');
}
if ($.docWidth() > 0) {
pass('docWidth');
}
var htmlStr = '<div>"hi there\'</div>';
htmlStr = $.encodeHTML(htmlStr);
if (htmlStr === "<div>"hi there'</div>") {
pass('encodeHTML');
}
$.text(linkTest, 'test');
if ($.text(linkTest) === 'test') {
pass('text');
}
$.remove(linkTest);
$.ajax({
url: 'test.json',
type: 'get',
dataType: 'json',
complete: function(data) {
if (typeof data.glossary.title === 'string') {
pass('ajax');
pass('parse(json)');
}
}
});
$.ajax({
url: 'test.xml',
type: 'get',
dataType: 'xml',
complete: function(data) {
var output = $.getTag('to', data)[0];
if (typeof $.text(output) === 'string') {
pass('parse(xml)');
}
}
});
var formArray = $.serialize($.getId('test_form'));
if (formArray.a === 'test' && formArray.d[0] === '1') {
pass('form serialize (to array)');
}
var params = $.formatParams(formArray);
if (params = 'a=test&c=3&d=1%2C3&b=1') {
pass('format params');
}
+ var template = "hey, #{name}. Your name is #{name} #{last}.";
+ var greeting = $.template(template, {name: 'dan', last: 'masq'});
+ if (greeting === 'hey, dan. Your name is dan masq.') {
+ pass('templating');
+ }
function pass(method) {
info.innerHTML += method +' works.<br>';
}
});
}(AWESOME));
diff --git a/test/index.html b/test/index.html
index 093942a..6f23c5d 100644
--- a/test/index.html
+++ b/test/index.html
@@ -1,25 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<title>Awesome Test</title>
</head>
<body>
<script type="text/javascript" src="../awesome.js"></script>
<script type="text/javascript" src="awesome.test.js"></script>
-<form id="test_form" action="faux" method="get" name="test_form">
+<form id="test_form" action="faux" method="get" name="test_form" style="display:none;">
<input type="text" name="a" value="test">
<select name="b">
<option value="1"></option>
<option value="2"></option>
</select>
<input type="radio" name="c" value="1"/>
<input type="radio" name="c" value="2"/>
<input type="radio" name="c" value="3" checked/>
<input type="checkbox" name="d" value="1" checked/>
<input type="checkbox" name="d" value="2"/>
<input type="checkbox" name="d" value="3" checked/>
</form>
</body>
</html>
|
dancrew32/AWESOME-JS | ab406c827bb5c632fd225a62409fd8ff40d92dcb | shorten camel case | diff --git a/awesome.js b/awesome.js
index 5fedf16..3d2b155 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,711 +1,713 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
- var oStringList = string.split('-');
- if (oStringList.length === 1) return oStringList[0];
+ var strs = string.split('-');
+ if (strs.length === 1) return strs[0];
- var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
+ var ccstr = string.indexOf('-') === 0
+ ? strs[0].charAt(0).toUpperCase() + strs[0].substring(1)
+ : strs[0];
- for (var i = 1, len = oStringList.length; i < len; ++i) {
- var s = oStringList[i];
+ for (var i = 1, len = strs.length; i < len; ++i) {
+ var s = strs[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
var interpolation = interpolate(fromNum, toNum, options.easing(pos));
$this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duraction, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
|
dancrew32/AWESOME-JS | a1865093f8a8b65e416ac77b923fb74966c4d3a5 | reduce line length, consistency | diff --git a/awesome.js b/awesome.js
index 26b8ee4..5fedf16 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,906 +1,908 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
- // IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
+ // IE
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
- // Call the onload function in given context or window object
+ // onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
- var re = el.className.split(" ");
+ var re = el.className.split(' ');
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
- el.className += ' ' + cls;
+ el.className += ' '+ cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
- if (this.isUndefined(re)) { return; }
+ if (this.isUndefined(re)) return;
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
- el.className += re[i] + ' ';
+ el.className += re[i] +' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
- $this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
+ var interpolation = interpolate(fromNum, toNum, options.easing(pos));
+ $this.style(el, options.property, interpolation + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
this.fade(el, duration, 0, callback);
},
fade: function(el, duraction, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
- for (var k=0; k < rawChildrenLen; ++k) {
+ for (var k = 0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
+ var encode = encodeURIComponent;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
- q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
+ q.push( encode(prop) +'='+ encode(obj[prop]) );
}
}
- return q.join("&");
+ return q.join('&');
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
- if (str === "") return;
+ if (str === '') return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
get(options.url, options.data);
}
//private
function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
var data = req;
if (!$this.isNull(options.dataType)) {
switch (options.dataType) {
case 'text':
data = req.responseText;
break;
default:
data = $this.parse(req.responseText, options.dataType);
}
}
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(data);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(data);
} else if (req.status === 0) { // file:/// ajax
options.complete(data);
} else {
options.failure(data);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (!$this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
}
};
}(window, document));
|
dancrew32/AWESOME-JS | 13ce529ea8891ef2c623015c61e68a117e730108 | reduce duplicate code for fadeIn/Out | diff --git a/awesome.js b/awesome.js
index 4b96827..26b8ee4 100644
--- a/awesome.js
+++ b/awesome.js
@@ -37,873 +37,870 @@ var AWESOME = (function (WIN, DOC) {
// Call the onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
- callback = callback || function() {};
- this.animate(el, {
- property: 'opacity',
- to: 1,
- duration: duration,
- callback: callback
- });
+ this.fade(el, duration, 1, callback);
},
fadeOut: function(el, duration, callback) {
+ this.fade(el, duration, 0, callback);
+ },
+ fade: function(el, duraction, to, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
- to: 0,
+ to: to,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k=0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
default:
get(options.url, options.data);
}
//private
function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
var data = req;
if (!$this.isNull(options.dataType)) {
switch (options.dataType) {
case 'text':
data = req.responseText;
break;
default:
data = $this.parse(req.responseText, options.dataType);
}
}
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(data);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(data);
} else if (req.status === 0) { // file:/// ajax
options.complete(data);
} else {
options.failure(data);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (!$this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
}
};
}(window, document));
|
dancrew32/AWESOME-JS | 17133759340a976fcd1de8281fb87bf0f20d6c94 | fix form serialize, use ajax.dataType to preparse | diff --git a/awesome.js b/awesome.js
index 43023e6..8d85fe3 100644
--- a/awesome.js
+++ b/awesome.js
@@ -90,829 +90,817 @@ var AWESOME = (function (WIN, DOC) {
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k=0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
case 'hidden':
case 'password':
formChildren.push(currentNode);
break;
+ case 'radio':
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
- returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
+ returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
- case 'JSON':
- get(options.url, options.data, 'json');
- break;
- case 'XML':
- get(options.url, options.data, 'xml');
- break;
- case 'TEXT':
- get(options.url, options.data, 'text');
- break;
default:
get(options.url, options.data);
}
//private
- function open(method, url, type) {
+ function open(method, url) {
var req = getRequest();
if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
- var data;
- switch (type) {
- case 'json':
- data = $this.parse(req.responseText, 'json');
- break;
- case 'xml':
- data = $this.parse(req.responseText, 'xml');
- break;
- case 'text':
- data = req.responseText;
- default:
- data = req;
+ var data = req;
+ if (!$this.isNull(options.dataType)) {
+ switch (options.dataType) {
+ case 'text':
+ data = req.responseText;
+ break;
+ default:
+ data = $this.parse(req.responseText, options.dataType);
+ }
}
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(data);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(data);
} else if (req.status === 0) { // file:/// ajax
options.complete(data);
} else {
options.failure(data);
}
break;
}
};
return req;
}
- function get(url, data, type) {
- type = type || null;
- var req = open('GET', url + $this.formatParams(options.data), type);
+ function get(url, data) {
+ var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (!$this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
}
};
}(window, document));
diff --git a/plugins/screenOverlay/screenOverlay.js b/plugins/screenOverlay/screenOverlay.js
index 8dc1038..6ec4b73 100644
--- a/plugins/screenOverlay/screenOverlay.js
+++ b/plugins/screenOverlay/screenOverlay.js
@@ -1,86 +1,86 @@
-(function($) {
+(function($, doc, win) {
$.screenOverlay = (function (options) {
options = $.setDefaults({
header: null,
headerType: 'h2',
data: null,
lightboxId: 'lightbox',
id: 'screen-overlayer',
closeText: 'Close'
}, options);
var $this = this;
var didResize = false;
// init
makeOverlay($this.docWidth(), $this.docHeight(), options.id);
// Make Viewport-sized grey area
function makeOverlay(windowWidth, windowHeight, id) {
- var $body = document.body,
+ var $body = doc.body,
overlayer = $this.getId(id),
lightbox = $this.getId(options.lightboxId),
lightboxClose = $this.getId(options.lightboxId + '-close');
if (!overlayer && !lightbox) {
var overlayDIV = $this.create('DIV'),
lightboxDIV = $this.create('DIV');
$this.prepend(overlayDIV, $body);
$this.attr(overlayDIV, 'id', id);
$this.prepend(lightboxDIV, $body);
$this.attr(lightboxDIV, 'id', options.lightboxId);
- $this.addClass(document.documentElement, 'has-overlay');
+ $this.addClass(doc.documentElement, 'has-overlay');
var overlayer = $this.getId(id),
lightbox = $this.getId(options.lightboxId);
// Output for lightbox
var lightboxOutput = '<a href="#' + options.lightboxId + '-close" id="' + options.lightboxId + '-close">'+
options.closeText +'</a><div id="' + options.lightboxId + '-inner">';
if (options.header) {
lightboxOutput += '<div class="header"><' + options.headerType + '>' +
options.header + '</' + options.headerType + '></div>';
}
lightboxOutput += '<div class="content">' + options.data + '</div></div>';
lightbox.innerHTML = lightboxOutput;
var lightboxClose = $this.getId(options.lightboxId + '-close');
}
$this.style(overlayer, 'width', windowWidth + 'px');
$this.style(overlayer, 'height', windowHeight + 'px');
function closeOverlay() {
- $this.removeClass(document.documentElement, 'has-overlay');
+ $this.removeClass(doc.documentElement, 'has-overlay');
$this.remove(lightbox);
$this.remove(overlayer);
}
// Bind close on overlayer
$this.bind(overlayer, 'click', function () {
closeOverlay();
});
// bind close button click
$this.bind(lightboxClose, 'click', function (e) {
$this.cancelEvent(e);
closeOverlay();
});
// bind resizing
- window.onresize = function() {
+ win.onresize = function() {
didResize = true;
};
setInterval(function() {
if (didResize) {
didResize = false;
$this.style($this.getId(options.id), 'width', $this.docWidth() + 'px');
$this.style($this.getId(options.id), 'height', $this.docHeight() + 'px');
}
}, 200);
}
});
-}(AWESOME));
+}(AWESOME, document, window));
diff --git a/test/awesome.test.js b/test/awesome.test.js
index f01fb52..45747d3 100644
--- a/test/awesome.test.js
+++ b/test/awesome.test.js
@@ -1,169 +1,177 @@
(function($) {
unitTest = {
pass : true,
flag : []
};
$.ready(function() {
var info = $.create('DIV');
$.attr(info, 'id', 'info');
$.append(info, document.body);
pass('ready');
pass('create');
pass('attr');
$.log('Safe Log Works.');
pass('log');
var a = $.create('DIV');
var b = $.create('DIV');
var c = $.create('DIV');
$.attr(a, 'id', 'a');
$.attr(b, 'id', 'b');
$.attr(c, 'id', 'c');
$.before(a, info);
pass('before');
$.prepend(b, info);
pass('prepend');
pass('append'); // see beginning
$.after(c, info);
pass('after');
var bindTest = {
prop : false,
pass : false
};
var bindMethod = function() {
bindTest.pass = true;
};
$.bind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === true) {
pass('bind');
pass('fire');
pass('hover');// it's just using bind.. i'll pass it
bindTest.pass = false;// reset
$.unbind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === false) {
pass('unbind');
}
}
var linkTest = $.create('A');
linkTest.id = 'link';
linkTest.href = 'http://www.google.com';
$.append(linkTest, $.getId('c'));
var propCanceled = true;
var propCanceled = true;
var linkPropCancelTest = function(e) {
propCanceled = false;
};
var linkCancelTest = function(e) {
$.cancelEvent(e);
$.cancelPropagation(e);
};
$.bind(linkTest, 'click', function(e) {
linkCancelTest(e);
});
$.bind(document.body, 'click', function(e) {
linkPropCancelTest(e);
});
$.fire(linkTest, 'click');
setTimeout(function() {
pass('cancelEvent');
if (propCanceled === true) {
pass('cancelPropagation');
}
}, 500);
if (typeof $.getId('a') === 'object') {
pass('getId');
}
if (typeof $.getTag('div')[0] === 'object') {
pass('getTag');
}
$.attr($.getId('a'), 'class', 'test');
if (typeof $.getClass('test', document.body, 'DIV')[0] === 'object') {
pass('getClass');
}
if ($.hasClass($.getId('a'), 'test')) {
pass('hasClass');
$.removeClass($.getId('a'), 'test');
if (!$.hasClass($.getId('a'), 'test')) {
pass('removeClass');
$.addClass($.getId('a'), 'testing');
if ($.hasClass($.getId('a'), 'testing')) {
pass('addClass');
}
}
}
$.remove($.getId('b'));
if ($.getId('b') === null) {
pass('remove');
}
var text = info.innerHTML.split('<br>');
text.pop(); // clear end empty node
info.innerHTML = '';
var arr = $.sort({
arr: text
});
var arrLen = arr.length;
while (arrLen--) {
info.innerHTML += arr[arrLen] +'<br>';
}
$.style(info, 'display', 'block');
if ($.style(info, 'display') === 'block') {
pass('style');
pass('toCamelCase');
}
if ($.docHeight() > 0) {
pass('docHeight');
}
if ($.docWidth() > 0) {
pass('docWidth');
}
var htmlStr = '<div>"hi there\'</div>';
htmlStr = $.encodeHTML(htmlStr);
if (htmlStr === "<div>"hi there'</div>") {
pass('encodeHTML');
}
$.text(linkTest, 'test');
if ($.text(linkTest) === 'test') {
pass('text');
}
$.remove(linkTest);
$.ajax({
url: 'test.json',
- type: 'JSON',
+ type: 'get',
+ dataType: 'json',
complete: function(data) {
if (typeof data.glossary.title === 'string') {
pass('ajax');
pass('parse(json)');
}
}
});
$.ajax({
url: 'test.xml',
- type: 'XML',
+ type: 'get',
+ dataType: 'xml',
complete: function(data) {
var output = $.getTag('to', data)[0];
if (typeof $.text(output) === 'string') {
pass('parse(xml)');
}
}
});
+ var form = $.serialize($.getId('test_form'));
+ if (form.a === 'test' && form.d[0] === '1') {
+ pass('form serialize (to array)');
+ }
+
+
function pass(method) {
info.innerHTML += method +' works.<br>';
}
});
}(AWESOME));
diff --git a/test/index.html b/test/index.html
index f4fa8fb..093942a 100644
--- a/test/index.html
+++ b/test/index.html
@@ -1,10 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<title>Awesome Test</title>
</head>
<body>
<script type="text/javascript" src="../awesome.js"></script>
<script type="text/javascript" src="awesome.test.js"></script>
+<form id="test_form" action="faux" method="get" name="test_form">
+ <input type="text" name="a" value="test">
+ <select name="b">
+ <option value="1"></option>
+ <option value="2"></option>
+ </select>
+
+ <input type="radio" name="c" value="1"/>
+ <input type="radio" name="c" value="2"/>
+ <input type="radio" name="c" value="3" checked/>
+
+ <input type="checkbox" name="d" value="1" checked/>
+ <input type="checkbox" name="d" value="2"/>
+ <input type="checkbox" name="d" value="3" checked/>
+</form>
</body>
</html>
|
dancrew32/AWESOME-JS | 4d0b0d9a0987f2b6e02c89c5dcecdc0d8c8e06cf | optimize form method and add preparsing capabilities to ajax (json/xml/text) | diff --git a/awesome.js b/awesome.js
index 3375957..43023e6 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,905 +1,918 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
- if (DOC.cookie.length > 0) {
+ if (DOC.cookie.length) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k=0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
- formChildren.push(currentNode);
- break;
case 'hidden':
- formChildren.push(currentNode);
- break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
- case 'radio':
- if (currentNode.checked) {
- formChildren.push(currentNode);
- }
- break;
}
break;
case 'select':
- formChildren.push(currentNode);
- break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
+ dataType: null,
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
- case 'GET':
- get(options.url, options.data);
- break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
+ case 'JSON':
+ get(options.url, options.data, 'json');
+ break;
+ case 'XML':
+ get(options.url, options.data, 'xml');
+ break;
+ case 'TEXT':
+ get(options.url, options.data, 'text');
+ break;
+ default:
+ get(options.url, options.data);
}
//private
- function open(method, url) {
+ function open(method, url, type) {
var req = getRequest();
- if (this.isNull(req)) {return;}
+ if ($this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
+ var data;
+ switch (type) {
+ case 'json':
+ data = $this.parse(req.responseText, 'json');
+ break;
+ case 'xml':
+ data = $this.parse(req.responseText, 'xml');
+ break;
+ case 'text':
+ data = req.responseText;
+ default:
+ data = req;
+ }
+
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
- options.preComplete(req);
+ options.preComplete(data);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
- options.complete(req);
+ options.complete(data);
} else if (req.status === 0) { // file:/// ajax
- options.complete(req);
+ options.complete(data);
} else {
- options.failure(req);
+ options.failure(data);
}
break;
}
};
return req;
}
- function get(url, data) {
- var req = open('GET', url + $this.formatParams(options.data));
+ function get(url, data, type) {
+ type = type || null;
+ var req = open('GET', url + $this.formatParams(options.data), type);
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
- if (!this.isUndefined(XMLHttpRequest))
+ if (!$this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
}
};
}(window, document));
|
dancrew32/AWESOME-JS | 04d31e290f9abbd860cdedb1ed6ef615a717d961 | add json and xml parse tests | diff --git a/test/awesome.test.js b/test/awesome.test.js
index c91c83f..f01fb52 100644
--- a/test/awesome.test.js
+++ b/test/awesome.test.js
@@ -1,148 +1,169 @@
(function($) {
unitTest = {
pass : true,
flag : []
};
$.ready(function() {
var info = $.create('DIV');
$.attr(info, 'id', 'info');
$.append(info, document.body);
pass('ready');
pass('create');
pass('attr');
$.log('Safe Log Works.');
pass('log');
var a = $.create('DIV');
var b = $.create('DIV');
var c = $.create('DIV');
$.attr(a, 'id', 'a');
$.attr(b, 'id', 'b');
$.attr(c, 'id', 'c');
$.before(a, info);
pass('before');
$.prepend(b, info);
pass('prepend');
pass('append'); // see beginning
$.after(c, info);
pass('after');
var bindTest = {
prop : false,
pass : false
};
var bindMethod = function() {
bindTest.pass = true;
};
$.bind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === true) {
pass('bind');
pass('fire');
pass('hover');// it's just using bind.. i'll pass it
bindTest.pass = false;// reset
$.unbind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === false) {
pass('unbind');
}
}
var linkTest = $.create('A');
linkTest.id = 'link';
linkTest.href = 'http://www.google.com';
$.append(linkTest, $.getId('c'));
var propCanceled = true;
var propCanceled = true;
var linkPropCancelTest = function(e) {
propCanceled = false;
};
var linkCancelTest = function(e) {
$.cancelEvent(e);
$.cancelPropagation(e);
};
$.bind(linkTest, 'click', function(e) {
linkCancelTest(e);
});
$.bind(document.body, 'click', function(e) {
linkPropCancelTest(e);
});
$.fire(linkTest, 'click');
setTimeout(function() {
pass('cancelEvent');
if (propCanceled === true) {
pass('cancelPropagation');
}
}, 500);
if (typeof $.getId('a') === 'object') {
pass('getId');
}
if (typeof $.getTag('div')[0] === 'object') {
pass('getTag');
}
$.attr($.getId('a'), 'class', 'test');
if (typeof $.getClass('test', document.body, 'DIV')[0] === 'object') {
pass('getClass');
}
if ($.hasClass($.getId('a'), 'test')) {
pass('hasClass');
$.removeClass($.getId('a'), 'test');
if (!$.hasClass($.getId('a'), 'test')) {
pass('removeClass');
$.addClass($.getId('a'), 'testing');
if ($.hasClass($.getId('a'), 'testing')) {
pass('addClass');
}
}
}
$.remove($.getId('b'));
if ($.getId('b') === null) {
pass('remove');
}
var text = info.innerHTML.split('<br>');
text.pop(); // clear end empty node
info.innerHTML = '';
var arr = $.sort({
arr: text
});
var arrLen = arr.length;
while (arrLen--) {
info.innerHTML += arr[arrLen] +'<br>';
}
$.style(info, 'display', 'block');
if ($.style(info, 'display') === 'block') {
pass('style');
pass('toCamelCase');
}
if ($.docHeight() > 0) {
pass('docHeight');
}
if ($.docWidth() > 0) {
pass('docWidth');
}
var htmlStr = '<div>"hi there\'</div>';
htmlStr = $.encodeHTML(htmlStr);
if (htmlStr === "<div>"hi there'</div>") {
pass('encodeHTML');
}
$.text(linkTest, 'test');
if ($.text(linkTest) === 'test') {
pass('text');
}
$.remove(linkTest);
+ $.ajax({
+ url: 'test.json',
+ type: 'JSON',
+ complete: function(data) {
+ if (typeof data.glossary.title === 'string') {
+ pass('ajax');
+ pass('parse(json)');
+ }
+ }
+ });
+ $.ajax({
+ url: 'test.xml',
+ type: 'XML',
+ complete: function(data) {
+ var output = $.getTag('to', data)[0];
+ if (typeof $.text(output) === 'string') {
+ pass('parse(xml)');
+ }
+ }
+ });
+
function pass(method) {
info.innerHTML += method +' works.<br>';
}
});
}(AWESOME));
diff --git a/test/test.xml b/test/test.xml
index 91f2458..bb70396 100644
--- a/test/test.xml
+++ b/test/test.xml
@@ -1,7 +1,7 @@
<?xml version="1.0"?>
<note>
- <to>Tove</to>
+ <to>Wat</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
|
dancrew32/AWESOME-JS | c01820b4890c93a8fd7011668712f4c83525a72f | formatting | diff --git a/awesome.js b/awesome.js
index 0be409f..3375957 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,766 +1,766 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curLeft = 0;
var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
top: curTop,
left: curLeft
};
},
getMousePosition: function(event, relativeTo) {
var x = event.pageX;
var y = event.pageY;
if (this.isNull(x) && !this.isNull(event.clientX)) {
var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
- var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
+ var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
x = event.clientX + xScroll - xClient;
y = event.clientY + yScroll - yClient;
}
if (!this.isNullOrUndefined(relativeTo)) {
var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
var tarPos = this.getPosition(tar);
x = x - tarPos.left;
y = y - tarPos.top;
}
return {
x: x,
y: y
};
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length > 0) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k=0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
|
dancrew32/AWESOME-JS | 0672982ea9572c767b2fc97b6eb1cee3a535cfdc | $.getMousePosition(). by default, gets page mouse position, if second param is true, gets mouse position relative to event.target, if second param is an object, it gets the mouse position relative to that target. closes #31. | diff --git a/awesome.js b/awesome.js
index 4985026..0be409f 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,756 +1,781 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
isNull: function(val) {
return typeof val === 'null';
},
isNullOrUndefined: function(val) {
return this.isNull(val) || this.isUndefined(val);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
- var curleft = 0;
- var curtop = 0;
+ var curLeft = 0;
+ var curTop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
- return [curLeft, curTop];
+ return {
+ top: curTop,
+ left: curLeft
+ };
+ },
+ getMousePosition: function(event, relativeTo) {
+ var x = event.pageX;
+ var y = event.pageY;
+ if (this.isNull(x) && !this.isNull(event.clientX)) {
+ var xScroll = (DOCEL && DOCEL.scrollLeft || BODY && BODY.scrollLeft || 0);
+ var xClient = (DOCEL && DOCEL.clientLeft || BODY && BODY.clientLeft || 0);
+ var yScroll = (DOCEL && DOCEL.scrollTop || BODY && BODY.scrollTop || 0);
+ var yClient = (DOCEL && DOCEL.clientTop || BODY && BODY.clientTop || 0);
+ x = event.clientX + xScroll - xClient;
+ y = event.clientY + yScroll - yClient;
+ }
+ if (!this.isNullOrUndefined(relativeTo)) {
+ var tar = (typeof relativeTo === 'object') ? relativeTo : event.target;
+ var tarPos = this.getPosition(tar);
+ x = x - tarPos.left;
+ y = y - tarPos.top;
+ }
+ return {
+ x: x,
+ y: y
+ };
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
cookie = name + '=' + value + expires + ';';
if (domain) {
cookie += ' domain=.'+ domain +' ;';
}
if (path) {
cookie += 'path='+ path;
}
DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length > 0) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k=0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (this.isNull(obj)) {return '';}
var q = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
|
dancrew32/AWESOME-JS | f6857fd5faa1b45bc4050fa59ea08c42bf163fc0 | isNull/ isNullOrUndefined shortcuts | diff --git a/awesome.js b/awesome.js
index 3c7b8e1..4985026 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,868 +1,880 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
- if (this.isUndefined(obj) || obj === null) {return;}
+ if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
- if (this.isUndefined(obj) || obj === null) {return;}
+ if (this.isUndefined(obj) || this.isNull(obj)) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
+ isNull: function(val) {
+ return typeof val === 'null';
+ },
+ isNullOrUndefined: function(val) {
+ return this.isNull(val) || this.isUndefined(val);
+ },
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curleft = 0;
var curtop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curLeft, curTop];
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
- // TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
+ var cookie;
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
- // document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
- DOC.cookie = name + '=' + value + expires + ';';
+ cookie = name + '=' + value + expires + ';';
+ if (domain) {
+ cookie += ' domain=.'+ domain +' ;';
+ }
+ if (path) {
+ cookie += 'path='+ path;
+ }
+ DOC.cookie = cookie;
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length > 0) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
- while (node !== null) {
+ while (!this.isNull(node)) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var k=0; k < rawChildrenLen; ++k) {
var currentNode = rawChildren[k];
switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var m = 0; m < formChildrenLen; ++m) {
var currentChild = formChildren[m];
if (!returnObject.hasOwnProperty(currentChild.name)) {
returnObject[currentChild.name] = currentChild.value;
} else {
if (typeof returnObject[currentChild.name] === 'string') {
returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
- if (obj === null) {return '';}
+ if (this.isNull(obj)) {return '';}
var q = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
- if (req === null) {return;}
+ if (this.isNull(req)) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (!this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
return new ActiveXObject(MSxml +'.6.0');
} catch(e1) {}
try {
return new ActiveXObject(MSxml +'.3.0');
} catch(e2) {}
try {
return new ActiveXObject(MSxml);
} catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e4) {}
}
}
};
}(window, document));
|
dancrew32/AWESOME-JS | 24e34cda7d6491e996946b145dedae0a3e44fac5 | forgot type check on canAttach | diff --git a/awesome.js b/awesome.js
index 431357a..3c7b8e1 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,517 +1,517 @@
// Awesome ensues
var AWESOME = (function (WIN, DOC) {
var BODY = DOC.body;
var DOCEL = DOC.documentElement;
- var canAttach = BODY.addEventListener;
+ var canAttach = typeof BODY.addEventListener === undefined;
return {
ready: function (fn, ctx) {
var contentLoaded = 'DOMContentLoaded';
var ready;
var timer;
var onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (DOC.readyState) {
if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if (!!DOCEL.doScroll) {
try {
ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || WIN);
// Clean up after the DOM is ready
if (canAttach)
DOC.removeEventListener(contentLoaded, onStateChange, false);
DOC.onreadystatechange = null;
WIN.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (canAttach)
DOC.addEventListener(contentLoaded, onStateChange, false);
// IE
DOC.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
WIN.onload = onStateChange;
},
log: function (data) {
if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || obj === null) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (this.isUndefined(obj) || obj === null) {return;}
delegate = delegate || false;
if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (DOC.createEventObject) { // ie
evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
isUndefined: function(val) {
return typeof val === 'undefined';
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
};
}
if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (!this.hasClass(el, cls)) return;
var re = el.className.split(' ');
if (this.isUndefined(re)) { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return DOC.getElementById(id);
},
getTag: function (tag, context) {
context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (!this.isUndefined(el))
if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curleft = 0;
var curtop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curLeft, curTop];
},
getScrollPosition: function() {
if (!this.isUndefined(WIN.pageYOffset)) {
return WIN.pageYOffset;
}
return DOCEL.scrollTop;
},
docHeight: function () {
return Math.max(
Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
if (!this.isUndefined(WIN.innerHeight)) {
return WIN.innerHeight;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientHeight)
&& DOCEL.clientHeight) { //ie6
return DOCEL.clientHeight;
}
return BODY.clientHeight;
},
viewportWidth: function () {
if (!this.isUndefined(WIN.innerWidth)) {
return WIN.innerWidth;
} else if (!this.isUndefined(DOCEL)
&& !this.isUndefined(DOCEL.clientWidth)
&& DOCEL.clientWidth) { //ie6
return DOCEL.clientWidth;
}
return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (!this.isUndefined(obj)) {
if (txt) {
if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
if (!this.isUndefined(ele[i].parentNode)) {
if (recursive) {
this.destroy(ele[i]);
continue;
}
ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
DOC.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (DOC.cookie.length > 0) {
var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = DOC.cookie.length;
}
return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (node !== null) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
|
dancrew32/AWESOME-JS | 8b9953e4611b03dbd73010d0409014ceab2b4207 | various JSHint suggestion fixes, feature detection for speed increases, variable caching to reduce lookups, added $.isUndefined() | diff --git a/awesome.js b/awesome.js
index b19592d..431357a 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,856 +1,868 @@
// Awesome ensues
-var AWESOME = (function () {
+var AWESOME = (function (WIN, DOC) {
+ var BODY = DOC.body;
+ var DOCEL = DOC.documentElement;
+ var canAttach = BODY.addEventListener;
+
return {
ready: function (fn, ctx) {
- var ready, timer,
- onStateChange = function (e) {
+ var contentLoaded = 'DOMContentLoaded';
+ var ready;
+ var timer;
+ var onStateChange = function (e) {
// Mozilla & Opera
- if (e && e.type === 'DOMContentLoaded') {
+ if (e && e.type === contentLoaded) {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
- } else if (document.readyState) {
- if ((/loaded|complete/).test(document.readyState)) {
+ } else if (DOC.readyState) {
+ if ((/loaded|complete/).test(DOC.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
- } else if ( !! document.documentElement.doScroll) {
+ } else if (!!DOCEL.doScroll) {
try {
- ready || document.documentElement.doScroll('left');
+ ready || DOCEL.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
- fn.call(ctx || window);
+ fn.call(ctx || WIN);
// Clean up after the DOM is ready
- if (document.removeEventListener)
- document.removeEventListener('DOMContentLoaded', onStateChange, false);
- document.onreadystatechange = null;
- window.onload = null;
- clearInterval(timer);
- timer = null;
+ if (canAttach)
+ DOC.removeEventListener(contentLoaded, onStateChange, false);
+ DOC.onreadystatechange = null;
+ WIN.onload = null;
+ clearInterval(timer);
+ timer = null;
}
};
// Mozilla & Opera
- if (document.addEventListener)
- document.addEventListener('DOMContentLoaded', onStateChange, false);
- // IE
- document.onreadystatechange = onStateChange;
- // Safari & IE
- timer = setInterval(onStateChange, 5);
- // Legacy
- window.onload = onStateChange;
+ if (canAttach)
+ DOC.addEventListener(contentLoaded, onStateChange, false);
+ // IE
+ DOC.onreadystatechange = onStateChange;
+ // Safari & IE
+ timer = setInterval(onStateChange, 5);
+ // Legacy
+ WIN.onload = onStateChange;
},
log: function (data) {
- if (typeof console !== 'undefined') {
+ if (!this.isUndefined(console)) {
console.log(data);
}
},
cancelEvent: function (event) {
- event = event || window.event;
+ event = event || WIN.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
- if (typeof obj === 'undefined' || obj === null) {return;}
+ if (this.isUndefined(obj) || obj === null) {return;}
delegate = delegate || false;
- if (typeof obj.length === 'undefined') {
+ if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
- if (obj[i].addEventListener) {
+ if (canAttach) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
- if (typeof obj === 'undefined' || obj === null) {return;}
+ if (this.isUndefined(obj) || obj === null) {return;}
delegate = delegate || false;
- if (typeof obj.length === 'undefined') {
+ if (this.isUndefined(obj.length)) {
obj = [obj];
}
var i = obj.length;
while (i--) {
- if (obj[i].removeEventListener) {
+ if (canAttach) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
- if (document.createEventObject) { // ie
- evt = document.createEventObject();
+ if (DOC.createEventObject) { // ie
+ evt = DOC.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
- evt = document.createEvent('HTMLEvents');
+ evt = DOC.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
- if (typeof obj === 'undefined') {return;}
+ if (this.isUndefined(obj)) {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
+ isUndefined: function(val) {
+ return typeof val === 'undefined';
+ },
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
- }
+ };
}
- if (typeof re === 'undefined') { return false; }
+ if (this.isUndefined(re)) { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
- if (this.hasClass(el, cls))
- var re = el.className.split(' ');
- if (typeof re === 'undefined') { return; }
- re.splice(re.indexOf(cls), 1);
- var i = re.length;
- el.className = ''; // empty
- while(i--) { // reload
- el.className += re[i] + ' ';
- }
+ if (!this.hasClass(el, cls)) return;
+ var re = el.className.split(' ');
+ if (this.isUndefined(re)) { return; }
+ re.splice(re.indexOf(cls), 1);
+ var i = re.length;
+ el.className = ''; // empty
+ while(i--) { // reload
+ el.className += re[i] + ' ';
+ }
},
getId: function (id) {
- return document.getElementById(id);
+ return DOC.getElementById(id);
},
getTag: function (tag, context) {
- context = context || document;
+ context = context || DOC;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
- if (typeof el !== 'undefined')
- if (typeof prop === 'undefined') {
+ if (!this.isUndefined(el))
+ if (this.isUndefined(prop)) {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
- var view = document.defaultView;
+ var view = DOC.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
- if (el.filters.length <= 0) {
+ if (el['filters'].length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
- var opacity = el.filters('alpha').opacity;
+ var opacity = el['filters']('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
- var curleft = curtop = 0;
+ var curleft = 0;
+ var curtop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curLeft, curTop];
},
getScrollPosition: function() {
- if (window.pageYOffset !== 'undefined') {
- return window.pageYOffset;
+ if (!this.isUndefined(WIN.pageYOffset)) {
+ return WIN.pageYOffset;
}
- return document.documentElement.scrollTop;
+ return DOCEL.scrollTop;
},
docHeight: function () {
- var D = document;
return Math.max(
- Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
- Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
- Math.max(D.body.clientHeight, D.documentElement.clientHeight)
+ Math.max(BODY.scrollHeight, DOCEL.scrollHeight),
+ Math.max(BODY.offsetHeight, DOCEL.offsetHeight),
+ Math.max(BODY.clientHeight, DOCEL.clientHeight)
);
},
docWidth: function () {
- var D = document;
- return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
+ return Math.max(BODY.clientWidth, DOCEL.clientWidth);
},
viewportHeight: function () {
- if (typeof window.innerHeight !== 'undefined') {
- return window.innerHeight;
- } else if (typeof document.documentElement !== 'undefined'
- && typeof document.documentElement.clientHeight !== 'undefined'
- && document.documentElement.clientHeight) { //ie6
- return document.documentElement.clientHeight;
+ if (!this.isUndefined(WIN.innerHeight)) {
+ return WIN.innerHeight;
+ } else if (!this.isUndefined(DOCEL)
+ && !this.isUndefined(DOCEL.clientHeight)
+ && DOCEL.clientHeight) { //ie6
+ return DOCEL.clientHeight;
}
- return document.getElementsByTagName('body')[0].clientHeight;
+ return BODY.clientHeight;
},
viewportWidth: function () {
- if (typeof window.innerWidth !== 'undefined') {
- return window.innerWidth;
- } else if (typeof document.documentElement !== 'undefined'
- && typeof document.documentElement.clientWidth !== 'undefined'
- && document.documentElement.clientWidth) { //ie6
- return document.documentElement.clientWidth;
+ if (!this.isUndefined(WIN.innerWidth)) {
+ return WIN.innerWidth;
+ } else if (!this.isUndefined(DOCEL)
+ && !this.isUndefined(DOCEL.clientWidth)
+ && DOCEL.clientWidth) { //ie6
+ return DOCEL.clientWidth;
}
- return document.getElementsByTagName('body')[0].clientWidth;
+ return BODY.clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
- if (typeof obj !== 'undefined') {
+ if (!this.isUndefined(obj)) {
if (txt) {
- if (obj.innerText !== 'undefined') {
+ if (!this.isUndefined(obj.innerText)) {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
- node.appendChild(newNode)
+ node.appendChild(newNode);
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
recursive = recursive || true;
while (i--) {
- if (typeof ele[i].parentNode !== 'undefined') {
- recursive ? this.destroy(ele[i]) : ele[i].parentNode.removeChild(ele[i]);
+ if (!this.isUndefined(ele[i].parentNode)) {
+ if (recursive) {
+ this.destroy(ele[i]);
+ continue;
+ }
+ ele[i].parentNode.removeChild(ele[i]);
}
}
},
destroy: function(el) {
- if (el !== 'undefined')
+ if (this.isUndefined(el)) return;
var trash = this.create('DIV');
trash.appendChild(el);
trash.innerHTML = '';
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
- return document.createElement(tag);
+ return DOC.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
- domain = domain || window.location.host;
+ domain = domain || WIN.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
- document.cookie = name + '=' + value + expires + ';';
+ DOC.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
- if (document.cookie.length > 0) {
- var c_start = document.cookie.indexOf(c_name + "=");
+ if (DOC.cookie.length > 0) {
+ var c_start = DOC.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
- var c_end = document.cookie.indexOf(";", c_start);
+ var c_end = DOC.cookie.indexOf(";", c_start);
if (c_end === -1) {
- c_end = document.cookie.length;
+ c_end = DOC.cookie.length;
}
- return unescape(document.cookie.substring(c_start, c_end));
+ return unescape(DOC.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (node !== null) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
- var start = +new Date;
+ var start = +new Date();
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
- var time = +new Date;
+ var time = +new Date();
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
- var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
+ var hashes = WIN.location.href.slice(WIN.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
- for (var i=0; i < rawChildrenLen; ++i) {
- var currentNode = rawChildren[i];
- switch(rawChildren[i].nodeName.toLowerCase()) {
+ for (var k=0; k < rawChildrenLen; ++k) {
+ var currentNode = rawChildren[k];
+ switch(rawChildren[k].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
- for (var i = 0; i < formChildrenLen; ++i) {
- var currentNode = formChildren[i];
- if (!returnObject.hasOwnProperty(currentNode.name)) {
- returnObject[currentNode.name] = currentNode.value;
+ for (var m = 0; m < formChildrenLen; ++m) {
+ var currentChild = formChildren[m];
+ if (!returnObject.hasOwnProperty(currentChild.name)) {
+ returnObject[currentChild.name] = currentChild.value;
} else {
- if (typeof returnObject[currentNode.name] === 'string') {
- returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
+ if (typeof returnObject[currentChild.name] === 'string') {
+ returnObject[currentChild.name] = [returnObject[currentChild.name], currentChild.value.toString()];
} else {
- returnObject[currentNode.name].push(currentNode.value.toString());
+ returnObject[currentChild.name].push(currentChild.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
- for (p in obj) {
- if (obj.hasOwnProperty(p)) {
- q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
+ q.push( encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
- if (typeof options[index] === 'undefined') {
+ if (this.isUndefined(options[index])) {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
- if (window.DOMParser) {
+ if (WIN.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
- var EMPTY_STRING = new String('');
+ var EMPTY_STRING = '';
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
- default: // sign or digit
- cont = stack[0];
- cont[key || cont.length] = +(tok);
- key = void 0;
- break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
+ default: // sign or digit
+ cont = stack[0];
+ cont[key || cont.length] = +(tok);
+ key = void 0;
+ break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
+ var MSxml = 'Msxml2.XMLHTTP';
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
- break
+ break;
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
- if (typeof(XMLHttpRequest) !== 'undefined')
+ if (!this.isUndefined(XMLHttpRequest))
return new XMLHttpRequest();
try {
- return new ActiveXObject('Msxml2.XMLHTTP.6.0');
- } catch(e) {}
+ return new ActiveXObject(MSxml +'.6.0');
+ } catch(e1) {}
try {
- return new ActiveXObject('Msxml2.XMLHTTP.3.0');
- } catch(e) {}
+ return new ActiveXObject(MSxml +'.3.0');
+ } catch(e2) {}
try {
- return new ActiveXObject('Msxml2.XMLHTTP');
- } catch(e) {}
+ return new ActiveXObject(MSxml);
+ } catch(e3) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
- } catch(e) {}
- return null;
+ } catch(e4) {}
}
}
};
-}());
+}(window, document));
|
dancrew32/AWESOME-JS | 4d854c1906ed318d958514fb8ec8aea55b3d50fe | adding playground | diff --git a/README b/README
index e01525b..72023ed 100644
--- a/README
+++ b/README
@@ -1,11 +1,15 @@
Tired of waiting for jQuery to load?
Get to docready faster and get the same stuff done with awesome.js!
(It works in IE6, 7, 8, 9, Firefox, Webkit, Opera too!)
awesome.js size:
- Original Size: 17.59KB (5.59KB gzipped)
- Compiled Size: 10.37KB (3.93KB gzipped)
vs. jQuery size:
- Development Size: 214KB
- Compiled Size: 29KB (gzipped)
+
+
+Playground:
+http://jsfiddle.net/danmasq/mFUbj/
\ No newline at end of file
|
dancrew32/AWESOME-JS | 86c5314de900ddbac4390dc2b2408caea3de6425 | fixing $.remove memory leak with $.destroy, which could be called directly. | diff --git a/awesome.js b/awesome.js
index 31eca56..b19592d 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,848 +1,855 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curleft = curtop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curLeft, curTop];
},
getScrollPosition: function() {
if (window.pageYOffset !== 'undefined') {
return window.pageYOffset;
}
return document.documentElement.scrollTop;
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
viewportHeight: function () {
if (typeof window.innerHeight !== 'undefined') {
return window.innerHeight;
} else if (typeof document.documentElement !== 'undefined'
&& typeof document.documentElement.clientHeight !== 'undefined'
&& document.documentElement.clientHeight) { //ie6
return document.documentElement.clientHeight;
}
return document.getElementsByTagName('body')[0].clientHeight;
},
viewportWidth: function () {
if (typeof window.innerWidth !== 'undefined') {
return window.innerWidth;
} else if (typeof document.documentElement !== 'undefined'
&& typeof document.documentElement.clientWidth !== 'undefined'
&& document.documentElement.clientWidth) { //ie6
return document.documentElement.clientWidth;
}
return document.getElementsByTagName('body')[0].clientWidth;
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
- remove: function (ele) {
+ remove: function (ele, recursive) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
+ recursive = recursive || true;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
- ele[i].parentNode.removeChild(ele[i]);
+ recursive ? this.destroy(ele[i]) : ele[i].parentNode.removeChild(ele[i]);
}
}
},
+ destroy: function(el) {
+ if (el !== 'undefined')
+ var trash = this.create('DIV');
+ trash.appendChild(el);
+ trash.innerHTML = '';
+ },
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (node !== null) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) {}
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) {}
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {}
return null;
}
}
};
diff --git a/awesome.test.js b/awesome.test.js
index 72b85c0..c91c83f 100644
--- a/awesome.test.js
+++ b/awesome.test.js
@@ -1,148 +1,148 @@
(function($) {
unitTest = {
pass : true,
flag : []
};
$.ready(function() {
var info = $.create('DIV');
$.attr(info, 'id', 'info');
$.append(info, document.body);
pass('ready');
pass('create');
pass('attr');
$.log('Safe Log Works.');
pass('log');
var a = $.create('DIV');
var b = $.create('DIV');
var c = $.create('DIV');
$.attr(a, 'id', 'a');
$.attr(b, 'id', 'b');
$.attr(c, 'id', 'c');
$.before(a, info);
pass('before');
$.prepend(b, info);
pass('prepend');
pass('append'); // see beginning
$.after(c, info);
pass('after');
var bindTest = {
prop : false,
pass : false
};
var bindMethod = function() {
bindTest.pass = true;
};
$.bind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === true) {
pass('bind');
pass('fire');
pass('hover');// it's just using bind.. i'll pass it
bindTest.pass = false;// reset
$.unbind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === false) {
pass('unbind');
}
}
var linkTest = $.create('A');
linkTest.id = 'link';
linkTest.href = 'http://www.google.com';
$.append(linkTest, $.getId('c'));
var propCanceled = true;
var propCanceled = true;
var linkPropCancelTest = function(e) {
propCanceled = false;
};
var linkCancelTest = function(e) {
$.cancelEvent(e);
$.cancelPropagation(e);
};
$.bind(linkTest, 'click', function(e) {
linkCancelTest(e);
});
$.bind(document.body, 'click', function(e) {
linkPropCancelTest(e);
});
$.fire(linkTest, 'click');
setTimeout(function() {
pass('cancelEvent');
if (propCanceled === true) {
pass('cancelPropagation');
}
}, 500);
if (typeof $.getId('a') === 'object') {
pass('getId');
}
if (typeof $.getTag('div')[0] === 'object') {
pass('getTag');
}
$.attr($.getId('a'), 'class', 'test');
if (typeof $.getClass('test', document.body, 'DIV')[0] === 'object') {
pass('getClass');
}
if ($.hasClass($.getId('a'), 'test')) {
pass('hasClass');
$.removeClass($.getId('a'), 'test');
if (!$.hasClass($.getId('a'), 'test')) {
pass('removeClass');
$.addClass($.getId('a'), 'testing');
if ($.hasClass($.getId('a'), 'testing')) {
pass('addClass');
}
}
}
$.remove($.getId('b'));
- if (typeof $.getId('b') === 'undefined') {
+ if ($.getId('b') === null) {
pass('remove');
}
var text = info.innerHTML.split('<br>');
text.pop(); // clear end empty node
info.innerHTML = '';
var arr = $.sort({
arr: text
});
var arrLen = arr.length;
while (arrLen--) {
info.innerHTML += arr[arrLen] +'<br>';
}
$.style(info, 'display', 'block');
if ($.style(info, 'display') === 'block') {
pass('style');
pass('toCamelCase');
}
if ($.docHeight() > 0) {
pass('docHeight');
}
if ($.docWidth() > 0) {
pass('docWidth');
}
var htmlStr = '<div>"hi there\'</div>';
htmlStr = $.encodeHTML(htmlStr);
if (htmlStr === "<div>"hi there'</div>") {
pass('encodeHTML');
}
$.text(linkTest, 'test');
if ($.text(linkTest) === 'test') {
pass('text');
}
$.remove(linkTest);
function pass(method) {
info.innerHTML += method +' works.<br>';
}
});
}(AWESOME));
diff --git a/index.html b/index.html
index 4b4c42b..a2ad23f 100644
--- a/index.html
+++ b/index.html
@@ -1,32 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Awesome</title>
<style>
body {
height: 2000px;
}
</style>
</head>
<body>
-
<script type="text/javascript" src="awesome.js"></script>
<script type="text/javascript" src="awesome.test.js"></script>
-<script type="text/javascript" src="plugins/infinityScroll/infinityScroll.js"></script>
-<script>
-(function($) {
- $.ready(function() {
- $.infinityScroll({
- onScroll: function() {
- /*var initHeight = parseInt($.style($.getTag('body')[0], 'height'), 10);*/
- /*$.style($.getTag('body')[0], 'height', initHeight + 2000 +'px');*/
- /*$.log(this);*/
- /*this.pageHeight = $.docHeight();*/
- /*this.stop = false;*/
- }
- });
- });
-}(AWESOME));
-</script>
</body>
</html>
|
dancrew32/AWESOME-JS | bdeb34f8d04df074ee19112f8c1e3d98bec877c1 | infinity scroll plugin checkin.. still needs work | diff --git a/index.html b/index.html
index fea9381..4b4c42b 100644
--- a/index.html
+++ b/index.html
@@ -1,11 +1,32 @@
<!DOCTYPE html>
<html>
<head>
<title>Awesome</title>
+<style>
+body {
+height: 2000px;
+}
+</style>
</head>
<body>
<script type="text/javascript" src="awesome.js"></script>
<script type="text/javascript" src="awesome.test.js"></script>
+<script type="text/javascript" src="plugins/infinityScroll/infinityScroll.js"></script>
+<script>
+(function($) {
+ $.ready(function() {
+ $.infinityScroll({
+ onScroll: function() {
+ /*var initHeight = parseInt($.style($.getTag('body')[0], 'height'), 10);*/
+ /*$.style($.getTag('body')[0], 'height', initHeight + 2000 +'px');*/
+ /*$.log(this);*/
+ /*this.pageHeight = $.docHeight();*/
+ /*this.stop = false;*/
+ }
+ });
+ });
+}(AWESOME));
+</script>
</body>
</html>
diff --git a/plugins/infinityScroll/infinityScroll.js b/plugins/infinityScroll/infinityScroll.js
new file mode 100644
index 0000000..c77ebec
--- /dev/null
+++ b/plugins/infinityScroll/infinityScroll.js
@@ -0,0 +1,36 @@
+(function($) {
+ $.infinityScroll = (function (options) {
+ options = $.setDefaults({
+ checkRate: 500,
+ onScroll: function() {
+ this.pageHeight = $.docHeight();
+ this.stop = false;
+ },
+ pageOffset: 1,
+ viewportsToScroll: 3,
+ stop: false,
+ pageHeight: $.docHeight()
+ }, options);
+
+ var page = options.pageOffset;
+ var scrollPosition;
+ var pageHeight = $.docHeight();
+ var viewPortDistancesToScroll = 3;
+ var vpHeight;
+
+ setInterval(function() {
+ vpHeight = $.viewportHeight();
+
+ var scrollPosition = $.getScrollPosition();
+ var heightDifference = vpHeight * options.viewportsToScroll;
+ var heightScrollDifference = pageHeight - scrollPosition;
+
+
+ if (!options.stop && heightScrollDifference < heightDifference) {
+ page = page + 1;
+ options.stop = true;
+ options.onScroll(page); // TODO: set this.stop = false, set new pageHeight in callback
+ }
+ }, options.checkRate);
+ });
+}(AWESOME));
|
dancrew32/AWESOME-JS | 64c56cef31f318cd66ca25190542b00d87c72557 | fix test | diff --git a/awesome.test.js b/awesome.test.js
index 5d4dad1..72b85c0 100644
--- a/awesome.test.js
+++ b/awesome.test.js
@@ -1,147 +1,148 @@
(function($) {
unitTest = {
pass : true,
flag : []
};
$.ready(function() {
var info = $.create('DIV');
$.attr(info, 'id', 'info');
$.append(info, document.body);
pass('ready');
pass('create');
pass('attr');
$.log('Safe Log Works.');
pass('log');
var a = $.create('DIV');
var b = $.create('DIV');
var c = $.create('DIV');
$.attr(a, 'id', 'a');
$.attr(b, 'id', 'b');
$.attr(c, 'id', 'c');
$.before(a, info);
pass('before');
$.prepend(b, info);
pass('prepend');
pass('append'); // see beginning
$.after(c, info);
pass('after');
var bindTest = {
prop : false,
pass : false
};
var bindMethod = function() {
bindTest.pass = true;
};
$.bind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === true) {
pass('bind');
pass('fire');
pass('hover');// it's just using bind.. i'll pass it
bindTest.pass = false;// reset
$.unbind(a, 'click', bindMethod);
$.fire(a, 'click');
if (bindTest.pass === false) {
pass('unbind');
}
}
var linkTest = $.create('A');
linkTest.id = 'link';
linkTest.href = 'http://www.google.com';
$.append(linkTest, $.getId('c'));
var propCanceled = true;
var propCanceled = true;
var linkPropCancelTest = function(e) {
propCanceled = false;
};
var linkCancelTest = function(e) {
$.cancelEvent(e);
$.cancelPropagation(e);
};
$.bind(linkTest, 'click', function(e) {
linkCancelTest(e);
});
$.bind(document.body, 'click', function(e) {
linkPropCancelTest(e);
});
$.fire(linkTest, 'click');
setTimeout(function() {
pass('cancelEvent');
if (propCanceled === true) {
pass('cancelPropagation');
}
}, 500);
if (typeof $.getId('a') === 'object') {
pass('getId');
}
if (typeof $.getTag('div')[0] === 'object') {
pass('getTag');
}
$.attr($.getId('a'), 'class', 'test');
if (typeof $.getClass('test', document.body, 'DIV')[0] === 'object') {
pass('getClass');
}
if ($.hasClass($.getId('a'), 'test')) {
pass('hasClass');
$.removeClass($.getId('a'), 'test');
if (!$.hasClass($.getId('a'), 'test')) {
pass('removeClass');
$.addClass($.getId('a'), 'testing');
if ($.hasClass($.getId('a'), 'testing')) {
pass('addClass');
}
}
}
$.remove($.getId('b'));
if (typeof $.getId('b') === 'undefined') {
pass('remove');
}
var text = info.innerHTML.split('<br>');
text.pop(); // clear end empty node
info.innerHTML = '';
var arr = $.sort({
arr: text
});
var arrLen = arr.length;
while (arrLen--) {
info.innerHTML += arr[arrLen] +'<br>';
}
$.style(info, 'display', 'block');
if ($.style(info, 'display') === 'block') {
pass('style');
pass('toCamelCase');
}
if ($.docHeight() > 0) {
pass('docHeight');
}
if ($.docWidth() > 0) {
pass('docWidth');
}
var htmlStr = '<div>"hi there\'</div>';
htmlStr = $.encodeHTML(htmlStr);
if (htmlStr === "<div>"hi there'</div>") {
pass('encodeHTML');
}
- $.text(link, 'test');
- if ($.text(link) === 'test') {
+ $.text(linkTest, 'test');
+ if ($.text(linkTest) === 'test') {
pass('text');
}
- $.remove(link);
+ $.remove(linkTest);
+
+ function pass(method) {
+ info.innerHTML += method +' works.<br>';
+ }
});
- function pass(method) {
- info.innerHTML += method +' works.<br>';
- }
}(AWESOME));
|
dancrew32/AWESOME-JS | 63197620e30206746977769913e07fcc69abc7a8 | viewportHeight/Width | diff --git a/awesome.js b/awesome.js
index fc3f1de..31eca56 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,829 +1,849 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
getPosition: function(obj) {
if (!obj) return;
var curleft = curtop = 0;
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curLeft, curTop];
},
getScrollPosition: function() {
if (window.pageYOffset !== 'undefined') {
return window.pageYOffset;
}
return document.documentElement.scrollTop;
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
+ viewportHeight: function () {
+ if (typeof window.innerHeight !== 'undefined') {
+ return window.innerHeight;
+ } else if (typeof document.documentElement !== 'undefined'
+ && typeof document.documentElement.clientHeight !== 'undefined'
+ && document.documentElement.clientHeight) { //ie6
+ return document.documentElement.clientHeight;
+ }
+ return document.getElementsByTagName('body')[0].clientHeight;
+ },
+ viewportWidth: function () {
+ if (typeof window.innerWidth !== 'undefined') {
+ return window.innerWidth;
+ } else if (typeof document.documentElement !== 'undefined'
+ && typeof document.documentElement.clientWidth !== 'undefined'
+ && document.documentElement.clientWidth) { //ie6
+ return document.documentElement.clientWidth;
+ }
+ return document.getElementsByTagName('body')[0].clientWidth;
+ },
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (node !== null) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
- } catch(e) { }
+ } catch(e) {}
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
- } catch(e) { }
+ } catch(e) {}
try {
return new ActiveXObject('Msxml2.XMLHTTP');
- } catch(e) { }
+ } catch(e) {}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
- } catch(e) { }
+ } catch(e) {}
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 935336fcb56b3500961edb0f1c4fbfec8e40c10e | $.getPosition(el) ([x, y]) and $.getScrollPosition() (number from top) | diff --git a/awesome.js b/awesome.js
index 793985d..fc3f1de 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,732 +1,747 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
+ getPosition: function(obj) {
+ if (!obj) return;
+ var curleft = curtop = 0;
+ do {
+ curLeft += obj.offsetLeft;
+ curTop += obj.offsetTop;
+ } while (obj = obj.offsetParent);
+ return [curLeft, curTop];
+ },
+ getScrollPosition: function() {
+ if (window.pageYOffset !== 'undefined') {
+ return window.pageYOffset;
+ }
+ return document.documentElement.scrollTop;
+ },
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (node !== null) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
|
dancrew32/AWESOME-JS | faf85dc899c5acfad696b27a20d4f14e5ea9becc | initial checkin for awesome unit test | diff --git a/awesome.test.js b/awesome.test.js
new file mode 100644
index 0000000..5d4dad1
--- /dev/null
+++ b/awesome.test.js
@@ -0,0 +1,147 @@
+(function($) {
+ unitTest = {
+ pass : true,
+ flag : []
+ };
+ $.ready(function() {
+ var info = $.create('DIV');
+ $.attr(info, 'id', 'info');
+ $.append(info, document.body);
+ pass('ready');
+ pass('create');
+ pass('attr');
+ $.log('Safe Log Works.');
+ pass('log');
+ var a = $.create('DIV');
+ var b = $.create('DIV');
+ var c = $.create('DIV');
+ $.attr(a, 'id', 'a');
+ $.attr(b, 'id', 'b');
+ $.attr(c, 'id', 'c');
+ $.before(a, info);
+ pass('before');
+ $.prepend(b, info);
+ pass('prepend');
+ pass('append'); // see beginning
+ $.after(c, info);
+ pass('after');
+
+ var bindTest = {
+ prop : false,
+ pass : false
+ };
+ var bindMethod = function() {
+ bindTest.pass = true;
+ };
+ $.bind(a, 'click', bindMethod);
+ $.fire(a, 'click');
+ if (bindTest.pass === true) {
+ pass('bind');
+ pass('fire');
+ pass('hover');// it's just using bind.. i'll pass it
+ bindTest.pass = false;// reset
+
+ $.unbind(a, 'click', bindMethod);
+ $.fire(a, 'click');
+ if (bindTest.pass === false) {
+ pass('unbind');
+ }
+ }
+ var linkTest = $.create('A');
+ linkTest.id = 'link';
+ linkTest.href = 'http://www.google.com';
+ $.append(linkTest, $.getId('c'));
+ var propCanceled = true;
+ var propCanceled = true;
+ var linkPropCancelTest = function(e) {
+ propCanceled = false;
+ };
+ var linkCancelTest = function(e) {
+ $.cancelEvent(e);
+ $.cancelPropagation(e);
+ };
+ $.bind(linkTest, 'click', function(e) {
+ linkCancelTest(e);
+ });
+ $.bind(document.body, 'click', function(e) {
+ linkPropCancelTest(e);
+ });
+ $.fire(linkTest, 'click');
+ setTimeout(function() {
+ pass('cancelEvent');
+ if (propCanceled === true) {
+ pass('cancelPropagation');
+ }
+ }, 500);
+
+
+ if (typeof $.getId('a') === 'object') {
+ pass('getId');
+ }
+ if (typeof $.getTag('div')[0] === 'object') {
+ pass('getTag');
+ }
+ $.attr($.getId('a'), 'class', 'test');
+ if (typeof $.getClass('test', document.body, 'DIV')[0] === 'object') {
+ pass('getClass');
+ }
+
+ if ($.hasClass($.getId('a'), 'test')) {
+ pass('hasClass');
+ $.removeClass($.getId('a'), 'test');
+ if (!$.hasClass($.getId('a'), 'test')) {
+ pass('removeClass');
+ $.addClass($.getId('a'), 'testing');
+ if ($.hasClass($.getId('a'), 'testing')) {
+ pass('addClass');
+ }
+ }
+ }
+
+ $.remove($.getId('b'));
+ if (typeof $.getId('b') === 'undefined') {
+ pass('remove');
+ }
+
+ var text = info.innerHTML.split('<br>');
+ text.pop(); // clear end empty node
+ info.innerHTML = '';
+ var arr = $.sort({
+ arr: text
+ });
+ var arrLen = arr.length;
+ while (arrLen--) {
+ info.innerHTML += arr[arrLen] +'<br>';
+ }
+
+ $.style(info, 'display', 'block');
+ if ($.style(info, 'display') === 'block') {
+ pass('style');
+ pass('toCamelCase');
+ }
+
+ if ($.docHeight() > 0) {
+ pass('docHeight');
+ }
+ if ($.docWidth() > 0) {
+ pass('docWidth');
+ }
+
+ var htmlStr = '<div>"hi there\'</div>';
+ htmlStr = $.encodeHTML(htmlStr);
+ if (htmlStr === "<div>"hi there'</div>") {
+ pass('encodeHTML');
+ }
+
+
+ $.text(link, 'test');
+ if ($.text(link) === 'test') {
+ pass('text');
+ }
+ $.remove(link);
+ });
+
+ function pass(method) {
+ info.innerHTML += method +' works.<br>';
+ }
+}(AWESOME));
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..fea9381
--- /dev/null
+++ b/index.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Awesome</title>
+</head>
+<body>
+
+<script type="text/javascript" src="awesome.js"></script>
+<script type="text/javascript" src="awesome.test.js"></script>
+</body>
+</html>
diff --git a/test.json b/test.json
new file mode 100644
index 0000000..084ff2e
--- /dev/null
+++ b/test.json
@@ -0,0 +1,23 @@
+{
+ "glossary": {
+ "title": "example glossary",
+ "GlossDiv": {
+ "title": "S",
+ "GlossList": {
+ "GlossEntry": {
+ "ID": "SGML",
+ "SortAs": "SGML",
+ "GlossTerm": "Standard Generalized Markup Language",
+ "Acronym": "SGML",
+ "Abbrev": "ISO 8879:1986",
+ "GlossDef": {
+ "para": "A meta-markup language, used to create markup languages such as DocBook.",
+ "GlossSeeAlso": ["GML", "XML"]
+ },
+ "GlossSee": "markup"
+ }
+ }
+ }
+ }
+}
+
diff --git a/test.xml b/test.xml
new file mode 100644
index 0000000..91f2458
--- /dev/null
+++ b/test.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+<note>
+ <to>Tove</to>
+ <from>Jani</from>
+ <heading>Reminder</heading>
+ <body>Don't forget me this weekend!</body>
+</note>
|
dancrew32/AWESOME-JS | 7f570952de5c420d86235574b65028d4f23739f0 | should probably capitalize document.createElement node names. won't force it though since html5 created elements have to be lowercase | diff --git a/plugins/characterLimit/characterLimit.js b/plugins/characterLimit/characterLimit.js
index 5e0f08c..e565a5e 100644
--- a/plugins/characterLimit/characterLimit.js
+++ b/plugins/characterLimit/characterLimit.js
@@ -1,88 +1,88 @@
(function($) {
$.characterLimit = (function (options) {
options = $.setDefaults({
obj: null,
limit: 140,
limitOffset: 0,
truncate: true,
prefixSingular: '',
prefixPlural: '',
suffixSingular: 'character remaining',
suffixPlural: 'characters remaining',
warning: 10,
warningClass: 'warning',
exceeded: 0,
exceededClass: 'exceeded',
position: 'after'
}, options);
if (!('length' in options.obj)) {
options.obj = [options.obj];
}
var i = options.obj.length;
while(i--) {
var obj = options.obj[i];
- var counter = $.create('div');
+ var counter = $.create('DIV');
counter.className = 'counter';
var hasPrefix = false;
var hasSuffix = false;
counter.innerHTML = "";
if (options.prefixSingular != "" || options.prefixPlural != "") {
hasPrefix = true;
counter.innerHTML += '<span class="prefix"></span> ';
}
counter.innerHTML += '<span class="number"></span>';
if (options.suffixSingular != "" || options.suffixPlural != "") {
hasSuffix = true;
counter.innerHTML += ' <span class="suffix"></span>';
}
if (options.position == 'after') {
$.after(counter, obj);
} else {
$.before(counter, obj);
}
var num = $.getClass('number', counter, 'span')[0];
var initCount = getCount(obj.value.length);
num.innerHTML = initCount;
if (hasPrefix) {
var prefix = $.getClass('prefix', counter, 'span')[0];
prefix.innerHTML = $.plural(initCount, options.prefixSingular, options.prefixPlural);
}
if (hasSuffix) {
var suffix = $.getClass('suffix', counter, 'span')[0];
suffix.innerHTML = $.plural(initCount, options.suffixSingular, options.suffixPlural);
}
$.bind(obj, 'keyup', function(e) {
var count = getCount(this.value.length);
if (count <= 0 && options.truncate) {
this.value = this.value.substring(0, options.limit + options.limitOffset);
}
num.innerHTML = count;
addLabels(counter, count);
if (hasPrefix) {
prefix.innerHTML = $.plural(count, options.prefixSingular, options.prefixPlural);
}
if (hasSuffix) {
suffix.innerHTML = $.plural(count, options.suffixSingular, options.suffixPlural);
}
});
}
function getCount(len) {
return options.limit - len;
}
function addLabels(label, count) {
if (count <= options.warning) {
$.addClass(label, options.warningClass);
} else {
$.removeClass(label, options.warningClass);
}
if (count <= options.exceeded) {
$.addClass(label, options.exceededClass);
} else {
$.removeClass(label, options.exceededClass);
}
}
});
}(AWESOME));
diff --git a/plugins/screenOverlay/screenOverlay.js b/plugins/screenOverlay/screenOverlay.js
index 012e927..8dc1038 100644
--- a/plugins/screenOverlay/screenOverlay.js
+++ b/plugins/screenOverlay/screenOverlay.js
@@ -1,86 +1,86 @@
(function($) {
$.screenOverlay = (function (options) {
options = $.setDefaults({
header: null,
headerType: 'h2',
data: null,
lightboxId: 'lightbox',
id: 'screen-overlayer',
closeText: 'Close'
}, options);
var $this = this;
var didResize = false;
// init
makeOverlay($this.docWidth(), $this.docHeight(), options.id);
// Make Viewport-sized grey area
function makeOverlay(windowWidth, windowHeight, id) {
var $body = document.body,
overlayer = $this.getId(id),
lightbox = $this.getId(options.lightboxId),
lightboxClose = $this.getId(options.lightboxId + '-close');
if (!overlayer && !lightbox) {
- var overlayDIV = $this.create('div'),
- lightboxDIV = $this.create('div');
+ var overlayDIV = $this.create('DIV'),
+ lightboxDIV = $this.create('DIV');
$this.prepend(overlayDIV, $body);
$this.attr(overlayDIV, 'id', id);
$this.prepend(lightboxDIV, $body);
$this.attr(lightboxDIV, 'id', options.lightboxId);
$this.addClass(document.documentElement, 'has-overlay');
var overlayer = $this.getId(id),
lightbox = $this.getId(options.lightboxId);
// Output for lightbox
var lightboxOutput = '<a href="#' + options.lightboxId + '-close" id="' + options.lightboxId + '-close">'+
options.closeText +'</a><div id="' + options.lightboxId + '-inner">';
if (options.header) {
lightboxOutput += '<div class="header"><' + options.headerType + '>' +
options.header + '</' + options.headerType + '></div>';
}
lightboxOutput += '<div class="content">' + options.data + '</div></div>';
lightbox.innerHTML = lightboxOutput;
var lightboxClose = $this.getId(options.lightboxId + '-close');
}
$this.style(overlayer, 'width', windowWidth + 'px');
$this.style(overlayer, 'height', windowHeight + 'px');
function closeOverlay() {
$this.removeClass(document.documentElement, 'has-overlay');
$this.remove(lightbox);
$this.remove(overlayer);
}
// Bind close on overlayer
$this.bind(overlayer, 'click', function () {
closeOverlay();
});
// bind close button click
$this.bind(lightboxClose, 'click', function (e) {
$this.cancelEvent(e);
closeOverlay();
});
// bind resizing
window.onresize = function() {
didResize = true;
};
setInterval(function() {
if (didResize) {
didResize = false;
$this.style($this.getId(options.id), 'width', $this.docWidth() + 'px');
$this.style($this.getId(options.id), 'height', $this.docHeight() + 'px');
}
}, 200);
}
});
}(AWESOME));
diff --git a/plugins/tabs/tabs.js b/plugins/tabs/tabs.js
index 2345470..aad834f 100644
--- a/plugins/tabs/tabs.js
+++ b/plugins/tabs/tabs.js
@@ -1,49 +1,49 @@
(function($) {
$.tabs = (function (options) {
options = $.setDefaults({
obj: null,
open: 1,
tabClass: 'tab',
containerClass: 'tabs'
}, options);
if (!('length' in options.obj)) {
options.obj = [options.obj];
}
var i = options.obj.length;
while(i--) {
var obj = options.obj[i];
// Generate Tabs
var tabHtml = "";
var panes = $.getClass(options.tabClass, obj, 'div').reverse();
var panesLen = tabsLen = panes.length;
while(panesLen--) {
var pane = panes[panesLen];
tabHtml += '<li id="tab-'+ pane.id +'"><a href="#">'+ $.attr(pane, "title") +'</a></li>';
}
- var tabContainer = $.create('ul');
+ var tabContainer = $.create('UL');
tabContainer.innerHTML = tabHtml;
$.addClass(tabContainer, options.containerClass);
$.prepend(tabContainer, obj);
// Add Tab Bindings
var tabs = $.getTag('li', tabContainer);
var toOpen = -options.open + tabsLen;
while(tabsLen--) {
if (tabsLen != toOpen) {
panes[tabsLen].style.display = 'none'; // init hide
}
$.bind(tabs[tabsLen], 'click', function(e) {
$.cancelEvent(e);
panesLen = panes.length; // reset
while(panesLen--) {
panes[panesLen].style.display = 'none';
}
var related = $.getId(this.id.split('tab-')[1]);
related.style.display = "";
});
}
}
});
}(AWESOME));
|
dancrew32/AWESOME-JS | 57914dadc8c5922475616da1090f481dff90df4d | (for prev typo fix) | diff --git a/awesome.js b/awesome.js
index d2b9465..793985d 100644
--- a/awesome.js
+++ b/awesome.js
@@ -92,723 +92,723 @@ var AWESOME = (function () {
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (node !== null) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
if (JSON.parse) {
return JSON.parse(str);
}
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
- t\\': '\\',
+ '\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | dfe6aa2125306355661dd070f4528fc52f6f4976 | use native json parse if exists, fix typo in fallback method | diff --git a/awesome.js b/awesome.js
index f9d3d05..d2b9465 100644
--- a/awesome.js
+++ b/awesome.js
@@ -76,736 +76,739 @@ var AWESOME = (function () {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
isDescendant: function(p, c) {
var node = c.parentNode;
while (node !== null) {
if (node === p) {
return true;
}
node = node.parentNode;
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
+ if (JSON.parse) {
+ return JSON.parse(str);
+ }
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
- '\\': '\\',
+ t\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | da9f21fda5b7c493a57dd216343d2de80cf20859 | optimizations to truncate, dragdrop, added isDecendant test | diff --git a/awesome.js b/awesome.js
index 284f82c..f9d3d05 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,801 +1,811 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
+ isDescendant: function(p, c) {
+ var node = c.parentNode;
+ while (node !== null) {
+ if (node === p) {
+ return true;
+ }
+ node = node.parentNode;
+ }
+ return false;
+ },
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
diff --git a/plugins/dragDrop/dragDrop.js b/plugins/dragDrop/dragDrop.js
index b1ee3a7..c2eaf73 100644
--- a/plugins/dragDrop/dragDrop.js
+++ b/plugins/dragDrop/dragDrop.js
@@ -1,102 +1,103 @@
(function($) {
$.dragDrop = {
keyHTML: '<a href="#" class="keyLink">#</a>',
keySpeed: 10, // pixels per keypress event
initialMouseX: undefined,
initialMouseY: undefined,
startX: undefined,
startY: undefined,
dXKeys: undefined,
dYKeys: undefined,
draggedObject: undefined,
initElement: function (element) {
element.onmousedown = $.dragDrop.startDragMouse;
element.innerHTML += $.dragDrop.keyHTML;
var links = element.getElementsByTagName('a');
var lastLink = links[links.length - 1];
lastLink.relatedElement = element;
lastLink.onclick = $.dragDrop.startDragKeys;
+ $.addClass(element, 'draggable');
},
startDragMouse: function (e) {
$.dragDrop.startDrag(this);
var evt = e || window.event;
$.dragDrop.initialMouseX = evt.clientX;
$.dragDrop.initialMouseY = evt.clientY;
$.bind(document, 'mousemove', $.dragDrop.dragMouse);
$.bind(document, 'mouseup', $.dragDrop.releaseElement);
return false;
},
startDragKeys: function () {
$.dragDrop.startDrag(this.relatedElement);
$.dragDrop.dXKeys = $.dragDrop.dYKeys = 0;
$.bind(document, 'keydown', $.dragDrop.dragKeys);
$.bind(document, 'keypress', $.dragDrop.switchKeyEvents);
this.blur();
return false;
},
startDrag: function (obj) {
if ($.dragDrop.draggedObject)
$.dragDrop.releaseElement();
$.dragDrop.startX = obj.offsetLeft;
$.dragDrop.startY = obj.offsetTop;
$.dragDrop.draggedObject = obj;
obj.className += ' dragged';
},
dragMouse: function (e) {
var evt = e || window.event;
var dX = evt.clientX - $.dragDrop.initialMouseX;
var dY = evt.clientY - $.dragDrop.initialMouseY;
$.dragDrop.setPosition(dX,dY);
return false;
},
dragKeys: function(e) {
var evt = e || window.event;
var key = evt.keyCode;
switch (key) {
case 37: // left
case 63234:
$.dragDrop.dXKeys -= $.dragDrop.keySpeed;
break;
case 38: // up
case 63232:
$.dragDrop.dYKeys -= $.dragDrop.keySpeed;
break;
case 39: // right
case 63235:
$.dragDrop.dXKeys += $.dragDrop.keySpeed;
break;
case 40: // down
case 63233:
$.dragDrop.dYKeys += $.dragDrop.keySpeed;
break;
case 13: // enter
case 27: // escape
$.dragDrop.releaseElement();
return false;
default:
return true;
}
$.dragDrop.setPosition($.dragDrop.dXKeys, $.dragDrop.dYKeys);
$.cancelEvent(evt);
return false;
},
setPosition: function (dx,dy) {
$.dragDrop.draggedObject.style.left = $.dragDrop.startX + dx + 'px';
$.dragDrop.draggedObject.style.top = $.dragDrop.startY + dy + 'px';
},
switchKeyEvents: function () {
$.unbind(document, 'keydown', $.dragDrop.dragKeys);
$.unbind(document, 'keypress', $.dragDrop.switchKeyEvents);
$.bind(document, 'keypress', $.dragDrop.dragKeys);
},
releaseElement: function() {
$.unbind(document, 'mousemove', $.dragDrop.dragMouse);
$.unbind(document, 'mouseup', $.dragDrop.releaseElement);
$.unbind(document, 'keypress', $.dragDrop.dragKeys);
$.unbind(document, 'keypress', $.dragDrop.switchKeyEvents);
$.unbind(document, 'keydown', $.dragDrop.dragKeys);
$.dragDrop.draggedObject.className = $.dragDrop.draggedObject.className.replace(/dragged/,'');
$.dragDrop.draggedObject = null;
}
};
}(AWESOME));
diff --git a/plugins/truncate/truncate.js b/plugins/truncate/truncate.js
index 8e127fe..8250062 100644
--- a/plugins/truncate/truncate.js
+++ b/plugins/truncate/truncate.js
@@ -1,24 +1,23 @@
(function($) {
-$.truncate = (function (options) {
+$.truncate = (function (obj, options) {
options = $.setDefaults({
- obj: null,
length: 80,
moreText: 'Read More »',
elipsis: '...',
className: 'readmore'
}, options);
- if (!('length' in options.obj)) {
- options.obj = [options.obj];
+ if (!('length' in obj)) {
+ obj = [obj];
}
- var i = options.obj.length;
+ var i = obj.length;
while(i--) {
- var trunc = options.obj[i].innerHTML;
+ var trunc = obj[i].innerHTML;
if (trunc.length > options.length) {
trunc = trunc.substring(0, options.length);
trunc = trunc.replace(/\w+$/, "");
trunc += options.elipsis +'<a class="'+ options.className +'" href="#" onclick="this.parentNode.innerHTML=unescape(\''+ escape(obj[i].innerHTML)+'\'); return false;">'+ options.moreText +'<\/a>';
- options.obj[i].innerHTML = trunc;
+ obj[i].innerHTML = trunc;
}
}
});
}(AWESOME));
|
dancrew32/AWESOME-JS | 14596bdefc3b0dfe70f2284ec143f479af5d385c | add dragDrop plugin (still needs work.. basically lets you pick up a node and place it. need drop targetting/snapping etc.. still | diff --git a/plugins/dragDrop/dragDrop.js b/plugins/dragDrop/dragDrop.js
new file mode 100644
index 0000000..b1ee3a7
--- /dev/null
+++ b/plugins/dragDrop/dragDrop.js
@@ -0,0 +1,102 @@
+(function($) {
+ $.dragDrop = {
+ keyHTML: '<a href="#" class="keyLink">#</a>',
+ keySpeed: 10, // pixels per keypress event
+ initialMouseX: undefined,
+ initialMouseY: undefined,
+ startX: undefined,
+ startY: undefined,
+ dXKeys: undefined,
+ dYKeys: undefined,
+ draggedObject: undefined,
+ initElement: function (element) {
+ element.onmousedown = $.dragDrop.startDragMouse;
+ element.innerHTML += $.dragDrop.keyHTML;
+ var links = element.getElementsByTagName('a');
+ var lastLink = links[links.length - 1];
+ lastLink.relatedElement = element;
+ lastLink.onclick = $.dragDrop.startDragKeys;
+ },
+ startDragMouse: function (e) {
+ $.dragDrop.startDrag(this);
+ var evt = e || window.event;
+ $.dragDrop.initialMouseX = evt.clientX;
+ $.dragDrop.initialMouseY = evt.clientY;
+ $.bind(document, 'mousemove', $.dragDrop.dragMouse);
+ $.bind(document, 'mouseup', $.dragDrop.releaseElement);
+ return false;
+ },
+ startDragKeys: function () {
+ $.dragDrop.startDrag(this.relatedElement);
+ $.dragDrop.dXKeys = $.dragDrop.dYKeys = 0;
+ $.bind(document, 'keydown', $.dragDrop.dragKeys);
+ $.bind(document, 'keypress', $.dragDrop.switchKeyEvents);
+ this.blur();
+ return false;
+ },
+ startDrag: function (obj) {
+ if ($.dragDrop.draggedObject)
+ $.dragDrop.releaseElement();
+ $.dragDrop.startX = obj.offsetLeft;
+ $.dragDrop.startY = obj.offsetTop;
+ $.dragDrop.draggedObject = obj;
+ obj.className += ' dragged';
+ },
+ dragMouse: function (e) {
+ var evt = e || window.event;
+ var dX = evt.clientX - $.dragDrop.initialMouseX;
+ var dY = evt.clientY - $.dragDrop.initialMouseY;
+ $.dragDrop.setPosition(dX,dY);
+ return false;
+ },
+ dragKeys: function(e) {
+ var evt = e || window.event;
+ var key = evt.keyCode;
+ switch (key) {
+ case 37: // left
+ case 63234:
+ $.dragDrop.dXKeys -= $.dragDrop.keySpeed;
+ break;
+ case 38: // up
+ case 63232:
+ $.dragDrop.dYKeys -= $.dragDrop.keySpeed;
+ break;
+ case 39: // right
+ case 63235:
+ $.dragDrop.dXKeys += $.dragDrop.keySpeed;
+ break;
+ case 40: // down
+ case 63233:
+ $.dragDrop.dYKeys += $.dragDrop.keySpeed;
+ break;
+ case 13: // enter
+ case 27: // escape
+ $.dragDrop.releaseElement();
+ return false;
+ default:
+ return true;
+ }
+ $.dragDrop.setPosition($.dragDrop.dXKeys, $.dragDrop.dYKeys);
+ $.cancelEvent(evt);
+ return false;
+ },
+ setPosition: function (dx,dy) {
+ $.dragDrop.draggedObject.style.left = $.dragDrop.startX + dx + 'px';
+ $.dragDrop.draggedObject.style.top = $.dragDrop.startY + dy + 'px';
+ },
+ switchKeyEvents: function () {
+ $.unbind(document, 'keydown', $.dragDrop.dragKeys);
+ $.unbind(document, 'keypress', $.dragDrop.switchKeyEvents);
+ $.bind(document, 'keypress', $.dragDrop.dragKeys);
+ },
+ releaseElement: function() {
+ $.unbind(document, 'mousemove', $.dragDrop.dragMouse);
+ $.unbind(document, 'mouseup', $.dragDrop.releaseElement);
+ $.unbind(document, 'keypress', $.dragDrop.dragKeys);
+ $.unbind(document, 'keypress', $.dragDrop.switchKeyEvents);
+ $.unbind(document, 'keydown', $.dragDrop.dragKeys);
+ $.dragDrop.draggedObject.className = $.dragDrop.draggedObject.className.replace(/dragged/,'');
+ $.dragDrop.draggedObject = null;
+ }
+ };
+}(AWESOME));
|
dancrew32/AWESOME-JS | b7b11fc18213c6d36363e30f54871b64d0eef1fc | another failsafe for parse | diff --git a/awesome.js b/awesome.js
index c14d48b..284f82c 100644
--- a/awesome.js
+++ b/awesome.js
@@ -52,749 +52,750 @@ var AWESOME = (function () {
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
inArray: function(obj, arr) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true;
}
}
return false;
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
+ if (str === "") return;
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 93a5b5dc4a8e2cd0381258d2d9c80dcb100ffd43 | simple inArray test method | diff --git a/awesome.js b/awesome.js
index c5daa80..c14d48b 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,791 +1,800 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
stripHTML: function (str) {
return str.replace(/<.*?>/g,'');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
+ inArray: function(obj, arr) {
+ var i = arr.length;
+ while (i--) {
+ if (arr[i] === obj) {
+ return true;
+ }
+ }
+ return false;
+ },
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 1c73f22f26a9bfdddb277c92b8b5390f6df54a05 | added method to strip html tags out of a string | diff --git a/awesome.js b/awesome.js
index d8a2c76..c5daa80 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,765 +1,768 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
+ stripHTML: function (str) {
+ return str.replace(/<.*?>/g,'');
+ },
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
addScript: function(url, id) {
var $this = this;
var script = this.create('script');
script.type = 'text/javascript';
script.src = url || '#';
script.id = id || 'awesome-script'; // id to remove
this.append(script, $this.getTag('head')[0]);
return true;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
|
dancrew32/AWESOME-JS | 66b854af827a5d3ab6154c7df1e96ee7dab55de7 | abstract jsonp's add script to header method into $.addScript(url, id); | diff --git a/awesome.js b/awesome.js
index 5df6b06..d8a2c76 100644
--- a/awesome.js
+++ b/awesome.js
@@ -163,625 +163,626 @@ var AWESOME = (function () {
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
type = type || 'json';
var result;
switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
+ addScript: function(url, id) {
+ var $this = this;
+ var script = this.create('script');
+ script.type = 'text/javascript';
+ script.src = url || '#';
+ script.id = id || 'awesome-script'; // id to remove
+ this.append(script, $this.getTag('head')[0]);
+ return true;
+ },
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
- getJSONP(options.url, options.requestId);
+ this.addScript(options.url, options.requestId || 'awesome-jsonp');
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
- function getJSONP(url, id) {
- var script = $this.create('script');
- script.type = 'text/javascript';
- script.src = url;
- script.id = id || 'awesome-jsonp'; // id to remove
- $this.append(script, $this.getTag('head')[0]);
- }
-
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 7b5cf450dad5f906837fb1e9590e6a38f417b5c6 | $.parse(str) without default type (json) wasn't working. it now does. | diff --git a/awesome.js b/awesome.js
index 01d1028..5df6b06 100644
--- a/awesome.js
+++ b/awesome.js
@@ -40,748 +40,748 @@ var AWESOME = (function () {
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
if (el.filters.length <= 0) {
el.style.filter = 'alpha(opacity = 100)';
}
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
$this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
options.callback();
}
}, 10);
},
fadeIn: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 1,
duration: duration,
callback: callback
});
},
fadeOut: function(el, duration, callback) {
callback = callback || function() {};
this.animate(el, {
property: 'opacity',
to: 0,
duration: duration,
callback: callback
});
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
- type = type.toLowerCase() || 'json';
+ type = type || 'json';
var result;
- switch (type) {
+ switch (type.toLowerCase()) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 27abd9c26352e7f04aa8e7ceb5ec744d873e4deb | updating readme with jquery filesize comparisons modified: README | diff --git a/README b/README
index da959ef..e01525b 100644
--- a/README
+++ b/README
@@ -1,5 +1,11 @@
-Get to docready faster and get stuff done with awesome.js.
+Tired of waiting for jQuery to load?
+Get to docready faster and get the same stuff done with awesome.js!
+(It works in IE6, 7, 8, 9, Firefox, Webkit, Opera too!)
-Closure Compiler Stats:
-Original Size: 16.08KB (5.16KB gzipped)
-Compiled Size: 9.47KB (3.63KB gzipped)
+awesome.js size:
+- Original Size: 17.59KB (5.59KB gzipped)
+- Compiled Size: 10.37KB (3.93KB gzipped)
+
+vs. jQuery size:
+- Development Size: 214KB
+- Compiled Size: 29KB (gzipped)
|
dancrew32/AWESOME-JS | 0824b6e1877f5cd1f35aaec4f31d7ce31994810f | got $.animate() working in ie 6,7,8! also added callbacks and two convenience animation methods: $.fadeIn(el, speed, callback); and $.fadeOut(el, speed, callback); | diff --git a/animationTest.html b/animationTest.html
index b9a0fba..2424af3 100644
--- a/animationTest.html
+++ b/animationTest.html
@@ -1,43 +1,66 @@
<!doctype html>
<html>
<head>
<title>Awesome animation</title>
<style type="text/css">
#foo {
+ background-color:#eee;
border:1px solid #ccc;
margin:0 auto;
/*filter:Alpha(Opacity=20);*/
width:1000px;
height:1000px;
}
</style>
</head>
<body>
<div id="foo">
animate me
</div>
<script type="text/javascript" src="awesome.js"></script>
<script type="text/javascript">
(function($) {
$.ready(function() {
var foo = $.getId('foo');
- $.animate(foo, {
- property: 'width',
- to: '300px',
- duration: 8000
- });
- /*$.animate(foo, {*/
- /*property: 'opacity',*/
- /*to: 0,*/
- /*duration: 8000*/
- /*});*/
- $.animate(foo, {
- property: 'height',
- to: '400px',
- duration: 8000
- });
+
+ $.bind(foo, 'click', doStuff);
+ function doStuff() {
+ $.animate(foo, {
+ property: 'width',
+ to: '300px',
+ duration: 900,
+ callback: function() {
+ foo.innerHTML = 'width is done animating';
+ setTimeout(doHeight, 900);
+ }
+ });
+ function doHeight() {
+ foo.innerHTML = 'now we animate height!';
+ $.animate(foo, {
+ property: 'height',
+ to: '400px',
+ duration: 900,
+ callback: function() {
+ foo.innerHTML = 'done';
+ doOpacity();
+ }
+ });
+ }
+ function doOpacity() {
+ $.animate(foo, {
+ property: 'opacity',
+ to: 0,
+ duration: 4000,
+ callback: function() {
+ $.fadeIn(foo, 200, function(){
+ $.fadeOut(foo);
+ });
+ }
+ });
+ }
+ }
});
}(AWESOME));
</script>
</body>
</html>
diff --git a/awesome.js b/awesome.js
index 9b00182..01d1028 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,765 +1,787 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (typeof el !== 'undefined')
if (typeof prop === 'undefined') {
return el.currentStyle || getComputedStyle(el, null);
} else {
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
+ if (el.filters.length <= 0) {
+ el.style.filter = 'alpha(opacity = 100)';
+ }
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
animate: function (el, options) {
var $this = this;
options = this.setDefaults({
property: 'width',
from: $this.style(el, options.property),
to: '0px',
duration: 200,
easing: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
- }
+ },
+ callback: function() {}
}, options);
var fromNum = parseFloat(options.from);
var fromUnit = getUnit(options.from);
var toNum = parseFloat(options.to);
var toUnit = getUnit(options.to) || fromUnit;
var interval;
var start = +new Date;
var finish = start + options.duration;
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}
function getUnit(prop){
- return prop.replace(/^[\-\d\.]+/,'') || '';
+ return prop.toString().replace(/^[\-\d\.]+/,'') || '';
}
interval = setInterval(function() {
var time = +new Date;
var pos = time > finish ? 1 : (time-start) / options.duration;
- $this.log(options.property);
- $this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit); // wrap pos in easing formula
+ $this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit);
if (time > finish) {
clearInterval(interval);
+ options.callback();
}
}, 10);
},
+ fadeIn: function(el, duration, callback) {
+ callback = callback || function() {};
+ this.animate(el, {
+ property: 'opacity',
+ to: 1,
+ duration: duration,
+ callback: callback
+ });
+ },
+ fadeOut: function(el, duration, callback) {
+ callback = callback || function() {};
+ this.animate(el, {
+ property: 'opacity',
+ to: 0,
+ duration: duration,
+ callback: callback
+ });
+ },
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
type = type.toLowerCase() || 'json';
var result;
switch (type) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 24b5e1f164fcecf7de4fd64b2604e3b24a3e76a3 | adding first attempt at animation method. still a little sketchy with opacity/alpha properties. (ie6/7/8) works good in everything else. | diff --git a/animationTest.html b/animationTest.html
new file mode 100644
index 0000000..b9a0fba
--- /dev/null
+++ b/animationTest.html
@@ -0,0 +1,43 @@
+<!doctype html>
+<html>
+<head>
+<title>Awesome animation</title>
+<style type="text/css">
+#foo {
+ border:1px solid #ccc;
+ margin:0 auto;
+ /*filter:Alpha(Opacity=20);*/
+ width:1000px;
+ height:1000px;
+}
+</style>
+</head>
+<body>
+<div id="foo">
+animate me
+</div>
+<script type="text/javascript" src="awesome.js"></script>
+<script type="text/javascript">
+(function($) {
+ $.ready(function() {
+ var foo = $.getId('foo');
+ $.animate(foo, {
+ property: 'width',
+ to: '300px',
+ duration: 8000
+ });
+ /*$.animate(foo, {*/
+ /*property: 'opacity',*/
+ /*to: 0,*/
+ /*duration: 8000*/
+ /*});*/
+ $.animate(foo, {
+ property: 'height',
+ to: '400px',
+ duration: 8000
+ });
+ });
+}(AWESOME));
+</script>
+</body>
+</html>
diff --git a/awesome.js b/awesome.js
index 0d30048..9b00182 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,721 +1,765 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
- if (el)
- prop = this.toCamelCase(prop);
- newVal = newVal || null;
- if (newVal) {
- if (prop === 'opacity') {
- el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
- el.style.opacity = newVal;
- } else {
- prop = this.toCamelCase(prop);
- el.style[prop] = newVal;
- }
+ if (typeof el !== 'undefined')
+ if (typeof prop === 'undefined') {
+ return el.currentStyle || getComputedStyle(el, null);
} else {
- var view = document.defaultView;
- if (view && view.getComputedStyle) {
- return view.getComputedStyle(el, '')[prop] || null;
- } else {
+ prop = this.toCamelCase(prop);
+ newVal = newVal || null;
+ if (newVal) {
if (prop === 'opacity') {
- var opacity = el.filters('alpha').opacity;
- return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
+ el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
+ el.style.opacity = newVal;
+ } else {
+ prop = this.toCamelCase(prop);
+ el.style[prop] = newVal;
+ }
+ } else {
+ var view = document.defaultView;
+ if (view && view.getComputedStyle) {
+ return view.getComputedStyle(el, '')[prop] || null;
+ } else {
+ if (prop === 'opacity') {
+ var opacity = el.filters('alpha').opacity;
+ return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
+ }
+ return el.currentStyle[prop] || null;
}
- return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
+ animate: function (el, options) {
+ var $this = this;
+ options = this.setDefaults({
+ property: 'width',
+ from: $this.style(el, options.property),
+ to: '0px',
+ duration: 200,
+ easing: function(pos) {
+ return (-Math.cos(pos * Math.PI) / 2) + 0.5;
+ }
+ }, options);
+
+ var fromNum = parseFloat(options.from);
+ var fromUnit = getUnit(options.from);
+
+ var toNum = parseFloat(options.to);
+ var toUnit = getUnit(options.to) || fromUnit;
+
+ var interval;
+ var start = +new Date;
+ var finish = start + options.duration;
+
+ function interpolate(source, target, pos) {
+ return (source + (target - source) * pos).toFixed(3);
+ }
+
+ function getUnit(prop){
+ return prop.replace(/^[\-\d\.]+/,'') || '';
+ }
+
+ interval = setInterval(function() {
+ var time = +new Date;
+ var pos = time > finish ? 1 : (time-start) / options.duration;
+ $this.log(options.property);
+ $this.style(el, options.property, interpolate(fromNum, toNum, options.easing(pos)) + toUnit); // wrap pos in easing formula
+ if (time > finish) {
+ clearInterval(interval);
+ }
+ }, 10);
+ },
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
type = type.toLowerCase() || 'json';
var result;
switch (type) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 370c75db67c70156abf5e78239fcbbfde887552b | can't string concat in regexp literal. | diff --git a/README b/README
index 0d6a7b3..da959ef 100644
--- a/README
+++ b/README
@@ -1,4 +1,5 @@
Get to docready faster and get stuff done with awesome.js.
-Uncompressed: 12.16KB (3.83KB gzipped)
-Minified Size: ~7.39KB (~2.72KB gzipped)
+Closure Compiler Stats:
+Original Size: 16.08KB (5.16KB gzipped)
+Compiled Size: 9.47KB (3.63KB gzipped)
diff --git a/awesome.js b/awesome.js
index 237b4a0..0d30048 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,680 +1,680 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
- var pattern = /('(^|\\s)' + searchClass + '(\\s|$)')/;
+ var pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
parse: function(str, type) {
type = type.toLowerCase() || 'json';
var result;
switch (type) {
case 'xml':
if (window.DOMParser) {
var parser = new DOMParser();
result = parser.parseFromString(str, 'text/xml');
} else { // ie
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
result = xmlDoc.loadXML(str); }
break;
case 'json':
var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var string = '(?:\"' + oneChar + '*\")';
var jsonToken = new RegExp(
'(?:false|true|null|[\\{\\}\\[\\]]'
+ '|' + number
+ '|' + string
+ ')', 'g');
var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
var escapes = {
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
function unescapeOne(_, ch, hex) {
return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
}
var EMPTY_STRING = new String('');
var SLASH = '\\';
var firstTokenCtors = { '{': Object, '[': Array };
var hop = Object.hasOwnProperty;
var toks = str.match(jsonToken);
var tok = toks[0];
var topLevelPrimitive = false;
if ('{' === tok) {
result = {};
} else if ('[' === tok) {
result = [];
} else {
result = [];
topLevelPrimitive = true;
}
var key;
var stack = [result];
for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
tok = toks[i];
var cont;
switch (tok.charCodeAt(0)) {
default: // sign or digit
cont = stack[0];
cont[key || cont.length] = +(tok);
key = void 0;
break;
case 0x22: // '"'
tok = tok.substring(1, tok.length - 1);
if (tok.indexOf(SLASH) !== -1) {
tok = tok.replace(escapeSequence, unescapeOne);
}
cont = stack[0];
if (!key) {
if (cont instanceof Array) {
key = cont.length;
} else {
key = tok || EMPTY_STRING; // Use as key for next value seen.
break;
}
}
cont[key] = tok;
key = void 0;
break;
case 0x5b: // '['
cont = stack[0];
stack.unshift(cont[key || cont.length] = []);
key = void 0;
break;
case 0x5d: // ']'
stack.shift();
break;
case 0x66: // 'f'
cont = stack[0];
cont[key || cont.length] = false;
key = void 0;
break;
case 0x6e: // 'n'
cont = stack[0];
cont[key || cont.length] = null;
key = void 0;
break;
case 0x74: // 't'
cont = stack[0];
cont[key || cont.length] = true;
key = void 0;
break;
case 0x7b: // '{'
cont = stack[0];
stack.unshift(cont[key || cont.length] = {});
key = void 0;
break;
case 0x7d: // '}'
stack.shift();
break;
}
}
if (topLevelPrimitive) {
if (stack.length !== 1) { throw new Error(); }
result = result[0];
} else {
if (stack.length) { throw new Error(); }
}
break;
}
return result;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
|
dancrew32/AWESOME-JS | c8a4c5dfaecdf02130e1d3544011c3de301f44a7 | adding lightweight xml and json parsers var obj = $.parse(str, type); where type is 'xml' or 'json' (default) | diff --git a/awesome.js b/awesome.js
index 5bbfb5b..237b4a0 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,597 +1,721 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = /('(^|\\s)' + searchClass + '(\\s|$)')/;
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
- ele = [ele];
- }
+ ele = [ele];
+ }
var i = ele.length;
while (i--) {
if (typeof ele[i].parentNode !== 'undefined') {
ele[i].parentNode.removeChild(ele[i]);
}
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
- return m.max.apply(m, array);
+ return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
- return m.min.apply(m, array);
+ return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
+ parse: function(str, type) {
+ type = type.toLowerCase() || 'json';
+ var result;
+ switch (type) {
+ case 'xml':
+ if (window.DOMParser) {
+ var parser = new DOMParser();
+ result = parser.parseFromString(str, 'text/xml');
+ } else { // ie
+ var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
+ xmlDoc.async = 'false';
+ result = xmlDoc.loadXML(str); }
+ break;
+ case 'json':
+ var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
+ var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
+ + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
+ var string = '(?:\"' + oneChar + '*\")';
+ var jsonToken = new RegExp(
+ '(?:false|true|null|[\\{\\}\\[\\]]'
+ + '|' + number
+ + '|' + string
+ + ')', 'g');
+ var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
+ var escapes = {
+ '"': '"',
+ '/': '/',
+ '\\': '\\',
+ 'b': '\b',
+ 'f': '\f',
+ 'n': '\n',
+ 'r': '\r',
+ 't': '\t'
+ };
+ function unescapeOne(_, ch, hex) {
+ return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
+ }
+ var EMPTY_STRING = new String('');
+ var SLASH = '\\';
+ var firstTokenCtors = { '{': Object, '[': Array };
+ var hop = Object.hasOwnProperty;
+
+ var toks = str.match(jsonToken);
+ var tok = toks[0];
+ var topLevelPrimitive = false;
+ if ('{' === tok) {
+ result = {};
+ } else if ('[' === tok) {
+ result = [];
+ } else {
+ result = [];
+ topLevelPrimitive = true;
+ }
+ var key;
+ var stack = [result];
+ for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
+ tok = toks[i];
+ var cont;
+ switch (tok.charCodeAt(0)) {
+ default: // sign or digit
+ cont = stack[0];
+ cont[key || cont.length] = +(tok);
+ key = void 0;
+ break;
+ case 0x22: // '"'
+ tok = tok.substring(1, tok.length - 1);
+ if (tok.indexOf(SLASH) !== -1) {
+ tok = tok.replace(escapeSequence, unescapeOne);
+ }
+ cont = stack[0];
+ if (!key) {
+ if (cont instanceof Array) {
+ key = cont.length;
+ } else {
+ key = tok || EMPTY_STRING; // Use as key for next value seen.
+ break;
+ }
+ }
+ cont[key] = tok;
+ key = void 0;
+ break;
+ case 0x5b: // '['
+ cont = stack[0];
+ stack.unshift(cont[key || cont.length] = []);
+ key = void 0;
+ break;
+ case 0x5d: // ']'
+ stack.shift();
+ break;
+ case 0x66: // 'f'
+ cont = stack[0];
+ cont[key || cont.length] = false;
+ key = void 0;
+ break;
+ case 0x6e: // 'n'
+ cont = stack[0];
+ cont[key || cont.length] = null;
+ key = void 0;
+ break;
+ case 0x74: // 't'
+ cont = stack[0];
+ cont[key || cont.length] = true;
+ key = void 0;
+ break;
+ case 0x7b: // '{'
+ cont = stack[0];
+ stack.unshift(cont[key || cont.length] = {});
+ key = void 0;
+ break;
+ case 0x7d: // '}'
+ stack.shift();
+ break;
+ }
+ }
+ if (topLevelPrimitive) {
+ if (stack.length !== 1) { throw new Error(); }
+ result = result[0];
+ } else {
+ if (stack.length) { throw new Error(); }
+ }
+ break;
+ }
+ return result;
+ },
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | be5cf5945dc650ca54e539b8179d93d61acc1ec8 | removed submit method that was rediculous. modified: awesome.js | diff --git a/awesome.js b/awesome.js
index 0086cdc..5bbfb5b 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,603 +1,597 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
- submit: function(form) {
- if (typeof form !== 'undefined') {
- form.submit();
- return false;
- }
- },
hover: function (obj, over, out, delegate) {
if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] === obj){
return i;
}
}
return -1;
}
}
if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = /('(^|\\s)' + searchClass + '(\\s|$)')/;
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length === 1) return oStringList[0];
var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop === 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
- for (var i = 0, len = ele.length; i < len; ++i) {
- if (!ele[i].parentNode) {
- return false;
+ var i = ele.length;
+ while (i--) {
+ if (typeof ele[i].parentNode !== 'undefined') {
+ ele[i].parentNode.removeChild(ele[i]);
}
- ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
- serialize: function (obj) {
+ serialize: function(obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | febf3309b735186dba3784ddd0d819b21d3edc75 | search and replace fail. now everything has strict equals | diff --git a/awesome.js b/awesome.js
index 82376a0..0086cdc 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,603 +1,603 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
- if (typeof obj == 'undefined' || obj == null) {return;}
+ if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
- if (typeof obj.length == 'undefined') {
+ if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
- if (typeof obj == 'undefined' || obj == null) {return;}
+ if (typeof obj === 'undefined' || obj === null) {return;}
delegate = delegate || false;
- if (typeof obj.length == 'undefined') {
+ if (typeof obj.length === 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form !== 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
- if (typeof obj == 'undefined') {return;}
+ if (typeof obj === 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
- if (this[i] == obj){
+ if (this[i] === obj){
return i;
}
}
return -1;
}
}
- if (typeof re == 'undefined') { return false; }
+ if (typeof re === 'undefined') { return false; }
return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
- if (typeof re == 'undefined') { return; }
+ if (typeof re === 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = /('(^|\\s)' + searchClass + '(\\s|$)')/;
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
- if (oStringList.length == 1) return oStringList[0];
+ if (oStringList.length === 1) return oStringList[0];
- var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
+ var ccstr = string.indexOf('-') === 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
- if (prop == 'opacity') {
+ if (prop === 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
- if (prop == 'opacity') {
+ if (prop === 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj !== 'undefined') {
if (txt) {
if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
-}());
\ No newline at end of file
+}());
|
dancrew32/AWESOME-JS | 9fe75e074a073a4009bf1c6220ff4b5d71a7874a | strict equals is faster than non-strict. http://www.timmywillison.com/pres/operators/#strict-equals | diff --git a/awesome.js b/awesome.js
old mode 100755
new mode 100644
index 98547ed..82376a0
--- a/awesome.js
+++ b/awesome.js
@@ -1,603 +1,603 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
- if (e && e.type == 'DOMContentLoaded') {
+ if (e && e.type === 'DOMContentLoaded') {
fireDOMReady();
// Legacy
- } else if (e && e.type == 'load') {
+ } else if (e && e.type === 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
- if (typeof form != 'undefined') {
+ if (typeof form !== 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] == obj){
return i;
}
}
return -1;
}
}
if (typeof re == 'undefined') { return false; }
- return -1 != re.indexOf(cls);
+ return -1 !== re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re == 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = /('(^|\\s)' + searchClass + '(\\s|$)')/;
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
- if (typeof obj != 'undefined') {
+ if (typeof obj !== 'undefined') {
if (txt) {
- if (obj.innerText != 'undefined') {
+ if (obj.innerText !== 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
- return count == 1 ? singular : plural;
+ return count === 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
- if (c_start != -1) {
+ if (c_start !== -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
- if (c_end == -1) {
+ if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
- if (options.order == 'asc') {
+ if (options.order === 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
- if (options.order == 'asc') {
+ if (options.order === 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
- if (typeof returnObject[currentNode.name] == 'string') {
+ if (typeof returnObject[currentNode.name] === 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
- if (obj == null) {return '';}
+ if (obj === null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
- if (typeof options[index] == 'undefined') {
+ if (typeof options[index] === 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
- if (req == null) {return;}
+ if (req === null) {return;}
var d = new Date();
req.open(method, url, true);
- if (method == 'POST') {
+ if (method === 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
- } else if (req.status == 0) { // file:/// ajax
+ } else if (req.status === 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
- if (typeof(XMLHttpRequest) != 'undefined')
+ if (typeof(XMLHttpRequest) !== 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
-}());
+}());
\ No newline at end of file
|
dancrew32/AWESOME-JS | 5f5ef558c18c95299beb600e3d4d0064a7ad2d44 | was accidently using event keyword in fire/trigger method. I should also probably rename fire to trigger or something | diff --git a/awesome.js b/awesome.js
index c53b31c..98547ed 100755
--- a/awesome.js
+++ b/awesome.js
@@ -1,603 +1,603 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
- fire: function(obj, event, delegate, cancelable) {
+ fire: function(obj, ev, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
- return obj.fireEvent('on'+ event, evt);
+ return obj.fireEvent('on'+ ev, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
- evt.initEvent(event, delegate, cancelable);
+ evt.initEvent(ev, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(" ");
if (!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i = 0; i < this.length; i++) {
if (this[i] == obj){
return i;
}
}
return -1;
}
}
if (typeof re == 'undefined') { return false; }
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re == 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [];
var els = this.getTag(tag, context);
var elsLen = els.length;
var pattern = /('(^|\\s)' + searchClass + '(\\s|$)')/;
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count == 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order == 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order == 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | bcc411841cb50487bfd50135c94488cb8f149000 | using indexOf in lteIE7 fails, so if it doesn't exist, fix it | diff --git a/awesome.js b/awesome.js
old mode 100644
new mode 100755
index 7c82887..bcd4416
--- a/awesome.js
+++ b/awesome.js
@@ -1,593 +1,603 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
- var re = el.className.split(' ');
+ var re = el.className.split(" ");
+ if (!Array.indexOf) {
+ Array.prototype.indexOf = function(obj) {
+ for(var i = 0; i < this.length; i++) {
+ if (this[i] == obj){
+ return i;
+ }
+ }
+ return -1;
+ }
+ }
if (typeof re == 'undefined') { return false; }
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re == 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
plural: function(count, singular, plural) {
return count == 1 ? singular : plural;
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order == 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order == 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | cbfa6c2bf78b5f4c441609c85437e81611fd713c | adding $.plural() to deal with singular/plural output. | diff --git a/awesome.js b/awesome.js
index b45b4b2..7c82887 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,590 +1,593 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (typeof re == 'undefined') { return false; }
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re == 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
+ plural: function(count, singular, plural) {
+ return count == 1 ? singular : plural;
+ },
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order == 'asc') {
if (A < B) { return -1; }
else if (A > B) { return 1; }
else { return 0; }
} else {
if (A > B) { return -1; }
else if (A < B) { return 1; }
else { return 0; }
}
};
break;
case 'numerical':
if (options.order == 'asc') {
method = function(a, b) { return a - b; };
} else {
method = function(a, b) { return b - a; };
}
break;
case 'random':
method = function() {
return Math.round(Math.random()) - 0.5;
};
break;
}
return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
diff --git a/plugins/characterLimit/characterLimit.js b/plugins/characterLimit/characterLimit.js
index 095a6fb..5e0f08c 100644
--- a/plugins/characterLimit/characterLimit.js
+++ b/plugins/characterLimit/characterLimit.js
@@ -1,88 +1,88 @@
(function($) {
$.characterLimit = (function (options) {
options = $.setDefaults({
obj: null,
limit: 140,
limitOffset: 0,
truncate: true,
prefixSingular: '',
prefixPlural: '',
suffixSingular: 'character remaining',
suffixPlural: 'characters remaining',
warning: 10,
warningClass: 'warning',
exceeded: 0,
exceededClass: 'exceeded',
position: 'after'
}, options);
if (!('length' in options.obj)) {
options.obj = [options.obj];
}
var i = options.obj.length;
while(i--) {
var obj = options.obj[i];
var counter = $.create('div');
counter.className = 'counter';
var hasPrefix = false;
var hasSuffix = false;
counter.innerHTML = "";
if (options.prefixSingular != "" || options.prefixPlural != "") {
hasPrefix = true;
counter.innerHTML += '<span class="prefix"></span> ';
}
counter.innerHTML += '<span class="number"></span>';
if (options.suffixSingular != "" || options.suffixPlural != "") {
hasSuffix = true;
counter.innerHTML += ' <span class="suffix"></span>';
}
if (options.position == 'after') {
$.after(counter, obj);
} else {
$.before(counter, obj);
}
var num = $.getClass('number', counter, 'span')[0];
var initCount = getCount(obj.value.length);
num.innerHTML = initCount;
if (hasPrefix) {
var prefix = $.getClass('prefix', counter, 'span')[0];
- prefix.innerHTML = initCount == 1 ? options.prefixSingular : options.prefixPlural;
+ prefix.innerHTML = $.plural(initCount, options.prefixSingular, options.prefixPlural);
}
if (hasSuffix) {
var suffix = $.getClass('suffix', counter, 'span')[0];
- suffix.innerHTML = initCount == 1 ? options.suffixSingular : options.suffixPlural;
+ suffix.innerHTML = $.plural(initCount, options.suffixSingular, options.suffixPlural);
}
$.bind(obj, 'keyup', function(e) {
var count = getCount(this.value.length);
if (count <= 0 && options.truncate) {
this.value = this.value.substring(0, options.limit + options.limitOffset);
}
num.innerHTML = count;
addLabels(counter, count);
if (hasPrefix) {
- prefix.innerHTML = count == 1 ? options.prefixSingular : options.prefixPlural;
+ prefix.innerHTML = $.plural(count, options.prefixSingular, options.prefixPlural);
}
if (hasSuffix) {
- suffix.innerHTML = count == 1 ? options.suffixSingular : options.suffixPlural;
+ suffix.innerHTML = $.plural(count, options.suffixSingular, options.suffixPlural);
}
});
}
function getCount(len) {
return options.limit - len;
}
function addLabels(label, count) {
if (count <= options.warning) {
$.addClass(label, options.warningClass);
} else {
$.removeClass(label, options.warningClass);
}
if (count <= options.exceeded) {
$.addClass(label, options.exceededClass);
} else {
$.removeClass(label, options.exceededClass);
}
}
});
}(AWESOME));
|
dancrew32/AWESOME-JS | 83f5c8c8a8720252b1646818ecadf98ea3436127 | fixing array sort methods | diff --git a/awesome.js b/awesome.js
old mode 100755
new mode 100644
index f61c2e5..b45b4b2
--- a/awesome.js
+++ b/awesome.js
@@ -1,596 +1,590 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (typeof re == 'undefined') { return false; }
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re == 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
sort: function(options) {
options = this.setDefaults({
- array: [],
+ arr: [],
type: 'alphabetical',
order: 'desc',
property: null,
method: null
}, options);
var $this = this;
var method;
switch(options.type) {
case 'alphabetical':
method = function(a, b) {
var A = a.toLowerCase();
var B = b.toLowerCase();
if (options.order == 'asc') {
- if (A < B) {
- return -1;
- } else if (A > B) {
- return 1;
- } else {
- return 0;
- }
+ if (A < B) { return -1; }
+ else if (A > B) { return 1; }
+ else { return 0; }
} else {
- if (A > B) {
- return -1;
- } else if (A < B) {
- return 1;
- } else {
- return 0;
- }
+ if (A > B) { return -1; }
+ else if (A < B) { return 1; }
+ else { return 0; }
}
};
break;
case 'numerical':
- var asc = function(a, b) { return a - b; };
- var desc = function(a, b) { return b - a; };
- method = options.order == 'asc' ? asc() : desc();
+ if (options.order == 'asc') {
+ method = function(a, b) { return a - b; };
+ } else {
+ method = function(a, b) { return b - a; };
+ }
break;
case 'random':
method = function() {
- $this.getRandom() - 0.5;
+ return Math.round(Math.random()) - 0.5;
};
break;
}
- return array.sort(method);
+ return options.arr.sort(method);
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | a60732e4ce37989a200da63b6e49cbc6c4ee7279 | classy sort methods through $.sort({... | diff --git a/awesome.js b/awesome.js
old mode 100644
new mode 100755
index b5e86e7..f61c2e5
--- a/awesome.js
+++ b/awesome.js
@@ -1,548 +1,596 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
if (typeof re == 'undefined') { return false; }
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
if (typeof re == 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
+ sort: function(options) {
+ options = this.setDefaults({
+ array: [],
+ type: 'alphabetical',
+ order: 'desc',
+ property: null,
+ method: null
+ }, options);
+
+ var $this = this;
+ var method;
+ switch(options.type) {
+ case 'alphabetical':
+ method = function(a, b) {
+ var A = a.toLowerCase();
+ var B = b.toLowerCase();
+ if (options.order == 'asc') {
+ if (A < B) {
+ return -1;
+ } else if (A > B) {
+ return 1;
+ } else {
+ return 0;
+ }
+ } else {
+ if (A > B) {
+ return -1;
+ } else if (A < B) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+ };
+ break;
+ case 'numerical':
+ var asc = function(a, b) { return a - b; };
+ var desc = function(a, b) { return b - a; };
+ method = options.order == 'asc' ? asc() : desc();
+ break;
+ case 'random':
+ method = function() {
+ $this.getRandom() - 0.5;
+ };
+ break;
+ }
+ return array.sort(method);
+ },
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 6889bce66a70a5956e4fb00b9549aeb23ad1d07e | adding characterLimit plugin (twitter style) | diff --git a/plugins/characterLimit/characterLimit.js b/plugins/characterLimit/characterLimit.js
index 842011f..095a6fb 100644
--- a/plugins/characterLimit/characterLimit.js
+++ b/plugins/characterLimit/characterLimit.js
@@ -1,43 +1,88 @@
(function($) {
$.characterLimit = (function (options) {
options = $.setDefaults({
obj: null,
limit: 140,
+ limitOffset: 0,
+ truncate: true,
+ prefixSingular: '',
+ prefixPlural: '',
+ suffixSingular: 'character remaining',
+ suffixPlural: 'characters remaining',
warning: 10,
warningClass: 'warning',
+ exceeded: 0,
+ exceededClass: 'exceeded',
position: 'after'
}, options);
if (!('length' in options.obj)) {
options.obj = [options.obj];
}
var i = options.obj.length;
while(i--) {
var obj = options.obj[i];
var counter = $.create('div');
counter.className = 'counter';
- counter.innerHTML = '<span class="number"></span>';
+ var hasPrefix = false;
+ var hasSuffix = false;
+ counter.innerHTML = "";
+ if (options.prefixSingular != "" || options.prefixPlural != "") {
+ hasPrefix = true;
+ counter.innerHTML += '<span class="prefix"></span> ';
+ }
+ counter.innerHTML += '<span class="number"></span>';
+ if (options.suffixSingular != "" || options.suffixPlural != "") {
+ hasSuffix = true;
+ counter.innerHTML += ' <span class="suffix"></span>';
+ }
if (options.position == 'after') {
$.after(counter, obj);
} else {
$.before(counter, obj);
}
var num = $.getClass('number', counter, 'span')[0];
- num.innerHTML = getCount(obj.textLength);
+ var initCount = getCount(obj.value.length);
+ num.innerHTML = initCount;
+ if (hasPrefix) {
+ var prefix = $.getClass('prefix', counter, 'span')[0];
+ prefix.innerHTML = initCount == 1 ? options.prefixSingular : options.prefixPlural;
+ }
+ if (hasSuffix) {
+ var suffix = $.getClass('suffix', counter, 'span')[0];
+ suffix.innerHTML = initCount == 1 ? options.suffixSingular : options.suffixPlural;
+ }
$.bind(obj, 'keyup', function(e) {
- var count = getCount(this.textLength);
- if (count <= 0) {
- //this.value = this.value.substr(-1);
- //todo: find how to cut back 1 character:wq
-
+ var count = getCount(this.value.length);
+ if (count <= 0 && options.truncate) {
+ this.value = this.value.substring(0, options.limit + options.limitOffset);
}
num.innerHTML = count;
+ addLabels(counter, count);
+ if (hasPrefix) {
+ prefix.innerHTML = count == 1 ? options.prefixSingular : options.prefixPlural;
+ }
+ if (hasSuffix) {
+ suffix.innerHTML = count == 1 ? options.suffixSingular : options.suffixPlural;
+ }
});
}
function getCount(len) {
return options.limit - len;
}
+ function addLabels(label, count) {
+ if (count <= options.warning) {
+ $.addClass(label, options.warningClass);
+ } else {
+ $.removeClass(label, options.warningClass);
+ }
+ if (count <= options.exceeded) {
+ $.addClass(label, options.exceededClass);
+ } else {
+ $.removeClass(label, options.exceededClass);
+ }
+ }
});
}(AWESOME));
|
dancrew32/AWESOME-JS | 0b07dd7e9ad57d6e6ffd014d92d792cbc8f75434 | hasClass/removeClass needed better undefined checks. | diff --git a/awesome.js b/awesome.js
old mode 100755
new mode 100644
index 5c91a64..b5e86e7
--- a/awesome.js
+++ b/awesome.js
@@ -1,546 +1,548 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
- return -1 != re.indexOf(cls);
+ if (typeof re == 'undefined') { return false; }
+ return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
+ if (typeof re == 'undefined') { return; }
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
diff --git a/plugins/characterLimit/characterLimit.js b/plugins/characterLimit/characterLimit.js
new file mode 100644
index 0000000..842011f
--- /dev/null
+++ b/plugins/characterLimit/characterLimit.js
@@ -0,0 +1,43 @@
+(function($) {
+$.characterLimit = (function (options) {
+ options = $.setDefaults({
+ obj: null,
+ limit: 140,
+ warning: 10,
+ warningClass: 'warning',
+ position: 'after'
+ }, options);
+
+ if (!('length' in options.obj)) {
+ options.obj = [options.obj];
+ }
+ var i = options.obj.length;
+ while(i--) {
+ var obj = options.obj[i];
+
+ var counter = $.create('div');
+ counter.className = 'counter';
+ counter.innerHTML = '<span class="number"></span>';
+ if (options.position == 'after') {
+ $.after(counter, obj);
+ } else {
+ $.before(counter, obj);
+ }
+ var num = $.getClass('number', counter, 'span')[0];
+ num.innerHTML = getCount(obj.textLength);
+
+ $.bind(obj, 'keyup', function(e) {
+ var count = getCount(this.textLength);
+ if (count <= 0) {
+ //this.value = this.value.substr(-1);
+ //todo: find how to cut back 1 character:wq
+
+ }
+ num.innerHTML = count;
+ });
+ }
+ function getCount(len) {
+ return options.limit - len;
+ }
+});
+}(AWESOME));
|
dancrew32/AWESOME-JS | ce0af3c049b40d9d0f1a2e2a23b2e332c9fce78a | tabs plugin (create a container, nested containers with 'tab' class and title class (what you want the tab to say), and presto.. tabs. | diff --git a/awesome.js b/awesome.js
old mode 100644
new mode 100755
index 6221dd0..5c91a64
--- a/awesome.js
+++ b/awesome.js
@@ -1,546 +1,546 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
- greatest: function (array) {
+ getMax: function (array) {
var m = Math;
return m.max.apply(m, array);
},
- smallest: function (array) {
+ getMin: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
diff --git a/plugins/tabs/tabs.css b/plugins/tabs/tabs.css
new file mode 100644
index 0000000..0df2be2
--- /dev/null
+++ b/plugins/tabs/tabs.css
@@ -0,0 +1,27 @@
+.tabs {
+ display:block;
+ zoom:1;
+}
+.tabs:after {
+ visibility:hidden;
+ display:block;
+ font-size:0;
+ content: " ";
+ clear:both;
+ height:0;
+}
+.tabs li {
+ display:inline;
+ float:left;
+ list-style:none;
+}
+.tabs a {
+ border:1px solid #ccc;
+ display:block;
+ float:left;
+ padding:3px 5px;
+}
+
+.tab {
+ border:1px solid #ccc;
+}
diff --git a/plugins/tabs/tabs.js b/plugins/tabs/tabs.js
new file mode 100644
index 0000000..2345470
--- /dev/null
+++ b/plugins/tabs/tabs.js
@@ -0,0 +1,49 @@
+(function($) {
+$.tabs = (function (options) {
+ options = $.setDefaults({
+ obj: null,
+ open: 1,
+ tabClass: 'tab',
+ containerClass: 'tabs'
+ }, options);
+
+ if (!('length' in options.obj)) {
+ options.obj = [options.obj];
+ }
+ var i = options.obj.length;
+ while(i--) {
+ var obj = options.obj[i];
+
+ // Generate Tabs
+ var tabHtml = "";
+ var panes = $.getClass(options.tabClass, obj, 'div').reverse();
+ var panesLen = tabsLen = panes.length;
+ while(panesLen--) {
+ var pane = panes[panesLen];
+ tabHtml += '<li id="tab-'+ pane.id +'"><a href="#">'+ $.attr(pane, "title") +'</a></li>';
+ }
+ var tabContainer = $.create('ul');
+ tabContainer.innerHTML = tabHtml;
+ $.addClass(tabContainer, options.containerClass);
+ $.prepend(tabContainer, obj);
+
+ // Add Tab Bindings
+ var tabs = $.getTag('li', tabContainer);
+ var toOpen = -options.open + tabsLen;
+ while(tabsLen--) {
+ if (tabsLen != toOpen) {
+ panes[tabsLen].style.display = 'none'; // init hide
+ }
+ $.bind(tabs[tabsLen], 'click', function(e) {
+ $.cancelEvent(e);
+ panesLen = panes.length; // reset
+ while(panesLen--) {
+ panes[panesLen].style.display = 'none';
+ }
+ var related = $.getId(this.id.split('tab-')[1]);
+ related.style.display = "";
+ });
+ }
+ }
+});
+}(AWESOME));
|
dancrew32/AWESOME-JS | 216d03fd5e9e1f77456ae808477b20f683835f94 | $ -> $this fix for jsonp modified: awesome.js | diff --git a/awesome.js b/awesome.js
index c0e42a1..6221dd0 100644
--- a/awesome.js
+++ b/awesome.js
@@ -8,539 +8,539 @@ var AWESOME = (function () {
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
greatest: function (array) {
var m = Math;
return m.max.apply(m, array);
},
smallest: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
- var script = $.create('script');
+ var script = $this.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
- $this.append(script, $.getTag('head')[0]);
+ $this.append(script, $this.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 151579c9984dc7edf1145314f00570444f23f2be | typo fix for jsonp modified: awesome.js | diff --git a/awesome.js b/awesome.js
index cfee52c..c0e42a1 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,546 +1,546 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
greatest: function (array) {
var m = Math;
return m.max.apply(m, array);
},
smallest: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
disguise: false,
requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
- case: 'JSONP':
+ case 'JSONP':
getJSONP(options.url, options.requestId);
break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
function getJSONP(url, id) {
var script = $.create('script');
script.type = 'text/javascript';
script.src = url;
script.id = id || 'awesome-jsonp'; // id to remove
$this.append(script, $.getTag('head')[0]);
}
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 61aca98e547356b034a4cd7b8f7aae78b02660b7 | added a jsonp method.. User will need to remove the script on successful load in their global method. | diff --git a/awesome.js b/awesome.js
index 8af0630..cfee52c 100644
--- a/awesome.js
+++ b/awesome.js
@@ -1,535 +1,546 @@
// Awesome ensues
var AWESOME = (function () {
return {
ready: function (fn, ctx) {
var ready, timer,
onStateChange = function (e) {
// Mozilla & Opera
if (e && e.type == 'DOMContentLoaded') {
fireDOMReady();
// Legacy
} else if (e && e.type == 'load') {
fireDOMReady();
// Safari & IE
} else if (document.readyState) {
if ((/loaded|complete/).test(document.readyState)) {
fireDOMReady();
// IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if ( !! document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch (ex) {
return;
}
fireDOMReady();
}
}
};
var fireDOMReady = function () {
if (!ready) {
ready = true;
// Call the onload function in given context or window object
fn.call(ctx || window);
// Clean up after the DOM is ready
if (document.removeEventListener)
document.removeEventListener('DOMContentLoaded', onStateChange, false);
document.onreadystatechange = null;
window.onload = null;
clearInterval(timer);
timer = null;
}
};
// Mozilla & Opera
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', onStateChange, false);
// IE
document.onreadystatechange = onStateChange;
// Safari & IE
timer = setInterval(onStateChange, 5);
// Legacy
window.onload = onStateChange;
},
log: function (data) {
if (typeof console !== 'undefined') {
console.log(data);
}
},
cancelEvent: function (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
cancelPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
bind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].addEventListener) {
obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
} else if (obj.attachEvent) {
obj[i].attachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = handler;
}
}
},
unbind: function (obj, type, handler, delegate) {
if (typeof obj == 'undefined' || obj == null) {return;}
delegate = delegate || false;
if (typeof obj.length == 'undefined') {
obj = [obj];
}
var i = obj.length;
while (i--) {
if (obj[i].removeEventListener) {
obj[i].removeEventListener(type, handler, delegate);
} else if (obj[i].detachEvent) {
obj[i].detachEvent('on' + type, handler);
} else {
obj[i]['on' + type] = null;
}
}
},
fire: function(obj, event, delegate, cancelable) {
var evt;
if (document.createEventObject) { // ie
evt = document.createEventObject();
return obj.fireEvent('on'+ event, evt);
}
delegate = delegate || false;
cancelable = cancelable || true;
evt = document.createEvent('HTMLEvents');
evt.initEvent(event, delegate, cancelable);
return !obj.dispatchEvent(evt);
},
submit: function(form) {
if (typeof form != 'undefined') {
form.submit();
return false;
}
},
hover: function (obj, over, out, delegate) {
if (typeof obj == 'undefined') {return;}
var $this = this;
out = out || null;
$this.bind(obj, 'mouseover', over, delegate);
if (out)
$this.bind(obj, 'mouseout', out, delegate);
},
hasClass: function (el, cls) {
var re = el.className.split(' ');
return -1 != re.indexOf(cls);
},
addClass: function (el, cls) {
if (!this.hasClass(el, cls))
el.className += ' ' + cls;
},
removeClass: function (el, cls) {
if (this.hasClass(el, cls))
var re = el.className.split(' ');
re.splice(re.indexOf(cls), 1);
var i = re.length;
el.className = ''; // empty
while(i--) { // reload
el.className += re[i] + ' ';
}
},
getId: function (id) {
return document.getElementById(id);
},
getTag: function (tag, context) {
context = context || document;
tag = tag || '*';
return context.getElementsByTagName(tag);
},
getClass: function (searchClass, context, tag) {
var classElements = [],
els = this.getTag(tag, context),
elsLen = els.length,
pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
for (var i = 0, j = 0; i < elsLen; ++i) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},
toCamelCase: function (string) {
var oStringList = string.split('-');
if (oStringList.length == 1) return oStringList[0];
var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
for (var i = 1, len = oStringList.length; i < len; ++i) {
var s = oStringList[i];
ccstr += s.charAt(0).toUpperCase() + s.substring(1);
}
return ccstr;
},
style: function (el, prop, newVal) {
if (el)
prop = this.toCamelCase(prop);
newVal = newVal || null;
if (newVal) {
if (prop == 'opacity') {
el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
el.style.opacity = newVal;
} else {
prop = this.toCamelCase(prop);
el.style[prop] = newVal;
}
} else {
var view = document.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop] || null;
} else {
if (prop == 'opacity') {
var opacity = el.filters('alpha').opacity;
return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
}
return el.currentStyle[prop] || null;
}
}
},
docHeight: function () {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
},
docWidth: function () {
var D = document;
return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
},
attr: function (ele, attr, newVal) {
newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrsLen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
while (attrsLen--) {
if (attr[attrsLen].nodeName === attr)
result = attr[i].nodeValue;
}
}
return result;
}
},
encodeHTML: function (str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
},
text: function (obj, txt) {
if (typeof obj != 'undefined') {
if (txt) {
if (obj.innerText != 'undefined') {
obj.innerText = txt;
}
obj.textContent = txt;
} else {
return obj.innerText || obj.textContent;
}
}
},
trim: function (str) {
return str.replace(/^\s+|\s+$/g);
},
prepend: function (newNode, node) {
node.insertBefore(newNode, node.childNodes[0]);
},
append: function (newNode, node) {
node.appendChild(newNode)
},
before: function (newNode, node) {
node.parentNode.insertBefore(newNode, node);
},
after: function (newNode, node) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
swap: function (a, b) {
a.parentNode.replaceChild(b, a);
},
remove: function (ele) {
if (!ele) return false;
if (!('length' in ele)) {
ele = [ele];
}
for (var i = 0, len = ele.length; i < len; ++i) {
if (!ele[i].parentNode) {
return false;
}
ele[i].parentNode.removeChild(ele[i]);
}
},
create: function (tag) {
// TODO: add a name attribute try/catch to solve <= ie7 submitName issue
return document.createElement(tag);
},
// Cookies
createCookie: function (name, value, days, domain) {
var expires = '';
domain = domain || window.location.host;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
// document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
document.cookie = name + '=' + value + expires + ';';
},
eraseCookie: function (name) {
this.createCookie(name, '', -1);
},
readCookie: function (c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return null;
},
// Math
greatest: function (array) {
var m = Math;
return m.max.apply(m, array);
},
smallest: function (array) {
var m = Math;
return m.min.apply(m, array);
},
getRandom: function(min, max) {
var m = Math;
if (min) {
return m.floor(m.random() * (max - min + 1)) + min;
} else {
return m.round(m.random()); // 1 or 0
}
},
// Ajax
getUrlVars: function () {
var vars = [];
var hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var hashlen = hashes.length;
for (var i = 0; i < hashlen; ++i) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
serialize: function (obj) {
var viableNodes = ['input', 'select', 'textarea'];
var viableNodesLen = viableNodes.length;
var rawChildren = [];
var formChildren = [];
var returnObject = {};
var nodeList = [];
for (var i = 0; i < viableNodesLen; ++i) {
nodeList = obj.getElementsByTagName(viableNodes[i]);
var nodeListLen = nodeList.length;
for (var j = 0; j < nodeListLen; ++j) {
rawChildren.push(nodeList[j]);
}
}
// build list of viable form elements
var rawChildrenLen = rawChildren.length;
for (var i=0; i < rawChildrenLen; ++i) {
var currentNode = rawChildren[i];
switch(rawChildren[i].nodeName.toLowerCase()) {
case 'input':
switch(currentNode.type) {
case 'text':
formChildren.push(currentNode);
break;
case 'hidden':
formChildren.push(currentNode);
break;
case 'password':
formChildren.push(currentNode);
break;
case 'checkbox':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
case 'radio':
if (currentNode.checked) {
formChildren.push(currentNode);
}
break;
}
break;
case 'select':
formChildren.push(currentNode);
break;
case 'textarea':
formChildren.push(currentNode);
break;
}
}
//build object of the name-value pairs
var formChildrenLen = formChildren.length;
for (var i = 0; i < formChildrenLen; ++i) {
var currentNode = formChildren[i];
if (!returnObject.hasOwnProperty(currentNode.name)) {
returnObject[currentNode.name] = currentNode.value;
} else {
if (typeof returnObject[currentNode.name] == 'string') {
returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
} else {
returnObject[currentNode.name].push(currentNode.value.toString());
}
}
}
return returnObject;
},
formatParams: function (obj) {
if (obj == null) {return '';}
var q = [];
for (p in obj) {
if (obj.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
}
}
return q.join("&");
},
setDefaults: function(defaults, options) {
if (!options) {
options = defaults;
} else {
for (var index in defaults) {
if (typeof options[index] == 'undefined') {
options[index] = defaults[index];
}
}
}
return options;
},
ajax: function(options) {
options = this.setDefaults({
url: null,
data: null, // key:val
type: 'post',
- dataType: null,
disguise: false,
+ requestId: null,
beforeSend: function() {},
sendPrepared: function() {},
afterSend: function() {},
preComplete: function() {},
complete: function() {},
failure: function() {}
}, options);
var $this = this;
// init
switch (options.type.toUpperCase()) {
case 'GET':
get(options.url, options.data);
break;
case 'POST':
post(options.url, options.data);
break;
+ case: 'JSONP':
+ getJSONP(options.url, options.requestId);
+ break;
}
//private
function open(method, url) {
var req = getRequest();
if (req == null) {return;}
var d = new Date();
req.open(method, url, true);
if (method == 'POST') {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (!options.disguise) {
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
req.setRequestHeader("X-Request-Id", d.getTime());
req.onreadystatechange = function(e) {
switch (req.readyState) {
case 0:
options.beforeSend();
break
case 1:
options.sendPrepared();
break;
case 2:
options.afterSend();
break;
case 3:
options.preComplete(req);
break;
case 4:
if (req.status >= 200 && req.status < 300) {
options.complete(req);
} else if (req.status == 0) { // file:/// ajax
options.complete(req);
} else {
options.failure(req);
}
break;
}
};
return req;
}
function get(url, data) {
var req = open('GET', url + $this.formatParams(options.data));
req.send('');
return req;
}
function post(url, data) {
var req = open('POST', url);
req.send($this.formatParams(options.data));
return req;
}
+
+ function getJSONP(url, id) {
+ var script = $.create('script');
+ script.type = 'text/javascript';
+ script.src = url;
+ script.id = id || 'awesome-jsonp'; // id to remove
+ $this.append(script, $.getTag('head')[0]);
+ }
function getRequest() {
if (typeof(XMLHttpRequest) != 'undefined')
return new XMLHttpRequest();
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
return null;
}
}
};
}());
|
dancrew32/AWESOME-JS | 6afd4f73427adc1a6918aee94b1a45c5019c1b22 | array literal optimization for getClass | diff --git a/README b/README
new file mode 100644
index 0000000..0d6a7b3
--- /dev/null
+++ b/README
@@ -0,0 +1,4 @@
+Get to docready faster and get stuff done with awesome.js.
+
+Uncompressed: 12.16KB (3.83KB gzipped)
+Minified Size: ~7.39KB (~2.72KB gzipped)
diff --git a/awesome.js b/awesome.js
new file mode 100644
index 0000000..8af0630
--- /dev/null
+++ b/awesome.js
@@ -0,0 +1,535 @@
+// Awesome ensues
+var AWESOME = (function () {
+ return {
+ ready: function (fn, ctx) {
+ var ready, timer,
+ onStateChange = function (e) {
+ // Mozilla & Opera
+ if (e && e.type == 'DOMContentLoaded') {
+ fireDOMReady();
+ // Legacy
+ } else if (e && e.type == 'load') {
+ fireDOMReady();
+ // Safari & IE
+ } else if (document.readyState) {
+ if ((/loaded|complete/).test(document.readyState)) {
+ fireDOMReady();
+ // IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
+ } else if ( !! document.documentElement.doScroll) {
+ try {
+ ready || document.documentElement.doScroll('left');
+ } catch (ex) {
+ return;
+ }
+ fireDOMReady();
+ }
+ }
+ };
+ var fireDOMReady = function () {
+ if (!ready) {
+ ready = true;
+ // Call the onload function in given context or window object
+ fn.call(ctx || window);
+ // Clean up after the DOM is ready
+ if (document.removeEventListener)
+ document.removeEventListener('DOMContentLoaded', onStateChange, false);
+ document.onreadystatechange = null;
+ window.onload = null;
+ clearInterval(timer);
+ timer = null;
+ }
+ };
+ // Mozilla & Opera
+ if (document.addEventListener)
+ document.addEventListener('DOMContentLoaded', onStateChange, false);
+ // IE
+ document.onreadystatechange = onStateChange;
+ // Safari & IE
+ timer = setInterval(onStateChange, 5);
+ // Legacy
+ window.onload = onStateChange;
+ },
+ log: function (data) {
+ if (typeof console !== 'undefined') {
+ console.log(data);
+ }
+ },
+ cancelEvent: function (event) {
+ event = event || window.event;
+ if (event.preventDefault) {
+ event.preventDefault();
+ } else {
+ event.returnValue = false;
+ }
+ },
+ cancelPropagation: function (event) {
+ if (event.stopPropagation) {
+ event.stopPropagation();
+ } else {
+ event.cancelBubble = true;
+ }
+ },
+ bind: function (obj, type, handler, delegate) {
+ if (typeof obj == 'undefined' || obj == null) {return;}
+ delegate = delegate || false;
+ if (typeof obj.length == 'undefined') {
+ obj = [obj];
+ }
+ var i = obj.length;
+ while (i--) {
+ if (obj[i].addEventListener) {
+ obj[i].addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
+ } else if (obj.attachEvent) {
+ obj[i].attachEvent('on' + type, handler);
+ } else {
+ obj[i]['on' + type] = handler;
+ }
+ }
+ },
+ unbind: function (obj, type, handler, delegate) {
+ if (typeof obj == 'undefined' || obj == null) {return;}
+ delegate = delegate || false;
+ if (typeof obj.length == 'undefined') {
+ obj = [obj];
+ }
+ var i = obj.length;
+ while (i--) {
+ if (obj[i].removeEventListener) {
+ obj[i].removeEventListener(type, handler, delegate);
+ } else if (obj[i].detachEvent) {
+ obj[i].detachEvent('on' + type, handler);
+ } else {
+ obj[i]['on' + type] = null;
+ }
+ }
+ },
+ fire: function(obj, event, delegate, cancelable) {
+ var evt;
+ if (document.createEventObject) { // ie
+ evt = document.createEventObject();
+ return obj.fireEvent('on'+ event, evt);
+ }
+ delegate = delegate || false;
+ cancelable = cancelable || true;
+ evt = document.createEvent('HTMLEvents');
+ evt.initEvent(event, delegate, cancelable);
+ return !obj.dispatchEvent(evt);
+ },
+ submit: function(form) {
+ if (typeof form != 'undefined') {
+ form.submit();
+ return false;
+ }
+ },
+ hover: function (obj, over, out, delegate) {
+ if (typeof obj == 'undefined') {return;}
+ var $this = this;
+ out = out || null;
+ $this.bind(obj, 'mouseover', over, delegate);
+ if (out)
+ $this.bind(obj, 'mouseout', out, delegate);
+ },
+ hasClass: function (el, cls) {
+ var re = el.className.split(' ');
+ return -1 != re.indexOf(cls);
+ },
+ addClass: function (el, cls) {
+ if (!this.hasClass(el, cls))
+ el.className += ' ' + cls;
+ },
+ removeClass: function (el, cls) {
+ if (this.hasClass(el, cls))
+ var re = el.className.split(' ');
+ re.splice(re.indexOf(cls), 1);
+ var i = re.length;
+ el.className = ''; // empty
+ while(i--) { // reload
+ el.className += re[i] + ' ';
+ }
+ },
+ getId: function (id) {
+ return document.getElementById(id);
+ },
+ getTag: function (tag, context) {
+ context = context || document;
+ tag = tag || '*';
+ return context.getElementsByTagName(tag);
+ },
+ getClass: function (searchClass, context, tag) {
+ var classElements = [],
+ els = this.getTag(tag, context),
+ elsLen = els.length,
+ pattern = new RegExp('(^|\\s)' + searchClass + '(\\s|$)');
+ for (var i = 0, j = 0; i < elsLen; ++i) {
+ if (pattern.test(els[i].className)) {
+ classElements[j] = els[i];
+ j++;
+ }
+ }
+ return classElements;
+ },
+ toCamelCase: function (string) {
+ var oStringList = string.split('-');
+ if (oStringList.length == 1) return oStringList[0];
+
+ var ccstr = string.indexOf('-') == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
+
+ for (var i = 1, len = oStringList.length; i < len; ++i) {
+ var s = oStringList[i];
+ ccstr += s.charAt(0).toUpperCase() + s.substring(1);
+ }
+ return ccstr;
+ },
+ style: function (el, prop, newVal) {
+ if (el)
+ prop = this.toCamelCase(prop);
+ newVal = newVal || null;
+ if (newVal) {
+ if (prop == 'opacity') {
+ el.style.filter = "alpha(opacity=" + newVal * 100 + ")";
+ el.style.opacity = newVal;
+ } else {
+ prop = this.toCamelCase(prop);
+ el.style[prop] = newVal;
+ }
+ } else {
+ var view = document.defaultView;
+ if (view && view.getComputedStyle) {
+ return view.getComputedStyle(el, '')[prop] || null;
+ } else {
+ if (prop == 'opacity') {
+ var opacity = el.filters('alpha').opacity;
+ return isNaN(opacity) ? 1 : (opacity ? opacity / 100 : 0);
+ }
+ return el.currentStyle[prop] || null;
+ }
+ }
+ },
+ docHeight: function () {
+ var D = document;
+ return Math.max(
+ Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
+ Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
+ Math.max(D.body.clientHeight, D.documentElement.clientHeight)
+ );
+ },
+ docWidth: function () {
+ var D = document;
+ return Math.max(D.body.clientWidth, D.documentElement.clientWidth);
+ },
+ attr: function (ele, attr, newVal) {
+ newVal = newVal || null;
+ if (newVal) {
+ ele.setAttribute(attr, newVal);
+ } else {
+ var attrs = ele.attributes,
+ attrsLen = attrs.length,
+ result = ele.getAttribute(attr) || ele[attr] || null;
+
+ if (!result) {
+ while (attrsLen--) {
+ if (attr[attrsLen].nodeName === attr)
+ result = attr[i].nodeValue;
+ }
+ }
+ return result;
+ }
+ },
+ encodeHTML: function (str) {
+ return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
+ },
+ text: function (obj, txt) {
+ if (typeof obj != 'undefined') {
+ if (txt) {
+ if (obj.innerText != 'undefined') {
+ obj.innerText = txt;
+ }
+ obj.textContent = txt;
+ } else {
+ return obj.innerText || obj.textContent;
+ }
+ }
+ },
+ trim: function (str) {
+ return str.replace(/^\s+|\s+$/g);
+ },
+ prepend: function (newNode, node) {
+ node.insertBefore(newNode, node.childNodes[0]);
+ },
+ append: function (newNode, node) {
+ node.appendChild(newNode)
+ },
+ before: function (newNode, node) {
+ node.parentNode.insertBefore(newNode, node);
+ },
+ after: function (newNode, node) {
+ node.parentNode.insertBefore(newNode, node.nextSibling);
+ },
+ swap: function (a, b) {
+ a.parentNode.replaceChild(b, a);
+ },
+ remove: function (ele) {
+ if (!ele) return false;
+ if (!('length' in ele)) {
+ ele = [ele];
+ }
+ for (var i = 0, len = ele.length; i < len; ++i) {
+ if (!ele[i].parentNode) {
+ return false;
+ }
+ ele[i].parentNode.removeChild(ele[i]);
+ }
+ },
+ create: function (tag) {
+ // TODO: add a name attribute try/catch to solve <= ie7 submitName issue
+ return document.createElement(tag);
+ },
+ // Cookies
+ createCookie: function (name, value, days, domain) {
+ var expires = '';
+ domain = domain || window.location.host;
+ if (days) {
+ var date = new Date();
+ date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
+ expires = '; expires=' + date.toGMTString();
+ }
+ // document.cookie = name +'='+ value + expires +'; domain=.'+ domain +' ;path=/';
+ document.cookie = name + '=' + value + expires + ';';
+ },
+ eraseCookie: function (name) {
+ this.createCookie(name, '', -1);
+ },
+ readCookie: function (c_name) {
+ if (document.cookie.length > 0) {
+ var c_start = document.cookie.indexOf(c_name + "=");
+ if (c_start != -1) {
+ c_start = c_start + c_name.length + 1;
+ var c_end = document.cookie.indexOf(";", c_start);
+ if (c_end == -1) {
+ c_end = document.cookie.length;
+ }
+ return unescape(document.cookie.substring(c_start, c_end));
+ }
+ }
+ return null;
+ },
+ // Math
+ greatest: function (array) {
+ var m = Math;
+ return m.max.apply(m, array);
+ },
+ smallest: function (array) {
+ var m = Math;
+ return m.min.apply(m, array);
+ },
+ getRandom: function(min, max) {
+ var m = Math;
+ if (min) {
+ return m.floor(m.random() * (max - min + 1)) + min;
+ } else {
+ return m.round(m.random()); // 1 or 0
+ }
+ },
+ // Ajax
+ getUrlVars: function () {
+ var vars = [];
+ var hash;
+ var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
+ var hashlen = hashes.length;
+ for (var i = 0; i < hashlen; ++i) {
+ hash = hashes[i].split('=');
+ vars.push(hash[0]);
+ vars[hash[0]] = hash[1];
+ }
+ return vars;
+ },
+ serialize: function (obj) {
+ var viableNodes = ['input', 'select', 'textarea'];
+ var viableNodesLen = viableNodes.length;
+ var rawChildren = [];
+ var formChildren = [];
+ var returnObject = {};
+ var nodeList = [];
+ for (var i = 0; i < viableNodesLen; ++i) {
+ nodeList = obj.getElementsByTagName(viableNodes[i]);
+ var nodeListLen = nodeList.length;
+ for (var j = 0; j < nodeListLen; ++j) {
+ rawChildren.push(nodeList[j]);
+ }
+ }
+ // build list of viable form elements
+ var rawChildrenLen = rawChildren.length;
+ for (var i=0; i < rawChildrenLen; ++i) {
+ var currentNode = rawChildren[i];
+ switch(rawChildren[i].nodeName.toLowerCase()) {
+ case 'input':
+ switch(currentNode.type) {
+ case 'text':
+ formChildren.push(currentNode);
+ break;
+ case 'hidden':
+ formChildren.push(currentNode);
+ break;
+ case 'password':
+ formChildren.push(currentNode);
+ break;
+ case 'checkbox':
+ if (currentNode.checked) {
+ formChildren.push(currentNode);
+ }
+ break;
+ case 'radio':
+ if (currentNode.checked) {
+ formChildren.push(currentNode);
+ }
+ break;
+ }
+ break;
+ case 'select':
+ formChildren.push(currentNode);
+ break;
+ case 'textarea':
+ formChildren.push(currentNode);
+ break;
+ }
+ }
+ //build object of the name-value pairs
+ var formChildrenLen = formChildren.length;
+ for (var i = 0; i < formChildrenLen; ++i) {
+ var currentNode = formChildren[i];
+ if (!returnObject.hasOwnProperty(currentNode.name)) {
+ returnObject[currentNode.name] = currentNode.value;
+ } else {
+ if (typeof returnObject[currentNode.name] == 'string') {
+ returnObject[currentNode.name] = [returnObject[currentNode.name], currentNode.value.toString()];
+ } else {
+ returnObject[currentNode.name].push(currentNode.value.toString());
+ }
+ }
+ }
+ return returnObject;
+ },
+ formatParams: function (obj) {
+ if (obj == null) {return '';}
+ var q = [];
+ for (p in obj) {
+ if (obj.hasOwnProperty(p)) {
+ q.push( encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]) );
+ }
+ }
+ return q.join("&");
+ },
+ setDefaults: function(defaults, options) {
+ if (!options) {
+ options = defaults;
+ } else {
+ for (var index in defaults) {
+ if (typeof options[index] == 'undefined') {
+ options[index] = defaults[index];
+ }
+ }
+ }
+ return options;
+ },
+ ajax: function(options) {
+ options = this.setDefaults({
+ url: null,
+ data: null, // key:val
+ type: 'post',
+ dataType: null,
+ disguise: false,
+ beforeSend: function() {},
+ sendPrepared: function() {},
+ afterSend: function() {},
+ preComplete: function() {},
+ complete: function() {},
+ failure: function() {}
+ }, options);
+ var $this = this;
+
+ // init
+ switch (options.type.toUpperCase()) {
+ case 'GET':
+ get(options.url, options.data);
+ break;
+ case 'POST':
+ post(options.url, options.data);
+ break;
+ }
+
+ //private
+ function open(method, url) {
+ var req = getRequest();
+ if (req == null) {return;}
+ var d = new Date();
+
+ req.open(method, url, true);
+
+ if (method == 'POST') {
+ req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+ }
+ if (!options.disguise) {
+ req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ }
+ req.setRequestHeader("X-Request-Id", d.getTime());
+
+ req.onreadystatechange = function(e) {
+ switch (req.readyState) {
+ case 0:
+ options.beforeSend();
+ break
+ case 1:
+ options.sendPrepared();
+ break;
+ case 2:
+ options.afterSend();
+ break;
+ case 3:
+ options.preComplete(req);
+ break;
+ case 4:
+ if (req.status >= 200 && req.status < 300) {
+ options.complete(req);
+ } else if (req.status == 0) { // file:/// ajax
+ options.complete(req);
+ } else {
+ options.failure(req);
+ }
+ break;
+ }
+ };
+ return req;
+ }
+
+ function get(url, data) {
+ var req = open('GET', url + $this.formatParams(options.data));
+ req.send('');
+ return req;
+ }
+
+ function post(url, data) {
+ var req = open('POST', url);
+ req.send($this.formatParams(options.data));
+ return req;
+ }
+
+ function getRequest() {
+ if (typeof(XMLHttpRequest) != 'undefined')
+ return new XMLHttpRequest();
+ try {
+ return new ActiveXObject('Msxml2.XMLHTTP.6.0');
+ } catch(e) { }
+ try {
+ return new ActiveXObject('Msxml2.XMLHTTP.3.0');
+ } catch(e) { }
+ try {
+ return new ActiveXObject('Msxml2.XMLHTTP');
+ } catch(e) { }
+ try {
+ return new ActiveXObject('Microsoft.XMLHTTP');
+ } catch(e) { }
+ return null;
+ }
+ }
+ };
+}());
diff --git a/plugins/screenOverlay/screenOverlay.css b/plugins/screenOverlay/screenOverlay.css
new file mode 100644
index 0000000..7ac12f2
--- /dev/null
+++ b/plugins/screenOverlay/screenOverlay.css
@@ -0,0 +1,77 @@
+#screen-overlayer {
+ background-color: rgba(85, 85, 85, 0.7);
+ display: block;
+ overflow: hidden;
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 9998;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#55555570',EndColorStr='#55555570');
+}
+#lightbox {
+ background-color: #fff;
+ border: 5px solid #eee;
+ left: 50%;
+ height: 400px;
+ position: fixed;
+ _position: absolute;
+ text-align: center;
+ top: 0;
+ width: 500px;
+ margin-top: 40px;
+ margin-left: -250px;
+ z-index: 9999;
+ box-shadow: 3px 0 20px rgba(0, 0, 0, 0.7);
+ -moz-box-shadow: 3px 0 20px rgba(0, 0, 0, 0.7);
+ -webkit-box-shadow: 3px 0 20px rgba(0, 0, 0, 0.7);
+}
+#lightbox #lightbox-inner {
+ text-align: left;
+}
+#lightbox .header {
+ background-color: #FFFFFF;
+ border-bottom: 5px solid #fff;
+ color: #fff;
+ padding: 20px 10px;
+ background-color: #111;
+ overflow: hidden;
+}
+#lightbox .header h2 {
+ font-size: 1.5em;
+}
+#lightbox .content {
+ padding: 20px;
+ height: 320px;
+ overflow: auto;
+}
+#lightbox .content img {
+ display: block;
+ border-style: solid;
+ border-width: 1px;
+ border-color: #cccccc;
+ padding: 3px;
+ margin: 0 auto;
+ text-align: center;
+ width: 100%;
+}
+#lightbox a {
+ background-color: #ddd;
+ border: 1px solid #ccc;
+ cursor: pointer;
+ height: px;
+ width: 45px;
+ line-height: 45px;
+ top: -22.5px;
+ right: -22.5px;
+ position: absolute;
+ -khtml-border-radius: 20px;
+ -moz-border-radius: 20px;
+ -webkit-border-radius: 20px;
+ border-radius: 20px;
+}
+#lightbox a:hover {
+ background-color: #eee;
+}
+#lightbox a:active {
+ background-color: #ccc;
+}
diff --git a/plugins/screenOverlay/screenOverlay.js b/plugins/screenOverlay/screenOverlay.js
new file mode 100644
index 0000000..012e927
--- /dev/null
+++ b/plugins/screenOverlay/screenOverlay.js
@@ -0,0 +1,86 @@
+(function($) {
+$.screenOverlay = (function (options) {
+ options = $.setDefaults({
+ header: null,
+ headerType: 'h2',
+ data: null,
+ lightboxId: 'lightbox',
+ id: 'screen-overlayer',
+ closeText: 'Close'
+ }, options);
+ var $this = this;
+ var didResize = false;
+
+ // init
+ makeOverlay($this.docWidth(), $this.docHeight(), options.id);
+
+ // Make Viewport-sized grey area
+ function makeOverlay(windowWidth, windowHeight, id) {
+ var $body = document.body,
+ overlayer = $this.getId(id),
+ lightbox = $this.getId(options.lightboxId),
+ lightboxClose = $this.getId(options.lightboxId + '-close');
+
+ if (!overlayer && !lightbox) {
+ var overlayDIV = $this.create('div'),
+ lightboxDIV = $this.create('div');
+
+ $this.prepend(overlayDIV, $body);
+ $this.attr(overlayDIV, 'id', id);
+
+ $this.prepend(lightboxDIV, $body);
+ $this.attr(lightboxDIV, 'id', options.lightboxId);
+
+ $this.addClass(document.documentElement, 'has-overlay');
+
+ var overlayer = $this.getId(id),
+ lightbox = $this.getId(options.lightboxId);
+
+ // Output for lightbox
+ var lightboxOutput = '<a href="#' + options.lightboxId + '-close" id="' + options.lightboxId + '-close">'+
+ options.closeText +'</a><div id="' + options.lightboxId + '-inner">';
+ if (options.header) {
+ lightboxOutput += '<div class="header"><' + options.headerType + '>' +
+ options.header + '</' + options.headerType + '></div>';
+ }
+ lightboxOutput += '<div class="content">' + options.data + '</div></div>';
+ lightbox.innerHTML = lightboxOutput;
+
+ var lightboxClose = $this.getId(options.lightboxId + '-close');
+ }
+
+ $this.style(overlayer, 'width', windowWidth + 'px');
+ $this.style(overlayer, 'height', windowHeight + 'px');
+
+ function closeOverlay() {
+ $this.removeClass(document.documentElement, 'has-overlay');
+ $this.remove(lightbox);
+ $this.remove(overlayer);
+ }
+
+ // Bind close on overlayer
+ $this.bind(overlayer, 'click', function () {
+ closeOverlay();
+ });
+
+ // bind close button click
+ $this.bind(lightboxClose, 'click', function (e) {
+ $this.cancelEvent(e);
+ closeOverlay();
+ });
+
+ // bind resizing
+ window.onresize = function() {
+ didResize = true;
+ };
+
+ setInterval(function() {
+ if (didResize) {
+ didResize = false;
+ $this.style($this.getId(options.id), 'width', $this.docWidth() + 'px');
+ $this.style($this.getId(options.id), 'height', $this.docHeight() + 'px');
+ }
+ }, 200);
+ }
+});
+}(AWESOME));
diff --git a/plugins/truncate/truncate.js b/plugins/truncate/truncate.js
new file mode 100644
index 0000000..8e127fe
--- /dev/null
+++ b/plugins/truncate/truncate.js
@@ -0,0 +1,24 @@
+(function($) {
+$.truncate = (function (options) {
+ options = $.setDefaults({
+ obj: null,
+ length: 80,
+ moreText: 'Read More »',
+ elipsis: '...',
+ className: 'readmore'
+ }, options);
+ if (!('length' in options.obj)) {
+ options.obj = [options.obj];
+ }
+ var i = options.obj.length;
+ while(i--) {
+ var trunc = options.obj[i].innerHTML;
+ if (trunc.length > options.length) {
+ trunc = trunc.substring(0, options.length);
+ trunc = trunc.replace(/\w+$/, "");
+ trunc += options.elipsis +'<a class="'+ options.className +'" href="#" onclick="this.parentNode.innerHTML=unescape(\''+ escape(obj[i].innerHTML)+'\'); return false;">'+ options.moreText +'<\/a>';
+ options.obj[i].innerHTML = trunc;
+ }
+ }
+});
+}(AWESOME));
|
temog/ServersMan-VPS-Tool | 1993ae2680c7a46e46deb1befb88b8ead21a6805 | ç»åã®æå¤§å¹
ãæå®ã§ããããã« | diff --git a/generateThumbnail/make_thumbnail_html.php b/generateThumbnail/make_thumbnail_html.php
index 9d418a6..1a908c6 100755
--- a/generateThumbnail/make_thumbnail_html.php
+++ b/generateThumbnail/make_thumbnail_html.php
@@ -1,260 +1,288 @@
<?php
$generate = new GenerateThumbnailHTML(
'/var/serversman/htdocs/MyStorage/android_pic',
'/android_pic',
'/var/serversman/htdocs/MyStorage/android_pic/index.html',
'/var/serversman/htdocs/MyStorage/android_pic/thumbnail',
'/android_pic/thumbnail',
- '100'
+ '100',
+ '600'
);
$generate->generate();
class GenerateThumbnailHTML {
//ç»åè¨ç½®å ´æ(iPhone ã¨ã Android ããç»åãUpããå
)
protected $imgPath;
//ç»åè¨ç½®å ´æ(URL)
protected $imgURL;
//HTMLåºåå
protected $htmlPath;
//ãµã ãã¤ã«è¨ç½®å ´æï¼ãã£ã¬ã¯ããªï¼
protected $thumbPath;
//ãµã ãã¤ã«è¨ç½®å ´æï¼URLï¼
protected $thumbURL;
//ãµã ãã¤ã«ç»åã®æ¨ªå¹
(px)
protected $thumbWidth;
+ //ç»åã®æå¤§æ¨ªå¹
(px) çç¥æã¯ãªãµã¤ãºããªã
+ protected $imgWidth;
//HTMLã«åºåãããµã ãã¤ã«åæ°
protected $numOfThumb = 5;
//対å¿ããæ¡å¼µå
private $ext = array('.jpg', '.gif', '.png');
//ç»åä¸è¦§
protected $images = array();
//thumbnailç»åä¸è¦§
protected $thumbnails = array();
//htmlçæãã©ã°
private $updateHTML = false;
//ç»åã®è¦ªã¿ã°(div)ã®CSSã¯ã©ã¹å
protected $cssName = 'serversman_pictures';
public function __construct($imgPath, $imgURL, $htmlPath,
- $thumbPath, $thumbURL, $thumbWidth){
+ $thumbPath, $thumbURL, $thumbWidth, $imgWidth = null){
$this->imgPath = $imgPath;
$this->imgURL = $imgURL;
$this->htmlPath = $htmlPath;
$this->thumbPath = $thumbPath;
$this->thumbURL = $thumbURL;
$this->thumbWidth = $thumbWidth;
+ $this->imgWidth = $imgWidth;
}
public function generate(){
//ç»åè¨ç½®å ´æããç»åä¸è¦§åå¾
$this->getImgPathPictures();
//thumbnail è¨ç½®å ´æããç»åä¸è¦§åå¾
$this->getThumbPathPictures();
//ç»åä¸è¦§ã¨thumbnailä¸è¦§ãæ¯è¼ãã¦åå¨ããªãç»åããã£ããthumbnail ç¨ç»åãä½ã
$this->generateThumbImages();
//ç»åä¸è¦§ã«ãªããthumnailã«åå¨ããç»åãåé¤
$this->deleteThumbImages();
//ç»åçæããå ´åãhtml ãçæãã
$this->generateHTML();
}
//ç»åè¨ç½®å ´æããç»åä¸è¦§åå¾
private function getImgPathPictures(){
if(! $open = opendir($this->imgPath)){
return;
}
while(false !== ($file = readdir($open))){
$filePath = $this->imgPath . "/" . $file;
if(is_dir($filePath)){
continue;
}
//æ¡å¼µåãã§ãã¯
foreach($this->ext as $ext){
if(preg_match("/" . $ext . "/e", strtolower($file))){
$this->images[filemtime($filePath) . "_" . $file] = array($file, $ext);
continue;
}
}
}
closedir($open);
//ç»åæ´æ°æ¥ï¼éé ï¼ã§ä¸¦ã³æ¿ã
krsort($this->images);
}
//thumbnail è¨ç½®å ´æããç»åä¸è¦§åå¾
private function getThumbPathPictures(){
if(! $open = opendir($this->thumbPath)){
return;
}
while(false !== ($file = readdir($open))){
$filePath = $this->thumbPath . "/" . $file;
if(is_dir($filePath)){
continue;
}
array_push($this->thumbnails, $file);
}
closedir($open);
}
//ç»åä¸è¦§ã¨thumbnailä¸è¦§ãæ¯è¼ãã¦åå¨ããªãç»åããã£ããthumbnail ç¨ç»åãä½ã
private function generateThumbImages(){
foreach($this->images as $thumbName => $fileAndExt){
if(in_array($thumbName, $this->thumbnails)){
continue;
}
$this->updateHTML = true;
$file = $fileAndExt[0];
$ext = $fileAndExt[1];
//thumbnail使
switch($ext){
case ".jpg":
$img = imagecreatefromjpeg($this->imgPath . "/" . $file);
break;
case ".png":
$img = imagecreatefrompng($this->imgPath . "/" . $file);
break;
case ".gif":
$img = imagecreatefromgif($this->imgPath . "/" . $file);
break;
default:
$this->stderr("invalid extension");
}
//ç»åãµã¤ãºåå¾
$width = ImageSX($img);
$height = ImageSY($img);
$thumbWidth = $this->thumbWidth;
$thumbHeight = 0;
//thumbnail æå®ãµã¤ãºãã大ãããã°thumbnail使
if($width > $thumbWidth){
$thumbHeight = ($thumbWidth / $width) * $height;
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImg, $img, 0, 0, 0, 0,
$thumbWidth, $thumbHeight, $width, $height);
}
//thumbnail é
ç½®
$saveThumbPath = $this->thumbPath . "/" . $thumbName;
if($thumbHeight == 0 && $ext == ".jpg"){
imagejpeg($img, $saveThumbPath, 90);
} else if($thumbHeight == 0 && $ext == ".png"){
imagepng($img, $saveThumbPath);
} else if($thumbHeight == 0 && $ext == ".gif"){
imagegif($img, $saveThumbPath);
} else if($ext == ".jpg"){
imagejpeg($thumbImg, $saveThumbPath, 90);
} else if($ext == ".png"){
imagepng($thumbImg, $saveThumbPath);
} else if($ext == ".gif"){
imagegif($thumbImg, $saveThumbPath);
}
+ //ç»åãæå¤§å¹
ãè¶
ãã¦ãããªãµã¤ãº
+ if($this->imgWidth && $width > $this->imgWidth){
+ $resizeHeight = ($this->imgWidth / $width) * $height;
+ $resizeImg = imagecreatetruecolor($this->imgWidth, $resizeHeight);
+ imagecopyresampled($resizeImg, $img, 0, 0, 0, 0,
+ $this->imgWidth, $resizeHeight, $width, $height);
+
+ unlink($this->imgPath . "/" . $file);
+
+ switch($ext){
+ case ".jpg":
+ imagejpeg($resizeImg, $this->imgPath . "/" . $file, 90);
+ break;
+ case ".png":
+ imagepng($resizeImg, $this->imgPath . "/" . $file);
+ break;
+ case ".gif":
+ imagegif($resizeImg, $this->imgPath . "/" . $file);
+ break;
+ default:
+ $this->stderr("invalid extension");
+ }
+ }
+
//ã¡ã¢ãªè§£æ¾
if($thumbHeight != 0){
imagedestroy($thumbImg);
}
imagedestroy($img);
$this->stdout("generage thumbnail " . $saveThumbPath);
}
}
//ç»åä¸è¦§ã«ãªããthumnailã«åå¨ããç»åãåé¤
private function deleteThumbImages(){
foreach($this->thumbnails as $i => $thumbName){
$exist = false;
foreach($this->images as $k_thumbName => $fileAndExt){
if($thumbName == $k_thumbName){
$exist = true;
break;
}
}
//åå¨ããªããã° thumbnail ãåé¤
if($exist){
continue;
}
$this->updateHTML = true;
unlink($this->thumbPath . "/" . $thumbName);
array_splice($this->thumbnails, $i, 1);
$this->stdout("delete thumbnail " . $this->thumbPath . "/" . $thumbName);
}
}
//ç»åçæ or thumbnail åé¤ããå ´åãhtml ãçæãã
private function generateHTML(){
if(! $this->updateHTML){
return;
}
$i = 0;
if(! $f = fopen($this->htmlPath, "w")){
$this->stderr("fopen error " . $this->htmlPath);
}
if(! flock($f, LOCK_EX)){
$this->stderr("file lock error " . $this->htmlPath);
}
fwrite($f, '<div class="' . $this->cssName . '">');
foreach($this->images as $thumbName => $fileAndExt){
$i++;
$file = $fileAndExt[0];
fwrite($f, '<a href="' . $this->imgURL . '/' . $file . '">'.
'<img src="' . $this->thumbURL . '/' . $thumbName . '"></a>');
if($i == $this->numOfThumb){
break;
}
}
fwrite($f, '</div>');
flock($f, LOCK_UN);
fclose($f);
$this->stdout("generate html " . $this->htmlPath);
}
//表示ããThumbnail åæ°ã夿´
public function setNumOfThumb($num){
if(! preg_match("/^[0-9]+$/", $num)){
return false;
}
$this->numOfThumb = $num;
return true;
}
//divã¿ã°ã®CSSåã夿´
public function setCssName($cssName){
if(! $cssName){
return false;
}
$this->cssName = $cssName;
}
//stderrç¨
private function stderr($message){
$message = "[" . date("Y-m-d H:i:s") . "] " . $message;
fwrite(STDERR, $message . "\n");
exit;
}
//stdoutç¨
private function stdout($message){
$message = "[" . date("Y-m-d H:i:s") . "] " . $message;
echo $message . "\n";
}
}
|
temog/ServersMan-VPS-Tool | ea229b9c832b1820d5dcc1fe6d325f804ef10e58 | html update flag ã false ã« | diff --git a/generateThumbnail/make_thumbnail_html.php b/generateThumbnail/make_thumbnail_html.php
index a45c506..9d418a6 100755
--- a/generateThumbnail/make_thumbnail_html.php
+++ b/generateThumbnail/make_thumbnail_html.php
@@ -1,260 +1,260 @@
<?php
$generate = new GenerateThumbnailHTML(
'/var/serversman/htdocs/MyStorage/android_pic',
'/android_pic',
'/var/serversman/htdocs/MyStorage/android_pic/index.html',
'/var/serversman/htdocs/MyStorage/android_pic/thumbnail',
'/android_pic/thumbnail',
'100'
);
$generate->generate();
class GenerateThumbnailHTML {
//ç»åè¨ç½®å ´æ(iPhone ã¨ã Android ããç»åãUpããå
)
protected $imgPath;
//ç»åè¨ç½®å ´æ(URL)
protected $imgURL;
//HTMLåºåå
protected $htmlPath;
//ãµã ãã¤ã«è¨ç½®å ´æï¼ãã£ã¬ã¯ããªï¼
protected $thumbPath;
//ãµã ãã¤ã«è¨ç½®å ´æï¼URLï¼
protected $thumbURL;
//ãµã ãã¤ã«ç»åã®æ¨ªå¹
(px)
protected $thumbWidth;
//HTMLã«åºåãããµã ãã¤ã«åæ°
protected $numOfThumb = 5;
//対å¿ããæ¡å¼µå
private $ext = array('.jpg', '.gif', '.png');
//ç»åä¸è¦§
protected $images = array();
//thumbnailç»åä¸è¦§
protected $thumbnails = array();
//htmlçæãã©ã°
- private $updateHTML = true;
+ private $updateHTML = false;
//ç»åã®è¦ªã¿ã°(div)ã®CSSã¯ã©ã¹å
protected $cssName = 'serversman_pictures';
public function __construct($imgPath, $imgURL, $htmlPath,
$thumbPath, $thumbURL, $thumbWidth){
$this->imgPath = $imgPath;
$this->imgURL = $imgURL;
$this->htmlPath = $htmlPath;
$this->thumbPath = $thumbPath;
$this->thumbURL = $thumbURL;
$this->thumbWidth = $thumbWidth;
}
public function generate(){
//ç»åè¨ç½®å ´æããç»åä¸è¦§åå¾
$this->getImgPathPictures();
//thumbnail è¨ç½®å ´æããç»åä¸è¦§åå¾
$this->getThumbPathPictures();
//ç»åä¸è¦§ã¨thumbnailä¸è¦§ãæ¯è¼ãã¦åå¨ããªãç»åããã£ããthumbnail ç¨ç»åãä½ã
$this->generateThumbImages();
//ç»åä¸è¦§ã«ãªããthumnailã«åå¨ããç»åãåé¤
$this->deleteThumbImages();
//ç»åçæããå ´åãhtml ãçæãã
$this->generateHTML();
}
//ç»åè¨ç½®å ´æããç»åä¸è¦§åå¾
private function getImgPathPictures(){
if(! $open = opendir($this->imgPath)){
return;
}
while(false !== ($file = readdir($open))){
$filePath = $this->imgPath . "/" . $file;
if(is_dir($filePath)){
continue;
}
//æ¡å¼µåãã§ãã¯
foreach($this->ext as $ext){
if(preg_match("/" . $ext . "/e", strtolower($file))){
$this->images[filemtime($filePath) . "_" . $file] = array($file, $ext);
continue;
}
}
}
closedir($open);
//ç»åæ´æ°æ¥ï¼éé ï¼ã§ä¸¦ã³æ¿ã
krsort($this->images);
}
//thumbnail è¨ç½®å ´æããç»åä¸è¦§åå¾
private function getThumbPathPictures(){
if(! $open = opendir($this->thumbPath)){
return;
}
while(false !== ($file = readdir($open))){
$filePath = $this->thumbPath . "/" . $file;
if(is_dir($filePath)){
continue;
}
array_push($this->thumbnails, $file);
}
closedir($open);
}
//ç»åä¸è¦§ã¨thumbnailä¸è¦§ãæ¯è¼ãã¦åå¨ããªãç»åããã£ããthumbnail ç¨ç»åãä½ã
private function generateThumbImages(){
foreach($this->images as $thumbName => $fileAndExt){
if(in_array($thumbName, $this->thumbnails)){
continue;
}
$this->updateHTML = true;
$file = $fileAndExt[0];
$ext = $fileAndExt[1];
//thumbnail使
switch($ext){
case ".jpg":
$img = imagecreatefromjpeg($this->imgPath . "/" . $file);
break;
case ".png":
$img = imagecreatefrompng($this->imgPath . "/" . $file);
break;
case ".gif":
$img = imagecreatefromgif($this->imgPath . "/" . $file);
break;
default:
$this->stderr("invalid extension");
}
//ç»åãµã¤ãºåå¾
$width = ImageSX($img);
$height = ImageSY($img);
$thumbWidth = $this->thumbWidth;
$thumbHeight = 0;
//thumbnail æå®ãµã¤ãºãã大ãããã°thumbnail使
if($width > $thumbWidth){
$thumbHeight = ($thumbWidth / $width) * $height;
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImg, $img, 0, 0, 0, 0,
$thumbWidth, $thumbHeight, $width, $height);
}
//thumbnail é
ç½®
$saveThumbPath = $this->thumbPath . "/" . $thumbName;
if($thumbHeight == 0 && $ext == ".jpg"){
imagejpeg($img, $saveThumbPath, 90);
} else if($thumbHeight == 0 && $ext == ".png"){
imagepng($img, $saveThumbPath);
} else if($thumbHeight == 0 && $ext == ".gif"){
imagegif($img, $saveThumbPath);
} else if($ext == ".jpg"){
imagejpeg($thumbImg, $saveThumbPath, 90);
} else if($ext == ".png"){
imagepng($thumbImg, $saveThumbPath);
} else if($ext == ".gif"){
imagegif($thumbImg, $saveThumbPath);
}
//ã¡ã¢ãªè§£æ¾
if($thumbHeight != 0){
imagedestroy($thumbImg);
}
imagedestroy($img);
$this->stdout("generage thumbnail " . $saveThumbPath);
}
}
//ç»åä¸è¦§ã«ãªããthumnailã«åå¨ããç»åãåé¤
private function deleteThumbImages(){
foreach($this->thumbnails as $i => $thumbName){
$exist = false;
foreach($this->images as $k_thumbName => $fileAndExt){
if($thumbName == $k_thumbName){
$exist = true;
break;
}
}
//åå¨ããªããã° thumbnail ãåé¤
if($exist){
continue;
}
$this->updateHTML = true;
unlink($this->thumbPath . "/" . $thumbName);
array_splice($this->thumbnails, $i, 1);
$this->stdout("delete thumbnail " . $this->thumbPath . "/" . $thumbName);
}
}
//ç»åçæ or thumbnail åé¤ããå ´åãhtml ãçæãã
private function generateHTML(){
if(! $this->updateHTML){
return;
}
$i = 0;
if(! $f = fopen($this->htmlPath, "w")){
$this->stderr("fopen error " . $this->htmlPath);
}
if(! flock($f, LOCK_EX)){
$this->stderr("file lock error " . $this->htmlPath);
}
fwrite($f, '<div class="' . $this->cssName . '">');
foreach($this->images as $thumbName => $fileAndExt){
$i++;
$file = $fileAndExt[0];
fwrite($f, '<a href="' . $this->imgURL . '/' . $file . '">'.
'<img src="' . $this->thumbURL . '/' . $thumbName . '"></a>');
if($i == $this->numOfThumb){
break;
}
}
fwrite($f, '</div>');
flock($f, LOCK_UN);
fclose($f);
$this->stdout("generate html " . $this->htmlPath);
}
//表示ããThumbnail åæ°ã夿´
public function setNumOfThumb($num){
if(! preg_match("/^[0-9]+$/", $num)){
return false;
}
$this->numOfThumb = $num;
return true;
}
//divã¿ã°ã®CSSåã夿´
public function setCssName($cssName){
if(! $cssName){
return false;
}
$this->cssName = $cssName;
}
//stderrç¨
private function stderr($message){
$message = "[" . date("Y-m-d H:i:s") . "] " . $message;
fwrite(STDERR, $message . "\n");
exit;
}
//stdoutç¨
private function stdout($message){
$message = "[" . date("Y-m-d H:i:s") . "] " . $message;
echo $message . "\n";
}
}
|
temog/ServersMan-VPS-Tool | 7198b3f57ddbc0428e32c44cf242b70eb0f18195 | generateThumbnail commit | diff --git a/README b/README
index 455a0ce..17c7303 100644
--- a/README
+++ b/README
@@ -1,8 +1,13 @@
-ServersMan@VPS ã® ServersMan ããã»ã¹ãç£è¦ãã¦ãã亡ããªãã«ãªã£ã¦ãããèªåèµ·åããã¹ã¯ãªããã§ãã
+monitor
+ ServersMan@VPS ã® ServersMan ããã»ã¹ãç£è¦ãã¦ãã亡ããªãã«ãªã£ã¦ãããèªåèµ·åããã¹ã¯ãªããã§ãã
-詳ããã¯ãBlog ãè¦ã¦ãã ããã
-http://temog.info/archives/programming/serversman-monitor.html
+ 詳ããã¯ãBlog ãè¦ã¦ãã ããã
+ http://temog.info/archives/programming/serversman-monitor.html
+
+generateThumbnail
+ ãã£ã¬ã¯ããªå
ã®ç»åãThumbnail å + html çæ
æ´æ°å±¥æ´
- 2010/10/14 åã³ããã
+ 2010/10/14 monitor åã³ããã
+ 2011/04/18 generateThumbnail ã³ããã
|
temog/ServersMan-VPS-Tool | 5b3fe1fefdd716c95376e304fceb42068fdb17cb | generateThumbnail commit | diff --git a/generateThumbnail/make_thumbnail_html.php b/generateThumbnail/make_thumbnail_html.php
new file mode 100755
index 0000000..a45c506
--- /dev/null
+++ b/generateThumbnail/make_thumbnail_html.php
@@ -0,0 +1,260 @@
+<?php
+
+$generate = new GenerateThumbnailHTML(
+ '/var/serversman/htdocs/MyStorage/android_pic',
+ '/android_pic',
+ '/var/serversman/htdocs/MyStorage/android_pic/index.html',
+ '/var/serversman/htdocs/MyStorage/android_pic/thumbnail',
+ '/android_pic/thumbnail',
+ '100'
+);
+$generate->generate();
+
+class GenerateThumbnailHTML {
+
+ //ç»åè¨ç½®å ´æ(iPhone ã¨ã Android ããç»åãUpããå
)
+ protected $imgPath;
+ //ç»åè¨ç½®å ´æ(URL)
+ protected $imgURL;
+ //HTMLåºåå
+ protected $htmlPath;
+ //ãµã ãã¤ã«è¨ç½®å ´æï¼ãã£ã¬ã¯ããªï¼
+ protected $thumbPath;
+ //ãµã ãã¤ã«è¨ç½®å ´æï¼URLï¼
+ protected $thumbURL;
+ //ãµã ãã¤ã«ç»åã®æ¨ªå¹
(px)
+ protected $thumbWidth;
+
+ //HTMLã«åºåãããµã ãã¤ã«åæ°
+ protected $numOfThumb = 5;
+ //対å¿ããæ¡å¼µå
+ private $ext = array('.jpg', '.gif', '.png');
+ //ç»åä¸è¦§
+ protected $images = array();
+ //thumbnailç»åä¸è¦§
+ protected $thumbnails = array();
+ //htmlçæãã©ã°
+ private $updateHTML = true;
+ //ç»åã®è¦ªã¿ã°(div)ã®CSSã¯ã©ã¹å
+ protected $cssName = 'serversman_pictures';
+
+ public function __construct($imgPath, $imgURL, $htmlPath,
+ $thumbPath, $thumbURL, $thumbWidth){
+ $this->imgPath = $imgPath;
+ $this->imgURL = $imgURL;
+ $this->htmlPath = $htmlPath;
+ $this->thumbPath = $thumbPath;
+ $this->thumbURL = $thumbURL;
+ $this->thumbWidth = $thumbWidth;
+ }
+
+ public function generate(){
+ //ç»åè¨ç½®å ´æããç»åä¸è¦§åå¾
+ $this->getImgPathPictures();
+
+ //thumbnail è¨ç½®å ´æããç»åä¸è¦§åå¾
+ $this->getThumbPathPictures();
+
+ //ç»åä¸è¦§ã¨thumbnailä¸è¦§ãæ¯è¼ãã¦åå¨ããªãç»åããã£ããthumbnail ç¨ç»åãä½ã
+ $this->generateThumbImages();
+
+ //ç»åä¸è¦§ã«ãªããthumnailã«åå¨ããç»åãåé¤
+ $this->deleteThumbImages();
+
+ //ç»åçæããå ´åãhtml ãçæãã
+ $this->generateHTML();
+
+ }
+
+ //ç»åè¨ç½®å ´æããç»åä¸è¦§åå¾
+ private function getImgPathPictures(){
+ if(! $open = opendir($this->imgPath)){
+ return;
+ }
+
+ while(false !== ($file = readdir($open))){
+ $filePath = $this->imgPath . "/" . $file;
+ if(is_dir($filePath)){
+ continue;
+ }
+ //æ¡å¼µåãã§ãã¯
+ foreach($this->ext as $ext){
+ if(preg_match("/" . $ext . "/e", strtolower($file))){
+ $this->images[filemtime($filePath) . "_" . $file] = array($file, $ext);
+ continue;
+ }
+ }
+ }
+ closedir($open);
+
+ //ç»åæ´æ°æ¥ï¼éé ï¼ã§ä¸¦ã³æ¿ã
+ krsort($this->images);
+ }
+
+ //thumbnail è¨ç½®å ´æããç»åä¸è¦§åå¾
+ private function getThumbPathPictures(){
+ if(! $open = opendir($this->thumbPath)){
+ return;
+ }
+
+ while(false !== ($file = readdir($open))){
+ $filePath = $this->thumbPath . "/" . $file;
+ if(is_dir($filePath)){
+ continue;
+ }
+ array_push($this->thumbnails, $file);
+ }
+ closedir($open);
+ }
+
+ //ç»åä¸è¦§ã¨thumbnailä¸è¦§ãæ¯è¼ãã¦åå¨ããªãç»åããã£ããthumbnail ç¨ç»åãä½ã
+ private function generateThumbImages(){
+ foreach($this->images as $thumbName => $fileAndExt){
+ if(in_array($thumbName, $this->thumbnails)){
+ continue;
+ }
+ $this->updateHTML = true;
+ $file = $fileAndExt[0];
+ $ext = $fileAndExt[1];
+
+ //thumbnail使
+ switch($ext){
+ case ".jpg":
+ $img = imagecreatefromjpeg($this->imgPath . "/" . $file);
+ break;
+ case ".png":
+ $img = imagecreatefrompng($this->imgPath . "/" . $file);
+ break;
+ case ".gif":
+ $img = imagecreatefromgif($this->imgPath . "/" . $file);
+ break;
+ default:
+ $this->stderr("invalid extension");
+ }
+
+ //ç»åãµã¤ãºåå¾
+ $width = ImageSX($img);
+ $height = ImageSY($img);
+ $thumbWidth = $this->thumbWidth;
+ $thumbHeight = 0;
+
+ //thumbnail æå®ãµã¤ãºãã大ãããã°thumbnail使
+ if($width > $thumbWidth){
+ $thumbHeight = ($thumbWidth / $width) * $height;
+ $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
+ imagecopyresampled($thumbImg, $img, 0, 0, 0, 0,
+ $thumbWidth, $thumbHeight, $width, $height);
+ }
+
+ //thumbnail é
ç½®
+ $saveThumbPath = $this->thumbPath . "/" . $thumbName;
+
+ if($thumbHeight == 0 && $ext == ".jpg"){
+ imagejpeg($img, $saveThumbPath, 90);
+ } else if($thumbHeight == 0 && $ext == ".png"){
+ imagepng($img, $saveThumbPath);
+ } else if($thumbHeight == 0 && $ext == ".gif"){
+ imagegif($img, $saveThumbPath);
+ } else if($ext == ".jpg"){
+ imagejpeg($thumbImg, $saveThumbPath, 90);
+ } else if($ext == ".png"){
+ imagepng($thumbImg, $saveThumbPath);
+ } else if($ext == ".gif"){
+ imagegif($thumbImg, $saveThumbPath);
+ }
+
+ //ã¡ã¢ãªè§£æ¾
+ if($thumbHeight != 0){
+ imagedestroy($thumbImg);
+ }
+ imagedestroy($img);
+
+ $this->stdout("generage thumbnail " . $saveThumbPath);
+ }
+ }
+
+ //ç»åä¸è¦§ã«ãªããthumnailã«åå¨ããç»åãåé¤
+ private function deleteThumbImages(){
+ foreach($this->thumbnails as $i => $thumbName){
+ $exist = false;
+ foreach($this->images as $k_thumbName => $fileAndExt){
+ if($thumbName == $k_thumbName){
+ $exist = true;
+ break;
+ }
+ }
+
+ //åå¨ããªããã° thumbnail ãåé¤
+ if($exist){
+ continue;
+ }
+ $this->updateHTML = true;
+ unlink($this->thumbPath . "/" . $thumbName);
+ array_splice($this->thumbnails, $i, 1);
+
+ $this->stdout("delete thumbnail " . $this->thumbPath . "/" . $thumbName);
+ }
+ }
+
+ //ç»åçæ or thumbnail åé¤ããå ´åãhtml ãçæãã
+ private function generateHTML(){
+ if(! $this->updateHTML){
+ return;
+ }
+
+ $i = 0;
+ if(! $f = fopen($this->htmlPath, "w")){
+ $this->stderr("fopen error " . $this->htmlPath);
+ }
+ if(! flock($f, LOCK_EX)){
+ $this->stderr("file lock error " . $this->htmlPath);
+ }
+ fwrite($f, '<div class="' . $this->cssName . '">');
+ foreach($this->images as $thumbName => $fileAndExt){
+ $i++;
+ $file = $fileAndExt[0];
+ fwrite($f, '<a href="' . $this->imgURL . '/' . $file . '">'.
+ '<img src="' . $this->thumbURL . '/' . $thumbName . '"></a>');
+
+ if($i == $this->numOfThumb){
+ break;
+ }
+ }
+ fwrite($f, '</div>');
+ flock($f, LOCK_UN);
+ fclose($f);
+
+ $this->stdout("generate html " . $this->htmlPath);
+ }
+
+ //表示ããThumbnail åæ°ã夿´
+ public function setNumOfThumb($num){
+ if(! preg_match("/^[0-9]+$/", $num)){
+ return false;
+ }
+ $this->numOfThumb = $num;
+ return true;
+ }
+
+ //divã¿ã°ã®CSSåã夿´
+ public function setCssName($cssName){
+ if(! $cssName){
+ return false;
+ }
+ $this->cssName = $cssName;
+ }
+
+ //stderrç¨
+ private function stderr($message){
+ $message = "[" . date("Y-m-d H:i:s") . "] " . $message;
+ fwrite(STDERR, $message . "\n");
+ exit;
+ }
+
+ //stdoutç¨
+ private function stdout($message){
+ $message = "[" . date("Y-m-d H:i:s") . "] " . $message;
+ echo $message . "\n";
+ }
+}
+
diff --git a/monitor/monitServersman.py b/monitor/monitServersman.py
new file mode 100644
index 0000000..8b61cbe
--- /dev/null
+++ b/monitor/monitServersman.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+import sys, urllib, urllib2, cookielib, commands, datetime
+
+#### è¨å®éå§ #########################################
+
+# ServersMan管çãã¼ã«
+smAdminParam = {
+ 'passwd' : '管çãã¼ã«ã®ãã¹ã¯ã¼ã',
+ 'usr_name' : 'admin',
+ 'q' : 'auth',
+}
+
+# ServersManã®IDã¨ãã¹ã¯ã¼ã
+smAccParam = {
+ 'sm-account' : 'ServersManã®ã¡ã¼ã«ã¢ãã¬ã¹',
+ 'sm-password' : 'ServersManã®ãã¹ã¯ã¼ã',
+ 'q' : 4,
+ 'setSMState' : 0,
+ 'smSwitch' : 1,
+ 'B1' : 'è¨å®'
+}
+
+#### è¨å®çµäº #########################################
+
+# ServersManã®URL
+smUrl = 'http://localhost/serversman'
+
+# ããã»ã¹ç£è¦ããã³ãã³ã
+chkstr = 'ps -ef | grep "/opt/serversman/bin/serversman" | grep -v "grep"'
+
+
+result = commands.getoutput(chkstr)
+if result:
+ sys.exit();
+
+
+cookie = cookielib.CookieJar()
+opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
+
+# ããããã¼ã¸ã§ãã°ã¤ã³
+try:
+ result = opener.open(
+ smUrl,
+ urllib.urlencode(smAdminParam)
+ )
+except:
+ print sys.exc_info()
+ sys.exit()
+
+# è¨å®ã»å¤æ´ãã¼ã¸ããServersManããæå¹ãã«ãã
+try:
+ result = opener.open(
+ smUrl,
+ urllib.urlencode(smAccParam)
+ )
+except:
+ print sys.exc_info()
+ sys.exit()
+
+# ãªã¹ã¿ã¼ãããæ¥æãåºå
+now = datetime.datetime.now()
+print now.strftime("%Y-%m-%d %H:%M:%S")
+
|
temog/ServersMan-VPS-Tool | 48cb8a6b904c16953b3cf24b03c2f69e62c63811 | add readme | diff --git a/monitServersman.py b/monitServersman.py
index 1a30b16..8b61cbe 100644
--- a/monitServersman.py
+++ b/monitServersman.py
@@ -1,63 +1,64 @@
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, urllib, urllib2, cookielib, commands, datetime
#### è¨å®éå§ #########################################
# ServersMan管çãã¼ã«
smAdminParam = {
'passwd' : '管çãã¼ã«ã®ãã¹ã¯ã¼ã',
'usr_name' : 'admin',
'q' : 'auth',
}
# ServersManã®IDã¨ãã¹ã¯ã¼ã
smAccParam = {
- 'sm-account' : 'ServersManç¨ã¡ã¼ã«ã¢ãã¬ã¹',
+ 'sm-account' : 'ServersManã®ã¡ã¼ã«ã¢ãã¬ã¹',
'sm-password' : 'ServersManã®ãã¹ã¯ã¼ã',
'q' : 4,
'setSMState' : 0,
'smSwitch' : 1,
'B1' : 'è¨å®'
}
#### è¨å®çµäº #########################################
# ServersManã®URL
smUrl = 'http://localhost/serversman'
# ããã»ã¹ç£è¦ããã³ãã³ã
chkstr = 'ps -ef | grep "/opt/serversman/bin/serversman" | grep -v "grep"'
result = commands.getoutput(chkstr)
if result:
sys.exit();
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
# ããããã¼ã¸ã§ãã°ã¤ã³
try:
result = opener.open(
smUrl,
urllib.urlencode(smAdminParam)
)
except:
print sys.exc_info()
sys.exit()
# è¨å®ã»å¤æ´ãã¼ã¸ããServersManããæå¹ãã«ãã
try:
result = opener.open(
smUrl,
urllib.urlencode(smAccParam)
)
except:
print sys.exc_info()
sys.exit()
# ãªã¹ã¿ã¼ãããæ¥æãåºå
now = datetime.datetime.now()
print now.strftime("%Y-%m-%d %H:%M:%S")
|
temog/ServersMan-VPS-Tool | c059de1964a593c4f5baae8b7fdcf22852ca3cfd | add readme | diff --git a/README b/README
index e69de29..455a0ce 100644
--- a/README
+++ b/README
@@ -0,0 +1,8 @@
+ServersMan@VPS ã® ServersMan ããã»ã¹ãç£è¦ãã¦ãã亡ããªãã«ãªã£ã¦ãããèªåèµ·åããã¹ã¯ãªããã§ãã
+
+詳ããã¯ãBlog ãè¦ã¦ãã ããã
+http://temog.info/archives/programming/serversman-monitor.html
+
+æ´æ°å±¥æ´
+ 2010/10/14 åã³ããã
+
|
temog/ServersMan-VPS-Tool | 4f64da4e064e27f98f6bf4a4a3148e8eff62ac2d | serversman check tool | diff --git a/monitServersman.py b/monitServersman.py
new file mode 100644
index 0000000..1a30b16
--- /dev/null
+++ b/monitServersman.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+import sys, urllib, urllib2, cookielib, commands, datetime
+
+#### è¨å®éå§ #########################################
+
+# ServersMan管çãã¼ã«
+smAdminParam = {
+ 'passwd' : '管çãã¼ã«ã®ãã¹ã¯ã¼ã',
+ 'usr_name' : 'admin',
+ 'q' : 'auth',
+}
+
+# ServersManã®IDã¨ãã¹ã¯ã¼ã
+smAccParam = {
+ 'sm-account' : 'ServersManç¨ã¡ã¼ã«ã¢ãã¬ã¹',
+ 'sm-password' : 'ServersManã®ãã¹ã¯ã¼ã',
+ 'q' : 4,
+ 'setSMState' : 0,
+ 'smSwitch' : 1,
+ 'B1' : 'è¨å®'
+}
+
+#### è¨å®çµäº #########################################
+
+# ServersManã®URL
+smUrl = 'http://localhost/serversman'
+
+# ããã»ã¹ç£è¦ããã³ãã³ã
+chkstr = 'ps -ef | grep "/opt/serversman/bin/serversman" | grep -v "grep"'
+
+
+result = commands.getoutput(chkstr)
+if result:
+ sys.exit();
+
+
+cookie = cookielib.CookieJar()
+opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
+
+# ããããã¼ã¸ã§ãã°ã¤ã³
+try:
+ result = opener.open(
+ smUrl,
+ urllib.urlencode(smAdminParam)
+ )
+except:
+ print sys.exc_info()
+ sys.exit()
+
+# è¨å®ã»å¤æ´ãã¼ã¸ããServersManããæå¹ãã«ãã
+try:
+ result = opener.open(
+ smUrl,
+ urllib.urlencode(smAccParam)
+ )
+except:
+ print sys.exc_info()
+ sys.exit()
+
+# ãªã¹ã¿ã¼ãããæ¥æãåºå
+now = datetime.datetime.now()
+print now.strftime("%Y-%m-%d %H:%M:%S")
+
|
gman989/CaboCON | cfe4bef2d0b742e1ecaa61e29a274f6829b30777 | My First Commit | diff --git a/README b/README
new file mode 100644
index 0000000..c943b7e
--- /dev/null
+++ b/README
@@ -0,0 +1 @@
+G-Man
|
logankoester/vimrc | d0462e418fe3c847d52005ff4976d20964d32f46 | Adds my gvimrc file to repo | diff --git a/gvimrc b/gvimrc
new file mode 100644
index 0000000..c678900
--- /dev/null
+++ b/gvimrc
@@ -0,0 +1,54 @@
+colorscheme slate
+
+" Enable toolbars
+set guioptions+=m
+set guioptions+=T
+set number
+
+set gfn=Terminus\ 12
+
+" Enable NerdTREE
+"autocmd VimEnter * NERDTree
+"autocmd VimEnter * wincmd p
+
+" F12 to toggle word-wrapping, and Shift+F12 to toggle horizontal scrollbar
+function ToggleWrap()
+ set wrap!
+ echo &wrap ? 'wrap' : 'nowrap'
+endfunc
+
+"F12 toggles wrap (Thanks to Alexandre Moreira)
+nnoremap <silent> <F12> :call ToggleWrap()<CR>
+vnoremap <silent> <F12> <C-C>:call ToggleWrap()<CR>
+inoremap <silent> <F12> <C-O>:call ToggleWrap()<CR>
+
+function ToggleHorizontalScrollbar()
+ "set guioptions+=b
+ if &go =~# "b"
+ set go-=b
+ else
+ set go+=b
+ endif
+endfunc
+
+function ToggleHorizontalScrollbar_setKeys()
+ "Shift+F12 toggles the horizontal scrollbar
+ nnoremap <silent> <S-F12> :call ToggleHorizontalScrollbar()<CR>
+ vnoremap <silent> <S-F12> <C-C>:call ToggleHorizontalScrollbar()<CR>
+ inoremap <silent> <S-F12> <C-O>:call ToggleHorizontalScrollbar()<CR>
+endfunc
+
+au GUIEnter * call ToggleHorizontalScrollbar_setKeys()
+
+
+" Statusline (with Syntastic syntax checking)
+
+set statusline=%t%h%m%r%=[%b\ 0x%02B]\ \ \ %l,%c%V\ %P
+" Always show a status line
+set laststatus=2
+"make the command line 1 line high
+set cmdheight=1
+
+set statusline+=%#warningmsg#
+set statusline+=%{SyntasticStatuslineFlag()}
+set statusline+=%*
|
logankoester/vimrc | 4e76465b353eaedf73490d39fe937ac632f48cad | Typos in README | diff --git a/README.textile b/README.textile
index 8589e75..22a3c6c 100644
--- a/README.textile
+++ b/README.textile
@@ -1,7 +1,7 @@
h1. How to install
# Clone this repo using git
<pre>git clone git://github.com/logankoester/vimrc.git ~/projects/vimrc</pre>
-# Symlink the file to ~/.irbrc
- <pre>ln -s ~/projects/vimrc/vimrc ~/.irbrc</pre>
+# Symlink the file to ~/.vimrc
+ <pre>ln -s ~/projects/vimrc/vimrc ~/.vimrc</pre>
# Run vim and enjoy!
|
logankoester/vimrc | 2f317575ad98538d036f9523d5cadee6eb8f4ce2 | Added README | diff --git a/README.textile b/README.textile
new file mode 100644
index 0000000..8589e75
--- /dev/null
+++ b/README.textile
@@ -0,0 +1,7 @@
+h1. How to install
+
+# Clone this repo using git
+ <pre>git clone git://github.com/logankoester/vimrc.git ~/projects/vimrc</pre>
+# Symlink the file to ~/.irbrc
+ <pre>ln -s ~/projects/vimrc/vimrc ~/.irbrc</pre>
+# Run vim and enjoy!
|
DHowett/theos-modules | da9815a2b8e3e5d50104605cdf9409821d2c3d46 | [avr] AVR module. | diff --git a/avr/firmware.mk b/avr/firmware.mk
new file mode 100644
index 0000000..5bec9b5
--- /dev/null
+++ b/avr/firmware.mk
@@ -0,0 +1,7 @@
+ifeq ($(THEOS_CURRENT_INSTANCE),)
+ include $(THEOS_MODULE_PATH)/avr/master/firmware.mk
+else
+ ifeq ($(_THEOS_CURRENT_TYPE),firmware)
+ include $(THEOS_MODULE_PATH)/avr/instance/firmware.mk
+ endif
+endif
diff --git a/avr/instance/firmware.mk b/avr/instance/firmware.mk
new file mode 100644
index 0000000..94566c0
--- /dev/null
+++ b/avr/instance/firmware.mk
@@ -0,0 +1,30 @@
+ifeq ($(_THEOS_RULES_LOADED),)
+include $(THEOS_MAKE_PATH)/rules.mk
+endif
+
+_THEOS_INTERNAL_LDFLAGS += -Wl,--gc-sections -e main
+
+.PHONY: internal-firmware-all_ internal-firmware-stage_ internal-firmware-compile
+
+ifeq ($(_THEOS_MAKE_PARALLEL_BUILDING), no)
+internal-firmware-all_:: $(_OBJ_DIR_STAMPS) $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).hex
+else
+internal-firmware-all_:: $(_OBJ_DIR_STAMPS)
+ $(ECHO_NOTHING)$(MAKE) $(_THEOS_NO_PRINT_DIRECTORY_FLAG) --no-keep-going \
+ internal-firmware-compile \
+ _THEOS_CURRENT_TYPE=$(_THEOS_CURRENT_TYPE) THEOS_CURRENT_INSTANCE=$(THEOS_CURRENT_INSTANCE) _THEOS_CURRENT_OPERATION=compile \
+ THEOS_BUILD_DIR="$(THEOS_BUILD_DIR)" _THEOS_MAKE_PARALLEL=yes$(ECHO_END)
+
+internal-firmware-compile: $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).hex
+endif
+
+$(eval $(call _THEOS_TEMPLATE_DEFAULT_LINKING_RULE,$(THEOS_CURRENT_INSTANCE).elf))
+
+$(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).eep: $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).elf
+ $(ECHO_NOTHING)$(TARGET_OBJCOPY) -O ihex $(_THEOS_TARGET_EEPROM_OBJCOPYFLAGS) $< $@$(ECHO_END)
+$(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).hex: $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).elf $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).eep
+ $(ECHO_NOTHING)$(TARGET_OBJCOPY) -O ihex $(_THEOS_TARGET_OBJCOPYFLAGS) $< $@$(ECHO_END)
+
+internal-firmware-stage_::
+ #$(ECHO_NOTHING)$(THEOS_ARDUINO_TEENSY_TOOLS_PATH)/teensy_post_compile -file=$(THEOS_CURRENT_INSTANCE) -path=$(call __clean_pwd,$(THEOS_OBJ_DIR)) -tools=$(THEOS_ARDUINO_TEENSY_TOOLS_PATH)/$(ECHO_END)
+ #$(ECHO_NOTHING)$(THEOS_ARDUINO_TEENSY_TOOLS_PATH)/teensy_reboot$(ECHO_END)
diff --git a/avr/master/firmware.mk b/avr/master/firmware.mk
new file mode 100644
index 0000000..714a351
--- /dev/null
+++ b/avr/master/firmware.mk
@@ -0,0 +1,17 @@
+FIRMWARE_NAME := $(strip $(FIRMWARE_NAME))
+
+ifeq ($(_THEOS_RULES_LOADED),)
+include $(THEOS_MAKE_PATH)/rules.mk
+endif
+
+internal-all:: $(FIRMWARE_NAME:=.all.firmware.variables);
+
+internal-stage:: $(FIRMWARE_NAME:=.stage.firmware.variables);
+
+FIRMWARES_WITH_SUBPROJECTS = $(strip $(foreach firmware,$(FIRMWARE_NAME),$(patsubst %,$(firmware),$(call __schema_var_all,$(firmware)_,SUBPROJECTS))))
+ifneq ($(FIRMWARES_WITH_SUBPROJECTS),)
+internal-clean:: $(FIRMWARES_WITH_SUBPROJECTS:=.clean.firmware.subprojects)
+endif
+
+$(FIRMWARE_NAME):
+ @$(MAKE) -f $(_THEOS_PROJECT_MAKEFILE_NAME) $(_THEOS_NO_PRINT_DIRECTORY_FLAG) --no-keep-going [email protected]
diff --git a/avr/targets/avr.mk b/avr/targets/avr.mk
new file mode 100644
index 0000000..d933c4a
--- /dev/null
+++ b/avr/targets/avr.mk
@@ -0,0 +1,29 @@
+ifeq ($(_THEOS_TARGET_LOADED),)
+_THEOS_TARGET_LOADED := 1
+THEOS_TARGET_NAME := avr
+
+_THEOS_TARGET_AVR_MCU := $(__THEOS_TARGET_ARG_1)
+_THEOS_TARGET_AVR_HZ := $(__THEOS_TARGET_ARG_2)
+ifeq ($(_THEOS_TARGET_AVR_MCU),)
+$(error AVR MCU not specified as arg1 in $$(TARGET))
+endif
+ifeq ($(_THEOS_TARGET_AVR_HZ),)
+$(error AVR speed in hZ not specified as arg2 in $$(TARGET))
+endif
+
+TARGET_CC ?= avr-gcc
+TARGET_CXX ?= avr-g++
+TARGET_LD ?= avr-g++
+TARGET_OBJCOPY ?= avr-objcopy
+TARGET_STRIP ?= avr-strip
+TARGET_STRIP_FLAGS ?=
+TARGET_CODESIGN_ALLOCATE ?= ""
+override TARGET_CODESIGN :=
+TARGET_CODESIGN_FLAGS ?=
+
+_THEOS_TARGET_CFLAGS := -DF_CPU=$(_THEOS_TARGET_AVR_HZ)L -Os -ffunction-sections -fdata-sections -mmcu=$(_THEOS_TARGET_AVR_MCU) -DARDUINO=103 #-I$(THEOS_ARDUINO_CORE_PATH) -include $(THEOS_ARDUINO_CORE_PATH)/WProgram.h
+_THEOS_TARGET_CCFLAGS := -std=c++0x -felide-constructors -fno-exceptions -fno-rtti
+_THEOS_TARGET_LDFLAGS := -fdata-sections -ffunction-sections -Os -mmcu=$(_THEOS_TARGET_AVR_MCU)
+_THEOS_TARGET_EEPROM_OBJCOPYFLAGS := -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0
+_THEOS_TARGET_OBJCOPYFLAGS := -R .eeprom
+endif
|
DHowett/theos-modules | 6965c4fdd0e918dc7438c92024019a3e5fd223a7 | [congruence] Add support for CoreData data models, specified in xxx_DATA_MODELS. Uses momc. Switch to xcrun for ibtool. | diff --git a/congruence/instance/rules.mk b/congruence/instance/rules.mk
index cbbcc71..93dba30 100644
--- a/congruence/instance/rules.mk
+++ b/congruence/instance/rules.mk
@@ -1,9 +1,13 @@
NIB_FILES = $(strip $(patsubst %.xib,%.nib,$($(THEOS_CURRENT_INSTANCE)_XIBS)))
NIB_FILES_TO_USE = $(strip $(addprefix $(THEOS_OBJ_DIR)/,$(NIB_FILES)))
_NIB_DIR_STAMPS = $(sort $(foreach o,$(filter $(THEOS_OBJ_DIR)%,$(NIB_FILES_TO_USE)),$(dir $o).stamp))
-ifneq ($(NIB_FILES_TO_USE),)
-after-$(THEOS_CURRENT_INSTANCE)-all:: $(_NIB_DIR_STAMPS) $(NIB_FILES_TO_USE)
-after-$(THEOS_CURRENT_INSTANCE)-stage:: $(NIB_FILES_TO_USE)
- @cp $(NIB_FILES_TO_USE) $(THEOS_SHARED_BUNDLE_RESOURCE_PATH)/
+DATA_MODELS = $(strip $(patsubst %.xcdatamodeld,%.momd,$($(THEOS_CURRENT_INSTANCE)_DATA_MODELS)))
+DATA_MODELS_TO_USE = $(strip $(addprefix $(THEOS_OBJ_DIR)/,$(DATA_MODELS)))
+_DATA_MODEL_DIR_STAMPS = $(sort $(foreach o,$(filter $(THEOS_OBJ_DIR)%,$(DATA_MODELS_TO_USE)),$(dir $o).stamp))
+
+ifneq ($(NIB_FILES_TO_USE)$(DATA_MODELS_TO_USE),)
+after-$(THEOS_CURRENT_INSTANCE)-all:: $(_NIB_DIR_STAMPS) $(NIB_FILES_TO_USE) $(_DATA_MODEL_DIR_STAMPS) $(DATA_MODELS_TO_USE)
+after-$(THEOS_CURRENT_INSTANCE)-stage:: $(NIB_FILES_TO_USE) $(DATA_MODELS_TO_USE)
+ @cp -a $(DATA_MODELS_TO_USE) $(NIB_FILES_TO_USE) $(THEOS_SHARED_BUNDLE_RESOURCE_PATH)/
endif
diff --git a/congruence/rules.mk b/congruence/rules.mk
index 91b8abf..16f4690 100644
--- a/congruence/rules.mk
+++ b/congruence/rules.mk
@@ -1,2 +1,5 @@
$(THEOS_OBJ_DIR)/%.nib: %.xib
- $(ECHO_COMPILING)ibtool --compile $@ $<$(ECHO_END)
+ $(ECHO_COMPILING)xcrun -sdk iphoneos ibtool --compile "$@" "$<"$(ECHO_END)
+
+$(THEOS_OBJ_DIR)/%.momd: %.xcdatamodeld
+ $(ECHO_COMPILING)xcrun -sdk iphoneos momc -XD_MOMC_SDKROOT="$(SYSROOT)" -XD_MOMC_IOS_TARGET_VERSION=$(_THEOS_TARGET_SDK_VERSION) -MOMC_PLATFORMS iphoneos -XD_MOMC_TARGET_VERSION="10.6" "$(shell unset CDPATH; cd $(dir $<); pwd)/$(notdir $<)" "$(shell unset CDPATH; cd $(dir $@); pwd)/$(notdir $@)"$(ECHO_END)
|
DHowett/theos-modules | f24f578ca1dee7b942e2aff604731cd4e8e84939 | [java] Set sourcepath, and touch AFTER compilation (so a failure doesn't make theos skip the file next time. Also depend on _OBJ_DIR_STAMPS. | diff --git a/java/instance/jar.mk b/java/instance/jar.mk
index da194bf..af64a39 100644
--- a/java/instance/jar.mk
+++ b/java/instance/jar.mk
@@ -1,37 +1,37 @@
ifeq ($(_THEOS_RULES_LOADED),)
include $(THEOS_MAKE_PATH)/rules.mk
endif
.PHONY: internal-jar-all_ internal-jar-stage_ internal-jar-compile
ifeq ($(_THEOS_MAKE_PARALLEL_BUILDING), no)
-internal-jar-all_:: $(THEOS_CLASSES_DIR) $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar
+internal-jar-all_:: $(_OBJ_DIR_STAMPS) $(THEOS_CLASSES_DIR) $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar
else
-internal-jar-all_:: $(THEOS_CLASSES_DIR)
+internal-jar-all_:: $(_OBJ_DIR_STAMPS) $(THEOS_CLASSES_DIR)
$(ECHO_NOTHING)$(MAKE) --no-print-directory --no-keep-going \
internal-jar-compile \
_THEOS_CURRENT_TYPE=$(_THEOS_CURRENT_TYPE) THEOS_CURRENT_INSTANCE=$(THEOS_CURRENT_INSTANCE) _THEOS_CURRENT_OPERATION=compile \
THEOS_BUILD_DIR="$(THEOS_BUILD_DIR)" _THEOS_MAKE_PARALLEL=yes$(ECHO_END)
internal-jar-compile: $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar
endif
_RESOURCE_DIRS := $(or $($(THEOS_CURRENT_INSTANCE)_JAR_RESOURCE_DIRS),$($(THEOS_CURRENT_INSTANCE)_RESOURCE_DIRS))
_MAIN_CLASS=$(or $($(THEOS_CURRENT_INSTANCE)_MAIN_CLASS),$(patsubst %.java,%,$(firstword $($(THEOS_CURRENT_INSTANCE)_FILES))))
# $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).manifest
$(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar: $(OBJ_FILES_TO_LINK)
$(ECHO_JARRING)jar cfe $@ $(_MAIN_CLASS) -C $(THEOS_CLASSES_DIR) .$(ECHO_END)
ifneq ($(_RESOURCE_DIRS),)
$(ECHO_COPYING_RESOURCE_DIRS)for d in $(_RESOURCE_DIRS); do \
if [ -d "$$d" ]; then \
( cd $$d; jar uf ../$@ .; ); \
else \
echo "Warning: ignoring missing bundle resource directory $$d."; \
fi; \
done$(ECHO_END)
endif
internal-jar-stage_::
$(ECHO_NOTHING)cp $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar "$(THEOS_STAGING_DIR)"$(ECHO_END)
diff --git a/java/rules.mk b/java/rules.mk
index f9a09ba..cbe199f 100644
--- a/java/rules.mk
+++ b/java/rules.mk
@@ -1,10 +1,10 @@
ALL_JAVACFLAGS = $(INTERNAL_JAVACFLAGS) $(TARGET_JAVAC_ARGS) $(ADDITIONAL_JAVACFLAGS) $(AUXILIARY_JAVACFLAGS) $(JAVACFLAGS)
.SUFFIXES: .java
$(THEOS_OBJ_DIR)/%.java.o: %.java
+ $(ECHO_COMPILING)$(TARGET_JAVAC) -sourcepath $(THEOS_PROJECT_DIR) $(ALL_JAVACFLAGS) -d $(THEOS_CLASSES_DIR)/ $^$(ECHO_END)
@touch $@
- $(ECHO_COMPILING)$(TARGET_JAVAC) $(ALL_JAVACFLAGS) -d $(THEOS_CLASSES_DIR)/ $^$(ECHO_END)
$(THEOS_CLASSES_DIR): $(THEOS_OBJ_DIR)
@cd $(THEOS_OBJ_DIR); mkdir -p $(THEOS_CLASSES_DIR_NAME)
|
DHowett/theos-modules | 3964252bd3d9f0cef509d154a2911849b33e4ac5 | [java] Make JAVACFLAGS a lot more like CFLAGS from stock Theos. | diff --git a/java/instance/rules.mk b/java/instance/rules.mk
index 6145087..f145a7d 100644
--- a/java/instance/rules.mk
+++ b/java/instance/rules.mk
@@ -1,2 +1,4 @@
JAVA_CLASSES = $(patsubst %.java,$(THEOS_OBJ_DIR)/%.java.stamp,$($(THEOS_CURRENT_INSTANCE)_JAVA_FILES))
OBJ_FILES_TO_LINK += $(JAVA_CLASSES)
+
+ADDITIONAL_JAVACFLAGS += $($(THEOS_CURRENT_INSTANCE)_JAVACFLAGS)
diff --git a/java/rules.mk b/java/rules.mk
index d488c99..f9a09ba 100644
--- a/java/rules.mk
+++ b/java/rules.mk
@@ -1,8 +1,10 @@
+ALL_JAVACFLAGS = $(INTERNAL_JAVACFLAGS) $(TARGET_JAVAC_ARGS) $(ADDITIONAL_JAVACFLAGS) $(AUXILIARY_JAVACFLAGS) $(JAVACFLAGS)
+
.SUFFIXES: .java
$(THEOS_OBJ_DIR)/%.java.o: %.java
@touch $@
- $(ECHO_COMPILING)$(TARGET_JAVAC) $(TARGET_JAVAC_ARGS) -d $(THEOS_CLASSES_DIR)/ $^$(ECHO_END)
+ $(ECHO_COMPILING)$(TARGET_JAVAC) $(ALL_JAVACFLAGS) -d $(THEOS_CLASSES_DIR)/ $^$(ECHO_END)
$(THEOS_CLASSES_DIR): $(THEOS_OBJ_DIR)
@cd $(THEOS_OBJ_DIR); mkdir -p $(THEOS_CLASSES_DIR_NAME)
|
DHowett/theos-modules | fa7422ca969fb899657a1a2b0c001afdb9768e08 | [java] I forgot the java target. | diff --git a/java/targets/java.mk b/java/targets/java.mk
new file mode 100644
index 0000000..bb78311
--- /dev/null
+++ b/java/targets/java.mk
@@ -0,0 +1,10 @@
+ifeq ($(_THEOS_TARGET_LOADED),)
+_THEOS_TARGET_LOADED := 1
+THEOS_TARGET_NAME := java
+
+TARGET_JAVAC ?= javac
+#TARGET_JAVAC_ARGS ?= -bootclasspath $(BOOTCLASSPATH)
+TARGET_JARSIGNER ?= jarsigner
+TARGET_KEYTOOL ?= keytool
+
+endif
|
DHowett/theos-modules | 22221b8ad47dc1876e56b795e15755ef84407a8c | [java] Add the Darwin platform override. | diff --git a/java/platform/Darwin.mk b/java/platform/Darwin.mk
new file mode 100644
index 0000000..1a2c902
--- /dev/null
+++ b/java/platform/Darwin.mk
@@ -0,0 +1 @@
+_THEOS_PLATFORM_DEFAULT_TARGET = java
|
DHowett/theos-modules | 18dc0f2677b4e6d72ba6adf64c0737aedcc70806 | [java] Various updates to the java module. | diff --git a/java/apk.mk b/java/apk.mk
index 8741f07..73773fb 100644
--- a/java/apk.mk
+++ b/java/apk.mk
@@ -1,7 +1,7 @@
-ifeq ($(FW_INSTANCE),)
- include $(FW_MODDIR)/java/master/apk.mk
+ifeq ($(THEOS_CURRENT_INSTANCE),)
+ include $(THEOS_MODULE_PATH)/java/master/apk.mk
else
- ifeq ($(FW_TYPE),apk)
- include $(FW_MODDIR)/java/instance/apk.mk
+ ifeq ($(_THEOS_CURRENT_TYPE),apk)
+ include $(THEOS_MODULE_PATH)/java/instance/apk.mk
endif
endif
diff --git a/java/common.mk b/java/common.mk
index 9474930..c6bff7b 100644
--- a/java/common.mk
+++ b/java/common.mk
@@ -1,16 +1,18 @@
-FW_CLASSES_DIR_NAME = classes
-FW_CLASSES_DIR = $(FW_OBJ_DIR)/$(FW_CLASSES_DIR_NAME)
+THEOS_CLASSES_DIR_NAME = classes
+THEOS_CLASSES_DIR = $(THEOS_OBJ_DIR)/$(THEOS_CLASSES_DIR_NAME)
ifneq ($(messages),yes)
+ ECHO_JARRING = @(echo " Jarring $(THEOS_CURRENT_INSTANCE)...";
ECHO_RESOURCES = @(echo " Processing Resources...";
ECHO_RJAVA = @(echo " Compiling R.java...";
ECHO_DEXING = @(echo " Converting to Dalvik bytecode...";
- ECHO_PACKING = @(echo " Packing $(FW_INSTANCE)...";
- ECHO_ALIGNING = @(echo " Aligning $(FW_INSTANCE)...";
+ ECHO_PACKING = @(echo " Packing $(THEOS_CURRENT_INSTANCE)...";
+ ECHO_ALIGNING = @(echo " Aligning $(THEOS_CURRENT_INSTANCE)...";
else
+ ECHO_JARRING =
ECHO_RESOURCES =
ECHO_RJAVA =
ECHO_DEXING =
ECHO_PACKING =
ECHO_ALIGNING =
endif
diff --git a/java/instance/apk.mk b/java/instance/apk.mk
index 5a020a7..0e72992 100644
--- a/java/instance/apk.mk
+++ b/java/instance/apk.mk
@@ -1,38 +1,38 @@
-ifeq ($(FW_RULES_LOADED),)
-include $(FW_MAKEDIR)/rules.mk
+ifeq ($(_THEOS_RULES_LOADED),)
+include $(THEOS_MAKE_PATH)/rules.mk
endif
.PHONY: internal-apk-all_ internal-apk-stage_ internal-apk-compile
-ifeq ($(FW_MAKE_PARALLEL_BUILDING), no)
-internal-apk-all_:: $(FW_OBJ_DIR) $(FW_CLASSES_DIR) $(FW_OBJ_DIR)/$(FW_INSTANCE).apk
+ifeq ($(_THEOS_MAKE_PARALLEL_BUILDING), no)
+internal-apk-all_:: $(THEOS_OBJ_DIR) $(THEOS_CLASSES_DIR) $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).apk
else
-internal-apk-all_:: $(FW_OBJ_DIR) $(FW_CLASSES_DIR)
+internal-apk-all_:: $(THEOS_OBJ_DIR) $(THEOS_CLASSES_DIR)
$(ECHO_NOTHING)$(MAKE) --no-print-directory --no-keep-going \
internal-apk-compile \
- FW_TYPE=$(FW_TYPE) FW_INSTANCE=$(FW_INSTANCE) FW_OPERATION=compile \
- FW_BUILD_DIR="$(FW_BUILD_DIR)" _FW_MAKE_PARALLEL=yes$(ECHO_END)
+ _THEOS_CURRENT_TYPE=$(_THEOS_CURRENT_TYPE) THEOS_CURRENT_INSTANCE=$(THEOS_CURRENT_INSTANCE) _THEOS_CURRENT_OPERATION=compile \
+ THEOS_BUILD_DIR="$(THEOS_BUILD_DIR)" _THEOS_MAKE_PARALLEL=yes$(ECHO_END)
-internal-apk-compile: $(FW_OBJ_DIR)/$(FW_INSTANCE).apk
+internal-apk-compile: $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).apk
endif
-# $(FW_OBJ_DIR)/$(FW_INSTANCE).manifest
-$(FW_OBJ_DIR)/res.zip.stamp: res
+# $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).manifest
+$(THEOS_OBJ_DIR)/res.zip.stamp: res
@touch $@
- $(ECHO_RESOURCES)$(TARGET_AAPT) package -f -M AndroidManifest.xml -F $(FW_OBJ_DIR)/res.zip -I $(BOOTCLASSPATH) -S res -J $(FW_OBJ_DIR)$(ECHO_END)
+ $(ECHO_RESOURCES)$(TARGET_AAPT) package -f -M AndroidManifest.xml -F $(THEOS_OBJ_DIR)/res.zip -I $(BOOTCLASSPATH) -S res -J $(THEOS_OBJ_DIR)$(ECHO_END)
-$(FW_OBJ_DIR)/R.java.stamp: $(FW_OBJ_DIR)/res.zip.stamp
+$(THEOS_OBJ_DIR)/R.java.stamp: $(THEOS_OBJ_DIR)/res.zip.stamp
@touch $@
- $(ECHO_RJAVA)$(TARGET_JAVAC) $(TARGET_JAVAC_ARGS) -d $(FW_CLASSES_DIR)/ $(FW_OBJ_DIR)/R.java$(ECHO_END)
+ $(ECHO_RJAVA)$(TARGET_JAVAC) $(TARGET_JAVAC_ARGS) -d $(THEOS_CLASSES_DIR)/ $(THEOS_OBJ_DIR)/R.java$(ECHO_END)
-$(FW_OBJ_DIR)/classes.dex: $(OBJ_FILES_TO_LINK)
- $(ECHO_DEXING)$(TARGET_DX) --dex --output=$@ $(FW_CLASSES_DIR)$(ECHO_END)
+$(THEOS_OBJ_DIR)/classes.dex: $(OBJ_FILES_TO_LINK)
+ $(ECHO_DEXING)$(TARGET_DX) --dex --output=$@ $(THEOS_CLASSES_DIR)$(ECHO_END)
-$(FW_OBJ_DIR)/$(FW_INSTANCE).unsigned.apk: AndroidManifest.xml $(FW_OBJ_DIR)/res.zip.stamp $(FW_OBJ_DIR)/R.java.stamp $(FW_OBJ_DIR)/classes.dex
- $(ECHO_PACKING)$(TARGET_APKBUILDER) $@ -u -z $(FW_OBJ_DIR)/res.zip -f $(FW_OBJ_DIR)/classes.dex$(ECHO_END)
+$(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).unsigned.apk: AndroidManifest.xml $(THEOS_OBJ_DIR)/res.zip.stamp $(THEOS_OBJ_DIR)/R.java.stamp $(THEOS_OBJ_DIR)/classes.dex
+ $(ECHO_PACKING)$(TARGET_APKBUILDER) $@ -u -z $(THEOS_OBJ_DIR)/res.zip -f $(THEOS_OBJ_DIR)/classes.dex$(ECHO_END)
-$(FW_OBJ_DIR)/$(FW_INSTANCE).apk: $(TARGET_DEBUG_KEYSTORE) $(FW_OBJ_DIR)/$(FW_INSTANCE).unsigned.apk
- $(ECHO_SIGNING)$(TARGET_JARSIGNER) -keystore $(TARGET_DEBUG_KEYSTORE) -storepass android -keypass android -signedjar $(FW_OBJ_DIR)/$(FW_INSTANCE).unaligned.apk $(FW_OBJ_DIR)/$(FW_INSTANCE).unsigned.apk androiddebugkey$(ECHO_END)
- $(ECHO_ALIGNING)$(TARGET_ZIPALIGN) -f 4 $(FW_OBJ_DIR)/$(FW_INSTANCE).unaligned.apk $@$(ECHO_END)
+$(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).apk: $(TARGET_DEBUG_KEYSTORE) $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).unsigned.apk
+ $(ECHO_SIGNING)$(TARGET_JARSIGNER) -keystore $(TARGET_DEBUG_KEYSTORE) -storepass android -keypass android -signedjar $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).unaligned.apk $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).unsigned.apk androiddebugkey$(ECHO_END)
+ $(ECHO_ALIGNING)$(TARGET_ZIPALIGN) -f 4 $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).unaligned.apk $@$(ECHO_END)
internal-apk-stage_::
- $(ECHO_NOTHING)cp $(FW_OBJ_DIR)/$(FW_INSTANCE).apk "$(FW_STAGING_DIR)"$(ECHO_END)
+ $(ECHO_NOTHING)cp $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).apk "$(THEOS_STAGING_DIR)"$(ECHO_END)
diff --git a/java/instance/jar.mk b/java/instance/jar.mk
index 72cdbb5..da194bf 100644
--- a/java/instance/jar.mk
+++ b/java/instance/jar.mk
@@ -1,23 +1,37 @@
-ifeq ($(FW_RULES_LOADED),)
-include $(FW_MAKEDIR)/rules.mk
+ifeq ($(_THEOS_RULES_LOADED),)
+include $(THEOS_MAKE_PATH)/rules.mk
endif
.PHONY: internal-jar-all_ internal-jar-stage_ internal-jar-compile
-ifeq ($(FW_MAKE_PARALLEL_BUILDING), no)
-internal-jar-all_:: $(FW_CLASSES_DIR) $(FW_OBJ_DIR)/$(FW_INSTANCE).jar
+ifeq ($(_THEOS_MAKE_PARALLEL_BUILDING), no)
+internal-jar-all_:: $(THEOS_CLASSES_DIR) $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar
else
-internal-jar-all_:: $(FW_CLASSES_DIR)
+internal-jar-all_:: $(THEOS_CLASSES_DIR)
$(ECHO_NOTHING)$(MAKE) --no-print-directory --no-keep-going \
internal-jar-compile \
- FW_TYPE=$(FW_TYPE) FW_INSTANCE=$(FW_INSTANCE) FW_OPERATION=compile \
- FW_BUILD_DIR="$(FW_BUILD_DIR)" _FW_MAKE_PARALLEL=yes$(ECHO_END)
+ _THEOS_CURRENT_TYPE=$(_THEOS_CURRENT_TYPE) THEOS_CURRENT_INSTANCE=$(THEOS_CURRENT_INSTANCE) _THEOS_CURRENT_OPERATION=compile \
+ THEOS_BUILD_DIR="$(THEOS_BUILD_DIR)" _THEOS_MAKE_PARALLEL=yes$(ECHO_END)
-internal-jar-compile: $(FW_OBJ_DIR)/$(FW_INSTANCE).jar
+internal-jar-compile: $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar
+endif
+
+_RESOURCE_DIRS := $(or $($(THEOS_CURRENT_INSTANCE)_JAR_RESOURCE_DIRS),$($(THEOS_CURRENT_INSTANCE)_RESOURCE_DIRS))
+
+_MAIN_CLASS=$(or $($(THEOS_CURRENT_INSTANCE)_MAIN_CLASS),$(patsubst %.java,%,$(firstword $($(THEOS_CURRENT_INSTANCE)_FILES))))
+
+# $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).manifest
+$(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar: $(OBJ_FILES_TO_LINK)
+ $(ECHO_JARRING)jar cfe $@ $(_MAIN_CLASS) -C $(THEOS_CLASSES_DIR) .$(ECHO_END)
+ifneq ($(_RESOURCE_DIRS),)
+ $(ECHO_COPYING_RESOURCE_DIRS)for d in $(_RESOURCE_DIRS); do \
+ if [ -d "$$d" ]; then \
+ ( cd $$d; jar uf ../$@ .; ); \
+ else \
+ echo "Warning: ignoring missing bundle resource directory $$d."; \
+ fi; \
+ done$(ECHO_END)
endif
-# $(FW_OBJ_DIR)/$(FW_INSTANCE).manifest
-$(FW_OBJ_DIR)/$(FW_INSTANCE).jar: $(OBJ_FILES_TO_LINK)
- @(echo " Jarring $(FW_INSTANCE).jar..."; jar cfe $@ $($(FW_INSTANCE)_MAIN_CLASS) -C $(FW_CLASSES_DIR) .)
internal-jar-stage_::
- $(ECHO_NOTHING)cp $(FW_OBJ_DIR)/$(FW_INSTANCE).jar "$(FW_STAGING_DIR)"$(ECHO_END)
+ $(ECHO_NOTHING)cp $(THEOS_OBJ_DIR)/$(THEOS_CURRENT_INSTANCE).jar "$(THEOS_STAGING_DIR)"$(ECHO_END)
diff --git a/java/instance/rules.mk b/java/instance/rules.mk
index 1d9eacb..6145087 100644
--- a/java/instance/rules.mk
+++ b/java/instance/rules.mk
@@ -1,2 +1,2 @@
-JAVA_CLASSES = $(patsubst %.java,$(FW_OBJ_DIR)/%.java.stamp,$($(FW_INSTANCE)_JAVA_FILES))
+JAVA_CLASSES = $(patsubst %.java,$(THEOS_OBJ_DIR)/%.java.stamp,$($(THEOS_CURRENT_INSTANCE)_JAVA_FILES))
OBJ_FILES_TO_LINK += $(JAVA_CLASSES)
diff --git a/java/jar.mk b/java/jar.mk
index d525c41..e00df7f 100644
--- a/java/jar.mk
+++ b/java/jar.mk
@@ -1,7 +1,7 @@
-ifeq ($(FW_INSTANCE),)
- include $(FW_MODDIR)/java/master/jar.mk
+ifeq ($(THEOS_CURRENT_INSTANCE),)
+ include $(THEOS_MODULE_PATH)/java/master/jar.mk
else
- ifeq ($(FW_TYPE),jar)
- include $(FW_MODDIR)/java/instance/jar.mk
+ ifeq ($(_THEOS_CURRENT_TYPE),jar)
+ include $(THEOS_MODULE_PATH)/java/instance/jar.mk
endif
endif
diff --git a/java/master/apk.mk b/java/master/apk.mk
index 4f90d37..2482a8b 100644
--- a/java/master/apk.mk
+++ b/java/master/apk.mk
@@ -1,14 +1,14 @@
APK_NAME := $(strip $(APK_NAME))
-ifeq ($(FW_RULES_LOADED),)
-include $(FW_MAKEDIR)/rules.mk
+ifeq ($(_THEOS_RULES_LOADED),)
+include $(THEOS_MAKE_PATH)/rules.mk
endif
internal-all:: $(APK_NAME:=.all.apk.variables);
internal-stage:: $(APK_NAME:=.stage.apk.variables);
internal-after-install::
$(APK_NAME):
@$(MAKE) --no-print-directory --no-keep-going [email protected]
diff --git a/java/master/jar.mk b/java/master/jar.mk
index 9d4b9b3..29c9272 100644
--- a/java/master/jar.mk
+++ b/java/master/jar.mk
@@ -1,14 +1,14 @@
JAR_NAME := $(strip $(JAR_NAME))
-ifeq ($(FW_RULES_LOADED),)
-include $(FW_MAKEDIR)/rules.mk
+ifeq ($(_THEOS_RULES_LOADED),)
+include $(THEOS_MAKE_PATH)/rules.mk
endif
internal-all:: $(JAR_NAME:=.all.jar.variables);
internal-stage:: $(JAR_NAME:=.stage.jar.variables);
internal-after-install::
$(JAR_NAME):
@$(MAKE) --no-print-directory --no-keep-going [email protected]
diff --git a/java/rules.mk b/java/rules.mk
index 093c995..d488c99 100644
--- a/java/rules.mk
+++ b/java/rules.mk
@@ -1,8 +1,8 @@
.SUFFIXES: .java
-$(FW_OBJ_DIR)/%.java.stamp: %.java
+$(THEOS_OBJ_DIR)/%.java.o: %.java
@touch $@
- $(ECHO_COMPILING)$(TARGET_JAVAC) $(TARGET_JAVAC_ARGS) -d $(FW_CLASSES_DIR)/ $^$(ECHO_END)
+ $(ECHO_COMPILING)$(TARGET_JAVAC) $(TARGET_JAVAC_ARGS) -d $(THEOS_CLASSES_DIR)/ $^$(ECHO_END)
-$(FW_CLASSES_DIR): $(FW_OBJ_DIR)
- @cd $(FW_OBJ_DIR); mkdir -p $(FW_CLASSES_DIR_NAME)
+$(THEOS_CLASSES_DIR): $(THEOS_OBJ_DIR)
+ @cd $(THEOS_OBJ_DIR); mkdir -p $(THEOS_CLASSES_DIR_NAME)
diff --git a/java/targets/android.mk b/java/targets/android.mk
index cd98ca5..83ce0d0 100644
--- a/java/targets/android.mk
+++ b/java/targets/android.mk
@@ -1,30 +1,30 @@
-ifeq ($(FW_TARGET_LOADED),)
-FW_TARGET_LOADED := 1
-FW_TARGET_NAME := android
+ifeq ($(_THEOS_TARGET_LOADED),)
+_THEOS_TARGET_LOADED := 1
+THEOS_TARGET_NAME := android
SDK_ROOT ?= /opt/android-sdk
-SDKVERSION ?= 7
+SDKVERSION ?= 8
PLATFORM_ROOT ?= $(SDK_ROOT)/platforms/android-$(SDKVERSION)
BOOTCLASSPATH = $(PLATFORM_ROOT)/android.jar
TARGET_JAVAC ?= javac
TARGET_JAVAC_ARGS ?= -bootclasspath $(BOOTCLASSPATH)
TARGET_JARSIGNER ?= jarsigner
TARGET_KEYTOOL ?= keytool
-TARGET_AAPT ?= $(PLATFORM_ROOT)/tools/aapt
-TARGET_DX ?= $(PLATFORM_ROOT)/tools/dx
+TARGET_AAPT ?= $(SDK_ROOT)/platform-tools/aapt
+TARGET_DX ?= $(SDK_ROOT)/platform-tools/dx
TARGET_APKBUILDER ?= $(SDK_ROOT)/tools/apkbuilder
TARGET_ZIPALIGN ?= $(SDK_ROOT)/tools/zipalign
TARGET_DEBUG_KEYSTORE_DIR ?= $(HOME)/.android
TARGET_DEBUG_KEYSTORE ?= $(TARGET_DEBUG_KEYSTORE_DIR)/debug.keystore
all::
$(TARGET_DEBUG_KEYSTORE_DIR):
@mkdir -p $@
$(TARGET_DEBUG_KEYSTORE): $(TARGET_DEBUG_KEYSTORE_DIR)
$(ECHO_NOTHING)$(TARGET_KEYTOOL) -genkeypair -dname "CN=Android Debug,O=Android,C=US" -validity 365 -alias "androiddebugkey" -keypass "android" -keystore $@ -storepass "android"$(ECHO_END)
endif
|
DHowett/theos-modules | 72e94f5c733e0db60a5e91d50f2602f834fd4f17 | [congruence] Variable reform updates (how did I miss this one? I even wrote it post-reform!) and fix a stupid typo in DIR_STAMPS. | diff --git a/congruence/instance/rules.mk b/congruence/instance/rules.mk
index 0a7119f..cbbcc71 100644
--- a/congruence/instance/rules.mk
+++ b/congruence/instance/rules.mk
@@ -1,9 +1,9 @@
NIB_FILES = $(strip $(patsubst %.xib,%.nib,$($(THEOS_CURRENT_INSTANCE)_XIBS)))
NIB_FILES_TO_USE = $(strip $(addprefix $(THEOS_OBJ_DIR)/,$(NIB_FILES)))
_NIB_DIR_STAMPS = $(sort $(foreach o,$(filter $(THEOS_OBJ_DIR)%,$(NIB_FILES_TO_USE)),$(dir $o).stamp))
ifneq ($(NIB_FILES_TO_USE),)
-after-$(THEOS_CURRENT_INSTANCE)-all:: $(_XIB_DIR_STAMPS) $(NIB_FILES_TO_USE)
+after-$(THEOS_CURRENT_INSTANCE)-all:: $(_NIB_DIR_STAMPS) $(NIB_FILES_TO_USE)
after-$(THEOS_CURRENT_INSTANCE)-stage:: $(NIB_FILES_TO_USE)
@cp $(NIB_FILES_TO_USE) $(THEOS_SHARED_BUNDLE_RESOURCE_PATH)/
endif
diff --git a/congruence/rules.mk b/congruence/rules.mk
index 5c569c9..91b8abf 100644
--- a/congruence/rules.mk
+++ b/congruence/rules.mk
@@ -1,2 +1,2 @@
-$(FW_OBJ_DIR)/%.nib: %.xib
+$(THEOS_OBJ_DIR)/%.nib: %.xib
$(ECHO_COMPILING)ibtool --compile $@ $<$(ECHO_END)
|
DHowett/theos-modules | a372d4a58cba09b4672398fb52ef9f37cea6bd23 | [install] Update for variable reform, and automatically determine the number of jobs to use. | diff --git a/install/master/rules.mk b/install/master/rules.mk
index bf86174..4a2209c 100644
--- a/install/master/rules.mk
+++ b/install/master/rules.mk
@@ -1,16 +1,16 @@
-ifeq ($(FW_DEVICE_IPS),)
+ifeq ($(THEOS_DEVICE_IPS),)
installs:
- @echo "make installs requires that you set FW_DEVICE_IPS to a space-delimited list of devices to install to."; exit 1
+ @echo "make installs requires that you set THEOS_DEVICE_IPS to a space-delimited list of devices to install to."; exit 1
else
installs:
- @$(MAKE) --no-print-directory --no-keep-going mod-internal-installs _FW_MAKE_PARALLEL=yes _FW_DEVICE_IPS="$(FW_DEVICE_IPS)"
+ @$(MAKE) -j$(words $(THEOS_DEVICE_IPS)) --no-print-directory --no-keep-going mod-internal-installs _THEOS_MAKE_PARALLEL=yes _THEOS_DEVICE_IPS="$(THEOS_DEVICE_IPS)"
endif
-mod-internal-installs: $(foreach i,$(_FW_DEVICE_IPS),$(i).install)
+mod-internal-installs: $(foreach i,$(_THEOS_DEVICE_IPS),$(i).install)
%.install:
@ \
in="$@"; \
ip=$${in%.install}; \
echo Making install for $$ip; \
- $(MAKE) --no-print-directory --no-keep-going install FW_DEVICE_IP=$$ip _FW_TOP_INVOCATION_DONE=""
+ $(MAKE) --no-print-directory --no-keep-going install THEOS_DEVICE_IP=$$ip _THEOS_TOP_INVOCATION_DONE=""
|
DHowett/theos-modules | 4d38df67fceff5915915e8c9ab448da33bee4e8d | Experimental congruence module, adding support for Interface Builder NIBs. | diff --git a/congruence/instance/rules.mk b/congruence/instance/rules.mk
new file mode 100644
index 0000000..0a7119f
--- /dev/null
+++ b/congruence/instance/rules.mk
@@ -0,0 +1,9 @@
+NIB_FILES = $(strip $(patsubst %.xib,%.nib,$($(THEOS_CURRENT_INSTANCE)_XIBS)))
+NIB_FILES_TO_USE = $(strip $(addprefix $(THEOS_OBJ_DIR)/,$(NIB_FILES)))
+_NIB_DIR_STAMPS = $(sort $(foreach o,$(filter $(THEOS_OBJ_DIR)%,$(NIB_FILES_TO_USE)),$(dir $o).stamp))
+
+ifneq ($(NIB_FILES_TO_USE),)
+after-$(THEOS_CURRENT_INSTANCE)-all:: $(_XIB_DIR_STAMPS) $(NIB_FILES_TO_USE)
+after-$(THEOS_CURRENT_INSTANCE)-stage:: $(NIB_FILES_TO_USE)
+ @cp $(NIB_FILES_TO_USE) $(THEOS_SHARED_BUNDLE_RESOURCE_PATH)/
+endif
diff --git a/congruence/rules.mk b/congruence/rules.mk
new file mode 100644
index 0000000..5c569c9
--- /dev/null
+++ b/congruence/rules.mk
@@ -0,0 +1,2 @@
+$(FW_OBJ_DIR)/%.nib: %.xib
+ $(ECHO_COMPILING)ibtool --compile $@ $<$(ECHO_END)
diff --git a/java/instance/jar.mk b/java/instance/jar.mk
index f714caf..72cdbb5 100644
--- a/java/instance/jar.mk
+++ b/java/instance/jar.mk
@@ -1,23 +1,23 @@
ifeq ($(FW_RULES_LOADED),)
include $(FW_MAKEDIR)/rules.mk
endif
.PHONY: internal-jar-all_ internal-jar-stage_ internal-jar-compile
ifeq ($(FW_MAKE_PARALLEL_BUILDING), no)
-internal-jar-all_:: $(FW_OBJ_DIR) $(FW_OBJ_DIR)/$(FW_INSTANCE).jar
+internal-jar-all_:: $(FW_CLASSES_DIR) $(FW_OBJ_DIR)/$(FW_INSTANCE).jar
else
-internal-jar-all_:: $(FW_OBJ_DIR)
+internal-jar-all_:: $(FW_CLASSES_DIR)
$(ECHO_NOTHING)$(MAKE) --no-print-directory --no-keep-going \
internal-jar-compile \
FW_TYPE=$(FW_TYPE) FW_INSTANCE=$(FW_INSTANCE) FW_OPERATION=compile \
FW_BUILD_DIR="$(FW_BUILD_DIR)" _FW_MAKE_PARALLEL=yes$(ECHO_END)
internal-jar-compile: $(FW_OBJ_DIR)/$(FW_INSTANCE).jar
endif
# $(FW_OBJ_DIR)/$(FW_INSTANCE).manifest
$(FW_OBJ_DIR)/$(FW_INSTANCE).jar: $(OBJ_FILES_TO_LINK)
- @(echo " Jarring $(FW_INSTANCE).jar..."; cd $(FW_CLASSES_DIR); jar cfe ../$(FW_INSTANCE).jar $($(FW_INSTANCE)_MAIN_CLASS) $(subst $(FW_CLASSES_DIR)/,,$(OBJ_FILES_TO_LINK)) )
+ @(echo " Jarring $(FW_INSTANCE).jar..."; jar cfe $@ $($(FW_INSTANCE)_MAIN_CLASS) -C $(FW_CLASSES_DIR) .)
internal-jar-stage_::
$(ECHO_NOTHING)cp $(FW_OBJ_DIR)/$(FW_INSTANCE).jar "$(FW_STAGING_DIR)"$(ECHO_END)
|
DHowett/theos-modules | d36502dc31784795ed0cf4013fdc2240f4754026 | Include an 'install' module which provides a parallelized 'make installs' - runs make install for everything in FW_DEVICE_IPS. | diff --git a/install/master/rules.mk b/install/master/rules.mk
new file mode 100644
index 0000000..bf86174
--- /dev/null
+++ b/install/master/rules.mk
@@ -0,0 +1,16 @@
+ifeq ($(FW_DEVICE_IPS),)
+installs:
+ @echo "make installs requires that you set FW_DEVICE_IPS to a space-delimited list of devices to install to."; exit 1
+else
+installs:
+ @$(MAKE) --no-print-directory --no-keep-going mod-internal-installs _FW_MAKE_PARALLEL=yes _FW_DEVICE_IPS="$(FW_DEVICE_IPS)"
+endif
+
+mod-internal-installs: $(foreach i,$(_FW_DEVICE_IPS),$(i).install)
+
+%.install:
+ @ \
+ in="$@"; \
+ ip=$${in%.install}; \
+ echo Making install for $$ip; \
+ $(MAKE) --no-print-directory --no-keep-going install FW_DEVICE_IP=$$ip _FW_TOP_INVOCATION_DONE=""
|
DHowett/theos-modules | 1765d3c36dd491f4aad3e30c21c4edca0e29778a | Ugly but working copy of the Java module (!) | diff --git a/java/apk.mk b/java/apk.mk
new file mode 100644
index 0000000..8741f07
--- /dev/null
+++ b/java/apk.mk
@@ -0,0 +1,7 @@
+ifeq ($(FW_INSTANCE),)
+ include $(FW_MODDIR)/java/master/apk.mk
+else
+ ifeq ($(FW_TYPE),apk)
+ include $(FW_MODDIR)/java/instance/apk.mk
+ endif
+endif
diff --git a/java/common.mk b/java/common.mk
new file mode 100644
index 0000000..9474930
--- /dev/null
+++ b/java/common.mk
@@ -0,0 +1,16 @@
+FW_CLASSES_DIR_NAME = classes
+FW_CLASSES_DIR = $(FW_OBJ_DIR)/$(FW_CLASSES_DIR_NAME)
+
+ifneq ($(messages),yes)
+ ECHO_RESOURCES = @(echo " Processing Resources...";
+ ECHO_RJAVA = @(echo " Compiling R.java...";
+ ECHO_DEXING = @(echo " Converting to Dalvik bytecode...";
+ ECHO_PACKING = @(echo " Packing $(FW_INSTANCE)...";
+ ECHO_ALIGNING = @(echo " Aligning $(FW_INSTANCE)...";
+else
+ ECHO_RESOURCES =
+ ECHO_RJAVA =
+ ECHO_DEXING =
+ ECHO_PACKING =
+ ECHO_ALIGNING =
+endif
diff --git a/java/instance/apk.mk b/java/instance/apk.mk
new file mode 100644
index 0000000..5a020a7
--- /dev/null
+++ b/java/instance/apk.mk
@@ -0,0 +1,38 @@
+ifeq ($(FW_RULES_LOADED),)
+include $(FW_MAKEDIR)/rules.mk
+endif
+.PHONY: internal-apk-all_ internal-apk-stage_ internal-apk-compile
+
+ifeq ($(FW_MAKE_PARALLEL_BUILDING), no)
+internal-apk-all_:: $(FW_OBJ_DIR) $(FW_CLASSES_DIR) $(FW_OBJ_DIR)/$(FW_INSTANCE).apk
+else
+internal-apk-all_:: $(FW_OBJ_DIR) $(FW_CLASSES_DIR)
+ $(ECHO_NOTHING)$(MAKE) --no-print-directory --no-keep-going \
+ internal-apk-compile \
+ FW_TYPE=$(FW_TYPE) FW_INSTANCE=$(FW_INSTANCE) FW_OPERATION=compile \
+ FW_BUILD_DIR="$(FW_BUILD_DIR)" _FW_MAKE_PARALLEL=yes$(ECHO_END)
+
+internal-apk-compile: $(FW_OBJ_DIR)/$(FW_INSTANCE).apk
+endif
+
+# $(FW_OBJ_DIR)/$(FW_INSTANCE).manifest
+$(FW_OBJ_DIR)/res.zip.stamp: res
+ @touch $@
+ $(ECHO_RESOURCES)$(TARGET_AAPT) package -f -M AndroidManifest.xml -F $(FW_OBJ_DIR)/res.zip -I $(BOOTCLASSPATH) -S res -J $(FW_OBJ_DIR)$(ECHO_END)
+
+$(FW_OBJ_DIR)/R.java.stamp: $(FW_OBJ_DIR)/res.zip.stamp
+ @touch $@
+ $(ECHO_RJAVA)$(TARGET_JAVAC) $(TARGET_JAVAC_ARGS) -d $(FW_CLASSES_DIR)/ $(FW_OBJ_DIR)/R.java$(ECHO_END)
+
+$(FW_OBJ_DIR)/classes.dex: $(OBJ_FILES_TO_LINK)
+ $(ECHO_DEXING)$(TARGET_DX) --dex --output=$@ $(FW_CLASSES_DIR)$(ECHO_END)
+
+$(FW_OBJ_DIR)/$(FW_INSTANCE).unsigned.apk: AndroidManifest.xml $(FW_OBJ_DIR)/res.zip.stamp $(FW_OBJ_DIR)/R.java.stamp $(FW_OBJ_DIR)/classes.dex
+ $(ECHO_PACKING)$(TARGET_APKBUILDER) $@ -u -z $(FW_OBJ_DIR)/res.zip -f $(FW_OBJ_DIR)/classes.dex$(ECHO_END)
+
+$(FW_OBJ_DIR)/$(FW_INSTANCE).apk: $(TARGET_DEBUG_KEYSTORE) $(FW_OBJ_DIR)/$(FW_INSTANCE).unsigned.apk
+ $(ECHO_SIGNING)$(TARGET_JARSIGNER) -keystore $(TARGET_DEBUG_KEYSTORE) -storepass android -keypass android -signedjar $(FW_OBJ_DIR)/$(FW_INSTANCE).unaligned.apk $(FW_OBJ_DIR)/$(FW_INSTANCE).unsigned.apk androiddebugkey$(ECHO_END)
+ $(ECHO_ALIGNING)$(TARGET_ZIPALIGN) -f 4 $(FW_OBJ_DIR)/$(FW_INSTANCE).unaligned.apk $@$(ECHO_END)
+
+internal-apk-stage_::
+ $(ECHO_NOTHING)cp $(FW_OBJ_DIR)/$(FW_INSTANCE).apk "$(FW_STAGING_DIR)"$(ECHO_END)
diff --git a/java/instance/jar.mk b/java/instance/jar.mk
new file mode 100644
index 0000000..f714caf
--- /dev/null
+++ b/java/instance/jar.mk
@@ -0,0 +1,23 @@
+ifeq ($(FW_RULES_LOADED),)
+include $(FW_MAKEDIR)/rules.mk
+endif
+.PHONY: internal-jar-all_ internal-jar-stage_ internal-jar-compile
+
+ifeq ($(FW_MAKE_PARALLEL_BUILDING), no)
+internal-jar-all_:: $(FW_OBJ_DIR) $(FW_OBJ_DIR)/$(FW_INSTANCE).jar
+else
+internal-jar-all_:: $(FW_OBJ_DIR)
+ $(ECHO_NOTHING)$(MAKE) --no-print-directory --no-keep-going \
+ internal-jar-compile \
+ FW_TYPE=$(FW_TYPE) FW_INSTANCE=$(FW_INSTANCE) FW_OPERATION=compile \
+ FW_BUILD_DIR="$(FW_BUILD_DIR)" _FW_MAKE_PARALLEL=yes$(ECHO_END)
+
+internal-jar-compile: $(FW_OBJ_DIR)/$(FW_INSTANCE).jar
+endif
+
+# $(FW_OBJ_DIR)/$(FW_INSTANCE).manifest
+$(FW_OBJ_DIR)/$(FW_INSTANCE).jar: $(OBJ_FILES_TO_LINK)
+ @(echo " Jarring $(FW_INSTANCE).jar..."; cd $(FW_CLASSES_DIR); jar cfe ../$(FW_INSTANCE).jar $($(FW_INSTANCE)_MAIN_CLASS) $(subst $(FW_CLASSES_DIR)/,,$(OBJ_FILES_TO_LINK)) )
+
+internal-jar-stage_::
+ $(ECHO_NOTHING)cp $(FW_OBJ_DIR)/$(FW_INSTANCE).jar "$(FW_STAGING_DIR)"$(ECHO_END)
diff --git a/java/instance/rules.mk b/java/instance/rules.mk
new file mode 100644
index 0000000..1d9eacb
--- /dev/null
+++ b/java/instance/rules.mk
@@ -0,0 +1,2 @@
+JAVA_CLASSES = $(patsubst %.java,$(FW_OBJ_DIR)/%.java.stamp,$($(FW_INSTANCE)_JAVA_FILES))
+OBJ_FILES_TO_LINK += $(JAVA_CLASSES)
diff --git a/java/jar.mk b/java/jar.mk
new file mode 100644
index 0000000..d525c41
--- /dev/null
+++ b/java/jar.mk
@@ -0,0 +1,7 @@
+ifeq ($(FW_INSTANCE),)
+ include $(FW_MODDIR)/java/master/jar.mk
+else
+ ifeq ($(FW_TYPE),jar)
+ include $(FW_MODDIR)/java/instance/jar.mk
+ endif
+endif
diff --git a/java/master/apk.mk b/java/master/apk.mk
new file mode 100644
index 0000000..4f90d37
--- /dev/null
+++ b/java/master/apk.mk
@@ -0,0 +1,14 @@
+APK_NAME := $(strip $(APK_NAME))
+
+ifeq ($(FW_RULES_LOADED),)
+include $(FW_MAKEDIR)/rules.mk
+endif
+
+internal-all:: $(APK_NAME:=.all.apk.variables);
+
+internal-stage:: $(APK_NAME:=.stage.apk.variables);
+
+internal-after-install::
+
+$(APK_NAME):
+ @$(MAKE) --no-print-directory --no-keep-going [email protected]
diff --git a/java/master/jar.mk b/java/master/jar.mk
new file mode 100644
index 0000000..9d4b9b3
--- /dev/null
+++ b/java/master/jar.mk
@@ -0,0 +1,14 @@
+JAR_NAME := $(strip $(JAR_NAME))
+
+ifeq ($(FW_RULES_LOADED),)
+include $(FW_MAKEDIR)/rules.mk
+endif
+
+internal-all:: $(JAR_NAME:=.all.jar.variables);
+
+internal-stage:: $(JAR_NAME:=.stage.jar.variables);
+
+internal-after-install::
+
+$(JAR_NAME):
+ @$(MAKE) --no-print-directory --no-keep-going [email protected]
diff --git a/java/master/rules.mk b/java/master/rules.mk
new file mode 100644
index 0000000..e69de29
diff --git a/java/rules.mk b/java/rules.mk
new file mode 100644
index 0000000..093c995
--- /dev/null
+++ b/java/rules.mk
@@ -0,0 +1,8 @@
+.SUFFIXES: .java
+
+$(FW_OBJ_DIR)/%.java.stamp: %.java
+ @touch $@
+ $(ECHO_COMPILING)$(TARGET_JAVAC) $(TARGET_JAVAC_ARGS) -d $(FW_CLASSES_DIR)/ $^$(ECHO_END)
+
+$(FW_CLASSES_DIR): $(FW_OBJ_DIR)
+ @cd $(FW_OBJ_DIR); mkdir -p $(FW_CLASSES_DIR_NAME)
diff --git a/java/targets/android.mk b/java/targets/android.mk
new file mode 100644
index 0000000..cd98ca5
--- /dev/null
+++ b/java/targets/android.mk
@@ -0,0 +1,30 @@
+ifeq ($(FW_TARGET_LOADED),)
+FW_TARGET_LOADED := 1
+FW_TARGET_NAME := android
+
+SDK_ROOT ?= /opt/android-sdk
+SDKVERSION ?= 7
+PLATFORM_ROOT ?= $(SDK_ROOT)/platforms/android-$(SDKVERSION)
+BOOTCLASSPATH = $(PLATFORM_ROOT)/android.jar
+
+TARGET_JAVAC ?= javac
+TARGET_JAVAC_ARGS ?= -bootclasspath $(BOOTCLASSPATH)
+TARGET_JARSIGNER ?= jarsigner
+TARGET_KEYTOOL ?= keytool
+TARGET_AAPT ?= $(PLATFORM_ROOT)/tools/aapt
+TARGET_DX ?= $(PLATFORM_ROOT)/tools/dx
+TARGET_APKBUILDER ?= $(SDK_ROOT)/tools/apkbuilder
+TARGET_ZIPALIGN ?= $(SDK_ROOT)/tools/zipalign
+
+TARGET_DEBUG_KEYSTORE_DIR ?= $(HOME)/.android
+TARGET_DEBUG_KEYSTORE ?= $(TARGET_DEBUG_KEYSTORE_DIR)/debug.keystore
+
+all::
+
+$(TARGET_DEBUG_KEYSTORE_DIR):
+ @mkdir -p $@
+
+$(TARGET_DEBUG_KEYSTORE): $(TARGET_DEBUG_KEYSTORE_DIR)
+ $(ECHO_NOTHING)$(TARGET_KEYTOOL) -genkeypair -dname "CN=Android Debug,O=Android,C=US" -validity 365 -alias "androiddebugkey" -keypass "android" -keystore $@ -storepass "android"$(ECHO_END)
+
+endif
|
mikowitz/morse | 93a4196b8cbe20bac1febdacfa35602f9c190c24 | Version bump to 0.1.0 | diff --git a/VERSION b/VERSION
index 77d6f4c..6e8bf73 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.0.0
+0.1.0
|
mikowitz/morse | 2b9237b56f795e7a8bbdfac4d7e2648059ed4724 | Version bump to 0.0.0 | diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..77d6f4c
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.0.0
|
mikowitz/morse | 916a8dca13d97b322ad699754607e634aba22bff | Moves dependencies into Gemfile. | diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..1846292
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,2 @@
+gem "rspec", ">= 1.2.9"
+gem "cucumber", ">= 0"
diff --git a/Rakefile b/Rakefile
index c97c8a0..16758e5 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,52 +1,50 @@
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "morse"
gem.summary = %Q{TODO: one-line summary of your gem}
gem.description = %Q{TODO: longer description of your gem}
gem.email = "[email protected]"
gem.homepage = "http://github.com/mikowitz/morse"
gem.authors = ["Michael Berkowitz"]
- gem.add_development_dependency "rspec", ">= 1.2.9"
- gem.add_development_dependency "cucumber", ">= 0"
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
end
require 'spec/rake/spectask'
Spec::Rake::SpecTask.new(:spec) do |spec|
spec.libs << 'lib' << 'spec'
spec.spec_files = FileList['spec/**/*_spec.rb']
end
Spec::Rake::SpecTask.new(:rcov) do |spec|
spec.libs << 'lib' << 'spec'
spec.pattern = 'spec/**/*_spec.rb'
spec.rcov = true
end
task :spec => :check_dependencies
begin
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features)
task :features => :check_dependencies
rescue LoadError
task :features do
abort "Cucumber is not available. In order to run features, you must: sudo gem install cucumber"
end
end
task :default => :spec
require 'yard'
YARD::Rake::YardocTask.new do |t|
t.options = %w{--no-private -mmarkdown}
end
diff --git a/lib/morse.rb b/lib/morse.rb
index 09b9e76..485ef52 100644
--- a/lib/morse.rb
+++ b/lib/morse.rb
@@ -1,30 +1,28 @@
module Morse
ENGLISH = Array('a'..'z') << " "
MORSE = %w{.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. /}
def self.translate(string)
@string = string.downcase.strip.gsub(/\s{2,}/, " ")
if @string.is_morse?
@split, @join = " ", ""
self.translate_from_to(MORSE, ENGLISH)
else
@split, @join = "", " "
self.translate_from_to(ENGLISH, MORSE)
end
end
# @private
def self.translate_from_to(source, target)
@string.split(@split).map{|char| target[source.index(char)] }.join(@join)
end
-
- private :translate_from_to
end
# @private
class String
# @private
def is_morse?
self.gsub(/\.|-|\//, "").strip == ""
end
end
|
mikowitz/morse | e27383d941fa2cc4081ef0680fcba9671366ee1b | Documentation updates. | diff --git a/README.md b/README.md
new file mode 100644
index 0000000..973e89e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,15 @@
+# morse
+
+Small module for converting between English and Morse code.
+
+## Usage
+
+ Morse.translate("github")
+ #=> "--. .. - .... ..- -..."
+
+ Morse.translate(".. / .-.. --- ...- . / -- --- .-. ... . / -.-. --- -.. .")
+ #=> "i love morse code"
+
+## Copyright
+
+Copyright (c) 2010 Michael Berkowitz. See LICENSE for details.
diff --git a/README.rdoc b/README.rdoc
deleted file mode 100644
index aaf458a..0000000
--- a/README.rdoc
+++ /dev/null
@@ -1,17 +0,0 @@
-= morse
-
-Description goes here.
-
-== Note on Patches/Pull Requests
-
-* Fork the project.
-* Make your feature addition or bug fix.
-* Add tests for it. This is important so I don't break it in a
- future version unintentionally.
-* Commit, do not mess with rakefile, version, or history.
- (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
-* Send me a pull request. Bonus points for topic branches.
-
-== Copyright
-
-Copyright (c) 2010 Michael Berkowitz. See LICENSE for details.
diff --git a/Rakefile b/Rakefile
index 4c273a0..c97c8a0 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,57 +1,52 @@
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "morse"
gem.summary = %Q{TODO: one-line summary of your gem}
gem.description = %Q{TODO: longer description of your gem}
gem.email = "[email protected]"
gem.homepage = "http://github.com/mikowitz/morse"
gem.authors = ["Michael Berkowitz"]
gem.add_development_dependency "rspec", ">= 1.2.9"
gem.add_development_dependency "cucumber", ">= 0"
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
end
require 'spec/rake/spectask'
Spec::Rake::SpecTask.new(:spec) do |spec|
spec.libs << 'lib' << 'spec'
spec.spec_files = FileList['spec/**/*_spec.rb']
end
Spec::Rake::SpecTask.new(:rcov) do |spec|
spec.libs << 'lib' << 'spec'
spec.pattern = 'spec/**/*_spec.rb'
spec.rcov = true
end
task :spec => :check_dependencies
begin
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features)
task :features => :check_dependencies
rescue LoadError
task :features do
abort "Cucumber is not available. In order to run features, you must: sudo gem install cucumber"
end
end
task :default => :spec
-require 'rake/rdoctask'
-Rake::RDocTask.new do |rdoc|
- version = File.exist?('VERSION') ? File.read('VERSION') : ""
-
- rdoc.rdoc_dir = 'rdoc'
- rdoc.title = "morse #{version}"
- rdoc.rdoc_files.include('README*')
- rdoc.rdoc_files.include('lib/**/*.rb')
+require 'yard'
+YARD::Rake::YardocTask.new do |t|
+ t.options = %w{--no-private -mmarkdown}
end
diff --git a/lib/morse.rb b/lib/morse.rb
index 664fd6e..09b9e76 100644
--- a/lib/morse.rb
+++ b/lib/morse.rb
@@ -1,25 +1,30 @@
module Morse
ENGLISH = Array('a'..'z') << " "
MORSE = %w{.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. /}
def self.translate(string)
@string = string.downcase.strip.gsub(/\s{2,}/, " ")
if @string.is_morse?
@split, @join = " ", ""
self.translate_from_to(MORSE, ENGLISH)
else
@split, @join = "", " "
self.translate_from_to(ENGLISH, MORSE)
end
end
+ # @private
def self.translate_from_to(source, target)
@string.split(@split).map{|char| target[source.index(char)] }.join(@join)
end
+
+ private :translate_from_to
end
+# @private
class String
+ # @private
def is_morse?
self.gsub(/\.|-|\//, "").strip == ""
end
end
|
patrickjennings/JavaToc | b7eb2b5d6d8a9722f6d53d41f6e4377703166d3f | Adding the javatoc package to my github repository! | diff --git a/.classpath b/.classpath
new file mode 100644
index 0000000..18d70f0
--- /dev/null
+++ b/.classpath
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/.project b/.project
new file mode 100644
index 0000000..b349a59
--- /dev/null
+++ b/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>JavaToc</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..e8677a0
--- /dev/null
+++ b/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,12 @@
+#Sun Aug 01 15:00:06 EST 2010
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/README b/README
new file mode 100644
index 0000000..0911f6b
--- /dev/null
+++ b/README
@@ -0,0 +1,23 @@
+README
+JavaToc v0.0.1
+written by Patrick Jennings
+
+--------------------------------------------------------------------------------
+About JavaToc
+
+JavaToc is an interface written in java that can be used to connect to and send
+and receive commands from the AOL TOC server. The interface uses the TOC2
+(Talk to OSCAR 2) protocol developed by AOL. The TOC2 protocol is a wrapper for
+AOL's proprietary OSCAR protocol used for its AIM clients. TOC2 is an ASCII-
+based protocol which makes it much easier to work with compared with its binary
+counterpart, OSCAR.
+
+--------------------------------------------------------------------------------
+Resources
+
+-TOC2 specs:
+ http://terraim.cvs.sourceforge.net/viewvc/terraim/terraim/src/toc/TOC2.txt
+-TOC wiki:
+ http://en.wikipedia.org/wiki/TOC_protocol
+-OSCAR doc:
+ http://code.google.com/p/joscar/wiki/FrontPage
diff --git a/src/JTocTest.java b/src/JTocTest.java
new file mode 100644
index 0000000..d40b0e4
--- /dev/null
+++ b/src/JTocTest.java
@@ -0,0 +1,78 @@
+
+import java.io.IOException;
+import java.util.Scanner;
+
+import javatoc.JTocActionListener;
+import javatoc.JTocConnection;
+import javatoc.JTocEvent;
+import javatoc.JTocNewMessageEvent;
+
+/**
+ * @author Patrick Jennings
+ *
+ * The JTocTest class holds an example of how to use the
+ * javatoc package.
+ *
+ */
+public class JTocTest implements JTocActionListener {
+
+ private JTocConnection c;
+
+ public static void main(String[] args) {
+ new JTocTest();
+ }
+
+ public JTocTest() {
+ c = new JTocConnection();
+ c.addEventListener(this);
+ try {
+ c.connect("username","password");
+ } catch (IOException e) {
+ e.printStackTrace();
+ return;
+ }
+
+ c.setAway("Send me a message and I will echo!");
+ c.setInfo("Using the javatoc package!");
+ c.setIdle(90);
+
+ Scanner sc = new Scanner(System.in);
+ String command;
+ StringBuffer sb;
+ command = sc.next();
+ while(!command.equals("exit")) {
+ sb = new StringBuffer(command);
+ if(command.startsWith("send")) {
+ nextElement(sb);
+ c.sendMessage(nextElement(sb), sb.toString());
+ }
+ command = sc.next();
+ }
+ c.disconnect();
+ }
+
+ public void receiveEvent(JTocEvent ev) {
+ System.out.println(ev);
+
+ if(ev.getType().equals(JTocEvent.NEWMESSAGE)) {
+ c.setIdle(0);
+ c.sendMessage(((JTocNewMessageEvent) ev).getUser(), ((JTocNewMessageEvent) ev).getMessage());
+ }
+ }
+
+ public static String nextElement(StringBuffer str) {
+ String result = "";
+ int i = str.indexOf(":", 0);
+ if(i == -1) {
+ result = str.toString();
+ str.setLength(0);
+ }
+ else {
+ result = str.substring(0,i).toString();
+ String a = str.substring(i+1);
+ str.setLength(0);
+ str.append(a);
+ }
+ return result;
+ }
+}
diff --git a/src/javatoc/JTocActionListener.java b/src/javatoc/JTocActionListener.java
new file mode 100644
index 0000000..5109e30
--- /dev/null
+++ b/src/javatoc/JTocActionListener.java
@@ -0,0 +1,7 @@
+package javatoc;
+
+public interface JTocActionListener {
+
+ public void receiveEvent(JTocEvent ev);
+
+}
diff --git a/src/javatoc/JTocBuddyUpdateEvent.java b/src/javatoc/JTocBuddyUpdateEvent.java
new file mode 100644
index 0000000..8a9b025
--- /dev/null
+++ b/src/javatoc/JTocBuddyUpdateEvent.java
@@ -0,0 +1,46 @@
+package javatoc;
+
+public class JTocBuddyUpdateEvent implements JTocEvent {
+
+ private static final String type = BUDDYUPDATE;
+
+ private String user;
+ private String warn;
+ private String signOnTime;
+ private String idle;
+
+ public JTocBuddyUpdateEvent(String u, String w, String s, String i) {
+ user = u;
+ warn = w;
+ signOnTime = s;
+ idle = i;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public String getWarn() {
+ return warn;
+ }
+
+ public String getSignOnTime() {
+ return signOnTime;
+ }
+
+ public String getIdle() {
+ return idle;
+ }
+
+ public String toString() {
+ return "Status update:\n"
+ + "\tUser:\t" + user + "\n"
+ + "\tWarn:\t" + warn + "\n"
+ + "\tUptime:\t" + signOnTime + "\n"
+ + "\tIdle:\t" + idle;
+ }
+}
diff --git a/src/javatoc/JTocConnection.java b/src/javatoc/JTocConnection.java
new file mode 100644
index 0000000..deb0fad
--- /dev/null
+++ b/src/javatoc/JTocConnection.java
@@ -0,0 +1,231 @@
+package javatoc;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+
+/**
+ * @author Patrick Jennings
+ *
+ * The JacConnention object holds all of the important
+ * information in order to connect and send commands
+ * to the AIM servers.
+ * The user should add a JacActionListener before connection
+ * so that events may be processed.
+ *
+ */
+public class JTocConnection {
+
+ /*
+ * Some static variables.
+ */
+ private static final int SIGNON = 1;
+ private static final int DATA = 2;
+ private static String tocHost = "toc.oscar.aol.com";
+ private static int tocPort = 9898;
+ private static String authHost = "login.oscar.aol.com";
+ private static int authPort = 5190;
+ private static String language = "english";
+ private static String version = "TIC:JToc";
+
+ /*
+ * Class variables.
+ */
+ private Socket connection;
+ private InputStream is;
+ private OutputStream os;
+ private String screenname;
+ private short sequence;
+ private JTocActionListener al;
+ private JTocParserThread it;
+
+ public JTocConnection() {
+ }
+
+ /**
+ * Creates a TCP connection with the oscar server.
+ * @param s The screen name fo the user
+ * @param p The users password (Is not saved)
+ * @throws IOException Throws an exception if a connection error occurs
+ */
+ public void connect(String s, String p) throws IOException {
+ screenname = s;
+ connection = new Socket(tocHost, tocPort); // Create a socket to the toc server.
+ is = connection.getInputStream(); // Get input and output streams so that we may write bytes to the toc server.
+ os = connection.getOutputStream();
+ os.write(("FLAPON\r\n\r\n").getBytes()); // Must sent these bytes to the toc server before authentication.
+ getFlap(); // Server responds with garbage we don't care about.
+ sendFlapSignon(); // Send the signon FLAP
+
+ String command = "toc2_login " + authHost + " " + authPort + " "
+ + screenname + " " + Util.roastPassword(p) + " " + language +
+ " \"" + version + "\" 160 US \"\" \"\" 3 0 30303 -kentucky -utf8 "
+ + Util.signOnCode(screenname, p);
+
+ sendFlap(DATA,command); // Send authentication FLAP.
+ String str = getFlap(); // Get return message from the toc server.
+
+ if(str.toUpperCase().startsWith("ERROR:")) // If an error occurred, throw an exception and leave immediately.
+ throw new IOException("Could not connect! " + str);
+
+ sendFlap(DATA,"toc_add_buddy " + screenname); // Send the remaining FLAPs needed to signon.
+ sendFlap(DATA,"toc_init_done");
+ sendFlap(DATA,"toc_set_caps 09461343-4C7F-11D1-8222-444553540000 09461348-4C7F-11D1-8222-444553540000");
+ sendFlap(DATA,"toc_add_permit ");
+ sendFlap(DATA,"toc_add_deny ");
+
+ it = new JTocParserThread(this); // Create and start a toc parser thread.
+ it.start();
+ }
+
+ /**
+ * Kills the connection to the toc server.
+ */
+ public void disconnect() {
+ try {
+ it.end();
+ connection.close();
+ is.close();
+ os.close();
+ } catch(IOException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ /**
+ * Returns whether there is an open socket to the
+ * toc server.
+ */
+ public boolean isConnected() {
+ return connection.isConnected();
+ }
+
+ public void sendMessage(String to, String msg) {
+ try {
+ this.sendFlap(DATA,"toc_send_im " + Util.normalize(to) + " \"" +
+ Util.encode(msg) + "\"");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void addBuddy(String group, String buddy) {
+ try {
+ sendFlap(DATA, "toc2_new_buddies {g:" + group + "\nb:" + buddy + "\n}");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void deleteBuddy(String group, String buddy) {
+ try {
+ sendFlap(DATA, "toc2_remove_buddy {g:" + group + "\nb:" + buddy + "\n}");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void newGroup(String group) {
+ try {
+ System.out.println("toc2_new_group \"" + group + "\"");
+ sendFlap(DATA, "toc2_new_group \"" + group + "\"");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void deleteGroup(String group) {
+ try {
+ sendFlap(DATA, "toc2_del_group \"" + group + "\"");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void setInfo(String info) {
+ try {
+ sendFlap(DATA, "toc_set_info \"" + info + "\"");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void setAway(String message) {
+ try {
+ sendFlap(DATA, "toc_set_away \"" + message + "\"");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void setIdle(int secs) {
+ try {
+ sendFlap(DATA, "toc_set_idle \"" + secs + "\"");
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String getFlap() throws IOException {
+ if(is.read() != '*')
+ throw new IOException();
+ is.read();
+ is.read();
+ is.read();
+ int length = (is.read()*0x100) + is.read();
+ byte b[] = new byte[length];
+ is.read(b);
+ return new String(b);
+ }
+
+ public void sendFlap(int type,String str) throws IOException {
+ int length = str.length()+1;
+ sequence++;
+ os.write((byte)'*');
+ os.write((byte)type);
+ writeWord(sequence);
+ writeWord((short)length);
+ os.write(str.getBytes());
+ os.write(0);
+ os.flush();
+ }
+
+ private void sendFlapSignon() throws IOException {
+ int length = 8 + screenname.length();
+ sequence++;
+ os.write((byte)'*');
+ os.write((byte)SIGNON);
+ writeWord(sequence);
+ writeWord((short)length);
+
+ os.write(0);
+ os.write(0);
+ os.write(0);
+ os.write(1);
+
+ os.write(0);
+ os.write(1);
+
+ writeWord((short)screenname.length());
+ os.write(screenname.getBytes());
+ os.flush();
+ }
+
+ private void writeWord(short word) throws IOException {
+ os.write((byte) ((word >> 8) & 0xff) );
+ os.write( (byte) (word & 0xff) );
+ }
+
+ public void sendEvent(JTocEvent event) {
+ al.receiveEvent(event);
+ }
+
+ public void addEventListener(JTocActionListener l) {
+ al = l;
+ }
+
+ public void removeEventListener(JTocActionListener l) {
+ al = null;
+ }
+}
diff --git a/src/javatoc/JTocEvent.java b/src/javatoc/JTocEvent.java
new file mode 100644
index 0000000..403300c
--- /dev/null
+++ b/src/javatoc/JTocEvent.java
@@ -0,0 +1,24 @@
+package javatoc;
+
+/**
+ * @author Patrick Jennings
+ *
+ * The JTocEvent class provides an interface for
+ * generic events.
+ *
+ */
+public interface JTocEvent {
+
+ /*
+ * Some generic events that may be sent from the toc
+ * servers.
+ */
+ public static final String NEWMESSAGE = "IM_IN_ENC2";
+ public static final String BUDDYUPDATE = "UPDATE_BUDDY2";
+ public static final String BUDDYADDED = "NEW_BUDDY_REPLY2";
+ public static final String CONFIG = "CONFIG2";
+ public static final String NAMEFORMAT = "NICK";
+ public static final String UNKNOWN = "Unknown Event";
+
+ public String getType();
+}
diff --git a/src/javatoc/JTocNewMessageEvent.java b/src/javatoc/JTocNewMessageEvent.java
new file mode 100644
index 0000000..bdadaed
--- /dev/null
+++ b/src/javatoc/JTocNewMessageEvent.java
@@ -0,0 +1,32 @@
+package javatoc;
+
+public class JTocNewMessageEvent implements JTocEvent {
+
+ private static final String type = NEWMESSAGE;
+
+ private String from;
+ private String message;
+
+ public JTocNewMessageEvent(String f, String m) {
+ from = f;
+ message = m;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public String getUser() {
+ return from;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String toString() {
+ return "New Message:\n"
+ + "\tUser:\t" + from + "\n"
+ + "\tMSG:\t" + message;
+ }
+}
diff --git a/src/javatoc/JTocParserThread.java b/src/javatoc/JTocParserThread.java
new file mode 100644
index 0000000..582dea8
--- /dev/null
+++ b/src/javatoc/JTocParserThread.java
@@ -0,0 +1,98 @@
+package javatoc;
+
+import java.io.IOException;
+
+/**
+ * @author Patrick Jennings
+ *
+ * The JTocParserThread class parses the messages received
+ * from the toc server and sends new events to the
+ * JTocActionListener.
+ *
+ */
+public class JTocParserThread extends Thread {
+
+ private boolean running;
+ private JTocConnection connection;
+
+ public JTocParserThread(JTocConnection c) {
+ connection = c;
+ running = false;
+ }
+
+ public void end() {
+ running = false;
+ }
+
+ /*
+ * Run the parser thread on the connection. The thread
+ * will parse new messages from the toc server.
+ * If the connection is disconnected, the parser
+ * will stop running.
+ */
+ public void run() {
+ running = connection.isConnected();
+ while(running) {
+ String msg = null;
+ try {
+ msg = connection.getFlap();
+ } catch (IOException e) {
+ System.out.println("Connection broken!");
+ break;
+ }
+
+ parseMessage(msg);
+
+ running = connection.isConnected();
+ }
+ }
+
+ /*
+ * Parses the toc server message into a new event
+ * then sends the event to the register action
+ * listener.
+ */
+ private void parseMessage(String str) {
+ if(str == null)
+ return;
+
+ StringBuffer sb = new StringBuffer(str);
+ String event = Util.nextElement(sb); // The event type
+ String message = sb.toString(); // The rest of the message
+
+ if(event.equals(JTocEvent.NEWMESSAGE)) { // If the event is a new message, parse and send a NEWMESSAGE event.
+ String from = Util.nextElement(sb); // Get the user name who sent the message.
+ Util.nextElement(sb); // auto (dunno what it does)
+ Util.nextElement(sb); // garbage
+ Util.nextElement(sb); // garbage
+ Util.nextElement(sb); // buddy status (could be useful...)
+ Util.nextElement(sb); // garbage
+ Util.nextElement(sb); // garbage
+ Util.nextElement(sb); // language (could be useful...)
+ message = sb.toString(); // Get the contents of the message (in HTML format)
+ if(message == null)
+ message = "";
+ connection.sendEvent(new JTocNewMessageEvent(from, message));
+ }
+ else if(event.equals(JTocEvent.BUDDYUPDATE)) { // If event is a buddy update, send appropriate event.
+ String name = Util.nextElement(sb);
+ Util.nextElement(sb);
+ String warn = Util.nextElement(sb);
+ String signOnTime = Util.nextElement(sb);
+ String idle = Util.nextElement(sb);
+ connection.sendEvent(new JTocBuddyUpdateEvent(name, warn, signOnTime, idle));
+ }
+ /*else if(event.equals("NEW_BUDDY_REPLY2")) {
+ connection.sendEvent(new JTocEvent(JTocEvent.BUDDYADDED, message));
+ }
+ else if(event.equals("CONFIG2")) {
+ connection.sendEvent(new JTocEvent(JTocEvent.CONFIG, message));
+ }
+ else if(event.equals("NICK")) {
+ connection.sendEvent(new JTocEvent(JTocEvent.NAMEFORMAT, message));
+ }*/
+ else {
+ connection.sendEvent(new JTocUnknownEvent(str));
+ }
+ }
+}
diff --git a/src/javatoc/JTocUnknownEvent.java b/src/javatoc/JTocUnknownEvent.java
new file mode 100644
index 0000000..0dfcf83
--- /dev/null
+++ b/src/javatoc/JTocUnknownEvent.java
@@ -0,0 +1,25 @@
+package javatoc;
+
+public class JTocUnknownEvent implements JTocEvent {
+
+ private static final String type = UNKNOWN;
+
+ private String message;
+
+ public JTocUnknownEvent(String m) {
+ message = m;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String toString() {
+ return "Unknown event:\n"
+ + "\t" + message;
+ }
+}
diff --git a/src/javatoc/Util.java b/src/javatoc/Util.java
new file mode 100644
index 0000000..99f612f
--- /dev/null
+++ b/src/javatoc/Util.java
@@ -0,0 +1,113 @@
+package javatoc;
+
+/**
+ * @author Patrick Jennings
+ *
+ * The Util class holds special parsing and general
+ * purpose utilities for the javatoc package.
+ *
+ */
+public class Util {
+
+ /*
+ * "sn = ascii value of the first letter of the screen name
+ * pw = ascii value of the first character of the password
+ * return 7696 * sn * pw"
+ * http://terraim.cvs.sourceforge.net/viewvc/terraim/terraim/src/toc/TOC2.txt
+ */
+ public static int signOnCode(String u, String p) {
+ int sn = u.charAt(0);
+ int pw = p.charAt(0);
+ return 7696 * sn * pw;
+ }
+
+ /*
+ * "Roasting is performed by first xoring each byte
+ * in the password with the equivalent modulo byte in the roasting
+ * string. The result is then converted to ascii hex, and prepended
+ * with 0x".
+ * http://terraim.cvs.sourceforge.net/viewvc/terraim/terraim/src/toc/TOC1.txt
+ */
+ public static String roastPassword(String str) {
+ byte xor[] = "Tic/Toc".getBytes();
+ int xorIndex = 0;
+ String rtn = "0x";
+
+ for(int i= 0; i < str.length(); i++) {
+ String hex = Integer.toHexString(xor[xorIndex]^(int)str.charAt(i));
+ if(hex.length() == 1)
+ hex = "0" + hex;
+ rtn += hex;
+ xorIndex++;
+ if(xorIndex == xor.length)
+ xorIndex=0;
+ }
+ return rtn;
+ }
+
+ /*
+ * Normalize the input string by making all chars lower
+ * case and remove all non-alphabetical/numerical chars.
+ */
+ public static String normalize(String input) {
+ StringBuffer output = new StringBuffer();
+ String temp = input.toLowerCase();
+ for(int i = 0; i < input.length(); i++) {
+ char c = temp.charAt(i);
+ if((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')) {
+ output.append(c);
+ }
+ }
+
+ return output.toString();
+ }
+
+ /*
+ * Can be used to encode a new message.
+ *
+ * Encode the string with the following:
+ * Change all newlines to <br>.
+ * Place '\\' before special chars: "Dollar signs,
+ * curly brackets, square brackets, parentheses,
+ * quotes, and backslashes".
+ */
+ public static String encode(String str) {
+ String rtn="";
+ for(int i = 0; i < str.length(); i++) {
+ switch(str.charAt(i)) {
+ case '\r':
+ rtn+="<br>";
+ break;
+ case '{':
+ case '}':
+ case '\\':
+ case ':':
+ case '"':
+ rtn+="\\";
+ default:
+ rtn+=str.charAt(i);
+ }
+ }
+ return rtn;
+ }
+
+ /*
+ * Returns the next element from a string with
+ * the following format: next:restOfString
+ */
+ public static String nextElement(StringBuffer str) {
+ String result = "";
+ int i = str.indexOf(":", 0);
+ if(i == -1) {
+ result = str.toString();
+ str.setLength(0);
+ }
+ else {
+ result = str.substring(0,i).toString();
+ String a = str.substring(i+1);
+ str.setLength(0);
+ str.append(a);
+ }
+ return result;
+ }
+}
|
sammyt/fussy | 3db10da2f24710d70c7563429b993536e29b6105 | bumped to snapshot version | diff --git a/pom.xml b/pom.xml
index 4932f00..ff72fd0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,63 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>uk.co.ziazoo</groupId>
<artifactId>fussy</artifactId>
- <version>0.2</version>
+ <version>0.2.1-SNAPSHOT</version>
<packaging>swc</packaging>
<name>Fussy query language</name>
<properties>
<flexversion>3.5.0.12683</flexversion>
<mojoversion>3.5.0</mojoversion>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.sonatype.flexmojos</groupId>
<artifactId>flexmojos-maven-plugin</artifactId>
<version>${mojoversion}</version>
<extensions>true</extensions>
<configuration>
<keepAs3Metadatas>
<!-- can i just keep these for tests? -->
<keepAs3Metadata>Inject</keepAs3Metadata>
<keepAs3Metadata>Fussy</keepAs3Metadata>
</keepAs3Metadatas>
</configuration>
<dependencies>
<dependency>
<groupId>com.adobe.flex</groupId>
<artifactId>compiler</artifactId>
<version>${flexversion}</version>
<type>pom</type>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.adobe.flex.framework</groupId>
<artifactId>flex-framework</artifactId>
<version>${flexversion}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.sonatype.flexmojos</groupId>
<artifactId>flexmojos-unittest-support</artifactId>
<version>${mojoversion}</version>
<type>swc</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.adobe.flexunit</groupId>
<artifactId>flexunit</artifactId>
<version>4.0-rc-1</version>
<type>swc</type>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
|
sammyt/fussy | 641bdef192b7bde51b97446916553f975283be3a | optimise loop (see issue https://github.com/sammyt/fussy/issues/9) | diff --git a/src/uk/co/ziazoo/fussy/Reflector.as b/src/uk/co/ziazoo/fussy/Reflector.as
index 906332a..27a3fab 100644
--- a/src/uk/co/ziazoo/fussy/Reflector.as
+++ b/src/uk/co/ziazoo/fussy/Reflector.as
@@ -1,129 +1,130 @@
package uk.co.ziazoo.fussy
{
import flash.system.ApplicationDomain;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.describeType;
import flash.utils.getQualifiedClassName;
public class Reflector implements IReflector
{
private var cache:Dictionary;
private var _applicationDomain:ApplicationDomain;
public function Reflector(applicationDomain:ApplicationDomain = null)
{
cache = new Dictionary();
_applicationDomain = applicationDomain;
}
/**
* @inheritDoc
*/
public function forType(type:Class):XML
{
var description:XML = cache[type] as XML;
if (description)
{
return description;
}
description = describeType(type);
var constructor:XML = description.factory.constructor[0];
if (constructor &&
constructor.parameter.(@type == "*").length()
== [email protected]())
{
var parameters:XMLList = constructor.parameter;
- if (parameters.length() > 0)
+ var len:int = parameters.length();
+ if (len > 0)
{
try
{
var args:Array = [];
- for (var i:int = 0; i < parameters.length(); i++)
+ for (var i:int = 0; i < len; i++)
{
args.push(null);
}
InstanceCreator.create(type, args);
description = describeType(type);
}
catch(error:Error)
{
}
}
}
cache[type] = description;
return description;
}
/**
* @inheritDoc
*/
public function forQName(qName:String):XML
{
var type:Class = Class(applicationDomain.getDefinition(qName));
return forType(type);
}
/**
* @inheritDoc
*/
public function clearAll():void
{
cache = null;
cache = new Dictionary();
}
/**
* @inheritDoc
*/
public function clearForType(type:Class):void
{
if (cache[type])
{
delete cache[type];
}
}
/**
* @inheritDoc
*/
public function clearForQName(qName:String):void
{
var type:Class = Class(applicationDomain.getDefinition(qName));
clearForType(type);
}
public function hasReflection(type:Class):Boolean
{
return cache[type] != null;
}
public function get applicationDomain():ApplicationDomain
{
return _applicationDomain || ApplicationDomain.currentDomain;
}
public function set applicationDomain(value:ApplicationDomain):void
{
_applicationDomain = value;
}
/**
* @inheritDoc
*/
public function getType(object:Object):Class
{
if (object is Proxy || object is Number || object is XML || object is
XMLList)
{
return Class(applicationDomain.getDefinition(getQualifiedClassName
(object)));
}
return object.constructor as Class;
}
}
}
\ No newline at end of file
|
sammyt/fussy | c03344c661171868d6bfa1efdc6094986c13b916 | getting types from objects | diff --git a/src/uk/co/ziazoo/fussy/IReflector.as b/src/uk/co/ziazoo/fussy/IReflector.as
index eeeeaf5..2168a9b 100644
--- a/src/uk/co/ziazoo/fussy/IReflector.as
+++ b/src/uk/co/ziazoo/fussy/IReflector.as
@@ -1,48 +1,55 @@
package uk.co.ziazoo.fussy
{
import flash.system.ApplicationDomain;
/**
* stores result of describeType calls
*/
public interface IReflector
{
/**
* Get reflection for a class
* @param type the class to reflect
* @return result of describeType
*/
function forType(type:Class):XML;
/**
* Get reflection for a types qualified name
* @param qName of type to reflect
* @return result of describeType
*/
function forQName(qName:String):XML;
/**
* Release all type description in memory (drop references)
*/
function clearAll():void;
/**
* Release specific types description
* @param type who's description reference can be released
*/
function clearForType(type:Class):void;
/**
* Release specific types description
* @param qName of type who's description reference can be released
*/
function clearForQName(qName:String):void;
-
+
+ /**
+ * Gets the class definition for a object
+ * @param object
+ * @return the class object for the object
+ */
+ function getType(object:Object):Class;
+
/**
* The application domain which fussy will request class
* definitions from
*/
function get applicationDomain():ApplicationDomain;
function set applicationDomain(value:ApplicationDomain):void;
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/Reflector.as b/src/uk/co/ziazoo/fussy/Reflector.as
index 026eac2..906332a 100644
--- a/src/uk/co/ziazoo/fussy/Reflector.as
+++ b/src/uk/co/ziazoo/fussy/Reflector.as
@@ -1,113 +1,129 @@
package uk.co.ziazoo.fussy
{
import flash.system.ApplicationDomain;
import flash.utils.Dictionary;
+ import flash.utils.Proxy;
import flash.utils.describeType;
+ import flash.utils.getQualifiedClassName;
public class Reflector implements IReflector
{
private var cache:Dictionary;
private var _applicationDomain:ApplicationDomain;
public function Reflector(applicationDomain:ApplicationDomain = null)
{
cache = new Dictionary();
_applicationDomain = applicationDomain;
}
/**
* @inheritDoc
*/
public function forType(type:Class):XML
{
var description:XML = cache[type] as XML;
if (description)
{
return description;
}
description = describeType(type);
var constructor:XML = description.factory.constructor[0];
if (constructor &&
constructor.parameter.(@type == "*").length()
== [email protected]())
{
var parameters:XMLList = constructor.parameter;
if (parameters.length() > 0)
{
try
{
var args:Array = [];
for (var i:int = 0; i < parameters.length(); i++)
{
args.push(null);
}
InstanceCreator.create(type, args);
description = describeType(type);
}
catch(error:Error)
{
}
}
}
cache[type] = description;
return description;
}
/**
* @inheritDoc
*/
public function forQName(qName:String):XML
{
var type:Class = Class(applicationDomain.getDefinition(qName));
return forType(type);
}
/**
* @inheritDoc
*/
public function clearAll():void
{
cache = null;
cache = new Dictionary();
}
/**
* @inheritDoc
*/
public function clearForType(type:Class):void
{
if (cache[type])
{
delete cache[type];
}
}
/**
* @inheritDoc
*/
public function clearForQName(qName:String):void
{
var type:Class = Class(applicationDomain.getDefinition(qName));
clearForType(type);
}
public function hasReflection(type:Class):Boolean
{
return cache[type] != null;
}
public function get applicationDomain():ApplicationDomain
{
return _applicationDomain || ApplicationDomain.currentDomain;
}
public function set applicationDomain(value:ApplicationDomain):void
{
_applicationDomain = value;
}
+
+ /**
+ * @inheritDoc
+ */
+ public function getType(object:Object):Class
+ {
+ if (object is Proxy || object is Number || object is XML || object is
+ XMLList)
+ {
+ return Class(applicationDomain.getDefinition(getQualifiedClassName
+ (object)));
+ }
+ return object.constructor as Class;
+ }
}
}
\ No newline at end of file
|
sammyt/fussy | 2e6f8226a9d5d837133ed973458a47ade65477c5 | 0.2 now stable | diff --git a/pom.xml b/pom.xml
index c415b2c..4932f00 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,63 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>uk.co.ziazoo</groupId>
<artifactId>fussy</artifactId>
- <version>0.2-SNAPSHOT</version>
+ <version>0.2</version>
<packaging>swc</packaging>
<name>Fussy query language</name>
<properties>
<flexversion>3.5.0.12683</flexversion>
<mojoversion>3.5.0</mojoversion>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.sonatype.flexmojos</groupId>
<artifactId>flexmojos-maven-plugin</artifactId>
<version>${mojoversion}</version>
<extensions>true</extensions>
<configuration>
<keepAs3Metadatas>
<!-- can i just keep these for tests? -->
<keepAs3Metadata>Inject</keepAs3Metadata>
<keepAs3Metadata>Fussy</keepAs3Metadata>
</keepAs3Metadatas>
</configuration>
<dependencies>
<dependency>
<groupId>com.adobe.flex</groupId>
<artifactId>compiler</artifactId>
<version>${flexversion}</version>
<type>pom</type>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.adobe.flex.framework</groupId>
<artifactId>flex-framework</artifactId>
<version>${flexversion}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.sonatype.flexmojos</groupId>
<artifactId>flexmojos-unittest-support</artifactId>
<version>${mojoversion}</version>
<type>swc</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.adobe.flexunit</groupId>
<artifactId>flexunit</artifactId>
<version>4.0-rc-1</version>
<type>swc</type>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
|
sammyt/fussy | 15627b093c768f9a7f9abe4929102d0130e07683 | allow passing application domain in via constructor | diff --git a/src/uk/co/ziazoo/fussy/Reflector.as b/src/uk/co/ziazoo/fussy/Reflector.as
index 87fc621..026eac2 100644
--- a/src/uk/co/ziazoo/fussy/Reflector.as
+++ b/src/uk/co/ziazoo/fussy/Reflector.as
@@ -1,112 +1,113 @@
package uk.co.ziazoo.fussy
{
import flash.system.ApplicationDomain;
import flash.utils.Dictionary;
import flash.utils.describeType;
public class Reflector implements IReflector
{
private var cache:Dictionary;
private var _applicationDomain:ApplicationDomain;
- public function Reflector()
+ public function Reflector(applicationDomain:ApplicationDomain = null)
{
cache = new Dictionary();
+ _applicationDomain = applicationDomain;
}
/**
* @inheritDoc
*/
public function forType(type:Class):XML
{
var description:XML = cache[type] as XML;
if (description)
{
return description;
}
description = describeType(type);
var constructor:XML = description.factory.constructor[0];
-
- if ( constructor &&
- constructor.parameter.(@type == "*").length()
- == [email protected]())
+
+ if (constructor &&
+ constructor.parameter.(@type == "*").length()
+ == [email protected]())
{
var parameters:XMLList = constructor.parameter;
if (parameters.length() > 0)
{
try
{
var args:Array = [];
for (var i:int = 0; i < parameters.length(); i++)
{
args.push(null);
}
InstanceCreator.create(type, args);
description = describeType(type);
}
catch(error:Error)
{
}
}
}
cache[type] = description;
return description;
}
/**
* @inheritDoc
*/
public function forQName(qName:String):XML
{
var type:Class = Class(applicationDomain.getDefinition(qName));
return forType(type);
}
/**
* @inheritDoc
*/
public function clearAll():void
{
cache = null;
cache = new Dictionary();
}
/**
* @inheritDoc
*/
public function clearForType(type:Class):void
{
if (cache[type])
{
delete cache[type];
}
}
/**
* @inheritDoc
*/
public function clearForQName(qName:String):void
{
var type:Class = Class(applicationDomain.getDefinition(qName));
clearForType(type);
}
public function hasReflection(type:Class):Boolean
{
return cache[type] != null;
}
-
+
public function get applicationDomain():ApplicationDomain
{
return _applicationDomain || ApplicationDomain.currentDomain;
}
-
+
public function set applicationDomain(value:ApplicationDomain):void
{
_applicationDomain = value;
}
}
}
\ No newline at end of file
|
sammyt/fussy | 89b15ab7d06aec924532ebdba920af487f02732b | added some documentation (via hg-git) | diff --git a/src/uk/co/ziazoo/fussy/IReflector.as b/src/uk/co/ziazoo/fussy/IReflector.as
index 3e00d41..eeeeaf5 100644
--- a/src/uk/co/ziazoo/fussy/IReflector.as
+++ b/src/uk/co/ziazoo/fussy/IReflector.as
@@ -1,44 +1,48 @@
package uk.co.ziazoo.fussy
{
import flash.system.ApplicationDomain;
/**
* stores result of describeType calls
*/
public interface IReflector
{
/**
* Get reflection for a class
* @param type the class to reflect
* @return result of describeType
*/
function forType(type:Class):XML;
/**
* Get reflection for a types qualified name
* @param qName of type to reflect
* @return result of describeType
*/
function forQName(qName:String):XML;
/**
* Release all type description in memory (drop references)
*/
function clearAll():void;
/**
* Release specific types description
* @param type who's description reference can be released
*/
function clearForType(type:Class):void;
/**
* Release specific types description
* @param qName of type who's description reference can be released
*/
function clearForQName(qName:String):void;
+ /**
+ * The application domain which fussy will request class
+ * definitions from
+ */
function get applicationDomain():ApplicationDomain;
function set applicationDomain(value:ApplicationDomain):void;
}
}
\ No newline at end of file
|
sammyt/fussy | ede5a13e899152f03e539f0b243fc471c7017ad3 | adding multiple application domain support | diff --git a/.gitignore b/.gitignore
index d5617ef..f1f272e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,11 @@
-*.settings
-*.actionScriptProperties
-*.flexLibProperties
-*.FlexUnitSettings
-*.project
-*.DS_Store
+.settings
+.actionScriptProperties
+.flexLibProperties
+.FlexUnitSettings
+.project
+.DS_Store
*bin/
+fussy.iml
+fussy.ipr
+fussy.iws
+target/
diff --git a/pom.xml b/pom.xml
index 0a7e850..c415b2c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,63 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>uk.co.ziazoo</groupId>
<artifactId>fussy</artifactId>
- <version>0.1-SNAPSHOT</version>
+ <version>0.2-SNAPSHOT</version>
<packaging>swc</packaging>
<name>Fussy query language</name>
<properties>
<flexversion>3.5.0.12683</flexversion>
<mojoversion>3.5.0</mojoversion>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.sonatype.flexmojos</groupId>
<artifactId>flexmojos-maven-plugin</artifactId>
<version>${mojoversion}</version>
<extensions>true</extensions>
<configuration>
<keepAs3Metadatas>
<!-- can i just keep these for tests? -->
<keepAs3Metadata>Inject</keepAs3Metadata>
<keepAs3Metadata>Fussy</keepAs3Metadata>
</keepAs3Metadatas>
</configuration>
<dependencies>
<dependency>
<groupId>com.adobe.flex</groupId>
<artifactId>compiler</artifactId>
<version>${flexversion}</version>
<type>pom</type>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.adobe.flex.framework</groupId>
<artifactId>flex-framework</artifactId>
<version>${flexversion}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.sonatype.flexmojos</groupId>
<artifactId>flexmojos-unittest-support</artifactId>
<version>${mojoversion}</version>
<type>swc</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.adobe.flexunit</groupId>
<artifactId>flexunit</artifactId>
<version>4.0-rc-1</version>
<type>swc</type>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as
index 9c4f6c6..25bd044 100644
--- a/src/uk/co/ziazoo/fussy/Fussy.as
+++ b/src/uk/co/ziazoo/fussy/Fussy.as
@@ -1,69 +1,54 @@
package uk.co.ziazoo.fussy
{
+ import flash.system.ApplicationDomain;
import flash.system.Capabilities;
import flash.utils.Dictionary;
import uk.co.ziazoo.fussy.parser.AccessorParser;
import uk.co.ziazoo.fussy.parser.ConstructorParser;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.parser.MetadataParser;
import uk.co.ziazoo.fussy.parser.MethodParser;
import uk.co.ziazoo.fussy.parser.ParameterParser;
import uk.co.ziazoo.fussy.parser.PropertyParser;
import uk.co.ziazoo.fussy.parser.VariableParser;
import uk.co.ziazoo.fussy.query.QueryBuilder;
public class Fussy
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
private var metadataParser:MetadataParser;
private var _reflector:IReflector;
public function Fussy(reflector:IReflector = null)
{
var parameterParser:ParameterParser = new ParameterParser();
metadataParser = new MetadataParser();
methodParser = new MethodParser(parameterParser, metadataParser);
propertyParser = new PropertyParser(
new VariableParser(metadataParser), new AccessorParser(metadataParser));
constructorParser = new ConstructorParser(parameterParser);
_reflector = reflector;
}
public function query():QueryBuilder
{
return new QueryBuilder(reflector, methodParser,
propertyParser, constructorParser, metadataParser);
}
public function get reflector():IReflector
{
if (!_reflector) {
- _reflector = new Reflector(needsFlashPlayerHack());
+ _reflector = new Reflector();
}
return _reflector;
}
-
- /**
- * @private
- */
- internal static function needsFlashPlayerHack():Boolean
- {
- var versionNumber:String = Capabilities.version;
- var versionArray:Array = versionNumber.split(",");
- var osPlusVersion:Array = versionArray[0].split(" ");
-
- var major:int = parseInt(osPlusVersion[1]);
- var minor:int = parseInt(versionArray[1]);
- var build:int = parseInt(versionArray[2]);
-
- return !(major >= 10 && minor >= 1 && build >= 52);
- }
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/IReflector.as b/src/uk/co/ziazoo/fussy/IReflector.as
index f26c738..3e00d41 100644
--- a/src/uk/co/ziazoo/fussy/IReflector.as
+++ b/src/uk/co/ziazoo/fussy/IReflector.as
@@ -1,39 +1,44 @@
package uk.co.ziazoo.fussy
{
+ import flash.system.ApplicationDomain;
+
/**
* stores result of describeType calls
*/
public interface IReflector
{
/**
* Get reflection for a class
* @param type the class to reflect
* @return result of describeType
*/
function forType(type:Class):XML;
/**
* Get reflection for a types qualified name
* @param qName of type to reflect
* @return result of describeType
*/
function forQName(qName:String):XML;
/**
* Release all type description in memory (drop references)
*/
function clearAll():void;
/**
* Release specific types description
* @param type who's description reference can be released
*/
function clearForType(type:Class):void;
/**
* Release specific types description
* @param qName of type who's description reference can be released
*/
function clearForQName(qName:String):void;
+
+ function get applicationDomain():ApplicationDomain;
+ function set applicationDomain(value:ApplicationDomain):void;
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/Reflector.as b/src/uk/co/ziazoo/fussy/Reflector.as
index d3f24ac..87fc621 100644
--- a/src/uk/co/ziazoo/fussy/Reflector.as
+++ b/src/uk/co/ziazoo/fussy/Reflector.as
@@ -1,100 +1,112 @@
package uk.co.ziazoo.fussy
{
+ import flash.system.ApplicationDomain;
import flash.utils.Dictionary;
import flash.utils.describeType;
- import flash.utils.getDefinitionByName;
public class Reflector implements IReflector
{
private var cache:Dictionary;
- private var needsPlayerFix:Boolean;
+ private var _applicationDomain:ApplicationDomain;
- public function Reflector(needsPlayerFix:Boolean = false)
+ public function Reflector()
{
- this.needsPlayerFix = needsPlayerFix;
cache = new Dictionary();
}
/**
* @inheritDoc
*/
public function forType(type:Class):XML
{
var description:XML = cache[type] as XML;
if (description)
{
return description;
}
description = describeType(type);
-
- if (needsPlayerFix)
+ var constructor:XML = description.factory.constructor[0];
+
+ if ( constructor &&
+ constructor.parameter.(@type == "*").length()
+ == [email protected]())
{
- var parameters:XMLList = description.factory.constructor.parameter;
+ var parameters:XMLList = constructor.parameter;
if (parameters.length() > 0)
{
try
{
var args:Array = [];
for (var i:int = 0; i < parameters.length(); i++)
{
args.push(null);
}
InstanceCreator.create(type, args);
description = describeType(type);
}
catch(error:Error)
{
}
}
}
cache[type] = description;
return description;
}
/**
* @inheritDoc
*/
public function forQName(qName:String):XML
{
- var type:Class = Class(getDefinitionByName(qName));
+ var type:Class = Class(applicationDomain.getDefinition(qName));
return forType(type);
}
/**
* @inheritDoc
*/
public function clearAll():void
{
cache = null;
cache = new Dictionary();
}
/**
* @inheritDoc
*/
public function clearForType(type:Class):void
{
if (cache[type])
{
delete cache[type];
}
}
/**
* @inheritDoc
*/
public function clearForQName(qName:String):void
{
- var type:Class = Class(getDefinitionByName(qName));
+ var type:Class = Class(applicationDomain.getDefinition(qName));
clearForType(type);
}
public function hasReflection(type:Class):Boolean
{
return cache[type] != null;
}
+
+ public function get applicationDomain():ApplicationDomain
+ {
+ return _applicationDomain || ApplicationDomain.currentDomain;
+ }
+
+ public function set applicationDomain(value:ApplicationDomain):void
+ {
+ _applicationDomain = value;
+ }
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/TypeQuery.as b/src/uk/co/ziazoo/fussy/query/TypeQuery.as
index adb6cf4..5140d78 100644
--- a/src/uk/co/ziazoo/fussy/query/TypeQuery.as
+++ b/src/uk/co/ziazoo/fussy/query/TypeQuery.as
@@ -1,87 +1,86 @@
package uk.co.ziazoo.fussy.query
{
import flash.utils.Dictionary;
- import flash.utils.getDefinitionByName;
import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.TypeDescription;
import uk.co.ziazoo.fussy.model.Constructor;
import uk.co.ziazoo.fussy.parser.IResultParser;
public class TypeQuery implements ITypeQuery
{
private var reflector:IReflector;
private var constructorParser:IResultParser;
private var metadataParser:IResultParser;
private var cache:Dictionary;
public function TypeQuery(reflector:IReflector,
constructorParser:IResultParser, metadataParser:IResultParser)
{
this.reflector = reflector;
this.constructorParser = constructorParser;
this.metadataParser = metadataParser;
this.cache = new Dictionary();
}
public function forType(type:Class):TypeDescription
{
var description:TypeDescription = cache[type] as TypeDescription;
if (description)
{
return description;
}
var reflection:XML = reflector.forType(type);
description = new TypeDescription
(
getQName(reflection),
getIsDynamic(reflection),
getIsFinal(reflection),
getConstructor(reflection),
getMetadata(reflection)
);
cache[type] = description;
return description;
}
public function forQName(qName:String):TypeDescription
{
- return forType(Class(getDefinitionByName(qName)));
+ return forType(Class(reflector.applicationDomain.getDefinition(qName)));
}
private function getQName(reflection:XML):String
{
return reflection.@name;
}
private function getIsDynamic(reflection:XML):Boolean
{
return String(reflection.@isDynamic) == "true";
}
private function getIsFinal(reflection:XML):Boolean
{
return String(reflection.@isFinal) == "true";
}
private function getConstructor(reflection:XML):Constructor
{
var result:Array = constructorParser.parse(reflection.factory);
var constructor:Constructor = result[0] as Constructor;
return constructor;
}
private function getMetadata(reflection:XML):Array
{
return metadataParser.parse(reflection.factory.metadata);
}
internal function hasTypeCached(type:Class):Boolean
{
return cache[type] != null;
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/ReflectorTest.as b/test/uk/co/ziazoo/fussy/ReflectorTest.as
index c25a7bb..1f8bbde 100644
--- a/test/uk/co/ziazoo/fussy/ReflectorTest.as
+++ b/test/uk/co/ziazoo/fussy/ReflectorTest.as
@@ -1,113 +1,113 @@
package uk.co.ziazoo.fussy
{
import flash.system.Capabilities;
import flash.utils.getQualifiedClassName;
import org.flexunit.Assert;
public class ReflectorTest
{
private var reflector:Reflector;
public function ReflectorTest()
{
}
[Before]
public function setUp():void
{
- reflector = new Reflector(Fussy.needsFlashPlayerHack());
+ reflector = new Reflector();
}
[After]
public function tearDown():void
{
reflector = null;
}
[Test]
public function doesCache():void
{
var desc:XML = reflector.forType(Bubbles);
Assert.assertNotNull(desc);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
}
[Test]
public function getCorrectResult():void
{
var desc:XML = reflector.forType(Bubbles);
Assert.assertNotNull(desc);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(desc, reflector.forType(Bubbles));
}
[Test]
public function getForQName():void
{
var desc:XML = reflector.forQName(getQualifiedClassName(Bubbles));
Assert.assertNotNull(desc);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(desc, reflector.forType(Bubbles));
}
[Test]
public function clearAll():void
{
reflector.forType(Bubbles);
reflector.forType(Wibble);
reflector.forType(Array);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(true, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
reflector.clearAll();
Assert.assertEquals(false, reflector.hasReflection(Bubbles));
Assert.assertEquals(false, reflector.hasReflection(Wibble));
Assert.assertEquals(false, reflector.hasReflection(Array));
}
[Test]
public function clearSomeByType():void
{
reflector.forType(Bubbles);
reflector.forType(Wibble);
reflector.forType(Array);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(true, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
reflector.clearForType(Wibble)
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(false, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
}
[Test]
public function clearSomeByQName():void
{
reflector.forType(Bubbles);
reflector.forType(Wibble);
reflector.forType(Array);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(true, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
reflector.clearForQName(getQualifiedClassName(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(false, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
index e9a75b4..d4d5820 100644
--- a/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
+++ b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
@@ -1,61 +1,61 @@
package uk.co.ziazoo.fussy.parser
{
import flash.utils.describeType;
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.Banana;
import uk.co.ziazoo.fussy.Bubbles;
import uk.co.ziazoo.fussy.Fussy;
import uk.co.ziazoo.fussy.Reflector;
import uk.co.ziazoo.fussy.model.Constructor;
import uk.co.ziazoo.fussy.model.Parameter;
public class ConstructorParserTest
{
public function ConstructorParserTest()
{
}
[Test]
public function parseConsructor():void
{
var parser:ConstructorParser =
new ConstructorParser(new ParameterParser());
- var reflector:Reflector = new Reflector(true);
+ var reflector:Reflector = new Reflector();
var result:Array = parser.parse(reflector.forType(Banana).factory);
var constructor:Constructor = result[0] as Constructor;
Assert.assertNotNull(constructor);
Assert.assertEquals(2, constructor.parameters.length);
var param1:Parameter = constructor.parameters[0] as Parameter;
Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", param1.type);
var param2:Parameter = constructor.parameters[1] as Parameter;
Assert.assertEquals("Array", param2.type);
}
[Test]
public function parseOneParamConsructor():void
{
var parser:ConstructorParser =
new ConstructorParser(new ParameterParser());
- var reflector:Reflector = new Reflector(true);
+ var reflector:Reflector = new Reflector();
var result:Array = parser.parse(reflector.forType(Bubbles).factory);
var constructor:Constructor = result[0] as Constructor;
Assert.assertNotNull(constructor);
Assert.assertEquals(1, constructor.parameters.length);
var param1:Parameter = constructor.parameters[0] as Parameter;
Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", param1.type);
}
}
}
\ No newline at end of file
|
sammyt/fussy | 46c32782a5777d89ba8d2dd7c2e158c902c20655 | added line endings | diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as
index 2e14411..9c4f6c6 100644
--- a/src/uk/co/ziazoo/fussy/Fussy.as
+++ b/src/uk/co/ziazoo/fussy/Fussy.as
@@ -1,70 +1,69 @@
package uk.co.ziazoo.fussy
{
import flash.system.Capabilities;
import flash.utils.Dictionary;
import uk.co.ziazoo.fussy.parser.AccessorParser;
import uk.co.ziazoo.fussy.parser.ConstructorParser;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.parser.MetadataParser;
import uk.co.ziazoo.fussy.parser.MethodParser;
import uk.co.ziazoo.fussy.parser.ParameterParser;
import uk.co.ziazoo.fussy.parser.PropertyParser;
import uk.co.ziazoo.fussy.parser.VariableParser;
import uk.co.ziazoo.fussy.query.QueryBuilder;
public class Fussy
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
- private var metadataParser:MetadataParser
+ private var metadataParser:MetadataParser;
private var _reflector:IReflector;
public function Fussy(reflector:IReflector = null)
{
var parameterParser:ParameterParser = new ParameterParser();
metadataParser = new MetadataParser();
methodParser = new MethodParser(parameterParser, metadataParser);
propertyParser = new PropertyParser(
- new VariableParser(metadataParser), new AccessorParser(metadataParser));
+ new VariableParser(metadataParser), new AccessorParser(metadataParser));
constructorParser = new ConstructorParser(parameterParser);
_reflector = reflector;
}
public function query():QueryBuilder
{
return new QueryBuilder(reflector, methodParser,
- propertyParser, constructorParser, metadataParser);
+ propertyParser, constructorParser, metadataParser);
}
public function get reflector():IReflector
{
- if (!_reflector)
- {
+ if (!_reflector) {
_reflector = new Reflector(needsFlashPlayerHack());
}
return _reflector;
}
/**
* @private
*/
internal static function needsFlashPlayerHack():Boolean
{
- var versionNumber:String = Capabilities.version
+ var versionNumber:String = Capabilities.version;
var versionArray:Array = versionNumber.split(",");
var osPlusVersion:Array = versionArray[0].split(" ");
var major:int = parseInt(osPlusVersion[1]);
var minor:int = parseInt(versionArray[1]);
var build:int = parseInt(versionArray[2]);
return !(major >= 10 && minor >= 1 && build >= 52);
}
}
}
\ No newline at end of file
|
sammyt/fussy | 540f9ac15a3bf247c408841d5c61e43a40f65b81 | fixed issue with variable filters and started namespace investagation | diff --git a/src/uk/co/ziazoo/fussy/query/IQueryBuilder.as b/src/uk/co/ziazoo/fussy/query/IQueryBuilder.as
new file mode 100644
index 0000000..162ffc2
--- /dev/null
+++ b/src/uk/co/ziazoo/fussy/query/IQueryBuilder.as
@@ -0,0 +1,20 @@
+package uk.co.ziazoo.fussy.query
+{
+ import uk.co.ziazoo.fussy.accessors.AccessorQueryChain;
+ import uk.co.ziazoo.fussy.methods.MethodQueryChain;
+ import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
+ import uk.co.ziazoo.fussy.variables.VariableQueryChain;
+
+ public interface IQueryBuilder
+ {
+ function getTypeQuery():ITypeQuery;
+
+ function findMethods():MethodQueryChain;
+
+ function findProperties():PropertyQueryChain;
+
+ function findAccessors():AccessorQueryChain;
+
+ function findVariables():VariableQueryChain;
+ }
+}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/QueryBuilder.as b/src/uk/co/ziazoo/fussy/query/QueryBuilder.as
index b485ecb..abb1098 100644
--- a/src/uk/co/ziazoo/fussy/query/QueryBuilder.as
+++ b/src/uk/co/ziazoo/fussy/query/QueryBuilder.as
@@ -1,55 +1,54 @@
package uk.co.ziazoo.fussy.query
{
import uk.co.ziazoo.fussy.IReflector;
- import uk.co.ziazoo.fussy.TypeDescription;
import uk.co.ziazoo.fussy.accessors.AccessorQueryChain;
import uk.co.ziazoo.fussy.methods.MethodQueryChain;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
import uk.co.ziazoo.fussy.variables.VariableQueryChain;
- public class QueryBuilder
+ public class QueryBuilder implements IQueryBuilder
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
private var metadataParser:IResultParser;
private var reflector:IReflector;
public function QueryBuilder(reflector:IReflector, methodParser:IResultParser,
propertyParser:IResultParser, constructorParser:IResultParser,
metadataParser:IResultParser)
{
this.propertyParser = propertyParser;
this.methodParser = methodParser;
this.constructorParser = constructorParser;
this.metadataParser = metadataParser;
this.reflector = reflector;
}
public function getTypeQuery():ITypeQuery
{
return new TypeQuery(reflector, constructorParser, metadataParser);
}
public function findMethods():MethodQueryChain
{
return new MethodQueryChain(reflector, methodParser);
}
public function findProperties():PropertyQueryChain
{
return new PropertyQueryChain(reflector, propertyParser);
}
public function findAccessors():AccessorQueryChain
{
return new AccessorQueryChain(reflector, propertyParser);
}
public function findVariables():VariableQueryChain
{
return new VariableQueryChain(reflector, propertyParser);
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/WithMetadata.as b/src/uk/co/ziazoo/fussy/query/WithMetadata.as
index 8dde29a..e60a8d8 100644
--- a/src/uk/co/ziazoo/fussy/query/WithMetadata.as
+++ b/src/uk/co/ziazoo/fussy/query/WithMetadata.as
@@ -1,20 +1,21 @@
package uk.co.ziazoo.fussy.query
{
dynamic public class WithMetadata implements IQueryPart
{
private var name:String;
public function WithMetadata(name:String)
{
this.name = name;
}
public function filter(data:XMLList):XMLList
{
+ var a:String = data.toString();
return data.(
hasOwnProperty("metadata") && metadata.(@name == name).length() > 0
);
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as
index 5c271d5..5a38d5d 100644
--- a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as
@@ -1,20 +1,20 @@
package uk.co.ziazoo.fussy.variables
{
import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
public class VariableQueryChain extends PropertyQueryChain
{
public function VariableQueryChain(reflector:IReflector,
parser:IResultParser)
{
super(reflector, parser);
}
override protected function getList(reflection:XML):XMLList
{
- return reflection.factory.varaible;
+ return reflection.factory.variable;
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as
index ac067a5..4c4aef0 100644
--- a/test/uk/co/ziazoo/fussy/FussyTest.as
+++ b/test/uk/co/ziazoo/fussy/FussyTest.as
@@ -1,82 +1,110 @@
package uk.co.ziazoo.fussy
{
+ import flash.utils.describeType;
+
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.model.Method;
import uk.co.ziazoo.fussy.query.IQuery;
public class FussyTest
{
[Test]
public function findInjectableMethods():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withMetadata("Inject").withArguments();
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "wowowo");
Assert.assertEquals(method.parameters.length, 2);
}
[Test]
public function findInjectableProperties():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findProperties().withMetadata("Inject");
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
}
[Test]
public function findInjectableVars():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findVariables().withMetadata("Inject");
var list:Array = query.forType(Bubbles);
Assert.assertEquals(0, list.length);
}
[Test]
public function filterBySignature():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withTypeSignature(int, String);
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "wowowo");
}
[Test]
- public function filterByArgsLengh():void
+ public function filterByArgsLength():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withArgsLengthOf(1);
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "doIt");
}
+ [Test]
+ [Ignore]
+ public function letsSee():void
+ {
+ var a:XML = describeType(Thing);
+ trace(a);
+
+ var ns:Namespace = new Namespace("inject.demo");
+ var thing:Thing = new Thing();
+ var f:* = ns::thing["doItBacon"];
+
+ trace(f);
+ }
+
+
+ [Test]
+ public function issue3Test():void
+ {
+ var fussy:Fussy = new Fussy();
+ var query1:IQuery = fussy.query().findVariables().withMetadata("Fussy");
+ var list1:Array = query1.forType(Bubbles);
+
+ Assert.assertEquals(list1.length, 1);
+ trace("list1.length:", list1.length);
+ }
+
[Test]
[Ignore]
public function getTypeDescription():void
{
var fussy:Fussy = new Fussy();
var description:TypeDescription = fussy.query().getTypeQuery().forType(Bubbles);
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/Thing.as b/test/uk/co/ziazoo/fussy/Thing.as
new file mode 100644
index 0000000..c8fe784
--- /dev/null
+++ b/test/uk/co/ziazoo/fussy/Thing.as
@@ -0,0 +1,30 @@
+package uk.co.ziazoo.fussy
+{
+ use namespace demo;
+ use namespace nibble;
+
+ public class Thing
+ {
+ public function Thing()
+ {
+ }
+
+ demo function imInDemoNameSpace():void
+ {
+
+ }
+
+ nibble function doItBacon():void
+ {
+
+ }
+
+ demo function doItBacon():void
+ {
+
+ }
+ }
+}
+
+namespace nibble = "inject.nibble";
+namespace foo = "inject.foo";
diff --git a/test/uk/co/ziazoo/fussy/demo.as b/test/uk/co/ziazoo/fussy/demo.as
new file mode 100644
index 0000000..cfba751
--- /dev/null
+++ b/test/uk/co/ziazoo/fussy/demo.as
@@ -0,0 +1,4 @@
+package uk.co.ziazoo.fussy
+{
+ public namespace demo="inject.demo";
+}
\ No newline at end of file
|
sammyt/fussy | 72cf9d4e8805a63faffabfe1d553002ed96436ee | renamed query to query builder for clarity | diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as
index de70ffa..2e14411 100644
--- a/src/uk/co/ziazoo/fussy/Fussy.as
+++ b/src/uk/co/ziazoo/fussy/Fussy.as
@@ -1,70 +1,70 @@
package uk.co.ziazoo.fussy
{
import flash.system.Capabilities;
import flash.utils.Dictionary;
import uk.co.ziazoo.fussy.parser.AccessorParser;
import uk.co.ziazoo.fussy.parser.ConstructorParser;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.parser.MetadataParser;
import uk.co.ziazoo.fussy.parser.MethodParser;
import uk.co.ziazoo.fussy.parser.ParameterParser;
import uk.co.ziazoo.fussy.parser.PropertyParser;
import uk.co.ziazoo.fussy.parser.VariableParser;
- import uk.co.ziazoo.fussy.query.Query;
+ import uk.co.ziazoo.fussy.query.QueryBuilder;
public class Fussy
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
private var metadataParser:MetadataParser
private var _reflector:IReflector;
public function Fussy(reflector:IReflector = null)
{
var parameterParser:ParameterParser = new ParameterParser();
metadataParser = new MetadataParser();
methodParser = new MethodParser(parameterParser, metadataParser);
propertyParser = new PropertyParser(
new VariableParser(metadataParser), new AccessorParser(metadataParser));
constructorParser = new ConstructorParser(parameterParser);
_reflector = reflector;
}
- public function query():Query
+ public function query():QueryBuilder
{
- return new Query(reflector, methodParser,
+ return new QueryBuilder(reflector, methodParser,
propertyParser, constructorParser, metadataParser);
}
public function get reflector():IReflector
{
if (!_reflector)
{
_reflector = new Reflector(needsFlashPlayerHack());
}
return _reflector;
}
/**
* @private
*/
internal static function needsFlashPlayerHack():Boolean
{
var versionNumber:String = Capabilities.version
var versionArray:Array = versionNumber.split(",");
var osPlusVersion:Array = versionArray[0].split(" ");
var major:int = parseInt(osPlusVersion[1]);
var minor:int = parseInt(versionArray[1]);
var build:int = parseInt(versionArray[2]);
return !(major >= 10 && minor >= 1 && build >= 52);
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/QueryBuilder.as
similarity index 93%
rename from src/uk/co/ziazoo/fussy/query/Query.as
rename to src/uk/co/ziazoo/fussy/query/QueryBuilder.as
index 0328fa6..b485ecb 100644
--- a/src/uk/co/ziazoo/fussy/query/Query.as
+++ b/src/uk/co/ziazoo/fussy/query/QueryBuilder.as
@@ -1,55 +1,55 @@
package uk.co.ziazoo.fussy.query
{
import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.TypeDescription;
import uk.co.ziazoo.fussy.accessors.AccessorQueryChain;
import uk.co.ziazoo.fussy.methods.MethodQueryChain;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
import uk.co.ziazoo.fussy.variables.VariableQueryChain;
- public class Query
+ public class QueryBuilder
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
private var metadataParser:IResultParser;
private var reflector:IReflector;
- public function Query(reflector:IReflector, methodParser:IResultParser,
+ public function QueryBuilder(reflector:IReflector, methodParser:IResultParser,
propertyParser:IResultParser, constructorParser:IResultParser,
metadataParser:IResultParser)
{
this.propertyParser = propertyParser;
this.methodParser = methodParser;
this.constructorParser = constructorParser;
this.metadataParser = metadataParser;
this.reflector = reflector;
}
public function getTypeQuery():ITypeQuery
{
return new TypeQuery(reflector, constructorParser, metadataParser);
}
public function findMethods():MethodQueryChain
{
return new MethodQueryChain(reflector, methodParser);
}
public function findProperties():PropertyQueryChain
{
return new PropertyQueryChain(reflector, propertyParser);
}
public function findAccessors():AccessorQueryChain
{
return new AccessorQueryChain(reflector, propertyParser);
}
public function findVariables():VariableQueryChain
{
return new VariableQueryChain(reflector, propertyParser);
}
}
}
\ No newline at end of file
|
sammyt/fussy | d185e26dd9053a2fa5a02ddbfb1d06ba8b714cde | implemented fix for FP-183 and added method invoke option | diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as
index 760f01b..de70ffa 100644
--- a/src/uk/co/ziazoo/fussy/Fussy.as
+++ b/src/uk/co/ziazoo/fussy/Fussy.as
@@ -1,50 +1,70 @@
package uk.co.ziazoo.fussy
{
+ import flash.system.Capabilities;
+
+ import flash.utils.Dictionary;
+
import uk.co.ziazoo.fussy.parser.AccessorParser;
import uk.co.ziazoo.fussy.parser.ConstructorParser;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.parser.MetadataParser;
import uk.co.ziazoo.fussy.parser.MethodParser;
import uk.co.ziazoo.fussy.parser.ParameterParser;
import uk.co.ziazoo.fussy.parser.PropertyParser;
import uk.co.ziazoo.fussy.parser.VariableParser;
import uk.co.ziazoo.fussy.query.Query;
public class Fussy
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
private var metadataParser:MetadataParser
private var _reflector:IReflector;
public function Fussy(reflector:IReflector = null)
{
var parameterParser:ParameterParser = new ParameterParser();
metadataParser = new MetadataParser();
methodParser = new MethodParser(parameterParser, metadataParser);
propertyParser = new PropertyParser(
new VariableParser(metadataParser), new AccessorParser(metadataParser));
constructorParser = new ConstructorParser(parameterParser);
_reflector = reflector;
}
public function query():Query
{
return new Query(reflector, methodParser,
propertyParser, constructorParser, metadataParser);
}
public function get reflector():IReflector
{
if (!_reflector)
{
- _reflector = new Reflector();
+ _reflector = new Reflector(needsFlashPlayerHack());
}
return _reflector;
}
+
+ /**
+ * @private
+ */
+ internal static function needsFlashPlayerHack():Boolean
+ {
+ var versionNumber:String = Capabilities.version
+ var versionArray:Array = versionNumber.split(",");
+ var osPlusVersion:Array = versionArray[0].split(" ");
+
+ var major:int = parseInt(osPlusVersion[1]);
+ var minor:int = parseInt(versionArray[1]);
+ var build:int = parseInt(versionArray[2]);
+
+ return !(major >= 10 && minor >= 1 && build >= 52);
+ }
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/InstanceCreator.as b/src/uk/co/ziazoo/fussy/InstanceCreator.as
index 0baf4e4..f031d53 100644
--- a/src/uk/co/ziazoo/fussy/InstanceCreator.as
+++ b/src/uk/co/ziazoo/fussy/InstanceCreator.as
@@ -1,40 +1,41 @@
package uk.co.ziazoo.fussy
{
public class InstanceCreator
{
- public static function create( type:Class, params:Array ):Object
+ public static function create(type:Class, params:Array):Object
{
- if( !params )
+ if (!params)
{
return new type();
}
-
- switch ( params.length ) {
+
+ switch (params.length)
+ {
case 0:
return new type();
case 1:
return new type(params[0]);
case 2:
return new type(params[0], params[1]);
case 3:
return new type(params[0], params[1], params[2]);
case 4:
return new type(params[0], params[1], params[2], params[3]);
case 5:
return new type(params[0], params[1], params[2], params[3], params[4]);
case 6:
return new type(params[0], params[1], params[2], params[3], params[4], params[5]);
case 7:
return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6]);
case 8:
return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7]);
case 9:
return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7], params[8]);
case 10:
return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7], params[8], params[9]);
}
return null;
}
}
}
diff --git a/src/uk/co/ziazoo/fussy/Reflector.as b/src/uk/co/ziazoo/fussy/Reflector.as
index e9cd76f..d3f24ac 100644
--- a/src/uk/co/ziazoo/fussy/Reflector.as
+++ b/src/uk/co/ziazoo/fussy/Reflector.as
@@ -1,76 +1,100 @@
package uk.co.ziazoo.fussy
{
import flash.utils.Dictionary;
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
public class Reflector implements IReflector
{
private var cache:Dictionary;
+ private var needsPlayerFix:Boolean;
- public function Reflector()
+ public function Reflector(needsPlayerFix:Boolean = false)
{
+ this.needsPlayerFix = needsPlayerFix;
cache = new Dictionary();
}
/**
* @inheritDoc
*/
public function forType(type:Class):XML
{
var description:XML = cache[type] as XML;
if (description)
{
return description;
}
- description = cache[type] = describeType(type);
+ description = describeType(type);
+ if (needsPlayerFix)
+ {
+ var parameters:XMLList = description.factory.constructor.parameter;
+ if (parameters.length() > 0)
+ {
+ try
+ {
+ var args:Array = [];
+ for (var i:int = 0; i < parameters.length(); i++)
+ {
+ args.push(null);
+ }
+ InstanceCreator.create(type, args);
+ description = describeType(type);
+ }
+ catch(error:Error)
+ {
+ }
+ }
+ }
+
+ cache[type] = description;
return description;
}
/**
* @inheritDoc
*/
public function forQName(qName:String):XML
{
var type:Class = Class(getDefinitionByName(qName));
return forType(type);
}
/**
* @inheritDoc
*/
public function clearAll():void
{
cache = null;
cache = new Dictionary();
}
/**
* @inheritDoc
*/
public function clearForType(type:Class):void
{
if (cache[type])
{
delete cache[type];
}
}
/**
* @inheritDoc
*/
public function clearForQName(qName:String):void
{
var type:Class = Class(getDefinitionByName(qName));
clearForType(type);
}
- public function hasReflection(type):Boolean
+ public function hasReflection(type:Class):Boolean
{
return cache[type] != null;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/model/Method.as b/src/uk/co/ziazoo/fussy/model/Method.as
index 91f6424..1d350a3 100644
--- a/src/uk/co/ziazoo/fussy/model/Method.as
+++ b/src/uk/co/ziazoo/fussy/model/Method.as
@@ -1,13 +1,19 @@
package uk.co.ziazoo.fussy.model
{
public class Method
{
public var name:String;
public var parameters:Array;
public var metadata:Array;
public function Method()
{
}
+
+ public function invoke(instance:Object, args:Array = null):Object
+ {
+ var fnt:Function = instance[ name ] as Function;
+ return fnt.apply(instance, args);
+ }
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/model/Property.as b/src/uk/co/ziazoo/fussy/model/Property.as
index fc26594..96c7994 100644
--- a/src/uk/co/ziazoo/fussy/model/Property.as
+++ b/src/uk/co/ziazoo/fussy/model/Property.as
@@ -1,13 +1,23 @@
package uk.co.ziazoo.fussy.model
{
public class Property
{
public var name:String;
public var type:String;
public var metadata:Array;
public function Property()
{
}
+
+ public function setter(instance:Object, arg:Object):void
+ {
+ instance[name] = arg;
+ }
+
+ public function getter(instance:Object):Object
+ {
+ return instance[name];
+ }
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as
index 7b8461c..f61bd23 100644
--- a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as
+++ b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as
@@ -1,28 +1,27 @@
package uk.co.ziazoo.fussy.parser
{
public class PropertyParser implements IResultParser
{
private var variableParser:VariableParser;
private var accessorParser:AccessorParser;
public function PropertyParser(variableParser:VariableParser,
accessorParser:AccessorParser)
{
this.variableParser = variableParser;
this.accessorParser = accessorParser;
}
public function parse(result:XMLList):Array
{
- trace(result);
var root:XML = <root/>;
root.appendChild(result);
var accessors:Array = accessorParser.parse(root.accessor);
var variables:Array = variableParser.parse(root.variable);
var properties:Array = accessors.concat(variables);
return properties;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/Query.as
index abdb186..0328fa6 100644
--- a/src/uk/co/ziazoo/fussy/query/Query.as
+++ b/src/uk/co/ziazoo/fussy/query/Query.as
@@ -1,55 +1,55 @@
package uk.co.ziazoo.fussy.query
{
import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.TypeDescription;
import uk.co.ziazoo.fussy.accessors.AccessorQueryChain;
import uk.co.ziazoo.fussy.methods.MethodQueryChain;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
import uk.co.ziazoo.fussy.variables.VariableQueryChain;
public class Query
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
private var metadataParser:IResultParser;
private var reflector:IReflector;
public function Query(reflector:IReflector, methodParser:IResultParser,
propertyParser:IResultParser, constructorParser:IResultParser,
metadataParser:IResultParser)
{
this.propertyParser = propertyParser;
this.methodParser = methodParser;
this.constructorParser = constructorParser;
this.metadataParser = metadataParser;
this.reflector = reflector;
}
- public function getTypeQuery(type:Class):ITypeQuery
+ public function getTypeQuery():ITypeQuery
{
return new TypeQuery(reflector, constructorParser, metadataParser);
}
public function findMethods():MethodQueryChain
{
return new MethodQueryChain(reflector, methodParser);
}
public function findProperties():PropertyQueryChain
{
return new PropertyQueryChain(reflector, propertyParser);
}
public function findAccessors():AccessorQueryChain
{
return new AccessorQueryChain(reflector, propertyParser);
}
public function findVariables():VariableQueryChain
{
return new VariableQueryChain(reflector, propertyParser);
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/TypeQuery.as b/src/uk/co/ziazoo/fussy/query/TypeQuery.as
index 88e7d60..adb6cf4 100644
--- a/src/uk/co/ziazoo/fussy/query/TypeQuery.as
+++ b/src/uk/co/ziazoo/fussy/query/TypeQuery.as
@@ -1,87 +1,87 @@
package uk.co.ziazoo.fussy.query
{
import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;
import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.TypeDescription;
import uk.co.ziazoo.fussy.model.Constructor;
import uk.co.ziazoo.fussy.parser.IResultParser;
public class TypeQuery implements ITypeQuery
{
private var reflector:IReflector;
private var constructorParser:IResultParser;
private var metadataParser:IResultParser;
private var cache:Dictionary;
public function TypeQuery(reflector:IReflector,
constructorParser:IResultParser, metadataParser:IResultParser)
{
this.reflector = reflector;
this.constructorParser = constructorParser;
this.metadataParser = metadataParser;
this.cache = new Dictionary();
}
public function forType(type:Class):TypeDescription
{
var description:TypeDescription = cache[type] as TypeDescription;
if (description)
{
return description;
}
var reflection:XML = reflector.forType(type);
- trace(reflection);
+
description = new TypeDescription
(
getQName(reflection),
getIsDynamic(reflection),
getIsFinal(reflection),
getConstructor(reflection),
getMetadata(reflection)
);
cache[type] = description;
return description;
}
public function forQName(qName:String):TypeDescription
{
return forType(Class(getDefinitionByName(qName)));
}
private function getQName(reflection:XML):String
{
return reflection.@name;
}
private function getIsDynamic(reflection:XML):Boolean
{
return String(reflection.@isDynamic) == "true";
}
private function getIsFinal(reflection:XML):Boolean
{
return String(reflection.@isFinal) == "true";
}
private function getConstructor(reflection:XML):Constructor
{
var result:Array = constructorParser.parse(reflection.factory);
var constructor:Constructor = result[0] as Constructor;
return constructor;
}
private function getMetadata(reflection:XML):Array
{
return metadataParser.parse(reflection.factory.metadata);
}
internal function hasTypeCached(type:Class):Boolean
{
return cache[type] != null;
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as
index 69455d0..ac067a5 100644
--- a/test/uk/co/ziazoo/fussy/FussyTest.as
+++ b/test/uk/co/ziazoo/fussy/FussyTest.as
@@ -1,80 +1,82 @@
package uk.co.ziazoo.fussy
{
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.model.Method;
import uk.co.ziazoo.fussy.query.IQuery;
public class FussyTest
{
[Test]
public function findInjectableMethods():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withMetadata("Inject").withArguments();
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "wowowo");
Assert.assertEquals(method.parameters.length, 2);
}
[Test]
public function findInjectableProperties():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findProperties().withMetadata("Inject");
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
}
[Test]
public function findInjectableVars():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findVariables().withMetadata("Inject");
var list:Array = query.forType(Bubbles);
Assert.assertEquals(0, list.length);
}
[Test]
public function filterBySignature():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withTypeSignature(int, String);
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "wowowo");
}
[Test]
public function filterByArgsLengh():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withArgsLengthOf(1);
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "doIt");
}
[Test]
- public function getConstructor():void
+ [Ignore]
+ public function getTypeDescription():void
{
-
+ var fussy:Fussy = new Fussy();
+ var description:TypeDescription = fussy.query().getTypeQuery().forType(Bubbles);
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/ReflectorTest.as b/test/uk/co/ziazoo/fussy/ReflectorTest.as
index 3d9df73..c25a7bb 100644
--- a/test/uk/co/ziazoo/fussy/ReflectorTest.as
+++ b/test/uk/co/ziazoo/fussy/ReflectorTest.as
@@ -1,112 +1,113 @@
package uk.co.ziazoo.fussy
{
+ import flash.system.Capabilities;
import flash.utils.getQualifiedClassName;
import org.flexunit.Assert;
public class ReflectorTest
{
private var reflector:Reflector;
public function ReflectorTest()
{
}
[Before]
public function setUp():void
{
- reflector = new Reflector();
+ reflector = new Reflector(Fussy.needsFlashPlayerHack());
}
[After]
public function tearDown():void
{
reflector = null;
}
[Test]
public function doesCache():void
{
var desc:XML = reflector.forType(Bubbles);
Assert.assertNotNull(desc);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
}
[Test]
public function getCorrectResult():void
{
var desc:XML = reflector.forType(Bubbles);
Assert.assertNotNull(desc);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(desc, reflector.forType(Bubbles));
}
[Test]
public function getForQName():void
{
var desc:XML = reflector.forQName(getQualifiedClassName(Bubbles));
Assert.assertNotNull(desc);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(desc, reflector.forType(Bubbles));
}
[Test]
public function clearAll():void
{
reflector.forType(Bubbles);
reflector.forType(Wibble);
reflector.forType(Array);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(true, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
reflector.clearAll();
Assert.assertEquals(false, reflector.hasReflection(Bubbles));
Assert.assertEquals(false, reflector.hasReflection(Wibble));
Assert.assertEquals(false, reflector.hasReflection(Array));
}
[Test]
public function clearSomeByType():void
{
reflector.forType(Bubbles);
reflector.forType(Wibble);
reflector.forType(Array);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(true, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
reflector.clearForType(Wibble)
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(false, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
}
[Test]
public function clearSomeByQName():void
{
reflector.forType(Bubbles);
reflector.forType(Wibble);
reflector.forType(Array);
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(true, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
reflector.clearForQName(getQualifiedClassName(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Bubbles));
Assert.assertEquals(false, reflector.hasReflection(Wibble));
Assert.assertEquals(true, reflector.hasReflection(Array));
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
index 5b9b63d..e9a75b4 100644
--- a/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
+++ b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
@@ -1,38 +1,61 @@
package uk.co.ziazoo.fussy.parser
{
import flash.utils.describeType;
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.Banana;
import uk.co.ziazoo.fussy.Bubbles;
+ import uk.co.ziazoo.fussy.Fussy;
+ import uk.co.ziazoo.fussy.Reflector;
import uk.co.ziazoo.fussy.model.Constructor;
import uk.co.ziazoo.fussy.model.Parameter;
public class ConstructorParserTest
{
public function ConstructorParserTest()
{
}
[Test]
public function parseConsructor():void
{
var parser:ConstructorParser =
new ConstructorParser(new ParameterParser());
- var result:Array = parser.parse(describeType(Banana).factory);
+ var reflector:Reflector = new Reflector(true);
+
+ var result:Array = parser.parse(reflector.forType(Banana).factory);
var constructor:Constructor = result[0] as Constructor;
Assert.assertNotNull(constructor);
Assert.assertEquals(2, constructor.parameters.length);
var param1:Parameter = constructor.parameters[0] as Parameter;
Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", param1.type);
var param2:Parameter = constructor.parameters[1] as Parameter;
Assert.assertEquals("Array", param2.type);
}
+
+ [Test]
+ public function parseOneParamConsructor():void
+ {
+ var parser:ConstructorParser =
+ new ConstructorParser(new ParameterParser());
+
+ var reflector:Reflector = new Reflector(true);
+
+ var result:Array = parser.parse(reflector.forType(Bubbles).factory);
+
+ var constructor:Constructor = result[0] as Constructor;
+
+ Assert.assertNotNull(constructor);
+ Assert.assertEquals(1, constructor.parameters.length);
+
+ var param1:Parameter = constructor.parameters[0] as Parameter;
+ Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", param1.type);
+ }
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as
index a19a11a..f3502f6 100644
--- a/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as
+++ b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as
@@ -1,95 +1,93 @@
package uk.co.ziazoo.fussy.parser
{
import flash.utils.describeType;
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.Bubbles;
import uk.co.ziazoo.fussy.model.Accessor;
import uk.co.ziazoo.fussy.model.Metadata;
import uk.co.ziazoo.fussy.model.Property;
import uk.co.ziazoo.fussy.model.Variable;
public class PropertyParserTest
{
private var parser:PropertyParser;
public function PropertyParserTest()
{
}
[Before]
public function setUp():void
{
var metadataParser:MetadataParser = new MetadataParser();
parser = new PropertyParser(
new VariableParser(metadataParser),
new AccessorParser(metadataParser));
}
[Test]
public function tearDown():void
{
parser = null;
}
[Test]
public function parseSomeProperties():void
{
var description:XML = describeType(Bubbles);
var p:XMLList = new XMLList(<root/>);
p.appendChild(description.factory.variable);
p.appendChild(description.factory.accessor);
var props:XMLList = p.*;
- trace(props);
-
var properties:Array = parser.parse(props);
Assert.assertNotNull(properties);
Assert.assertTrue(properties.length == 7);
}
[Test]
public function canParseVariable():void
{
var v:XMLList = new XMLList(<root>
<variable name="wibble" type="uk.co.ziazoo.fussy::Wibble"/>
</root>);
var properties:Array = parser.parse(v.*);
Assert.assertNotNull(properties);
Assert.assertTrue(properties.length == 1);
var prop:Variable = properties[0] as Variable;
Assert.assertEquals("wibble", prop.name);
Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", prop.type);
}
[Test]
public function canParseAccessor():void
{
var v:XMLList = new XMLList(<root>
<accessor name="thing" access="writeonly" type="String" declaredBy="uk.co.ziazoo.fussy::Bubbles">
<metadata name="Inject"/>
</accessor>
</root>);
var properties:Array = parser.parse(v.*);
Assert.assertNotNull(properties);
Assert.assertTrue(properties.length == 1);
var prop:Accessor = properties[0] as Accessor;
Assert.assertEquals("thing", prop.name);
Assert.assertEquals("String", prop.type);
Assert.assertEquals(1, prop.metadata.length);
Assert.assertEquals("writeonly", prop.access);
Assert.assertEquals("uk.co.ziazoo.fussy::Bubbles", prop.declaredBy);
}
}
}
\ No newline at end of file
|
sammyt/fussy | 092a513f8510bea11d404b5c525cc591f992c141 | implemented ITypeQuery for basic type information | diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as
index 207f5aa..760f01b 100644
--- a/src/uk/co/ziazoo/fussy/Fussy.as
+++ b/src/uk/co/ziazoo/fussy/Fussy.as
@@ -1,49 +1,50 @@
package uk.co.ziazoo.fussy
{
import uk.co.ziazoo.fussy.parser.AccessorParser;
import uk.co.ziazoo.fussy.parser.ConstructorParser;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.parser.MetadataParser;
import uk.co.ziazoo.fussy.parser.MethodParser;
import uk.co.ziazoo.fussy.parser.ParameterParser;
import uk.co.ziazoo.fussy.parser.PropertyParser;
import uk.co.ziazoo.fussy.parser.VariableParser;
import uk.co.ziazoo.fussy.query.Query;
public class Fussy
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
+ private var metadataParser:MetadataParser
private var _reflector:IReflector;
public function Fussy(reflector:IReflector = null)
{
var parameterParser:ParameterParser = new ParameterParser();
- var metadataParser:MetadataParser = new MetadataParser();
+ metadataParser = new MetadataParser();
methodParser = new MethodParser(parameterParser, metadataParser);
propertyParser = new PropertyParser(
new VariableParser(metadataParser), new AccessorParser(metadataParser));
constructorParser = new ConstructorParser(parameterParser);
_reflector = reflector;
}
public function query():Query
{
return new Query(reflector, methodParser,
- propertyParser, constructorParser);
+ propertyParser, constructorParser, metadataParser);
}
public function get reflector():IReflector
{
if (!_reflector)
{
_reflector = new Reflector();
}
return _reflector;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/Type.as b/src/uk/co/ziazoo/fussy/Type.as
deleted file mode 100644
index 2bde79a..0000000
--- a/src/uk/co/ziazoo/fussy/Type.as
+++ /dev/null
@@ -1,63 +0,0 @@
-package uk.co.ziazoo.fussy
-{
- import uk.co.ziazoo.fussy.model.Constructor;
-
- /**
- * Provides basic information about a class
- */
- public class Type
- {
- public function Type()
- {
- }
-
- /**
- * The name of a class. For a class with a fully qualified
- * name of com.example::Tree the name is Tree
- */
- public function get name():String
- {
- return null;
- }
-
- /**
- * The fully qualified of a class
- */
- public function get qName():String
- {
- return null;
- }
-
- /**
- * Is this a class that describes a dynamic object
- */
- public function get isDynamic():String
- {
- return null;
- }
-
- /**
- * Is this a class that describes a final object
- */
- public function get isFinal():String
- {
- return null;
- }
-
- /**
- * The constructor for this object
- */
- public function get constructor():Constructor
- {
- return null;
- }
-
- /**
- * Any class level meta data for this class
- */
- public function get metaData():Array
- {
- return null;
- }
- }
-}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/TypeDescription.as b/src/uk/co/ziazoo/fussy/TypeDescription.as
new file mode 100644
index 0000000..6bad2ee
--- /dev/null
+++ b/src/uk/co/ziazoo/fussy/TypeDescription.as
@@ -0,0 +1,67 @@
+package uk.co.ziazoo.fussy
+{
+ import uk.co.ziazoo.fussy.model.Constructor;
+
+ /**
+ * Provides basic information about a class
+ */
+ public class TypeDescription
+ {
+ private var _qName:String;
+ private var _isDynamic:Boolean;
+ private var _isFinal:Boolean;
+ private var _constructor:Constructor;
+ private var _metadata:Array;
+
+ public function TypeDescription(qName:String,
+ isDynamic:Boolean, isFinal:Boolean, constructor:Constructor,
+ metadata:Array)
+ {
+ _qName = qName;
+ _isDynamic = isDynamic;
+ _isFinal = isFinal;
+ _constructor = constructor;
+ _metadata = metadata;
+ }
+
+ /**
+ * The fully qualified of a class
+ */
+ public function get qName():String
+ {
+ return _qName;
+ }
+
+ /**
+ * Is this a class that describes a dynamic object
+ */
+ public function get isDynamic():Boolean
+ {
+ return _isDynamic;
+ }
+
+ /**
+ * Is this a class that describes a final object
+ */
+ public function get isFinal():Boolean
+ {
+ return _isFinal;
+ }
+
+ /**
+ * The constructor for this object
+ */
+ public function get constructor():Constructor
+ {
+ return _constructor;
+ }
+
+ /**
+ * Any class level meta data for this class
+ */
+ public function get metadata():Array
+ {
+ return _metadata;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/ITypeQuery.as b/src/uk/co/ziazoo/fussy/query/ITypeQuery.as
new file mode 100644
index 0000000..b48240a
--- /dev/null
+++ b/src/uk/co/ziazoo/fussy/query/ITypeQuery.as
@@ -0,0 +1,11 @@
+package uk.co.ziazoo.fussy.query
+{
+ import uk.co.ziazoo.fussy.TypeDescription;
+
+ public interface ITypeQuery
+ {
+ function forType(type:Class):TypeDescription;
+
+ function forQName(qName:String):TypeDescription;
+ }
+}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/Query.as
index ef68875..abdb186 100644
--- a/src/uk/co/ziazoo/fussy/query/Query.as
+++ b/src/uk/co/ziazoo/fussy/query/Query.as
@@ -1,59 +1,55 @@
package uk.co.ziazoo.fussy.query
{
import uk.co.ziazoo.fussy.IReflector;
- import uk.co.ziazoo.fussy.Type;
+ import uk.co.ziazoo.fussy.TypeDescription;
import uk.co.ziazoo.fussy.accessors.AccessorQueryChain;
import uk.co.ziazoo.fussy.methods.MethodQueryChain;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
import uk.co.ziazoo.fussy.variables.VariableQueryChain;
public class Query
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
+ private var metadataParser:IResultParser;
private var reflector:IReflector;
public function Query(reflector:IReflector, methodParser:IResultParser,
- propertyParser:IResultParser, constructorParser:IResultParser)
+ propertyParser:IResultParser, constructorParser:IResultParser,
+ metadataParser:IResultParser)
{
this.propertyParser = propertyParser;
this.methodParser = methodParser;
this.constructorParser = constructorParser;
+ this.metadataParser = metadataParser;
this.reflector = reflector;
}
- // TODO: review Type queries api
-
- public function type(type:Class):Type
- {
- return null;
- }
-
- public function forQName(qName:String):Type
+ public function getTypeQuery(type:Class):ITypeQuery
{
- return null;
+ return new TypeQuery(reflector, constructorParser, metadataParser);
}
public function findMethods():MethodQueryChain
{
return new MethodQueryChain(reflector, methodParser);
}
public function findProperties():PropertyQueryChain
{
return new PropertyQueryChain(reflector, propertyParser);
}
public function findAccessors():AccessorQueryChain
{
return new AccessorQueryChain(reflector, propertyParser);
}
public function findVariables():VariableQueryChain
{
return new VariableQueryChain(reflector, propertyParser);
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/TypeQuery.as b/src/uk/co/ziazoo/fussy/query/TypeQuery.as
new file mode 100644
index 0000000..88e7d60
--- /dev/null
+++ b/src/uk/co/ziazoo/fussy/query/TypeQuery.as
@@ -0,0 +1,87 @@
+package uk.co.ziazoo.fussy.query
+{
+ import flash.utils.Dictionary;
+ import flash.utils.getDefinitionByName;
+
+ import uk.co.ziazoo.fussy.IReflector;
+ import uk.co.ziazoo.fussy.TypeDescription;
+ import uk.co.ziazoo.fussy.model.Constructor;
+ import uk.co.ziazoo.fussy.parser.IResultParser;
+
+ public class TypeQuery implements ITypeQuery
+ {
+ private var reflector:IReflector;
+ private var constructorParser:IResultParser;
+ private var metadataParser:IResultParser;
+ private var cache:Dictionary;
+
+ public function TypeQuery(reflector:IReflector,
+ constructorParser:IResultParser, metadataParser:IResultParser)
+ {
+ this.reflector = reflector;
+ this.constructorParser = constructorParser;
+ this.metadataParser = metadataParser;
+ this.cache = new Dictionary();
+ }
+
+ public function forType(type:Class):TypeDescription
+ {
+ var description:TypeDescription = cache[type] as TypeDescription;
+
+ if (description)
+ {
+ return description;
+ }
+ var reflection:XML = reflector.forType(type);
+ trace(reflection);
+ description = new TypeDescription
+ (
+ getQName(reflection),
+ getIsDynamic(reflection),
+ getIsFinal(reflection),
+ getConstructor(reflection),
+ getMetadata(reflection)
+ );
+
+ cache[type] = description;
+ return description;
+ }
+
+ public function forQName(qName:String):TypeDescription
+ {
+ return forType(Class(getDefinitionByName(qName)));
+ }
+
+ private function getQName(reflection:XML):String
+ {
+ return reflection.@name;
+ }
+
+ private function getIsDynamic(reflection:XML):Boolean
+ {
+ return String(reflection.@isDynamic) == "true";
+ }
+
+ private function getIsFinal(reflection:XML):Boolean
+ {
+ return String(reflection.@isFinal) == "true";
+ }
+
+ private function getConstructor(reflection:XML):Constructor
+ {
+ var result:Array = constructorParser.parse(reflection.factory);
+ var constructor:Constructor = result[0] as Constructor;
+ return constructor;
+ }
+
+ private function getMetadata(reflection:XML):Array
+ {
+ return metadataParser.parse(reflection.factory.metadata);
+ }
+
+ internal function hasTypeCached(type:Class):Boolean
+ {
+ return cache[type] != null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/Banana.as b/test/uk/co/ziazoo/fussy/Banana.as
new file mode 100644
index 0000000..d1d3f6d
--- /dev/null
+++ b/test/uk/co/ziazoo/fussy/Banana.as
@@ -0,0 +1,9 @@
+package uk.co.ziazoo.fussy
+{
+ public class Banana
+ {
+ public function Banana(thing:Wibble, list:Array)
+ {
+ }
+ }
+}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/Bubbles.as b/test/uk/co/ziazoo/fussy/Bubbles.as
index 3b4609d..3d06830 100644
--- a/test/uk/co/ziazoo/fussy/Bubbles.as
+++ b/test/uk/co/ziazoo/fussy/Bubbles.as
@@ -1,58 +1,59 @@
package uk.co.ziazoo.fussy
{
+ [Fussy]
public class Bubbles
{
public var wibble:Wibble;
public var wobble:int;
public var foo:String;
[Fussy]
public var bar:String;
public function Bubbles(thing:Wibble)
{
}
[Inject]
public function wowowo(a:int, b:String):void
{
}
[Inject]
[Fussy(thing="bacon")]
public function bebeb():void
{
}
public function doIt(a:int = 0):void
{
}
public function bebeboo(h:Object, r:Object):void
{
}
public function get sammy():Array
{
return null;
}
public function get window():Object
{
return null;
}
public function set window(value:Object):void
{
}
[Inject]
public function set thing(value:String):void
{
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
index 800a802..5b9b63d 100644
--- a/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
+++ b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as
@@ -1,30 +1,38 @@
package uk.co.ziazoo.fussy.parser
{
import flash.utils.describeType;
import org.flexunit.Assert;
+ import uk.co.ziazoo.fussy.Banana;
import uk.co.ziazoo.fussy.Bubbles;
import uk.co.ziazoo.fussy.model.Constructor;
+ import uk.co.ziazoo.fussy.model.Parameter;
public class ConstructorParserTest
{
public function ConstructorParserTest()
{
}
[Test]
public function parseConsructor():void
{
var parser:ConstructorParser =
new ConstructorParser(new ParameterParser());
- var result:Array = parser.parse(describeType(Bubbles).factory);
+ var result:Array = parser.parse(describeType(Banana).factory);
var constructor:Constructor = result[0] as Constructor;
Assert.assertNotNull(constructor);
- Assert.assertEquals(1, constructor.parameters.length);
+ Assert.assertEquals(2, constructor.parameters.length);
+
+ var param1:Parameter = constructor.parameters[0] as Parameter;
+ Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", param1.type);
+
+ var param2:Parameter = constructor.parameters[1] as Parameter;
+ Assert.assertEquals("Array", param2.type);
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/query/TypeQueryTest.as b/test/uk/co/ziazoo/fussy/query/TypeQueryTest.as
new file mode 100644
index 0000000..1d618c0
--- /dev/null
+++ b/test/uk/co/ziazoo/fussy/query/TypeQueryTest.as
@@ -0,0 +1,52 @@
+package uk.co.ziazoo.fussy.query
+{
+ import flash.utils.describeType;
+
+ import org.flexunit.Assert;
+
+ import uk.co.ziazoo.fussy.Bubbles;
+ import uk.co.ziazoo.fussy.Reflector;
+ import uk.co.ziazoo.fussy.TypeDescription;
+ import uk.co.ziazoo.fussy.parser.ConstructorParser;
+ import uk.co.ziazoo.fussy.parser.MetadataParser;
+ import uk.co.ziazoo.fussy.parser.ParameterParser;
+
+ public class TypeQueryTest
+ {
+ private var typeQuery:TypeQuery;
+
+ public function TypeQueryTest()
+ {
+ }
+
+ [Before]
+ public function setUp():void
+ {
+ typeQuery = new TypeQuery(new Reflector(),
+ new ConstructorParser(new ParameterParser()), new MetadataParser());
+ }
+
+ [After]
+ public function tearDown():void
+ {
+ typeQuery = null;
+ }
+
+ [Test]
+ public function getsTypeDescription():void
+ {
+ var description:TypeDescription = typeQuery.forType(Bubbles);
+
+ Assert.assertEquals("uk.co.ziazoo.fussy::Bubbles", description.qName);
+ Assert.assertEquals(true, description.isDynamic);
+ Assert.assertEquals(true, description.isFinal);
+
+ Assert.assertNotNull(description.constructor);
+ Assert.assertNotNull(description.metadata);
+
+ Assert.assertEquals(1, description.constructor.parameters.length);
+ Assert.assertEquals(1, description.constructor.parameters.length);
+ Assert.assertEquals(1, description.metadata.length);
+ }
+ }
+}
\ No newline at end of file
|
sammyt/fussy | 30cdd5fd1130b3e664f932d0c349de5299f941ce | added the reflector for describeType caching etc | diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as
index 682a76f..207f5aa 100644
--- a/src/uk/co/ziazoo/fussy/Fussy.as
+++ b/src/uk/co/ziazoo/fussy/Fussy.as
@@ -1,36 +1,49 @@
package uk.co.ziazoo.fussy
{
import uk.co.ziazoo.fussy.parser.AccessorParser;
import uk.co.ziazoo.fussy.parser.ConstructorParser;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.parser.MetadataParser;
import uk.co.ziazoo.fussy.parser.MethodParser;
import uk.co.ziazoo.fussy.parser.ParameterParser;
import uk.co.ziazoo.fussy.parser.PropertyParser;
import uk.co.ziazoo.fussy.parser.VariableParser;
import uk.co.ziazoo.fussy.query.Query;
public class Fussy
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
+ private var _reflector:IReflector;
- public function Fussy()
+ public function Fussy(reflector:IReflector = null)
{
var parameterParser:ParameterParser = new ParameterParser();
var metadataParser:MetadataParser = new MetadataParser();
methodParser = new MethodParser(parameterParser, metadataParser);
propertyParser = new PropertyParser(
new VariableParser(metadataParser), new AccessorParser(metadataParser));
constructorParser = new ConstructorParser(parameterParser);
+
+ _reflector = reflector;
}
public function query():Query
{
- return new Query(methodParser, propertyParser, constructorParser);
+ return new Query(reflector, methodParser,
+ propertyParser, constructorParser);
+ }
+
+ public function get reflector():IReflector
+ {
+ if (!_reflector)
+ {
+ _reflector = new Reflector();
+ }
+ return _reflector;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/IReflector.as b/src/uk/co/ziazoo/fussy/IReflector.as
new file mode 100644
index 0000000..f26c738
--- /dev/null
+++ b/src/uk/co/ziazoo/fussy/IReflector.as
@@ -0,0 +1,39 @@
+package uk.co.ziazoo.fussy
+{
+ /**
+ * stores result of describeType calls
+ */
+ public interface IReflector
+ {
+ /**
+ * Get reflection for a class
+ * @param type the class to reflect
+ * @return result of describeType
+ */
+ function forType(type:Class):XML;
+
+ /**
+ * Get reflection for a types qualified name
+ * @param qName of type to reflect
+ * @return result of describeType
+ */
+ function forQName(qName:String):XML;
+
+ /**
+ * Release all type description in memory (drop references)
+ */
+ function clearAll():void;
+
+ /**
+ * Release specific types description
+ * @param type who's description reference can be released
+ */
+ function clearForType(type:Class):void;
+
+ /**
+ * Release specific types description
+ * @param qName of type who's description reference can be released
+ */
+ function clearForQName(qName:String):void;
+ }
+}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/Reflector.as b/src/uk/co/ziazoo/fussy/Reflector.as
new file mode 100644
index 0000000..e9cd76f
--- /dev/null
+++ b/src/uk/co/ziazoo/fussy/Reflector.as
@@ -0,0 +1,76 @@
+package uk.co.ziazoo.fussy
+{
+ import flash.utils.Dictionary;
+ import flash.utils.describeType;
+ import flash.utils.getDefinitionByName;
+
+ public class Reflector implements IReflector
+ {
+ private var cache:Dictionary;
+
+ public function Reflector()
+ {
+ cache = new Dictionary();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function forType(type:Class):XML
+ {
+ var description:XML = cache[type] as XML;
+
+ if (description)
+ {
+ return description;
+ }
+
+ description = cache[type] = describeType(type);
+
+ return description;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function forQName(qName:String):XML
+ {
+ var type:Class = Class(getDefinitionByName(qName));
+ return forType(type);
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function clearAll():void
+ {
+ cache = null;
+ cache = new Dictionary();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function clearForType(type:Class):void
+ {
+ if (cache[type])
+ {
+ delete cache[type];
+ }
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function clearForQName(qName:String):void
+ {
+ var type:Class = Class(getDefinitionByName(qName));
+ clearForType(type);
+ }
+
+ public function hasReflection(type):Boolean
+ {
+ return cache[type] != null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as
index a43d8fd..450601f 100644
--- a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as
@@ -1,48 +1,50 @@
package uk.co.ziazoo.fussy.accessors
{
+ import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
public class AccessorQueryChain extends PropertyQueryChain
{
- public function AccessorQueryChain(parser:IResultParser)
+ public function AccessorQueryChain(reflector:IReflector,
+ parser:IResultParser)
{
- super(parser);
+ super(reflector, parser);
}
override protected function getList(reflection:XML):XMLList
{
return reflection.factory.accessor;
}
public function readable():AccessorQueryChain
{
parts.push(new Readable());
return this;
}
public function writable():AccessorQueryChain
{
parts.push(new Writable());
return this;
}
public function readOnly():AccessorQueryChain
{
parts.push(new ReadOnly());
return this;
}
public function writeOnly():AccessorQueryChain
{
parts.push(new WriteOnly());
return this;
}
public function readAndWrite():AccessorQueryChain
{
parts.push(new ReadAndWrite());
return this;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
index 329f1b3..415bcf0 100644
--- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
@@ -1,100 +1,101 @@
package uk.co.ziazoo.fussy.methods
{
+ import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.query.AbstractQueryChain;
import uk.co.ziazoo.fussy.query.Named;
import uk.co.ziazoo.fussy.query.WithMetadata;
public class MethodQueryChain extends AbstractQueryChain
{
- public function MethodQueryChain(parser:IResultParser)
+ public function MethodQueryChain(reflector:IReflector, parser:IResultParser)
{
- super(parser);
+ super(reflector, parser);
}
override protected function getList(reflection:XML):XMLList
{
return reflection.factory.method;
}
/**
* Filters based on the method name
* @param name of method
* @return MethodQueryChain to allow query DSL
*/
public function named(name:String):MethodQueryChain
{
parts.push(new Named(name));
return this;
}
/**
* Allows filtering by the type signature of the arguments
* e.g. hasTypeSignature(String,int,Array) would return all the
* methods which take a string, followed by a int then an array as
* their argument list
*
* @param types the classes of the arguments
* @return MethodQueryChain to allow query DSL
*/
public function withTypeSignature(...types):MethodQueryChain
{
parts.push(new HasTypeSignature(types));
return this;
}
/**
* Filters by the number of arguements the method takes
* @param count number of arguments the method has in its signature
* @return MethodQueryChain to allow query DSL
*/
public function withArgsLengthOf(count:int):MethodQueryChain
{
parts.push(new ArgumentsLengthOf(count));
return this;
}
/**
* Filters by metadata name
* @param named the name of the metadata a method must have to pass through
* this filter
* @return MethodQueryChain to allow query DSL
*/
public function withMetadata(named:String):MethodQueryChain
{
parts.push(new WithMetadata(named));
return this;
}
/**
* To find methods that take not arguments
* @return MethodQueryChain to allow query DSL
*/
public function noArguments():MethodQueryChain
{
parts.push(new NoArgs());
return this;
}
/**
* To find methods that have no arguments that must be provided. Methods
* with many arguments that have default values can pass this filter
* @return MethodQueryChain to allow query DSL
*/
public function noCompulsoryArguments():MethodQueryChain
{
parts.push(new NoCompulsoryArgs());
return this;
}
/**
* To find methods that have one or more arguments
* @return MethodQueryChain to allow query DSL
*/
public function withArguments():MethodQueryChain
{
parts.push(new WithArguments());
return this;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as
index ff54170..9cbce03 100644
--- a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as
@@ -1,34 +1,37 @@
package uk.co.ziazoo.fussy.properties
{
+ import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.query.AbstractQueryChain;
import uk.co.ziazoo.fussy.query.WithMetadata;
public class PropertyQueryChain extends AbstractQueryChain
{
- public function PropertyQueryChain(parser:IResultParser)
+ public function PropertyQueryChain(reflector:IReflector, parser:IResultParser)
{
- super(parser);
+ super(reflector, parser);
}
+ // TODO: allow readable/writable queries on properties
+
override protected function getList(reflection:XML):XMLList
{
var p:XMLList = new XMLList(<root/>);
p.appendChild(reflection.factory.variable);
p.appendChild(reflection.factory.accessor);
return p.*;
}
public function ofType(type:Class):PropertyQueryChain
{
parts.push(new OfType(type));
return this;
}
public function withMetadata(name:String):PropertyQueryChain
{
parts.push(new WithMetadata(name));
return this;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as
index 2e2ba6c..9491b79 100644
--- a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as
@@ -1,68 +1,76 @@
package uk.co.ziazoo.fussy.query
{
import flash.utils.describeType;
+ import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.parser.IResultParser;
public class AbstractQueryChain implements IQueryChain
{
/**
* @private
*/
protected var parts:Array;
+ /**
+ * @private
+ */
+ protected var reflector:IReflector;
+
private var _parser:IResultParser;
- public function AbstractQueryChain(parser:IResultParser)
+
+ public function AbstractQueryChain(reflector:IReflector, parser:IResultParser)
{
parts = [];
_parser = parser;
+ this.reflector = reflector;
}
public function forType(type:Class):Array
{
return parser.parse(xmlForType(type));
}
public function xmlForType(type:Class):XMLList
{
if (parts.length == 0)
{
return null;
}
var firstPart:IQueryPart = parts[0];
- var lastResult:XMLList = firstPart.filter(getList(describeType(type)));
+ var lastResult:XMLList = firstPart.filter(getList(reflector.forType(type)));
var i:int = parts.length - 1;
while (i >= 0)
{
var part:IQueryPart = parts[i];
lastResult = part.filter(lastResult);
i--;
}
return lastResult;
}
protected function getList(reflection:XML):XMLList
{
return null;
}
public function get parser():IResultParser
{
return _parser;
}
public function set parser(value:IResultParser):void
{
_parser = value;
}
public function addQueryPart(part:IQueryPart):void
{
parts.push(part);
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/Query.as
index a7ee044..ef68875 100644
--- a/src/uk/co/ziazoo/fussy/query/Query.as
+++ b/src/uk/co/ziazoo/fussy/query/Query.as
@@ -1,54 +1,59 @@
package uk.co.ziazoo.fussy.query
{
+ import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.Type;
import uk.co.ziazoo.fussy.accessors.AccessorQueryChain;
import uk.co.ziazoo.fussy.methods.MethodQueryChain;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
import uk.co.ziazoo.fussy.variables.VariableQueryChain;
public class Query
{
private var methodParser:IResultParser;
private var propertyParser:IResultParser;
private var constructorParser:IResultParser;
+ private var reflector:IReflector;
- public function Query(methodParser:IResultParser,
+ public function Query(reflector:IReflector, methodParser:IResultParser,
propertyParser:IResultParser, constructorParser:IResultParser)
{
this.propertyParser = propertyParser;
this.methodParser = methodParser;
this.constructorParser = constructorParser;
+ this.reflector = reflector;
}
+ // TODO: review Type queries api
+
public function type(type:Class):Type
{
return null;
}
public function forQName(qName:String):Type
{
return null;
}
public function findMethods():MethodQueryChain
{
- return new MethodQueryChain(methodParser);
+ return new MethodQueryChain(reflector, methodParser);
}
public function findProperties():PropertyQueryChain
{
- return new PropertyQueryChain(propertyParser);
+ return new PropertyQueryChain(reflector, propertyParser);
}
public function findAccessors():AccessorQueryChain
{
- return new AccessorQueryChain(propertyParser);
+ return new AccessorQueryChain(reflector, propertyParser);
}
public function findVariables():VariableQueryChain
{
- return new VariableQueryChain(propertyParser);
+ return new VariableQueryChain(reflector, propertyParser);
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as
index 6ce6331..5c271d5 100644
--- a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as
@@ -1,18 +1,20 @@
package uk.co.ziazoo.fussy.variables
{
+ import uk.co.ziazoo.fussy.IReflector;
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.properties.PropertyQueryChain;
public class VariableQueryChain extends PropertyQueryChain
{
- public function VariableQueryChain(parser:IResultParser)
+ public function VariableQueryChain(reflector:IReflector,
+ parser:IResultParser)
{
- super(parser);
+ super(reflector, parser);
}
override protected function getList(reflection:XML):XMLList
{
return reflection.factory.varaible;
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as
index be9e588..69455d0 100644
--- a/test/uk/co/ziazoo/fussy/FussyTest.as
+++ b/test/uk/co/ziazoo/fussy/FussyTest.as
@@ -1,74 +1,80 @@
package uk.co.ziazoo.fussy
{
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.model.Method;
import uk.co.ziazoo.fussy.query.IQuery;
public class FussyTest
{
[Test]
public function findInjectableMethods():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withMetadata("Inject").withArguments();
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "wowowo");
Assert.assertEquals(method.parameters.length, 2);
}
[Test]
public function findInjectableProperties():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findProperties().withMetadata("Inject");
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
}
[Test]
public function findInjectableVars():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findVariables().withMetadata("Inject");
var list:Array = query.forType(Bubbles);
Assert.assertEquals(0, list.length);
}
[Test]
public function filterBySignature():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withTypeSignature(int, String);
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "wowowo");
}
[Test]
public function filterByArgsLengh():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withArgsLengthOf(1);
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "doIt");
}
+
+ [Test]
+ public function getConstructor():void
+ {
+
+ }
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/ReflectorTest.as b/test/uk/co/ziazoo/fussy/ReflectorTest.as
new file mode 100644
index 0000000..3d9df73
--- /dev/null
+++ b/test/uk/co/ziazoo/fussy/ReflectorTest.as
@@ -0,0 +1,112 @@
+package uk.co.ziazoo.fussy
+{
+ import flash.utils.getQualifiedClassName;
+
+ import org.flexunit.Assert;
+
+ public class ReflectorTest
+ {
+ private var reflector:Reflector;
+
+ public function ReflectorTest()
+ {
+ }
+
+ [Before]
+ public function setUp():void
+ {
+ reflector = new Reflector();
+ }
+
+ [After]
+ public function tearDown():void
+ {
+ reflector = null;
+ }
+
+ [Test]
+ public function doesCache():void
+ {
+ var desc:XML = reflector.forType(Bubbles);
+ Assert.assertNotNull(desc);
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+ }
+
+ [Test]
+ public function getCorrectResult():void
+ {
+ var desc:XML = reflector.forType(Bubbles);
+ Assert.assertNotNull(desc);
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+
+ Assert.assertEquals(desc, reflector.forType(Bubbles));
+ }
+
+ [Test]
+ public function getForQName():void
+ {
+ var desc:XML = reflector.forQName(getQualifiedClassName(Bubbles));
+ Assert.assertNotNull(desc);
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+
+ Assert.assertEquals(desc, reflector.forType(Bubbles));
+ }
+
+ [Test]
+ public function clearAll():void
+ {
+ reflector.forType(Bubbles);
+ reflector.forType(Wibble);
+ reflector.forType(Array);
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+ Assert.assertEquals(true, reflector.hasReflection(Wibble));
+ Assert.assertEquals(true, reflector.hasReflection(Array));
+
+ reflector.clearAll();
+
+ Assert.assertEquals(false, reflector.hasReflection(Bubbles));
+ Assert.assertEquals(false, reflector.hasReflection(Wibble));
+ Assert.assertEquals(false, reflector.hasReflection(Array));
+ }
+
+ [Test]
+ public function clearSomeByType():void
+ {
+ reflector.forType(Bubbles);
+ reflector.forType(Wibble);
+ reflector.forType(Array);
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+ Assert.assertEquals(true, reflector.hasReflection(Wibble));
+ Assert.assertEquals(true, reflector.hasReflection(Array));
+
+ reflector.clearForType(Wibble)
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+ Assert.assertEquals(false, reflector.hasReflection(Wibble));
+ Assert.assertEquals(true, reflector.hasReflection(Array));
+ }
+
+ [Test]
+ public function clearSomeByQName():void
+ {
+ reflector.forType(Bubbles);
+ reflector.forType(Wibble);
+ reflector.forType(Array);
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+ Assert.assertEquals(true, reflector.hasReflection(Wibble));
+ Assert.assertEquals(true, reflector.hasReflection(Array));
+
+ reflector.clearForQName(getQualifiedClassName(Wibble));
+
+ Assert.assertEquals(true, reflector.hasReflection(Bubbles));
+ Assert.assertEquals(false, reflector.hasReflection(Wibble));
+ Assert.assertEquals(true, reflector.hasReflection(Array));
+ }
+ }
+}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as b/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as
index 3910b00..ca12515 100644
--- a/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as
+++ b/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as
@@ -1,31 +1,32 @@
package uk.co.ziazoo.fussy.methods
{
import flash.utils.describeType;
import uk.co.ziazoo.fussy.Bubbles;
+ import uk.co.ziazoo.fussy.Reflector;
public class MethodQueryChainTest
{
private var methodsList:XMLList;
[Before]
public function setUp():void
{
var tmp:XML = describeType(Bubbles);
methodsList = tmp.factory.method;
}
[After]
public function tearDown():void
{
methodsList = null;
}
[Test]
public function createNameQuery():void
{
- var chain:MethodQueryChain = new MethodQueryChain(null);
+ var chain:MethodQueryChain = new MethodQueryChain(new Reflector(), null);
chain.named("wowowo");
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/query/QueryTest.as b/test/uk/co/ziazoo/fussy/query/QueryTest.as
deleted file mode 100644
index 1a4263c..0000000
--- a/test/uk/co/ziazoo/fussy/query/QueryTest.as
+++ /dev/null
@@ -1,22 +0,0 @@
-package uk.co.ziazoo.fussy.query
-{
- public class QueryTest
- {
- [Before]
- public function setUp():void
- {
- }
-
- [After]
- public function tearDown():void
- {
- }
-
- [Test]
- public function creation():void
- {
- var query:Query = new Query(null, null, null);
- query.findMethods().named("getEtc");
- }
- }
-}
\ No newline at end of file
|
sammyt/fussy | 622652282c4145a8e60b522c85cdb572d75acc58 | added some more end to end tests and recactored DSL for better readablilty | diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
index e9605da..329f1b3 100644
--- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
@@ -1,100 +1,100 @@
package uk.co.ziazoo.fussy.methods
{
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.query.AbstractQueryChain;
import uk.co.ziazoo.fussy.query.Named;
import uk.co.ziazoo.fussy.query.WithMetadata;
public class MethodQueryChain extends AbstractQueryChain
{
public function MethodQueryChain(parser:IResultParser)
{
super(parser);
}
override protected function getList(reflection:XML):XMLList
{
return reflection.factory.method;
}
/**
* Filters based on the method name
* @param name of method
* @return MethodQueryChain to allow query DSL
*/
public function named(name:String):MethodQueryChain
{
parts.push(new Named(name));
return this;
}
/**
* Allows filtering by the type signature of the arguments
* e.g. hasTypeSignature(String,int,Array) would return all the
* methods which take a string, followed by a int then an array as
* their argument list
*
* @param types the classes of the arguments
* @return MethodQueryChain to allow query DSL
*/
- public function hasTypeSignature(...types):MethodQueryChain
+ public function withTypeSignature(...types):MethodQueryChain
{
parts.push(new HasTypeSignature(types));
return this;
}
/**
* Filters by the number of arguements the method takes
* @param count number of arguments the method has in its signature
* @return MethodQueryChain to allow query DSL
*/
- public function argumentsLengthOf(count:int):MethodQueryChain
+ public function withArgsLengthOf(count:int):MethodQueryChain
{
parts.push(new ArgumentsLengthOf(count));
return this;
}
/**
* Filters by metadata name
* @param named the name of the metadata a method must have to pass through
* this filter
* @return MethodQueryChain to allow query DSL
*/
public function withMetadata(named:String):MethodQueryChain
{
parts.push(new WithMetadata(named));
return this;
}
/**
* To find methods that take not arguments
* @return MethodQueryChain to allow query DSL
*/
public function noArguments():MethodQueryChain
{
parts.push(new NoArgs());
return this;
}
/**
* To find methods that have no arguments that must be provided. Methods
* with many arguments that have default values can pass this filter
* @return MethodQueryChain to allow query DSL
*/
public function noCompulsoryArguments():MethodQueryChain
{
parts.push(new NoCompulsoryArgs());
return this;
}
/**
* To find methods that have one or more arguments
* @return MethodQueryChain to allow query DSL
*/
public function withArguments():MethodQueryChain
{
parts.push(new WithArguments());
return this;
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as
index c7760b4..be9e588 100644
--- a/test/uk/co/ziazoo/fussy/FussyTest.as
+++ b/test/uk/co/ziazoo/fussy/FussyTest.as
@@ -1,38 +1,74 @@
package uk.co.ziazoo.fussy
{
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.model.Method;
import uk.co.ziazoo.fussy.query.IQuery;
public class FussyTest
{
[Test]
public function findInjectableMethods():void
{
var fussy:Fussy = new Fussy();
var query:IQuery = fussy.query().findMethods().withMetadata("Inject").withArguments();
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
var method:Method = list[0] as Method;
Assert.assertEquals(method.name, "wowowo");
Assert.assertEquals(method.parameters.length, 2);
}
[Test]
public function findInjectableProperties():void
{
var fussy:Fussy = new Fussy();
-
var query:IQuery = fussy.query().findProperties().withMetadata("Inject");
var list:Array = query.forType(Bubbles);
Assert.assertEquals(1, list.length);
}
+
+ [Test]
+ public function findInjectableVars():void
+ {
+ var fussy:Fussy = new Fussy();
+ var query:IQuery = fussy.query().findVariables().withMetadata("Inject");
+
+ var list:Array = query.forType(Bubbles);
+
+ Assert.assertEquals(0, list.length);
+ }
+
+ [Test]
+ public function filterBySignature():void
+ {
+ var fussy:Fussy = new Fussy();
+ var query:IQuery = fussy.query().findMethods().withTypeSignature(int, String);
+
+ var list:Array = query.forType(Bubbles);
+ Assert.assertEquals(1, list.length);
+
+ var method:Method = list[0] as Method;
+ Assert.assertEquals(method.name, "wowowo");
+ }
+
+ [Test]
+ public function filterByArgsLengh():void
+ {
+ var fussy:Fussy = new Fussy();
+ var query:IQuery = fussy.query().findMethods().withArgsLengthOf(1);
+
+ var list:Array = query.forType(Bubbles);
+ Assert.assertEquals(1, list.length);
+
+ var method:Method = list[0] as Method;
+ Assert.assertEquals(method.name, "doIt");
+ }
}
}
\ No newline at end of file
|
sammyt/fussy | 6cff66182187b76add2667ff7d2826f59c937874 | fixed signature filter params | diff --git a/src/uk/co/ziazoo/fussy/methods/HasTypeSignature.as b/src/uk/co/ziazoo/fussy/methods/HasTypeSignature.as
index 316c5ec..3b24737 100644
--- a/src/uk/co/ziazoo/fussy/methods/HasTypeSignature.as
+++ b/src/uk/co/ziazoo/fussy/methods/HasTypeSignature.as
@@ -1,53 +1,53 @@
package uk.co.ziazoo.fussy.methods
{
import flash.utils.getQualifiedClassName;
import uk.co.ziazoo.fussy.query.IQueryPart;
public class HasTypeSignature implements IQueryPart
{
private var types:Array;
- public function HasTypeSignature(...types)
+ public function HasTypeSignature(types:Array)
{
this.types = types;
}
public function filter(data:XMLList):XMLList
{
var filtered:XMLList = new XMLList(<root />);
for each(var method:XML in data)
{
var parameters:XMLList = method.parameter;
if (lengthIsCorrect(parameters)
&& typesAreCorrect(parameters))
{
filtered.appendChild(method);
}
}
return filtered.method;
}
private function lengthIsCorrect(parameters:XMLList):Boolean
{
return types.length == parameters.length();
}
private function typesAreCorrect(parameters:XMLList):Boolean
{
for each(var parameter:XML in parameters)
{
var type:Class = types[Number(parameter.@index) - 1] as Class;
var qName:String = getQualifiedClassName(type);
if (parameter.@type != qName)
{
return false;
}
}
return true;
}
}
}
\ No newline at end of file
diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
index 00a6be7..e9605da 100644
--- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
+++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as
@@ -1,98 +1,100 @@
package uk.co.ziazoo.fussy.methods
{
import uk.co.ziazoo.fussy.parser.IResultParser;
import uk.co.ziazoo.fussy.query.AbstractQueryChain;
import uk.co.ziazoo.fussy.query.Named;
import uk.co.ziazoo.fussy.query.WithMetadata;
public class MethodQueryChain extends AbstractQueryChain
{
public function MethodQueryChain(parser:IResultParser)
{
super(parser);
}
override protected function getList(reflection:XML):XMLList
{
return reflection.factory.method;
}
/**
* Filters based on the method name
* @param name of method
* @return MethodQueryChain to allow query DSL
*/
public function named(name:String):MethodQueryChain
{
parts.push(new Named(name));
return this;
}
/**
* Allows filtering by the type signature of the arguments
* e.g. hasTypeSignature(String,int,Array) would return all the
* methods which take a string, followed by a int then an array as
* their argument list
*
* @param types the classes of the arguments
* @return MethodQueryChain to allow query DSL
*/
public function hasTypeSignature(...types):MethodQueryChain
{
+ parts.push(new HasTypeSignature(types));
return this;
}
/**
* Filters by the number of arguements the method takes
* @param count number of arguments the method has in its signature
* @return MethodQueryChain to allow query DSL
*/
public function argumentsLengthOf(count:int):MethodQueryChain
{
+ parts.push(new ArgumentsLengthOf(count));
return this;
}
/**
* Filters by metadata name
* @param named the name of the metadata a method must have to pass through
* this filter
* @return MethodQueryChain to allow query DSL
*/
public function withMetadata(named:String):MethodQueryChain
{
parts.push(new WithMetadata(named));
return this;
}
/**
* To find methods that take not arguments
* @return MethodQueryChain to allow query DSL
*/
public function noArguments():MethodQueryChain
{
parts.push(new NoArgs());
return this;
}
/**
* To find methods that have no arguments that must be provided. Methods
* with many arguments that have default values can pass this filter
* @return MethodQueryChain to allow query DSL
*/
public function noCompulsoryArguments():MethodQueryChain
{
parts.push(new NoCompulsoryArgs());
return this;
}
/**
* To find methods that have one or more arguments
* @return MethodQueryChain to allow query DSL
*/
public function withArguments():MethodQueryChain
{
parts.push(new WithArguments());
return this;
}
}
}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/methods/HasTypeSignatureTest.as b/test/uk/co/ziazoo/fussy/methods/HasTypeSignatureTest.as
index 7c04f3f..80b3694 100644
--- a/test/uk/co/ziazoo/fussy/methods/HasTypeSignatureTest.as
+++ b/test/uk/co/ziazoo/fussy/methods/HasTypeSignatureTest.as
@@ -1,37 +1,37 @@
package uk.co.ziazoo.fussy.methods
{
import org.flexunit.Assert;
import uk.co.ziazoo.fussy.Wibble;
public class HasTypeSignatureTest
{
public function HasTypeSignatureTest()
{
}
[Test]
public function checkTypes():void
{
- var queryPart:HasTypeSignature = new HasTypeSignature(int, String, Wibble);
+ var queryPart:HasTypeSignature = new HasTypeSignature([int, String, Wibble]);
var methods:XML = <root>
<method name="bebeboo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void">
<parameter index="1" type="Object" optional="false"/>
<parameter index="2" type="Object" optional="false"/>
</method>
<method name="demo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void">
<parameter index="1" type="int" optional="false"/>
<parameter index="2" type="String" optional="false"/>
<parameter index="3" type="uk.co.ziazoo.fussy::Wibble" optional="false"/>
<metadata name="Inject"/>
</method>
</root>;
var result:XMLList = queryPart.filter(methods.method);
Assert.assertEquals(1, result.length());
Assert.assertEquals("demo", result.@name);
}
}
}
\ No newline at end of file
|
sammyt/fussy | 8f72baca6f0319f536a354728a32449a04ee73ad | added arguements length check | diff --git a/src/uk/co/ziazoo/fussy/methods/ArgumentsLengthOf.as b/src/uk/co/ziazoo/fussy/methods/ArgumentsLengthOf.as
new file mode 100644
index 0000000..9c36c84
--- /dev/null
+++ b/src/uk/co/ziazoo/fussy/methods/ArgumentsLengthOf.as
@@ -0,0 +1,21 @@
+package uk.co.ziazoo.fussy.methods
+{
+ import uk.co.ziazoo.fussy.query.IQueryPart;
+
+ public class ArgumentsLengthOf implements IQueryPart
+ {
+ private var count:int;
+
+ public function ArgumentsLengthOf(count:int)
+ {
+ this.count = count;
+ }
+
+ public function filter(data:XMLList):XMLList
+ {
+ return data.(
+ hasOwnProperty("parameter") && parameter.length() == count
+ );
+ }
+ }
+}
\ No newline at end of file
diff --git a/test/uk/co/ziazoo/fussy/methods/ArgumentsLengthOfTest.as b/test/uk/co/ziazoo/fussy/methods/ArgumentsLengthOfTest.as
new file mode 100644
index 0000000..aea1506
--- /dev/null
+++ b/test/uk/co/ziazoo/fussy/methods/ArgumentsLengthOfTest.as
@@ -0,0 +1,35 @@
+package uk.co.ziazoo.fussy.methods
+{
+ import org.flexunit.Assert;
+
+ public class ArgumentsLengthOfTest
+ {
+ public function ArgumentsLengthOfTest()
+ {
+ }
+
+ [Test]
+ public function checkLength():void
+ {
+ var queryPart:ArgumentsLengthOf = new ArgumentsLengthOf(3);
+
+ var methods:XML = <root>
+ <method name="bebeboo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void">
+ <parameter index="1" type="Object" optional="false"/>
+ <parameter index="2" type="Object" optional="false"/>
+ </method>
+ <method name="demo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void">
+ <parameter index="1" type="int" optional="false"/>
+ <parameter index="2" type="String" optional="false"/>
+ <parameter index="3" type="uk.co.ziazoo.fussy::Wibble" optional="false"/>
+ <metadata name="Inject"/>
+ </method>
+ </root>;
+
+ var result:XMLList = queryPart.filter(methods.method);
+
+ Assert.assertEquals(1, result.length());
+ Assert.assertEquals("demo", result.@name);
+ }
+ }
+}
\ No newline at end of file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.