merging github and google code

This commit is contained in:
Jono Brandel 2013-12-18 14:24:50 -08:00
commit 1019f6c4f9
17 changed files with 2424 additions and 5835 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
.DS_Store .DS_Store
.sass-cache .sass-cache
.idea

0
.gitmodules vendored Normal file
View File

89
README.md Normal file
View File

@ -0,0 +1,89 @@
#dat.GUI
A lightweight graphical user interface for changing variables in JavaScript.
Get started with dat.GUI by reading the tutorial at [http://workshop.chromeexperiments.com/examples/gui].
----
##Packaged Builds
The easiest way to use dat.GUI in your code is by using the built source at `build/dat.gui.min.js`. These built JavaScript files bundle all the necessary dependencies to run dat.GUI.
In your `head` tag, include the following code:
```
<script type="text/javascript" src="dat.gui.min.js"></script>
```
----
##Using dat.GUI with require.js
Internally, dat.GUI uses [require.js](http://requirejs.org/) to handle dependency management. If you're making changes to the source and want to see the effects of your changes without building, use require js.
In your `head` tag, include the following code:
```
<script data-main="path/to/main" src="path/to/requirejs/require.js"></script>
```
Then, in `path/to/main.js`:
```
require([
'path/to/gui/module/GUI'
], function(GUI) {
// No namespace necessary
var gui = new GUI();
});
```
----
##Directory Contents
* build: Concatenated source code.
* src: Modular code in [require.js](http://requirejs.org/) format. Also includes css, [scss](http://sass-lang.com/), and html, some of which is included during build.
* tests: [QUnit](https://github.com/jquery/qunit) test suite.
* utils: [node.js](http://nodejs.org/) utility scripts for compiling source.
----
##Building your own dat.GUI
In the terminal, enter the following:
```
$ cd utils
$ node build_gui.js
```
This will create a namespaced, unminified build of dat.GUI at `build/dat.gui.js`
_To export minified source using Closure Compiler, open `utils/build_gui.js` and set the `minify` parameter to `true`._
----
##Change log
###0.5
* Moved to requirejs for dependency management.
* Changed global namespace from *DAT* to *dat* (lowercase).
* Added support for color controllers. See [Color Controllers](http://workshop.chromeexperiments.com/examples/gui/#4--Color-Controllers).
* Added support for folders. See [Folders](http://workshop.chromeexperiments.com/examples/gui/#3--Folders).
* Added support for saving named presets. See [Presets](http://workshop.chromeexperiments.com/examples/gui/examples/gui/#6--Presets).
* Removed `height` parameter from GUI constructor. Scrollbar automatically induced when window is too short.
* `dat.GUI.autoPlace` parameter removed. Use `new dat.GUI( { autoPlace: false } )`. See [Custom Placement](http://workshop.chromeexperiments.com/examples/gui/#9--Custom-Placement).
* `gui.autoListen` and `gui.listenAll()` removed. See [Updating The Display Manually](http://workshop.chromeexperiments.com/examples/gui/#11--Updating-the-Display-Manually).
* `dat.GUI.load` removed. See [Saving Values](http://workshop.chromeexperiments.com/examples/gui/#5--Saving-Values).
* Made Controller code completely agnostic of GUI. Controllers can easily be created independent of a GUI panel.
#0.4
* Migrated from GitHub to Google Code.
----
##Thanks
The following libraries / open-source projects were used in the development of dat.GUI:
* [require.js](http://requirejs.org/)
* [Sass](http://sass-lang.com/)
* [node.js](http://nodejs.org/)
* [QUnit](https://github.com/jquery/qunit) / [jquery](http://jquery.com/)

View File

@ -1,755 +0,0 @@
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
/** @namespace */
var dat = dat || {};
/** @namespace */
dat.color = dat.color || {};
/** @namespace */
dat.utils = dat.utils || {};
dat.utils.common = (function () {
var ARR_EACH = Array.prototype.forEach;
var ARR_SLICE = Array.prototype.slice;
/**
* Band-aid methods for things that should be a lot easier in JavaScript.
* Implementation and structure inspired by underscore.js
* http://documentcloud.github.com/underscore/
*/
return {
BREAK: {},
extend: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (!this.isUndefined(obj[key]))
target[key] = obj[key];
}, this);
return target;
},
defaults: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (this.isUndefined(target[key]))
target[key] = obj[key];
}, this);
return target;
},
compose: function() {
var toCall = ARR_SLICE.call(arguments);
return function() {
var args = ARR_SLICE.call(arguments);
for (var i = toCall.length -1; i >= 0; i--) {
args = [toCall[i].apply(this, args)];
}
return args[0];
}
},
each: function(obj, itr, scope) {
if (ARR_EACH && obj.forEach === ARR_EACH) {
obj.forEach(itr, scope);
} else if (obj.length === obj.length + 0) { // Is number but not NaN
for (var key = 0, l = obj.length; key < l; key++)
if (key in obj && itr.call(scope, obj[key], key) === this.BREAK)
return;
} else {
for (var key in obj)
if (itr.call(scope, obj[key], key) === this.BREAK)
return;
}
},
defer: function(fnc) {
setTimeout(fnc, 0);
},
toArray: function(obj) {
if (obj.toArray) return obj.toArray();
return ARR_SLICE.call(obj);
},
isUndefined: function(obj) {
return obj === undefined;
},
isNull: function(obj) {
return obj === null;
},
isNaN: function(obj) {
return obj !== obj;
},
isArray: Array.isArray || function(obj) {
return obj.constructor === Array;
},
isObject: function(obj) {
return obj === Object(obj);
},
isNumber: function(obj) {
return obj === obj+0;
},
isString: function(obj) {
return obj === obj+'';
},
isBoolean: function(obj) {
return obj === false || obj === true;
},
isFunction: function(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
};
})();
dat.color.toString = (function (common) {
return function(color) {
if (color.a == 1 || common.isUndefined(color.a)) {
var s = color.hex.toString(16);
while (s.length < 6) {
s = '0' + s;
}
return '#' + s;
} else {
return 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',' + color.a + ')';
}
}
})(dat.utils.common);
dat.Color = dat.color.Color = (function (interpret, math, toString, common) {
var Color = function() {
this.__state = interpret.apply(this, arguments);
if (this.__state === false) {
throw 'Failed to interpret color arguments';
}
this.__state.a = this.__state.a || 1;
};
Color.COMPONENTS = ['r','g','b','h','s','v','hex','a'];
common.extend(Color.prototype, {
toString: function() {
return toString(this);
},
toOriginal: function() {
return this.__state.conversion.write(this);
}
});
defineRGBComponent(Color.prototype, 'r', 2);
defineRGBComponent(Color.prototype, 'g', 1);
defineRGBComponent(Color.prototype, 'b', 0);
defineHSVComponent(Color.prototype, 'h');
defineHSVComponent(Color.prototype, 's');
defineHSVComponent(Color.prototype, 'v');
Object.defineProperty(Color.prototype, 'a', {
get: function() {
return this.__state.a;
},
set: function(v) {
this.__state.a = v;
}
});
Object.defineProperty(Color.prototype, 'hex', {
get: function() {
if (!this.__state.space !== 'HEX') {
this.__state.hex = math.rgb_to_hex(this.r, this.g, this.b);
}
return this.__state.hex;
},
set: function(v) {
this.__state.space = 'HEX';
this.__state.hex = v;
}
});
function defineRGBComponent(target, component, componentHexIndex) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'RGB') {
return this.__state[component];
}
recalculateRGB(this, component, componentHexIndex);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'RGB') {
recalculateRGB(this, component, componentHexIndex);
this.__state.space = 'RGB';
}
this.__state[component] = v;
}
});
}
function defineHSVComponent(target, component) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'HSV')
return this.__state[component];
recalculateHSV(this);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'HSV') {
recalculateHSV(this);
this.__state.space = 'HSV';
}
this.__state[component] = v;
}
});
}
function recalculateRGB(color, component, componentHexIndex) {
if (color.__state.space === 'HEX') {
color.__state[component] = math.component_from_hex(color.__state.hex, componentHexIndex);
} else if (color.__state.space === 'HSV') {
common.extend(color.__state, math.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
} else {
throw 'Corrupted color state';
}
}
function recalculateHSV(color) {
var result = math.rgb_to_hsv(color.r, color.g, color.b);
common.extend(color.__state,
{
s: result.s,
v: result.v
}
);
if (!common.isNaN(result.h)) {
color.__state.h = result.h;
} else if (common.isUndefined(color.__state.h)) {
color.__state.h = 0;
}
}
return Color;
})(dat.color.interpret = (function (toString, common) {
var result, toReturn;
var interpret = function() {
toReturn = false;
var original = arguments.length > 1 ? common.toArray(arguments) : arguments[0];
common.each(INTERPRETATIONS, function(family) {
if (family.litmus(original)) {
common.each(family.conversions, function(conversion, conversionName) {
result = conversion.read(original);
if (toReturn === false && result !== false) {
toReturn = result;
result.conversionName = conversionName;
result.conversion = conversion;
return common.BREAK;
}
});
return common.BREAK;
}
});
return toReturn;
};
var INTERPRETATIONS = [
// Strings
{
litmus: common.isString,
conversions: {
THREE_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt(
'0x' +
test[1].toString() + test[1].toString() +
test[2].toString() + test[2].toString() +
test[3].toString() + test[3].toString())
};
},
write: toString
},
SIX_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9]{6})$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt('0x' + test[1].toString())
};
},
write: toString
},
CSS_RGB: {
read: function(original) {
var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3])
};
},
write: toString
},
CSS_RGBA: {
read: function(original) {
var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3]),
a: parseFloat(test[4])
};
},
write: toString
}
}
},
// Numbers
{
litmus: common.isNumber,
conversions: {
HEX: {
read: function(original) {
return {
space: 'HEX',
hex: original,
conversionName: 'HEX'
}
},
write: function(color) {
return color.hex;
}
}
}
},
// Arrays
{
litmus: common.isArray,
conversions: {
RGB_ARRAY: {
read: function(original) {
if (original.length != 3) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2]
};
},
write: function(color) {
return [color.r, color.g, color.b];
}
},
RGBA_ARRAY: {
read: function(original) {
if (original.length != 4) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2],
a: original[3]
};
},
write: function(color) {
return [color.r, color.g, color.b, color.a];
}
}
}
},
// Objects
{
litmus: common.isObject,
conversions: {
RGBA_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b) &&
common.isNumber(original.a)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b,
a: original.a
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b,
a: color.a
}
}
},
RGB_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b
}
}
},
HSVA_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v) &&
common.isNumber(original.a)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v,
a: original.a
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v,
a: color.a
}
}
},
HSV_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v
}
}
}
}
}
];
return interpret;
})(dat.color.toString,
dat.utils.common),
dat.color.math = (function () {
var tmpComponent;
return {
hsv_to_rgb: function(h, s, v) {
var hi = Math.floor(h / 60) % 6;
var f = h / 60 - Math.floor(h / 60);
var p = v * (1.0 - s);
var q = v * (1.0 - (f * s));
var t = v * (1.0 - ((1.0 - f) * s));
var c = [
[v, t, p],
[q, v, p],
[p, v, t],
[p, q, v],
[t, p, v],
[v, p, q]
][hi];
return {
r: c[0] * 255,
g: c[1] * 255,
b: c[2] * 255
};
},
rgb_to_hsv: function(r, g, b) {
var min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s;
if (max != 0) {
s = delta / max;
} else {
return {
h: NaN,
s: 0,
v: 0
};
}
if (r == max) {
h = (g - b) / delta;
} else if (g == max) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h /= 6;
if (h < 0) {
h += 1;
}
return {
h: h * 360,
s: s,
v: max / 255
};
},
rgb_to_hex: function(r, g, b) {
var hex = this.hex_with_component(0, 2, r);
hex = this.hex_with_component(hex, 1, g);
hex = this.hex_with_component(hex, 0, b);
return hex;
},
component_from_hex: function(hex, componentIndex) {
return (hex >> (componentIndex * 8)) & 0xFF;
},
hex_with_component: function(hex, componentIndex, value) {
return value << (tmpComponent = componentIndex * 8) | (hex & ~ (0xFF << tmpComponent));
}
}
})(),
dat.color.toString,
dat.utils.common);

