add some more documentation, pass some more tests

This commit is contained in:
rlx 2011-10-01 02:21:55 +00:00
parent c6d67420a8
commit f2dbfbd1e5
9 changed files with 589 additions and 494 deletions

View file

@ -35,7 +35,7 @@ Ox.load('UI', {
})
.appendTo(Ox.UI.$body);
[
'anyclick', 'singleclick', 'doubleclick', 'mouserepeat',
'anyclick', 'singleclick', 'doubleclick', 'mousedown', 'mouserepeat',
'dragstart', 'drag', 'dragenter', 'dragleave', 'dragpause', 'dragend'
].forEach(function(event) {
$target.bindEvent(event, function(e) {
@ -44,13 +44,18 @@ Ox.load('UI', {
.html(
Ox.formatDate(date, '%H:%M:%S') + '.' + (Ox.pad(date % 1000, 3)) +
' <span style="font-weight: bold">' + event + '</span> ' +
JSON.stringify(Ox.extend(e.clientX ? {
JSON.stringify(
Ox.extend(e.clientX ? {
clientX: e.clientX,
clientY: e.clientY,
} : {}, e.clientDX ? {
clientDX: e.clientDX,
clientDY: e.clientDY
} : {}))
} : {})
)
.replace(/"/g, '')
.replace(/:/g, ': ')
.replace(/,/g, ', ')
)
.prependTo($log.$element);
event == 'anyclick' && Ox.print(e);

View file

@ -46,9 +46,9 @@ Ox.load.Geo = function(options, callback) {
}).length,
// Current independent countries without dependencies or disputes
Ox.COUNTRIES.filter(function(c) {
return !c.dependencies.length && !c.dependency.length &&
!c.disputes.length && !c.disputed.length &&
!c.dissolved.length && !c.other;
return !c.dependencies.length && !c.dependency.length
&& !c.disputes.length && !c.disputed.length
&& !c.dissolved.length && !c.other;
}).length,
// Current dependent countries
Ox.COUNTRIES.filter(function(c) {
@ -68,9 +68,9 @@ Ox.load.Geo = function(options, callback) {
}).length,
// Former independent countries without dependencies or disputes
Ox.COUNTRIES.filter(function(c) {
return !c.dependencies.length && !c.dependency.length &&
!c.disputes.length && !c.disputed.length &&
c.dissolved.length && !c.other;
return !c.dependencies.length && !c.dependency.length
&& !c.disputes.length && !c.disputed.length
&& c.dissolved.length && !c.other;
}).length,
// Former dependect countries
Ox.COUNTRIES.filter(function(c) {

View file

@ -3,22 +3,29 @@
/*@
Ox.Element <function:Ox.JQueryElement> Basic UI element object
# Usage --------------------------------------------------------------------
([options[, self]]) -> <object> UI element
(element) -> <object> UI element
(options) -> <object> UI element
(options, self) -> <object> UI element
# Arguments ----------------------------------------------------------------
options <object> the options of the element
element <string> Tagname or CSS selector
options <object> Options of the element
# Properties
element <string> tagname or CSS selector
tooltip <string|function> tooltip title or function that returns one
element <string> Tagname or CSS selector
tooltip <string|function> Tooltip title, or a function that returns one
(e) -> <string> tooltip title
e <object> mouse event
options <string> tagname or CSS selector
self <object> shared private variable
self <object> Shared private variable
# Events -------------------------------------------------------------------
anyclick <event> anyclick
Fires on mouseup, but not on any subsequent mouseup within 250 ms
Fires on mouseup, but not on any subsequent mouseup within 250 ms (this
is useful if one wants to listen for singleclicks, but not doubleclicks,
since it will fire immediately, and won't fire again in case of a
doubleclick)
* <*> original event properties
doubleclick <event> doubleclick
Fires on the second mousedown within 250 ms
Fires on the second mousedown within 250 ms (this is useful if one wants
to listen for both singleclicks and doubleclicks, since it will not
trigger a singleclick event)
* <*> original event properties
drag <event> drag
Fires on mousemove after dragstart, stops firing on mouseup
@ -31,23 +38,41 @@ Ox.Element <function:Ox.JQueryElement> Basic UI element object
clientDY <number> vertical drag delta in px
* <*> original event properties
dragenter <event> dragenter
Fires when entering an element during drag
dragleave <event> dragleave
Fires when leaving an element during drag
dragpause <event> dragpause
Fires once when the mouse doesn't move for 250 ms during drag
Fires when entering an element during drag (this fires on the element
being dragged -- the target element is the event's target property)
clientDX <number> horizontal drag delta in px
clientDY <number> vertical drag delta in px
* <*> original event properties
dragleave <event> dragleave
Fires when leaving an element during drag (this fires on the element
being dragged -- the target element is the event's target property)
clientDX <number> horizontal drag delta in px
clientDY <number> vertical drag delta in px
* <*> original event properties
dragpause <event> dragpause
Fires once when the mouse doesn't move for 250 ms during drag (this is
useful in order to execute operations that are too expensive to be
attached to the drag event)
clientDX <number> horizontal drag delta in px
clientDY <number> vertical drag delta in px
* <*> original event properties
mousedown <event> mousedown
Fires on mousedown (this is useful if one wants to listen for
singleclicks, but not doubleclicks or drag events, and wants the event
to fire as early as possible)
* <*> original event properties
dragstart <event> dragstart
Fires when the mouse is down for 250 ms
* <*> original event properties
mouserepeat <event> mouserepeat
Fires every 50 ms after the mouse was down for 250 ms, stops firing on
mouseleave or mouseup
* <*> original event properties
mouseleave or mouseup (this fires like a key that is being pressed and
held, and is useful for buttons like scrollbars arrows that need to
react to both clicking and holding)
singleclick <event> singleclick
Fires 250 ms after mouseup, if there was no subsequent mousedown
Fires 250 ms after mouseup, if there was no subsequent mousedown (this
is useful if one wants to listen for both singleclicks and doubleclicks,
since it will not fire for doubleclicks)
* <*> original event properties
@*/
@ -113,7 +138,7 @@ Ox.Element = function(options, self) {
mousedown:
trigger mousedown
within 250 msec:
mouseup: trigger anyclick ("click" would collide with click events of certain widgets)
mouseup: trigger anyclick
mouseup + mousedown: trigger doubleclick
after 250 msec:
mouseup + no mousedown within 250 msec: trigger singleclick
@ -121,9 +146,11 @@ Ox.Element = function(options, self) {
trigger mouserepeat every 50 msec
trigger dragstart
mousemove: trigger drag
no mousemove within 250 msec:
no mousemove for 250 msec:
trigger dragpause
mouseup: trigger dragend
"anyclick" is not called "click" since this would collide with the click
events of some widgets
*/
var clientX, clientY,
dragTimeout = 0,
@ -133,50 +160,59 @@ Ox.Element = function(options, self) {
that.triggerEvent('mousedown', e);
self.mouseup = false;
self.mouseTimeout = setTimeout(function() {
// 250 ms later, no subsequent click
self.mouseTimeout = 0;
if (self.mouseup) {
// singleclick
// mouse went up, trigger singleclick
that.triggerEvent('singleclick', e);
} else {
// mouserepeat, drag
clientX = e.clientX;
clientY = e.clientY;
// mouse is still down, trigger mouserepeat
// every 50 ms until mouseleave or mouseup
mouserepeat();
mouseInterval = setInterval(mouserepeat, 50);
that.one('mouseleave', function() {
clearInterval(mouseInterval);
});
// trigger dragstart, set up drag events
that.triggerEvent('dragstart', e);
$('*').bind({
mouseenter: dragenter,
mouseleave: dragleave
});
mouserepeat();
mouseInterval = setInterval(mouserepeat, 50);
Ox.UI.$window.unbind('mouseup', mouseup)
clientX = e.clientX;
clientY = e.clientY;
Ox.UI.$window
.unbind('mouseup', mouseup)
.mousemove(mousemove)
.one('mouseup', function(e) {
// stop checking for mouserepeat
clearInterval(mouseInterval);
// stop checking for dragpause
clearTimeout(dragTimeout);
// stop checking for drag
Ox.UI.$window.unbind('mousemove', mousemove);
// stop checking for dragenter and dragleave
$('*').unbind({
mouseenter: dragenter,
mouseleave: dragleave
});
// trigger dragend
that.triggerEvent('dragend', extend(e));
});
that.one('mouseleave', function() {
clearInterval(mouseInterval);
});
}
}, 250);
} else {
// second mousedown
// second mousedown within 250 ms, trigger doubleclick
clearTimeout(self.mouseTimeout);
self.mouseTimeout = 0;
that.triggerEvent('doubleclick', e);
}
Ox.UI.$window.one('mouseup', mouseup);
function dragenter(e) {
that.triggerEvent('dragenter', e);
that.triggerEvent('dragenter', extend(e));
}
function dragleave(e) {
that.triggerEvent('dragleave', e);
that.triggerEvent('dragleave', extend(e));
}
function extend(e) {
return Ox.extend({
@ -188,16 +224,17 @@ Ox.Element = function(options, self) {
e = extend(e);
clearTimeout(dragTimeout);
dragTimeout = setTimeout(function() {
// mouse did not move for 250 ms, trigger dragpause
that.triggerEvent('dragpause', e);
}, 250);
that.triggerEvent('drag', e);
}
function mouserepeat() {
that.triggerEvent('mouserepeat');
function mouserepeat(e) {
that.triggerEvent('mouserepeat', e);
}
function mouseup(e) {
// only trigger on first mouseup
if (!self.mouseup) {
// mouse went up for the first time, trigger anyclick
that.triggerEvent('anyclick', e);
self.mouseup = true;
}

View file

@ -60,8 +60,8 @@ view List or item view, like "clips" or "map". Both list and item views are
per type.
span Position or selection in a view, either one or two coordinates or one
id, like in "video/01:00", "video/-01:00", "video/01:00,-01:00",
"video/annotationABC", "video/subtitles:23", "text/chapter42",
"map/0,0", "map/-45,-90,45,90", "map/Barcelona", "image/100,100" etc.
"video/@annotationABC", "video/@subtitles:23", "text/@chapter42",
"map/0,0", "map/-45,-90,45,90", "map/@barcelona", "image/100,100" etc.
Testing id is asynchronous.
sort Sort, like "title" or "-director" or "country,year,-language,+runtime"
find Query, like a=x or a=x&b=y or a=x&(b=y|c=z). A query object has the form
@ -85,8 +85,8 @@ k<v k v < is less than (number)
k!<v k v !< is not less than (number)
k>v k v > is more than (number)
k!>v k v !> is not more than (number)
k=v:w k [v,w] = is between (number), is (string)
k!=v:w k [v,w] != is not between (number), is not (string)
k=v:w k [v,w] - is between (number), is (string)
k!=v:w k [v,w] !- is not between (number), is not (string)
All parts of the URL can be omitted, as long as the order is preserved.
@ -504,7 +504,7 @@ Ox.URL = function(options) {
}
if (!state.span && /^[A-Z@]/.test(parts[0])) {
// test for span id or name
self.options.getSpan(state.item, state.view, parts[0], function(span, view) {
self.options.getSpan(state.item, state.view, parts[0].replace(/%20/g, ' '), function(span, view) {
if (span) {
if (!state.view) {
// set list or item view

View file

@ -14,6 +14,7 @@ Ox.Map <function> Basic map object
options <o|{}> options
clickable <b|false> If true, clicking on the map finds a place
editable <b|false> If true, places are editable
find <s|""> Initial query
findPlaceholder <s|"Find"> Placeholder text for the find input element
maxMarkers <n|100> Maximum number of markers to be displayed
places <[o]|f|null> Array of, or function that returns, place objects
@ -97,6 +98,7 @@ Ox.Map = function(options, self) {
// fixme: isClickable? hasZoombar?
clickable: false,
editable: false,
find: '',
findPlaceholder: 'Find',
maxMarkers: 100,
places: null,
@ -570,15 +572,9 @@ Ox.Map = function(options, self) {
}
function getMetersPerPixel() {
// fixme: this is wrong when resizing the map horizontally
var mapWidth = self.$map.width(),
span = self.map.getBounds().toSpan().lng();
/*
if (span >= 360) {
span = 360 * mapWidth / Ox.MAP_TILE_SIZE;
}
*/
return Ox.getMetersPerDegree(self.map.getCenter().lat()) * span / mapWidth;
// m/px = m/deg * deg/px
var degreesPerPixel = 360 / (Ox.MAP_TILE_SIZE * Math.pow(2, self.map.getZoom()));
return Ox.getMetersPerDegree(self.map.getCenter().lat()) * degreesPerPixel;
}
function getMinZoom() {
@ -726,10 +722,19 @@ Ox.Map = function(options, self) {
google.maps.event.addListener(self.map, 'zoom_changed', zoomChanged);
google.maps.event.addListenerOnce(self.map, 'tilesloaded', tilesLoaded);
if (self.options.find) {
self.$findInput.options({value: self.options.find})
.triggerEvent('submit', {value: self.options.find});
} else if (self.options.selected) {
selectPlace(self.options.selected);
} else {
mapBounds && self.map.fitBounds(mapBounds);
///*
if (self.map.getZoom() < self.minZoom) {
self.map.setZoom(self.minZoom);
}
//*/
}
self.places = [];
if (!self.isAsync) {
@ -754,6 +759,11 @@ Ox.Map = function(options, self) {
}
}
function crossesDateline() {
var bounds = self.map.getBounds();
return bounds.getSouthWest().lng() > bounds.getNorthEast().lng();
}
function mapChanged() {
// gets called after panning or zooming
Ox.print('mapChanged');
@ -765,8 +775,7 @@ Ox.Map = function(options, self) {
south = southWest.lat(),
west = southWest.lng(),
north = northEast.lat(),
east = northEast.lng(),
crossesDateline = west > east;
east = northEast.lng();
if (!self.isAsync) {
self.places.sort(function(a, b) {
var sort = {
@ -784,31 +793,18 @@ Ox.Map = function(options, self) {
}
});
} else {
Ox.print('QUERY', {
conditions: Ox.merge([
{key: 'lat', value: [south, north], operator: '-'}
], !crossesDateline ? [
{key: 'lng', value: [west, east], operator: '-'}
] : [
{
conditions: [
{key: 'lng', value: west, operator: '<'},
{key: 'lng', value: east, operator: '>'}
],
operator: '|'
}
]),
operator: '&'
});
Ox.print ('sG cD', spansGlobe(), crossesDateline())
self.options.places({
keys: self.placeKeys,
query: {
conditions: Ox.merge([
{key: 'lat', value: [south, north], operator: '-'}
], !crossesDateline ? [
{key: 'lng', value: [west, east], operator: '-'}
] : [
], spansGlobe() ? [
{key: 'lng', value: [-180, 180], operator: '-'}
] : crossesDateline() ? [
{key: 'lng', value: [east, west], operator: '!-'}
] : [
{key: 'lng', value: [west, east], operator: '-'}
]),
operator: '&'
},
@ -1033,16 +1029,19 @@ Ox.Map = function(options, self) {
keys: self.placeKeys,
query: {
conditions: [
{key: 'id', value: id, operator: '='}
]
{key: 'id', value: id, operator: '=='}
],
operator: '&'
}
}, function(results) {
}, function(result) {
if (result.data.items.length) {
place = new Ox.MapPlace(Ox.extend({
map: that
}, results.data.items[0])).add();
}, result.data.items[0])).add();
self.places.push(place);
select();
that.panToPlace();
that.zoomToPlace();
}
});
}
} else {
@ -1110,6 +1109,11 @@ Ox.Map = function(options, self) {
//Ox.print('STATUS DONE');
}
function spansGlobe() {
// fixme: or self.options.width ??
return self.$map.width() > Ox.MAP_TILE_SIZE * Math.pow(2, self.map.getZoom());
};
function submitFind(data) {
that.findPlace(data.value, function(place) {
setStatus(place);

View file

@ -145,7 +145,6 @@ Ox.SplitPanel = function(options, self) {
css[self.edges[1]] = (
self.length == 3 ? getVisibleSize(self.options.elements[2]) : 0
) + 'px';
Ox.print('i==1 CSS', css)
} else {
if (element.size == 'auto') {
css[self.edges[0]] = getVisibleSize(self.options.elements[0])

View file

@ -20,7 +20,7 @@ Ox.VideoPlayer <f> Generic Video Player
enableFind <b|false> If true, enable find
enableFullscreen <b|false> If true, enable fullscreen
enableKeyboard <b|false> If true, enable keyboard controls
enableMouse <b|false> If true, click toggles paused
enableMouse <b|false> If true, click toggles paused and drag changes position
externalControls <b|false> If true, controls are outside the video
find <s|''> Query string
focus <s|'click'> focus on 'click', 'load' or 'mouseover'
@ -34,7 +34,7 @@ Ox.VideoPlayer <f> Generic Video Player
keepLogoVisible <b|false> If true, logo stays visible after mouseleave
logo <s|''> Logo image URL
logoLink <s|''> Logo link URL
logoTitle <s|''> Text for tooltip
logoTitle <s|''> Text for Logo tooltip // fixme: shouldn't this be logoTooltip then?s
muted <b|false> If true, video is muted
paused <b|false> If true, video is paused
playInToOut <b|false> If true, video plays only from in to out

View file

@ -6,11 +6,12 @@
Some conventions:
Functions
- only one var statement, in the first line of the function
- return only once, from the last line of the function body
- return only once, from the last line of the function
Variable names
arg argument
args arguments
arr array
canFoo boolean
callback callback function
col collection (array, string or object)
date date
@ -29,18 +30,48 @@ Some conventions:
v value (of a key/value pair)
val value (of a key/value pair)
Indentation
var a = 1,
b = 2,
c = 3;
Obj.fn1()
.fn2()
.fn3();
Variable definitions
var a = {
key: value,
key: value,
key: value
},
b = {key: value},
c = {key: value};
Method chaining
Obj.fnA({
key: value,
key: value,
key: value
})
.fnB({key: val})
.fnC({key: val});
Simple conditionals
condition && expression;
Conditionals
if (condition) {
expression;
}
Conditionals with long conditions
if (
condition
&& condition
&& condition
) {
expression;
}
Ternary operator
condition ? expression : expression;
Ternary operator with long conditions or expressions
condition ? expression
: condition ? expression
: expression;
*/
// todo: check http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
// also see https://github.com/tlrobinson/narwhal/blob/master/lib/util.js
// Fallbacks -------------------------------------------------------------------
// see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
if (!Array.prototype.filter) {
@ -176,11 +207,17 @@ Ox = function(val) {
/*@
Ox.load <f> Loads a module
A module named "Test" provides <code>Ox.Test/Ox.Test.js</code>, in which it
defines one method, <code>Ox.load.Test</code>, that takes two arguments,
<code>options</code> and <code>callback</code>, and calls
<code>callback</code> with one argument, <code>true</code> for success or
<code>false</code> if an error occurred. Generally, the module should
define <code>Ox.Test</code> and attach its own methods there.
(module, callback) -> <u> undefined
(module, options, callback) -> <u> undefined
(modules, callback) -> <u> undefined
module <s> Module name
modules <o> Multiple modules {name: options}
modules <o> Multiple modules {name: options, ...}
options <o> Module options
callback <f> Callback function
success <b> If true, the module has been loaded successfully
@ -235,6 +272,7 @@ Ox.uid <f> Returns a unique id
> Ox.uid() != Ox.uid()
true
@*/
Ox.uid = (function() {
var uid = 0;
return function() {
@ -244,13 +282,14 @@ Ox.uid = (function() {
/*@
Ox.wrap <f> Wraps a value so that one can directly call any Ox function on it
<code>Ox(value)</code> is a shorthand for <code>Ox.wrap(value)</code>.
(value) -> <o> wrapped value
chain <f> wrap the return value to allow chaining
value <f> unwrap the value wrapped by <code>chain()</chain>
chain <f> Wrap return values to allow chaining
value <f> Unwrap the value wrapped by <code>chain()</chain>
value <*> Any value
> Ox.wrap("foobar").repeat(2)
> Ox("foobar").repeat(2)
"foobarfoobar"
> Ox.wrap("foobar").chain().reverse().toTitleCase().value()
> Ox("foobar").chain().reverse().toTitleCase().value()
"Raboof"
> Ox.wrap("foobar").value()
"foobar"
@ -425,32 +464,6 @@ Ox.avg = function(obj) {
return Ox.sum(obj) / Ox.len(obj);
};
/*@
Ox.clone <f> Returns a (shallow or deep) copy of an object or array
> (function() { a = ['val']; b = Ox.clone(a); a[0] = null; return b[0]; }())
'val'
> (function() { a = {key: 'val'}; b = Ox.clone(a); a.key = null; return b.key; }())
'val'
> Ox.clone(0)
0
@*/
Ox.clone = function(col, deep) {
// fixme: is there any use case for shallow copy?
var ret = Ox.isArray(col) ? [] : {};
if (deep) {
Ox.forEach(col, function(val, key) {
ret[key] = ['array', 'object'].indexOf(Ox.typeOf(val)) > -1
? Ox.clone(val, true) : val;
});
} else {
ret = Ox.isArray(col) ? col.slice()
: Ox.isObject(col) ? Ox.extend({}, col)
: col;
}
return ret;
};
/*@
Ox.contains <f> Tests if a collection contains a value
> Ox.contains(['foo', 'bar'], 'foo')
@ -470,6 +483,33 @@ Ox.contains = function(col, val) {
return (Ox.isObject(col) ? Ox.values(col) : col).indexOf(val) > -1;
};
/*@
Ox.copy <f> Returns a (shallow or deep) copy of an object or array
> (function() { a = ['v']; b = Ox.copy(a); a[0] = null; return b[0]; }())
'v'
> (function() { a = {k: 'v'}; b = Ox.copy(a); a.k = null; return b.k; }())
'v'
> Ox.clone(0)
0
@*/
Ox.copy = Ox.clone = function(col, deep) {
// fixme: remove references to Ox.clone
// fixme: is there any use case for shallow copy?
var ret = Ox.isArray(col) ? [] : {};
if (deep) {
Ox.forEach(col, function(val, key) {
ret[key] = ['array', 'object'].indexOf(Ox.typeOf(val)) > -1
? Ox.clone(val, true) : val;
});
} else {
ret = Ox.isArray(col) ? col.slice()
: Ox.isObject(col) ? Ox.extend({}, col)
: col;
}
return ret;
};
/*@
Ox.count <f> Counts the occurences of values in a collection
> Ox.count(['f', 'o', 'o'])
@ -600,7 +640,7 @@ Ox.getObjectById <f> Returns an array element with a given id
> Ox.getObjectById([{id: "foo", title: "Foo"}, {id: "bar", title: "Bar"}], "foo")
{id: "foo", title: "Foo"}
@*/
// fixme: shouldn't this be getElementById() ?
// fixme: should this be getElementById() ?
Ox.getObjectById = function(arr, id) {
var ret = null;
Ox.forEach(arr, function(v) {
@ -617,7 +657,7 @@ Ox.getPositionById <f> Returns the index of an array element with a given id
> Ox.getPositionById([{id: "foo", title: "Foo"}, {id: "bar", title: "Bar"}], "foo")
0
@*/
// fixme: shouldn't this be getIndexById() ?
// fixme: this should be getIndexById()
Ox.getPositionById = function(arr, id) {
var ret = -1;
Ox.forEach(arr, function(v, i) {
@ -656,7 +696,9 @@ Ox.getset <f> Generic getter and setter function
<script>
Ox.test.object = new function() {
var options = {},
setOption = function(key, value) {},
setOption = function(key, value) {
// handle added or modified options
},
that = this;
that.options = function() {
return Ox.getset(options, arguments, setOption, that);
@ -673,13 +715,13 @@ Ox.getset <f> Generic getter and setter function
Ox.getset = function(obj, args, callback, context) {
var obj_ = Ox.clone(obj), ret;
if (args.length == 0) {
// getset([])
// []
ret = obj_;
} else if (args.length == 1 && !Ox.isObject(args[0])) {
// getset([key])
// [key]
ret = Ox.clone(obj[args[0]]);
} else {
// getset([key, val]) or getset([{key: val, ...}])
// [key, val] or [{key: val, ...}]
args = Ox.makeObject(args);
obj = Ox.extend(obj, args);
Ox.forEach(args, function(val, key) {
@ -710,7 +752,6 @@ Ox.isEmpty <f> Returns true if a collection is empty
false
@*/
Ox.isEmpty = function(val) {
// fixme: what about deep isEmpty?
return Ox.len(val) == 0;
};
@ -783,8 +824,7 @@ Ox.len <f> Returns the length of an array, function, object or string
@*/
Ox.len = function(col) {
var type = Ox.typeOf(col);
return ['array', 'function', 'string'].indexOf(type) > -1
? col.length
return ['array', 'function', 'string'].indexOf(type) > -1 ? col.length
: type == 'object' ? Ox.values(col).length : void 0;
};
@ -809,10 +849,10 @@ Ox.loop <f> For-loop, functional-style
step <n> Step value
callback <f> Iterator function
i <n> Counter value
> Ox.loop(0, 3, 2, function() {})
4
> Ox.loop(10, function(i) { return i != 4; })
4
> Ox.loop(0, 3, 2, function() {})
4
@*/
Ox.loop = function() {
var len = arguments.length,
@ -842,7 +882,8 @@ Ox.makeArray <f> Takes an array-like object and returns a true array
["f", "o", "o"]
@*/
Ox.makeArray = /MSIE/.test(navigator.userAgent) ? function(col) {
Ox.makeArray = /MSIE/.test(navigator.userAgent)
? function(col) {
var i, len, ret = [];
try {
ret = Array.prototype.slice.call(col);
@ -854,9 +895,10 @@ Ox.makeArray = /MSIE/.test(navigator.userAgent) ? function(col) {
}
}
return ret;
} : function(col) {
}
: function(col) {
return Array.prototype.slice.call(col);
}
};
/*@
Ox.makeObject <f> Takes an array and returns an object
@ -867,7 +909,7 @@ Ox.makeObject <f> Takes an array and returns an object
> (function() { return Ox.makeObject(arguments); }('foo', 1))
{foo: 1}
> (function() { return Ox.makeObject(arguments); }('foo'))
{}
{foo: void 0}
> (function() { return Ox.makeObject(arguments); }())
{}
@*/
@ -902,7 +944,7 @@ Ox.map <f> Transforms the values of an array, object or string
@*/
Ox.map = function(obj, fn) {
// fixme: return null to filter out is a bit esoteric
// fixme: return null to filter out may be a bit esoteric
var isObject = Ox.isObject(obj),
ret = isObject ? {} : [];
Ox.forEach(obj, function(val, key) {
@ -3300,16 +3342,24 @@ Ox.parseHTML <f> Takes HTML from an untrusted source and returns something sane
> Ox.parseHTML('<a href="http://foo.com" onmouseover="alert()">foo</a>')
'<a href="http://foo.com" title="http://foo.com">foo</a>'
> Ox.parseHTML('<a href="javascript:alert()">foo</a>')
'&lt;a href=&quot;javascript:alert()&quot;&gt;foo&lt;/a&gt;'
'&lt;a href="javascript:alert()"&gt;foo'
> Ox.parseHTML('[http://foo.com foo]')
'<a href="http://foo.com" title="http://foo.com">foo</a>'
> Ox.parseHTML('<rtl>foo</rtl>')
'<div style="direction: rtl">foo</div>'
> Ox.parseHTML('<script>alert()</script>')
'&lt;script&gt;alert()&lt;/script&gt;'
> Ox.parseHTML('\'foo\' < \'bar\' && "foo" > "bar"')
'\'foo\' &lt; \'bar\' &amp;&amp; "foo" &gt; "bar"'
> Ox.parseHTML('<b>foo')
'<b>foo</b>'
> Ox.parseHTML('<b>foo</b></b>')
'<b>foo</b>'
@*/
Ox.parseHTML = (function() {
var defaultTags = [
// fixme: why not p?
'a', 'b', 'blockquote', 'cite', 'code',
'del', 'em', 'i', 'img', 'ins',
'li', 'ol', 'q', 'rtl', 's',
@ -3357,13 +3407,13 @@ Ox.parseHTML = (function() {
html = Ox.encodeHTML(html);
html = Ox.parseURLs(html);
html = Ox.parseEmailAddresses(html);
Ox.print(html, 'matches', matches);
matches.forEach(function(match, i) {
html = html.replace(new RegExp(tab + i + tab, 'gi'), match);
});
html = html.replace(/\n/g, '<br/>\n')
// close extra opening (and remove extra closing) tags
// return $('<div>').html(html).html();
// fixme: this converts '&quot;' to '"'
// note: this converts '&quot;' to '"'
return Ox.element('<div>').html(html).html();
}
@ -3952,7 +4002,7 @@ Ox.tokenize = (function() {
'global', 'ignoreCase', 'lastIndex', 'multiline', 'source',
// Window
'applicationCache',
'closed', 'content', 'crypto',
'closed', 'console', 'content', 'crypto',
'defaultStatus', 'document',
'frameElement', 'frames',
'history',
@ -3966,7 +4016,6 @@ Ox.tokenize = (function() {
'self', 'sessionStorage', 'status', 'statusbar',
'toolbar', 'top'
]
// Window stuff? 'atob', 'btoa', 'console', 'document' ...
};
return function(source) {
@ -4269,10 +4318,10 @@ Ox.extend = function() {
Ox.serialize <f> Parses an object into query parameters
> Ox.serialize({a: 1, b: 2, c: 3})
'a=1&b=2&c=3'
> Ox.serialize({a: 1, b: 2.3, c: [4, 5]})
'a=1&b=2.3&c=4,5'
> Ox.serialize({a: -1, b: 2.3, c: [4, 5]})
'a=-1&b=2.3&c=4,5'
> Ox.serialize({string: 'foo', empty: {}, null: null, undefined: void 0})
'string=bar'
'string=foo'
@*/
Ox.serialize = function(obj) {
var arr = [];
@ -4288,8 +4337,8 @@ Ox.serialize = function(obj) {
Ox.unserialize <f> Parses query parameters into an object
> Ox.unserialize('a=1&b=2&c=3')
{a: '1', b: '2', c: '3'}
> Ox.unserialize('a=1&b=2.3&c=4,5', true)
{a: 1, b: 2.3, c: [4, 5]}
> Ox.unserialize('a=-1&b=2.3&c=4,5', true)
{a: -1, b: 2.3, c: [4, 5]}
@*/
Ox.unserialize = function(str, toNumber) {
var obj = {};
@ -4774,8 +4823,8 @@ Ox.truncate = function(str, len, pad, pos) {
Ox.words <f> Splits a string into words, removing punctuation
(string) -> <[s]> Array of words
string <s> Any string
> Ox.words('Let\'s "walk" a tree-like key/value store--okay?')
["let's", "walk", "a", "tree-like", "key", "value", "store", "okay"]
> Ox.words('Let\'s "split" array-likes into key/value pairs--okay?')
["let's", "split", "array-likes", "into", "key", "value", "pairs", "okay"]
@*/
Ox.words = function(str) {
var arr = str.toLowerCase().split(/\b/),
@ -4783,12 +4832,11 @@ Ox.words = function(str) {
len = arr.length,
startsWithWord = /\w/.test(arr[0]);
arr.forEach(function(v, i) {
// find single occurrences of "-" or "-"
// that are not at the beginning or end of the string
// and join the surrounding words with them
// find single occurrences of "-" or "'" that are not at the beginning
// or end of the string, and join the surrounding words with them
if (
i > 0 && i < len - 1 &&
v.length == 1 && chr.indexOf(v) > -1
i > 0 && i < len - 1
&& v.length == 1 && chr.indexOf(v) > -1
) {
arr[i + 1] = arr[i - 1] + arr[i] + arr[i + 1];
arr[i - 1] = arr[i] = '';
@ -4986,18 +5034,17 @@ Ox.isEqual = function(a, b) {
isEqual = true;
} else if (type == 'date') {
isEqual = a.getTime() == b.getTime();
/* toString doesn't do it
} else if (['element', 'function'].indexOf(type) > -1) {
} else if (type == 'element') {
isEqual = a.isEqualNode(b);
} else if (type == 'function') {
// fixme: this doesn't do it
isEqual = a.toString() == b.toString();
*/
} else if (type == 'regexp') {
isEqual = a.global == b.global &&
a.ignore == b.ignore &&
a.multiline == b.multiline &&
a.source == b.source;
isEqual = a.global == b.global && a.ignore == b.ignore
&& a.multiline == b.multiline && a.source == b.source;
} else if (
['arguments', 'array', 'object'].indexOf(type) > -1 &&
Ox.len(a) == Ox.len(b)
['arguments', 'array', 'object'].indexOf(type) > -1
&& Ox.len(a) == Ox.len(b)
) {
isEqual = true;
Ox.forEach(a, function(v, k) {
@ -5018,7 +5065,7 @@ Ox.isFunction <f> Tests if a value is a function
> Ox.isFunction(/ /)
false
@*/
Ox.isFunction = function(val) { // is in jQuery
Ox.isFunction = function(val) {
return typeof val == 'function' && !Ox.isRegExp(val);
};
@ -5090,11 +5137,14 @@ Ox.isObject <f> Tests if a value is a an object
false
> Ox.isObject(null)
false
> Ox.isObject(/ /)
false
@*/
Ox.isObject = function(val) {
return typeof val == 'object' && !Ox.isArguments(val)
&& !Ox.isArray(val) && !Ox.isDate(val) && !Ox.isNull(val);
&& !Ox.isArray(val) && !Ox.isDate(val)
&& !Ox.isNull(val) && !Ox.isRegExp(val);
};
/*@

View file

@ -1,4 +1,4 @@
Ox.load('UI', function() {
Ox.load({UI: {}, Geo: {}}, function() {
//Ox.UI.ready(function() {
@ -23,7 +23,7 @@ Ox.load('UI', function() {
setBackground($tests, true);
tests(['../build/Ox.js'/*, '../build/js/ox.data.js'*/]);
tests(['../build/Ox.js', '../build/Ox.Geo/Ox.Geo.js']);
function tests() {
var passed = 0, failed = 0,