View File

@ -1,26 +0,0 @@
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
var dat=dat||{};dat.color=dat.color||{};dat.utils=dat.utils||{};
dat.utils.common=function(){var f=Array.prototype.forEach,b=Array.prototype.slice;return{BREAK:{},extend:function(c){this.each(b.call(arguments,1),function(b){for(var d in b)this.isUndefined(b[d])||(c[d]=b[d])},this);return c},defaults:function(c){this.each(b.call(arguments,1),function(b){for(var d in b)this.isUndefined(c[d])&&(c[d]=b[d])},this);return c},compose:function(){var c=b.call(arguments);return function(){for(var e=b.call(arguments),d=c.length-1;d>=0;d--)e=[c[d].apply(this,e)];return e[0]}},
each:function(b,e,d){if(f&&b.forEach===f)b.forEach(e,d);else if(b.length===b.length+0)for(var a=0,h=b.length;a<h;a++){if(a in b&&e.call(d,b[a],a)===this.BREAK)break}else for(a in b)if(e.call(d,b[a],a)===this.BREAK)break},defer:function(b){setTimeout(b,0)},toArray:function(c){return c.toArray?c.toArray():b.call(c)},isUndefined:function(b){return b===void 0},isNull:function(b){return b===null},isNaN:function(b){return b!==b},isArray:Array.isArray||function(b){return b.constructor===Array},isObject:function(b){return b===
Object(b)},isNumber:function(b){return b===b+0},isString:function(b){return b===b+""},isBoolean:function(b){return b===false||b===true},isFunction:function(b){return Object.prototype.toString.call(b)==="[object Function]"}}}();dat.color.toString=function(f){return function(b){if(b.a==1||f.isUndefined(b.a)){for(b=b.hex.toString(16);b.length<6;)b="0"+b;return"#"+b}else return"rgba("+Math.round(b.r)+","+Math.round(b.g)+","+Math.round(b.b)+","+b.a+")"}}(dat.utils.common);
dat.Color=dat.color.Color=function(f,b,c,e){function d(a,b,c){Object.defineProperty(a,b,{get:function(){if(this.__state.space==="RGB")return this.__state[b];h(this,b,c);return this.__state[b]},set:function(a){if(this.__state.space!=="RGB")h(this,b,c),this.__state.space="RGB";this.__state[b]=a}})}function a(a,b){Object.defineProperty(a,b,{get:function(){if(this.__state.space==="HSV")return this.__state[b];i(this);return this.__state[b]},set:function(a){if(this.__state.space!=="HSV")i(this),this.__state.space=
"HSV";this.__state[b]=a}})}function h(a,c,d){if(a.__state.space==="HEX")a.__state[c]=b.component_from_hex(a.__state.hex,d);else if(a.__state.space==="HSV")e.extend(a.__state,b.hsv_to_rgb(a.__state.h,a.__state.s,a.__state.v));else throw"Corrupted color state";}function i(a){var c=b.rgb_to_hsv(a.r,a.g,a.b);e.extend(a.__state,{s:c.s,v:c.v});if(e.isNaN(c.h)){if(e.isUndefined(a.__state.h))a.__state.h=0}else a.__state.h=c.h}var g=function(){this.__state=f.apply(this,arguments);if(this.__state===false)throw"Failed to interpret color arguments";
this.__state.a=this.__state.a||1};g.COMPONENTS="r,g,b,h,s,v,hex,a".split(",");e.extend(g.prototype,{toString:function(){return c(this)},toOriginal:function(){return this.__state.conversion.write(this)}});d(g.prototype,"r",2);d(g.prototype,"g",1);d(g.prototype,"b",0);a(g.prototype,"h");a(g.prototype,"s");a(g.prototype,"v");Object.defineProperty(g.prototype,"a",{get:function(){return this.__state.a},set:function(a){this.__state.a=a}});Object.defineProperty(g.prototype,"hex",{get:function(){if(!this.__state.space!==
"HEX")this.__state.hex=b.rgb_to_hex(this.r,this.g,this.b);return this.__state.hex},set:function(a){this.__state.space="HEX";this.__state.hex=a}});return g}(dat.color.interpret=function(f,b){var c,e,d=[{litmus:b.isString,conversions:{THREE_CHAR_HEX:{read:function(a){a=a.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);return a===null?false:{space:"HEX",hex:parseInt("0x"+a[1].toString()+a[1].toString()+a[2].toString()+a[2].toString()+a[3].toString()+a[3].toString())}},write:f},SIX_CHAR_HEX:{read:function(a){a=
a.match(/^#([A-F0-9]{6})$/i);return a===null?false:{space:"HEX",hex:parseInt("0x"+a[1].toString())}},write:f},CSS_RGB:{read:function(a){a=a.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);return a===null?false:{space:"RGB",r:parseFloat(a[1]),g:parseFloat(a[2]),b:parseFloat(a[3])}},write:f},CSS_RGBA:{read:function(a){a=a.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/);return a===null?false:{space:"RGB",r:parseFloat(a[1]),g:parseFloat(a[2]),b:parseFloat(a[3]),a:parseFloat(a[4])}},write:f}}},
{litmus:b.isNumber,conversions:{HEX:{read:function(a){return{space:"HEX",hex:a,conversionName:"HEX"}},write:function(a){return a.hex}}}},{litmus:b.isArray,conversions:{RGB_ARRAY:{read:function(a){return a.length!=3?false:{space:"RGB",r:a[0],g:a[1],b:a[2]}},write:function(a){return[a.r,a.g,a.b]}},RGBA_ARRAY:{read:function(a){return a.length!=4?false:{space:"RGB",r:a[0],g:a[1],b:a[2],a:a[3]}},write:function(a){return[a.r,a.g,a.b,a.a]}}}},{litmus:b.isObject,conversions:{RGBA_OBJ:{read:function(a){return b.isNumber(a.r)&&
b.isNumber(a.g)&&b.isNumber(a.b)&&b.isNumber(a.a)?{space:"RGB",r:a.r,g:a.g,b:a.b,a:a.a}:false},write:function(a){return{r:a.r,g:a.g,b:a.b,a:a.a}}},RGB_OBJ:{read:function(a){return b.isNumber(a.r)&&b.isNumber(a.g)&&b.isNumber(a.b)?{space:"RGB",r:a.r,g:a.g,b:a.b}:false},write:function(a){return{r:a.r,g:a.g,b:a.b}}},HSVA_OBJ:{read:function(a){return b.isNumber(a.h)&&b.isNumber(a.s)&&b.isNumber(a.v)&&b.isNumber(a.a)?{space:"HSV",h:a.h,s:a.s,v:a.v,a:a.a}:false},write:function(a){return{h:a.h,s:a.s,v:a.v,
a:a.a}}},HSV_OBJ:{read:function(a){return b.isNumber(a.h)&&b.isNumber(a.s)&&b.isNumber(a.v)?{space:"HSV",h:a.h,s:a.s,v:a.v}:false},write:function(a){return{h:a.h,s:a.s,v:a.v}}}}}];return function(){e=false;var a=arguments.length>1?b.toArray(arguments):arguments[0];b.each(d,function(d){if(d.litmus(a))return b.each(d.conversions,function(d,f){c=d.read(a);if(e===false&&c!==false)return e=c,c.conversionName=f,c.conversion=d,b.BREAK}),b.BREAK});return e}}(dat.color.toString,dat.utils.common),dat.color.math=
function(){var f;return{hsv_to_rgb:function(b,c,e){var d=b/60-Math.floor(b/60),a=e*(1-c),f=e*(1-d*c),c=e*(1-(1-d)*c),b=[[e,c,a],[f,e,a],[a,e,c],[a,f,e],[c,a,e],[e,a,f]][Math.floor(b/60)%6];return{r:b[0]*255,g:b[1]*255,b:b[2]*255}},rgb_to_hsv:function(b,c,e){var d=Math.min(b,c,e),a=Math.max(b,c,e),d=a-d;if(a==0)return{h:NaN,s:0,v:0};b=b==a?(c-e)/d:c==a?2+(e-b)/d:4+(b-c)/d;b/=6;b<0&&(b+=1);return{h:b*360,s:d/a,v:a/255}},rgb_to_hex:function(b,c,e){b=this.hex_with_component(0,2,b);b=this.hex_with_component(b,
1,c);return b=this.hex_with_component(b,0,e)},component_from_hex:function(b,c){return b>>c*8&255},hex_with_component:function(b,c,e){return e<<(f=c*8)|b&~(255<<f)}}}(),dat.color.toString,dat.utils.common);

File diff suppressed because one or more lines are too long

94
build/dat.gui.min.js vendored

File diff suppressed because one or more lines are too long

114
src/DAT/GUI/Controller.js Normal file
View File

@ -0,0 +1,114 @@
DAT.GUI.Controller = function() {
this.parent = arguments[0];
this.object = arguments[1];
this.propertyName = arguments[2];
//if (arguments.length > 0) this.initialValue = this.propertyName[this.object];
if (arguments.length > 0) this.initialValue = this.object[this.propertyName];
this.domElement = document.createElement('div');
this.domElement.setAttribute('class', 'guidat-controller ' + this.type);
this.propertyNameElement = document.createElement('span');
this.propertyNameElement.setAttribute('class', 'guidat-propertyname');
this.name(this.propertyName);
this.domElement.appendChild(this.propertyNameElement);
DAT.GUI.makeUnselectable(this.domElement);
};
DAT.GUI.Controller.prototype.changeFunction = null;
DAT.GUI.Controller.prototype.finishChangeFunction = null;
DAT.GUI.Controller.prototype.name = function(n) {
this.propertyNameElement.innerHTML = n;
return this;
};
DAT.GUI.Controller.prototype.reset = function() {
this.setValue(this.initialValue);
return this;
};
DAT.GUI.Controller.prototype.listen = function() {
this.parent.listenTo(this);
return this;
};
DAT.GUI.Controller.prototype.unlisten = function() {
this.parent.unlistenTo(this); // <--- hasn't been tested yet
return this;
};
DAT.GUI.Controller.prototype.setValue = function(n) {
if(this.object[this.propertyName] != undefined){
this.object[this.propertyName] = n;
}else{
var o = new Object();
o[this.propertyName] = n;
this.object.set(o);
}
if (this.changeFunction != null) {
this.changeFunction.call(this, n);
}
this.updateDisplay();
return this;
};
DAT.GUI.Controller.prototype.getValue = function() {
var val = this.object[this.propertyName];
if(val == undefined) val = this.object.get(this.propertyName);
return val;
};
DAT.GUI.Controller.prototype.updateDisplay = function() {
};
DAT.GUI.Controller.prototype.onChange = function(fnc) {
this.changeFunction = fnc;
return this;
};
DAT.GUI.Controller.prototype.onFinishChange = function(fnc) {
this.finishChangeFunction = fnc;
return this;
};
DAT.GUI.Controller.prototype.options = function() {
var _this = this;
var select = document.createElement('select');
if (arguments.length == 1) {
var arr = arguments[0];
for (var i in arr) {
var opt = document.createElement('option');
opt.innerHTML = i;
opt.setAttribute('value', arr[i]);
if (arguments[i] == this.getValue()) {
opt.selected = true;
}
select.appendChild(opt);
}
} else {
for (var i = 0; i < arguments.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = arguments[i];
opt.setAttribute('value', arguments[i]);
if (arguments[i] == this.getValue()) {
opt.selected = true;
}
select.appendChild(opt);
}
}
select.addEventListener('change', function() {
_this.setValue(this.value);
if (_this.finishChangeFunction != null) {
_this.finishChangeFunction.call(this, _this.getValue());
}
}, false);
_this.domElement.appendChild(select);
return this;
};

View File

@ -0,0 +1,43 @@
DAT.GUI.ControllerBoolean = function() {
this.type = "boolean";
DAT.GUI.Controller.apply(this, arguments);
var _this = this;
var input = document.createElement('input');
input.setAttribute('type', 'checkbox');
input.checked = this.getValue();
this.setValue(this.getValue());
this.domElement.addEventListener('click', function(e) {
input.checked = !input.checked;
e.preventDefault();
_this.setValue(input.checked);
}, false);
input.addEventListener('mouseup', function(e) {
input.checked = !input.checked; // counteracts default.
}, false);
this.domElement.style.cursor = "pointer";
this.propertyNameElement.style.cursor = "pointer";
this.domElement.appendChild(input);
this.updateDisplay = function() {
input.checked = _this.getValue();
};
this.setValue = function(val) {
if (typeof val != "boolean") {
try {
val = eval(val);
} catch (e) {
}
}
return DAT.GUI.Controller.prototype.setValue.call(this, val);
};
};
DAT.GUI.extendController(DAT.GUI.ControllerBoolean);

View File

@ -0,0 +1,30 @@
DAT.GUI.ControllerFunction = function() {
this.type = "function";
var _this = this;
DAT.GUI.Controller.apply(this, arguments);
this.domElement.addEventListener('click', function() {
_this.fire();
}, false);
this.domElement.style.cursor = "pointer";
this.propertyNameElement.style.cursor = "pointer";
var fireFunction = null;
this.onFire = function(fnc) {
fireFunction = fnc;
return this;
}
this.fire = function() {
if (fireFunction != null) {
fireFunction.call(this);
}
_this.object[_this.propertyName].call(_this.object);
};
};
DAT.GUI.extendController(DAT.GUI.ControllerFunction);

View File

@ -0,0 +1,243 @@
DAT.GUI.ControllerNumber = function() {
this.type = "number";
DAT.GUI.Controller.apply(this, arguments);
var _this = this;
// If we simply click and release a number field, we want to highlight it.
// This variable keeps track of whether or not we've dragged
var draggedNumberField = false;
var clickedNumberField = false;
var draggingHorizontal = false;
var draggingVertical = false;
var y = 0, py = 0;
var min = arguments[3];
var max = arguments[4];
var step = arguments[5];
var defaultStep = function() {
step = (max - min) * 0.01;
};
this.min = function() {
var needsSlider = false;
if (min == undefined && max != undefined) {
needsSlider = true;
}
if (arguments.length == 0) {
return min;
} else {
min = arguments[0];
}
if (needsSlider) {
addSlider();
if (step == undefined) {
defaultStep();
}
}
return _this;
};
this.max = function() {
var needsSlider = false;
if (min != undefined && max == undefined) {
needsSlider = true;
}
if (arguments.length == 0) {
return max;
} else {
max = arguments[0];
}
if (needsSlider) {
addSlider();
if (step == undefined) {
defaultStep();
}
}
return _this;
};
this.step = function() {
if (arguments.length == 0) {
return step;
} else {
step = arguments[0];
}
return _this;
};
this.getMin = function() {
return min;
};
this.getMax = function() {
return max;
};
this.getStep = function() {
if (step == undefined) {
if (max != undefined && min != undefined) {
return (max-min)/100;
} else {
return 1;
}
} else {
return step;
}
}
var numberField = document.createElement('input');
numberField.setAttribute('id', this.propertyName);
numberField.setAttribute('type', 'text');
numberField.setAttribute('value', this.getValue());
if (step) numberField.setAttribute('step', step);
this.domElement.appendChild(numberField);
var slider;
var addSlider = function() {
slider = new DAT.GUI.ControllerNumberSlider(_this, min, max, step, _this.getValue());
_this.domElement.appendChild(slider.domElement);
};
if (min != undefined && max != undefined) {
addSlider();
}
numberField.addEventListener('blur', function() {
var val = parseFloat(this.value);
if (slider) {
DAT.GUI.removeClass(_this.domElement, 'active');
}
if (!isNaN(val)) {
_this.setValue(val);
}
}, false);
numberField.addEventListener('mousewheel', function(e) {
e.preventDefault();
_this.setValue(_this.getValue() + Math.abs(e.wheelDeltaY) / e.wheelDeltaY * _this.getStep());
return false;
}, false);
numberField.addEventListener('mousedown', function(e) {
py = y = e.pageY;
clickedNumberField = true;
DAT.GUI.makeSelectable(numberField);
document.addEventListener('mousemove', dragNumberField, false);
document.addEventListener('mouseup', mouseup, false);
}, false);
// Handle up arrow and down arrow
numberField.addEventListener('keydown', function(e) {
var newVal;
switch (e.keyCode) {
case 13: // enter
newVal = parseFloat(this.value);
_this.setValue(newVal);
break;
case 38: // up
newVal = _this.getValue() + _this.getStep();
_this.setValue(newVal);
break;
case 40: // down
newVal = _this.getValue() - _this.getStep();
_this.setValue(newVal);
break;
}
}, false);
var mouseup = function(e) {
document.removeEventListener('mousemove', dragNumberField, false);
DAT.GUI.makeSelectable(numberField);
if (clickedNumberField && !draggedNumberField) {
//numberField.focus();
//numberField.select();
}
draggedNumberField = false;
clickedNumberField = false;
if (_this.finishChangeFunction != null) {
_this.finishChangeFunction.call(this, _this.getValue());
}
draggingHorizontal = false;
draggingVertical = false;
document.removeEventListener('mouseup', mouseup, false);
};
var dragNumberField = function(e) {
py = y;
y = e.pageY;
var dy = py - y;
if (!draggingHorizontal && !draggingVertical) {
if (dy == 0) {
draggingHorizontal = true;
} else {
draggingVertical = true;
}
}
if (draggingHorizontal) {
return true;
}
DAT.GUI.addClass(_this.domElement, 'active');
DAT.GUI.makeUnselectable(_this.parent.domElement);
DAT.GUI.makeUnselectable(numberField);
draggedNumberField = true;
e.preventDefault();
var newVal = _this.getValue() + dy * _this.getStep();
_this.setValue(newVal);
return false;
};
this.options = function() {
_this.noSlider();
_this.domElement.removeChild(numberField);
return DAT.GUI.Controller.prototype.options.apply(this, arguments);
};
this.noSlider = function() {
if (slider) {
_this.domElement.removeChild(slider.domElement);
}
return this;
};
this.setValue = function(val) {
val = parseFloat(val);
if (min != undefined && val <= min) {
val = min;
} else if (max != undefined && val >= max) {
val = max;
}
return DAT.GUI.Controller.prototype.setValue.call(this, val);
};
this.updateDisplay = function() {
numberField.value = DAT.GUI.roundToDecimal(_this.getValue(), 4);
if (slider) slider.value = _this.getValue();
};
};
DAT.GUI.extendController(DAT.GUI.ControllerNumber);

View File

@ -0,0 +1,64 @@
DAT.GUI.ControllerNumberSlider = function(numberController, min, max, step, initValue) {
var clicked = false;
var _this = this;
var x, px;
this.domElement = document.createElement('div');
this.domElement.setAttribute('class', 'guidat-slider-bg');
this.fg = document.createElement('div');
this.fg.setAttribute('class', 'guidat-slider-fg');
this.domElement.appendChild(this.fg);
var onDrag = function(e) {
if (!clicked) return;
var pos = findPos(_this.domElement);
var val = DAT.GUI.map(e.pageX, pos[0], pos[0] + _this.domElement
.offsetWidth, numberController.getMin(), numberController.getMax());
val = Math.round(val / numberController.getStep()) * numberController
.getStep();
numberController.setValue(val);
};
this.domElement.addEventListener('mousedown', function(e) {
clicked = true;
x = px = e.pageX;
DAT.GUI.addClass(numberController.domElement, 'active');
onDrag(e);
document.addEventListener('mouseup', mouseup, false);
}, false);
var mouseup = function(e) {
DAT.GUI.removeClass(numberController.domElement, 'active');
clicked = false;
if (numberController.finishChangeFunction != null) {
numberController.finishChangeFunction.call(this,
numberController.getValue());
}
document.removeEventListener('mouseup', mouseup, false);
};
var findPos = function(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while ((obj = obj.offsetParent));
return [curleft,curtop];
}
};
this.__defineSetter__('value', function(e) {
this.fg.style.width = DAT.GUI.map(e, numberController.getMin(),
numberController.getMax(), 0, 100) + "%";
});
document.addEventListener('mousemove', onDrag, false);
this.value = initValue;
};

View File

@ -0,0 +1,57 @@
DAT.GUI.ControllerString = function() {
this.type = "string";
var _this = this;
DAT.GUI.Controller.apply(this, arguments);
var input = document.createElement('input');
var initialValue = this.getValue();
input.setAttribute('value', initialValue);
input.setAttribute('spellcheck', 'false');
this.domElement.addEventListener('mouseup', function() {
input.focus();
input.select();
}, false);
// TODO: getting messed up on ctrl a
input.addEventListener('keyup', function(e) {
if (e.keyCode == 13 && _this.finishChangeFunction != null) {
_this.finishChangeFunction.call(this, _this.getValue());
input.blur();
}
_this.setValue(input.value);
}, false);
input.addEventListener('mousedown', function(e) {
DAT.GUI.makeSelectable(input);
}, false);
input.addEventListener('blur', function() {
DAT.GUI.supressHotKeys = false;
if (_this.finishChangeFunction != null) {
_this.finishChangeFunction.call(this, _this.getValue());
}
}, false);
input.addEventListener('focus', function() {
DAT.GUI.supressHotKeys = true;
}, false);
this.updateDisplay = function() {
input.value = _this.getValue();
};
this.options = function() {
_this.domElement.removeChild(input);
return DAT.GUI.Controller.prototype.options.apply(this, arguments);
};
this.domElement.appendChild(input);
};
DAT.GUI.extendController(DAT.GUI.ControllerString);

168
src/DAT/GUI/GUI.css Normal file
View File

@ -0,0 +1,168 @@
#guidat {
position: fixed;
top: 0;
right: 0;
width: auto;
z-index: 1001;
text-align: right;
}
.guidat {
color: #fff;
opacity: 0.97;
text-align: left;
float: right;
margin-right: 20px;
margin-bottom: 20px;
background-color: #fff;
}
.guidat,
.guidat input {
font: 9.5px Lucida Grande, sans-serif;
}
.guidat-controllers {
height: 300px;
overflow-y: auto;
overflow-x: hidden;
background-color: rgba(0, 0, 0, 0.1);
}
a.guidat-toggle:link,
a.guidat-toggle:visited,
a.guidat-toggle:active {
text-decoration: none;
cursor: pointer;
color: #fff;
background-color: #222;
text-align: center;
display: block;
padding: 5px;
}
a.guidat-toggle:hover {
background-color: #000;
}
.guidat-controller {
padding: 3px;
height: 25px;
clear: left;
border-bottom: 1px solid #222;
background-color: #111;
}
.guidat-controller,
.guidat-controller input,
.guidat-slider-bg,
.guidat-slider-fg {
-moz-transition: background-color 0.15s linear;
-webkit-transition: background-color 0.15s linear;
transition: background-color 0.15s linear;
}
.guidat-controller.boolean:hover,
.guidat-controller.function:hover {
background-color: #000;
}
.guidat-controller input {
float: right;
outline: none;
border: 0;
padding: 4px;
margin-top: 2px;
background-color: #222;
}
.guidat-controller select {
margin-top: 4px;
float: right;
}
.guidat-controller input:hover {
background-color: #444;
}
.guidat-controller input:focus,
.guidat-controller.active input {
background-color: #555;
color: #fff;
}
.guidat-controller.number {
border-left: 5px solid #00aeff;
}
.guidat-controller.string {
border-left: 5px solid #1ed36f;
}
.guidat-controller.string input {
border: 0;
color: #1ed36f;
margin-right: 2px;
width: 148px;
}
.guidat-controller.boolean {
border-left: 5px solid #54396e;
}
.guidat-controller.function {
border-left: 5px solid #e61d5f;
}
.guidat-controller.number input[type=text] {
width: 35px;
margin-left: 5px;
margin-right: 2px;
color: #00aeff;
}
.guidat .guidat-controller.boolean input {
margin-top: 6px;
margin-right: 2px;
font-size: 20px;
}
.guidat-controller:last-child {
border-bottom: none;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5);
box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5);
}
.guidat-propertyname {
padding: 5px;
padding-top: 7px;
cursor: default;
display: inline-block;
}
.guidat-controller .guidat-slider-bg:hover,
.guidat-controller.active .guidat-slider-bg {
background-color: #444;
}
.guidat-controller .guidat-slider-bg .guidat-slider-fg:hover,
.guidat-controller.active .guidat-slider-bg .guidat-slider-fg {
background-color: #52c8ff;
}
.guidat-slider-bg {
background-color: #222;
cursor: ew-resize;
width: 40%;
margin-top: 2px;
float: right;
height: 21px;
}
.guidat-slider-fg {
cursor: ew-resize;
background-color: #00aeff;
height: 21px;
}

740
src/DAT/GUI/GUI.js Normal file
View File

@ -0,0 +1,740 @@
var DAT = DAT || {};
DAT.GUI = function(parameters) {
if (parameters == undefined) {
parameters = {};
}
var paramsExplicitHeight = false;
if (parameters.height == undefined) {
parameters.height = 300;
} else {
paramsExplicitHeight = true;
}
var MIN_WIDTH = 240;
var MAX_WIDTH = 500;
var controllers = [];
var listening = [];
var autoListen = true;
var listenInterval;
// Sum total of heights of controllers in this gui
var controllerHeight;
var _this = this;
var open = true;
var width = 280;
if (parameters.width != undefined) {
width = parameters.width;
}
// Prevents checkForOverflow bug in which loaded gui appearance
// settings are not respected by presence of scrollbar.
var explicitOpenHeight = false;
// How big we get when we open
var openHeight;
var closeString = 'Close Controls';
var openString = 'Open Controls';
var name;
var resizeTo = 0;
var resizeTimeout;
this.domElement = document.createElement('div');
this.domElement.setAttribute('class', 'guidat');
this.domElement.style.width = width + 'px';
var curControllerContainerHeight = parameters.height;
var controllerContainer = document.createElement('div');
controllerContainer.setAttribute('class', 'guidat-controllers');
controllerContainer.style.height = curControllerContainerHeight + 'px';
// Firefox hack to prevent horizontal scrolling
controllerContainer.addEventListener('DOMMouseScroll', function(e) {
var scrollAmount = this.scrollTop;
if (e.wheelDelta) {
scrollAmount += e.wheelDelta;
} else if (e.detail) {
scrollAmount += e.detail;
}
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
controllerContainer.scrollTop = scrollAmount;
}, false);
var toggleButton = document.createElement('a');
toggleButton.setAttribute('class', 'guidat-toggle');
toggleButton.setAttribute('href', '#');
toggleButton.innerHTML = open ? closeString : openString;
var toggleDragged = false;
var dragDisplacementY = 0;
var dragDisplacementX = 0;
var togglePressed = false;
var my, pmy, mx, pmx;
var resize = function(e) {
pmy = my;
pmx = mx;
my = e.pageY;
mx = e.pageX;
var dmy = my - pmy;
if (!open) {
if (dmy > 0) {
open = true;
curControllerContainerHeight = openHeight = 1;
toggleButton.innerHTML = name || closeString;
} else {
return;
}
}
// TODO: Flip this if you want to resize to the left.
var dmx = pmx - mx;
if (dmy > 0 &&
curControllerContainerHeight > controllerHeight) {
var d = DAT.GUI.map(curControllerContainerHeight, controllerHeight,
controllerHeight + 100, 1, 0);
dmy *= d;
}
toggleDragged = true;
dragDisplacementY += dmy;
openHeight += dmy;
curControllerContainerHeight += dmy;
controllerContainer.style.height = openHeight + 'px';
dragDisplacementX += dmx;
width += dmx;
width = DAT.GUI.constrain(width, MIN_WIDTH, MAX_WIDTH);
_this.domElement.style.width = width + 'px';
checkForOverflow();
};
toggleButton.addEventListener('mousedown', function(e) {
pmy = my = e.pageY;
pmx = mx = e.pageX;
togglePressed = true;
e.preventDefault();
dragDisplacementX = 0;
dragDisplacementY = 0;
document.addEventListener('mousemove', resize, false);
return false;
}, false);
toggleButton.addEventListener('click', function(e) {
e.preventDefault();
return false;
}, false);
document.addEventListener('mouseup', function(e) {
if (togglePressed && !toggleDragged) {
_this.toggle();
}
if (togglePressed && toggleDragged) {
if (dragDisplacementX == 0) {
adaptToScrollbar();
}
if (openHeight > controllerHeight) {
clearTimeout(resizeTimeout);
openHeight = resizeTo = controllerHeight;
beginResize();
} else if (controllerContainer.children.length >= 1) {
var singleControllerHeight = controllerContainer.children[0].
offsetHeight;
clearTimeout(resizeTimeout);
var target = Math.round(curControllerContainerHeight /
singleControllerHeight) * singleControllerHeight - 1;
resizeTo = target;
if (resizeTo <= 0) {
_this.close();
openHeight = singleControllerHeight * 2;
} else {
openHeight = resizeTo;
beginResize();
}
}
}
document.removeEventListener('mousemove', resize, false);
e.preventDefault();
toggleDragged = false;
togglePressed = false;
return false;
}, false);
this.domElement.appendChild(controllerContainer);
this.domElement.appendChild(toggleButton);
if (parameters.domElement) {
parameters.domElement.appendChild(this.domElement);
} else if (DAT.GUI.autoPlace) {
if (DAT.GUI.autoPlaceContainer == null) {
DAT.GUI.autoPlaceContainer = document.createElement('div');
DAT.GUI.autoPlaceContainer.setAttribute('id', 'guidat');
document.body.appendChild(DAT.GUI.autoPlaceContainer);
}
DAT.GUI.autoPlaceContainer.appendChild(this.domElement);
}
this.autoListenIntervalTime = 1000 / 60;
var createListenInterval = function() {
listenInterval = setInterval(function() {
_this.listen();
}, this.autoListenIntervalTime);
};
this.__defineSetter__('autoListen', function(v) {
autoListen = v;
if (!autoListen) {
clearInterval(listenInterval);
} else {
if (listening.length > 0) createListenInterval();
}
});
this.__defineGetter__('autoListen', function(v) {
return autoListen;
});
this.listenTo = function(controller) {
// TODO: check for duplicates
if (listening.length == 0) {
createListenInterval();
}
listening.push(controller);
};
this.unlistenTo = function(controller) {
// TODO: test this
for (var i = 0; i < listening.length; i++) {
if (listening[i] == controller) listening.splice(i, 1);
}
if (listening.length <= 0) {
clearInterval(listenInterval);
}
};
this.listen = function(whoToListenTo) {
var arr = whoToListenTo || listening;
for (var i in arr) {
arr[i].updateDisplay();
}
};
this.listenAll = function() {
this.listen(controllers);
}
this.autoListen = true;
var alreadyControlled = function(object, propertyName) {
for (var i in controllers) {
if (controllers[i].object == object &&
controllers[i].propertyName == propertyName) {
return true;
}
}
return false;
};
var construct = function(constructor, args) {
function C() {
return constructor.apply(this, args);
}
C.prototype = constructor.prototype;
return new C();
};
this.add = function() {
if (arguments.length == 1) {
var toReturn = [];
for (var i in arguments[0]) {
toReturn.push(_this.add(arguments[0], i));
}
return toReturn;
}
var object = arguments[0];
var propertyName = arguments[1];
// Have we already added this?
if (alreadyControlled(object, propertyName)) {
// DAT.GUI.error('Controller for \'' + propertyName+'\' already added.');
// return;
}
var value = object[propertyName];
if(value == undefined && object.get) value = object.get(propertyName);
// Does this value exist? Is it accessible?
if (value == undefined) {
DAT.GUI.error(object + ' either has no property \'' + propertyName +
'\', or the property is inaccessible.');
return;
}
var type = typeof value;
var handler = handlerTypes[type];
// Do we know how to deal with this data type?
if (handler == undefined) {
DAT.GUI.error('Cannot create controller for data type \'' + type + '\'');
return;
}
var args = [this]; // Set first arg (parent) to this
for (var j = 0; j < arguments.length; j++) {
args.push(arguments[j]);
}
var controllerObject = construct(handler, args);
// Were we able to make the controller?
if (!controllerObject) {
DAT.GUI.error('Error creating controller for \'' + propertyName + '\'.');
return;
}
// Success.
controllerContainer.appendChild(controllerObject.domElement);
controllers.push(controllerObject);
DAT.GUI.allControllers.push(controllerObject);
// Do we have a saved value for this controller?
if (type != 'function' &&
DAT.GUI.saveIndex < DAT.GUI.savedValues.length) {
controllerObject.setValue(DAT.GUI.savedValues[DAT.GUI.saveIndex]);
DAT.GUI.saveIndex++;
}
// Compute sum height of controllers.
checkForOverflow();
// Prevents checkForOverflow bug in which loaded gui appearance
// settings are not respected by presence of scrollbar.
if (!explicitOpenHeight) {
openHeight = controllerHeight;
}
// Let's see if we're doing this on onload and lets *try* to guess how
// big you want the damned box.
if (!paramsExplicitHeight) {
try {
// Probably a better way to do this
var caller = arguments.callee.caller;
if (caller == window['onload']) {
curControllerContainerHeight = resizeTo = openHeight =
controllerHeight;
controllerContainer.style.height = curControllerContainerHeight + 'px';
}
} catch (e) {}
}
return controllerObject;
}
var checkForOverflow = function() {
controllerHeight = 0;
for (var i in controllers) {
controllerHeight += controllers[i].domElement.offsetHeight;
}
if (controllerHeight - 1 > openHeight) {
controllerContainer.style.overflowY = 'auto';
} else {
controllerContainer.style.overflowY = 'hidden';
}
};
var handlerTypes = {
'number': DAT.GUI.ControllerNumber,
'string': DAT.GUI.ControllerString,
'boolean': DAT.GUI.ControllerBoolean,
'function': DAT.GUI.ControllerFunction
};
this.reset = function() {
// TODO ... Set all values back to their initials.
for (var i = 0, l = DAT.GUI.allControllers.length; i < l; i++) {
// apply to each controller
DAT.GUI.allControllers[i].reset();
}
}
this.toggle = function() {
open ? this.close() : this.open();
};
this.open = function() {
toggleButton.innerHTML = name || closeString;
resizeTo = openHeight;
clearTimeout(resizeTimeout);
beginResize();
adaptToScrollbar();
open = true;
}
this.close = function() {
toggleButton.innerHTML = name || openString;
resizeTo = 0;
clearTimeout(resizeTimeout);
beginResize();
adaptToScrollbar();
open = false;
}
this.name = function(n) {
name = n;
toggleButton.innerHTML = n;
}
// used in saveURL
this.appearanceVars = function() {
return [open, width, openHeight, controllerContainer.scrollTop]
}
var beginResize = function() {
curControllerContainerHeight = controllerContainer.offsetHeight;
curControllerContainerHeight += (resizeTo - curControllerContainerHeight)
* 0.6;
if (Math.abs(curControllerContainerHeight - resizeTo) < 1) {
curControllerContainerHeight = resizeTo;
} else {
resizeTimeout = setTimeout(beginResize, 1000 / 30);
}
controllerContainer.style.height = Math.round(curControllerContainerHeight)
+ 'px';
checkForOverflow();
}
var adaptToScrollbar = function() {
// Clears lingering scrollbar column
_this.domElement.style.width = (width - 1) + 'px';
setTimeout(function() {
_this.domElement.style.width = width + 'px';
}, 1);
};
// Load saved appearance:
if (DAT.GUI.guiIndex < DAT.GUI.savedAppearanceVars.length) {
width = parseInt(DAT.GUI.savedAppearanceVars[DAT.GUI.guiIndex][1]);
_this.domElement.style.width = width + 'px';
openHeight = parseInt(DAT.GUI.savedAppearanceVars[DAT.GUI.guiIndex][2]);
explicitOpenHeight = true;
if (eval(DAT.GUI.savedAppearanceVars[DAT.GUI.guiIndex][0]) == true) {
curControllerContainerHeight = openHeight;
var t = DAT.GUI.savedAppearanceVars[DAT.GUI.guiIndex][3]
// Hack.
setTimeout(function() {
controllerContainer.scrollTop = t;
}, 0);
if (DAT.GUI.scrollTop > -1) {
document.body.scrollTop = DAT.GUI.scrollTop;
}
resizeTo = openHeight;
this.open();
}
DAT.GUI.guiIndex++;
}
DAT.GUI.allGuis.push(this);
// Add hide listener if this is the first DAT.GUI.
if (DAT.GUI.allGuis.length == 1) {
window.addEventListener('keyup', function(e) {
// Hide on 'H'
if (!DAT.GUI.supressHotKeys && e.keyCode == 72) {
DAT.GUI.toggleHide();
}
}, false);
if (DAT.GUI.inlineCSS) {
var styleSheet = document.createElement('style');
styleSheet.setAttribute('type', 'text/css');
styleSheet.innerHTML = DAT.GUI.inlineCSS;
document.head.insertBefore(styleSheet, document.head.firstChild);
}
}
};
// Do not set this directly.
DAT.GUI.hidden = false;
// Static members
DAT.GUI.autoPlace = true;
DAT.GUI.autoPlaceContainer = null;
DAT.GUI.allControllers = [];
DAT.GUI.allGuis = [];
DAT.GUI.supressHotKeys = false;
DAT.GUI.toggleHide = function() {
if (DAT.GUI.hidden) {
DAT.GUI.open();
} else {
DAT.GUI.close();
}
}
DAT.GUI.open = function() {
DAT.GUI.hidden = false;
for (var i in DAT.GUI.allGuis) {
DAT.GUI.allGuis[i].domElement.style.display = 'block';
}
}
DAT.GUI.close = function() {
DAT.GUI.hidden = true;
for (var i in DAT.GUI.allGuis) {
DAT.GUI.allGuis[i].domElement.style.display = 'none';
}
}
DAT.GUI.saveURL = function() {
var url = DAT.GUI.replaceGetVar('saveString', DAT.GUI.getSaveString());
window.location = url;
};
DAT.GUI.scrollTop = -1;
DAT.GUI.load = function(saveString) {
//DAT.GUI.savedAppearanceVars = [];
var vals = saveString.split(',');
var numGuis = parseInt(vals[0]);
DAT.GUI.scrollTop = parseInt(vals[1]);
for (var i = 0; i < numGuis; i++) {
var appr = vals.splice(2, 4);
DAT.GUI.savedAppearanceVars.push(appr);
}
DAT.GUI.savedValues = vals.splice(2, vals.length);
};
DAT.GUI.savedValues = [];
DAT.GUI.savedAppearanceVars = [];
DAT.GUI.getSaveString = function() {
var vals = [], i;
vals.push(DAT.GUI.allGuis.length);
vals.push(document.body.scrollTop);
for (i in DAT.GUI.allGuis) {
var av = DAT.GUI.allGuis[i].appearanceVars();
for (var j = 0; j < av.length; j++) {
vals.push(av[j]);
}
}
for (i in DAT.GUI.allControllers) {
// We don't save values for functions.
if (DAT.GUI.allControllers[i].type == 'function') {
continue;
}
var v = DAT.GUI.allControllers[i].getValue();
// Round numbers so they don't get enormous
if (DAT.GUI.allControllers[i].type == 'number') {
v = DAT.GUI.roundToDecimal(v, 4);
}
vals.push(v);
}
return vals.join(',');
};
DAT.GUI.getVarFromURL = function(v) {
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash == undefined) continue;
if (hash[0] == v) {
return hash[1];
}
}
return null;
};
DAT.GUI.replaceGetVar = function(varName, val) {
var vars = [], hash;
var loc = window.location.href;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash == undefined) continue;
if (hash[0] == varName) {
return loc.replace(hash[1], val);
}
}
if (window.location.href.indexOf('?') != -1) {
return loc + '&' + varName + '=' + val;
}
return loc + '?' + varName + '=' + val;
};
DAT.GUI.saveIndex = 0;
DAT.GUI.guiIndex = 0;
DAT.GUI.showSaveString = function() {
alert(DAT.GUI.getSaveString());
};
// Util functions
DAT.GUI.makeUnselectable = function(elem) {
if (elem == undefined || elem.style == undefined) return;
elem.onselectstart = function() {
return false;
};
elem.style.MozUserSelect = 'none';
elem.style.KhtmlUserSelect = 'none';
elem.unselectable = 'on';
var kids = elem.childNodes;
for (var i = 0; i < kids.length; i++) {
DAT.GUI.makeUnselectable(kids[i]);
}
};
DAT.GUI.makeSelectable = function(elem) {
if (elem == undefined || elem.style == undefined) return;
elem.onselectstart = function() {
};
elem.style.MozUserSelect = 'auto';
elem.style.KhtmlUserSelect = 'auto';
elem.unselectable = 'off';
var kids = elem.childNodes;
for (var i = 0; i < kids.length; i++) {
DAT.GUI.makeSelectable(kids[i]);
}
};
DAT.GUI.map = function(v, i1, i2, o1, o2) {
return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
};
DAT.GUI.constrain = function (v, o1, o2) {
if (v < o1) v = o1;
else if (v > o2) v = o2;
return v;
};
DAT.GUI.error = function(str) {
if (typeof console.error == 'function') {
console.error('[DAT.GUI ERROR] ' + str);
}
};
DAT.GUI.roundToDecimal = function(n, decimals) {
var t = Math.pow(10, decimals);
return Math.round(n * t) / t;
};
DAT.GUI.extendController = function(clazz) {
clazz.prototype = new DAT.GUI.Controller();
clazz.prototype.constructor = clazz;
};
DAT.GUI.addClass = function(domElement, className) {
if (DAT.GUI.hasClass(domElement, className)) return;
domElement.className += ' ' + className;
}
DAT.GUI.hasClass = function(domElement, className) {
return domElement.className.indexOf(className) != -1;
}
DAT.GUI.removeClass = function(domElement, className) {
var reg = new RegExp(' ' + className, 'g');
domElement.className = domElement.className.replace(reg, '');
}
if (DAT.GUI.getVarFromURL('saveString') != null) {
DAT.GUI.load(DAT.GUI.getVarFromURL('saveString'));
}

File diff suppressed because it is too large Load Diff

186
utils/build.py Normal file
View File

@ -0,0 +1,186 @@
#/usr/bin/env python
from optparse import OptionParser
import httplib, urllib
import os, fnmatch, shutil, re
usage = """usage: %prog [options] command
Commands:
build build the script
debug print the header to include js files
clean remove any built files
"""
parser = OptionParser(usage=usage)
parser.add_option('-l', '--level', dest='level', default='SIMPLE_OPTIMIZATIONS',
help='Closure compilation level [WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, \
ADVANCED_OPTIMIZATIONS]')
UTILS = os.path.dirname(os.path.relpath(__file__))
PREFIX = os.path.join(UTILS,'..')
SRC_ROOT= os.path.join(PREFIX,'src')
BUILD_ROOT = os.path.join(PREFIX,'build')
INDEX = os.path.join(PREFIX,'index.html')
BUILD_NAME = 'DAT.GUI'
ALL_JS = ['DAT.GUI.js','DAT.GUI']
LICENSE = """/**
* dat.gui Javascript Controller Library
* http://dataarts.github.com/dat.gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
"""
def flatten(l, ltypes=(list, tuple)):
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)
def expand(path, globby):
matches = []
path = path.split('.')
path.insert(0,SRC_ROOT)
filename = "%s.%s"%(path[-2],path[-1])
if fnmatch.fnmatch(filename, globby):
tmppath = os.path.join(*(path[:-1]+[filename]))
if os.path.exists(tmppath):
path[-1] = filename
else:
path = path[:-2]+[filename]
path = os.path.join(*path)
if os.path.isdir(path):
for root, dirnames, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, globby):
matches.append(os.path.join(root, filename))
else:
matches.append(path)
return matches
def unique(seq, idfun=None):
"""Ordered uniquify function
if in 2.7 use:
OrderedDict.fromkeys(seq).keys()
"""
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
def source_list(src, globby='*.js'):
def expander(f):
return expand(f,globby)
return unique(flatten(map(expander, src)))
def compile(code):
params = urllib.urlencode([
('js_code', code),
('compilation_level', options.level),
('output_format', 'text'),
('output_info', 'compiled_code'),
])
headers = { 'Content-type': 'application/x-www-form-urlencoded' }
conn = httplib.HTTPConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)
response = conn.getresponse()
data = response.read()
conn.close()
return data
def bytes_to_kb(b,digits=1):
return round(0.0009765625 * b, digits)
def clean():
if os.path.exists(BUILD_ROOT):
shutil.rmtree(BUILD_ROOT)
print('DONE. Removed %s'%(BUILD_ROOT,))
else:
print('DONE. Nothing to clean')
def build(jssrc, csssrc=list([''])):
if not os.path.exists(BUILD_ROOT):
os.makedirs(BUILD_ROOT)
if csssrc:
cssfiles = source_list(csssrc, '*.css')
print('CSS files being compiled: ', cssfiles)
css = '\n'.join([open(f).read() for f in cssfiles])
css = re.sub(r'[ \t\n\r]+',' ',css)
jsfiles = source_list(jssrc, '*.js')
print('JS files being compiled: ', jsfiles)
code = '\n'.join([open(f).read() for f in jsfiles])
if csssrc:
code += """DAT.GUI.inlineCSS = '%s';\n"""%(css,)
outpath = os.path.join(BUILD_ROOT, BUILD_NAME+'.js')
with open(outpath,'w') as f:
f.write(LICENSE)
f.write(code)
compiled = compile(code)
outpathmin = os.path.join(BUILD_ROOT, BUILD_NAME+'.min.js')
with open(outpathmin,'w') as f:
f.write(LICENSE)
f.write(compiled)
size = bytes_to_kb(os.path.getsize(outpath))
sizemin = bytes_to_kb(os.path.getsize(outpathmin))
with open(INDEX,'r') as f:
index = f.read()
with open(INDEX,'w') as f:
index = re.sub(r'<small id=\'buildsize\'>\[[0-9.]+kb\]','<small id=\'buildsize\'>[%skb]'%(size,),index)
index = re.sub(r'<small id=\'buildsizemin\'>\[[0-9.]+kb\]','<small id=\'buildsizemin\'>[%skb]'%(sizemin,),index)
f.write(index)
print('DONE. Built files in %s.'%(BUILD_ROOT,))
def debug(jssrc, csssrc=list([''])):
head = ""
files = source_list(csssrc, '*.css')
for f in files:
f = f.replace(PREFIX+'/','')
head += '<link href="%s" media="screen" rel="stylesheet" type="text/css"/>\n'%(f,)
files = source_list(jssrc, '*.js')
for f in files:
f = f.replace(PREFIX+'/','')
head += '<script type="text/javascript" src="%s"></script>\n'%(f,)
print(head)
if __name__ == '__main__':
global options
(options, args) = parser.parse_args()
if len(args) != 1:
print(parser.usage)
exit(0)
command = args[0]
if command == 'build':
build(ALL_JS)
elif command == 'clean':
clean()
elif command == 'debug':
debug(ALL_JS)