code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREEFAB.CanvasTexture = function () {
THREE.Texture.call( this );
var canvas = document.createElement( 'canvas' );
canvas.width = 512;
canvas.height = 512;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255,255,255,1)";
ctx.fillRect(0, 0, 512, 512);
this.image = canvas;
this.needsUpdate = true;
}
THREEFAB.CanvasTexture.prototype = new THREE.Texture();
THREEFAB.CanvasTexture.prototype.constructor = THREEFAB.CanvasTexture; | JavaScript |
/**
* @author mikael emtinger / http://gomo.se/
*/
THREEFAB.AnimationMorphTarget = function( root, scale ) {
this.root = root;
this.currentTime = 0;
this.timeScale = scale !== undefined ? scale : 1000;
this.isPlaying = false;
this.isPaused = true;
this.loop = true;
this.influence = 1;
this.keyframes = 0;
this.interpolation = 0;
this.lastKeyframe = 0;
this.currentKeyframe = 0;
};
/*
* Play
*/
THREEFAB.AnimationMorphTarget.prototype.play = function( loop, startTimeMS ) {
if( !this.isPlaying ) {
this.isPlaying = true;
this.loop = loop !== undefined ? loop : true;
this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
// setup interpolation
this.keyframes = this.root.morphTargetInfluences.length - 1;
this.interpolation = this.timeScale / this.keyframes;
this.render();
}
this.isPaused = false;
//THREE.AnimationHandler.addToUpdate( this );
};
/*
* Pause
*/
THREEFAB.AnimationMorphTarget.prototype.pause = function() {
/*if( this.isPaused ) {
THREE.AnimationHandler.addToUpdate( this );
} else {
THREE.AnimationHandler.removeFromUpdate( this );
}*/
this.isPaused = !this.isPaused;
};
/*
* Stop
*/
THREEFAB.AnimationMorphTarget.prototype.stop = function() {
this.isPlaying = false;
this.isPaused = false;
//THREE.AnimationHandler.removeFromUpdate( this );
// reset JIT matrix and remove cache
this.lastKeyframe = 0;
this.currentKeyframe = 0;
this.timeScale = 1000;
};
/*
* Update
*/
THREEFAB.AnimationMorphTarget.prototype.render = function() {
var mesh = this.root,
time = Date.now() % this.timeScale,
keyframe = Math.floor( time / this.interpolation ) + 1;
if ( keyframe != this.currentKeyframe ) {
mesh.morphTargetInfluences[ this.lastKeyframe ] = 0;
mesh.morphTargetInfluences[ this.currentKeyframe ] = 1;
mesh.morphTargetInfluences[ keyframe ] = 0;
this.lastKeyframe = this.currentKeyframe;
this.currentKeyframe = keyframe;
}
mesh.morphTargetInfluences[ keyframe ] = ( time % this.interpolation ) / this.interpolation;
mesh.morphTargetInfluences[ this.lastKeyframe ] = 1 - mesh.morphTargetInfluences[ keyframe ];
return keyframe;
};
THREEFAB.AnimationMorphTarget.prototype.clear = function() {
var mesh = this.root;
for(var i=0; i < this.keyframes+1; i++) {
mesh.morphTargetInfluences[ i ] = 0;
}
};
/*
* Goto Frame
*/
THREEFAB.AnimationMorphTarget.prototype.gotoFrame = function( keyframe ) {
var mesh = this.root;
mesh.morphTargetInfluences[ this.currentKeyframe ] = 0;
mesh.morphTargetInfluences[ keyframe ] = 1;
this.lastKeyframe = this.currentKeyframe;
this.currentKeyframe = keyframe;
};
THREEFAB.AnimationMorphTarget.prototype.updateTimeScale = function( value ) {
this.timeScale = value;
};
| JavaScript |
/**
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREEFAB.DragDropLoader = function() {
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
window.URL = window.URL || window.webkitURL || window.mozURL;
// Need to prevent these events since the Drag and Drop API is weird.
document.addEventListener('dragover', function (event) { event.preventDefault(); }, false );
document.addEventListener('dragleave', function (event ) { event.preventDefault(); }, false );
document.addEventListener('drop', function (event) {
event.stopPropagation();
event.preventDefault();
var file = event.dataTransfer.files[ 0 ];
if(file === undefined) { return false; }
var extension = file.name.split( '.' )[1].toLowerCase();
var reader = new FileReader();
var isImage = false;
if(extension === "jpg" || extension === "png") {
isImage = true;
}
reader.onload = function ( event ) {
var contents = event.target.result,
loader, mesh, json;
if(extension === "js") {
// We dropping in a mesh.
json = JSON.parse(contents);
loader = new THREE.JSONLoader();
loader.createModel( json, function ( geometry ) {
// This is a valid model.
var material;
// Make sure this model has UV coordinates.
if(json.uvs[0].length > 0) {
material = new THREE.MeshPhongMaterial( { color: 0xffffff, wireframe: false, map: new THREEFAB.CanvasTexture() } );
} else {
material = new THREE.MeshPhongMaterial();
}
material.name = 'MeshPhongMaterial';
// Check for morphing targets and add to material.
if(geometry.morphTargets.length > 0) {
material.morphTargets = true;
}
if(geometry.skinWeights.length > 0) {
// Check for skinned mesh
mesh = new THREE.SkinnedMesh( geometry, material );
mesh.name = "THREE.SkinnedMesh." + mesh.id;
} else {
// Regular mesh.
mesh = new THREE.Mesh( geometry, material );
mesh.name = "THREE.JSONLoader." + mesh.id;
}
if(json.scale) {
mesh.scale.x = mesh.scale.y = mesh.scale.z = json.scale;
}
$.publish(THREEFAB.Events.MODEL_LOADED, mesh);
});
} else if(isImage) {
// We are dropping in a texture.
var img = new Image();
img.src = contents;
var texture = new THREE.Texture(img);
texture.needsUpdate = true;
img.onload = function() {
$.publish(THREEFAB.Events.TEXTURE_LOADED, texture);
};
}
};
if(extension === 'js') {
// JSON model file.
reader.readAsText( file );
} else if(isImage) {
// Read image textures as a data url.
reader.readAsDataURL(file);
}
});
};
| JavaScript |
/**
* @class THREEFAB.ExporterUtil
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Sets up exporter for threefab.
*
*/
THREEFAB.Exporter = function() {
var code_container = $('.code-container');
this.generate = function(viewport) {
var html = THREEFAB.Exporter.Utils.privates();
html += THREEFAB.Exporter.Utils.container();
html += THREEFAB.Exporter.Utils.camera(viewport.camera);
html += THREEFAB.Exporter.Utils.scene();
html += THREEFAB.Exporter.Utils.renderer();
html += THREEFAB.Exporter.Utils.sceneObjects(viewport.scene);
html += THREEFAB.Exporter.Utils.animate();
code_container.find('pre').html( html );
code_container.show();
};
};
THREEFAB.Exporter.Templates = {
material: '#material'
};
THREEFAB.Exporter.Utils = {
privates: function() {
return "var container = document.createElement( 'div' ),\nwidth = " + window.innerWidth + ",\nheight = " + window.innerHeight + ",\ncamera,\nscene,\nrenderer,\nSHADOW_MAP_WIDTH = 2048,\nSHADOW_MAP_HEIGHT = 1024;\n\n";
},
container: function() {
return "container = document.body.appendChild( container );\n\n";
},
addConatiner: function() {
return "container.appendChild( this.renderer.domElement )";
},
camera: function (cam) {
var str = ["camera = new THREE.PerspectiveCamera( 50, 1, 1, 5000 );"];
str.push('camera.position.set(' + cam.position.x + ',' + cam.position.y + ',' + cam.position.z + ');');
str.push('camera.rotation.set(' + cam.rotation.x + ',' + cam.rotation.y + ',' + cam.rotation.z + ');');
str.push('camera.aspect = width / height;');
str.push('camera.updateProjectionMatrix();');
return str.join('\n');
},
scene: function() {
return '\n\nscene = new THREE.Scene();';
},
renderer: function() {
var str = ["\n\nrenderer = new THREE.WebGLRenderer( { clearAlpha: 1, clearColor: 0x808080 } );"];
str.push('renderer.setSize( width, height );');
str.push('renderer.shadowCameraNear = 3;');
str.push('renderer.shadowCameraFar = this.camera.far;');
str.push('renderer.shadowCameraFov = 50;');
str.push('renderer.shadowMapBias = 0.0039;');
str.push('renderer.shadowMapDarkness = 0.5;');
str.push('renderer.shadowMapWidth = SHADOW_MAP_WIDTH;');
str.push('renderer.shadowMapHeight = SHADOW_MAP_HEIGHT;');
str.push('renderer.shadowMapEnabled = true;');
str.push('renderer.shadowMapSoft = true;');
str.push('container.appendChild( renderer.domElement );\n\n');
return str.join('\n');
},
sceneObjects: function(scene) {
var children = scene.children,
name_split,
str = [],
materialModel = new THREEFAB.MaterialModel(),
loaderUsed = false;
for(var i=0, len = children.length; i < len; i++) {
if(children[i].name) {
if( children[i].name === 'THREE.PointLight' || children[i].name === 'THREE.AmbientLight' || children[i].name === 'THREE.SpotLight' ) {
// Light
str.push( THREEFAB.Exporter.Utils.light(children[i], materialModel.lightList) );
THREEFAB.Exporter.Utils.transforms(children[i], str);
// Add light
str.push('scene.add( mesh );');
} else if( !children[i].light ) {
// Mesh
name_split = children[i].name.split('.');
var namespace = name_split[0],
meshtype = name_split[1],
id = name_split[2];
// Check for primitive geometry
if(meshtype === "CubeGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.cube(children[i]) );
} else if(meshtype === "SphereGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.sphere(children[i]) );
} else if(meshtype === "CylinderGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.cylinder(children[i]) );
} else if(meshtype === "ConeGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.cone(children[i]) );
} else if(meshtype === "PlaneGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.plane(children[i]) );
} else if(meshtype === "TorusGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.torus(children[i]) );
} else if(meshtype === "JSONLoader" || "SkinnedMesh") {
if(!loaderUsed) {
str.push('\nvar loader = new THREE.JSONLoader();');
}
str.push('loader.load( "path/to/model.js", function(geometry) {');
}
// Material
str.push( THREEFAB.Exporter.Utils.material(children[i].material, materialModel.materialList) );
if(children[i].geometry.morphTargets.length > 0) {
str.push('material.morphTargets = true;');
}
// Mesh
if(meshtype === "SkinnedMesh") {
str.push('var mesh = new THREE.SkinnedMesh(geometry, material);');
}
else {
str.push('var mesh = new THREE.Mesh(geometry, material);');
}
THREEFAB.Exporter.Utils.transforms(children[i], str);
// Add child
str.push('scene.add( mesh );');
if(meshtype === "JSONLoader" || "SkinnedMesh") {
str.push('});');
}
}
}
}
return str.join('\n');
},
light: function(light, lightList) {
var type = light.name.replace('THREE.',''),
lght = new THREE[type](),
html = '\nvar mesh = new ' + light.name + '();\n';
for(var i = 0, len = lightList.length; i < len; i++) {
if(lght[lightList[i]] !== lightList[i].prop) {
html += 'mesh.' + lightList[i].prop + ' = ' + light[lightList[i].prop] + ';\n';
}
}
// Add light color
html+= 'mesh.color = new THREE.Color().setRGB(' + light.color.r + ',' + light.color.g + ',' + light.color.b + ');';
return html;
},
material: function(material, materialList) {
var mat = new THREE[material.name](),
html = 'var material = new THREE.' + material.name + '();\n';
for(var i = 0, len = materialList.length; i < len; i++) {
// Make sure material has at least changed from the default.
if(material[materialList[i].prop] !== undefined && material[materialList[i].prop] !== mat[materialList[i].prop]) {
html+= 'material.' + materialList[i].prop + ' = ' + material[materialList[i].prop] + ';\n';
}
}
// Colors
// Do colors manually since they are currently not in the material list.
var color_props = ['color', 'ambient', 'specular'];
for(var j = 0, clen = color_props.length; j < clen; j++) {
if(mat[color_props[j]] !== material[color_props[j]]) {
html+= 'material.' + color_props[j] + ' = new THREE.Color().setRGB(' + material[color_props[j]].r+','+material[color_props[j]].g+','+material[color_props[j]].b+');\n';
}
}
if(material.map instanceof THREEFAB.CanvasTexture) {} else {
html += 'material.map = THREE.ImageUtils.loadTexture("path/to/texture.jpg");\n';
}
return html;
},
geometries: {
cube: function(mesh) {
return 'var geometry = new THREE.CubeGeometry( 100,100,100,1,1,1 );';
},
sphere: function(mesh) {
return 'var geometry = new THREE.SphereGeometry(100,16,16);';
},
cylinder: function(mesh) {
return 'var geometry = new THREE.CylinderGeometry(50, 50, 100, 16);';
},
cone: function(mesh) {
return 'var geometry = new THREE.CylinderGeometry( 0, 50, 100, 16, 1 );';
},
plane: function(mesh) {
return 'var geometry = new THREE.PlaneGeometry( 200, 200, 3, 3 );';
},
torus: function(mesh) {
return 'var geometry = new THREE.TorusGeometry();';
}
},
transforms: function(child, str) {
var pos = { x:0, y:0, z:0 },
rot = { x:0, y:0, z:0 },
scale = { x:1, y:1, z:1 };
if ( child.position.x !== 0 ) pos.x = child.position.x;
if ( child.position.y !== 0 ) pos.y = child.position.y;
if ( child.position.z !== 0 ) pos.z = child.position.z;
if ( child.rotation.x !== 0 ) rot.x = child.rotation.x;
if ( child.rotation.y !== 0 ) rot.y = child.rotation.y;
if ( child.rotation.z !== 0 ) rot.z = child.rotation.z;
if ( child.scale.x != 1 ) scale.x = child.scale.x;
if ( child.scale.y != 1 ) scale.y = child.scale.y;
if ( child.scale.z != 1 ) scale.z = child.scale.z;
str.push('mesh.position.set(' + pos.x + ',' + pos.y + ',' + pos.z + ');');
str.push('mesh.rotation.set(' + rot.x + ',' + rot.y + ',' + rot.z + ');');
str.push('mesh.scale.set(' + scale.x + ',' + scale.y + ',' + scale.z + ');');
},
animate: function() {
var html = '\n\nfunction animate() {\n';
html += '\trequestAnimationFrame( animate );\n';
html += '\trenderer.render( scene, camera );\n';
html += '}\n\n';
html += 'animate();';
return html;
}
};
| JavaScript |
/**
* @class THREEFAB.Ui
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Sets up ui components for threefab. Dependency on dat.gui.
* @param [THREEFAB.Viewport] viewport The instance of the viewport class.
*
*/
THREEFAB.Ui = function(viewport) {
var _viewport = viewport,
materialModel = new THREEFAB.MaterialModel();
this.materialView = new THREEFAB.MaterialView({ model: materialModel, selected: viewport._SELECTED });
this.transformView = new THREEFAB.TransformView({ viewport: viewport });
this.timelineView = new THREEFAB.TimelineView();
this.materialView.render();
this.transformView.render();
this.timelineView.render();
this.menu = $('.menu');
this.menu.bind('click', menuClicked);
function menuClicked(e) {
var target = e.target || e.srcElement,
id = target.id;
if(id === 'menu-animate') {
$.publish(THREEFAB.Events.SPACEBAR_PRESSED);
} else if(id === 'menu-delete') {
$.publish(THREEFAB.Events.DELETE_PRESSED);
}
}
};
/**
* Utils object that has shared functions.
* @private utils
*/
THREEFAB.Ui.utils = {
addProperties: function(object, list, folder, view) {
for(var i=0, len=list.length; i < len; i++) {
// Make sure the property is defined.
if(object[list[i].prop] !== undefined) {
var args = [object, list[i].prop],
tmp_controller;
if(list[i].min !== undefined) {
args.push(list[i].min);
}
if(list[i].max !== undefined) {
args.push(list[i].max);
}
if(list[i].values !== undefined) {
args.push(list[i].values);
}
tmp_controller = folder.add.apply(folder, args);
if(list[i].step !== undefined) {
tmp_controller.step(list[i].step);
}
}
}
},
removeFolderControllers: function(folder) {
for (var i in folder.__controllers) {
folder.__controllers[i].remove();
}
folder.__controllers = [];
}
};
| JavaScript |
/* =============================================================================
Author: Jason Kadrmas
Company: KadrmasConceps LLC
========================================================================== */
var THREEFAB = THREEFAB || {};
| JavaScript |
THREEFAB.Toolbox = Backbone.View.extend({
initialize:function() {
$('.toolbox-list').bind('click', function(event) {
event.preventDefault();
var target = event.target || event.srcElement,
className;
if(target.tagName.toLowerCase() === "a") {
className = target.className;
$.publish(THREEFAB.Events.PRIMITIVE_ADDED, target.className);
}
});
$('.light-list').bind('click', function(event) {
event.preventDefault();
var target = event.target || event.srcElement,
className;
if(target.tagName.toLowerCase() === "a") {
className = target.className;
$.publish(THREEFAB.Events.LIGHT_ADDED, target.className);
}
});
$('.export').bind('click', function(event) {
$.publish(THREEFAB.Events.EXPORTER_GENERATE);
});
}
});
| JavaScript |
/**
* @class THREEFAB.TextureView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup texture view.
*
*/
THREEFAB.TextureView = Backbone.View.extend({
el: document.createElement('li'),
texture: document.createElement('img'),
label: document.createElement('span'),
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.css({height:40, paddingTop:'5px'});
this.texture.width = this.texture.height = 30;
this.texture = $(this.texture);
this.texture.addClass('texture-container');
this.label = $(this.label);
this.label.html('X');
this.label.addClass('button fr hidden');
this.label.bind('click', this.clear);
this.el.append(this.texture);
this.el.append(this.label);
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.render);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.render);
$.subscribe(THREEFAB.Events.VIEWPORT_OBJECT_TEXTURE_ADDED, this.render);
},
render: function(object) {
var texture;
if(object.material.map) {
texture = object.material.map;
if(object.material.map.image instanceof HTMLImageElement ) {
this.texture.attr('src', object.material.map.image.src);
this.label.removeClass('hidden');
} else {
this.reset();
}
this.el.show();
} else {
this.el.hide();
this.reset();
}
},
clear: function() {
this.reset();
$.publish(THREEFAB.Events.TEXTURE_CLEAR);
},
reset: function() {
this.texture.attr('src', 'img/blank_texture.jpg');
this.label.addClass('hidden');
}
}); | JavaScript |
/**
*
* @class THREEFAB.MaterialView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup for material view.
*
*/
THREEFAB.MaterialView = Backbone.View.extend({
el: '#gui-materials-container',
gui: {},
selected: {},
texture: {},
color: {},
light: {},
folders: {
materials:{},
lights:{},
textures:{}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.selected = arguments[0].selected;
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.meshChanged);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.lightChanged);
$.subscribe(THREEFAB.Events.MATERIAL_COLOR_CHANGED, this.changeColor);
$.subscribe(THREEFAB.Events.LIGHT_COLOR_CHANGED, this.changeLightColor);
},
render: function() {
// Create materials GUI
this.gui = new dat.GUI({ autoPlace: false, hide:false });
this.el.append(this.gui.domElement);
// Add Folders
this.folders.materials = this.gui.addFolder('Material');
this.folders.textures = this.gui.addFolder('Texture');
this.folders.lights = this.gui.addFolder('Light');
this.folders.materials.open();
this.folders.textures.open();
// Material Color Chips
this.color = new THREEFAB.ColorView();
this.folders.materials.__ul.appendChild(this.color.el[0]);
this.addMaterialOptions();
// Texture Panel
this.texture = new THREEFAB.TextureView();
this.folders.textures.__ul.appendChild(this.texture.el[0]);
this.texture.render(this.selected);
// Light view
this.light = new THREEFAB.LightView();
this.folders.lights.__ul.appendChild(this.light.el[0]);
this.light.el.hide();
},
meshChanged: function(object) {
this.selected = object;
this.folders.lights.close();
this.resetControllers();
this.addMaterialOptions();
this.folders.materials.open();
this.folders.textures.open();
this.color.el.show();
this.texture.el.show();
this.light.el.hide();
//this.rebuildMaterial();
},
lightChanged: function(object) {
this.selected = object;
this.light.el.show();
this.folders.materials.close();
this.color.el.hide();
this.folders.textures.close();
this.texture.el.hide();
this.resetControllers();
THREEFAB.Ui.utils.addProperties( object.light, this.model.lightList, this.folders.lights );
this.folders.lights.open();
},
resetControllers: function() {
THREEFAB.Ui.utils.removeFolderControllers( this.folders.lights );
THREEFAB.Ui.utils.removeFolderControllers( this.folders.materials );
},
addMaterialOptions: function() {
// Add Material shader options.
this.folders.materials.add(this.selected.material, 'name', {Basic: 'MeshBasicMaterial', Phong:'MeshPhongMaterial', Lambert: 'MeshLambertMaterial'}).onChange( this.rebuildMaterial );
// Loop and add material properties.
THREEFAB.Ui.utils.addProperties(this.selected.material, this.model.materialList, this.folders.materials, this);
},
changeColor: function(c, type) {
this.selected.material[type] = new THREE.Color().setRGB(c.r/255, c.g/255, c.b/255);
if(type === 'ambient' || type === 'specular') {
this.rebuildMaterial();
}
},
changeLightColor: function(c) {
this.selected.light.color = new THREE.Color().setRGB(c.r/255, c.g/255, c.b/255);
},
rebuildMaterial: function(matName){
var mat;
if(matName === undefined) {
matName = this.selected.material.name;
}
// We can make a generic function constructor based on the material name.
mat = new THREE[matName]();
mat.name = matName;
this.copyMaterialAttributes(mat);
this.selected.material.program = false;
this.selected.material = mat;
},
copyMaterialAttributes: function(mat) {
for(var i = 0, len = this.model.materialList.length; i < len; i++) {
if(this.selected.material[this.model.materialList[i].prop] !== undefined) {
mat[this.model.materialList[i].prop] = this.selected.material[this.model.materialList[i].prop];
}
}
// Copy the map and color manually.
mat.map = this.selected.material.map;
mat.color = this.selected.material.color;
mat.ambient = this.selected.material.ambient;
mat.specular = this.selected.material.specular;
}
}); | JavaScript |
/**
* @class THREEFAB.OutlinerView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup outliner view.
*
*/
THREEFAB.OutlinerView = Backbone.View.extend({
el: document.createElement('li'),
select: document.createElement('select'),
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.select = $(this.select);
this.el.append(this.select);
this.select.bind('change', this.change);
$.subscribe( THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.render );
$.subscribe( THREEFAB.Events.VIEWPORT_OBJECT_REMOVED, this.render );
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.updateSelected);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.updateSelected);
},
render: function(scene) {
this.select.empty();
this.addOptions( scene.children );
},
change: function() {
$.publish( THREEFAB.Events.OUTLINER_CHANGED, this.select.val() );
},
updateSelected: function(object) {
var name = object.name;
this.select.val(name);
},
addOptions: function(children) {
var opt;
for(var i=0, len = children.length; i < len; i++) {
if(children[i].name && children[i].name !== 'THREE.PointLight' && children[i].name !== 'THREE.SpotLight' && children[i].name !== 'THREE.AmbientLight') {
opt = document.createElement('option');
opt.innerHTML = children[i].name;
opt.setAttribute('value', children[i].name);
this.select.append(opt);
}
}
}
}); | JavaScript |
/**
* @class THREEFAB.TimelineView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup timeline view.
*
*/
THREEFAB.TimelineView = Backbone.View.extend({
el: '#bottom-toolbar',
duration: '#duration',
container: '.timeline-container',
canvas: document.createElement("canvas"),
c: {},
headerHeight:35,
headerWidth:400,
frames:20,
currentFrame:0,
isPlaying: false,
playButton: {},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.container = this.el.find(this.container);
this.duration = this.el.find(this.duration);
this.duration.bind('keyup', this.durationChanged);
this.duration.bind('keypress', this.numericOnly);
this.canvas.width = this.headerWidth;
this.canvas.height = this.headerHeight;
this.c = this.canvas.getContext("2d");
this.canvas.addEventListener('mousedown', this.mouseDown, false);
document.body.addEventListener('mouseup', this.mouseUp, false);
this.el.find('.back').bind('click', this.back);
this.el.find('.forward').bind('click', this.forward);
this.playButton = this.el.find('#playButton');
this.playButton.bind('click', this.play);
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.objectChanged);
$.subscribe(THREEFAB.Events.VIEWPORT_KEYFRAME_CHANGED, this.keyframeChanged);
$.subscribe(THREEFAB.Events.SPACEBAR_PRESSED, this.play);
$.subscribe(THREEFAB.Events.TIMELINE_RESET, this.reset);
},
render: function(frames) {
this.container.append(this.canvas);
if(frames) {
this.frames = frames;
}
this.build(0, this.frames);
},
build: function(goto, frames, broadcast) {
var size = Math.floor(this.canvas.width/frames),
x = 0;
this.c.clearRect(0, 0, this.headerWidth, this.headerHeight);
this.c.fillStyle = "#666";
this.c.fillRect(0, 0, this.headerWidth, this.headerHeight);
for(var i=0; i < frames; i++) {
x = i * size;
if(i !== 0) {
this.drawLine(x, 0, x, this.headerHeight*0.3, "#999999");
this.c.fillStyle = "#ffffff";
if(i%2) {
this.c.fillText(i, x-3, this.headerHeight*0.8);
}
}
}
// Line marker
this.drawLine(goto*size, 0, goto*size, this.headerHeight, "#FF0000");
this.currentFrame = goto;
if(broadcast) {
$.publish(THREEFAB.Events.TIMELINE_CHANGED, this.currentFrame);
}
},
reset: function() {
this.pause();
this.keyframeChanged(0);
},
objectChanged: function(object) {
this.isPlaying = false;
this.playButton.addClass('play');
this.playButton.removeClass('pause');
if(object.morphTargetInfluences) {
if(object.morphTargetInfluences.length > 0) {
this.frames = object.morphTargetInfluences.length;
this.build(0, this.frames, false);
}
} else {
this.build(0,20, false);
this.frames = 20;
}
},
keyframeChanged: function(goto) {
this.build(goto, this.frames, false);
},
durationChanged: function() {
var value = this.duration.val();
if( $.isNumeric(value) ) {
$.publish(THREEFAB.Events.TIMELINE_DURATION_CHANGED, value*1000);
} else {
this.duration.val("1");
}
},
numericOnly: function(e) {
var key = e.charCode || e.keyCode || 0;
// Do not allow spacebar.
if(key === 32) {
return false;
}
},
drawLine: function(x1, y1, x2, y2, color, size) {
this.c.strokeStyle = color;
this.c.beginPath();
this.c.moveTo(x1+0.5, y1+0.5);
this.c.lineTo(x2+0.5, y2+0.5);
this.c.stroke();
},
mouseDown: function(e) {
this.canvas.addEventListener('mousemove', this.mouseMove, false);
},
mouseUp: function() {
this.canvas.removeEventListener('mousemove', this.mouseMove, false);
},
mouseMove: function(e) {
var x = event.pageX - 120,
y = event.pageY,
size = Math.floor(this.canvas.width/this.frames),
frame = Math.floor(x/size);
this.build(frame, this.frames, true);
},
back: function() {
this.build(0, this.frames, true);
},
play: function() {
if(this.isPlaying) {
// Pause
$.publish(THREEFAB.Events.TIMELINE_PAUSE);
this.pause();
} else {
// Play
$.publish(THREEFAB.Events.TIMELINE_PLAY);
this.isPlaying = true;
this.playButton.addClass('pause');
this.playButton.removeClass('play');
}
},
pause: function() {
this.isPlaying = false;
this.playButton.addClass('play');
this.playButton.removeClass('pause');
},
forward: function() {
this.build(this.frames-1, this.frames, true);
}
}); | JavaScript |
/**
* @class THREEFAB.TransformView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup transform view.
*
*/
THREEFAB.TransformView = Backbone.View.extend({
el: '#gui-transform-container',
gui: {},
outliner: {},
viewport: {},
viewportView: {},
selected: {},
folders: {
camera:{},
outliner:{},
viewport:{},
transforms:{},
animate:{}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.viewport = arguments[0].viewport;
// Listen to when an object is selected.
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.addTransformOptions);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.addTransformOptions);
},
render: function() {
// Create transform gui element.
this.gui = new dat.GUI({ autoPlace: false, hide:false });
this.el.append(this.gui.domElement);
// Add Camera
this.folders.camera = this.gui.addFolder('Camera') ;
this.addCameraOptions();
// Add target
this.folders.viewport = this.gui.addFolder('Controls');
this.viewportView = new THREEFAB.ViewportView();
this.folders.viewport.__ul.appendChild(this.viewportView.el[0]);
this.folders.viewport.open();
// Add outliner
this.folders.outliner = this.gui.addFolder('Outliner');
this.outliner = new THREEFAB.OutlinerView();
this.outliner.render( this.viewport.scene );
this.folders.outliner.__ul.appendChild(this.outliner.el[0]);
this.folders.outliner.open();
// Add transforms
this.folders.transforms = this.gui.addFolder('Transforms');
this.addTransformOptions();
this.folders.transforms.open();
},
addCameraOptions: function() {
this.folders.camera.add(this.viewport.camera.position, 'x').listen();
this.folders.camera.add(this.viewport.camera.position, 'y').listen();
this.folders.camera.add(this.viewport.camera.position, 'z').listen();
},
addTransformOptions: function() {
var selected = this.viewport._SELECTED;
var viewport = this.viewport;
THREEFAB.Ui.utils.removeFolderControllers(this.folders.transforms);
this.folders.transforms.add(selected.position, 'x').listen().onChange(function(){
viewport.updateManipulator();
});
this.folders.transforms.add(selected.position, 'y').listen().onChange(function(){
viewport.updateManipulator();
});
this.folders.transforms.add(selected.position, 'z').listen().onChange(function(){
viewport.updateManipulator();
});
// Rotation
this.folders.transforms.add(selected.rotation, 'x', -Math.PI, Math.PI);
this.folders.transforms.add(selected.rotation, 'y', -Math.PI, Math.PI);
this.folders.transforms.add(selected.rotation, 'z', -Math.PI, Math.PI);
if(!selected.light) {
// Scale
this.folders.transforms.add(selected.scale, 'x', 0);
this.folders.transforms.add(selected.scale, 'y', 0);
this.folders.transforms.add(selected.scale, 'z', 0);
}
// Shadows
this.folders.transforms.add(selected, 'castShadow');
this.folders.transforms.add(selected, 'receiveShadow').onChange(function() {
viewport.resetMaterials();
});
}
}); | JavaScript |
/**
* @class THREEFAB.OutlinerView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup outliner view.
*
*/
THREEFAB.ViewportView = Backbone.View.extend({
el: document.createElement('li'),
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.append('<button class="center button">Center</button>');
this.el.find('.center').bind('click', this.clicked);
},
clicked: function() {
$.publish(THREEFAB.Events.VIEWPORT_TARGET_CENTER);
}
}); | JavaScript |
/**
* @class THREEFAB.ColorView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup color view.
*
*/
THREEFAB.ColorView = Backbone.View.extend({
el: document.createElement('li'),
types: {
color: {},
ambient: {},
specular: {}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.css({height:55, padding:'7px 0 10px 60px'});
this.types.color = $("<div class='color_preview_container'><div class='color_preview'></div>Color</div>");
this.types.color.ColorPicker({ onChange: this.changeColor });
this.types.ambient = $("<div class='color_preview_container'><div class='color_preview'></div>Amb</div>");
this.types.ambient.ColorPicker({ onChange: this.changeAmbient });
this.types.specular = $("<div class='color_preview_container'><div class='color_preview'></div>Spec</div>");
this.types.specular.ColorPicker({ onChange: this.changeSpecular });
this.el.append( this.types.color );
this.el.append( this.types.ambient );
this.el.append( this.types.specular );
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.meshChanged);
},
meshChanged: function( object ) {
if(object.material) {
var color = { r: object.material.color.r*255, g:object.material.color.g*255, b:object.material.color.b*255 },
ambient = { r: object.material.ambient.r*255, g:object.material.ambient.g*255, b:object.material.ambient.b*255 },
specular = { r: object.material.specular.r*255, g:object.material.specular.g*255, b:object.material.specular.b*255 };
this.update( this.types.color, color );
this.update( this.types.ambient, ambient );
this.update( this.types.specular, specular );
}
},
changeColor: function( hsb, hex, rgb ) {
this.update(this.types.color, rgb);
$.publish(THREEFAB.Events.MATERIAL_COLOR_CHANGED, [rgb, 'color']);
},
changeAmbient: function( hsb, hex, rgb ) {
this.update(this.types.ambient, rgb);
$.publish(THREEFAB.Events.MATERIAL_COLOR_CHANGED, [rgb, 'ambient']);
},
changeSpecular: function( hsb, hex, rgb ) {
this.update(this.types.specular, rgb);
$.publish(THREEFAB.Events.MATERIAL_COLOR_CHANGED, [rgb, 'specular']);
},
update: function(type, rgb) {
var color = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
type.find('.color_preview').css('backgroundColor', color);
}
}); | JavaScript |
/**
* @class THREEFAB.MaterialModel
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Sets up material model for the right hand material panel.
*
*/
THREEFAB.MaterialModel = Backbone.Model.extend({
materialList: [
{
prop:'wireframe'
},
{
prop:'transparent'
},
{
prop:'opacity',
min:0,
max:1
},
{
prop:'shading',
values:{None: 0, Flat: 1, Smooth: 2},
onChange:'rebuildMaterial'
},
{
prop:'blending',
values:{Normal: 0, Additive: 1, Subtractive: 2, Multiply:3, AdditiveAlpha:4}
},
{
prop:'reflectivity',
min:0,
max:5
},
{
prop:'shininess'
}
],
lightList: [
{
prop: 'intensity',
min:0,
max:10
},
{
prop: 'castShadow'
}
]
}); | JavaScript |
/**
* @class THREEFAB.LightView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup color view.
*
*/
THREEFAB.LightView = Backbone.View.extend({
el: document.createElement('li'),
types: {
color: {}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.css({height:55, padding:'7px 0 10px 6px'});
this.types.color = $("<div class='color_preview_container'><div class='color_preview'></div>Color</div>");
this.types.color.ColorPicker({ onChange: this.changeColor });
this.el.append( this.types.color );
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.lightChanged);
},
lightChanged: function( object ) {
var color = { r: object.light.color.r*255, g:object.light.color.g*255, b:object.light.color.b*255 };
this.update( this.types.color, color );
},
changeColor: function( hsb, hex, rgb ) {
this.update(this.types.color, rgb);
$.publish(THREEFAB.Events.LIGHT_COLOR_CHANGED, [rgb, 'color']);
},
update: function(type, rgb) {
var color = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
type.find('.color_preview').css('backgroundColor', color);
}
}); | JavaScript |
/* =============================================================================
Name: Viewport
Description: Sets up basic three.js viewport.
Author: Jason Kadrmas
Company: KadrmasConceps LLC
========================================================================== */
THREEFAB.Viewport = function( parameters ) {
var _radius = 500,
_height = window.innerHeight,
_width = window.innerWidth,
_this = this,
_container = document.createElement( 'div' ),
_mouse = { x: 0, y: 0 },
_prev_mouse = { x: 0, y: 0 },
_prev_camera,
_SELECTED_DOWN = false,
_SELECTED_AXIS,
_projector = new THREE.Projector(),
SHADOW_MAP_WIDTH = 2048,
SHADOW_MAP_HEIGHT = 1024;
_container.style.position = 'absolute';
_container.style.overflow = 'hidden';
parameters = parameters || {};
this.grid = parameters.grid !== undefined ? parameters.grid : true;
// Add basic scene container
document.body.appendChild( _container );
this.camera = new THREE.PerspectiveCamera( 60, _width / _height, 1, 10000 );
this.camera.position.x = 500;
this.camera.position.y = 250;
this.camera.position.z = 500;
this.camera.lookAt( new THREE.Vector3() );
// Setup renderer
this.renderer = new THREE.WebGLRenderer( { clearAlpha: 1, clearColor: 0x808080 } );
this.renderer.setSize( _width, _height );
this.renderer.shadowCameraNear = 3;
this.renderer.shadowCameraFar = this.camera.far;
this.renderer.shadowCameraFov = 50;
this.renderer.shadowMapBias = 0.0039;
this.renderer.shadowMapDarkness = 0.5;
this.renderer.shadowMapWidth = SHADOW_MAP_WIDTH;
this.renderer.shadowMapHeight = SHADOW_MAP_HEIGHT;
this.renderer.shadowMapEnabled = true;
this.renderer.shadowMapSoft = true;
_container.appendChild( this.renderer.domElement );
// Add trackball this.controls.
this.controls = new THREE.ViewportControls( this.camera, this.renderer.domElement );
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.panSpeed = 0.2;
this.controls.noZoom = false;
this.controls.noPan = false;
this.controls.staticMoving = false;
this.controls.dynamicDampingFactor = 0.3;
this.controls.minDistance = 0;
this.controls.maxDistance = _radius * 100;
this.controls.keys = [ 65, 83, 68 ]; // [ rotateKey, zoomKey, panKey ]
// Scene
this.scene = new THREE.Scene();
//Grid
if(this.grid) {
this.grid = new THREE.Grid();
this.scene.add(this.grid);
// Axis
this.manipulator = new THREE.ManipulatorTool();
this.scene.add(this.manipulator);
}
// Drag and drop functionality
$.subscribe(THREEFAB.Events.MODEL_LOADED, $.proxy(this.addModel, this));
$.subscribe(THREEFAB.Events.TEXTURE_LOADED, $.proxy(this.addTexture, this));
$.subscribe(THREEFAB.Events.PRIMITIVE_ADDED, $.proxy(this.addPrimitive, this));
$.subscribe(THREEFAB.Events.LIGHT_ADDED, $.proxy(this.addLight, this));
$.subscribe(THREEFAB.Events.TEXTURE_CLEAR, $.proxy(this.clearTexture, this));
$.subscribe(THREEFAB.Events.OUTLINER_CHANGED, outlinerChanged);
$.subscribe(THREEFAB.Events.VIEWPORT_TARGET_CENTER, targetCenter);
$.subscribe(THREEFAB.Events.TIMELINE_CHANGED, updateMeshFrame);
$.subscribe(THREEFAB.Events.TIMELINE_PLAY, playAnimation);
$.subscribe(THREEFAB.Events.TIMELINE_PAUSE, pauseAnimation);
$.subscribe(THREEFAB.Events.TIMELINE_DURATION_CHANGED, changeAnimationDuration);
$.subscribe(THREEFAB.Events.DELETE_PRESSED, deleteObject);
// =============================================================================
// DEFAULT Light, Cube. JUST LIKE BLENDER
// =============================================================================
this.setupDefaultScene.apply(this);
this.animating = false;
this.duration = 1000;
this.particleSystem = {};
this.particleGeometry = {};
this.particleCount = 1800;
//this.addParticleSystem.apply(this);
// =============================================================================
// Public Functions
// =============================================================================
this.render = function() {
_this.controls.update();
if(this.animating) {
this.processAnimation();
}
//this.processParticles();
_this.renderer.render( _this.scene, _this.camera );
};
this.animate = function() {
requestAnimationFrame( _this.animate );
_this.render();
};
this.setSize = function ( width, height ) {
_width = width;
_height = height;
_this.camera.aspect = width / height;
//_this.camera.toPerspective();
_this.camera.updateProjectionMatrix();
_this.controls.screen.width = width;
_this.controls.screen.height = height;
_this.renderer.setSize( width, height );
_this.render();
};
this.selected = function(object) {
// Pause any animations taking place
pauseAnimation();
// Remove the current overdraw
if(_this._SELECTED) {
_this._SELECTED.material.program = null;
_this._SELECTED.material.overdraw = false;
}
_this._SELECTED = object;
if(!_this._SELECTED.light) {
// It's a mesh!
this.selectMesh(object);
} else {
// It's a light!
$.publish(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, object);
_this._SELECTED.material.program = null;
_this._SELECTED.material.overdraw = true;
}
_this.updateManipulator();
};
this.deselect = function() {
_this.controls.noRotate = false;
_SELECTED_AXIS = null;
_SELECTED_DOWN = false;
};
this.processAnimation = function() {
var frame = _this.animationMorphTarget.render();
$.publish(THREEFAB.Events.VIEWPORT_KEYFRAME_CHANGED, frame);
};
this.processParticles = function() {
var ps = _this.particleSystem,
pcount = _this.particleCount,
particleGeom = this.particleGeometry;
while(pcount--) {
particle = particleGeom.vertices[pcount];
// check if we need to reset
if(particle.position.y < -200) {
particle.position.y = 200;
particle.velocity.y = 0;
}
// update the velocity with
// a splat of randomniz
particle.velocity.y -= Math.random() * 0.1;
// and the position
particle.position.addSelf(particle.velocity);
}
// flag to the particle system that we've
// changed its vertices. This is the
// dirty little secret.
ps.geometry.__dirtyVertices = true;
};
this.updateManipulator = function() {
_this.manipulator.position.copy( _this._SELECTED.position );
};
this.selectMesh = function (object) {
if( meshCanAnimate() ) {
_this.animationMorphTarget = new THREEFAB.AnimationMorphTarget(object, _this.duration);
}
$.publish(THREEFAB.Events.VIEWPORT_MESH_SELECTED, object);
};
this.selectNextMesh = function() {
for(var i=0, len = _this.scene.children.length; i < len; i++) {
if(_this.scene.children[i].name) {
_this.selected(_this.scene.children[i]);
break;
}
}
};
function outlinerChanged(name) {
var child = _this.scene.getChildByName(name);
_this.selected(child);
}
function targetCenter() {
_this.controls.target = new THREE.Vector3();
}
function updateMeshFrame(frame) {
if( meshCanAnimate() ) {
/*_this._SELECTED.morphTargetInfluences[ _this.keyframe ] = 0;
_this._SELECTED.morphTargetInfluences[ frame ] = 1;
_this.keyframe = frame;*/
if(!_this.animating) {
_this.animationMorphTarget.gotoFrame( frame );
}
}
}
function playAnimation() {
if( meshCanAnimate() ) {
_this.animationMorphTarget.play();
_this.animating = true;
}
}
function pauseAnimation() {
if(_this.animationMorphTarget) {
_this.animationMorphTarget.pause();
}
_this.animating = false;
}
function changeAnimationDuration(value) {
_this.duration = value;
if(_this.animating) {
pauseAnimation();
}
if(_this.animationMorphTarget) {
_this.animationMorphTarget.clear();
_this.animationMorphTarget = new THREEFAB.AnimationMorphTarget(_this._SELECTED, _this.duration);
}
$.publish(THREEFAB.Events.TIMELINE_RESET);
}
function meshCanAnimate() {
if(_this._SELECTED.morphTargetInfluences) {
return true;
}
return false;
}
function deleteObject() {
if(_this._SELECTED) {
if(_this._SELECTED.light) {
// If it's a light remove that too
_this.scene.remove(_this._SELECTED.light);
}
// Remove currently selected mesh
_this.scene.remove(_this._SELECTED);
// Get the next object and select that one
_this.selectNextMesh();
// Tell everyone we deleted an object
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_REMOVED, _this.scene);
}
}
// =============================================================================
//
// Mouse Functions
//
// =============================================================================
// ----------------------------------------
// Mouse Down
// ----------------------------------------
this.renderer.domElement.addEventListener( 'mousedown', function ( event ) {
event.preventDefault();
// find intersections
var vector = new THREE.Vector3( _mouse.x, _mouse.y, 1 );
_projector.unprojectVector( vector, _this.camera );
var ray = new THREE.Ray( _this.camera.position, vector.subSelf( _this.camera.position ).normalize() );
var intersects = ray.intersectScene( _this.scene );
if ( intersects.length > 0 ) {
// Are we already selected?
if ( _SELECTED_AXIS != intersects[ 0 ].object && (intersects[ 0 ].object.name === "x_manipulator" || intersects[ 0 ].object.name === "y_manipulator" || intersects[ 0 ].object.name === "z_manipulator")) {
_this.controls.noRotate = true;
_SELECTED_AXIS = intersects[0].object;
} else {
// This is an object and not a grid handle.
_this.selected(intersects[0].object);
_SELECTED_DOWN = true;
}
}
// Log the camera postion. If it moves then don't deselect any selected items.
_prev_camera = _this.camera;
});
// ----------------------------------------
// Mouse up
// ----------------------------------------
this.renderer.domElement.addEventListener('mouseup', function(event) {
event.preventDefault();
_this.deselect();
});
// ----------------------------------------
// Mouse move
// ----------------------------------------
this.renderer.domElement.addEventListener('mousemove', function(event) {
event.preventDefault();
_prev_mouse.x = _mouse.x;
_prev_mouse.y = _mouse.y;
_mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
_mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
if ( _SELECTED_AXIS && _this._SELECTED ) {
var tx = (_mouse.x - _prev_mouse.x) * 1000;
var ty = (_mouse.y - _prev_mouse.y) * 1000;
if(_SELECTED_AXIS.name === "x_manipulator") {
_this.manipulator.translateX(tx);
} else if(_SELECTED_AXIS.name === "y_manipulator") {
_this.manipulator.translateY(ty);
} else if(_SELECTED_AXIS.name === "z_manipulator") {
_this.manipulator.translateZ(-ty);
}
if ( _this._SELECTED ) {
_this._SELECTED.position.copy( _this.manipulator.position );
}
}
});
this.renderer.domElement.addEventListener( 'dblclick', function (e) {
_this.animating = false;
_this._SELECTED.geometry.computeBoundingBox();
var bb = _this._SELECTED.geometry.boundingBox;
_this.camera.position.x = _this._SELECTED.position.x;
_this.camera.position.y = _this._SELECTED.position.y + _this._SELECTED.boundRadius;
if(bb.z) {
_this.camera.position.z = _this._SELECTED.position.z + (bb.z[1]+300);
}
_this.controls.target = _this._SELECTED.position;
});
// ----------------------------------------
// Keyboard Support
// ----------------------------------------
window.addEventListener('keydown', function(e) {
var code;
if (!e) { e = window.event; }
if (e.keyCode) {
code = e.keyCode;
} else if (e.which) {
code = e.which;
}
if (code === 88) {
// X Key
$.publish(THREEFAB.Events.DELETE_PRESSED);
} else if(code === 32) {
// Spacebar
$.publish(THREEFAB.Events.SPACEBAR_PRESSED);
}
});
};
THREEFAB.Viewport.prototype = {
addPrimitive: function(type) {
var material,
geometry,
mesh,
meshName,
rotation,
doubleSided = false;
material = new THREE.MeshPhongMaterial( { wireframe: false, map: new THREEFAB.CanvasTexture(), shading: THREE.SmoothShading, overdraw: false } );
material.name = 'MeshPhongMaterial';
if(type === "sphere") {
geometry = new THREE.SphereGeometry(100,16,16);
meshName = 'THREE.SphereGeometry';
} else if(type === "cube") {
geometry = new THREE.CubeGeometry(100,100,100,1,1,1);
meshName = 'THREE.CubeGeometry';
} else if(type === "cylinder") {
geometry = new THREE.CylinderGeometry(50, 50, 100, 16);
meshName = 'THREE.CylinderGeometry';
} else if(type === "cone") {
geometry = new THREE.CylinderGeometry( 0, 50, 100, 16, 1 );
meshName = 'THREE.ConeGeometry';
} else if(type === "plane") {
geometry = new THREE.PlaneGeometry( 200, 200, 3, 3 );
meshName = 'THREE.PlaneGeometry';
rotation = new THREE.Vector3(-Math.PI/2,0,0);
doubleSided = true;
} else if(type === "torus") {
geometry = new THREE.TorusGeometry();
rotation = new THREE.Vector3(-Math.PI/2,0,0);
meshName = 'THREE.TorusGeometry';
}
geometry.dynamic = true;
mesh = new THREE.Mesh(geometry, material);
mesh.name = meshName + "." + mesh.id;
if(rotation) {
mesh.rotation.copy(rotation);
}
if(doubleSided) {
mesh.doubleSided = true;
}
this.scene.add(mesh);
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.scene);
return mesh;
},
addParticleSystem: function() {
// create the particle variables
var particles = new THREE.Geometry(),
pMaterial = new THREE.ParticleBasicMaterial({ color: 0xFFFFFF, size: Math.random() * 25 + 10, map: THREE.ImageUtils.loadTexture( "img/particle.png" ), blending: THREE.AdditiveBlending, transparent: true });
particleCount = this.particleCount;
// now create the individual particles
for(var p = 0; p < particleCount; p++) {
// create a particle with random
// position values, -250 -> 250
var pX = Math.random() * 500 - 250,
pY = Math.random() * 500 - 250,
pZ = Math.random() * 500 - 250,
particle = new THREE.Vertex( new THREE.Vector3(pX, pY, pZ) );
// create a velocity vector
particle.velocity = new THREE.Vector3(
0, // x
-Math.random(), // y: start with random vel
0 // z
);
// add it to the geometry
particles.vertices.push(particle);
}
// create the particle system
this.particleSystem = new THREE.ParticleSystem( particles, pMaterial);
this.particleGeometry = particles;
this.particleSystem.sortParticles = true;
// add it to the scene
this.scene.add(this.particleSystem);
},
addModel: function(mesh) {
this.scene.add(mesh);
this.selected(mesh);
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.scene);
return mesh;
},
addLight: function(type) {
var lightmesh;
if(type === "point") {
lightmesh = new THREEFAB.PointLightContainer(this.scene);
} else if(type === "spot") {
lightmesh = new THREEFAB.SpotLightContainer(this.scene);
} else if(type === "ambient") {
lightmesh = new THREEFAB.AmbientLightContainer(this.scene);
}
lightmesh.mesh.position.y = 150;
lightmesh.mesh.position.x = 100;
this.resetMaterials();
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.scene);
return lightmesh;
},
addTexture: function(tex) {
if(!this._SELECTED.light) {
this._SELECTED.material.program = null;
this._SELECTED.material.program = null;
this._SELECTED.material.map = tex;
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_TEXTURE_ADDED, this._SELECTED);
}
},
clearTexture: function() {
this._SELECTED.material.program = null;
this._SELECTED.material.map = new THREEFAB.CanvasTexture();
},
resetMaterials: function() {
for(var i=0, len = this.scene.children.length; i < len; i++) {
var child = this.scene.children[i], cached_mat;
if(child.material && child instanceof THREE.Mesh) {
cached_mat = child.material;
child.material.program = false;
child.material = null;
child.material = cached_mat;
}
}
},
setupDefaultScene: function() {
var mesh = this.addPrimitive.call(this, 'cube');
var lightmesh = this.addLight.call(this, 'point');
this._SELECTED = mesh;
$.publish(THREEFAB.Events.VIEWPORT_MESH_SELECTED, mesh);
}
};
| JavaScript |
/* =============================================================================
Author: Jason Kadrmas
Company: KadrmasConceps LLC
========================================================================== */
(function(){
// Ready
$(document).ready(function(){
var dragDrop = new THREEFAB.DragDropLoader(),
viewport = new THREEFAB.Viewport(),
ui = new THREEFAB.Ui(viewport),
toolbox = new THREEFAB.Toolbox(),
exporter = new THREEFAB.Exporter();
// App Resize
window.addEventListener('resize', function(event) {
viewport.setSize( window.innerWidth, window.innerHeight );
}, false);
// Start animating viewport
viewport.animate();
viewport.setSize( window.innerWidth, window.innerHeight );
//exporter.generate(viewport);
$.subscribe(THREEFAB.Events.EXPORTER_GENERATE, function() {
exporter.generate(viewport);
});
$('#hide-button').on('click', function() {
$('.code-container').hide();
});
});
})(); | JavaScript |
/**
* Provides requestAnimationFrame in a cross browser way.
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
if ( !window.requestAnimationFrame ) {
window.requestAnimationFrame = ( function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || // comment out if FF4 is slow (it caps framerate at ~30fps: https://bugzilla.mozilla.org/show_bug.cgi?id=630127)
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
window.setTimeout( callback, 1000 / 60 );
};
} )();
}
| JavaScript |
ManipulatorTool = function () {
THREE.Object3D.call(this);
// Init
this.selected = {};
// setup geometery
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(new THREE.Vertex());
lineGeometry.vertices.push(new THREE.Vertex(new THREE.Vector3(0, 100, 0)));
var coneGeometry = new THREE.CylinderGeometry(0, 5, 25, 5, 1);
// x
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0xff0000 }));
line.rotation.z = -Math.PI / 2;
this.add(line);
this.xCone = new THREE.Mesh(coneGeometry, new THREE.MeshBasicMaterial({ color: 0xff0000 }));
this.xCone.name = "x_manipulator";
this.xCone.position.x = 100;
this.xCone.rotation.z = -Math.PI / 2;
this.add(this.xCone);
// y
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0x00ff00 }));
this.add(line);
this.yCone = new THREE.Mesh(coneGeometry, new THREE.MeshBasicMaterial({ color: 0x00ff00 }));
this.yCone.position.y = 100;
this.yCone.name = "y_manipulator";
this.add(this.yCone);
// z
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0x0000ff }));
line.rotation.x = Math.PI / 2;
this.add(line);
this.zCone = new THREE.Mesh(coneGeometry, new THREE.MeshBasicMaterial({ color: 0x0000ff }));
this.zCone.position.z = 100;
this.zCone.name = "z_manipulator";
this.zCone.rotation.x = Math.PI / 2;
this.add(this.zCone);
};
ManipulatorTool.prototype = new THREE.Object3D();
ManipulatorTool.prototype.constructor = ManipulatorTool;
| JavaScript |
Events = {
// VIEWPORT_MESH_SELECTED: 'viewport/mesh/selected',
// VIEWPORT_LIGHT_SELECTED: 'viewport/light/selected',
// VIEWPORT_OBJECT_TEXTURE_ADDED: 'viewport/object/texture/added',
// VIEWPORT_OBJECT_REMOVED: 'viewport/object/removed',
VIEWPORT_OBJECT_ADDED: 'viewport/object/added',
// VIEWPORT_TARGET_CENTER: 'viewport/target/center',
// VIEWPORT_KEYFRAME_CHANGED: 'viewport/keyframe/changed',
// MATERIAL_COLOR_CHANGED: 'material/color/changed',
// LIGHT_COLOR_CHANGED: 'light/color/changed',
// OUTLINER_CHANGED: 'outliner/changed',
// MODEL_LOADED: 'model/loaded',
// TEXTURE_LOADED: 'texture/loaded',
// TEXTURE_CLEAR: 'texture/clear',
PRIMITIVE_ADDED: 'primitive/add',
// LIGHT_ADDED: 'light/add',
// EXPORTER_GENERATE: 'exporter/generate',
// TIMELINE_CHANGED: 'timeline/changed',
// TIMELINE_PLAY: 'timeline/play',
// TIMELINE_PAUSE: 'timeline/pause',
// TIMELINE_RESET: 'timeline/reset',
// TIMELINE_DURATION_CHANGED: 'timeline/duration/changed',
// SPACEBAR_PRESSED: 'keyboard/spacebar/pressed',
// DELETE_PRESSED: 'keyboard/delete/pressed'
}; | JavaScript |
/*
* jQuery Tiny Pub/Sub - v0.6 - 1/10/2011
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($){var a=$("<b/>");$.subscribe=function(b,c){function d(){return c.apply(this,Array.prototype.slice.call(arguments,1))}d.guid=c.guid=c.guid||($.guid?$.guid++:$.event.guid++);a.bind(b,d)};$.unsubscribe=function(){a.unbind.apply(a,arguments)};$.publish=function(){a.trigger.apply(a,arguments)}})(jQuery);
/*
* jQuery Templates Plugin 1.0.0pre
* http://github.com/jquery/jquery-tmpl
* Requires jQuery 1.4.2
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},i=0,c=0,l=[];function g(g,d,h,e){var c={data:e||(e===0||e===false)?e:d?d.data:{},_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};g&&a.extend(c,g,{nodes:[],parent:d});if(h){c.tmpl=h;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++i;(l.length?f:b)[i]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a(i[h])[d](k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,m,k){if(d[0]&&a.isArray(d[0])){var g=a.makeArray(arguments),h=d[0],j=h.length,i=0,f;while(i<j&&!(f=a.data(h[i++],"tmplItem")));if(f&&c)g[2]=function(b){a.tmpl.afterManip(this,b,k)};r.apply(this,g)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var i,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(j(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);i=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(j(c,null,i)):i},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){__=__.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(__,$1,$2);__=[];",close:"call=$item.calls();__=call._.concat($item.wrap(call,__));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){__.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){__.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function j(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:j(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=k(c).concat(b);if(d)b=b.concat(k(d))});return b?b:k(c)}function k(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,__=[],$data=$item.data;with($data){__.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,k,g,b,c,d){var j=a.tmpl.tag[k],i,e,f;if(!j)throw"Unknown template tag: "+k;i=j._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=h(b);d=d?","+h(d)+")":c?")":"";e=c?b.indexOf(".")>-1?b+h(c):"("+b+").call($item"+d:b;f=c?e:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else f=e=i.$1||"null";g=h(g);return"');"+j[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(f).split("$1").join(e).split("$2").join(g||i.$2||"")+"__.push('"})+"');}return __;")}function n(c,b){c._wrap=j(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function h(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,h;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(h=j.length-1;h>=0;h--)m(j[h]);m(k)}function m(j){var p,h=j,k,e,m;if(m=j.getAttribute(d)){while(h.parentNode&&(h=h.parentNode).nodeType===1&&!(p=h.getAttribute(d)));if(p!==m){h=h.parentNode?h.nodeType===11?0:h.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[h]||f[h]);e.key=++i;b[i]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;h=a.data(j.parentNode,"tmplItem");h=h?h.key:0}if(e){k=e;while(k&&k.key!=h){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
// JK: Hack to align perfect.
left += 40;
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery);
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery); | JavaScript |
CanvasTexture = function () {
THREE.Texture.call( this );
var canvas = document.createElement( 'canvas' );
canvas.width = 512;
canvas.height = 512;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255,255,255,1)";
ctx.fillRect(0, 0, 512, 512);
this.image = canvas;
this.needsUpdate = true;
}
CanvasTexture.prototype = new THREE.Texture();
CanvasTexture.prototype.constructor = CanvasTexture; | JavaScript |
AxisTool = function () {
THREE.Object3D.call(this);
// Init
this.selected = {};
// setup geometery
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(new THREE.Vertex());
lineGeometry.vertices.push(new THREE.Vertex(new THREE.Vector3(0, 100, 0)));
var coneGeometry = new THREE.CylinderGeometry(0, 5, 25, 5, 1);
// x
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0xff0000 }));
line.rotation.z = -Math.PI / 2;
this.add(line);
this.xCone = new THREE.Mesh(coneGeometry, new THREE.MeshBasicMaterial({ color: 0xff0000 }));
this.xCone.name = "x_manipulator";
this.xCone.position.x = 100;
this.xCone.rotation.z = -Math.PI / 2;
this.add(this.xCone);
// y
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0x00ff00 }));
this.add(line);
this.yCone = new THREE.Mesh(coneGeometry, new THREE.MeshBasicMaterial({ color: 0x00ff00 }));
this.yCone.position.y = 100;
this.yCone.name = "y_manipulator";
this.add(this.yCone);
// z
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0x0000ff }));
line.rotation.x = Math.PI / 2;
this.add(line);
this.zCone = new THREE.Mesh(coneGeometry, new THREE.MeshBasicMaterial({ color: 0x0000ff }));
this.zCone.position.z = 100;
this.zCone.name = "z_manipulator";
this.zCone.rotation.x = Math.PI / 2;
this.add(this.zCone);
};
AxisTool.prototype = new THREE.Object3D();
AxisTool.prototype.constructor = AxisTool;
| JavaScript |
MyObject = function () {
this.name = "huy";
this.age = 22;
}
MyObject.prototype = new Object();
MyObject.prototype.constructor = MyObject(); | JavaScript |
Toolbox = Backbone.View.extend({
initialize: function () {
$('.toolbox-list').bind('click', function (event) {
event.preventDefault();
var target = event.target || event.srcElement,
className;
if (target.tagName.toLowerCase() === "a") {
className = target.className;
$.publish(Events.PRIMITIVE_ADDED, target.className);
}
});
// $('.light-list').bind('click', function (event) {
// event.preventDefault();
// var target = event.target || event.srcElement,
// className;
// if (target.tagName.toLowerCase() === "a") {
// className = target.className;
// $.publish(THREEFAB.Events.LIGHT_ADDED, target.className);
// }
// });
// $('.export').bind('click', function (event) {
// $.publish(THREEFAB.Events.EXPORTER_GENERATE);
// });
}
});
| JavaScript |
MyGrid = function () {
THREE.Object3D.call(this);
var _grid = new THREE.Mesh(new THREE.PlaneGeometry(1000, 1000, 20, 20), new THREE.MeshBasicMaterial({ color: 0x606060, wireframe: true, transparent: true }));
_grid.rotation.x = Math.PI / 2;
this.add(_grid);
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(new THREE.Vertex());
lineGeometry.vertices.push(new THREE.Vertex(new THREE.Vector3(0, 1000, 1)));
// x
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0xff0000 }));
line.rotation.z = -Math.PI / 2;
line.position.x = -500;
this.add(line);
//z
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0x0000ff }));
line.rotation.x = Math.PI / 2;
line.position.z = -500;
this.add(line);
};
MyGrid.prototype = new THREE.Object3D();
MyGrid.prototype.constructor = MyGrid; | JavaScript |
/**
* 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.gui = dat.gui || {};
/** @namespace */
dat.utils = dat.utils || {};
/** @namespace */
dat.controllers = dat.controllers || {};
/** @namespace */
dat.dom = dat.dom || {};
/** @namespace */
dat.color = dat.color || {};
dat.utils.css = (function () {
return {
load: function (url, doc) {
doc = doc || document;
var link = doc.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
doc.getElementsByTagName('head')[0].appendChild(link);
},
inject: function(css, doc) {
doc = doc || document;
var injected = document.createElement('style');
injected.type = 'text/css';
injected.innerHTML = css;
doc.getElementsByTagName('head')[0].appendChild(injected);
}
}
})();
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.controllers.Controller = (function (common) {
/**
* @class An "abstract" class that represents a given property of an object.
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var Controller = function(object, property) {
this.initialValue = object[property];
/**
* Those who extend this class will put their DOM elements in here.
* @type {DOMElement}
*/
this.domElement = document.createElement('div');
/**
* The object to manipulate
* @type {Object}
*/
this.object = object;
/**
* The name of the property to manipulate
* @type {String}
*/
this.property = property;
/**
* The function to be called on change.
* @type {Function}
* @ignore
*/
this.__onChange = undefined;
/**
* The function to be called on finishing change.
* @type {Function}
* @ignore
*/
this.__onFinishChange = undefined;
};
common.extend(
Controller.prototype,
/** @lends dat.controllers.Controller.prototype */
{
/**
* Specify that a function fire every time someone changes the value with
* this Controller.
*
* @param {Function} fnc This function will be called whenever the value
* is modified via this Controller.
* @returns {dat.controllers.Controller} this
*/
onChange: function(fnc) {
this.__onChange = fnc;
return this;
},
/**
* Specify that a function fire every time someone "finishes" changing
* the value wih this Controller. Useful for values that change
* incrementally like numbers or strings.
*
* @param {Function} fnc This function will be called whenever
* someone "finishes" changing the value via this Controller.
* @returns {dat.controllers.Controller} this
*/
onFinishChange: function(fnc) {
this.__onFinishChange = fnc;
return this;
},
/**
* Change the value of <code>object[property]</code>
*
* @param {Object} newValue The new value of <code>object[property]</code>
*/
setValue: function(newValue) {
this.object[this.property] = newValue;
if (this.__onChange) {
this.__onChange.call(this, newValue);
}
this.updateDisplay();
return this;
},
/**
* Gets the value of <code>object[property]</code>
*
* @returns {Object} The current value of <code>object[property]</code>
*/
getValue: function() {
return this.object[this.property];
},
/**
* Refreshes the visual display of a Controller in order to keep sync
* with the object's current value.
* @returns {dat.controllers.Controller} this
*/
updateDisplay: function() {
return this;
},
/**
* @returns {Boolean} true if the value has deviated from initialValue
*/
isModified: function() {
return this.initialValue !== this.getValue()
}
}
);
return Controller;
})(dat.utils.common);
dat.dom.dom = (function (common) {
var EVENT_MAP = {
'HTMLEvents': ['change'],
'MouseEvents': ['click','mousemove','mousedown','mouseup', 'mouseover'],
'KeyboardEvents': ['keydown']
};
var EVENT_MAP_INV = {};
common.each(EVENT_MAP, function(v, k) {
common.each(v, function(e) {
EVENT_MAP_INV[e] = k;
});
});
var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
function cssValueToPixels(val) {
if (val === '0' || common.isUndefined(val)) return 0;
var match = val.match(CSS_VALUE_PIXELS);
if (!common.isNull(match)) {
return parseFloat(match[1]);
}
// TODO ...ems? %?
return 0;
}
/**
* @namespace
* @member dat.dom
*/
var dom = {
/**
*
* @param elem
* @param selectable
*/
makeSelectable: function(elem, selectable) {
if (elem === undefined || elem.style === undefined) return;
elem.onselectstart = selectable ? function() {
return false;
} : function() {
};
elem.style.MozUserSelect = selectable ? 'auto' : 'none';
elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
elem.unselectable = selectable ? 'on' : 'off';
},
/**
*
* @param elem
* @param horizontal
* @param vertical
*/
makeFullscreen: function(elem, horizontal, vertical) {
if (common.isUndefined(horizontal)) horizontal = true;
if (common.isUndefined(vertical)) vertical = true;
elem.style.position = 'absolute';
if (horizontal) {
elem.style.left = 0;
elem.style.right = 0;
}
if (vertical) {
elem.style.top = 0;
elem.style.bottom = 0;
}
},
/**
*
* @param elem
* @param eventType
* @param params
*/
fakeEvent: function(elem, eventType, params, aux) {
params = params || {};
var className = EVENT_MAP_INV[eventType];
if (!className) {
throw new Error('Event type ' + eventType + ' not supported.');
}
var evt = document.createEvent(className);
switch (className) {
case 'MouseEvents':
var clientX = params.x || params.clientX || 0;
var clientY = params.y || params.clientY || 0;
evt.initMouseEvent(eventType, params.bubbles || false,
params.cancelable || true, window, params.clickCount || 1,
0, //screen X
0, //screen Y
clientX, //client X
clientY, //client Y
false, false, false, false, 0, null);
break;
case 'KeyboardEvents':
var init = evt.initKeyboardEvent || evt.initKeyEvent; // webkit || moz
common.defaults(params, {
cancelable: true,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: undefined,
charCode: undefined
});
init(eventType, params.bubbles || false,
params.cancelable, window,
params.ctrlKey, params.altKey,
params.shiftKey, params.metaKey,
params.keyCode, params.charCode);
break;
default:
evt.initEvent(eventType, params.bubbles || false,
params.cancelable || true);
break;
}
common.defaults(evt, aux);
elem.dispatchEvent(evt);
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
bind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.addEventListener)
elem.addEventListener(event, func, bool);
else if (elem.attachEvent)
elem.attachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
unbind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.removeEventListener)
elem.removeEventListener(event, func, bool);
else if (elem.detachEvent)
elem.detachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param className
*/
addClass: function(elem, className) {
if (elem.className === undefined) {
elem.className = className;
} else if (elem.className !== className) {
var classes = elem.className.split(/ +/);
if (classes.indexOf(className) == -1) {
classes.push(className);
elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
}
}
return dom;
},
/**
*
* @param elem
* @param className
*/
removeClass: function(elem, className) {
if (className) {
if (elem.className === undefined) {
// elem.className = className;
} else if (elem.className === className) {
elem.removeAttribute('class');
} else {
var classes = elem.className.split(/ +/);
var index = classes.indexOf(className);
if (index != -1) {
classes.splice(index, 1);
elem.className = classes.join(' ');
}
}
} else {
elem.className = undefined;
}
return dom;
},
hasClass: function(elem, className) {
return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
},
/**
*
* @param elem
*/
getWidth: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-left-width']) +
cssValueToPixels(style['border-right-width']) +
cssValueToPixels(style['padding-left']) +
cssValueToPixels(style['padding-right']) +
cssValueToPixels(style['width']);
},
/**
*
* @param elem
*/
getHeight: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-top-width']) +
cssValueToPixels(style['border-bottom-width']) +
cssValueToPixels(style['padding-top']) +
cssValueToPixels(style['padding-bottom']) +
cssValueToPixels(style['height']);
},
/**
*
* @param elem
*/
getOffset: function(elem) {
var offset = {left: 0, top:0};
if (elem.offsetParent) {
do {
offset.left += elem.offsetLeft;
offset.top += elem.offsetTop;
} while (elem = elem.offsetParent);
}
return offset;
},
// http://stackoverflow.com/posts/2684561/revisions
/**
*
* @param elem
*/
isActive: function(elem) {
return elem === document.activeElement && ( elem.type || elem.href );
}
};
return dom;
})(dat.utils.common);
dat.controllers.OptionController = (function (Controller, dom, common) {
/**
* @class Provides a select input to alter the property of an object, using a
* list of accepted values.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object|string[]} options A map of labels to acceptable values, or
* a list of acceptable string values.
*
* @member dat.controllers
*/
var OptionController = function(object, property, options) {
OptionController.superclass.call(this, object, property);
var _this = this;
/**
* The drop down menu
* @ignore
*/
this.__select = document.createElement('select');
if (common.isArray(options)) {
var map = {};
common.each(options, function(element) {
map[element] = element;
});
options = map;
}
common.each(options, function(value, key) {
var opt = document.createElement('option');
opt.innerHTML = key;
opt.setAttribute('value', value);
_this.__select.appendChild(opt);
});
// Acknowledge original value
this.updateDisplay();
dom.bind(this.__select, 'change', function() {
var desiredValue = this.options[this.selectedIndex].value;
_this.setValue(desiredValue);
});
this.domElement.appendChild(this.__select);
};
OptionController.superclass = Controller;
common.extend(
OptionController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = OptionController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
return toReturn;
},
updateDisplay: function() {
this.__select.value = this.getValue();
return OptionController.superclass.prototype.updateDisplay.call(this);
}
}
);
return OptionController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common);
dat.controllers.NumberController = (function (Controller, common) {
/**
* @class Represents a given property of an object that is a number.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberController = function(object, property, params) {
NumberController.superclass.call(this, object, property);
params = params || {};
this.__min = params.min;
this.__max = params.max;
this.__step = params.step;
if (common.isUndefined(this.__step)) {
if (this.initialValue == 0) {
this.__impliedStep = 1; // What are we, psychics?
} else {
// Hey Doug, check this out.
this.__impliedStep = Math.pow(10, Math.floor(Math.log(this.initialValue)/Math.LN10))/10;
}
} else {
this.__impliedStep = this.__step;
}
this.__precision = numDecimals(this.__impliedStep);
};
NumberController.superclass = Controller;
common.extend(
NumberController.prototype,
Controller.prototype,
/** @lends dat.controllers.NumberController.prototype */
{
setValue: function(v) {
if (this.__min !== undefined && v < this.__min) {
v = this.__min;
} else if (this.__max !== undefined && v > this.__max) {
v = this.__max;
}
if (this.__step !== undefined && v % this.__step != 0) {
v = Math.round(v / this.__step) * this.__step;
}
return NumberController.superclass.prototype.setValue.call(this, v);
},
/**
* Specify a minimum value for <code>object[property]</code>.
*
* @param {Number} minValue The minimum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
min: function(v) {
this.__min = v;
return this;
},
/**
* Specify a maximum value for <code>object[property]</code>.
*
* @param {Number} maxValue The maximum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
max: function(v) {
this.__max = v;
return this;
},
/**
* Specify a step value that dat.controllers.NumberController
* increments by.
*
* @param {Number} stepValue The step value for
* dat.controllers.NumberController
* @default if minimum and maximum specified increment is 1% of the
* difference otherwise stepValue is 1
* @returns {dat.controllers.NumberController} this
*/
step: function(v) {
this.__step = v;
return this;
}
}
);
function numDecimals(x) {
x = x.toString();
if (x.indexOf('.') > -1) {
return x.length - x.indexOf('.') - 1;
} else {
return 0;
}
}
return NumberController;
})(dat.controllers.Controller,
dat.utils.common);
dat.controllers.NumberControllerBox = (function (NumberController, dom, common) {
/**
* @class Represents a given property of an object that is a number and
* provides an input element with which to manipulate it.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerBox = function(object, property, params) {
this.__truncationSuspended = false;
NumberControllerBox.superclass.call(this, object, property, params);
var _this = this;
/**
* {Number} Previous mouse y position
* @ignore
*/
var prev_y;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
// Makes it so manually specified values are not truncated.
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'mousedown', onMouseDown);
dom.bind(this.__input, 'keydown', function(e) {
// When pressing entire, you can be as precise as you want.
if (e.keyCode === 13) {
_this.__truncationSuspended = true;
this.blur();
_this.__truncationSuspended = false;
}
});
function onChange() {
var attempted = parseFloat(_this.__input.value);
if (!common.isNaN(attempted)) _this.setValue(attempted);
}
function onBlur() {
onChange();
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
prev_y = e.clientY;
}
function onMouseDrag(e) {
var diff = prev_y - e.clientY;
_this.setValue(_this.getValue() + diff * _this.__impliedStep);
prev_y = e.clientY;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
NumberControllerBox.superclass = NumberController;
common.extend(
NumberControllerBox.prototype,
NumberController.prototype,
{
updateDisplay: function() {
this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
return NumberControllerBox.superclass.prototype.updateDisplay.call(this);
}
}
);
function roundToDecimal(value, decimals) {
var tenTo = Math.pow(10, decimals);
return Math.round(value * tenTo) / tenTo;
}
return NumberControllerBox;
})(dat.controllers.NumberController,
dat.dom.dom,
dat.utils.common);
dat.controllers.NumberControllerSlider = (function (NumberController, dom, css, common, styleSheet) {
/**
* @class Represents a given property of an object that is a number, contains
* a minimum and maximum, and provides a slider element with which to
* manipulate it. It should be noted that the slider element is made up of
* <code><div></code> tags, <strong>not</strong> the html5
* <code><slider></code> element.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Number} minValue Minimum allowed value
* @param {Number} maxValue Maximum allowed value
* @param {Number} stepValue Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerSlider = function(object, property, min, max, step) {
NumberControllerSlider.superclass.call(this, object, property, { min: min, max: max, step: step });
var _this = this;
this.__background = document.createElement('div');
this.__foreground = document.createElement('div');
dom.bind(this.__background, 'mousedown', onMouseDown);
dom.addClass(this.__background, 'slider');
dom.addClass(this.__foreground, 'slider-fg');
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
onMouseDrag(e);
}
function onMouseDrag(e) {
e.preventDefault();
var offset = dom.getOffset(_this.__background);
var width = dom.getWidth(_this.__background);
_this.setValue(
map(e.clientX, offset.left, offset.left + width, _this.__min, _this.__max)
);
return false;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.__background.appendChild(this.__foreground);
this.domElement.appendChild(this.__background);
};
NumberControllerSlider.superclass = NumberController;
/**
* Injects default stylesheet for slider elements.
*/
NumberControllerSlider.useDefaultStyles = function() {
css.inject(styleSheet);
};
common.extend(
NumberControllerSlider.prototype,
NumberController.prototype,
{
updateDisplay: function() {
var pct = (this.getValue() - this.__min)/(this.__max - this.__min);
this.__foreground.style.width = pct*100+'%';
return NumberControllerSlider.superclass.prototype.updateDisplay.call(this);
}
}
);
function map(v, i1, i2, o1, o2) {
return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
}
return NumberControllerSlider;
})(dat.controllers.NumberController,
dat.dom.dom,
dat.utils.css,
dat.utils.common,
".slider {\n box-shadow: inset 0 2px 4px rgba(0,0,0,0.15);\n height: 1em;\n border-radius: 1em;\n background-color: #eee;\n padding: 0 0.5em;\n overflow: hidden;\n}\n\n.slider-fg {\n padding: 1px 0 2px 0;\n background-color: #aaa;\n height: 1em;\n margin-left: -0.5em;\n padding-right: 0.5em;\n border-radius: 1em 0 0 1em;\n}\n\n.slider-fg:after {\n display: inline-block;\n border-radius: 1em;\n background-color: #fff;\n border: 1px solid #aaa;\n content: '';\n float: right;\n margin-right: -1em;\n margin-top: -1px;\n height: 0.9em;\n width: 0.9em;\n}");
dat.controllers.FunctionController = (function (Controller, dom, common) {
/**
* @class Provides a GUI interface to fire a specified method, a property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var FunctionController = function(object, property, text) {
FunctionController.superclass.call(this, object, property);
var _this = this;
this.__button = document.createElement('div');
this.__button.innerHTML = text === undefined ? 'Fire' : text;
dom.bind(this.__button, 'click', function(e) {
e.preventDefault();
_this.fire();
return false;
});
dom.addClass(this.__button, 'button');
this.domElement.appendChild(this.__button);
};
FunctionController.superclass = Controller;
common.extend(
FunctionController.prototype,
Controller.prototype,
{
fire: function() {
if (this.__onChange) {
this.__onChange.call(this);
}
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.getValue().call(this.object);
}
}
);
return FunctionController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common);
dat.controllers.BooleanController = (function (Controller, dom, common) {
/**
* @class Provides a checkbox input to alter the boolean property of an object.
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var BooleanController = function(object, property) {
BooleanController.superclass.call(this, object, property);
var _this = this;
this.__prev = this.getValue();
this.__checkbox = document.createElement('input');
this.__checkbox.setAttribute('type', 'checkbox');
dom.bind(this.__checkbox, 'change', onChange, false);
this.domElement.appendChild(this.__checkbox);
// Match original value
this.updateDisplay();
function onChange() {
_this.setValue(!_this.__prev);
}
};
BooleanController.superclass = Controller;
common.extend(
BooleanController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = BooleanController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.__prev = this.getValue();
return toReturn;
},
updateDisplay: function() {
if (this.getValue() === true) {
this.__checkbox.setAttribute('checked', 'checked');
this.__checkbox.checked = true;
} else {
this.__checkbox.checked = false;
}
return BooleanController.superclass.prototype.updateDisplay.call(this);
}
}
);
return BooleanController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common);
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.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.GUI = dat.gui.GUI = (function (css, saveDialogueContents, styleSheet, controllerFactory, Controller, BooleanController, FunctionController, NumberControllerBox, NumberControllerSlider, OptionController, ColorController, requestAnimationFrame, CenteredDiv, dom, common) {
css.inject(styleSheet);
/** Outer-most className for GUI's */
var CSS_NAMESPACE = 'dg';
var HIDE_KEY_CODE = 72;
/** The only value shared between the JS and SCSS. Use caution. */
var CLOSE_BUTTON_HEIGHT = 20;
var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
var SUPPORTS_LOCAL_STORAGE = (function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
var SAVE_DIALOGUE;
/** Have we yet to create an autoPlace GUI? */
var auto_place_virgin = true;
/** Fixed position div that auto place GUI's go inside */
var auto_place_container;
/** Are we hiding the GUI's ? */
var hide = false;
/** GUI's which should be hidden */
var hideable_guis = [];
/**
* A lightweight controller library for JavaScript. It allows you to easily
* manipulate variables and fire functions on the fly.
* @class
*
* @member dat.gui
*
* @param {Object} [params]
* @param {String} [params.name] The name of this GUI.
* @param {Object} [params.load] JSON object representing the saved state of
* this GUI.
* @param {Boolean} [params.auto=true]
* @param {dat.gui.GUI} [params.parent] The GUI I'm nested in.
* @param {Boolean} [params.closed] If true, starts closed
*/
var GUI = function(params) {
var _this = this;
/**
* Outermost DOM Element
* @type DOMElement
*/
this.domElement = document.createElement('div');
this.__ul = document.createElement('ul');
this.domElement.appendChild(this.__ul);
dom.addClass(this.domElement, CSS_NAMESPACE);
/**
* Nested GUI's by name
* @ignore
*/
this.__folders = {};
this.__controllers = [];
/**
* List of objects I'm remembering for save, only used in top level GUI
* @ignore
*/
this.__rememberedObjects = [];
/**
* Maps the index of remembered objects to a map of controllers, only used
* in top level GUI.
*
* @private
* @ignore
*
* @example
* [
* {
* propertyName: Controller,
* anotherPropertyName: Controller
* },
* {
* propertyName: Controller
* }
* ]
*/
this.__rememberedObjectIndecesToControllers = [];
this.__listening = [];
params = params || {};
// Default parameters
params = common.defaults(params, {
autoPlace: true,
width: GUI.DEFAULT_WIDTH
});
params = common.defaults(params, {
resizable: params.autoPlace,
hideable: params.autoPlace
});
if (!common.isUndefined(params.load)) {
// Explicit preset
if (params.preset) params.load.preset = params.preset;
} else {
params.load = { preset: DEFAULT_DEFAULT_PRESET_NAME };
}
if (common.isUndefined(params.parent) && params.hideable) {
hideable_guis.push(this);
}
// Only root level GUI's are resizable.
params.resizable = common.isUndefined(params.parent) && params.resizable;
if (params.autoPlace && common.isUndefined(params.scrollable)) {
params.scrollable = true;
}
// params.scrollable = common.isUndefined(params.parent) && params.scrollable === true;
// Not part of params because I don't want people passing this in via
// constructor. Should be a 'remembered' value.
var use_local_storage =
SUPPORTS_LOCAL_STORAGE &&
localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
Object.defineProperties(this,
/** @lends dat.gui.GUI.prototype */
{
/**
* The parent <code>GUI</code>
* @type dat.gui.GUI
*/
parent: {
get: function() {
return params.parent;
}
},
scrollable: {
get: function() {
return params.scrollable;
}
},
/**
* Handles <code>GUI</code>'s element placement for you
* @type Boolean
*/
autoPlace: {
get: function() {
return params.autoPlace;
}
},
/**
* The identifier for a set of saved values
* @type String
*/
preset: {
get: function() {
if (_this.parent) {
return _this.getRoot().preset;
} else {
return params.load.preset;
}
},
set: function(v) {
if (_this.parent) {
_this.getRoot().preset = v;
} else {
params.load.preset = v;
}
setPresetSelectIndex(this);
_this.revert();
}
},
/**
* The width of <code>GUI</code> element
* @type Number
*/
width: {
get: function() {
return params.width;
},
set: function(v) {
params.width = v;
setWidth(_this, v);
}
},
/**
* The name of <code>GUI</code>. Used for folders. i.e
* a folder's name
* @type String
*/
name: {
get: function() {
return params.name;
},
set: function(v) {
// TODO Check for collisions among sibling folders
params.name = v;
if (title_row_name) {
title_row_name.innerHTML = params.name;
}
}
},
/**
* Whether the <code>GUI</code> is collapsed or not
* @type Boolean
*/
closed: {
get: function() {
return params.closed;
},
set: function(v) {
params.closed = v;
if (params.closed) {
dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
} else {
dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
}
// For browsers that aren't going to respect the CSS transition,
// Lets just check our height against the window height right off
// the bat.
this.onResize();
if (_this.__closeButton) {
_this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
}
}
},
/**
* Contains all presets
* @type Object
*/
load: {
get: function() {
return params.load;
}
},
/**
* Determines whether or not to use <a href="https://developer.mozilla.org/en/DOM/Storage#localStorage">localStorage</a> as the means for
* <code>remember</code>ing
* @type Boolean
*/
useLocalStorage: {
get: function() {
return use_local_storage;
},
set: function(bool) {
if (SUPPORTS_LOCAL_STORAGE) {
use_local_storage = bool;
if (bool) {
dom.bind(window, 'unload', saveToLocalStorage);
} else {
dom.unbind(window, 'unload', saveToLocalStorage);
}
localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
}
}
}
});
// Are we a root level GUI?
if (common.isUndefined(params.parent)) {
params.closed = false;
dom.addClass(this.domElement, GUI.CLASS_MAIN);
dom.makeSelectable(this.domElement, false);
// Are we supposed to be loading locally?
if (SUPPORTS_LOCAL_STORAGE) {
if (use_local_storage) {
_this.useLocalStorage = true;
var saved_gui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
if (saved_gui) {
params.load = JSON.parse(saved_gui);
}
}
}
this.__closeButton = document.createElement('div');
this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
this.domElement.appendChild(this.__closeButton);
dom.bind(this.__closeButton, 'click', function() {
_this.closed = !_this.closed;
});
// Oh, you're a nested GUI!
} else {
if (params.closed === undefined) {
params.closed = true;
}
var title_row_name = document.createTextNode(params.name);
dom.addClass(title_row_name, 'controller-name');
var title_row = addRow(_this, title_row_name);
var on_click_title = function(e) {
e.preventDefault();
_this.closed = !_this.closed;
return false;
};
dom.addClass(this.__ul, GUI.CLASS_CLOSED);
dom.addClass(title_row, 'title');
dom.bind(title_row, 'click', on_click_title);
if (!params.closed) {
this.closed = false;
}
}
if (params.autoPlace) {
if (common.isUndefined(params.parent)) {
if (auto_place_virgin) {
auto_place_container = document.createElement('div');
dom.addClass(auto_place_container, CSS_NAMESPACE);
dom.addClass(auto_place_container, GUI.CLASS_AUTO_PLACE_CONTAINER);
document.body.appendChild(auto_place_container);
auto_place_virgin = false;
}
// Put it in the dom for you.
auto_place_container.appendChild(this.domElement);
// Apply the auto styles
dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
}
// Make it not elastic.
if (!this.parent) setWidth(_this, params.width);
}
dom.bind(window, 'resize', function() { _this.onResize() });
dom.bind(this.__ul, 'webkitTransitionEnd', function() { _this.onResize(); });
dom.bind(this.__ul, 'transitionend', function() { _this.onResize() });
dom.bind(this.__ul, 'oTransitionEnd', function() { _this.onResize() });
this.onResize();
if (params.resizable) {
addResizeHandle(this);
}
function saveToLocalStorage() {
localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
}
var root = _this.getRoot();
function resetWidth() {
var root = _this.getRoot();
root.width += 1;
common.defer(function() {
root.width -= 1;
});
}
if (!params.parent) {
resetWidth();
}
};
GUI.toggleHide = function() {
hide = !hide;
common.each(hideable_guis, function(gui) {
gui.domElement.style.zIndex = hide ? -999 : 999;
gui.domElement.style.opacity = hide ? 0 : 1;
});
};
GUI.CLASS_AUTO_PLACE = 'a';
GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
GUI.CLASS_MAIN = 'main';
GUI.CLASS_CONTROLLER_ROW = 'cr';
GUI.CLASS_TOO_TALL = 'taller-than-window';
GUI.CLASS_CLOSED = 'closed';
GUI.CLASS_CLOSE_BUTTON = 'close-button';
GUI.CLASS_DRAG = 'drag';
GUI.DEFAULT_WIDTH = 245;
GUI.TEXT_CLOSED = 'Close Controls';
GUI.TEXT_OPEN = 'Open Controls';
dom.bind(window, 'keydown', function(e) {
if (document.activeElement.type !== 'text' &&
(e.which === HIDE_KEY_CODE || e.keyCode == HIDE_KEY_CODE)) {
GUI.toggleHide();
}
}, false);
common.extend(
GUI.prototype,
/** @lends dat.gui.GUI */
{
/**
* @param object
* @param property
* @returns {dat.controllers.Controller} The new controller that was added.
* @instance
*/
add: function(object, property) {
return add(
this,
object,
property,
{
factoryArgs: Array.prototype.slice.call(arguments, 2)
}
);
},
/**
* @param object
* @param property
* @returns {dat.controllers.ColorController} The new controller that was added.
* @instance
*/
addColor: function(object, property) {
return add(
this,
object,
property,
{
color: true
}
);
},
/**
* @param controller
* @instance
*/
remove: function(controller) {
// TODO listening?
this.__ul.removeChild(controller.__li);
this.__controllers.slice(this.__controllers.indexOf(controller), 1);
var _this = this;
common.defer(function() {
_this.onResize();
});
},
destroy: function() {
if (this.autoPlace) {
auto_place_container.removeChild(this.domElement);
}
},
/**
* @param name
* @returns {dat.gui.GUI} The new folder.
* @throws {Error} if this GUI already has a folder by the specified
* name
* @instance
*/
addFolder: function(name) {
// We have to prevent collisions on names in order to have a key
// by which to remember saved values
if (this.__folders[name] !== undefined) {
throw new Error('You already have a folder in this GUI by the' +
' name "' + name + '"');
}
var new_gui_params = { name: name, parent: this };
// We need to pass down the autoPlace trait so that we can
// attach event listeners to open/close folder actions to
// ensure that a scrollbar appears if the window is too short.
new_gui_params.autoPlace = this.autoPlace;
// Do we have saved appearance data for this folder?
if (this.load && // Anything loaded?
this.load.folders && // Was my parent a dead-end?
this.load.folders[name]) { // Did daddy remember me?
// Start me closed if I was closed
new_gui_params.closed = this.load.folders[name].closed;
// Pass down the loaded data
new_gui_params.load = this.load.folders[name];
}
var gui = new GUI(new_gui_params);
this.__folders[name] = gui;
var li = addRow(this, gui.domElement);
dom.addClass(li, 'folder');
return gui;
},
open: function() {
this.closed = false;
},
close: function() {
this.closed = true;
},
onResize: function() {
var root = this.getRoot();
if (root.scrollable) {
var top = dom.getOffset(root.__ul).top;
var h = 0;
common.each(root.__ul.childNodes, function(node) {
if (! (root.autoPlace && node === root.__save_row))
h += dom.getHeight(node);
});
if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
} else {
dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = 'auto';
}
}
if (root.__resize_handle) {
common.defer(function() {
root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
});
}
if (root.__closeButton) {
root.__closeButton.style.width = root.width + 'px';
}
},
/**
* Mark objects for saving. The order of these objects cannot change as
* the GUI grows. When remembering new objects, append them to the end
* of the list.
*
* @param {Object...} objects
* @throws {Error} if not called on a top level GUI.
* @instance
*/
remember: function() {
if (common.isUndefined(SAVE_DIALOGUE)) {
SAVE_DIALOGUE = new CenteredDiv();
SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents;
}
if (this.parent) {
throw new Error("You can only call remember on a top level GUI.");
}
var _this = this;
common.each(Array.prototype.slice.call(arguments), function(object) {
if (_this.__rememberedObjects.length == 0) {
addSaveMenu(_this);
}
if (_this.__rememberedObjects.indexOf(object) == -1) {
_this.__rememberedObjects.push(object);
}
});
if (this.autoPlace) {
// Set save row width
setWidth(this, this.width);
}
},
/**
* @returns {dat.gui.GUI} the topmost parent GUI of a nested GUI.
* @instance
*/
getRoot: function() {
var gui = this;
while (gui.parent) {
gui = gui.parent;
}
return gui;
},
/**
* @returns {Object} a JSON object representing the current state of
* this GUI as well as its remembered properties.
* @instance
*/
getSaveObject: function() {
var toReturn = this.load;
toReturn.closed = this.closed;
// Am I remembering any values?
if (this.__rememberedObjects.length > 0) {
toReturn.preset = this.preset;
if (!toReturn.remembered) {
toReturn.remembered = {};
}
toReturn.remembered[this.preset] = getCurrentPreset(this);
}
toReturn.folders = {};
common.each(this.__folders, function(element, key) {
toReturn.folders[key] = element.getSaveObject();
});
return toReturn;
},
save: function() {
if (!this.load.remembered) {
this.load.remembered = {};
}
this.load.remembered[this.preset] = getCurrentPreset(this);
markPresetModified(this, false);
},
saveAs: function(presetName) {
if (!this.load.remembered) {
// Retain default values upon first save
this.load.remembered = {};
this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
}
this.load.remembered[presetName] = getCurrentPreset(this);
this.preset = presetName;
addPresetOption(this, presetName, true);
},
revert: function(gui) {
common.each(this.__controllers, function(controller) {
// Make revert work on Default.
if (!this.getRoot().load.remembered) {
controller.setValue(controller.initialValue);
} else {
recallSavedValue(gui || this.getRoot(), controller);
}
}, this);
common.each(this.__folders, function(folder) {
folder.revert(folder);
});
if (!gui) {
markPresetModified(this.getRoot(), false);
}
},
listen: function(controller) {
var init = this.__listening.length == 0;
this.__listening.push(controller);
if (init) updateDisplays(this.__listening);
}
}
);
function add(gui, object, property, params) {
if (object[property] === undefined) {
throw new Error("Object " + object + " has no property \"" + property + "\"");
}
var controller;
if (params.color) {
controller = new ColorController(object, property);
} else {
var factoryArgs = [object,property].concat(params.factoryArgs);
controller = controllerFactory.apply(gui, factoryArgs);
}
if (params.before instanceof Controller) {
params.before = params.before.__li;
}
recallSavedValue(gui, controller);
dom.addClass(controller.domElement, 'c');
var name = document.createElement('span');
dom.addClass(name, 'property-name');
name.innerHTML = controller.property;
var container = document.createElement('div');
container.appendChild(name);
container.appendChild(controller.domElement);
var li = addRow(gui, container, params.before);
dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
dom.addClass(li, typeof controller.getValue());
augmentController(gui, li, controller);
gui.__controllers.push(controller);
return controller;
}
/**
* Add a row to the end of the GUI or before another row.
*
* @param gui
* @param [dom] If specified, inserts the dom content in the new row
* @param [liBefore] If specified, places the new row before another row
*/
function addRow(gui, dom, liBefore) {
var li = document.createElement('li');
if (dom) li.appendChild(dom);
if (liBefore) {
gui.__ul.insertBefore(li, params.before);
} else {
gui.__ul.appendChild(li);
}
gui.onResize();
return li;
}
function augmentController(gui, li, controller) {
controller.__li = li;
controller.__gui = gui;
common.extend(controller, {
options: function(options) {
if (arguments.length > 1) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [common.toArray(arguments)]
}
);
}
if (common.isArray(options) || common.isObject(options)) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [options]
}
);
}
},
name: function(v) {
controller.__li.firstElementChild.firstElementChild.innerHTML = v;
return controller;
},
listen: function() {
controller.__gui.listen(controller);
return controller;
},
remove: function() {
controller.__gui.remove(controller);
return controller;
}
});
// All sliders should be accompanied by a box.
if (controller instanceof NumberControllerSlider) {
var box = new NumberControllerBox(controller.object, controller.property,
{ min: controller.__min, max: controller.__max, step: controller.__step });
common.each(['updateDisplay', 'onChange', 'onFinishChange'], function(method) {
var pc = controller[method];
var pb = box[method];
controller[method] = box[method] = function() {
var args = Array.prototype.slice.call(arguments);
pc.apply(controller, args);
return pb.apply(box, args);
}
});
dom.addClass(li, 'has-slider');
controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
}
else if (controller instanceof NumberControllerBox) {
var r = function(returned) {
// Have we defined both boundaries?
if (common.isNumber(controller.__min) && common.isNumber(controller.__max)) {
// Well, then lets just replace this with a slider.
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [controller.__min, controller.__max, controller.__step]
});
}
return returned;
};
controller.min = common.compose(r, controller.min);
controller.max = common.compose(r, controller.max);
}
else if (controller instanceof BooleanController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__checkbox, 'click');
});
dom.bind(controller.__checkbox, 'click', function(e) {
e.stopPropagation(); // Prevents double-toggle
})
}
else if (controller instanceof FunctionController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__button, 'click');
});
dom.bind(li, 'mouseover', function() {
dom.addClass(controller.__button, 'hover');
});
dom.bind(li, 'mouseout', function() {
dom.removeClass(controller.__button, 'hover');
});
}
else if (controller instanceof ColorController) {
dom.addClass(li, 'color');
controller.updateDisplay = common.compose(function(r) {
li.style.borderLeftColor = controller.__color.toString();
return r;
}, controller.updateDisplay);
controller.updateDisplay();
}
controller.setValue = common.compose(function(r) {
if (gui.getRoot().__preset_select && controller.isModified()) {
markPresetModified(gui.getRoot(), true);
}
return r;
}, controller.setValue);
}
function recallSavedValue(gui, controller) {
// Find the topmost GUI, that's where remembered objects live.
var root = gui.getRoot();
// Does the object we're controlling match anything we've been told to
// remember?
var matched_index = root.__rememberedObjects.indexOf(controller.object);
// Why yes, it does!
if (matched_index != -1) {
// Let me fetch a map of controllers for thcommon.isObject.
var controller_map =
root.__rememberedObjectIndecesToControllers[matched_index];
// Ohp, I believe this is the first controller we've created for this
// object. Lets make the map fresh.
if (controller_map === undefined) {
controller_map = {};
root.__rememberedObjectIndecesToControllers[matched_index] =
controller_map;
}
// Keep track of this controller
controller_map[controller.property] = controller;
// Okay, now have we saved any values for this controller?
if (root.load && root.load.remembered) {
var preset_map = root.load.remembered;
// Which preset are we trying to load?
var preset;
if (preset_map[gui.preset]) {
preset = preset_map[gui.preset];
} else if (preset_map[DEFAULT_DEFAULT_PRESET_NAME]) {
// Uhh, you can have the default instead?
preset = preset_map[DEFAULT_DEFAULT_PRESET_NAME];
} else {
// Nada.
return;
}
// Did the loaded object remember thcommon.isObject?
if (preset[matched_index] &&
// Did we remember this particular property?
preset[matched_index][controller.property] !== undefined) {
// We did remember something for this guy ...
var value = preset[matched_index][controller.property];
// And that's what it is.
controller.initialValue = value;
controller.setValue(value);
}
}
}
}
function getLocalStorageHash(gui, key) {
// TODO how does this deal with multiple GUI's?
return document.location.href + '.' + key;
}
function addSaveMenu(gui) {
var div = gui.__save_row = document.createElement('li');
dom.addClass(gui.domElement, 'has-save');
gui.__ul.insertBefore(div, gui.__ul.firstChild);
dom.addClass(div, 'save-row');
var gears = document.createElement('span');
gears.innerHTML = ' ';
dom.addClass(gears, 'button gears');
// TODO replace with FunctionController
var button = document.createElement('span');
button.innerHTML = 'Save';
dom.addClass(button, 'button');
dom.addClass(button, 'save');
var button2 = document.createElement('span');
button2.innerHTML = 'New';
dom.addClass(button2, 'button');
dom.addClass(button2, 'save-as');
var button3 = document.createElement('span');
button3.innerHTML = 'Revert';
dom.addClass(button3, 'button');
dom.addClass(button3, 'revert');
var select = gui.__preset_select = document.createElement('select');
if (gui.load && gui.load.remembered) {
common.each(gui.load.remembered, function(value, key) {
addPresetOption(gui, key, key == gui.preset);
});
} else {
addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
}
dom.bind(select, 'change', function() {
for (var index = 0; index < gui.__preset_select.length; index++) {
gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
}
gui.preset = this.value;
});
div.appendChild(select);
div.appendChild(gears);
div.appendChild(button);
div.appendChild(button2);
div.appendChild(button3);
if (SUPPORTS_LOCAL_STORAGE) {
var saveLocally = document.getElementById('dg-save-locally');
var explain = document.getElementById('dg-local-explain');
saveLocally.style.display = 'block';
var localStorageCheckBox = document.getElementById('dg-local-storage');
if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
localStorageCheckBox.setAttribute('checked', 'checked');
}
function showHideExplain() {
explain.style.display = gui.useLocalStorage ? 'block' : 'none';
}
showHideExplain();
// TODO: Use a boolean controller, fool!
dom.bind(localStorageCheckBox, 'change', function() {
gui.useLocalStorage = !gui.useLocalStorage;
showHideExplain();
});
}
var newConstructorTextArea = document.getElementById('dg-new-constructor');
dom.bind(newConstructorTextArea, 'keydown', function(e) {
if (e.metaKey && (e.which === 67 || e.keyCode == 67)) {
SAVE_DIALOGUE.hide();
}
});
dom.bind(gears, 'click', function() {
newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
SAVE_DIALOGUE.show();
newConstructorTextArea.focus();
newConstructorTextArea.select();
});
dom.bind(button, 'click', function() {
gui.save();
});
dom.bind(button2, 'click', function() {
var presetName = prompt('Enter a new preset name.');
if (presetName) gui.saveAs(presetName);
});
dom.bind(button3, 'click', function() {
gui.revert();
});
// div.appendChild(button2);
}
function addResizeHandle(gui) {
gui.__resize_handle = document.createElement('div');
common.extend(gui.__resize_handle.style, {
width: '6px',
marginLeft: '-3px',
height: '200px',
cursor: 'ew-resize',
position: 'absolute'
// border: '1px solid blue'
});
var pmouseX;
dom.bind(gui.__resize_handle, 'mousedown', dragStart);
dom.bind(gui.__closeButton, 'mousedown', dragStart);
gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
function dragStart(e) {
e.preventDefault();
pmouseX = e.clientX;
dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.bind(window, 'mousemove', drag);
dom.bind(window, 'mouseup', dragStop);
return false;
}
function drag(e) {
e.preventDefault();
gui.width += pmouseX - e.clientX;
gui.onResize();
pmouseX = e.clientX;
return false;
}
function dragStop() {
dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.unbind(window, 'mousemove', drag);
dom.unbind(window, 'mouseup', dragStop);
}
}
function setWidth(gui, w) {
gui.domElement.style.width = w + 'px';
// Auto placed save-rows are position fixed, so we have to
// set the width manually if we want it to bleed to the edge
if (gui.__save_row && gui.autoPlace) {
gui.__save_row.style.width = w + 'px';
}if (gui.__closeButton) {
gui.__closeButton.style.width = w + 'px';
}
}
function getCurrentPreset(gui, useInitialValues) {
var toReturn = {};
// For each object I'm remembering
common.each(gui.__rememberedObjects, function(val, index) {
var saved_values = {};
// The controllers I've made for thcommon.isObject by property
var controller_map =
gui.__rememberedObjectIndecesToControllers[index];
// Remember each value for each property
common.each(controller_map, function(controller, property) {
saved_values[property] = useInitialValues ? controller.initialValue : controller.getValue();
});
// Save the values for thcommon.isObject
toReturn[index] = saved_values;
});
return toReturn;
}
function addPresetOption(gui, name, setSelected) {
var opt = document.createElement('option');
opt.innerHTML = name;
opt.value = name;
gui.__preset_select.appendChild(opt);
if (setSelected) {
gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
}
}
function setPresetSelectIndex(gui) {
for (var index = 0; index < gui.__preset_select.length; index++) {
if (gui.__preset_select[index].value == gui.preset) {
gui.__preset_select.selectedIndex = index;
}
}
}
function markPresetModified(gui, modified) {
var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
// console.log('mark', modified, opt);
if (modified) {
opt.innerHTML = opt.value + "*";
} else {
opt.innerHTML = opt.value;
}
}
function updateDisplays(controllerArray) {
if (controllerArray.length != 0) {
requestAnimationFrame(function() {
updateDisplays(controllerArray);
});
}
common.each(controllerArray, function(c) {
c.updateDisplay();
});
}
return GUI;
})(dat.utils.css,
"<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n \n </div>\n \n </div>\n\n</div>",
".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity 0.1s linear;-o-transition:opacity 0.1s linear;-moz-transition:opacity 0.1s linear;transition:opacity 0.1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity 0.1s linear;-o-transition:opacity 0.1s linear;-moz-transition:opacity 0.1s linear;transition:opacity 0.1s linear;border:0;position:absolute;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-x:hidden}.dg.a.has-save ul{margin-top:27px}.dg.a.has-save ul.closed{margin-top:0}.dg.a .save-row{position:fixed;top:0;z-index:1002}.dg li{-webkit-transition:height 0.1s ease-out;-o-transition:height 0.1s ease-out;-moz-transition:height 0.1s ease-out;transition:height 0.1s ease-out}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;overflow:hidden;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li > *{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:9px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2fa1d6}.dg .cr.number input[type=text]{color:#2fa1d6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2fa1d6}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n",
dat.controllers.factory = (function (OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) {
return function(object, property) {
var initialValue = object[property];
// Providing options?
if (common.isArray(arguments[2]) || common.isObject(arguments[2])) {
return new OptionController(object, property, arguments[2]);
}
// Providing a map?
if (common.isNumber(initialValue)) {
if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) {
// Has min and max.
return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
} else {
return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] });
}
}
if (common.isString(initialValue)) {
return new StringController(object, property);
}
if (common.isFunction(initialValue)) {
return new FunctionController(object, property, '');
}
if (common.isBoolean(initialValue)) {
return new BooleanController(object, property);
}
}
})(dat.controllers.OptionController,
dat.controllers.NumberControllerBox,
dat.controllers.NumberControllerSlider,
dat.controllers.StringController = (function (Controller, dom, common) {
/**
* @class Provides a text input to alter the string property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var StringController = function(object, property) {
StringController.superclass.call(this, object, property);
var _this = this;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
dom.bind(this.__input, 'keyup', onChange);
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) {
this.blur();
}
});
function onChange() {
_this.setValue(_this.__input.value);
}
function onBlur() {
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
StringController.superclass = Controller;
common.extend(
StringController.prototype,
Controller.prototype,
{
updateDisplay: function() {
// Stops the caret from moving on account of:
// keyup -> setValue -> updateDisplay
if (!dom.isActive(this.__input)) {
this.__input.value = this.getValue();
}
return StringController.superclass.prototype.updateDisplay.call(this);
}
}
);
return StringController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common),
dat.controllers.FunctionController,
dat.controllers.BooleanController,
dat.utils.common),
dat.controllers.Controller,
dat.controllers.BooleanController,
dat.controllers.FunctionController,
dat.controllers.NumberControllerBox,
dat.controllers.NumberControllerSlider,
dat.controllers.OptionController,
dat.controllers.ColorController = (function (Controller, dom, Color, interpret, common) {
var ColorController = function(object, property) {
ColorController.superclass.call(this, object, property);
this.__color = new Color(this.getValue());
this.__temp = new Color(0);
var _this = this;
this.domElement = document.createElement('div');
dom.makeSelectable(this.domElement, false);
this.__selector = document.createElement('div');
this.__selector.className = 'selector';
this.__saturation_field = document.createElement('div');
this.__saturation_field.className = 'saturation-field';
this.__field_knob = document.createElement('div');
this.__field_knob.className = 'field-knob';
this.__field_knob_border = '2px solid ';
this.__hue_knob = document.createElement('div');
this.__hue_knob.className = 'hue-knob';
this.__hue_field = document.createElement('div');
this.__hue_field.className = 'hue-field';
this.__input = document.createElement('input');
this.__input.type = 'text';
this.__input_textShadow = '0 1px 1px ';
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) { // on enter
onBlur.call(this);
}
});
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__selector, 'mousedown', function(e) {
dom
.addClass(this, 'drag')
.bind(window, 'mouseup', function(e) {
dom.removeClass(_this.__selector, 'drag');
});
});
var value_field = document.createElement('div');
common.extend(this.__selector.style, {
width: '122px',
height: '102px',
padding: '3px',
backgroundColor: '#222',
boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
});
common.extend(this.__field_knob.style, {
position: 'absolute',
width: '12px',
height: '12px',
border: this.__field_knob_border + (this.__color.v < .5 ? '#fff' : '#000'),
boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
borderRadius: '12px',
zIndex: 1
});
common.extend(this.__hue_knob.style, {
position: 'absolute',
width: '15px',
height: '2px',
borderRight: '4px solid #fff',
zIndex: 1
});
common.extend(this.__saturation_field.style, {
width: '100px',
height: '100px',
border: '1px solid #555',
marginRight: '3px',
display: 'inline-block',
cursor: 'pointer'
});
common.extend(value_field.style, {
width: '100%',
height: '100%',
background: 'none'
});
linearGradient(value_field, 'top', 'rgba(0,0,0,0)', '#000');
common.extend(this.__hue_field.style, {
width: '15px',
height: '100px',
display: 'inline-block',
border: '1px solid #555',
cursor: 'ns-resize'
});
hueGradient(this.__hue_field);
common.extend(this.__input.style, {
outline: 'none',
// width: '120px',
textAlign: 'center',
// padding: '4px',
// marginBottom: '6px',
color: '#fff',
border: 0,
fontWeight: 'bold',
textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)'
});
dom.bind(this.__saturation_field, 'mousedown', fieldDown);
dom.bind(this.__field_knob, 'mousedown', fieldDown);
dom.bind(this.__hue_field, 'mousedown', function(e) {
setH(e);
dom.bind(window, 'mousemove', setH);
dom.bind(window, 'mouseup', unbindH);
});
function fieldDown(e) {
setSV(e);
// document.body.style.cursor = 'none';
dom.bind(window, 'mousemove', setSV);
dom.bind(window, 'mouseup', unbindSV);
}
function unbindSV() {
dom.unbind(window, 'mousemove', setSV);
dom.unbind(window, 'mouseup', unbindSV);
// document.body.style.cursor = 'default';
}
function onBlur() {
var i = interpret(this.value);
if (i !== false) {
_this.__color.__state = i;
_this.setValue(_this.__color.toOriginal());
} else {
this.value = _this.__color.toString();
}
}
function unbindH() {
dom.unbind(window, 'mousemove', setH);
dom.unbind(window, 'mouseup', unbindH);
}
this.__saturation_field.appendChild(value_field);
this.__selector.appendChild(this.__field_knob);
this.__selector.appendChild(this.__saturation_field);
this.__selector.appendChild(this.__hue_field);
this.__hue_field.appendChild(this.__hue_knob);
this.domElement.appendChild(this.__input);
this.domElement.appendChild(this.__selector);
this.updateDisplay();
function setSV(e) {
e.preventDefault();
var w = dom.getWidth(_this.__saturation_field);
var o = dom.getOffset(_this.__saturation_field);
var s = (e.clientX - o.left + document.body.scrollLeft) / w;
var v = 1 - (e.clientY - o.top + document.body.scrollTop) / w;
if (v > 1) v = 1;
else if (v < 0) v = 0;
if (s > 1) s = 1;
else if (s < 0) s = 0;
_this.__color.v = v;
_this.__color.s = s;
_this.setValue(_this.__color.toOriginal());
return false;
}
function setH(e) {
e.preventDefault();
var s = dom.getHeight(_this.__hue_field);
var o = dom.getOffset(_this.__hue_field);
var h = 1 - (e.clientY - o.top + document.body.scrollTop) / s;
if (h > 1) h = 1;
else if (h < 0) h = 0;
_this.__color.h = h * 360;
_this.setValue(_this.__color.toOriginal());
return false;
}
};
ColorController.superclass = Controller;
common.extend(
ColorController.prototype,
Controller.prototype,
{
updateDisplay: function() {
var i = interpret(this.getValue());
if (i !== false) {
var mismatch = false;
// Check for mismatch on the interpreted value.
common.each(Color.COMPONENTS, function(component) {
if (!common.isUndefined(i[component]) &&
!common.isUndefined(this.__color.__state[component]) &&
i[component] !== this.__color.__state[component]) {
mismatch = true;
return {}; // break
}
}, this);
// If nothing diverges, we keep our previous values
// for statefulness, otherwise we recalculate fresh
if (mismatch) {
common.extend(this.__color.__state, i);
}
}
common.extend(this.__temp.__state, this.__color.__state);
this.__temp.a = 1;
var flip = (this.__color.v < .5 || this.__color.s > .5) ? 255 : 0;
var _flip = 255 - flip;
common.extend(this.__field_knob.style, {
marginLeft: 100 * this.__color.s - 7 + 'px',
marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
backgroundColor: this.__temp.toString(),
border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip +')'
});
this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px'
this.__temp.s = 1;
this.__temp.v = 1;
linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString());
common.extend(this.__input.style, {
backgroundColor: this.__input.value = this.__color.toString(),
color: 'rgb(' + flip + ',' + flip + ',' + flip +')',
textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip +',.7)'
});
}
}
);
var vendors = ['-moz-','-o-','-webkit-','-ms-',''];
function linearGradient(elem, x, a, b) {
elem.style.background = '';
common.each(vendors, function(vendor) {
elem.style.cssText += 'background: ' + vendor + 'linear-gradient('+x+', '+a+' 0%, ' + b + ' 100%); ';
});
}
function hueGradient(elem) {
elem.style.background = '';
elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);'
elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
}
return ColorController;
})(dat.controllers.Controller,
dat.dom.dom,
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,
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),
dat.color.interpret,
dat.utils.common),
dat.utils.requestAnimationFrame = (function () {
/**
* requirejs version of Paul Irish's RequestAnimationFrame
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
window.setTimeout(callback, 1000 / 60);
};
})(),
dat.dom.CenteredDiv = (function (dom, common) {
var CenteredDiv = function() {
this.backgroundElement = document.createElement('div');
common.extend(this.backgroundElement.style, {
backgroundColor: 'rgba(0,0,0,0.8)',
top: 0,
left: 0,
display: 'none',
zIndex: '1000',
opacity: 0,
WebkitTransition: 'opacity 0.2s linear'
});
dom.makeFullscreen(this.backgroundElement);
this.backgroundElement.style.position = 'fixed';
this.domElement = document.createElement('div');
common.extend(this.domElement.style, {
position: 'fixed',
display: 'none',
zIndex: '1001',
opacity: 0,
WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear'
});
document.body.appendChild(this.backgroundElement);
document.body.appendChild(this.domElement);
var _this = this;
dom.bind(this.backgroundElement, 'click', function() {
_this.hide();
});
};
CenteredDiv.prototype.show = function() {
var _this = this;
this.backgroundElement.style.display = 'block';
this.domElement.style.display = 'block';
this.domElement.style.opacity = 0;
// this.domElement.style.top = '52%';
this.domElement.style.webkitTransform = 'scale(1.1)';
this.layout();
common.defer(function() {
_this.backgroundElement.style.opacity = 1;
_this.domElement.style.opacity = 1;
_this.domElement.style.webkitTransform = 'scale(1)';
});
};
CenteredDiv.prototype.hide = function() {
var _this = this;
var hide = function() {
_this.domElement.style.display = 'none';
_this.backgroundElement.style.display = 'none';
dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
dom.unbind(_this.domElement, 'transitionend', hide);
dom.unbind(_this.domElement, 'oTransitionEnd', hide);
};
dom.bind(this.domElement, 'webkitTransitionEnd', hide);
dom.bind(this.domElement, 'transitionend', hide);
dom.bind(this.domElement, 'oTransitionEnd', hide);
this.backgroundElement.style.opacity = 0;
// this.domElement.style.top = '48%';
this.domElement.style.opacity = 0;
this.domElement.style.webkitTransform = 'scale(1.1)';
};
CenteredDiv.prototype.layout = function() {
this.domElement.style.left = window.innerWidth/2 - dom.getWidth(this.domElement) / 2 + 'px';
this.domElement.style.top = window.innerHeight/2 - dom.getHeight(this.domElement) / 2 + 'px';
};
function lockScroll(e) {
console.log(e);
}
return CenteredDiv;
})(dat.dom.dom,
dat.utils.common),
dat.dom.dom,
dat.utils.common); | JavaScript |
// Backbone.js 0.5.3
// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://documentcloud.github.com/backbone
(function(){
// Initial Setup
// -------------
// Save a reference to the global object.
var root = this;
// Save the previous value of the `Backbone` variable.
var previousBackbone = root.Backbone;
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = root.Backbone = {};
}
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '0.5.3';
// Require Underscore, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._;
// For Backbone's purposes, jQuery or Zepto owns the `$` variable.
var $ = root.jQuery || root.Zepto;
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option will
// fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a
// `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// -----------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may `bind` or `unbind` a callback function to an event;
// `trigger`-ing an event fires all callbacks in succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.bind('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
Backbone.Events = {
// Bind an event, specified by a string name, `ev`, to a `callback` function.
// Passing `"all"` will bind the callback to all events fired.
bind : function(ev, callback, context) {
var calls = this._callbacks || (this._callbacks = {});
var list = calls[ev] || (calls[ev] = []);
list.push([callback, context]);
return this;
},
// Remove one or many callbacks. If `callback` is null, removes all
// callbacks for the event. If `ev` is null, removes all bound callbacks
// for all events.
unbind : function(ev, callback) {
var calls;
if (!ev) {
this._callbacks = {};
} else if (calls = this._callbacks) {
if (!callback) {
calls[ev] = [];
} else {
var list = calls[ev];
if (!list) return this;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i] && callback === list[i][0]) {
list[i] = null;
break;
}
}
}
}
return this;
},
// Trigger an event, firing all bound callbacks. Callbacks are passed the
// same arguments as `trigger` is, apart from the event name.
// Listening for `"all"` passes the true event name as the first argument.
trigger : function(eventName) {
var list, calls, ev, callback, args;
var both = 2;
if (!(calls = this._callbacks)) return this;
while (both--) {
ev = both ? eventName : 'all';
if (list = calls[ev]) {
for (var i = 0, l = list.length; i < l; i++) {
if (!(callback = list[i])) {
list.splice(i, 1); i--; l--;
} else {
args = both ? Array.prototype.slice.call(arguments, 1) : arguments;
callback[0].apply(callback[1] || this, args);
}
}
}
}
return this;
}
};
// Backbone.Model
// --------------
// Create a new model, with defined attributes. A client id (`cid`)
// is automatically generated and assigned for you.
Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
if (defaults = this.defaults) {
if (_.isFunction(defaults)) defaults = defaults.call(this);
attributes = _.extend({}, defaults, attributes);
}
this.attributes = {};
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.set(attributes, {silent : true});
this._changed = false;
this._previousAttributes = _.clone(this.attributes);
if (options && options.collection) this.collection = options.collection;
this.initialize(attributes, options);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Backbone.Model.prototype, Backbone.Events, {
// A snapshot of the model's previous attributes, taken immediately
// after the last `"change"` event was fired.
_previousAttributes : null,
// Has the item been changed since the last `"change"` event?
_changed : false,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute : 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize : function(){},
// Return a copy of the model's `attributes` object.
toJSON : function() {
return _.clone(this.attributes);
},
// Get the value of an attribute.
get : function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape : function(attr) {
var html;
if (html = this._escapedAttributes[attr]) return html;
var val = this.attributes[attr];
return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val);
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has : function(attr) {
return this.attributes[attr] != null;
},
// Set a hash of model attributes on the object, firing `"change"` unless you
// choose to silence it.
set : function(attrs, options) {
// Extract attributes and options.
options || (options = {});
if (!attrs) return this;
if (attrs.attributes) attrs = attrs.attributes;
var now = this.attributes, escaped = this._escapedAttributes;
// Run validation.
if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// We're about to start triggering change events.
var alreadyChanging = this._changing;
this._changing = true;
// Update attributes.
for (var attr in attrs) {
var val = attrs[attr];
if (!_.isEqual(now[attr], val)) {
now[attr] = val;
delete escaped[attr];
this._changed = true;
if (!options.silent) this.trigger('change:' + attr, this, val, options);
}
}
// Fire the `"change"` event, if the model has been changed.
if (!alreadyChanging && !options.silent && this._changed) this.change(options);
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"` unless you choose
// to silence it. `unset` is a noop if the attribute doesn't exist.
unset : function(attr, options) {
if (!(attr in this.attributes)) return this;
options || (options = {});
var value = this.attributes[attr];
// Run validation.
var validObj = {};
validObj[attr] = void 0;
if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
// Remove the attribute.
delete this.attributes[attr];
delete this._escapedAttributes[attr];
if (attr == this.idAttribute) delete this.id;
this._changed = true;
if (!options.silent) {
this.trigger('change:' + attr, this, void 0, options);
this.change(options);
}
return this;
},
// Clear all attributes on the model, firing `"change"` unless you choose
// to silence it.
clear : function(options) {
options || (options = {});
var attr;
var old = this.attributes;
// Run validation.
var validObj = {};
for (attr in old) validObj[attr] = void 0;
if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
this.attributes = {};
this._escapedAttributes = {};
this._changed = true;
if (!options.silent) {
for (attr in old) {
this.trigger('change:' + attr, this, void 0, options);
}
this.change(options);
}
return this;
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overriden,
// triggering a `"change"` event.
fetch : function(options) {
options || (options = {});
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
if (!model.set(model.parse(resp, xhr), options)) return false;
if (success) success(model, resp);
};
options.error = wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save : function(attrs, options) {
options || (options = {});
if (attrs && !this.set(attrs, options)) return false;
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
if (!model.set(model.parse(resp, xhr), options)) return false;
if (success) success(model, resp, xhr);
};
options.error = wrapError(options.error, model, options);
var method = this.isNew() ? 'create' : 'update';
return (this.sync || Backbone.sync).call(this, method, this, options);
},
// Destroy this model on the server if it was already persisted. Upon success, the model is removed
// from its collection, if it has one.
destroy : function(options) {
options || (options = {});
if (this.isNew()) return this.trigger('destroy', this, this.collection, options);
var model = this;
var success = options.success;
options.success = function(resp) {
model.trigger('destroy', model, model.collection, options);
if (success) success(model, resp);
};
options.error = wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'delete', this, options);
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url : function() {
var base = getUrl(this.collection) || this.urlRoot || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse : function(resp, xhr) {
return resp;
},
// Create a new model with identical attributes to this one.
clone : function() {
return new this.constructor(this);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew : function() {
return this.id == null;
},
// Call this method to manually fire a `change` event for this model.
// Calling this will cause all objects observing the model to update.
change : function(options) {
this.trigger('change', this, options);
this._previousAttributes = _.clone(this.attributes);
this._changed = false;
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged : function(attr) {
if (attr) return this._previousAttributes[attr] != this.attributes[attr];
return this._changed;
},
// Return an object containing all the attributes that have changed, or false
// if there are no changed attributes. Useful for determining what parts of a
// view need to be updated and/or what attributes need to be persisted to
// the server.
changedAttributes : function(now) {
now || (now = this.attributes);
var old = this._previousAttributes;
var changed = false;
for (var attr in now) {
if (!_.isEqual(old[attr], now[attr])) {
changed = changed || {};
changed[attr] = now[attr];
}
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous : function(attr) {
if (!attr || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes : function() {
return _.clone(this._previousAttributes);
},
// Run validation against a set of incoming attributes, returning `true`
// if all is well. If a specific `error` callback has been passed,
// call that instead of firing the general `"error"` event.
_performValidation : function(attrs, options) {
var error = this.validate(attrs);
if (error) {
if (options.error) {
options.error(this, error, options);
} else {
this.trigger('error', this, error, options);
}
return false;
}
return true;
}
});
// Backbone.Collection
// -------------------
// Provides a standard collection class for our sets of models, ordered
// or unordered. If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
Backbone.Collection = function(models, options) {
options || (options = {});
if (options.comparator) this.comparator = options.comparator;
_.bindAll(this, '_onModelEvent', '_removeReference');
this._reset();
if (models) this.reset(models, {silent: true});
this.initialize.apply(this, arguments);
};
// Define the Collection's inheritable methods.
_.extend(Backbone.Collection.prototype, Backbone.Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model : Backbone.Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize : function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON : function() {
return this.map(function(model){ return model.toJSON(); });
},
// Add a model, or list of models to the set. Pass **silent** to avoid
// firing the `added` event for every new model.
add : function(models, options) {
if (_.isArray(models)) {
for (var i = 0, l = models.length; i < l; i++) {
this._add(models[i], options);
}
} else {
this._add(models, options);
}
return this;
},
// Remove a model, or a list of models from the set. Pass silent to avoid
// firing the `removed` event for every model removed.
remove : function(models, options) {
if (_.isArray(models)) {
for (var i = 0, l = models.length; i < l; i++) {
this._remove(models[i], options);
}
} else {
this._remove(models, options);
}
return this;
},
// Get a model from the set by id.
get : function(id) {
if (id == null) return null;
return this._byId[id.id != null ? id.id : id];
},
// Get a model from the set by client id.
getByCid : function(cid) {
return cid && this._byCid[cid.cid || cid];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Force the collection to re-sort itself. You don't need to call this under normal
// circumstances, as the set will maintain sort order as each item is added.
sort : function(options) {
options || (options = {});
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
this.models = this.sortBy(this.comparator);
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck : function(attr) {
return _.map(this.models, function(model){ return model.get(attr); });
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any `added` or `removed` events. Fires `reset` when finished.
reset : function(models, options) {
models || (models = []);
options || (options = {});
this.each(this._removeReference);
this._reset();
this.add(models, {silent: true});
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `add: true` is passed, appends the
// models to the collection instead of resetting.
fetch : function(options) {
options || (options = {});
var collection = this;
var success = options.success;
options.success = function(resp, status, xhr) {
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
if (success) success(collection, resp);
};
options.error = wrapError(options.error, collection, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
},
// Create a new instance of a model in this collection. After the model
// has been created on the server, it will be added to the collection.
// Returns the model, or 'false' if validation on a new model fails.
create : function(model, options) {
var coll = this;
options || (options = {});
model = this._prepareModel(model, options);
if (!model) return false;
var success = options.success;
options.success = function(nextModel, resp, xhr) {
coll.add(nextModel, options);
if (success) success(nextModel, resp, xhr);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse : function(resp, xhr) {
return resp;
},
// Proxy to _'s chain. Can't be proxied the same way the rest of the
// underscore methods are proxied because it relies on the underscore
// constructor.
chain: function () {
return _(this.models).chain();
},
// Reset all internal state. Called when the collection is reset.
_reset : function(options) {
this.length = 0;
this.models = [];
this._byId = {};
this._byCid = {};
},
// Prepare a model to be added to this collection
_prepareModel: function(model, options) {
if (!(model instanceof Backbone.Model)) {
var attrs = model;
model = new this.model(attrs, {collection: this});
if (model.validate && !model._performValidation(attrs, options)) model = false;
} else if (!model.collection) {
model.collection = this;
}
return model;
},
// Internal implementation of adding a single model to the set, updating
// hash indexes for `id` and `cid` lookups.
// Returns the model, or 'false' if validation on a new model fails.
_add : function(model, options) {
options || (options = {});
model = this._prepareModel(model, options);
if (!model) return false;
var already = this.getByCid(model);
if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
this._byId[model.id] = model;
this._byCid[model.cid] = model;
var index = options.at != null ? options.at :
this.comparator ? this.sortedIndex(model, this.comparator) :
this.length;
this.models.splice(index, 0, model);
model.bind('all', this._onModelEvent);
this.length++;
if (!options.silent) model.trigger('add', model, this, options);
return model;
},
// Internal implementation of removing a single model from the set, updating
// hash indexes for `id` and `cid` lookups.
_remove : function(model, options) {
options || (options = {});
model = this.getByCid(model) || this.get(model);
if (!model) return null;
delete this._byId[model.id];
delete this._byCid[model.cid];
this.models.splice(this.indexOf(model), 1);
this.length--;
if (!options.silent) model.trigger('remove', model, this, options);
this._removeReference(model);
return model;
},
// Internal method to remove a model's ties to a collection.
_removeReference : function(model) {
if (this == model.collection) {
delete model.collection;
}
model.unbind('all', this._onModelEvent);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent : function(ev, model, collection, options) {
if ((ev == 'add' || ev == 'remove') && collection != this) return;
if (ev == 'destroy') {
this._remove(model, options);
}
if (model && ev === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty', 'groupBy'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Backbone.Collection.prototype[method] = function() {
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
};
});
// Backbone.Router
// -------------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var namedParam = /:([\w\d]+)/g;
var splatParam = /\*([\w\d]+)/g;
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Backbone.Router.prototype, Backbone.Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize : function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route : function(route, name, callback) {
Backbone.history || (Backbone.history = new Backbone.History);
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
}, this));
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate : function(fragment, triggerRoute) {
Backbone.history.navigate(fragment, triggerRoute);
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes : function() {
if (!this.routes) return;
var routes = [];
for (var route in this.routes) {
routes.unshift([route, this.routes[route]]);
}
for (var i = 0, l = routes.length; i < l; i++) {
this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp : function(route) {
route = route.replace(escapeRegExp, "\\$&")
.replace(namedParam, "([^\/]*)")
.replace(splatParam, "(.*?)");
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted parameters.
_extractParameters : function(route, fragment) {
return route.exec(fragment).slice(1);
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on URL fragments. If the
// browser does not support `onhashchange`, falls back to polling.
Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
};
// Cached regex for cleaning hashes.
var hashStrip = /^#*/;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Has the history handling already been started?
var historyStarted = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(Backbone.History.prototype, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment : function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || forcePushState) {
fragment = window.location.pathname;
var search = window.location.search;
if (search) fragment += search;
if (fragment.indexOf(this.options.root) == 0) fragment = fragment.substr(this.options.root.length);
} else {
fragment = window.location.hash;
}
}
return decodeURIComponent(fragment.replace(hashStrip, ''));
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start : function(options) {
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
if (historyStarted) throw new Error("Backbone.history has already been started");
this.options = _.extend({}, {root: '/'}, this.options, options);
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
if (oldIE) {
this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
$(window).bind('popstate', this.checkUrl);
} else if ('onhashchange' in window && !oldIE) {
$(window).bind('hashchange', this.checkUrl);
} else {
setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
historyStarted = true;
var loc = window.location;
var atRoot = loc.pathname == this.options.root;
if (this._wantsPushState && !this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
window.location.replace(this.options.root + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
this.fragment = loc.hash.replace(hashStrip, '');
window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
}
if (!this.options.silent) {
return this.loadUrl();
}
},
// Add a route to be tested when the fragment changes. Routes added later may
// override previous routes.
route : function(route, callback) {
this.handlers.unshift({route : route, callback : callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl : function(e) {
var current = this.getFragment();
if (current == this.fragment && this.iframe) current = this.getFragment(this.iframe.location.hash);
if (current == this.fragment || current == decodeURIComponent(this.fragment)) return false;
if (this.iframe) this.navigate(current);
this.loadUrl() || this.loadUrl(window.location.hash);
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl : function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
// Save a fragment into the hash history. You are responsible for properly
// URL-encoding the fragment in advance. This does not trigger
// a `hashchange` event.
navigate : function(fragment, triggerRoute) {
var frag = (fragment || '').replace(hashStrip, '');
if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return;
if (this._hasPushState) {
var loc = window.location;
if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
this.fragment = frag;
window.history.pushState({}, document.title, loc.protocol + '//' + loc.host + frag);
} else {
window.location.hash = this.fragment = frag;
if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) {
this.iframe.document.open().close();
this.iframe.location.hash = frag;
}
}
if (triggerRoute) this.loadUrl(fragment);
}
});
// Backbone.View
// -------------
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.delegateEvents();
this.initialize.apply(this, arguments);
};
// Element lookup, scoped to DOM elements within the current view.
// This should be prefered to global lookups, if you're dealing with
// a specific view.
var selectorDelegate = function(selector) {
return $(selector, this.el);
};
// Cached regex to split keys for `delegate`.
var eventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(Backbone.View.prototype, Backbone.Events, {
// The default `tagName` of a View's element is `"div"`.
tagName : 'div',
// Attach the `selectorDelegate` function as the `$` property.
$ : selectorDelegate,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize : function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render : function() {
return this;
},
// Remove this view from the DOM. Note that the view isn't present in the
// DOM by default, so calling this method may be a no-op.
remove : function() {
$(this.el).remove();
return this;
},
// For small amounts of DOM Elements, where a full-blown template isn't
// needed, use **make** to manufacture elements, one at a time.
//
// var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
//
make : function(tagName, attributes, content) {
var el = document.createElement(tagName);
if (attributes) $(el).attr(attributes);
if (content) $(el).html(content);
return el;
},
// Set callbacks, where `this.callbacks` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save'
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents : function(events) {
if (!(events || (events = this.events))) return;
if (_.isFunction(events)) events = events.call(this);
$(this.el).unbind('.delegateEvents' + this.cid);
for (var key in events) {
var method = this[events[key]];
if (!method) throw new Error('Event "' + events[key] + '" does not exist');
var match = key.match(eventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
$(this.el).bind(eventName, method);
} else {
$(this.el).delegate(selector, eventName, method);
}
}
},
// Performs the initial configuration of a View with a set of options.
// Keys with special meaning *(model, collection, id, className)*, are
// attached directly to the view.
_configure : function(options) {
if (this.options) options = _.extend({}, this.options, options);
for (var i = 0, l = viewOptions.length; i < l; i++) {
var attr = viewOptions[i];
if (options[attr]) this[attr] = options[attr];
}
this.options = options;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` proeprties.
_ensureElement : function() {
if (!this.el) {
var attrs = this.attributes || {};
if (this.id) attrs.id = this.id;
if (this.className) attrs['class'] = this.className;
this.el = this.make(this.tagName, attrs);
} else if (_.isString(this.el)) {
this.el = $(this.el).get(0);
}
}
});
// The self-propagating extend function that Backbone classes use.
var extend = function (protoProps, classProps) {
var child = inherits(this, protoProps, classProps);
child.extend = this.extend;
return child;
};
// Set up inheritance for the model, collection, and view.
Backbone.Model.extend = Backbone.Collection.extend =
Backbone.Router.extend = Backbone.View.extend = extend;
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read' : 'GET'
};
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, uses makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded` instead of
// `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default JSON-request options.
var params = _.extend({
type: type,
dataType: 'json'
}, options);
// Ensure that we have a URL.
if (!params.url) {
params.url = getUrl(model) || urlError();
}
// Ensure that we have the appropriate request data.
if (!params.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model : params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
// Make the request.
return $.ajax(params);
};
// Helpers
// -------
// Shared empty constructor function to aid in prototype-chain creation.
var ctor = function(){};
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var inherits = function(parent, protoProps, staticProps) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call `super()`.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Inherit class (static) properties from parent.
_.extend(child, parent);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Add static properties to the constructor function, if supplied.
if (staticProps) _.extend(child, staticProps);
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
};
// Helper function to get a URL from a Model or Collection as a property
// or as a function.
var getUrl = function(object) {
if (!(object && object.url)) return null;
return _.isFunction(object.url) ? object.url() : object.url;
};
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function(onError, model, options) {
return function(resp) {
if (onError) {
onError(model, resp, options);
} else {
model.trigger('error', model, resp, options);
}
};
};
// Helper function to escape a string for HTML rendering.
var escapeHTML = function(string) {
return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
}).call(this); | JavaScript |
/*
* jQuery Tiny Pub/Sub - v0.6 - 1/10/2011
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($){var a=$("<b/>");$.subscribe=function(b,c){function d(){return c.apply(this,Array.prototype.slice.call(arguments,1))}d.guid=c.guid=c.guid||($.guid?$.guid++:$.event.guid++);a.bind(b,d)};$.unsubscribe=function(){a.unbind.apply(a,arguments)};$.publish=function(){a.trigger.apply(a,arguments)}})(jQuery);
/*
* jQuery Templates Plugin 1.0.0pre
* http://github.com/jquery/jquery-tmpl
* Requires jQuery 1.4.2
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},i=0,c=0,l=[];function g(g,d,h,e){var c={data:e||(e===0||e===false)?e:d?d.data:{},_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};g&&a.extend(c,g,{nodes:[],parent:d});if(h){c.tmpl=h;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++i;(l.length?f:b)[i]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a(i[h])[d](k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,m,k){if(d[0]&&a.isArray(d[0])){var g=a.makeArray(arguments),h=d[0],j=h.length,i=0,f;while(i<j&&!(f=a.data(h[i++],"tmplItem")));if(f&&c)g[2]=function(b){a.tmpl.afterManip(this,b,k)};r.apply(this,g)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var i,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(j(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);i=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(j(c,null,i)):i},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){__=__.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(__,$1,$2);__=[];",close:"call=$item.calls();__=call._.concat($item.wrap(call,__));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){__.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){__.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function j(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:j(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=k(c).concat(b);if(d)b=b.concat(k(d))});return b?b:k(c)}function k(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,__=[],$data=$item.data;with($data){__.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,k,g,b,c,d){var j=a.tmpl.tag[k],i,e,f;if(!j)throw"Unknown template tag: "+k;i=j._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=h(b);d=d?","+h(d)+")":c?")":"";e=c?b.indexOf(".")>-1?b+h(c):"("+b+").call($item"+d:b;f=c?e:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else f=e=i.$1||"null";g=h(g);return"');"+j[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(f).split("$1").join(e).split("$2").join(g||i.$2||"")+"__.push('"})+"');}return __;")}function n(c,b){c._wrap=j(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function h(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,h;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(h=j.length-1;h>=0;h--)m(j[h]);m(k)}function m(j){var p,h=j,k,e,m;if(m=j.getAttribute(d)){while(h.parentNode&&(h=h.parentNode).nodeType===1&&!(p=h.getAttribute(d)));if(p!==m){h=h.parentNode?h.nodeType===11?0:h.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[h]||f[h]);e.key=++i;b[i]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;h=a.data(j.parentNode,"tmplItem");h=h?h.key:0}if(e){k=e;while(k&&k.key!=h){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
// JK: Hack to align perfect.
left += 40;
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery);
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery); | JavaScript |
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console) {
arguments.callee = arguments.callee.caller;
var newarr = [].slice.call(arguments);
(typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
}
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());
// place any jQuery/helper plugins in here, instead of separate, slower script files.
| JavaScript |
/* Author:
*/
| JavaScript |
/**
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
*/
THREEFAB.Events = {
VIEWPORT_MESH_SELECTED: 'viewport/mesh/selected',
VIEWPORT_LIGHT_SELECTED: 'viewport/light/selected',
VIEWPORT_OBJECT_TEXTURE_ADDED: 'viewport/object/texture/added',
VIEWPORT_OBJECT_REMOVED: 'viewport/object/removed',
VIEWPORT_OBJECT_ADDED: 'viewport/object/added',
VIEWPORT_TARGET_CENTER: 'viewport/target/center',
VIEWPORT_KEYFRAME_CHANGED: 'viewport/keyframe/changed',
MATERIAL_COLOR_CHANGED: 'material/color/changed',
LIGHT_COLOR_CHANGED: 'light/color/changed',
OUTLINER_CHANGED: 'outliner/changed',
MODEL_LOADED: 'model/loaded',
TEXTURE_LOADED: 'texture/loaded',
TEXTURE_CLEAR: 'texture/clear',
PRIMITIVE_ADDED: 'primitive/add',
LIGHT_ADDED: 'light/add',
EXPORTER_GENERATE: 'exporter/generate',
TIMELINE_CHANGED: 'timeline/changed',
TIMELINE_PLAY: 'timeline/play',
TIMELINE_PAUSE: 'timeline/pause',
TIMELINE_RESET: 'timeline/reset',
TIMELINE_DURATION_CHANGED: 'timeline/duration/changed',
SPACEBAR_PRESSED: 'keyboard/spacebar/pressed',
DELETE_PRESSED: 'keyboard/delete/pressed'
}; | JavaScript |
/**
* @autor itooamaneatguy http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREEFAB.AmbientLightContainer = function ( scene, hex) {
var geometry = new THREE.SphereGeometry( 6, 6, 6 ),
material = new THREE.MeshBasicMaterial( { color: 0xfff1a6, wireframe: true }),
mesh = new THREE.Mesh(geometry, material);
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vertex() );
lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 15, 1 ) ) );
var lineMat = new THREE.LineBasicMaterial( { color : 0xFFFFFF } );
for(var i=0; i < 10; i++) {
var line = new THREE.Line( lineGeometry, lineMat);
line.rotation.z = -Math.PI * (i/10) * 2;
mesh.add( line );
}
mesh.name = "THREE.AmbientLightContainer." + mesh.id;
var light = new THREE.AmbientLight(hex);
light.name = 'THREE.AmbientLight';
// Link light position and rotation to the fake holder object.
light.position = mesh.position;
light.rotation = mesh.rotation;
mesh.light = light;
scene.add(mesh);
scene.add(light);
this.mesh = mesh;
}; | JavaScript |
/**
* @autor itooamaneatguy http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREEFAB.PointLightContainer = function ( scene, hex, intensity, distance ) {
var geometry = new THREE.SphereGeometry( 6, 6, 6 ),
material = new THREE.MeshBasicMaterial( { color: 0xfff1a6, wireframe: true }),
mesh = new THREE.Mesh(geometry, material);
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vertex() );
lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 30, 1 ) ) );
var line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xFFFFFF } ) );
line.rotation.z = - Math.PI;
mesh.add( line );
mesh.name = "THREE.PointLightContainer." + mesh.id;
var light = new THREE.PointLight(hex, intensity, distance);
light.name = 'THREE.PointLight';
// Link light position and rotation to the fake holder object.
light.position = mesh.position;
light.rotation = mesh.rotation;
mesh.light = light;
scene.add(mesh);
scene.add(light);
this.mesh = mesh;
}; | JavaScript |
/**
* @autor itooamaneatguy http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREEFAB.SpotLightContainer = function ( scene, hex, intensity, distance ) {
var geometry = new THREE.CylinderGeometry( 0, 12.5, 25, 16, 1 ),
material = new THREE.MeshBasicMaterial( { color: 0xfff1a6, wireframe: true }),
mesh = new THREE.Mesh(geometry, material);
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vertex() );
lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 50, 1 ) ) );
var line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xFFFFFF } ) );
line.rotation.z = -Math.PI;
mesh.add( line );
mesh.name = "THREE.SpotLightContainer." + mesh.id;
var light = new THREE.SpotLight(hex, intensity, distance, true);
light.name = 'THREE.SpotLight';
// Link light position and rotation to the fake holder object.
light.position = mesh.position;
light.rotation = mesh.rotation;
mesh.light = light;
scene.add(mesh);
scene.add(light);
this.mesh = mesh;
}; | JavaScript |
/**
* @author Eberhard Graether / http://egraether.com/
* @itooamaneatguy http://kadrmasconcepts.com/blog/
*/
THREE.ViewportControls = function ( object, domElement ) {
var _this = this,
STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
this.object = object;
this.domElement = ( domElement !== undefined ) ? domElement : document;
// API
this.enabled = true;
this.screen = { width: window.innerWidth, height: window.innerHeight, offsetLeft: 0, offsetTop: 0 };
this.radius = ( this.screen.width + this.screen.height ) / 4;
this.rotateSpeed = 1.0;
this.zoomSpeed = 1.2;
this.panSpeed = 0.3;
this.mouseWheelSpeed = 0.01;
this.noRotate = false;
this.noZoom = false;
this.noPan = false;
this.staticMoving = false;
this.dynamicDampingFactor = 0.2;
this.minDistance = 0;
this.maxDistance = Infinity;
this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
// internals
this.target = new THREE.Vector3( 0, 0, 0 );
var _keyPressed = false,
_state = STATE.NONE,
_eye = new THREE.Vector3(),
_rotateStart = new THREE.Vector3(),
_rotateEnd = new THREE.Vector3(),
_zoomStart = new THREE.Vector2(),
_zoomEnd = new THREE.Vector2(),
_panStart = new THREE.Vector2(),
_panEnd = new THREE.Vector2();
// methods
this.handleEvent = function ( event ) {
if ( typeof this[ event.type ] == 'function' ) {
this[ event.type ]( event );
}
};
this.getMouseOnScreen = function( clientX, clientY ) {
return new THREE.Vector2(
( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
);
};
this.getMouseProjectionOnBall = function( clientX, clientY ) {
var mouseOnBall = new THREE.Vector3(
( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
0.0
);
var length = mouseOnBall.length();
if ( length > 1.0 ) {
mouseOnBall.normalize();
} else {
mouseOnBall.z = Math.sqrt( 1.0 - length * length );
}
_eye.copy( _this.object.position ).subSelf( _this.target );
var projection = _this.object.up.clone().setLength( mouseOnBall.y );
projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
projection.addSelf( _eye.setLength( mouseOnBall.z ) );
return projection;
};
this.rotateCamera = function() {
var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
if ( angle ) {
var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
quaternion = new THREE.Quaternion();
angle *= _this.rotateSpeed;
quaternion.setFromAxisAngle( axis, -angle );
quaternion.multiplyVector3( _eye );
quaternion.multiplyVector3( _this.object.up );
quaternion.multiplyVector3( _rotateEnd );
if ( _this.staticMoving ) {
_rotateStart = _rotateEnd;
} else {
quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
quaternion.multiplyVector3( _rotateStart );
}
}
};
this.zoomCamera = function() {
var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
if ( factor !== 1.0 && factor > 0.0 ) {
_eye.multiplyScalar( factor );
if ( _this.staticMoving ) {
_zoomStart = _zoomEnd;
} else {
_zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * _this.dynamicDampingFactor;
}
}
};
this.panCamera = function() {
var mouseChange = _panEnd.clone().subSelf( _panStart );
if ( mouseChange.lengthSq() ) {
mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
_this.object.position.addSelf( pan );
_this.target.addSelf( pan );
if ( _this.staticMoving ) {
_panStart = _panEnd;
} else {
_panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
}
}
};
this.checkDistances = function() {
if ( !_this.noZoom || !_this.noPan ) {
if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
_this.object.position.setLength( _this.maxDistance );
}
if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
_this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
}
}
};
this.update = function() {
_eye.copy( _this.object.position ).subSelf( this.target );
if ( !_this.noRotate ) {
_this.rotateCamera();
}
if ( !_this.noZoom ) {
_this.zoomCamera();
}
if ( !_this.noPan ) {
_this.panCamera();
}
_this.object.position.add( _this.target, _eye );
_this.checkDistances();
_this.object.lookAt( _this.target );
};
// listeners
function keydown( event ) {
if ( ! _this.enabled ) return;
if ( _state !== STATE.NONE ) {
return;
} else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
_state = STATE.ROTATE;
} else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
_state = STATE.ZOOM;
} else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
_state = STATE.PAN;
}
if ( _state !== STATE.NONE ) {
_keyPressed = true;
}
}
function keyup( event ) {
if ( ! _this.enabled ) return;
if ( _state !== STATE.NONE ) {
_state = STATE.NONE;
}
}
function mousedown( event ) {
if ( ! _this.enabled ) return;
event.preventDefault();
event.stopPropagation();
if ( _state === STATE.NONE ) {
_state = event.button;
if ( _state === STATE.ROTATE && !_this.noRotate ) {
_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
} else if ( _state === STATE.ZOOM && !_this.noZoom ) {
_zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
} else if ( !_this.noPan ) {
_panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
}
}
}
function mousemove( event ) {
if ( ! _this.enabled ) return;
if ( _keyPressed ) {
_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
_zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
_panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
_keyPressed = false;
}
if ( _state === STATE.NONE ) {
return;
} else if ( _state === STATE.ROTATE && !_this.noRotate ) {
_rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
} else if ( _state === STATE.ZOOM && !_this.noZoom ) {
_zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
} else if ( _state === STATE.PAN && !_this.noPan ) {
_panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
}
}
function mouseup( event ) {
if ( ! _this.enabled ) return;
event.preventDefault();
event.stopPropagation();
_state = STATE.NONE;
}
this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
this.domElement.addEventListener( 'mousemove', mousemove, false );
this.domElement.addEventListener( 'mousedown', mousedown, false );
this.domElement.addEventListener( 'mouseup', mouseup, false );
window.addEventListener( 'keydown', keydown, false );
window.addEventListener( 'keyup', keyup, false );
/* MouseWheel: JQuery plugin */
$('body').bind('mousewheel', function(event, delta, deltaX, deltaY) {
var speed = delta * 0.75;
_zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
_zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
_zoomStart.y += delta;
_zoomEnd.y = _zoomStart.y + (speed * _this.mouseWheelSpeed);
});
};
| JavaScript |
/**
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREE.ManipulatorTool = function () {
THREE.Object3D.call( this );
// Init
this.selected = {};
// setup geometery
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vertex() );
lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 100, 0 ) ) );
var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
// x
var line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
line.rotation.z = - Math.PI / 2;
this.add( line );
this.xCone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
this.xCone.name = "x_manipulator";
this.xCone.position.x = 100;
this.xCone.rotation.z = - Math.PI / 2;
this.add( this.xCone );
// y
var line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
this.add( line );
this.yCone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
this.yCone.position.y = 100;
this.yCone.name = "y_manipulator";
this.add( this.yCone );
// z
var line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
line.rotation.x = Math.PI / 2;
this.add( line );
this.zCone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
this.zCone.position.z = 100;
this.zCone.name = "z_manipulator";
this.zCone.rotation.x = Math.PI / 2;
this.add( this.zCone );
};
THREE.ManipulatorTool.prototype = new THREE.Object3D();
THREE.ManipulatorTool.prototype.constructor = THREE.ManipulatorTool;
| JavaScript |
/**
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREE.Grid = function () {
THREE.Object3D.call( this );
/*var geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( - 500, 0, 0 ) ) );
geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 500, 0, 0 ) ) );
for ( var i = 0; i <= 20; i ++ ) {
var line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
line.position.z = ( i * 50 ) - 500;
this.add( line );
var line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
line.position.x = ( i * 50 ) - 500;
line.rotation.y = 90 * Math.PI / 180;
this.add( line );
}*/
var _grid = new THREE.Mesh( new THREE.PlaneGeometry( 1000, 1000, 20, 20 ), new THREE.MeshBasicMaterial( { color: 0x606060, wireframe: true, transparent: true } ) );
_grid.rotation.x = Math.PI / 2;
this.add(_grid);
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vertex() );
lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 1000, 1 ) ) );
// x
var line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
line.rotation.z = - Math.PI / 2;
line.position.x = -500;
this.add( line );
//z
var line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
line.rotation.x = Math.PI / 2;
line.position.z = -500;
this.add( line );
};
THREE.Grid.prototype = new THREE.Object3D();
THREE.Grid.prototype.constructor = THREE.Grid; | JavaScript |
/**
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREEFAB.CanvasTexture = function () {
THREE.Texture.call( this );
var canvas = document.createElement( 'canvas' );
canvas.width = 512;
canvas.height = 512;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255,255,255,1)";
ctx.fillRect(0, 0, 512, 512);
this.image = canvas;
this.needsUpdate = true;
}
THREEFAB.CanvasTexture.prototype = new THREE.Texture();
THREEFAB.CanvasTexture.prototype.constructor = THREEFAB.CanvasTexture; | JavaScript |
/**
* @author mikael emtinger / http://gomo.se/
*/
THREEFAB.AnimationMorphTarget = function( root, scale ) {
this.root = root;
this.currentTime = 0;
this.timeScale = scale !== undefined ? scale : 1000;
this.isPlaying = false;
this.isPaused = true;
this.loop = true;
this.influence = 1;
this.keyframes = 0;
this.interpolation = 0;
this.lastKeyframe = 0;
this.currentKeyframe = 0;
};
/*
* Play
*/
THREEFAB.AnimationMorphTarget.prototype.play = function( loop, startTimeMS ) {
if( !this.isPlaying ) {
this.isPlaying = true;
this.loop = loop !== undefined ? loop : true;
this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
// setup interpolation
this.keyframes = this.root.morphTargetInfluences.length - 1;
this.interpolation = this.timeScale / this.keyframes;
this.render();
}
this.isPaused = false;
//THREE.AnimationHandler.addToUpdate( this );
};
/*
* Pause
*/
THREEFAB.AnimationMorphTarget.prototype.pause = function() {
/*if( this.isPaused ) {
THREE.AnimationHandler.addToUpdate( this );
} else {
THREE.AnimationHandler.removeFromUpdate( this );
}*/
this.isPaused = !this.isPaused;
};
/*
* Stop
*/
THREEFAB.AnimationMorphTarget.prototype.stop = function() {
this.isPlaying = false;
this.isPaused = false;
//THREE.AnimationHandler.removeFromUpdate( this );
// reset JIT matrix and remove cache
this.lastKeyframe = 0;
this.currentKeyframe = 0;
this.timeScale = 1000;
};
/*
* Update
*/
THREEFAB.AnimationMorphTarget.prototype.render = function() {
var mesh = this.root,
time = Date.now() % this.timeScale,
keyframe = Math.floor( time / this.interpolation ) + 1;
if ( keyframe != this.currentKeyframe ) {
mesh.morphTargetInfluences[ this.lastKeyframe ] = 0;
mesh.morphTargetInfluences[ this.currentKeyframe ] = 1;
mesh.morphTargetInfluences[ keyframe ] = 0;
this.lastKeyframe = this.currentKeyframe;
this.currentKeyframe = keyframe;
}
mesh.morphTargetInfluences[ keyframe ] = ( time % this.interpolation ) / this.interpolation;
mesh.morphTargetInfluences[ this.lastKeyframe ] = 1 - mesh.morphTargetInfluences[ keyframe ];
return keyframe;
};
THREEFAB.AnimationMorphTarget.prototype.clear = function() {
var mesh = this.root;
for(var i=0; i < this.keyframes+1; i++) {
mesh.morphTargetInfluences[ i ] = 0;
}
};
/*
* Goto Frame
*/
THREEFAB.AnimationMorphTarget.prototype.gotoFrame = function( keyframe ) {
var mesh = this.root;
mesh.morphTargetInfluences[ this.currentKeyframe ] = 0;
mesh.morphTargetInfluences[ keyframe ] = 1;
this.lastKeyframe = this.currentKeyframe;
this.currentKeyframe = keyframe;
};
THREEFAB.AnimationMorphTarget.prototype.updateTimeScale = function( value ) {
this.timeScale = value;
};
| JavaScript |
/**
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @author mr.doob / http://mrdoob.com/
*/
THREEFAB.DragDropLoader = function() {
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
window.URL = window.URL || window.webkitURL || window.mozURL;
// Need to prevent these events since the Drag and Drop API is weird.
document.addEventListener('dragover', function (event) { event.preventDefault(); }, false );
document.addEventListener('dragleave', function (event ) { event.preventDefault(); }, false );
document.addEventListener('drop', function (event) {
event.stopPropagation();
event.preventDefault();
var file = event.dataTransfer.files[ 0 ];
if(file === undefined) { return false; }
var extension = file.name.split( '.' )[1].toLowerCase();
var reader = new FileReader();
var isImage = false;
if(extension === "jpg" || extension === "png") {
isImage = true;
}
reader.onload = function ( event ) {
var contents = event.target.result,
loader, mesh, json;
if(extension === "js") {
// We dropping in a mesh.
json = JSON.parse(contents);
loader = new THREE.JSONLoader();
loader.createModel( json, function ( geometry ) {
// This is a valid model.
var material;
// Make sure this model has UV coordinates.
if(json.uvs[0].length > 0) {
material = new THREE.MeshPhongMaterial( { color: 0xffffff, wireframe: false, map: new THREEFAB.CanvasTexture() } );
} else {
material = new THREE.MeshPhongMaterial();
}
material.name = 'MeshPhongMaterial';
// Check for morphing targets and add to material.
if(geometry.morphTargets.length > 0) {
material.morphTargets = true;
}
if(geometry.skinWeights.length > 0) {
// Check for skinned mesh
mesh = new THREE.SkinnedMesh( geometry, material );
mesh.name = "THREE.SkinnedMesh." + mesh.id;
} else {
// Regular mesh.
mesh = new THREE.Mesh( geometry, material );
mesh.name = "THREE.JSONLoader." + mesh.id;
}
if(json.scale) {
mesh.scale.x = mesh.scale.y = mesh.scale.z = json.scale;
}
$.publish(THREEFAB.Events.MODEL_LOADED, mesh);
});
} else if(isImage) {
// We are dropping in a texture.
var img = new Image();
img.src = contents;
var texture = new THREE.Texture(img);
texture.needsUpdate = true;
img.onload = function() {
$.publish(THREEFAB.Events.TEXTURE_LOADED, texture);
};
}
};
if(extension === 'js') {
// JSON model file.
reader.readAsText( file );
} else if(isImage) {
// Read image textures as a data url.
reader.readAsDataURL(file);
}
});
};
| JavaScript |
/**
* @class THREEFAB.ExporterUtil
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Sets up exporter for threefab.
*
*/
THREEFAB.Exporter = function() {
var code_container = $('.code-container');
this.generate = function(viewport) {
var html = THREEFAB.Exporter.Utils.privates();
html += THREEFAB.Exporter.Utils.container();
html += THREEFAB.Exporter.Utils.camera(viewport.camera);
html += THREEFAB.Exporter.Utils.scene();
html += THREEFAB.Exporter.Utils.renderer();
html += THREEFAB.Exporter.Utils.sceneObjects(viewport.scene);
html += THREEFAB.Exporter.Utils.animate();
code_container.find('pre').html( html );
code_container.show();
};
};
THREEFAB.Exporter.Templates = {
material: '#material'
};
THREEFAB.Exporter.Utils = {
privates: function() {
return "var container = document.createElement( 'div' ),\nwidth = " + window.innerWidth + ",\nheight = " + window.innerHeight + ",\ncamera,\nscene,\nrenderer,\nSHADOW_MAP_WIDTH = 2048,\nSHADOW_MAP_HEIGHT = 1024;\n\n";
},
container: function() {
return "container = document.body.appendChild( container );\n\n";
},
addConatiner: function() {
return "container.appendChild( this.renderer.domElement )";
},
camera: function (cam) {
var str = ["camera = new THREE.PerspectiveCamera( 50, 1, 1, 5000 );"];
str.push('camera.position.set(' + cam.position.x + ',' + cam.position.y + ',' + cam.position.z + ');');
str.push('camera.rotation.set(' + cam.rotation.x + ',' + cam.rotation.y + ',' + cam.rotation.z + ');');
str.push('camera.aspect = width / height;');
str.push('camera.updateProjectionMatrix();');
return str.join('\n');
},
scene: function() {
return '\n\nscene = new THREE.Scene();';
},
renderer: function() {
var str = ["\n\nrenderer = new THREE.WebGLRenderer( { clearAlpha: 1, clearColor: 0x808080 } );"];
str.push('renderer.setSize( width, height );');
str.push('renderer.shadowCameraNear = 3;');
str.push('renderer.shadowCameraFar = this.camera.far;');
str.push('renderer.shadowCameraFov = 50;');
str.push('renderer.shadowMapBias = 0.0039;');
str.push('renderer.shadowMapDarkness = 0.5;');
str.push('renderer.shadowMapWidth = SHADOW_MAP_WIDTH;');
str.push('renderer.shadowMapHeight = SHADOW_MAP_HEIGHT;');
str.push('renderer.shadowMapEnabled = true;');
str.push('renderer.shadowMapSoft = true;');
str.push('container.appendChild( renderer.domElement );\n\n');
return str.join('\n');
},
sceneObjects: function(scene) {
var children = scene.children,
name_split,
str = [],
materialModel = new THREEFAB.MaterialModel(),
loaderUsed = false;
for(var i=0, len = children.length; i < len; i++) {
if(children[i].name) {
if( children[i].name === 'THREE.PointLight' || children[i].name === 'THREE.AmbientLight' || children[i].name === 'THREE.SpotLight' ) {
// Light
str.push( THREEFAB.Exporter.Utils.light(children[i], materialModel.lightList) );
THREEFAB.Exporter.Utils.transforms(children[i], str);
// Add light
str.push('scene.add( mesh );');
} else if( !children[i].light ) {
// Mesh
name_split = children[i].name.split('.');
var namespace = name_split[0],
meshtype = name_split[1],
id = name_split[2];
// Check for primitive geometry
if(meshtype === "CubeGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.cube(children[i]) );
} else if(meshtype === "SphereGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.sphere(children[i]) );
} else if(meshtype === "CylinderGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.cylinder(children[i]) );
} else if(meshtype === "ConeGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.cone(children[i]) );
} else if(meshtype === "PlaneGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.plane(children[i]) );
} else if(meshtype === "TorusGeometry") {
str.push( THREEFAB.Exporter.Utils.geometries.torus(children[i]) );
} else if(meshtype === "JSONLoader" || "SkinnedMesh") {
if(!loaderUsed) {
str.push('\nvar loader = new THREE.JSONLoader();');
}
str.push('loader.load( "path/to/model.js", function(geometry) {');
}
// Material
str.push( THREEFAB.Exporter.Utils.material(children[i].material, materialModel.materialList) );
if(children[i].geometry.morphTargets.length > 0) {
str.push('material.morphTargets = true;');
}
// Mesh
if(meshtype === "SkinnedMesh") {
str.push('var mesh = new THREE.SkinnedMesh(geometry, material);');
}
else {
str.push('var mesh = new THREE.Mesh(geometry, material);');
}
THREEFAB.Exporter.Utils.transforms(children[i], str);
// Add child
str.push('scene.add( mesh );');
if(meshtype === "JSONLoader" || "SkinnedMesh") {
str.push('});');
}
}
}
}
return str.join('\n');
},
light: function(light, lightList) {
var type = light.name.replace('THREE.',''),
lght = new THREE[type](),
html = '\nvar mesh = new ' + light.name + '();\n';
for(var i = 0, len = lightList.length; i < len; i++) {
if(lght[lightList[i]] !== lightList[i].prop) {
html += 'mesh.' + lightList[i].prop + ' = ' + light[lightList[i].prop] + ';\n';
}
}
// Add light color
html+= 'mesh.color = new THREE.Color().setRGB(' + light.color.r + ',' + light.color.g + ',' + light.color.b + ');';
return html;
},
material: function(material, materialList) {
var mat = new THREE[material.name](),
html = 'var material = new THREE.' + material.name + '();\n';
for(var i = 0, len = materialList.length; i < len; i++) {
// Make sure material has at least changed from the default.
if(material[materialList[i].prop] !== undefined && material[materialList[i].prop] !== mat[materialList[i].prop]) {
html+= 'material.' + materialList[i].prop + ' = ' + material[materialList[i].prop] + ';\n';
}
}
// Colors
// Do colors manually since they are currently not in the material list.
var color_props = ['color', 'ambient', 'specular'];
for(var j = 0, clen = color_props.length; j < clen; j++) {
if(mat[color_props[j]] !== material[color_props[j]]) {
html+= 'material.' + color_props[j] + ' = new THREE.Color().setRGB(' + material[color_props[j]].r+','+material[color_props[j]].g+','+material[color_props[j]].b+');\n';
}
}
if(material.map instanceof THREEFAB.CanvasTexture) {} else {
html += 'material.map = THREE.ImageUtils.loadTexture("path/to/texture.jpg");\n';
}
return html;
},
geometries: {
cube: function(mesh) {
return 'var geometry = new THREE.CubeGeometry( 100,100,100,1,1,1 );';
},
sphere: function(mesh) {
return 'var geometry = new THREE.SphereGeometry(100,16,16);';
},
cylinder: function(mesh) {
return 'var geometry = new THREE.CylinderGeometry(50, 50, 100, 16);';
},
cone: function(mesh) {
return 'var geometry = new THREE.CylinderGeometry( 0, 50, 100, 16, 1 );';
},
plane: function(mesh) {
return 'var geometry = new THREE.PlaneGeometry( 200, 200, 3, 3 );';
},
torus: function(mesh) {
return 'var geometry = new THREE.TorusGeometry();';
}
},
transforms: function(child, str) {
var pos = { x:0, y:0, z:0 },
rot = { x:0, y:0, z:0 },
scale = { x:1, y:1, z:1 };
if ( child.position.x !== 0 ) pos.x = child.position.x;
if ( child.position.y !== 0 ) pos.y = child.position.y;
if ( child.position.z !== 0 ) pos.z = child.position.z;
if ( child.rotation.x !== 0 ) rot.x = child.rotation.x;
if ( child.rotation.y !== 0 ) rot.y = child.rotation.y;
if ( child.rotation.z !== 0 ) rot.z = child.rotation.z;
if ( child.scale.x != 1 ) scale.x = child.scale.x;
if ( child.scale.y != 1 ) scale.y = child.scale.y;
if ( child.scale.z != 1 ) scale.z = child.scale.z;
str.push('mesh.position.set(' + pos.x + ',' + pos.y + ',' + pos.z + ');');
str.push('mesh.rotation.set(' + rot.x + ',' + rot.y + ',' + rot.z + ');');
str.push('mesh.scale.set(' + scale.x + ',' + scale.y + ',' + scale.z + ');');
},
animate: function() {
var html = '\n\nfunction animate() {\n';
html += '\trequestAnimationFrame( animate );\n';
html += '\trenderer.render( scene, camera );\n';
html += '}\n\n';
html += 'animate();';
return html;
}
};
| JavaScript |
/**
* @class THREEFAB.Ui
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Sets up ui components for threefab. Dependency on dat.gui.
* @param [THREEFAB.Viewport] viewport The instance of the viewport class.
*
*/
THREEFAB.Ui = function(viewport) {
var _viewport = viewport,
materialModel = new THREEFAB.MaterialModel();
this.materialView = new THREEFAB.MaterialView({ model: materialModel, selected: viewport._SELECTED });
this.transformView = new THREEFAB.TransformView({ viewport: viewport });
this.timelineView = new THREEFAB.TimelineView();
this.materialView.render();
this.transformView.render();
this.timelineView.render();
this.menu = $('.menu');
this.menu.bind('click', menuClicked);
function menuClicked(e) {
var target = e.target || e.srcElement,
id = target.id;
if(id === 'menu-animate') {
$.publish(THREEFAB.Events.SPACEBAR_PRESSED);
} else if(id === 'menu-delete') {
$.publish(THREEFAB.Events.DELETE_PRESSED);
}
}
};
/**
* Utils object that has shared functions.
* @private utils
*/
THREEFAB.Ui.utils = {
addProperties: function(object, list, folder, view) {
for(var i=0, len=list.length; i < len; i++) {
// Make sure the property is defined.
if(object[list[i].prop] !== undefined) {
var args = [object, list[i].prop],
tmp_controller;
if(list[i].min !== undefined) {
args.push(list[i].min);
}
if(list[i].max !== undefined) {
args.push(list[i].max);
}
if(list[i].values !== undefined) {
args.push(list[i].values);
}
tmp_controller = folder.add.apply(folder, args);
if(list[i].step !== undefined) {
tmp_controller.step(list[i].step);
}
}
}
},
removeFolderControllers: function(folder) {
for (var i in folder.__controllers) {
folder.__controllers[i].remove();
}
folder.__controllers = [];
}
};
| JavaScript |
/* =============================================================================
Author: Jason Kadrmas
Company: KadrmasConceps LLC
========================================================================== */
var THREEFAB = THREEFAB || {};
| JavaScript |
THREEFAB.Toolbox = Backbone.View.extend({
initialize:function() {
$('.toolbox-list').bind('click', function(event) {
event.preventDefault();
var target = event.target || event.srcElement,
className;
if(target.tagName.toLowerCase() === "a") {
className = target.className;
$.publish(threefab.events.primitive_added, target.classname);
}
});
$('.light-list').bind('click', function(event) {
event.preventDefault();
var target = event.target || event.srcElement,
className;
if(target.tagName.toLowerCase() === "a") {
className = target.className;
$.publish(THREEFAB.Events.LIGHT_ADDED, target.className);
}
});
$('.export').bind('click', function(event) {
$.publish(THREEFAB.Events.EXPORTER_GENERATE);
});
}
});
| JavaScript |
/**
* @class THREEFAB.TextureView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup texture view.
*
*/
THREEFAB.TextureView = Backbone.View.extend({
el: document.createElement('li'),
texture: document.createElement('img'),
label: document.createElement('span'),
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.css({height:40, paddingTop:'5px'});
this.texture.width = this.texture.height = 30;
this.texture = $(this.texture);
this.texture.addClass('texture-container');
this.label = $(this.label);
this.label.html('X');
this.label.addClass('button fr hidden');
this.label.bind('click', this.clear);
this.el.append(this.texture);
this.el.append(this.label);
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.render);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.render);
$.subscribe(THREEFAB.Events.VIEWPORT_OBJECT_TEXTURE_ADDED, this.render);
},
render: function(object) {
var texture;
if(object.material.map) {
texture = object.material.map;
if(object.material.map.image instanceof HTMLImageElement ) {
this.texture.attr('src', object.material.map.image.src);
this.label.removeClass('hidden');
} else {
this.reset();
}
this.el.show();
} else {
this.el.hide();
this.reset();
}
},
clear: function() {
this.reset();
$.publish(THREEFAB.Events.TEXTURE_CLEAR);
},
reset: function() {
this.texture.attr('src', 'img/blank_texture.jpg');
this.label.addClass('hidden');
}
}); | JavaScript |
/**
*
* @class THREEFAB.MaterialView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup for material view.
*
*/
THREEFAB.MaterialView = Backbone.View.extend({
el: '#gui-materials-container',
gui: {},
selected: {},
texture: {},
color: {},
light: {},
folders: {
materials:{},
lights:{},
textures:{}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.selected = arguments[0].selected;
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.meshChanged);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.lightChanged);
$.subscribe(THREEFAB.Events.MATERIAL_COLOR_CHANGED, this.changeColor);
$.subscribe(THREEFAB.Events.LIGHT_COLOR_CHANGED, this.changeLightColor);
},
render: function() {
// Create materials GUI
this.gui = new dat.GUI({ autoPlace: false, hide:false });
this.el.append(this.gui.domElement);
// Add Folders
this.folders.materials = this.gui.addFolder('Material');
this.folders.textures = this.gui.addFolder('Texture');
this.folders.lights = this.gui.addFolder('Light');
this.folders.materials.open();
this.folders.textures.open();
// Material Color Chips
this.color = new THREEFAB.ColorView();
this.folders.materials.__ul.appendChild(this.color.el[0]);
this.addMaterialOptions();
// Texture Panel
this.texture = new THREEFAB.TextureView();
this.folders.textures.__ul.appendChild(this.texture.el[0]);
this.texture.render(this.selected);
// Light view
this.light = new THREEFAB.LightView();
this.folders.lights.__ul.appendChild(this.light.el[0]);
this.light.el.hide();
},
meshChanged: function(object) {
this.selected = object;
this.folders.lights.close();
this.resetControllers();
this.addMaterialOptions();
this.folders.materials.open();
this.folders.textures.open();
this.color.el.show();
this.texture.el.show();
this.light.el.hide();
//this.rebuildMaterial();
},
lightChanged: function(object) {
this.selected = object;
this.light.el.show();
this.folders.materials.close();
this.color.el.hide();
this.folders.textures.close();
this.texture.el.hide();
this.resetControllers();
THREEFAB.Ui.utils.addProperties( object.light, this.model.lightList, this.folders.lights );
this.folders.lights.open();
},
resetControllers: function() {
THREEFAB.Ui.utils.removeFolderControllers( this.folders.lights );
THREEFAB.Ui.utils.removeFolderControllers( this.folders.materials );
},
addMaterialOptions: function() {
// Add Material shader options.
this.folders.materials.add(this.selected.material, 'name', {Basic: 'MeshBasicMaterial', Phong:'MeshPhongMaterial', Lambert: 'MeshLambertMaterial'}).onChange( this.rebuildMaterial );
// Loop and add material properties.
THREEFAB.Ui.utils.addProperties(this.selected.material, this.model.materialList, this.folders.materials, this);
},
changeColor: function(c, type) {
this.selected.material[type] = new THREE.Color().setRGB(c.r/255, c.g/255, c.b/255);
if(type === 'ambient' || type === 'specular') {
this.rebuildMaterial();
}
},
changeLightColor: function(c) {
this.selected.light.color = new THREE.Color().setRGB(c.r/255, c.g/255, c.b/255);
},
rebuildMaterial: function(matName){
var mat;
if(matName === undefined) {
matName = this.selected.material.name;
}
// We can make a generic function constructor based on the material name.
mat = new THREE[matName]();
mat.name = matName;
this.copyMaterialAttributes(mat);
this.selected.material.program = false;
this.selected.material = mat;
},
copyMaterialAttributes: function(mat) {
for(var i = 0, len = this.model.materialList.length; i < len; i++) {
if(this.selected.material[this.model.materialList[i].prop] !== undefined) {
mat[this.model.materialList[i].prop] = this.selected.material[this.model.materialList[i].prop];
}
}
// Copy the map and color manually.
mat.map = this.selected.material.map;
mat.color = this.selected.material.color;
mat.ambient = this.selected.material.ambient;
mat.specular = this.selected.material.specular;
}
}); | JavaScript |
/**
* @class THREEFAB.OutlinerView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup outliner view.
*
*/
THREEFAB.OutlinerView = Backbone.View.extend({
el: document.createElement('li'),
select: document.createElement('select'),
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.select = $(this.select);
this.el.append(this.select);
this.select.bind('change', this.change);
$.subscribe( THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.render );
$.subscribe( THREEFAB.Events.VIEWPORT_OBJECT_REMOVED, this.render );
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.updateSelected);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.updateSelected);
},
render: function(scene) {
this.select.empty();
this.addOptions( scene.children );
},
change: function() {
$.publish( THREEFAB.Events.OUTLINER_CHANGED, this.select.val() );
},
updateSelected: function(object) {
var name = object.name;
this.select.val(name);
},
addOptions: function(children) {
var opt;
for(var i=0, len = children.length; i < len; i++) {
if(children[i].name && children[i].name !== 'THREE.PointLight' && children[i].name !== 'THREE.SpotLight' && children[i].name !== 'THREE.AmbientLight') {
opt = document.createElement('option');
opt.innerHTML = children[i].name;
opt.setAttribute('value', children[i].name);
this.select.append(opt);
}
}
}
}); | JavaScript |
/**
* @class THREEFAB.TimelineView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup timeline view.
*
*/
THREEFAB.TimelineView = Backbone.View.extend({
el: '#bottom-toolbar',
duration: '#duration',
container: '.timeline-container',
canvas: document.createElement("canvas"),
c: {},
headerHeight:35,
headerWidth:400,
frames:20,
currentFrame:0,
isPlaying: false,
playButton: {},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.container = this.el.find(this.container);
this.duration = this.el.find(this.duration);
this.duration.bind('keyup', this.durationChanged);
this.duration.bind('keypress', this.numericOnly);
this.canvas.width = this.headerWidth;
this.canvas.height = this.headerHeight;
this.c = this.canvas.getContext("2d");
this.canvas.addEventListener('mousedown', this.mouseDown, false);
document.body.addEventListener('mouseup', this.mouseUp, false);
this.el.find('.back').bind('click', this.back);
this.el.find('.forward').bind('click', this.forward);
this.playButton = this.el.find('#playButton');
this.playButton.bind('click', this.play);
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.objectChanged);
$.subscribe(THREEFAB.Events.VIEWPORT_KEYFRAME_CHANGED, this.keyframeChanged);
$.subscribe(THREEFAB.Events.SPACEBAR_PRESSED, this.play);
$.subscribe(THREEFAB.Events.TIMELINE_RESET, this.reset);
},
render: function(frames) {
this.container.append(this.canvas);
if(frames) {
this.frames = frames;
}
this.build(0, this.frames);
},
build: function(goto, frames, broadcast) {
var size = Math.floor(this.canvas.width/frames),
x = 0;
this.c.clearRect(0, 0, this.headerWidth, this.headerHeight);
this.c.fillStyle = "#666";
this.c.fillRect(0, 0, this.headerWidth, this.headerHeight);
for(var i=0; i < frames; i++) {
x = i * size;
if(i !== 0) {
this.drawLine(x, 0, x, this.headerHeight*0.3, "#999999");
this.c.fillStyle = "#ffffff";
if(i%2) {
this.c.fillText(i, x-3, this.headerHeight*0.8);
}
}
}
// Line marker
this.drawLine(goto*size, 0, goto*size, this.headerHeight, "#FF0000");
this.currentFrame = goto;
if(broadcast) {
$.publish(THREEFAB.Events.TIMELINE_CHANGED, this.currentFrame);
}
},
reset: function() {
this.pause();
this.keyframeChanged(0);
},
objectChanged: function(object) {
this.isPlaying = false;
this.playButton.addClass('play');
this.playButton.removeClass('pause');
if(object.morphTargetInfluences) {
if(object.morphTargetInfluences.length > 0) {
this.frames = object.morphTargetInfluences.length;
this.build(0, this.frames, false);
}
} else {
this.build(0,20, false);
this.frames = 20;
}
},
keyframeChanged: function(goto) {
this.build(goto, this.frames, false);
},
durationChanged: function() {
var value = this.duration.val();
if( $.isNumeric(value) ) {
$.publish(THREEFAB.Events.TIMELINE_DURATION_CHANGED, value*1000);
} else {
this.duration.val("1");
}
},
numericOnly: function(e) {
var key = e.charCode || e.keyCode || 0;
// Do not allow spacebar.
if(key === 32) {
return false;
}
},
drawLine: function(x1, y1, x2, y2, color, size) {
this.c.strokeStyle = color;
this.c.beginPath();
this.c.moveTo(x1+0.5, y1+0.5);
this.c.lineTo(x2+0.5, y2+0.5);
this.c.stroke();
},
mouseDown: function(e) {
this.canvas.addEventListener('mousemove', this.mouseMove, false);
},
mouseUp: function() {
this.canvas.removeEventListener('mousemove', this.mouseMove, false);
},
mouseMove: function(e) {
var x = event.pageX - 120,
y = event.pageY,
size = Math.floor(this.canvas.width/this.frames),
frame = Math.floor(x/size);
this.build(frame, this.frames, true);
},
back: function() {
this.build(0, this.frames, true);
},
play: function() {
if(this.isPlaying) {
// Pause
$.publish(THREEFAB.Events.TIMELINE_PAUSE);
this.pause();
} else {
// Play
$.publish(THREEFAB.Events.TIMELINE_PLAY);
this.isPlaying = true;
this.playButton.addClass('pause');
this.playButton.removeClass('play');
}
},
pause: function() {
this.isPlaying = false;
this.playButton.addClass('play');
this.playButton.removeClass('pause');
},
forward: function() {
this.build(this.frames-1, this.frames, true);
}
}); | JavaScript |
/**
* @class THREEFAB.TransformView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup transform view.
*
*/
THREEFAB.TransformView = Backbone.View.extend({
el: '#gui-transform-container',
gui: {},
outliner: {},
viewport: {},
viewportView: {},
selected: {},
folders: {
camera:{},
outliner:{},
viewport:{},
transforms:{},
animate:{}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.viewport = arguments[0].viewport;
// Listen to when an object is selected.
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.addTransformOptions);
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.addTransformOptions);
},
render: function() {
// Create transform gui element.
this.gui = new dat.GUI({ autoPlace: false, hide:false });
this.el.append(this.gui.domElement);
// Add Camera
this.folders.camera = this.gui.addFolder('Camera') ;
this.addCameraOptions();
// Add target
this.folders.viewport = this.gui.addFolder('Controls');
this.viewportView = new THREEFAB.ViewportView();
this.folders.viewport.__ul.appendChild(this.viewportView.el[0]);
this.folders.viewport.open();
// Add outliner
this.folders.outliner = this.gui.addFolder('Outliner');
this.outliner = new THREEFAB.OutlinerView();
this.outliner.render( this.viewport.scene );
this.folders.outliner.__ul.appendChild(this.outliner.el[0]);
this.folders.outliner.open();
// Add transforms
this.folders.transforms = this.gui.addFolder('Transforms');
this.addTransformOptions();
this.folders.transforms.open();
},
addCameraOptions: function() {
this.folders.camera.add(this.viewport.camera.position, 'x').listen();
this.folders.camera.add(this.viewport.camera.position, 'y').listen();
this.folders.camera.add(this.viewport.camera.position, 'z').listen();
},
addTransformOptions: function() {
var selected = this.viewport._SELECTED;
var viewport = this.viewport;
THREEFAB.Ui.utils.removeFolderControllers(this.folders.transforms);
this.folders.transforms.add(selected.position, 'x').listen().onChange(function(){
viewport.updateManipulator();
});
this.folders.transforms.add(selected.position, 'y').listen().onChange(function(){
viewport.updateManipulator();
});
this.folders.transforms.add(selected.position, 'z').listen().onChange(function(){
viewport.updateManipulator();
});
// Rotation
this.folders.transforms.add(selected.rotation, 'x', -Math.PI, Math.PI);
this.folders.transforms.add(selected.rotation, 'y', -Math.PI, Math.PI);
this.folders.transforms.add(selected.rotation, 'z', -Math.PI, Math.PI);
if(!selected.light) {
// Scale
this.folders.transforms.add(selected.scale, 'x', 0);
this.folders.transforms.add(selected.scale, 'y', 0);
this.folders.transforms.add(selected.scale, 'z', 0);
}
// Shadows
this.folders.transforms.add(selected, 'castShadow');
this.folders.transforms.add(selected, 'receiveShadow').onChange(function() {
viewport.resetMaterials();
});
}
}); | JavaScript |
/**
* @class THREEFAB.OutlinerView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup outliner view.
*
*/
THREEFAB.ViewportView = Backbone.View.extend({
el: document.createElement('li'),
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.append('<button class="center button">Center</button>');
this.el.find('.center').bind('click', this.clicked);
},
clicked: function() {
$.publish(THREEFAB.Events.VIEWPORT_TARGET_CENTER);
}
}); | JavaScript |
/**
* @class THREEFAB.ColorView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup color view.
*
*/
THREEFAB.ColorView = Backbone.View.extend({
el: document.createElement('li'),
types: {
color: {},
ambient: {},
specular: {}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.css({height:55, padding:'7px 0 10px 60px'});
this.types.color = $("<div class='color_preview_container'><div class='color_preview'></div>Color</div>");
this.types.color.ColorPicker({ onChange: this.changeColor });
this.types.ambient = $("<div class='color_preview_container'><div class='color_preview'></div>Amb</div>");
this.types.ambient.ColorPicker({ onChange: this.changeAmbient });
this.types.specular = $("<div class='color_preview_container'><div class='color_preview'></div>Spec</div>");
this.types.specular.ColorPicker({ onChange: this.changeSpecular });
this.el.append( this.types.color );
this.el.append( this.types.ambient );
this.el.append( this.types.specular );
$.subscribe(THREEFAB.Events.VIEWPORT_MESH_SELECTED, this.meshChanged);
},
meshChanged: function( object ) {
if(object.material) {
var color = { r: object.material.color.r*255, g:object.material.color.g*255, b:object.material.color.b*255 },
ambient = { r: object.material.ambient.r*255, g:object.material.ambient.g*255, b:object.material.ambient.b*255 },
specular = { r: object.material.specular.r*255, g:object.material.specular.g*255, b:object.material.specular.b*255 };
this.update( this.types.color, color );
this.update( this.types.ambient, ambient );
this.update( this.types.specular, specular );
}
},
changeColor: function( hsb, hex, rgb ) {
this.update(this.types.color, rgb);
$.publish(THREEFAB.Events.MATERIAL_COLOR_CHANGED, [rgb, 'color']);
},
changeAmbient: function( hsb, hex, rgb ) {
this.update(this.types.ambient, rgb);
$.publish(THREEFAB.Events.MATERIAL_COLOR_CHANGED, [rgb, 'ambient']);
},
changeSpecular: function( hsb, hex, rgb ) {
this.update(this.types.specular, rgb);
$.publish(THREEFAB.Events.MATERIAL_COLOR_CHANGED, [rgb, 'specular']);
},
update: function(type, rgb) {
var color = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
type.find('.color_preview').css('backgroundColor', color);
}
}); | JavaScript |
/**
* @class THREEFAB.MaterialModel
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Sets up material model for the right hand material panel.
*
*/
THREEFAB.MaterialModel = Backbone.Model.extend({
materialList: [
{
prop:'wireframe'
},
{
prop:'transparent'
},
{
prop:'opacity',
min:0,
max:1
},
{
prop:'shading',
values:{None: 0, Flat: 1, Smooth: 2},
onChange:'rebuildMaterial'
},
{
prop:'blending',
values:{Normal: 0, Additive: 1, Subtractive: 2, Multiply:3, AdditiveAlpha:4}
},
{
prop:'reflectivity',
min:0,
max:5
},
{
prop:'shininess'
}
],
lightList: [
{
prop: 'intensity',
min:0,
max:10
},
{
prop: 'castShadow'
}
]
}); | JavaScript |
/**
* @class THREEFAB.LightView
*
* @author itooamaneatguy / http://kadrmasconcepts.com/blog/
* @description Setup color view.
*
*/
THREEFAB.LightView = Backbone.View.extend({
el: document.createElement('li'),
types: {
color: {}
},
initialize: function() {
_.bindAll(this);
this.el = $(this.el);
this.el.css({height:55, padding:'7px 0 10px 6px'});
this.types.color = $("<div class='color_preview_container'><div class='color_preview'></div>Color</div>");
this.types.color.ColorPicker({ onChange: this.changeColor });
this.el.append( this.types.color );
$.subscribe(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, this.lightChanged);
},
lightChanged: function( object ) {
var color = { r: object.light.color.r*255, g:object.light.color.g*255, b:object.light.color.b*255 };
this.update( this.types.color, color );
},
changeColor: function( hsb, hex, rgb ) {
this.update(this.types.color, rgb);
$.publish(THREEFAB.Events.LIGHT_COLOR_CHANGED, [rgb, 'color']);
},
update: function(type, rgb) {
var color = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
type.find('.color_preview').css('backgroundColor', color);
}
}); | JavaScript |
/* =============================================================================
Name: Viewport
Description: Sets up basic three.js viewport.
Author: Jason Kadrmas
Company: KadrmasConceps LLC
========================================================================== */
THREEFAB.Viewport = function( parameters ) {
var _radius = 500,
_height = window.innerHeight,
_width = window.innerWidth,
_this = this,
_container = document.createElement( 'div' ),
_mouse = { x: 0, y: 0 },
_prev_mouse = { x: 0, y: 0 },
_prev_camera,
_SELECTED_DOWN = false,
_SELECTED_AXIS,
_projector = new THREE.Projector(),
SHADOW_MAP_WIDTH = 2048,
SHADOW_MAP_HEIGHT = 1024;
_container.style.position = 'absolute';
_container.style.overflow = 'hidden';
parameters = parameters || {};
this.grid = parameters.grid !== undefined ? parameters.grid : true;
// Add basic scene container
document.body.appendChild( _container );
this.camera = new THREE.PerspectiveCamera( 60, _width / _height, 1, 10000 );
this.camera.position.x = 500;
this.camera.position.y = 250;
this.camera.position.z = 500;
this.camera.lookAt( new THREE.Vector3() );
// Setup renderer
this.renderer = new THREE.WebGLRenderer( { clearAlpha: 1, clearColor: 0x808080 } );
this.renderer.setSize( _width, _height );
this.renderer.shadowCameraNear = 3;
this.renderer.shadowCameraFar = this.camera.far;
this.renderer.shadowCameraFov = 50;
this.renderer.shadowMapBias = 0.0039;
this.renderer.shadowMapDarkness = 0.5;
this.renderer.shadowMapWidth = SHADOW_MAP_WIDTH;
this.renderer.shadowMapHeight = SHADOW_MAP_HEIGHT;
this.renderer.shadowMapEnabled = true;
this.renderer.shadowMapSoft = true;
_container.appendChild( this.renderer.domElement );
// Add trackball this.controls.
this.controls = new THREE.ViewportControls( this.camera, this.renderer.domElement );
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.panSpeed = 0.2;
this.controls.noZoom = false;
this.controls.noPan = false;
this.controls.staticMoving = false;
this.controls.dynamicDampingFactor = 0.3;
this.controls.minDistance = 0;
this.controls.maxDistance = _radius * 100;
this.controls.keys = [ 65, 83, 68 ]; // [ rotateKey, zoomKey, panKey ]
// Scene
this.scene = new THREE.Scene();
//Grid
if(this.grid) {
this.grid = new THREE.Grid();
this.scene.add(this.grid);
// Axis
this.manipulator = new THREE.ManipulatorTool();
this.scene.add(this.manipulator);
}
// Drag and drop functionality
$.subscribe(THREEFAB.Events.MODEL_LOADED, $.proxy(this.addModel, this));
$.subscribe(THREEFAB.Events.TEXTURE_LOADED, $.proxy(this.addTexture, this));
$.subscribe(THREEFAB.Events.PRIMITIVE_ADDED, $.proxy(this.addPrimitive, this));
$.subscribe(THREEFAB.Events.LIGHT_ADDED, $.proxy(this.addLight, this));
$.subscribe(THREEFAB.Events.TEXTURE_CLEAR, $.proxy(this.clearTexture, this));
$.subscribe(THREEFAB.Events.OUTLINER_CHANGED, outlinerChanged);
$.subscribe(THREEFAB.Events.VIEWPORT_TARGET_CENTER, targetCenter);
$.subscribe(THREEFAB.Events.TIMELINE_CHANGED, updateMeshFrame);
$.subscribe(THREEFAB.Events.TIMELINE_PLAY, playAnimation);
$.subscribe(THREEFAB.Events.TIMELINE_PAUSE, pauseAnimation);
$.subscribe(THREEFAB.Events.TIMELINE_DURATION_CHANGED, changeAnimationDuration);
$.subscribe(THREEFAB.Events.DELETE_PRESSED, deleteObject);
// =============================================================================
// DEFAULT Light, Cube. JUST LIKE BLENDER
// =============================================================================
this.setupDefaultScene.apply(this);
this.animating = false;
this.duration = 1000;
this.particleSystem = {};
this.particleGeometry = {};
this.particleCount = 1800;
//this.addParticleSystem.apply(this);
// =============================================================================
// Public Functions
// =============================================================================
this.render = function() {
_this.controls.update();
if(this.animating) {
this.processAnimation();
}
//this.processParticles();
_this.renderer.render( _this.scene, _this.camera );
};
this.animate = function() {
requestAnimationFrame( _this.animate );
_this.render();
};
this.setSize = function ( width, height ) {
_width = width;
_height = height;
_this.camera.aspect = width / height;
//_this.camera.toPerspective();
_this.camera.updateProjectionMatrix();
_this.controls.screen.width = width;
_this.controls.screen.height = height;
_this.renderer.setSize( width, height );
_this.render();
};
this.selected = function(object) {
// Pause any animations taking place
pauseAnimation();
// Remove the current overdraw
if(_this._SELECTED) {
_this._SELECTED.material.program = null;
_this._SELECTED.material.overdraw = false;
}
_this._SELECTED = object;
if(!_this._SELECTED.light) {
// It's a mesh!
this.selectMesh(object);
} else {
// It's a light!
$.publish(THREEFAB.Events.VIEWPORT_LIGHT_SELECTED, object);
_this._SELECTED.material.program = null;
_this._SELECTED.material.overdraw = true;
}
_this.updateManipulator();
};
this.deselect = function() {
_this.controls.noRotate = false;
_SELECTED_AXIS = null;
_SELECTED_DOWN = false;
};
this.processAnimation = function() {
var frame = _this.animationMorphTarget.render();
$.publish(THREEFAB.Events.VIEWPORT_KEYFRAME_CHANGED, frame);
};
this.processParticles = function() {
var ps = _this.particleSystem,
pcount = _this.particleCount,
particleGeom = this.particleGeometry;
while(pcount--) {
particle = particleGeom.vertices[pcount];
// check if we need to reset
if(particle.position.y < -200) {
particle.position.y = 200;
particle.velocity.y = 0;
}
// update the velocity with
// a splat of randomniz
particle.velocity.y -= Math.random() * 0.1;
// and the position
particle.position.addSelf(particle.velocity);
}
// flag to the particle system that we've
// changed its vertices. This is the
// dirty little secret.
ps.geometry.__dirtyVertices = true;
};
this.updateManipulator = function() {
_this.manipulator.position.copy( _this._SELECTED.position );
};
this.selectMesh = function (object) {
if( meshCanAnimate() ) {
_this.animationMorphTarget = new THREEFAB.AnimationMorphTarget(object, _this.duration);
}
$.publish(THREEFAB.Events.VIEWPORT_MESH_SELECTED, object);
};
this.selectNextMesh = function() {
for(var i=0, len = _this.scene.children.length; i < len; i++) {
if(_this.scene.children[i].name) {
_this.selected(_this.scene.children[i]);
break;
}
}
};
function outlinerChanged(name) {
var child = _this.scene.getChildByName(name);
_this.selected(child);
}
function targetCenter() {
_this.controls.target = new THREE.Vector3();
}
function updateMeshFrame(frame) {
if( meshCanAnimate() ) {
/*_this._SELECTED.morphTargetInfluences[ _this.keyframe ] = 0;
_this._SELECTED.morphTargetInfluences[ frame ] = 1;
_this.keyframe = frame;*/
if(!_this.animating) {
_this.animationMorphTarget.gotoFrame( frame );
}
}
}
function playAnimation() {
if( meshCanAnimate() ) {
_this.animationMorphTarget.play();
_this.animating = true;
}
}
function pauseAnimation() {
if(_this.animationMorphTarget) {
_this.animationMorphTarget.pause();
}
_this.animating = false;
}
function changeAnimationDuration(value) {
_this.duration = value;
if(_this.animating) {
pauseAnimation();
}
if(_this.animationMorphTarget) {
_this.animationMorphTarget.clear();
_this.animationMorphTarget = new THREEFAB.AnimationMorphTarget(_this._SELECTED, _this.duration);
}
$.publish(THREEFAB.Events.TIMELINE_RESET);
}
function meshCanAnimate() {
if(_this._SELECTED.morphTargetInfluences) {
return true;
}
return false;
}
function deleteObject() {
if(_this._SELECTED) {
if(_this._SELECTED.light) {
// If it's a light remove that too
_this.scene.remove(_this._SELECTED.light);
}
// Remove currently selected mesh
_this.scene.remove(_this._SELECTED);
// Get the next object and select that one
_this.selectNextMesh();
// Tell everyone we deleted an object
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_REMOVED, _this.scene);
}
}
// =============================================================================
//
// Mouse Functions
//
// =============================================================================
// ----------------------------------------
// Mouse Down
// ----------------------------------------
this.renderer.domElement.addEventListener( 'mousedown', function ( event ) {
event.preventDefault();
// find intersections
var vector = new THREE.Vector3( _mouse.x, _mouse.y, 1 );
_projector.unprojectVector( vector, _this.camera );
var ray = new THREE.Ray( _this.camera.position, vector.subSelf( _this.camera.position ).normalize() );
var intersects = ray.intersectScene( _this.scene );
if ( intersects.length > 0 ) {
// Are we already selected?
if ( _SELECTED_AXIS != intersects[ 0 ].object && (intersects[ 0 ].object.name === "x_manipulator" || intersects[ 0 ].object.name === "y_manipulator" || intersects[ 0 ].object.name === "z_manipulator")) {
_this.controls.noRotate = true;
_SELECTED_AXIS = intersects[0].object;
} else {
// This is an object and not a grid handle.
_this.selected(intersects[0].object);
_SELECTED_DOWN = true;
}
}
// Log the camera postion. If it moves then don't deselect any selected items.
_prev_camera = _this.camera;
});
// ----------------------------------------
// Mouse up
// ----------------------------------------
this.renderer.domElement.addEventListener('mouseup', function(event) {
event.preventDefault();
_this.deselect();
});
// ----------------------------------------
// Mouse move
// ----------------------------------------
this.renderer.domElement.addEventListener('mousemove', function(event) {
event.preventDefault();
_prev_mouse.x = _mouse.x;
_prev_mouse.y = _mouse.y;
_mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
_mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
if ( _SELECTED_AXIS && _this._SELECTED ) {
var tx = (_mouse.x - _prev_mouse.x) * 1000;
var ty = (_mouse.y - _prev_mouse.y) * 1000;
if(_SELECTED_AXIS.name === "x_manipulator") {
_this.manipulator.translateX(tx);
} else if(_SELECTED_AXIS.name === "y_manipulator") {
_this.manipulator.translateY(ty);
} else if(_SELECTED_AXIS.name === "z_manipulator") {
_this.manipulator.translateZ(-ty);
}
if ( _this._SELECTED ) {
_this._SELECTED.position.copy( _this.manipulator.position );
}
}
});
this.renderer.domElement.addEventListener( 'dblclick', function (e) {
_this.animating = false;
_this._SELECTED.geometry.computeBoundingBox();
var bb = _this._SELECTED.geometry.boundingBox;
_this.camera.position.x = _this._SELECTED.position.x;
_this.camera.position.y = _this._SELECTED.position.y + _this._SELECTED.boundRadius;
if(bb.z) {
_this.camera.position.z = _this._SELECTED.position.z + (bb.z[1]+300);
}
_this.controls.target = _this._SELECTED.position;
});
// ----------------------------------------
// Keyboard Support
// ----------------------------------------
window.addEventListener('keydown', function(e) {
var code;
if (!e) { e = window.event; }
if (e.keyCode) {
code = e.keyCode;
} else if (e.which) {
code = e.which;
}
if (code === 88) {
// X Key
$.publish(THREEFAB.Events.DELETE_PRESSED);
} else if(code === 32) {
// Spacebar
$.publish(THREEFAB.Events.SPACEBAR_PRESSED);
}
});
};
THREEFAB.Viewport.prototype = {
addPrimitive: function(type) {
var material,
geometry,
mesh,
meshName,
rotation,
doubleSided = false;
material = new THREE.MeshPhongMaterial( { wireframe: false, map: new THREEFAB.CanvasTexture(), shading: THREE.SmoothShading, overdraw: false } );
material.name = 'MeshPhongMaterial';
if(type === "sphere") {
geometry = new THREE.SphereGeometry(100,16,16);
meshName = 'THREE.SphereGeometry';
} else if(type === "cube") {
geometry = new THREE.CubeGeometry(100,100,100,1,1,1);
meshName = 'THREE.CubeGeometry';
} else if(type === "cylinder") {
geometry = new THREE.CylinderGeometry(50, 50, 100, 16);
meshName = 'THREE.CylinderGeometry';
} else if(type === "cone") {
geometry = new THREE.CylinderGeometry( 0, 50, 100, 16, 1 );
meshName = 'THREE.ConeGeometry';
} else if(type === "plane") {
geometry = new THREE.PlaneGeometry( 200, 200, 3, 3 );
meshName = 'THREE.PlaneGeometry';
rotation = new THREE.Vector3(-Math.PI/2,0,0);
doubleSided = true;
} else if(type === "torus") {
geometry = new THREE.TorusGeometry();
rotation = new THREE.Vector3(-Math.PI/2,0,0);
meshName = 'THREE.TorusGeometry';
}
geometry.dynamic = true;
mesh = new THREE.Mesh(geometry, material);
mesh.name = meshName + "." + mesh.id;
if(rotation) {
mesh.rotation.copy(rotation);
}
if(doubleSided) {
mesh.doubleSided = true;
}
this.scene.add(mesh);
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.scene);
return mesh;
},
addParticleSystem: function() {
// create the particle variables
var particles = new THREE.Geometry(),
pMaterial = new THREE.ParticleBasicMaterial({ color: 0xFFFFFF, size: Math.random() * 25 + 10, map: THREE.ImageUtils.loadTexture( "img/particle.png" ), blending: THREE.AdditiveBlending, transparent: true });
particleCount = this.particleCount;
// now create the individual particles
for(var p = 0; p < particleCount; p++) {
// create a particle with random
// position values, -250 -> 250
var pX = Math.random() * 500 - 250,
pY = Math.random() * 500 - 250,
pZ = Math.random() * 500 - 250,
particle = new THREE.Vertex( new THREE.Vector3(pX, pY, pZ) );
// create a velocity vector
particle.velocity = new THREE.Vector3(
0, // x
-Math.random(), // y: start with random vel
0 // z
);
// add it to the geometry
particles.vertices.push(particle);
}
// create the particle system
this.particleSystem = new THREE.ParticleSystem( particles, pMaterial);
this.particleGeometry = particles;
this.particleSystem.sortParticles = true;
// add it to the scene
this.scene.add(this.particleSystem);
},
addModel: function(mesh) {
this.scene.add(mesh);
this.selected(mesh);
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.scene);
return mesh;
},
addLight: function(type) {
var lightmesh;
if(type === "point") {
lightmesh = new THREEFAB.PointLightContainer(this.scene);
} else if(type === "spot") {
lightmesh = new THREEFAB.SpotLightContainer(this.scene);
} else if(type === "ambient") {
lightmesh = new THREEFAB.AmbientLightContainer(this.scene);
}
lightmesh.mesh.position.y = 150;
lightmesh.mesh.position.x = 100;
this.resetMaterials();
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_ADDED, this.scene);
return lightmesh;
},
addTexture: function(tex) {
if(!this._SELECTED.light) {
this._SELECTED.material.program = null;
this._SELECTED.material.program = null;
this._SELECTED.material.map = tex;
$.publish(THREEFAB.Events.VIEWPORT_OBJECT_TEXTURE_ADDED, this._SELECTED);
}
},
clearTexture: function() {
this._SELECTED.material.program = null;
this._SELECTED.material.map = new THREEFAB.CanvasTexture();
},
resetMaterials: function() {
for(var i=0, len = this.scene.children.length; i < len; i++) {
var child = this.scene.children[i], cached_mat;
if(child.material && child instanceof THREE.Mesh) {
cached_mat = child.material;
child.material.program = false;
child.material = null;
child.material = cached_mat;
}
}
},
setupDefaultScene: function() {
var mesh = this.addPrimitive.call(this, 'cube');
var lightmesh = this.addLight.call(this, 'point');
this._SELECTED = mesh;
$.publish(THREEFAB.Events.VIEWPORT_MESH_SELECTED, mesh);
}
};
| JavaScript |
/* =============================================================================
Author: Jason Kadrmas
Company: KadrmasConceps LLC
========================================================================== */
(function(){
// Ready
$(document).ready(function(){
var dragDrop = new THREEFAB.DragDropLoader(),
viewport = new THREEFAB.Viewport(),
ui = new THREEFAB.Ui(viewport),
toolbox = new THREEFAB.Toolbox(),
exporter = new THREEFAB.Exporter();
// App Resize
window.addEventListener('resize', function(event) {
viewport.setSize( window.innerWidth, window.innerHeight );
}, false);
// Start animating viewport
viewport.animate();
viewport.setSize( window.innerWidth, window.innerHeight );
//exporter.generate(viewport);
$.subscribe(THREEFAB.Events.EXPORTER_GENERATE, function() {
exporter.generate(viewport);
});
$('#hide-button').on('click', function() {
$('.code-container').hide();
});
});
})(); | JavaScript |
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006-2007 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
var ECLIPSE_FRAME_NAME = "ContentViewFrame";
var eclipseBuild = false;
var liveDocsBaseUrl = "http://livedocs.macromedia.com/flex/2/langref/";
function findObject(objId) {
if (document.getElementById)
return document.getElementById(objId);
if (document.all)
return document.all[objId];
}
function isEclipse() {
return eclipseBuild;
// return (window.name == ECLIPSE_FRAME_NAME) || (parent.name == ECLIPSE_FRAME_NAME) || (parent.parent.name == ECLIPSE_FRAME_NAME);
}
function configPage() {
if (isEclipse()) {
if (window.name != "classFrame")
{
var localRef = window.location.href.indexOf('?') != -1 ? window.location.href.substring(0, window.location.href.indexOf('?')) : window.location.href;
localRef = localRef.substring(localRef.indexOf("langref/") + 8);
if (window.location.search != "")
localRef += ("#" + window.location.search.substring(1));
window.location.replace(baseRef + "index.html?" + localRef);
return;
}
else
{
setStyle(".eclipseBody", "display", "block");
// var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
// if (isIE == false && window.location.hash != "")
if (window.location.hash != "")
window.location.hash=window.location.hash.substring(1);
}
}
else if (window == top) { // no frames
findObject("titleTable").style.display = "";
}
else { // frames
findObject("titleTable").style.display = "none";
}
showTitle(asdocTitle);
}
function loadFrames(classFrameURL, classListFrameURL) {
var classListFrame = findObject("classListFrame");
if(classListFrame != null && classListFrameContent!='')
classListFrame.document.location.href=classListFrameContent;
if (isEclipse()) {
var contentViewFrame = findObject(ECLIPSE_FRAME_NAME);
if (contentViewFrame != null && classFrameURL != '')
contentViewFrame.document.location.href=classFrameURL;
}
else {
var classFrame = findObject("classFrame");
if(classFrame != null && classFrameContent!='')
classFrame.document.location.href=classFrameContent;
}
}
function showTitle(title) {
if (!isEclipse())
top.document.title = title;
}
function loadClassListFrame(classListFrameURL) {
if (parent.frames["classListFrame"] != null) {
parent.frames["classListFrame"].location = classListFrameURL;
}
else if (parent.frames["packageFrame"] != null) {
if (parent.frames["packageFrame"].frames["classListFrame"] != null) {
parent.frames["packageFrame"].frames["classListFrame"].location = classListFrameURL;
}
}
}
function gotoLiveDocs(primaryURL, secondaryURL) {
var url = liveDocsBaseUrl + "index.html?" + primaryURL;
if (secondaryURL != null && secondaryURL != "")
url += ("&" + secondaryURL);
window.open(url, "mm_livedocs", "menubar=1,toolbar=1,status=1,scrollbars=1");
}
function findTitleTableObject(id)
{
if (isEclipse())
return parent.titlebar.document.getElementById(id);
else if (top.titlebar)
return top.titlebar.document.getElementById(id);
else
return document.getElementById(id);
}
function titleBar_setSubTitle(title)
{
if (isEclipse() || top.titlebar)
findTitleTableObject("subTitle").childNodes.item(0).data = title;
}
function titleBar_setSubNav(showConstants,showProperties,showStyles,showEffects,showEvents,showConstructor,showMethods,showExamples,
showPackageConstants,showPackageProperties,showPackageFunctions,showInterfaces,showClasses,showPackageUse)
{
if (isEclipse() || top.titlebar)
{
findTitleTableObject("propertiesLink").style.display = showProperties ? "inline" : "none";
findTitleTableObject("propertiesBar").style.display = (showProperties && (showPackageProperties || showConstructor || showMethods || showPackageFunctions || showEvents || showStyles || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("packagePropertiesLink").style.display = showPackageProperties ? "inline" : "none";
findTitleTableObject("packagePropertiesBar").style.display = (showPackageProperties && (showConstructor || showMethods || showPackageFunctions || showEvents || showStyles || showConstants || showEffects || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("constructorLink").style.display = showConstructor ? "inline" : "none";
findTitleTableObject("constructorBar").style.display = (showConstructor && (showMethods || showPackageFunctions || showEvents || showStyles || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("methodsLink").style.display = showMethods ? "inline" : "none";
findTitleTableObject("methodsBar").style.display = (showMethods && (showPackageFunctions || showEvents || showStyles || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("packageFunctionsLink").style.display = showPackageFunctions ? "inline" : "none";
findTitleTableObject("packageFunctionsBar").style.display = (showPackageFunctions && (showEvents || showStyles || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("eventsLink").style.display = showEvents ? "inline" : "none";
findTitleTableObject("eventsBar").style.display = (showEvents && (showStyles || showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("stylesLink").style.display = showStyles ? "inline" : "none";
findTitleTableObject("stylesBar").style.display = (showStyles && (showEffects || showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("effectsLink").style.display = showEffects ? "inline" : "none";
findTitleTableObject("effectsBar").style.display = (showEffects && (showConstants || showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("constantsLink").style.display = showConstants ? "inline" : "none";
findTitleTableObject("constantsBar").style.display = (showConstants && (showPackageConstants || showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("packageConstantsLink").style.display = showPackageConstants ? "inline" : "none";
findTitleTableObject("packageConstantsBar").style.display = (showPackageConstants && (showInterfaces || showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("interfacesLink").style.display = showInterfaces ? "inline" : "none";
findTitleTableObject("interfacesBar").style.display = (showInterfaces && (showClasses || showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("classesLink").style.display = showClasses ? "inline" : "none";
findTitleTableObject("classesBar").style.display = (showClasses && (showPackageUse || showExamples)) ? "inline" : "none";
findTitleTableObject("packageUseLink").style.display = showPackageUse ? "inline" : "none";
findTitleTableObject("packageUseBar").style.display = (showPackageUse && showExamples) ? "inline" : "none";
findTitleTableObject("examplesLink").style.display = showExamples ? "inline" : "none";
}
}
function titleBar_gotoClassFrameAnchor(anchor)
{
if (isEclipse())
parent.classFrame.location = parent.classFrame.location.toString().split('#')[0] + "#" + anchor;
else
top.classFrame.location = top.classFrame.location.toString().split('#')[0] + "#" + anchor;
}
function setMXMLOnly()
{
if (getCookie("showMXML") == "false")
{
toggleMXMLOnly();
}
}
function toggleMXMLOnly()
{
var mxmlDiv = findObject("mxmlSyntax");
var mxmlShowLink = findObject("showMxmlLink");
var mxmlHideLink = findObject("hideMxmlLink");
if (mxmlDiv && mxmlShowLink && mxmlHideLink)
{
if (mxmlDiv.style.display == "none")
{
mxmlDiv.style.display = "block";
mxmlShowLink.style.display = "none";
mxmlHideLink.style.display = "inline";
setCookie("showMXML","true", new Date(3000,1,1,1,1), "/", document.location.domain);
}
else
{
mxmlDiv.style.display = "none";
mxmlShowLink.style.display = "inline";
mxmlHideLink.style.display = "none";
setCookie("showMXML","false", new Date(3000,1,1,1,1), "/", document.location.domain);
}
}
}
function showHideInherited()
{
setInheritedVisible(getCookie("showInheritedConstant") == "true", "Constant");
setInheritedVisible(getCookie("showInheritedProtectedConstant") == "true", "ProtectedConstant");
setInheritedVisible(getCookie("showInheritedProperty") == "true", "Property");
setInheritedVisible(getCookie("showInheritedProtectedProperty") == "true", "ProtectedProperty");
setInheritedVisible(getCookie("showInheritedMethod") == "true", "Method");
setInheritedVisible(getCookie("showInheritedProtectedMethod") == "true", "ProtectedMethod");
setInheritedVisible(getCookie("showInheritedEvent") == "true", "Event");
setInheritedVisible(getCookie("showInheritedStyle") == "true", "Style");
setInheritedVisible(getCookie("showInheritedEffect") == "true", "Effect");
}
function setInheritedVisible(show, selectorText)
{
if (document.styleSheets[0].cssRules != undefined)
{
var rules = document.styleSheets[0].cssRules;
for (var i = 0; i < rules.length; i++)
{
if (rules[i].selectorText == ".hideInherited" + selectorText)
rules[i].style.display = show ? "" : "none";
if (rules[i].selectorText == ".showInherited" + selectorText)
rules[i].style.display = show ? "none" : "";
}
}
else
{
document.styleSheets[0].addRule(".hideInherited" + selectorText, show ? "display:inline" : "display:none");
document.styleSheets[0].addRule(".showInherited" + selectorText, show ? "display:none" : "display:inline");
}
setCookie("showInherited" + selectorText, show ? "true" : "false", new Date(3000,1,1,1,1), "/", document.location.domain);
setRowColors(show, selectorText);
}
function setRowColors(show, selectorText)
{
var rowColor = "#F2F2F2";
var table = findObject("summaryTable" + selectorText);
if (table != null)
{
var rowNum = 0;
for (var i = 1; i < table.rows.length; i++)
{
if (table.rows[i].className.indexOf("hideInherited") == -1 || show)
{
rowNum++;
table.rows[i].bgColor = (rowNum % 2 == 0) ? rowColor : "#FFFFFF";
}
}
}
}
function setStyle(selectorText, styleName, newValue)
{
if (document.styleSheets[0].cssRules != undefined)
{
var rules = document.styleSheets[0].cssRules;
for (var i = 0; i < rules.length; i++)
{
if (rules[i].selectorText == selectorText)
{
rules[i].style[styleName] = newValue;
break;
}
}
}
else
{
document.styleSheets[0].addRule(selectorText, styleName + ":" + newValue);
}
} | JavaScript |
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006-2007 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
/**
* Read the JavaScript cookies tutorial at:
* http://www.netspade.com/articles/javascript/cookies.xml
*/
/**
* Sets a Cookie with the given name and value.
*
* name Name of the cookie
* value Value of the cookie
* [expires] Expiration date of the cookie (default: end of current session)
* [path] Path where the cookie is valid (default: path of calling document)
* [domain] Domain where the cookie is valid
* (default: domain of calling document)
* [secure] Boolean value indicating if the cookie transmission requires a
* secure transmission
*/
function setCookie(name, value, expires, path, domain, secure)
{
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
/**
* Gets the value of the specified cookie.
*
* name Name of the desired cookie.
*
* Returns a string containing value of specified cookie,
* or null if cookie does not exist.
*/
function getCookie(name)
{
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1)
{
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1)
{
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}
/**
* Deletes the specified cookie.
*
* name name of the cookie
* [path] path of the cookie (must be same as path used to create cookie)
* [domain] domain of the cookie (must be same as domain used to create cookie)
*/
function deleteCookie(name, path, domain)
{
if (getCookie(name))
{
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
| JavaScript |
/**
* BEGIN FIRST TIME
*/
// First Time Visit Processing
// copyright 10th January 2006, Stephen Chapman
// permission to use this Javascript on your web page is granted
// provided that all of the below code in this script (including this
// comment) is used without any alteration
function rC(nam) {var tC = document.cookie.split('; '); for (var i = tC.length - 1; i >= 0; i--) {var x = tC[i].split('='); if (nam == x[0]) return unescape(x[1]);} return '~';} function wC(nam,val) {document.cookie = nam + '=' + escape(val);} function lC(nam,pg) {var val = rC(nam); if (val.indexOf('~'+pg+'~') != -1) return false; val += pg + '~'; wC(nam,val); return true;} function firstTime(cN) {return lC('pWrD4jBo',cN);} function thisPage() {var page = location.href.substring(location.href.lastIndexOf('\/')+1); pos = page.indexOf('.');if (pos > -1) {page = page.substr(0,pos);} return page;}
// example code to call it - you may modify this as required
function start() {
if (firstTime(thisPage())) {
// this code only runs for first visit
var roles = [
"A - Compre a Camiseta Abercrombie & Fitch AFCM027.",
"B - Compre uma camiseta Abercrombie tamanho G de cor escura.",
"C - Você precisa de uma camiseta nova, escolha uma que você gostaria de comprar.",
"D - Não faça nada em específico, navegue um pouco pelo site.",
"A - Encontre o moletom Hollister feminino HOMF064.",
"B - Decida qual dos dois moletons você compraria? (HOMM011 ou HOMM001)",
"C - Você precisa comprar um moletom para o aniversário de um amigo.",
"D - Você não tem nada pra fazer e resolveu dar uma olhada no site para passar tempo.",
];
var r = confirm ("Olá,\n\nVocê poderia nos ajudar a melhorar o site?\nVocê só precisa navegar no site, executar o papel descrito abaixo e clicar em \'Finalizar Teste\' quando você achar que terminou.\n\n\n"+roles[Math.floor(Math.random() * 8)]);
if (r == true) {
window.location.replace("http://blisoutlet.com/teste/");
//alert('welcome');
}
}
// other code to run every time once page is loaded goes here
}
onload = start;
/*
* END FIRST TIME
*/
/**
* Método que envia o get COM um array javascript como parâmetro
**/
function sendData(arrayParameter) {
//document.write(arrayParameter);
$.getJSON(
"json.php", // The server URL
arrayParameter // Data you want to pass to the server.
// The function to call on completion.
// Salva nos cookies
//saveProfileToCookie(arrayParameter)
//,alert('Alerta da função GET! FUNCIONEI!\nSe eu estiver atrapalhando me comente.')
);
}
function sendData(arrayParameter, jsonFileDir) {
//document.write(arrayParameter);
$.getJSON(
jsonFileDir + "json.php", // The server URL
arrayParameter // Data you want to pass to the server.
// The function to call on completion.
// Salva nos cookies
//saveProfileToCookie(arrayParameter)
//,alert('Alerta da função GET! FUNCIONEI!\nSe eu estiver atrapalhando me comente.')
);
}
/*
* Get session cookie
* Return profile ID
* COOKIE NAME: 'id_perfil_sessao'
**/
function getProfileFromCookie() {
var profileFromCookie = document.cookie;
var profile = profileFromCookie.substring(14, 15);
//Imprime o resultado na página
//document.body.innerHTML = profile;
//alert(profile);
return profile;
}
// Informa o produto e categoria visitados
function notificaProduto(ref_produto, nome_categoria_produto) {
var json = 'metodo=1' + '&user_unique_id=' + generateID() + '&ref_produto=' + ref_produto + '&nome_categoria_produto=' + nome_categoria_produto;
//Executa a função uma vez após o tempo estipulado
var tempo_na_pagina_minutos = 1;
setTimeout('notificaTempoPagina();', tempo_na_pagina_minutos *60000);
//teste para a criação de pasta
//saveProfileOnServer();
//alert(ref_produto + ' - ' + nome_categoria_produto);
sendData(json, "../");
}
// Informa a categoria visitada
function notificaPaginaCategoria(nome_categoria) {
var json = 'metodo=2' + '&user_unique_id=' + generateID() + '&nome_categoria=' + nome_categoria;
sendData(json, "/");
}
function notificaPesquisaEspecifica() {
var json = 'metodo=3' + '&user_unique_id=' + generateID();
sendData(json, "");
}
function notificaPesquisaGenerica() {
var json = 'metodo=4' + '&user_unique_id=' + generateID();
sendData(json, "");
}
function notificaTempoPagina() {
var json = 'metodo=5' + '&user_unique_id=' + generateID();
//alert('Ó eu aqui!');
sendData(json, "../");
}
/*
* Math.random should be unique because of its seeding algorithm.
* Convert it to base 36 (numbers + letters), and grab the first 9 characters after the decimal.
*/
function generateID() {
if(getCookie('user_unique_id') == false){
var id = Math.random().toString(36).substr(2, 9).toUpperCase();
document.cookie = 'user_unique_id=' + id;
//document.setInterval(window.open('https://docs.google.com/forms/d/1FXXeR4xTh92K6HzXk51zf5_zFzQKCnsLvRZiBykxcQE/viewform?entry.1890893222='+id), 180000);
//location.reload();
//AlertIt();
}
return getCookie('user_unique_id');
}
/**
* Get the cookie if exists.
* Return false if the cookie does not exist
* COOKIE NAME: 'id_perfil_sessao'
*/
function getCookie(name){
var pattern = RegExp(name + "=.[^;]*")
matched = document.cookie.match(pattern)
if(matched){
var cookie = matched[0].split('=')
return cookie[1]
}
return false
}
/**
* Get session profile though the session cookie
* COOKIE NAME: 'id_perfil_sessao'
*/
/*function getProfileFromCookie() {
var profileFromCookie = document.cookie;
var profile = profileFromCookie.substring(profileFromCookie.length-1, profileFromCookie.length);
//Imprime o resultado na página
//document.body.innerHTML = profile;
alert('Id do perfil da sessão encontrado no cookie resuperado pelo JS: ' + profile);
return profile;
}
*/
/**
* Salva o perfil do usuário da sessão nos
* cookies. Através disso o servidor pode ler
* esta informação na proxima vez que carregar
* uma página
* COOKIE NAME: 'id_perfil_sessao'
**/
/*function saveProfileToCookie(id_perfil_sessao) {
//alert(id_perfil_sessao);
//NÃO TESTEI ESSE TRECHO COM TIMEOUT
var now = new Date();
var time = now.getTime();
time += 300; //5 minutos
now.setTime(time);
document.cookie =
'id_perfil_sessao=' + id_perfil_sessao +
'; expires=' + now.toUTCString() +
'; path=/';
//document.cookie=id_perfil_sessao;
}*/
| JavaScript |
document.write('<script type="text/javascript" src="javascript/jquery.js"></script>');
var srt = getCookie('path');
if((srt != false) && (!getCookie('gform'))&& (srt.length >5)){
document.cookie = 'gform=' + true;
AlertIt();
}
function AlertIt() {
var answer = confirm ("Olá,\nAjude-nos a conhecê-lo melhor com apenas uma pergunta!")
if (answer)
window.location="https://docs.google.com/forms/d/1FXXeR4xTh92K6HzXk51zf5_zFzQKCnsLvRZiBykxcQE/viewform?entry.1890893222="+id;
}
//$(function(){
//$("#dialog").dialog({
//autoOpen: false,
//modal: true,
//height: 600,
//open: function(ev, ui){
// $('#myIframe').attr('src','http://www.jQuery.com');
// }
//});
//});
// setTimeout('dialog(\'open\')', /*1800*/15000);
//}
/**
* Método que envia o get COM um array javascript como parâmetro
**/
function sendData(arrayParameter) {
//document.write(arrayParameter);
$.getJSON(
"json.php", // The server URL
arrayParameter // Data you want to pass to the server.
// The function to call on completion.
// Salva nos cookies
//saveProfileToCookie(arrayParameter)
//,alert('Alerta da função GET! FUNCIONEI!\nSe eu estiver atrapalhando me comente.')
);
}
/*
* Get session cookie
* Return profile ID
* COOKIE NAME: 'id_perfil_sessao'
**/
function getProfileFromCookie() {
var profileFromCookie = document.cookie;
var profile = profileFromCookie.substring(14, 15);
//var profile = profileFromCookie.substring(0, 20);
//Imprime o resultado na página
//document.body.innerHTML = profile;
//alert(profile);
return profile;
}
// Informa o produto e categoria visitados
//A ou AF
function notificaProduto(ref_produto, nome_categoria_produto) {
var json = 'metodo=1' + '&user_unique_id=' + generateID() + '&ref_produto=' + ref_produto + '&nome_categoria_produto=' + nome_categoria_produto;
//Executa a função uma vez após o tempo estipulado
var tempo_na_pagina_minutos = 1;
setTimeout('notificaTempoPagina();', tempo_na_pagina_minutos *60000);
//teste para a criação de pasta
//saveProfileOnServer();
sendData(json);
}
// Informa a categoria visitada
//B
function notificaPaginaCategoria(nome_categoria) {
var json = 'metodo=2' + '&user_unique_id=' + generateID() + '&nome_categoria=' + nome_categoria;
sendData(json);
}
//C
function notificaPesquisaEspecifica() {
var json = 'metodo=3' + '&user_unique_id=' + generateID();
sendData(json);
}
//D
function notificaPesquisaGenerica() {
var json = 'metodo=4' + '&user_unique_id=' + generateID();
sendData(json);
}
//E
function notificaTempoPagina() {
var json = 'metodo=5' + '&user_unique_id=' + generateID();
//alert('Ó eu aqui!');
sendData(json);
}
/*
* Math.random should be unique because of its seeding algorithm.
* Convert it to base 36 (numbers + letters), and grab the first 9 characters after the decimal.
*/
function generateID() {
if(getCookie('user_unique_id') == false){
var id = Math.random().toString(36).substr(2, 9).toUpperCase();
document.cookie = 'user_unique_id=' + id;
setInterval(window.open('https://docs.google.com/forms/d/1FXXeR4xTh92K6HzXk51zf5_zFzQKCnsLvRZiBykxcQE/viewform?entry.1890893222='+id), 3*60000);
}
return getCookie('user_unique_id');
}
/**
* Get the cookie if exists.
* Return false if the cookie does not exist
* COOKIE NAME: 'id_perfil_sessao'
*/
function generateID() {
if(getCookie('user_unique_id') == false){
var id = Math.random().toString(36).substr(2, 9).toUpperCase();
document.cookie = 'user_unique_id=' + id;
}
return getCookie('user_unique_id');
}
/**
* Get the cookie if exists.
* Return false if the cookie does not exist
* COOKIE NAME: 'id_perfil_sessao'
*/
function getCookie(name){
var pattern = RegExp(name + "=.[^;]*")
matched = document.cookie.match(pattern)
if(matched){
var cookie = matched[0].split('=')
return cookie[1]
}
return false
}
/**
* Get session profile though the session cookie
* COOKIE NAME: 'id_perfil_sessao'
*/
/*function getProfileFromCookie() {
var profileFromCookie = document.cookie;
var profile = profileFromCookie.substring(profileFromCookie.length-1, profileFromCookie.length);
//Imprime o resultado na página
//document.body.innerHTML = profile;
alert('Id do perfil da sessão encontrado no cookie resuperado pelo JS: ' + profile);
return profile;
}
*/
/**
* Salva o perfil do usuário da sessão nos
* cookies. Através disso o servidor pode ler
* esta informação na proxima vez que carregar
* uma página
* COOKIE NAME: 'id_perfil_sessao'
**/
/*function saveProfileToCookie(id_perfil_sessao) {
//alert(id_perfil_sessao);
//NÃO TESTEI ESSE TRECHO COM TIMEOUT
var now = new Date();
var time = now.getTime();
time += 300; //5 minutos
now.setTime(time);
document.cookie =
'id_perfil_sessao=' + id_perfil_sessao +
'; expires=' + now.toUTCString() +
'; path=/';
//document.cookie=id_perfil_sessao;
}*/ | JavaScript |
/*
* Project: Agitated User behavior data miner
* Description: Help you track where your users becomes agitated in your web application
* Author: Cedric Dugas, http://www.position-relative.net
* License: MIT
*/
;(function ( $, window, document, undefined ) {
var pluginName = "behaviorMiner",
defaults = {
connector: false,
track : {
keymultiplepress:true,
repeatkey:true,
multipleclick:true,
longclick:true,
texthighlight:true
},
sensibility : {
multipleclick : 2, // number of click before logging
multipleclicktime : 1000, // time elapsed for hitting for clicking the same dom element
repeatkey : 2, // number of same key hit before logging
repeatkeytime : 1000, // time elapsed for hitting the same key
keymultiplepress : 2, // number of click pressed at the same time before logging
longclick: 4000 // time elapsed before conseding a long click
}
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
var trackOptions = this.options.track,
self = this;
// Load dataConnector plugin and pass options to init
if($.behaviorMiner.connectors[this.options.connector] && $.behaviorMiner.connectors[this.options.connector].init){
$.behaviorMiner.connectors[this.options.connector].options = this.options;
$.behaviorMiner.connectors[this.options.connector].init();
}
// load all behaviors
$.each(trackOptions, function(behavior, state){
if(state && $.behaviorMiner.behaviors[behavior] && $.behaviorMiner.behaviors[behavior].load)
$.behaviorMiner.behaviors[behavior].options = self.options;
$.behaviorMiner.behaviors[behavior].load();
});
// receive data from behaviors
$(document).on("behaviorMiner_data", function(e,data){
self.pushData(data);
});
},
disable : function() {
$(document).off("mouseup.behaviorMiner");
$(document).off("mousedown.behaviorMiner");
$(document).off("keydown.behaviorMiner");
$(document).off("keyup.behaviorMiner");
$(document).off("click.behaviorMiner");
$(document).off("behaviorMiner_data");
$(document).off("log_multiple_click");
},
enable : function () {
this.disable();
this.init();
},
pushData : function(custom){
var defaults = {
timestamp : new Date().getTime(),
url : window.location.href
};
var data = $.extend({}, defaults, custom );
$(document).trigger("log_user_behavior", [data]);
}
};
$[pluginName] = {
behaviors : {},
connectors : {}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document ); | JavaScript |
var findPosts;
(function($){
findPosts = {
open : function(af_name, af_val) {
var st = document.documentElement.scrollTop || $(document).scrollTop(),
overlay = $( '.ui-find-overlay' );
if ( overlay.length == 0 ) {
$( 'body' ).append( '<div class="ui-find-overlay"></div>' );
findPosts.overlay();
}
overlay.show();
if ( af_name && af_val ) {
$('#affected').attr('name', af_name).val(af_val);
}
$('#find-posts').show().draggable({
handle: '#find-posts-head'
}).css({'top':st + 50 + 'px','left':'50%','marginLeft':'-328px'});
$('#find-posts-input').focus().keyup(function(e){
if (e.which == 27) { findPosts.close(); } // close on Escape
});
// Pull some results up by default
findPosts.send();
return false;
},
close : function() {
$('#find-posts-response').html('');
$('#find-posts').draggable('destroy').hide();
$( '.ui-find-overlay' ).hide();
},
overlay : function() {
$( '.ui-find-overlay' ).css(
{ 'z-index': '999', 'width': $( document ).width() + 'px', 'height': $( document ).height() + 'px' }
).on('click', function () {
findPosts.close();
});
},
send : function() {
var post = {
ps: $('#find-posts-input').val(),
action: 'find_posts',
_ajax_nonce: $('#_ajax_nonce').val()
},
spinner = $( '.find-box-search .spinner' );
spinner.show();
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { findPosts.show(x); spinner.hide(); },
error : function(r) { findPosts.error(r); spinner.hide(); }
});
},
show : function(x) {
if ( typeof(x) == 'string' ) {
this.error({'responseText': x});
return;
}
var r = wpAjax.parseAjaxResponse(x);
if ( r.errors ) {
this.error({'responseText': wpAjax.broken});
}
r = r.responses[0];
$('#find-posts-response').html(r.data);
// Enable whole row to be clicked
$( '.found-posts td' ).on( 'click', function () {
$( this ).parent().find( '.found-radio input' ).prop( 'checked', true );
});
},
error : function(r) {
var er = r.statusText;
if ( r.responseText ) {
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
}
if ( er ) {
$('#find-posts-response').html(er);
}
}
};
$(document).ready(function() {
$('#find-posts-submit').click(function(e) {
if ( '' == $('#find-posts-response').html() )
e.preventDefault();
});
$( '#find-posts .find-box-search :input' ).keypress( function( event ) {
if ( 13 == event.which ) {
findPosts.send();
return false;
}
} );
$( '#find-posts-search' ).click( findPosts.send );
$( '#find-posts-close' ).click( findPosts.close );
$('#doaction, #doaction2').click(function(e){
$('select[name^="action"]').each(function(){
if ( $(this).val() == 'attach' ) {
e.preventDefault();
findPosts.open();
}
});
});
});
$(window).resize(function() {
findPosts.overlay();
});
})(jQuery);
| JavaScript |
( function( $, undef ){
// html stuff
var _before = '<a tabindex="0" class="wp-color-result" />',
_after = '<div class="wp-picker-holder" />',
_wrap = '<div class="wp-picker-container" />',
_button = '<input type="button" class="button button-small hidden" />';
// jQuery UI Widget constructor
var ColorPicker = {
options: {
defaultColor: false,
change: false,
clear: false,
hide: true,
palettes: true
},
_create: function() {
// bail early for unsupported Iris.
if ( ! $.support.iris )
return;
var self = this;
var el = self.element;
$.extend( self.options, el.data() );
self.initialValue = el.val();
// Set up HTML structure, hide things
el.addClass( 'wp-color-picker' ).hide().wrap( _wrap );
self.wrap = el.parent();
self.toggler = $( _before ).insertBefore( el ).css( { backgroundColor: self.initialValue } ).attr( "title", wpColorPickerL10n.pick ).attr( "data-current", wpColorPickerL10n.current );
self.pickerContainer = $( _after ).insertAfter( el );
self.button = $( _button );
if ( self.options.defaultColor )
self.button.addClass( 'wp-picker-default' ).val( wpColorPickerL10n.defaultString );
else
self.button.addClass( 'wp-picker-clear' ).val( wpColorPickerL10n.clear );
el.wrap('<span class="wp-picker-input-wrap" />').after(self.button);
el.iris( {
target: self.pickerContainer,
hide: true,
width: 255,
mode: 'hsv',
palettes: self.options.palettes,
change: function( event, ui ) {
self.toggler.css( { backgroundColor: ui.color.toString() } );
// check for a custom cb
if ( $.isFunction( self.options.change ) )
self.options.change.call( this, event, ui );
}
} );
el.val( self.initialValue );
self._addListeners();
if ( ! self.options.hide )
self.toggler.click();
},
_addListeners: function() {
var self = this;
self.toggler.click( function( event ){
event.stopPropagation();
self.element.toggle().iris( 'toggle' );
self.button.toggleClass('hidden');
self.toggler.toggleClass( 'wp-picker-open' );
// close picker when you click outside it
if ( self.toggler.hasClass( 'wp-picker-open' ) )
$( "body" ).on( 'click', { wrap: self.wrap, toggler: self.toggler }, self._bodyListener );
else
$( "body" ).off( 'click', self._bodyListener );
});
self.element.change(function( event ) {
var me = $(this),
val = me.val();
// Empty = clear
if ( val === '' || val === '#' ) {
self.toggler.css('backgroundColor', '');
// fire clear callback if we have one
if ( $.isFunction( self.options.clear ) )
self.options.clear.call( this, event );
}
});
// open a keyboard-focused closed picker with space or enter
self.toggler.on('keyup', function( e ) {
if ( e.keyCode === 13 || e.keyCode === 32 ) {
e.preventDefault();
self.toggler.trigger('click').next().focus();
}
});
self.button.click( function( event ) {
var me = $(this);
if ( me.hasClass( 'wp-picker-clear' ) ) {
self.element.val( '' );
self.toggler.css('backgroundColor', '');
if ( $.isFunction( self.options.clear ) )
self.options.clear.call( this, event );
} else if ( me.hasClass( 'wp-picker-default' ) ) {
self.element.val( self.options.defaultColor ).change();
}
});
},
_bodyListener: function( event ) {
if ( ! event.data.wrap.find( event.target ).length )
event.data.toggler.click();
},
// $("#input").wpColorPicker('color') returns the current color
// $("#input").wpColorPicker('color', '#bada55') to set
color: function( newColor ) {
if ( newColor === undef )
return this.element.iris( "option", "color" );
this.element.iris( "option", "color", newColor );
},
//$("#input").wpColorPicker('defaultColor') returns the current default color
//$("#input").wpColorPicker('defaultColor', newDefaultColor) to set
defaultColor: function( newDefaultColor ) {
if ( newDefaultColor === undef )
return this.options.defaultColor;
this.options.defaultColor = newDefaultColor;
}
}
$.widget( 'wp.wpColorPicker', ColorPicker );
}( jQuery ) ); | JavaScript |
var showNotice, adminMenu, columns, validateForm, screenMeta;
(function($){
// Removed in 3.3.
// (perhaps) needed for back-compat
adminMenu = {
init : function() {},
fold : function() {},
restoreMenuState : function() {},
toggle : function() {},
favorites : function() {}
};
// show/hide/save table columns
columns = {
init : function() {
var that = this;
$('.hide-column-tog', '#adv-settings').click( function() {
var $t = $(this), column = $t.val();
if ( $t.prop('checked') )
that.checked(column);
else
that.unchecked(column);
columns.saveManageColumnsState();
});
},
saveManageColumnsState : function() {
var hidden = this.hidden();
$.post(ajaxurl, {
action: 'hidden-columns',
hidden: hidden,
screenoptionnonce: $('#screenoptionnonce').val(),
page: pagenow
});
},
checked : function(column) {
$('.column-' + column).show();
this.colSpanChange(+1);
},
unchecked : function(column) {
$('.column-' + column).hide();
this.colSpanChange(-1);
},
hidden : function() {
return $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(',');
},
useCheckboxesForHidden : function() {
this.hidden = function(){
return $('.hide-column-tog').not(':checked').map(function() {
var id = this.id;
return id.substring( id, id.length - 5 );
}).get().join(',');
};
},
colSpanChange : function(diff) {
var $t = $('table').find('.colspanchange'), n;
if ( !$t.length )
return;
n = parseInt( $t.attr('colspan'), 10 ) + diff;
$t.attr('colspan', n.toString());
}
}
$(document).ready(function(){columns.init();});
validateForm = function( form ) {
return !$( form ).find('.form-required').filter( function() { return $('input:visible', this).val() == ''; } ).addClass( 'form-invalid' ).find('input:visible').change( function() { $(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ).size();
}
// stub for doing better warnings
showNotice = {
warn : function() {
var msg = commonL10n.warnDelete || '';
if ( confirm(msg) ) {
return true;
}
return false;
},
note : function(text) {
alert(text);
}
};
screenMeta = {
element: null, // #screen-meta
toggles: null, // .screen-meta-toggle
page: null, // #wpcontent
init: function() {
this.element = $('#screen-meta');
this.toggles = $('.screen-meta-toggle a');
this.page = $('#wpcontent');
this.toggles.click( this.toggleEvent );
},
toggleEvent: function( e ) {
var panel = $( this.href.replace(/.+#/, '#') );
e.preventDefault();
if ( !panel.length )
return;
if ( panel.is(':visible') )
screenMeta.close( panel, $(this) );
else
screenMeta.open( panel, $(this) );
},
open: function( panel, link ) {
$('.screen-meta-toggle').not( link.parent() ).css('visibility', 'hidden');
panel.parent().show();
panel.slideDown( 'fast', function() {
panel.focus();
link.addClass('screen-meta-active').attr('aria-expanded', true);
});
},
close: function( panel, link ) {
panel.slideUp( 'fast', function() {
link.removeClass('screen-meta-active').attr('aria-expanded', false);
$('.screen-meta-toggle').css('visibility', '');
panel.parent().hide();
});
}
};
/**
* Help tabs.
*/
$('.contextual-help-tabs').delegate('a', 'click focus', function(e) {
var link = $(this),
panel;
e.preventDefault();
// Don't do anything if the click is for the tab already showing.
if ( link.is('.active a') )
return false;
// Links
$('.contextual-help-tabs .active').removeClass('active');
link.parent('li').addClass('active');
panel = $( link.attr('href') );
// Panels
$('.help-tab-content').not( panel ).removeClass('active').hide();
panel.addClass('active').show();
});
$(document).ready( function() {
var lastClicked = false, checks, first, last, checked, menu = $('#adminmenu'), mobileEvent,
pageInput = $('input.current-page'), currentPage = pageInput.val();
// when the menu is folded, make the fly-out submenu header clickable
menu.on('click.wp-submenu-head', '.wp-submenu-head', function(e){
$(e.target).parent().siblings('a').get(0).click();
});
$('#collapse-menu').on('click.collapse-menu', function(e){
var body = $( document.body ), respWidth;
// reset any compensation for submenus near the bottom of the screen
$('#adminmenu div.wp-submenu').css('margin-top', '');
// WebKit excludes the width of the vertical scrollbar when applying the CSS "@media screen and (max-width: ...)"
// and matches $(window).width().
// Firefox and IE > 8 include the scrollbar width, so after the jQuery normalization
// $(window).width() is 884px but window.innerWidth is 900px.
// (using window.innerWidth also excludes IE < 9)
respWidth = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $(window).width() : window.innerWidth;
if ( respWidth && respWidth < 900 ) {
if ( body.hasClass('auto-fold') ) {
body.removeClass('auto-fold').removeClass('folded');
setUserSetting('unfold', 1);
deleteUserSetting('mfold');
} else {
body.addClass('auto-fold');
deleteUserSetting('unfold');
}
} else {
if ( body.hasClass('folded') ) {
body.removeClass('folded');
deleteUserSetting('mfold');
} else {
body.addClass('folded');
setUserSetting('mfold', 'f');
}
}
});
if ( 'ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent) ) { // touch screen device
// iOS Safari works with touchstart, the rest work with click
mobileEvent = /Mobile\/.+Safari/.test(navigator.userAgent) ? 'touchstart' : 'click';
// close any open submenus when touch/click is not on the menu
$(document.body).on( mobileEvent+'.wp-mobile-hover', function(e) {
if ( !$(e.target).closest('#adminmenu').length )
menu.find('li.wp-has-submenu.opensub').removeClass('opensub');
});
menu.find('a.wp-has-submenu').on( mobileEvent+'.wp-mobile-hover', function(e) {
var el = $(this), parent = el.parent();
// Show the sub instead of following the link if:
// - the submenu is not open
// - the submenu is not shown inline or the menu is not folded
if ( !parent.hasClass('opensub') && ( !parent.hasClass('wp-menu-open') || parent.width() < 40 ) ) {
e.preventDefault();
menu.find('li.opensub').removeClass('opensub');
parent.addClass('opensub');
}
});
}
menu.find('li.wp-has-submenu').hoverIntent({
over: function(e){
var b, h, o, f, m = $(this).find('.wp-submenu'), menutop, wintop, maxtop, top = parseInt( m.css('top'), 10 );
if ( isNaN(top) || top > -5 ) // meaning the submenu is visible
return;
menutop = $(this).offset().top;
wintop = $(window).scrollTop();
maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar
b = menutop + m.height() + 1; // Bottom offset of the menu
h = $('#wpwrap').height(); // Height of the entire page
o = 60 + b - h;
f = $(window).height() + wintop - 15; // The fold
if ( f < (b - o) )
o = b - f;
if ( o > maxtop )
o = maxtop;
if ( o > 1 )
m.css('margin-top', '-'+o+'px');
else
m.css('margin-top', '');
menu.find('li.menu-top').removeClass('opensub');
$(this).addClass('opensub');
},
out: function(){
$(this).removeClass('opensub').find('.wp-submenu').css('margin-top', '');
},
timeout: 200,
sensitivity: 7,
interval: 90
});
menu.on('focus.adminmenu', '.wp-submenu a', function(e){
$(e.target).closest('li.menu-top').addClass('opensub');
}).on('blur.adminmenu', '.wp-submenu a', function(e){
$(e.target).closest('li.menu-top').removeClass('opensub');
});
// Move .updated and .error alert boxes. Don't move boxes designed to be inline.
$('div.wrap h2:first').nextAll('div.updated, div.error').addClass('below-h2');
$('div.updated, div.error').not('.below-h2, .inline').insertAfter( $('div.wrap h2:first') );
// Init screen meta
screenMeta.init();
// check all checkboxes
$('tbody').children().children('.check-column').find(':checkbox').click( function(e) {
if ( 'undefined' == e.shiftKey ) { return true; }
if ( e.shiftKey ) {
if ( !lastClicked ) { return true; }
checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' );
first = checks.index( lastClicked );
last = checks.index( this );
checked = $(this).prop('checked');
if ( 0 < first && 0 < last && first != last ) {
checks.slice( first, last ).prop( 'checked', function(){
if ( $(this).closest('tr').is(':visible') )
return checked;
return false;
});
}
}
lastClicked = this;
// toggle "check all" checkboxes
var unchecked = $(this).closest('tbody').find(':checkbox').filter(':visible').not(':checked');
$(this).closest('table').children('thead, tfoot').find(':checkbox').prop('checked', function() {
return ( 0 == unchecked.length );
});
return true;
});
$('thead, tfoot').find('.check-column :checkbox').click( function(e) {
var c = $(this).prop('checked'),
kbtoggle = 'undefined' == typeof toggleWithKeyboard ? false : toggleWithKeyboard,
toggle = e.shiftKey || kbtoggle;
$(this).closest( 'table' ).children( 'tbody' ).filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( $(this).is(':hidden') )
return false;
if ( toggle )
return $(this).prop( 'checked' );
else if (c)
return true;
return false;
});
$(this).closest('table').children('thead, tfoot').filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( toggle )
return false;
else if (c)
return true;
return false;
});
});
$('#default-password-nag-no').click( function() {
setUserSetting('default_password_nag', 'hide');
$('div.default-password-nag').hide();
return false;
});
// tab in textareas
$('#newcontent').bind('keydown.wpevent_InsertTab', function(e) {
var el = e.target, selStart, selEnd, val, scroll, sel;
if ( e.keyCode == 27 ) { // escape key
$(el).data('tab-out', true);
return;
}
if ( e.keyCode != 9 || e.ctrlKey || e.altKey || e.shiftKey ) // tab key
return;
if ( $(el).data('tab-out') ) {
$(el).data('tab-out', false);
return;
}
selStart = el.selectionStart;
selEnd = el.selectionEnd;
val = el.value;
try {
this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below.
} catch(err) {}
if ( document.selection ) {
el.focus();
sel = document.selection.createRange();
sel.text = '\t';
} else if ( selStart >= 0 ) {
scroll = this.scrollTop;
el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) );
el.selectionStart = el.selectionEnd = selStart + 1;
this.scrollTop = scroll;
}
if ( e.stopPropagation )
e.stopPropagation();
if ( e.preventDefault )
e.preventDefault();
});
$('#newcontent').bind('blur.wpevent_InsertTab', function(e) {
if ( this.lastKey && 9 == this.lastKey )
this.focus();
});
if ( pageInput.length ) {
pageInput.closest('form').submit( function(e){
// Reset paging var for new filters/searches but not for bulk actions. See #17685.
if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage )
pageInput.val('1');
});
}
// Scroll into view when focused
$('#contextual-help-link, #show-settings-link').on( 'focus.scroll-into-view', function(e){
if ( e.target.scrollIntoView )
e.target.scrollIntoView(false);
});
// Disable upload buttons until files are selected
(function(){
var button, input, form = $('form.wp-upload-form');
if ( ! form.length )
return;
button = form.find('input[type="submit"]');
input = form.find('input[type="file"]');
function toggleUploadButton() {
button.prop('disabled', '' === input.map( function() {
return $(this).val();
}).get().join(''));
}
toggleUploadButton();
input.on('change', toggleUploadButton);
})();
});
// internal use
$(document).bind( 'wp_CloseOnEscape', function( e, data ) {
if ( typeof(data.cb) != 'function' )
return;
if ( typeof(data.condition) != 'function' || data.condition() )
data.cb();
return true;
});
})(jQuery);
| JavaScript |
var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad;
jQuery(document).ready( function($) {
/* Dashboard Welcome Panel */
var welcomePanel = $('#welcome-panel'),
welcomePanelHide = $('#wp_welcome_panel-hide'),
updateWelcomePanel = function( visible ) {
$.post( ajaxurl, {
action: 'update-welcome-panel',
visible: visible,
welcomepanelnonce: $('#welcomepanelnonce').val()
});
};
if ( welcomePanel.hasClass('hidden') && welcomePanelHide.prop('checked') )
welcomePanel.removeClass('hidden');
$('.welcome-panel-close, .welcome-panel-dismiss a', welcomePanel).click( function(e) {
e.preventDefault();
welcomePanel.addClass('hidden');
updateWelcomePanel( 0 );
$('#wp_welcome_panel-hide').prop('checked', false);
});
welcomePanelHide.click( function() {
welcomePanel.toggleClass('hidden', ! this.checked );
updateWelcomePanel( this.checked ? 1 : 0 );
});
// These widgets are sometimes populated via ajax
ajaxWidgets = [
'dashboard_incoming_links',
'dashboard_primary',
'dashboard_secondary',
'dashboard_plugins'
];
ajaxPopulateWidgets = function(el) {
function show(i, id) {
var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading');
if ( e.length ) {
p = e.parent();
setTimeout( function(){
p.load( ajaxurl + '?action=dashboard-widgets&widget=' + id, '', function() {
p.hide().slideDown('normal', function(){
$(this).css('display', '');
});
});
}, i * 500 );
}
}
if ( el ) {
el = el.toString();
if ( $.inArray(el, ajaxWidgets) != -1 )
show(0, el);
} else {
$.each( ajaxWidgets, show );
}
};
ajaxPopulateWidgets();
postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } );
/* QuickPress */
quickPressLoad = function() {
var act = $('#quickpost-action'), t;
t = $('#quick-press').submit( function() {
$('#dashboard_quick_press #publishing-action .spinner').show();
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true);
if ( 'post' == act.val() ) {
act.val( 'post-quickpress-publish' );
}
$('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() {
$('#dashboard_quick_press #publishing-action .spinner').hide();
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', false);
$('#dashboard_quick_press ul').next('p').remove();
$('#dashboard_quick_press ul').find('li').each( function() {
$('#dashboard_recent_drafts ul').prepend( this );
} ).end().remove();
quickPressLoad();
} );
return false;
} );
$('#publish').click( function() { act.val( 'post-quickpress-publish' ); } );
$('#title, #tags-input').each( function() {
var input = $(this), prompt = $('#' + this.id + '-prompt-text');
if ( '' === this.value )
prompt.removeClass('screen-reader-text');
prompt.click( function() {
$(this).addClass('screen-reader-text');
input.focus();
});
input.blur( function() {
if ( '' === this.value )
prompt.removeClass('screen-reader-text');
});
input.focus( function() {
prompt.addClass('screen-reader-text');
});
});
$('#quick-press').on( 'click focusin', function() {
wpActiveEditor = 'content';
});
};
quickPressLoad();
} );
| JavaScript |
( function( $ ){
$( document ).ready( function () {
// Expand/Collapse on click
$( '.accordion-container' ).on( 'click keydown', '.accordion-section-title', function( e ) {
if ( e.type === 'keydown' && 13 !== e.which ) // "return" key
return;
e.preventDefault(); // Keep this AFTER the key filter above
accordionSwitch( $( this ) );
});
// Re-initialize accordion when screen options are toggled
$( '.hide-postbox-tog' ).click( function () {
accordionInit();
});
});
var accordionOptions = $( '.accordion-container li.accordion-section' ),
sectionContent = $( '.accordion-section-content' );
function accordionInit () {
// Rounded corners
accordionOptions.removeClass( 'top bottom' );
accordionOptions.filter( ':visible' ).first().addClass( 'top' );
accordionOptions.filter( ':visible' ).last().addClass( 'bottom' ).find( sectionContent ).addClass( 'bottom' );
}
function accordionSwitch ( el ) {
var section = el.closest( '.accordion-section' ),
siblings = section.closest( '.accordion-container' ).find( '.open' ),
content = section.find( sectionContent );
if ( section.hasClass( 'cannot-expand' ) )
return;
if ( section.hasClass( 'open' ) ) {
section.toggleClass( 'open' );
content.toggle( true ).slideToggle( 150 );
} else {
siblings.removeClass( 'open' );
siblings.find( sectionContent ).show().slideUp( 150 );
content.toggle( false ).slideToggle( 150 );
section.toggleClass( 'open' );
}
accordionInit();
}
// Initialize the accordion (currently just corner fixes)
accordionInit();
})(jQuery);
| JavaScript |
/**
* WordPress Administration Navigation Menu
* Interface JS functions
*
* @version 2.0.0
*
* @package WordPress
* @subpackage Administration
*/
var wpNavMenu;
(function($) {
var api = wpNavMenu = {
options : {
menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
globalMaxDepth : 11
},
menuList : undefined, // Set in init.
targetList : undefined, // Set in init.
menusChanged : false,
isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
// Functions that run on init.
init : function() {
api.menuList = $('#menu-to-edit');
api.targetList = api.menuList;
this.jQueryExtensions();
this.attachMenuEditListeners();
this.setupInputWithDefaultTitle();
this.attachQuickSearchListeners();
this.attachThemeLocationsListeners();
this.attachTabsPanelListeners();
this.attachUnsavedChangesListener();
if ( api.menuList.length )
this.initSortables();
if ( menus.oneThemeLocationNoMenus )
$( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
this.initManageLocations();
this.initAccessibility();
this.initToggles();
},
jQueryExtensions : function() {
// jQuery extensions
$.fn.extend({
menuItemDepth : function() {
var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
},
updateDepthClass : function(current, prev) {
return this.each(function(){
var t = $(this);
prev = prev || t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ prev )
.addClass('menu-item-depth-'+ current );
});
},
shiftDepthClass : function(change) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ depth )
.addClass('menu-item-depth-'+ (depth + change) );
});
},
childMenuItems : function() {
var result = $();
this.each(function(){
var t = $(this), depth = t.menuItemDepth(), next = t.next();
while( next.length && next.menuItemDepth() > depth ) {
result = result.add( next );
next = next.next();
}
});
return result;
},
shiftHorizontally : function( dir ) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth(),
newDepth = depth + dir;
// Change .menu-item-depth-n class
t.moveHorizontally( newDepth, depth );
});
},
moveHorizontally : function( newDepth, depth ) {
return this.each(function(){
var t = $(this),
children = t.childMenuItems(),
diff = newDepth - depth,
subItemText = t.find('.is-submenu');
// Change .menu-item-depth-n class
t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
// If it has children, move those too
if ( children ) {
children.each(function( index ) {
var t = $(this),
thisDepth = t.menuItemDepth(),
newDepth = thisDepth + diff;
t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
});
}
// Show "Sub item" helper text
if (0 === newDepth)
subItemText.hide();
else
subItemText.show();
});
},
updateParentMenuItemDBId : function() {
return this.each(function(){
var item = $(this),
input = item.find( '.menu-item-data-parent-id' ),
depth = parseInt( item.menuItemDepth() ),
parentDepth = depth - 1,
parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
if ( 0 == depth ) { // Item is on the top level, has no parent
input.val(0);
} else { // Find the parent item, and retrieve its object id.
input.val( parent.find( '.menu-item-data-db-id' ).val() );
}
});
},
hideAdvancedMenuItemFields : function() {
return this.each(function(){
var that = $(this);
$('.hide-column-tog').not(':checked').each(function(){
that.find('.field-' + $(this).val() ).addClass('hidden-field');
});
});
},
/**
* Adds selected menu items to the menu.
*
* @param jQuery metabox The metabox jQuery object.
*/
addSelectedToMenu : function(processMethod) {
if ( 0 == $('#menu-to-edit').length ) {
return false;
}
return this.each(function() {
var t = $(this), menuItems = {},
checkboxes = ( menus.oneThemeLocationNoMenus && 0 == t.find('.tabs-panel-active .categorychecklist li input:checked').length ) ? t.find('#page-all li input[type="checkbox"]') : t.find('.tabs-panel-active .categorychecklist li input:checked'),
re = new RegExp('menu-item\\[(\[^\\]\]*)');
processMethod = processMethod || api.addMenuItemToBottom;
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
// Show the ajax spinner
t.find('.spinner').show();
// Retrieve menu item data
$(checkboxes).each(function(){
var t = $(this),
listItemDBIDMatch = re.exec( t.attr('name') ),
listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
if ( this.className && -1 != this.className.indexOf('add-to-top') )
processMethod = api.addMenuItemToTop;
menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
});
// Add the items
api.addItemToMenu(menuItems, processMethod, function(){
// Deselect the items and hide the ajax spinner
checkboxes.removeAttr('checked');
t.find('.spinner').hide();
});
});
},
getItemData : function( itemType, id ) {
itemType = itemType || 'menu-item';
var itemData = {}, i,
fields = [
'menu-item-db-id',
'menu-item-object-id',
'menu-item-object',
'menu-item-parent-id',
'menu-item-position',
'menu-item-type',
'menu-item-title',
'menu-item-url',
'menu-item-description',
'menu-item-attr-title',
'menu-item-target',
'menu-item-classes',
'menu-item-xfn'
];
if( !id && itemType == 'menu-item' ) {
id = this.find('.menu-item-data-db-id').val();
}
if( !id ) return itemData;
this.find('input').each(function() {
var field;
i = fields.length;
while ( i-- ) {
if( itemType == 'menu-item' )
field = fields[i] + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + fields[i] + ']';
if (
this.name &&
field == this.name
) {
itemData[fields[i]] = this.value;
}
}
});
return itemData;
},
setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
itemType = itemType || 'menu-item';
if( !id && itemType == 'menu-item' ) {
id = $('.menu-item-data-db-id', this).val();
}
if( !id ) return this;
this.find('input').each(function() {
var t = $(this), field;
$.each( itemData, function( attr, val ) {
if( itemType == 'menu-item' )
field = attr + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + attr + ']';
if ( field == t.attr('name') ) {
t.val( val );
}
});
});
return this;
}
});
},
countMenuItems : function( depth ) {
return $( '.menu-item-depth-' + depth ).length;
},
moveMenuItem : function( $this, dir ) {
var menuItems = $('#menu-to-edit li');
menuItemsCount = menuItems.length,
thisItem = $this.parents( 'li.menu-item' ),
thisItemChildren = thisItem.childMenuItems(),
thisItemData = thisItem.getItemData(),
thisItemDepth = parseInt( thisItem.menuItemDepth() ),
thisItemPosition = parseInt( thisItem.index() ),
nextItem = thisItem.next(),
nextItemChildren = nextItem.childMenuItems(),
nextItemDepth = parseInt( nextItem.menuItemDepth() ) + 1,
prevItem = thisItem.prev(),
prevItemDepth = parseInt( prevItem.menuItemDepth() ),
prevItemId = prevItem.getItemData()['menu-item-db-id'];
switch ( dir ) {
case 'up':
var newItemPosition = thisItemPosition - 1;
// Already at top
if ( 0 === thisItemPosition )
break;
// If a sub item is moved to top, shift it to 0 depth
if ( 0 === newItemPosition && 0 !== thisItemDepth )
thisItem.moveHorizontally( 0, thisItemDepth );
// If prev item is sub item, shift to match depth
if ( 0 !== prevItemDepth )
thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
// Does this item have sub items?
if ( thisItemChildren ) {
var items = thisItem.add( thisItemChildren );
// Move the entire block
items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
} else {
thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
}
break;
case 'down':
// Does this item have sub items?
if ( thisItemChildren ) {
var items = thisItem.add( thisItemChildren ),
nextItem = menuItems.eq( items.length + thisItemPosition ),
nextItemChildren = 0 !== nextItem.childMenuItems().length;
if ( nextItemChildren ) {
var newDepth = parseInt( nextItem.menuItemDepth() ) + 1;
thisItem.moveHorizontally( newDepth, thisItemDepth );
}
// Have we reached the bottom?
if ( menuItemsCount === thisItemPosition + items.length )
break;
items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
} else {
// If next item has sub items, shift depth
if ( 0 !== nextItemChildren.length )
thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
// Have we reached the bottom
if ( menuItemsCount === thisItemPosition + 1 )
break;
thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
}
break;
case 'top':
// Already at top
if ( 0 === thisItemPosition )
break;
// Does this item have sub items?
if ( thisItemChildren ) {
var items = thisItem.add( thisItemChildren );
// Move the entire block
items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
} else {
thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
}
break;
case 'left':
// As far left as possible
if ( 0 === thisItemDepth )
break;
thisItem.shiftHorizontally( -1 );
break;
case 'right':
// Can't be sub item at top
if ( 0 === thisItemPosition )
break;
// Already sub item of prevItem
if ( thisItemData['menu-item-parent-id'] === prevItemId )
break;
thisItem.shiftHorizontally( 1 );
break;
}
$this.focus();
api.registerChange();
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
initAccessibility : function() {
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
// Events
$( '.menus-move-up' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'up' );
e.preventDefault();
});
$( '.menus-move-down' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'down' );
e.preventDefault();
});
$( '.menus-move-top' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'top' );
e.preventDefault();
});
$( '.menus-move-left' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'left' );
e.preventDefault();
});
$( '.menus-move-right' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'right' );
e.preventDefault();
});
},
refreshAdvancedAccessibility : function() {
// Hide all links by default
$( '.menu-item-settings .field-move a' ).hide();
$( '.item-edit' ).each( function() {
var $this = $(this),
movement = [],
availableMovement = '',
menuItem = $this.parents( 'li.menu-item' ).first(),
depth = menuItem.menuItemDepth(),
isPrimaryMenuItem = ( 0 === depth ),
itemName = $this.parents( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
position = parseInt( menuItem.index() ),
prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1 ),
prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
totalMenuItems = $('#menu-to-edit li').length,
hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
// Where can they move this menu item?
if ( 0 !== position ) {
var thisLink = menuItem.find( '.menus-move-up' );
thisLink.prop( 'title', menus.moveUp ).show();
}
if ( 0 !== position && isPrimaryMenuItem ) {
var thisLink = menuItem.find( '.menus-move-top' );
thisLink.prop( 'title', menus.moveToTop ).show();
}
if ( position + 1 !== totalMenuItems && 0 !== position ) {
var thisLink = menuItem.find( '.menus-move-down' );
thisLink.prop( 'title', menus.moveDown ).show();
}
if ( 0 === position && 0 !== hasSameDepthSibling ) {
var thisLink = menuItem.find( '.menus-move-down' );
thisLink.prop( 'title', menus.moveDown ).show();
}
if ( ! isPrimaryMenuItem ) {
var thisLink = menuItem.find( '.menus-move-left' ),
thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).html( thisLinkText ).show();
}
if ( 0 !== position ) {
if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
var thisLink = menuItem.find( '.menus-move-right' ),
thisLinkText = menus.under.replace( '%s', prevItemNameRight );
thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).html( thisLinkText ).show();
}
}
if ( isPrimaryMenuItem ) {
var primaryItems = $( '.menu-item-depth-0' ),
itemPosition = primaryItems.index( menuItem ) + 1,
totalMenuItems = primaryItems.length,
// String together help text for primary menu items
title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems );
} else {
var parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1 ) ).first(),
parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
parentItemName = parentItem.find( '.menu-item-title' ).text(),
subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
// String together help text for sub menu items
title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName );
}
$this.prop('title', title).html( title );
});
},
refreshKeyboardAccessibility : function() {
$( '.item-edit' ).off( 'focus' ).on( 'focus', function(){
$(this).off( 'keydown' ).on( 'keydown', function(e){
var $this = $(this);
// Bail if it's not an arrow key
if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
return;
// Avoid multiple keydown events
$this.off('keydown');
// Bail if there is only one menu item
if ( 1 === $('#menu-to-edit li').length )
return;
// If RTL, swap left/right arrows
var arrows = { '38' : 'up', '40' : 'down', '37' : 'left', '39' : 'right' };
if ( $('body').hasClass('rtl') )
arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
switch ( arrows[e.which] ) {
case 'up':
api.moveMenuItem( $this, 'up' );
break;
case 'down':
api.moveMenuItem( $this, 'down' );
break;
case 'left':
api.moveMenuItem( $this, 'left' );
break;
case 'right':
api.moveMenuItem( $this, 'right' );
break;
}
// Put focus back on same menu item
$( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
return false;
});
});
},
initToggles : function() {
// init postboxes
postboxes.add_postbox_toggles('nav-menus');
// adjust columns functions for menus UI
columns.useCheckboxesForHidden();
columns.checked = function(field) {
$('.field-' + field).removeClass('hidden-field');
}
columns.unchecked = function(field) {
$('.field-' + field).addClass('hidden-field');
}
// hide fields
api.menuList.hideAdvancedMenuItemFields();
$('.hide-postbox-tog').click(function () {
var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: 'nav-menus'
});
});
},
initSortables : function() {
var currentDepth = 0, originalDepth, minDepth, maxDepth,
prev, next, prevBottom, nextThreshold, helperHeight, transport,
menuEdge = api.menuList.offset().left,
body = $('body'), maxChildDepth,
menuMaxDepth = initialMenuMaxDepth();
if( 0 != $( '#menu-to-edit li' ).length )
$( '.drag-instructions' ).show();
// Use the right edge if RTL.
menuEdge += api.isRTL ? api.menuList.width() : 0;
api.menuList.sortable({
handle: '.menu-item-handle',
placeholder: 'sortable-placeholder',
start: function(e, ui) {
var height, width, parent, children, tempHolder;
// handle placement for rtl orientation
if ( api.isRTL )
ui.item[0].style.right = 'auto';
transport = ui.item.children('.menu-item-transport');
// Set depths. currentDepth must be set before children are located.
originalDepth = ui.item.menuItemDepth();
updateCurrentDepth(ui, originalDepth);
// Attach child elements to parent
// Skip the placeholder
parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
children = parent.childMenuItems();
transport.append( children );
// Update the height of the placeholder to match the moving item.
height = transport.outerHeight();
// If there are children, account for distance between top of children and parent
height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
height += ui.helper.outerHeight();
helperHeight = height;
height -= 2; // Subtract 2 for borders
ui.placeholder.height(height);
// Update the width of the placeholder to match the moving item.
maxChildDepth = originalDepth;
children.each(function(){
var depth = $(this).menuItemDepth();
maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
});
width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
width -= 2; // Subtract 2 for borders
ui.placeholder.width(width);
// Update the list of menu items.
tempHolder = ui.placeholder.next();
tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
$(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know.
ui.item.after( ui.placeholder ); // reattach the placeholder.
tempHolder.css('margin-top', 0); // reset the margin
// Now that the element is complete, we can update...
updateSharedVars(ui);
},
stop: function(e, ui) {
var children, depthChange = currentDepth - originalDepth;
// Return child elements to the list
children = transport.children().insertAfter(ui.item);
// Add "sub menu" description
var subMenuTitle = ui.item.find( '.item-title .is-submenu' );
if ( 0 < currentDepth )
subMenuTitle.show();
else
subMenuTitle.hide();
// Update depth classes
if( depthChange != 0 ) {
ui.item.updateDepthClass( currentDepth );
children.shiftDepthClass( depthChange );
updateMenuMaxDepth( depthChange );
}
// Register a change
api.registerChange();
// Update the item data.
ui.item.updateParentMenuItemDBId();
// address sortable's incorrectly-calculated top in opera
ui.item[0].style.top = 0;
// handle drop placement for rtl orientation
if ( api.isRTL ) {
ui.item[0].style.left = 'auto';
ui.item[0].style.right = 0;
}
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
change: function(e, ui) {
// Make sure the placeholder is inside the menu.
// Otherwise fix it, or we're in trouble.
if( ! ui.placeholder.parent().hasClass('menu') )
(prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
updateSharedVars(ui);
},
sort: function(e, ui) {
var offset = ui.helper.offset(),
edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
// Check and correct if depth is not within range.
// Also, if the dragged element is dragged upwards over
// an item, shift the placeholder to a child position.
if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
else if ( depth < minDepth ) depth = minDepth;
if( depth != currentDepth )
updateCurrentDepth(ui, depth);
// If we overlap the next element, manually shift downwards
if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
next.after( ui.placeholder );
updateSharedVars( ui );
$(this).sortable( "refreshPositions" );
}
}
});
function updateSharedVars(ui) {
var depth;
prev = ui.placeholder.prev();
next = ui.placeholder.next();
// Make sure we don't select the moving item.
if( prev[0] == ui.item[0] ) prev = prev.prev();
if( next[0] == ui.item[0] ) next = next.next();
prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
minDepth = (next.length) ? next.menuItemDepth() : 0;
if( prev.length )
maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
else
maxDepth = 0;
}
function updateCurrentDepth(ui, depth) {
ui.placeholder.updateDepthClass( depth, currentDepth );
currentDepth = depth;
}
function initialMenuMaxDepth() {
if( ! body[0].className ) return 0;
var match = body[0].className.match(/menu-max-depth-(\d+)/);
return match && match[1] ? parseInt(match[1]) : 0;
}
function updateMenuMaxDepth( depthChange ) {
var depth, newDepth = menuMaxDepth;
if ( depthChange === 0 ) {
return;
} else if ( depthChange > 0 ) {
depth = maxChildDepth + depthChange;
if( depth > menuMaxDepth )
newDepth = depth;
} else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
newDepth--;
}
// Update the depth class.
body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
menuMaxDepth = newDepth;
}
},
initManageLocations : function () {
$('#menu-locations-wrap form').submit(function(){
window.onbeforeunload = null;
});
$('.menu-location-menus select').on('change', function () {
var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
if ($(this).find('option:selected').data('orig'))
editLink.show();
else
editLink.hide();
});
},
attachMenuEditListeners : function() {
var that = this;
$('#update-nav-menu').bind('click', function(e) {
if ( e.target && e.target.className ) {
if ( -1 != e.target.className.indexOf('item-edit') ) {
return that.eventOnClickEditLink(e.target);
} else if ( -1 != e.target.className.indexOf('menu-save') ) {
return that.eventOnClickMenuSave(e.target);
} else if ( -1 != e.target.className.indexOf('menu-delete') ) {
return that.eventOnClickMenuDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-delete') ) {
return that.eventOnClickMenuItemDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-cancel') ) {
return that.eventOnClickCancelLink(e.target);
}
}
});
$('#add-custom-links input[type="text"]').keypress(function(e){
if ( e.keyCode === 13 ) {
e.preventDefault();
$("#submit-customlinkdiv").click();
}
});
},
/**
* An interface for managing default values for input elements
* that is both JS and accessibility-friendly.
*
* Input elements that add the class 'input-with-default-title'
* will have their values set to the provided HTML title when empty.
*/
setupInputWithDefaultTitle : function() {
var name = 'input-with-default-title';
$('.' + name).each( function(){
var $t = $(this), title = $t.attr('title'), val = $t.val();
$t.data( name, title );
if( '' == val ) $t.val( title );
else if ( title == val ) return;
else $t.removeClass( name );
}).focus( function(){
var $t = $(this);
if( $t.val() == $t.data(name) )
$t.val('').removeClass( name );
}).blur( function(){
var $t = $(this);
if( '' == $t.val() )
$t.addClass( name ).val( $t.data(name) );
});
$( '.blank-slate .input-with-default-title' ).focus();
},
attachThemeLocationsListeners : function() {
var loc = $('#nav-menu-theme-locations'), params = {};
params['action'] = 'menu-locations-save';
params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
loc.find('input[type="submit"]').click(function() {
loc.find('select').each(function() {
params[this.name] = $(this).val();
});
loc.find('.spinner').show();
$.post( ajaxurl, params, function(r) {
loc.find('.spinner').hide();
});
return false;
});
},
attachQuickSearchListeners : function() {
var searchTimer;
$('.quick-search').keypress(function(e){
var t = $(this);
if( 13 == e.which ) {
api.updateQuickSearchResults( t );
return false;
}
if( searchTimer ) clearTimeout(searchTimer);
searchTimer = setTimeout(function(){
api.updateQuickSearchResults( t );
}, 400);
}).attr('autocomplete','off');
},
updateQuickSearchResults : function(input) {
var panel, params,
minSearchLength = 2,
q = input.val();
if( q.length < minSearchLength ) return;
panel = input.parents('.tabs-panel');
params = {
'action': 'menu-quick-search',
'response-format': 'markup',
'menu': $('#menu').val(),
'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
'q': q,
'type': input.attr('name')
};
$('.spinner', panel).show();
$.post( ajaxurl, params, function(menuMarkup) {
api.processQuickSearchQueryResponse(menuMarkup, params, panel);
});
},
addCustomLink : function( processMethod ) {
var url = $('#custom-menu-item-url').val(),
label = $('#custom-menu-item-name').val();
processMethod = processMethod || api.addMenuItemToBottom;
if ( '' == url || 'http://' == url )
return false;
// Show the ajax spinner
$('.customlinkdiv .spinner').show();
this.addLinkToMenu( url, label, processMethod, function() {
// Remove the ajax spinner
$('.customlinkdiv .spinner').hide();
// Set custom link form back to defaults
$('#custom-menu-item-name').val('').blur();
$('#custom-menu-item-url').val('http://');
});
},
addLinkToMenu : function(url, label, processMethod, callback) {
processMethod = processMethod || api.addMenuItemToBottom;
callback = callback || function(){};
api.addItemToMenu({
'-1': {
'menu-item-type': 'custom',
'menu-item-url': url,
'menu-item-title': label
}
}, processMethod, callback);
},
addItemToMenu : function(menuItem, processMethod, callback) {
var menu = $('#menu').val(),
nonce = $('#menu-settings-column-nonce').val();
processMethod = processMethod || function(){};
callback = callback || function(){};
params = {
'action': 'add-menu-item',
'menu': menu,
'menu-settings-column-nonce': nonce,
'menu-item': menuItem
};
$.post( ajaxurl, params, function(menuMarkup) {
var ins = $('#menu-instructions');
processMethod(menuMarkup, params);
// Make it stand out a bit more visually, by adding a fadeIn
$( 'li.pending' ).hide().fadeIn('slow');
$( '.drag-instructions' ).show();
if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
ins.addClass( 'menu-instructions-inactive' );
callback();
});
},
/**
* Process the add menu item request response into menu list item.
*
* @param string menuMarkup The text server response of menu item markup.
* @param object req The request arguments.
*/
addMenuItemToBottom : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
addMenuItemToTop : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
attachUnsavedChangesListener : function() {
$('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
api.registerChange();
});
if ( 0 != $('#menu-to-edit').length || 0 != $('.menu-location-menus select').length ) {
window.onbeforeunload = function(){
if ( api.menusChanged )
return navMenuL10n.saveAlert;
};
} else {
// Make the post boxes read-only, as they can't be used yet
$( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
}
},
registerChange : function() {
api.menusChanged = true;
},
attachTabsPanelListeners : function() {
$('#menu-settings-column').bind('click', function(e) {
var selectAreaMatch, panelId, wrapper, items,
target = $(e.target);
if ( target.hasClass('nav-tab-link') ) {
panelId = target.data( 'type' );
wrapper = target.parents('.accordion-section-content').first();
// upon changing tabs, we want to uncheck all checkboxes
$('input', wrapper).removeAttr('checked');
$('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
$('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
$('.tabs', wrapper).removeClass('tabs');
target.parent().addClass('tabs');
// select the search bar
$('.quick-search', wrapper).focus();
e.preventDefault();
} else if ( target.hasClass('select-all') ) {
selectAreaMatch = /#(.*)$/.exec(e.target.href);
if ( selectAreaMatch && selectAreaMatch[1] ) {
items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
if( items.length === items.filter(':checked').length )
items.removeAttr('checked');
else
items.prop('checked', true);
return false;
}
} else if ( target.hasClass('submit-add-to-menu') ) {
api.registerChange();
if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
api.addCustomLink( api.addMenuItemToBottom );
else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
$('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
return false;
} else if ( target.hasClass('page-numbers') ) {
$.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
function( resp ) {
if ( -1 == resp.indexOf('replace-id') )
return;
var metaBoxData = $.parseJSON(resp),
toReplace = document.getElementById(metaBoxData['replace-id']),
placeholder = document.createElement('div'),
wrap = document.createElement('div');
if ( ! metaBoxData['markup'] || ! toReplace )
return;
wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : '';
toReplace.parentNode.insertBefore( placeholder, toReplace );
placeholder.parentNode.removeChild( toReplace );
placeholder.parentNode.insertBefore( wrap, placeholder );
placeholder.parentNode.removeChild( placeholder );
}
);
return false;
}
});
},
eventOnClickEditLink : function(clickedEl) {
var settings, item,
matchedSection = /#(.*)$/.exec(clickedEl.href);
if ( matchedSection && matchedSection[1] ) {
settings = $('#'+matchedSection[1]);
item = settings.parent();
if( 0 != item.length ) {
if( item.hasClass('menu-item-edit-inactive') ) {
if( ! settings.data('menu-item-data') ) {
settings.data( 'menu-item-data', settings.getItemData() );
}
settings.slideDown('fast');
item.removeClass('menu-item-edit-inactive')
.addClass('menu-item-edit-active');
} else {
settings.slideUp('fast');
item.removeClass('menu-item-edit-active')
.addClass('menu-item-edit-inactive');
}
return false;
}
}
},
eventOnClickCancelLink : function(clickedEl) {
var settings = $( clickedEl ).closest( '.menu-item-settings' ),
thisMenuItem = $( clickedEl ).closest( '.menu-item' );
thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
settings.setItemData( settings.data('menu-item-data') ).hide();
return false;
},
eventOnClickMenuSave : function(clickedEl) {
var locs = '',
menuName = $('#menu-name'),
menuNameVal = menuName.val();
// Cancel and warn if invalid menu name
if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
menuName.parent().addClass('form-invalid');
return false;
}
// Copy menu theme locations
$('#nav-menu-theme-locations select').each(function() {
locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
});
$('#update-nav-menu').append( locs );
// Update menu item position data
api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
window.onbeforeunload = null;
return true;
},
eventOnClickMenuDelete : function(clickedEl) {
// Delete warning AYS
if ( confirm( navMenuL10n.warnDeleteMenu ) ) {
window.onbeforeunload = null;
return true;
}
return false;
},
eventOnClickMenuItemDelete : function(clickedEl) {
var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
api.removeMenuItem( $('#menu-item-' + itemID) );
api.registerChange();
return false;
},
/**
* Process the quick search response into a search result
*
* @param string resp The server response to the query.
* @param object req The request arguments.
* @param jQuery panel The tabs panel we're searching in.
*/
processQuickSearchQueryResponse : function(resp, req, panel) {
var matched, newID,
takenIDs = {},
form = document.getElementById('nav-menu-meta'),
pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'),
$items = $('<div>').html(resp).find('li'),
$item;
if( ! $items.length ) {
$('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
$('.spinner', panel).hide();
return;
}
$items.each(function(){
$item = $(this);
// make a unique DB ID number
matched = pattern.exec($item.html());
if ( matched && matched[1] ) {
newID = matched[1];
while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
newID--;
}
takenIDs[newID] = true;
if ( newID != matched[1] ) {
$item.html( $item.html().replace(new RegExp(
'menu-item\\[' + matched[1] + '\\]', 'g'),
'menu-item[' + newID + ']'
) );
}
}
});
$('.categorychecklist', panel).html( $items );
$('.spinner', panel).hide();
},
removeMenuItem : function(el) {
var children = el.childMenuItems();
el.addClass('deleting').animate({
opacity : 0,
height: 0
}, 350, function() {
var ins = $('#menu-instructions');
el.remove();
children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
if( 0 == $( '#menu-to-edit li' ).length ) {
$( '.drag-instructions' ).hide();
ins.removeClass( 'menu-instructions-inactive' );
}
});
},
depthToPx : function(depth) {
return depth * api.options.menuItemDepthPerLevel;
},
pxToDepth : function(px) {
return Math.floor(px / api.options.menuItemDepthPerLevel);
}
};
$(document).ready(function(){ wpNavMenu.init(); });
})(jQuery);
| JavaScript |
(function($) {
var frame;
$( function() {
// Fetch available headers and apply jQuery.masonry
// once the images have loaded.
var $headers = $('.available-headers');
$headers.imagesLoaded( function() {
$headers.masonry({
itemSelector: '.default-header',
isRTL: !! ( 'undefined' != typeof isRtl && isRtl )
});
});
// Build the choose from library frame.
$('#choose-from-library-link').click( function( event ) {
var $el = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.customHeader = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first(),
link = $el.data('updateLink');
// Tell the browser to navigate to the crop step.
window.location = link + '&file=' + attachment.id;
});
frame.open();
});
});
}(jQuery));
| JavaScript |
var tagBox, commentsBox, editPermalink, makeSlugeditClickable, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint;
// return an array with any duplicate, whitespace or values removed
function array_unique_noempty(a) {
var out = [];
jQuery.each( a, function(key, val) {
val = jQuery.trim(val);
if ( val && jQuery.inArray(val, out) == -1 )
out.push(val);
} );
return out;
}
(function($){
tagBox = {
clean : function(tags) {
var comma = postL10n.comma;
if ( ',' !== comma )
tags = tags.replace(new RegExp(comma, 'g'), ',');
tags = tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, '');
if ( ',' !== comma )
tags = tags.replace(/,/g, comma);
return tags;
},
parseTags : function(el) {
var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'),
thetags = taxbox.find('.the-tags'), comma = postL10n.comma,
current_tags = thetags.val().split(comma), new_tags = [];
delete current_tags[num];
$.each( current_tags, function(key, val) {
val = $.trim(val);
if ( val ) {
new_tags.push(val);
}
});
thetags.val( this.clean( new_tags.join(comma) ) );
this.quickClicks(taxbox);
return false;
},
quickClicks : function(el) {
var thetags = $('.the-tags', el),
tagchecklist = $('.tagchecklist', el),
id = $(el).attr('id'),
current_tags, disabled;
if ( !thetags.length )
return;
disabled = thetags.prop('disabled');
current_tags = thetags.val().split(postL10n.comma);
tagchecklist.empty();
$.each( current_tags, function( key, val ) {
var span, xbutton;
val = $.trim( val );
if ( ! val )
return;
// Create a new span, and ensure the text is properly escaped.
span = $('<span />').text( val );
// If tags editing isn't disabled, create the X button.
if ( ! disabled ) {
xbutton = $( '<a id="' + id + '-check-num-' + key + '" class="ntdelbutton">X</a>' );
xbutton.click( function(){ tagBox.parseTags(this); });
span.prepend(' ').prepend( xbutton );
}
// Append the span to the tag list.
tagchecklist.append( span );
});
},
flushTags : function(el, a, f) {
a = a || false;
var tags = $('.the-tags', el),
newtag = $('input.newtag', el),
comma = postL10n.comma,
newtags, text;
text = a ? $(a).text() : newtag.val();
tagsval = tags.val();
newtags = tagsval ? tagsval + comma + text : text;
newtags = this.clean( newtags );
newtags = array_unique_noempty( newtags.split(comma) ).join(comma);
tags.val(newtags);
this.quickClicks(el);
if ( !a )
newtag.val('');
if ( 'undefined' == typeof(f) )
newtag.focus();
return false;
},
get : function(id) {
var tax = id.substr(id.indexOf('-')+1);
$.post(ajaxurl, {'action':'get-tagcloud', 'tax':tax}, function(r, stat) {
if ( 0 == r || 'success' != stat )
r = wpAjax.broken;
r = $('<p id="tagcloud-'+tax+'" class="the-tagcloud">'+r+'</p>');
$('a', r).click(function(){
tagBox.flushTags( $(this).closest('.inside').children('.tagsdiv'), this);
return false;
});
$('#'+id).after(r);
});
},
init : function() {
var t = this, ajaxtag = $('div.ajaxtag');
$('.tagsdiv').each( function() {
tagBox.quickClicks(this);
});
$('input.tagadd', ajaxtag).click(function(){
t.flushTags( $(this).closest('.tagsdiv') );
});
$('div.taghint', ajaxtag).click(function(){
$(this).css('visibility', 'hidden').parent().siblings('.newtag').focus();
});
$('input.newtag', ajaxtag).blur(function() {
if ( this.value == '' )
$(this).parent().siblings('.taghint').css('visibility', '');
}).focus(function(){
$(this).parent().siblings('.taghint').css('visibility', 'hidden');
}).keyup(function(e){
if ( 13 == e.which ) {
tagBox.flushTags( $(this).closest('.tagsdiv') );
return false;
}
}).keypress(function(e){
if ( 13 == e.which ) {
e.preventDefault();
return false;
}
}).each(function(){
var tax = $(this).closest('div.tagsdiv').attr('id');
$(this).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: postL10n.comma + ' ' } );
});
// save tags on post save/publish
$('#post').submit(function(){
$('div.tagsdiv').each( function() {
tagBox.flushTags(this, false, 1);
});
});
// tag cloud
$('a.tagcloud-link').click(function(){
tagBox.get( $(this).attr('id') );
$(this).unbind().click(function(){
$(this).siblings('.the-tagcloud').toggle();
return false;
});
return false;
});
}
};
commentsBox = {
st : 0,
get : function(total, num) {
var st = this.st, data;
if ( ! num )
num = 20;
this.st += num;
this.total = total;
$('#commentsdiv .spinner').show();
data = {
'action' : 'get-comments',
'mode' : 'single',
'_ajax_nonce' : $('#add_comment_nonce').val(),
'p' : $('#post_ID').val(),
'start' : st,
'number' : num
};
$.post(ajaxurl, data,
function(r) {
r = wpAjax.parseAjaxResponse(r);
$('#commentsdiv .widefat').show();
$('#commentsdiv .spinner').hide();
if ( 'object' == typeof r && r.responses[0] ) {
$('#the-comment-list').append( r.responses[0].data );
theList = theExtraList = null;
$("a[className*=':']").unbind();
if ( commentsBox.st > commentsBox.total )
$('#show-comments').hide();
else
$('#show-comments').show().children('a').html(postL10n.showcomm);
return;
} else if ( 1 == r ) {
$('#show-comments').html(postL10n.endcomm);
return;
}
$('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>');
}
);
return false;
}
};
WPSetThumbnailHTML = function(html){
$('.inside', '#postimagediv').html(html);
};
WPSetThumbnailID = function(id){
var field = $('input[value="_thumbnail_id"]', '#list-table');
if ( field.size() > 0 ) {
$('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id);
}
};
WPRemoveThumbnail = function(nonce){
$.post(ajaxurl, {
action:"set-post-thumbnail", post_id: $('#post_ID').val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
WPSetThumbnailHTML(str);
}
}
);
};
$(document).on( 'heartbeat-send.refresh-lock', function( e, data ) {
var lock = $('#active_post_lock').val(),
post_id = $('#post_ID').val(),
send = {};
if ( ! post_id || ! $('#post-lock-dialog').length )
return;
send['post_id'] = post_id;
if ( lock )
send['lock'] = lock;
data['wp-refresh-post-lock'] = send;
});
// Post locks: update the lock string or show the dialog if somebody has taken over editing
$(document).on( 'heartbeat-tick.refresh-lock', function( e, data ) {
var received, wrap, avatar;
if ( data['wp-refresh-post-lock'] ) {
received = data['wp-refresh-post-lock'];
if ( received.lock_error ) {
// show "editing taken over" message
wrap = $('#post-lock-dialog');
if ( wrap.length && ! wrap.is(':visible') ) {
if ( typeof autosave == 'function' ) {
$(document).on('autosave-disable-buttons.post-lock', function() {
wrap.addClass('saving');
}).on('autosave-enable-buttons.post-lock', function() {
wrap.removeClass('saving').addClass('saved');
window.onbeforeunload = null;
});
// Save the latest changes and disable
if ( ! autosave() )
window.onbeforeunload = null;
autosave = function(){};
}
if ( received.lock_error.avatar_src ) {
avatar = $('<img class="avatar avatar-64 photo" width="64" height="64" />').attr( 'src', received.lock_error.avatar_src.replace(/&/g, '&') );
wrap.find('div.post-locked-avatar').empty().append( avatar );
}
wrap.show().find('.currently-editing').text( received.lock_error.text );
wrap.find('.wp-tab-first').focus();
}
} else if ( received.new_lock ) {
$('#active_post_lock').val( received.new_lock );
}
}
});
}(jQuery));
(function($) {
var check, timeout;
function schedule() {
check = false;
window.clearTimeout( timeout );
timeout = window.setTimeout( function(){ check = true; }, 300000 );
}
$(document).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) {
var nonce, post_id;
if ( check ) {
if ( ( post_id = $('#post_ID').val() ) && ( nonce = $('#_wpnonce').val() ) ) {
data['wp-refresh-post-nonces'] = {
post_id: post_id,
post_nonce: nonce
};
}
}
}).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) {
var nonces = data['wp-refresh-post-nonces'];
if ( nonces ) {
schedule();
if ( nonces.replace ) {
$.each( nonces.replace, function( selector, value ) {
$( '#' + selector ).val( value );
});
}
if ( nonces.heartbeatNonce )
window.heartbeatSettings.nonce = nonces.heartbeatNonce;
}
}).ready( function() {
schedule();
});
}(jQuery));
jQuery(document).ready( function($) {
var stamp, visibility, sticky = '', last = 0, co = $('#content');
postboxes.add_postbox_toggles(pagenow);
// Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item.
$('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) {
if ( e.which != 9 )
return;
var target = $(e.target);
if ( target.hasClass('wp-tab-first') && e.shiftKey ) {
$(this).find('.wp-tab-last').focus();
e.preventDefault();
} else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) {
$(this).find('.wp-tab-first').focus();
e.preventDefault();
}
}).filter(':visible').find('.wp-tab-first').focus();
// multi-taxonomies
if ( $('#tagsdiv-post_tag').length ) {
tagBox.init();
} else {
$('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){
if ( this.id.indexOf('tagsdiv-') === 0 ) {
tagBox.init();
return false;
}
});
}
// categories
$('.categorydiv').each( function(){
var this_id = $(this).attr('id'), catAddBefore, catAddAfter, taxonomyParts, taxonomy, settingName;
taxonomyParts = this_id.split('-');
taxonomyParts.shift();
taxonomy = taxonomyParts.join('-');
settingName = taxonomy + '_tab';
if ( taxonomy == 'category' )
settingName = 'cats';
// TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js
$('a', '#' + taxonomy + '-tabs').click( function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide();
$(t).show();
if ( '#' + taxonomy + '-all' == t )
deleteUserSetting(settingName);
else
setUserSetting(settingName, 'pop');
return false;
});
if ( getUserSetting(settingName) )
$('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click();
// Ajax Cat
$('#new' + taxonomy).one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#new' + taxonomy).keypress( function(event){
if( 13 === event.keyCode ) {
event.preventDefault();
$('#' + taxonomy + '-add-submit').click();
}
});
$('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); });
catAddBefore = function( s ) {
if ( !$('#new'+taxonomy).val() )
return false;
s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize();
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true );
return s;
};
catAddAfter = function( r, s ) {
var sup, drop = $('#new'+taxonomy+'_parent');
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false );
if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) {
drop.before(sup);
drop.remove();
}
};
$('#' + taxonomy + 'checklist').wpList({
alt: '',
response: taxonomy + '-ajax-response',
addBefore: catAddBefore,
addAfter: catAddAfter
});
$('#' + taxonomy + '-add-toggle').click( function() {
$('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' );
$('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click();
$('#new'+taxonomy).focus();
return false;
});
$('#' + taxonomy + 'checklist, #' + taxonomy + 'checklist-pop').on( 'click', 'li.popular-category > label input[type="checkbox"]', function() {
var t = $(this), c = t.is(':checked'), id = t.val();
if ( id && t.parents('#taxonomy-'+taxonomy).length )
$('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c );
});
}); // end cats
// Custom Fields
if ( $('#postcustom').length ) {
$('#the-list').wpList( { addAfter: function( xml, s ) {
$('table#list-table').show();
}, addBefore: function( s ) {
s.data += '&post_id=' + $('#post_ID').val();
return s;
}
});
}
// submitdiv
if ( $('#submitdiv').length ) {
stamp = $('#timestamp').html();
visibility = $('#post-visibility-display').html();
function updateVisibility() {
var pvSelect = $('#post-visibility-select');
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
$('#sticky-span').hide();
} else {
$('#sticky-span').show();
}
if ( $('input:radio:checked', pvSelect).val() != 'password' ) {
$('#password-span').hide();
} else {
$('#password-span').show();
}
}
function updateText() {
if ( ! $('#timestampdiv').length )
return true;
var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'),
optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(),
mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val();
attemptedDate = new Date( aa, mm - 1, jj, hh, mn );
originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() );
currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() );
if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) {
publishOn = postL10n.publishOnFuture;
$('#publish').val( postL10n.schedule );
} else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) {
publishOn = postL10n.publishOn;
$('#publish').val( postL10n.publish );
} else {
publishOn = postL10n.publishOnPast;
$('#publish').val( postL10n.update );
}
if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack
$('#timestamp').html(stamp);
} else {
$('#timestamp').html(
publishOn + ' <b>' +
postL10n.dateFormat.replace( '%1$s', $('option[value="' + $('#mm').val() + '"]', '#mm').text() )
.replace( '%2$s', jj )
.replace( '%3$s', aa )
.replace( '%4$s', hh )
.replace( '%5$s', mn )
+ '</b> '
);
}
if ( $('input:radio:checked', '#post-visibility-select').val() == 'private' ) {
$('#publish').val( postL10n.update );
if ( optPublish.length == 0 ) {
postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>');
} else {
optPublish.html( postL10n.privatelyPublished );
}
$('option[value="publish"]', postStatus).prop('selected', true);
$('.edit-post-status', '#misc-publishing-actions').hide();
} else {
if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) {
if ( optPublish.length ) {
optPublish.remove();
postStatus.val($('#hidden_post_status').val());
}
} else {
optPublish.html( postL10n.published );
}
if ( postStatus.is(':hidden') )
$('.edit-post-status', '#misc-publishing-actions').show();
}
$('#post-status-display').html($('option:selected', postStatus).text());
if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) {
$('#save-post').hide();
} else {
$('#save-post').show();
if ( $('option:selected', postStatus).val() == 'pending' ) {
$('#save-post').show().val( postL10n.savePending );
} else {
$('#save-post').show().val( postL10n.saveDraft );
}
}
return true;
}
$('.edit-visibility', '#visibility').click(function () {
if ($('#post-visibility-select').is(":hidden")) {
updateVisibility();
$('#post-visibility-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.cancel-post-visibility', '#post-visibility-select').click(function () {
$('#post-visibility-select').slideUp('fast');
$('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true);
$('#post_password').val($('#hidden-post-password').val());
$('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked'));
$('#post-visibility-display').html(visibility);
$('.edit-visibility', '#visibility').show();
updateText();
return false;
});
$('.save-post-visibility', '#post-visibility-select').click(function () { // crazyhorse - multiple ok cancels
var pvSelect = $('#post-visibility-select');
pvSelect.slideUp('fast');
$('.edit-visibility', '#visibility').show();
updateText();
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
} // WEAPON LOCKED
if ( true == $('#sticky').prop('checked') ) {
sticky = 'Sticky';
} else {
sticky = '';
}
$('#post-visibility-display').html( postL10n[$('input:radio:checked', pvSelect).val() + sticky] );
return false;
});
$('input:radio', '#post-visibility-select').change(function() {
updateVisibility();
});
$('#timestampdiv').siblings('a.edit-timestamp').click(function() {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown('fast');
$('#mm').focus();
$(this).hide();
}
return false;
});
$('.cancel-timestamp', '#timestampdiv').click(function() {
$('#timestampdiv').slideUp('fast');
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestampdiv').siblings('a.edit-timestamp').show();
updateText();
return false;
});
$('.save-timestamp', '#timestampdiv').click(function () { // crazyhorse - multiple ok cancels
if ( updateText() ) {
$('#timestampdiv').slideUp('fast');
$('#timestampdiv').siblings('a.edit-timestamp').show();
}
return false;
});
$('#post').on( 'submit', function(e){
if ( ! updateText() ) {
e.preventDefault();
$('#timestampdiv').show();
$('#publishing-action .spinner').hide();
$('#publish').prop('disabled', false).removeClass('button-primary-disabled');
return false;
}
});
$('#post-status-select').siblings('a.edit-post-status').click(function() {
if ($('#post-status-select').is(":hidden")) {
$('#post-status-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.save-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
$('.cancel-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post_status').val($('#hidden_post_status').val());
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
} // end submitdiv
// permalink
if ( $('#edit-slug-box').length ) {
editPermalink = function(post_id) {
var i, c = 0, e = $('#editable-post-name'), revert_e = e.html(), real_slug = $('#post_name'), revert_slug = real_slug.val(), b = $('#edit-slug-buttons'), revert_b = b.html(), full = $('#editable-post-name-full').html();
$('#view-post-btn').hide();
b.html('<a href="#" class="save button button-small">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>');
b.children('.save').click(function() {
var new_slug = e.children('input').val();
if ( new_slug == $('#editable-post-name-full').text() ) {
return $('.cancel', '#edit-slug-buttons').click();
}
$.post(ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_slug: new_slug,
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
}, function(data) {
var box = $('#edit-slug-box');
box.html(data);
if (box.hasClass('hidden')) {
box.fadeIn('fast', function () {
box.removeClass('hidden');
});
}
b.html(revert_b);
real_slug.val(new_slug);
makeSlugeditClickable();
$('#view-post-btn').show();
});
return false;
});
$('.cancel', '#edit-slug-buttons').click(function() {
$('#view-post-btn').show();
e.html(revert_e);
b.html(revert_b);
real_slug.val(revert_slug);
return false;
});
for ( i = 0; i < full.length; ++i ) {
if ( '%' == full.charAt(i) )
c++;
}
slug_value = ( c > full.length / 4 ) ? '' : full;
e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e) {
var key = e.keyCode || 0;
// on enter, just save the new slug, don't save the post
if ( 13 == key ) {
b.children('.save').click();
return false;
}
if ( 27 == key ) {
b.children('.cancel').click();
return false;
}
}).keyup(function(e) {
real_slug.val(this.value);
}).focus();
}
makeSlugeditClickable = function() {
$('#editable-post-name').click(function() {
$('#edit-slug-buttons').children('.edit-slug').click();
});
}
makeSlugeditClickable();
}
// word count
if ( typeof(wpWordCount) != 'undefined' ) {
$(document).triggerHandler('wpcountwords', [ co.val() ]);
co.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ co.val() ]);
last = k;
return true;
});
}
wptitlehint = function(id) {
id = id || 'title';
var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text');
if ( title.val() == '' )
titleprompt.removeClass('screen-reader-text');
titleprompt.click(function(){
$(this).addClass('screen-reader-text');
title.focus();
});
title.blur(function(){
if ( this.value == '' )
titleprompt.removeClass('screen-reader-text');
}).focus(function(){
titleprompt.addClass('screen-reader-text');
}).keydown(function(e){
titleprompt.addClass('screen-reader-text');
$(this).unbind(e);
});
}
wptitlehint();
// resizable textarea#content
(function() {
var textarea = $('textarea#content'), offset = null, el;
// No point for touch devices
if ( !textarea.length || 'ontouchstart' in window )
return;
function dragging(e) {
textarea.height( Math.max(50, offset + e.pageY) + 'px' );
return false;
}
function endDrag(e) {
var height;
textarea.focus();
$(document).unbind('mousemove', dragging).unbind('mouseup', endDrag);
height = parseInt( textarea.css('height'), 10 );
// sanity check
if ( height && height > 50 && height < 5000 )
setUserSetting( 'ed_size', height );
}
textarea.css('resize', 'none');
el = $('<div id="content-resize-handle"><br></div>');
$('#wp-content-wrap').append(el);
el.on('mousedown', function(e) {
offset = textarea.height() - e.pageY;
textarea.blur();
$(document).mousemove(dragging).mouseup(endDrag);
return false;
});
})();
if ( typeof(tinymce) != 'undefined' ) {
tinymce.onAddEditor.add(function(mce, ed){
// iOS expands the iframe to full height and the user cannot adjust it.
if ( ed.id != 'content' || tinymce.isIOS5 )
return;
function getHeight() {
var height, node = document.getElementById('content_ifr'),
ifr_height = node ? parseInt( node.style.height, 10 ) : 0,
tb_height = $('#content_tbl tr.mceFirst').height();
if ( !ifr_height || !tb_height )
return false;
// total height including toolbar and statusbar
height = ifr_height + tb_height + 21;
// textarea height = total height - 33px toolbar
height -= 33;
return height;
}
// resize TinyMCE to match the textarea height when switching Text -> Visual
ed.onLoadContent.add( function(ed, o) {
var ifr_height, node = document.getElementById('content'),
height = node ? parseInt( node.style.height, 10 ) : 0,
tb_height = $('#content_tbl tr.mceFirst').height() || 33;
// height cannot be under 50 or over 5000
if ( !height || height < 50 || height > 5000 )
height = 360; // default height for the main editor
if ( getUserSetting( 'ed_size' ) > 5000 )
setUserSetting( 'ed_size', 360 );
// compensate for padding and toolbars
ifr_height = ( height - tb_height ) + 12;
// sanity check
if ( ifr_height > 50 && ifr_height < 5000 ) {
$('#content_tbl').css('height', '' );
$('#content_ifr').css('height', ifr_height + 'px' );
}
});
// resize the textarea to match TinyMCE's height when switching Visual -> Text
ed.onSaveContent.add( function(ed, o) {
var height = getHeight();
if ( !height || height < 50 || height > 5000 )
return;
$('textarea#content').css( 'height', height + 'px' );
});
// save on resizing TinyMCE
ed.onPostRender.add(function() {
$('#content_resize').on('mousedown.wp-mce-resize', function(e){
$(document).on('mouseup.wp-mce-resize', function(e){
var height;
$(document).off('mouseup.wp-mce-resize');
height = getHeight();
// sanity check
if ( height && height > 50 && height < 5000 )
setUserSetting( 'ed_size', height );
});
});
});
});
// When changing post formats, change the editor body class
$('#post-formats-select input.post-format').on( 'change.set-editor-class', function( event ) {
var editor, body, format = this.id;
if ( format && $( this ).prop('checked') ) {
editor = tinymce.get( 'content' );
if ( editor ) {
body = editor.getBody();
body.className = body.className.replace( /\bpost-format-[^ ]+/, '' );
editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format );
}
}
});
}
});
| JavaScript |
/**
* PubSub
*
* A lightweight publish/subscribe implementation.
* Private use only!
*/
var PubSub, fullscreen, wptitlehint;
PubSub = function() {
this.topics = {};
};
PubSub.prototype.subscribe = function( topic, callback ) {
if ( ! this.topics[ topic ] )
this.topics[ topic ] = [];
this.topics[ topic ].push( callback );
return callback;
};
PubSub.prototype.unsubscribe = function( topic, callback ) {
var i, l,
topics = this.topics[ topic ];
if ( ! topics )
return callback || [];
// Clear matching callbacks
if ( callback ) {
for ( i = 0, l = topics.length; i < l; i++ ) {
if ( callback == topics[i] )
topics.splice( i, 1 );
}
return callback;
// Clear all callbacks
} else {
this.topics[ topic ] = [];
return topics;
}
};
PubSub.prototype.publish = function( topic, args ) {
var i, l, broken,
topics = this.topics[ topic ];
if ( ! topics )
return;
args = args || [];
for ( i = 0, l = topics.length; i < l; i++ ) {
broken = ( topics[i].apply( null, args ) === false || broken );
}
return ! broken;
};
/**
* Distraction Free Writing
* (wp-fullscreen)
*
* Access the API globally using the fullscreen variable.
*/
(function($){
var api, ps, bounder, s;
// Initialize the fullscreen/api object
fullscreen = api = {};
// Create the PubSub (publish/subscribe) interface.
ps = api.pubsub = new PubSub();
timer = 0;
block = false;
s = api.settings = { // Settings
visible : false,
mode : 'tinymce',
editor_id : 'content',
title_id : '',
timer : 0,
toolbar_shown : false
}
/**
* Bounder
*
* Creates a function that publishes start/stop topics.
* Used to throttle events.
*/
bounder = api.bounder = function( start, stop, delay, e ) {
var y, top;
delay = delay || 1250;
if ( e ) {
y = e.pageY || e.clientY || e.offsetY;
top = $(document).scrollTop();
if ( !e.isDefaultPrevented ) // test if e ic jQuery normalized
y = 135 + y;
if ( y - top > 120 )
return;
}
if ( block )
return;
block = true;
setTimeout( function() {
block = false;
}, 400 );
if ( s.timer )
clearTimeout( s.timer );
else
ps.publish( start );
function timed() {
ps.publish( stop );
s.timer = 0;
}
s.timer = setTimeout( timed, delay );
};
/**
* on()
*
* Turns fullscreen on.
*
* @param string mode Optional. Switch to the given mode before opening.
*/
api.on = function() {
if ( s.visible )
return;
// Settings can be added or changed by defining "wp_fullscreen_settings" JS object.
if ( typeof(wp_fullscreen_settings) == 'object' )
$.extend( s, wp_fullscreen_settings );
s.editor_id = wpActiveEditor || 'content';
if ( $('input#title').length && s.editor_id == 'content' )
s.title_id = 'title';
else if ( $('input#' + s.editor_id + '-title').length ) // the title input field should have [editor_id]-title HTML ID to be auto detected
s.title_id = s.editor_id + '-title';
else
$('#wp-fullscreen-title, #wp-fullscreen-title-prompt-text').hide();
s.mode = $('#' + s.editor_id).is(':hidden') ? 'tinymce' : 'html';
s.qt_canvas = $('#' + s.editor_id).get(0);
if ( ! s.element )
api.ui.init();
s.is_mce_on = s.has_tinymce && typeof( tinyMCE.get(s.editor_id) ) != 'undefined';
api.ui.fade( 'show', 'showing', 'shown' );
};
/**
* off()
*
* Turns fullscreen off.
*/
api.off = function() {
if ( ! s.visible )
return;
api.ui.fade( 'hide', 'hiding', 'hidden' );
};
/**
* switchmode()
*
* @return string - The current mode.
*
* @param string to - The fullscreen mode to switch to.
* @event switchMode
* @eventparam string to - The new mode.
* @eventparam string from - The old mode.
*/
api.switchmode = function( to ) {
var from = s.mode;
if ( ! to || ! s.visible || ! s.has_tinymce )
return from;
// Don't switch if the mode is the same.
if ( from == to )
return from;
ps.publish( 'switchMode', [ from, to ] );
s.mode = to;
ps.publish( 'switchedMode', [ from, to ] );
return to;
};
/**
* General
*/
api.save = function() {
var hidden = $('#hiddenaction'), old = hidden.val(), spinner = $('#wp-fullscreen-save .spinner'),
message = $('#wp-fullscreen-save span');
spinner.show();
api.savecontent();
hidden.val('wp-fullscreen-save-post');
$.post( ajaxurl, $('form#post').serialize(), function(r){
spinner.hide();
message.show();
setTimeout( function(){
message.fadeOut(1000);
}, 3000 );
if ( r.last_edited )
$('#wp-fullscreen-save input').attr( 'title', r.last_edited );
}, 'json');
hidden.val(old);
}
api.savecontent = function() {
var ed, content;
if ( s.title_id )
$('#' + s.title_id).val( $('#wp-fullscreen-title').val() );
if ( s.mode === 'tinymce' && (ed = tinyMCE.get('wp_mce_fullscreen')) ) {
content = ed.save();
} else {
content = $('#wp_mce_fullscreen').val();
}
$('#' + s.editor_id).val( content );
$(document).triggerHandler('wpcountwords', [ content ]);
}
set_title_hint = function( title ) {
if ( ! title.val().length )
title.siblings('label').css( 'visibility', '' );
else
title.siblings('label').css( 'visibility', 'hidden' );
}
api.dfw_width = function(n) {
var el = $('#wp-fullscreen-wrap'), w = el.width();
if ( !n ) { // reset to theme width
el.width( $('#wp-fullscreen-central-toolbar').width() );
deleteUserSetting('dfw_width');
return;
}
w = n + w;
if ( w < 200 || w > 1200 ) // sanity check
return;
el.width( w );
setUserSetting('dfw_width', w);
}
ps.subscribe( 'showToolbar', function() {
s.toolbars.removeClass('fade-1000').addClass('fade-300');
api.fade.In( s.toolbars, 300, function(){ ps.publish('toolbarShown'); }, true );
$('#wp-fullscreen-body').addClass('wp-fullscreen-focus');
s.toolbar_shown = true;
});
ps.subscribe( 'hideToolbar', function() {
s.toolbars.removeClass('fade-300').addClass('fade-1000');
api.fade.Out( s.toolbars, 1000, function(){ ps.publish('toolbarHidden'); }, true );
$('#wp-fullscreen-body').removeClass('wp-fullscreen-focus');
});
ps.subscribe( 'toolbarShown', function() {
s.toolbars.removeClass('fade-300');
});
ps.subscribe( 'toolbarHidden', function() {
s.toolbars.removeClass('fade-1000');
s.toolbar_shown = false;
});
ps.subscribe( 'show', function() { // This event occurs before the overlay blocks the UI.
var title;
if ( s.title_id ) {
title = $('#wp-fullscreen-title').val( $('#' + s.title_id).val() );
set_title_hint( title );
}
$('#wp-fullscreen-save input').attr( 'title', $('#last-edit').text() );
s.textarea_obj.value = s.qt_canvas.value;
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenInit');
s.orig_y = $(window).scrollTop();
});
ps.subscribe( 'showing', function() { // This event occurs while the DFW overlay blocks the UI.
$( document.body ).addClass( 'fullscreen-active' );
api.refresh_buttons();
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
bounder( 'showToolbar', 'hideToolbar', 2000 );
api.bind_resize();
setTimeout( api.resize_textarea, 200 );
// scroll to top so the user is not disoriented
scrollTo(0, 0);
// needed it for IE7 and compat mode
$('#wpadminbar').hide();
});
ps.subscribe( 'shown', function() { // This event occurs after the DFW overlay is shown
var interim_init;
s.visible = true;
// init the standard TinyMCE instance if missing
if ( s.has_tinymce && ! s.is_mce_on ) {
interim_init = function(mce, ed) {
var el = ed.getElement(), old_val = el.value, settings = tinyMCEPreInit.mceInit[s.editor_id];
if ( settings && settings.wpautop && typeof(switchEditors) != 'undefined' )
el.value = switchEditors.wpautop( el.value );
ed.onInit.add(function(ed) {
ed.hide();
ed.getElement().value = old_val;
tinymce.onAddEditor.remove(interim_init);
});
};
tinymce.onAddEditor.add(interim_init);
tinyMCE.init(tinyMCEPreInit.mceInit[s.editor_id]);
s.is_mce_on = true;
}
wpActiveEditor = 'wp_mce_fullscreen';
});
ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW.
var htmled_is_hidden = $('#' + s.editor_id).is(':hidden');
// Make sure the correct editor is displaying.
if ( s.has_tinymce && s.mode === 'tinymce' && !htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'tmce');
} else if ( s.mode === 'html' && htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'html');
}
// Save content must be after switchEditors or content will be overwritten. See #17229.
api.savecontent();
$( document ).unbind( '.fullscreen' );
$(s.textarea_obj).unbind('.grow');
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenSave');
if ( s.title_id )
set_title_hint( $('#' + s.title_id) );
s.qt_canvas.value = s.textarea_obj.value;
});
ps.subscribe( 'hiding', function() { // This event occurs while the overlay blocks the DFW UI.
$( document.body ).removeClass( 'fullscreen-active' );
scrollTo(0, s.orig_y);
$('#wpadminbar').show();
});
ps.subscribe( 'hidden', function() { // This event occurs after DFW is removed.
s.visible = false;
$('#wp_mce_fullscreen, #wp-fullscreen-title').removeAttr('style');
if ( s.has_tinymce && s.is_mce_on )
tinyMCE.execCommand('wpFullScreenClose');
s.textarea_obj.value = '';
api.oldheight = 0;
wpActiveEditor = s.editor_id;
});
ps.subscribe( 'switchMode', function( from, to ) {
var ed;
if ( !s.has_tinymce || !s.is_mce_on )
return;
ed = tinyMCE.get('wp_mce_fullscreen');
if ( from === 'html' && to === 'tinymce' ) {
if ( tinyMCE.get(s.editor_id).getParam('wpautop') && typeof(switchEditors) != 'undefined' )
s.textarea_obj.value = switchEditors.wpautop( s.textarea_obj.value );
if ( 'undefined' == typeof(ed) )
tinyMCE.execCommand('wpFullScreenInit');
else
ed.show();
} else if ( from === 'tinymce' && to === 'html' ) {
if ( ed )
ed.hide();
}
});
ps.subscribe( 'switchedMode', function( from, to ) {
api.refresh_buttons(true);
if ( to === 'html' )
setTimeout( api.resize_textarea, 200 );
});
/**
* Buttons
*/
api.b = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Bold');
}
api.i = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Italic');
}
api.ul = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertUnorderedList');
}
api.ol = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertOrderedList');
}
api.link = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Link');
else
wpLink.open();
}
api.unlink = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('unlink');
}
api.atd = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceWritingImprovementTool');
}
api.help = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Help');
}
api.blockquote = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceBlockQuote');
}
api.medialib = function() {
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor )
wp.media.editor.open(s.editor_id);
}
api.refresh_buttons = function( fade ) {
fade = fade || false;
if ( s.mode === 'html' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-tmce-mode').addClass('wp-html-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).addClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').addClass('wp-html-mode');
} else if ( s.mode === 'tinymce' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-html-mode').addClass('wp-tmce-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).removeClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').removeClass('wp-html-mode');
}
}
/**
* UI Elements
*
* Used for transitioning between states.
*/
api.ui = {
init: function() {
var topbar = $('#fullscreen-topbar'), txtarea = $('#wp_mce_fullscreen'), last = 0;
s.toolbars = topbar.add( $('#wp-fullscreen-status') );
s.element = $('#fullscreen-fader');
s.textarea_obj = txtarea[0];
s.has_tinymce = typeof(tinymce) != 'undefined';
if ( !s.has_tinymce )
$('#wp-fullscreen-mode-bar').hide();
if ( wptitlehint && $('#wp-fullscreen-title').length )
wptitlehint('wp-fullscreen-title');
$(document).keyup(function(e){
var c = e.keyCode || e.charCode, a, data;
if ( !fullscreen.settings.visible )
return true;
if ( navigator.platform && navigator.platform.indexOf('Mac') != -1 )
a = e.ctrlKey; // Ctrl key for Mac
else
a = e.altKey; // Alt key for Win & Linux
if ( 27 == c ) { // Esc
data = {
event: e,
what: 'dfw',
cb: fullscreen.off,
condition: function(){
if ( $('#TB_window').is(':visible') || $('.wp-dialog').is(':visible') )
return false;
return true;
}
};
if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [data] ) )
fullscreen.off();
}
if ( a && (61 == c || 107 == c || 187 == c) ) // +
api.dfw_width(25);
if ( a && (45 == c || 109 == c || 189 == c) ) // -
api.dfw_width(-25);
if ( a && 48 == c ) // 0
api.dfw_width(0);
return false;
});
// word count in Text mode
if ( typeof(wpWordCount) != 'undefined' ) {
txtarea.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ txtarea.val() ]);
last = k;
return true;
});
}
topbar.mouseenter(function(e){
s.toolbars.addClass('fullscreen-make-sticky');
$( document ).unbind( '.fullscreen' );
clearTimeout( s.timer );
s.timer = 0;
}).mouseleave(function(e){
s.toolbars.removeClass('fullscreen-make-sticky');
if ( s.visible )
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
});
},
fade: function( before, during, after ) {
if ( ! s.element )
api.ui.init();
// If any callback bound to before returns false, bail.
if ( before && ! ps.publish( before ) )
return;
api.fade.In( s.element, 600, function() {
if ( during )
ps.publish( during );
api.fade.Out( s.element, 600, function() {
if ( after )
ps.publish( after );
})
});
}
};
api.fade = {
transitionend: 'transitionend webkitTransitionEnd oTransitionEnd',
// Sensitivity to allow browsers to render the blank element before animating.
sensitivity: 100,
In: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( api.fade.transitions ) {
if ( element.is(':visible') ) {
element.addClass( 'fade-trigger' );
return element;
}
element.show();
element.first().one( this.transitionend, function() {
callback();
});
setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.css( 'opacity', 1 );
element.first().fadeIn( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeIn( speed );
}
return element;
},
Out: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( ! element.is(':visible') )
return element;
if ( api.fade.transitions ) {
element.first().one( api.fade.transitionend, function() {
if ( element.hasClass('fade-trigger') )
return;
element.hide();
callback();
});
setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.first().fadeOut( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeOut( speed );
}
return element;
},
transitions: (function() { // Check if the browser supports CSS 3.0 transitions
var s = document.documentElement.style;
return ( typeof ( s.WebkitTransition ) == 'string' ||
typeof ( s.MozTransition ) == 'string' ||
typeof ( s.OTransition ) == 'string' ||
typeof ( s.transition ) == 'string' );
})()
};
/**
* Resize API
*
* Automatically updates textarea height.
*/
api.bind_resize = function() {
$(s.textarea_obj).bind('keypress.grow click.grow paste.grow', function(){
setTimeout( api.resize_textarea, 200 );
});
}
api.oldheight = 0;
api.resize_textarea = function() {
var txt = s.textarea_obj, newheight;
newheight = txt.scrollHeight > 300 ? txt.scrollHeight : 300;
if ( newheight != api.oldheight ) {
txt.style.height = newheight + 'px';
api.oldheight = newheight;
}
};
})(jQuery);
| JavaScript |
var thickDims, tbWidth, tbHeight;
jQuery(document).ready(function($) {
thickDims = function() {
var tbWindow = $('#TB_window'), H = $(window).height(), W = $(window).width(), w, h;
w = (tbWidth && tbWidth < W - 90) ? tbWidth : W - 90;
h = (tbHeight && tbHeight < H - 60) ? tbHeight : H - 60;
if ( tbWindow.size() ) {
tbWindow.width(w).height(h);
$('#TB_iframeContent').width(w).height(h - 27);
tbWindow.css({'margin-left': '-' + parseInt((w / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top':'30px','margin-top':'0'});
}
};
thickDims();
$(window).resize( function() { thickDims() } );
$('a.thickbox-preview').click( function() {
tb_click.call(this);
var alink = $(this).parents('.available-theme').find('.activatelink'), link = '', href = $(this).attr('href'), url, text;
if ( tbWidth = href.match(/&tbWidth=[0-9]+/) )
tbWidth = parseInt(tbWidth[0].replace(/[^0-9]+/g, ''), 10);
else
tbWidth = $(window).width() - 90;
if ( tbHeight = href.match(/&tbHeight=[0-9]+/) )
tbHeight = parseInt(tbHeight[0].replace(/[^0-9]+/g, ''), 10);
else
tbHeight = $(window).height() - 60;
if ( alink.length ) {
url = alink.attr('href') || '';
text = alink.attr('title') || '';
link = ' <a href="' + url + '" target="_top" class="tb-theme-preview-link">' + text + '</a>';
} else {
text = $(this).attr('title') || '';
link = ' <span class="tb-theme-preview-link">' + text + '</span>';
}
$('#TB_title').css({'background-color':'#222','color':'#dfdfdf'});
$('#TB_closeAjaxWindow').css({'float':'left'});
$('#TB_ajaxWindowTitle').css({'float':'right'}).html(link);
$('#TB_iframeContent').width('100%');
thickDims();
return false;
} );
});
| JavaScript |
/*!
* Farbtastic: jQuery color picker plug-in v1.3u
*
* Licensed under the GPL license:
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
$.fn.farbtastic = function (options) {
$.farbtastic(this, options);
return this;
};
$.farbtastic = function (container, callback) {
var container = $(container).get(0);
return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback));
};
$._farbtastic = function (container, callback) {
// Store farbtastic object
var fb = this;
// Insert markup
$(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>');
var e = $('.farbtastic', container);
fb.wheel = $('.wheel', container).get(0);
// Dimensions
fb.radius = 84;
fb.square = 100;
fb.width = 194;
// Fix background PNGs in IE6
if (navigator.appVersion.match(/MSIE [0-6]\./)) {
$('*', e).each(function () {
if (this.currentStyle.backgroundImage != 'none') {
var image = this.currentStyle.backgroundImage;
image = this.currentStyle.backgroundImage.substring(5, image.length - 2);
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
});
}
});
}
/**
* Link to the given element(s) or callback.
*/
fb.linkTo = function (callback) {
// Unbind previous nodes
if (typeof fb.callback == 'object') {
$(fb.callback).unbind('keyup', fb.updateValue);
}
// Reset color
fb.color = null;
// Bind callback or elements
if (typeof callback == 'function') {
fb.callback = callback;
}
else if (typeof callback == 'object' || typeof callback == 'string') {
fb.callback = $(callback);
fb.callback.bind('keyup', fb.updateValue);
if (fb.callback.get(0).value) {
fb.setColor(fb.callback.get(0).value);
}
}
return this;
};
fb.updateValue = function (event) {
if (this.value && this.value != fb.color) {
fb.setColor(this.value);
}
};
/**
* Change color with HTML syntax #123456
*/
fb.setColor = function (color) {
var unpack = fb.unpack(color);
if (fb.color != color && unpack) {
fb.color = color;
fb.rgb = unpack;
fb.hsl = fb.RGBToHSL(fb.rgb);
fb.updateDisplay();
}
return this;
};
/**
* Change color with HSL triplet [0..1, 0..1, 0..1]
*/
fb.setHSL = function (hsl) {
fb.hsl = hsl;
fb.rgb = fb.HSLToRGB(hsl);
fb.color = fb.pack(fb.rgb);
fb.updateDisplay();
return this;
};
/////////////////////////////////////////////////////
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*/
fb.widgetCoords = function (event) {
var offset = $(fb.wheel).offset();
return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 };
};
/**
* Mousedown handler
*/
fb.mousedown = function (event) {
// Capture mouse
if (!document.dragging) {
$(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
document.dragging = true;
}
// Check which area is being dragged
var pos = fb.widgetCoords(event);
fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square;
// Process
fb.mousemove(event);
return false;
};
/**
* Mousemove handler
*/
fb.mousemove = function (event) {
// Get coordinates relative to color picker center
var pos = fb.widgetCoords(event);
// Set new HSL parameters
if (fb.circleDrag) {
var hue = Math.atan2(pos.x, -pos.y) / 6.28;
if (hue < 0) hue += 1;
fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]);
}
else {
var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5));
var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5));
fb.setHSL([fb.hsl[0], sat, lum]);
}
return false;
};
/**
* Mouseup handler
*/
fb.mouseup = function () {
// Uncapture mouse
$(document).unbind('mousemove', fb.mousemove);
$(document).unbind('mouseup', fb.mouseup);
document.dragging = false;
};
/**
* Update the markers and styles
*/
fb.updateDisplay = function () {
// Markers
var angle = fb.hsl[0] * 6.28;
$('.h-marker', e).css({
left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
});
$('.sl-marker', e).css({
left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px',
top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px'
});
// Saturation/Luminance gradient
$('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
// Linked elements or callback
if (typeof fb.callback == 'object') {
// Set background/foreground color
$(fb.callback).css({
backgroundColor: fb.color,
color: fb.hsl[2] > 0.5 ? '#000' : '#fff'
});
// Change linked value
$(fb.callback).each(function() {
if (this.value && this.value != fb.color) {
this.value = fb.color;
}
});
}
else if (typeof fb.callback == 'function') {
fb.callback.call(fb, fb.color);
}
};
/* Various color utility functions */
fb.pack = function (rgb) {
var r = Math.round(rgb[0] * 255);
var g = Math.round(rgb[1] * 255);
var b = Math.round(rgb[2] * 255);
return '#' + (r < 16 ? '0' : '') + r.toString(16) +
(g < 16 ? '0' : '') + g.toString(16) +
(b < 16 ? '0' : '') + b.toString(16);
};
fb.unpack = function (color) {
if (color.length == 7) {
return [parseInt('0x' + color.substring(1, 3)) / 255,
parseInt('0x' + color.substring(3, 5)) / 255,
parseInt('0x' + color.substring(5, 7)) / 255];
}
else if (color.length == 4) {
return [parseInt('0x' + color.substring(1, 2)) / 15,
parseInt('0x' + color.substring(2, 3)) / 15,
parseInt('0x' + color.substring(3, 4)) / 15];
}
};
fb.HSLToRGB = function (hsl) {
var m1, m2, r, g, b;
var h = hsl[0], s = hsl[1], l = hsl[2];
m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
m1 = l * 2 - m2;
return [this.hueToRGB(m1, m2, h+0.33333),
this.hueToRGB(m1, m2, h),
this.hueToRGB(m1, m2, h-0.33333)];
};
fb.hueToRGB = function (m1, m2, h) {
h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
return m1;
};
fb.RGBToHSL = function (rgb) {
var min, max, delta, h, s, l;
var r = rgb[0], g = rgb[1], b = rgb[2];
min = Math.min(r, Math.min(g, b));
max = Math.max(r, Math.max(g, b));
delta = max - min;
l = (min + max) / 2;
s = 0;
if (l > 0 && l < 1) {
s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
}
h = 0;
if (delta > 0) {
if (max == r && max != g) h += (g - b) / delta;
if (max == g && max != b) h += (2 + (b - r) / delta);
if (max == b && max != r) h += (4 + (r - g) / delta);
h /= 6;
}
return [h, s, l];
};
// Install mousedown handler (the others are set on the document on-demand)
$('*', e).mousedown(fb.mousedown);
// Init color
fb.setColor('#000000');
// Set linked elements/callback
if (callback) {
fb.linkTo(callback);
}
};
})(jQuery); | JavaScript |
jQuery(document).ready( function($) {
postboxes.add_postbox_toggles('comment');
var stamp = $('#timestamp').html();
$('.edit-timestamp').click(function () {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown("normal");
$('.edit-timestamp').hide();
}
return false;
});
$('.cancel-timestamp').click(function() {
$('#timestampdiv').slideUp("normal");
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestamp').html(stamp);
$('.edit-timestamp').show();
return false;
});
$('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels
var aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(),
newD = new Date( aa, mm - 1, jj, hh, mn );
if ( newD.getFullYear() != aa || (1 + newD.getMonth()) != mm || newD.getDate() != jj || newD.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
$('#timestampdiv').slideUp("normal");
$('.edit-timestamp').show();
$('#timestamp').html(
commentL10n.submittedOn + ' <b>' +
$( '#mm option[value="' + mm + '"]' ).text() + ' ' +
jj + ', ' +
aa + ' @ ' +
hh + ':' +
mn + '</b> '
);
return false;
});
});
| JavaScript |
function WPSetAsThumbnail(id, nonce){
var $link = jQuery('a#wp-post-thumbnail-' + id);
$link.text( setPostThumbnailL10n.saving );
jQuery.post(ajaxurl, {
action:"set-post-thumbnail", post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
var win = window.dialogArguments || opener || parent || top;
$link.text( setPostThumbnailL10n.setThumbnail );
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
jQuery('a.wp-post-thumbnail').show();
$link.text( setPostThumbnailL10n.done );
$link.fadeOut( 2000 );
win.WPSetThumbnailID(id);
win.WPSetThumbnailHTML(str);
}
}
);
}
| JavaScript |
// Password strength meter
function passwordStrength(password1, username, password2) {
var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score;
// password 1 != password 2
if ( (password1 != password2) && password2.length > 0)
return mismatch
//password < 4
if ( password1.length < 4 )
return shortPass
//password1 == username
if ( password1.toLowerCase() == username.toLowerCase() )
return badPass;
if ( password1.match(/[0-9]/) )
symbolSize +=10;
if ( password1.match(/[a-z]/) )
symbolSize +=26;
if ( password1.match(/[A-Z]/) )
symbolSize +=26;
if ( password1.match(/[^a-zA-Z0-9]/) )
symbolSize +=31;
natLog = Math.log( Math.pow(symbolSize, password1.length) );
score = natLog / Math.LN2;
if (score < 40 )
return badPass
if (score < 56 )
return goodPass
return strongPass;
}
| JavaScript |
window.wp = window.wp || {};
(function($) {
var revisions;
revisions = wp.revisions = { model: {}, view: {}, controller: {} };
// Link settings.
revisions.settings = _.isUndefined( _wpRevisionsSettings ) ? {} : _wpRevisionsSettings;
// For debugging
revisions.debug = false;
revisions.log = function() {
if ( window.console && revisions.debug )
console.log.apply( console, arguments );
};
// Handy functions to help with positioning
$.fn.allOffsets = function() {
var offset = this.offset() || {top: 0, left: 0}, win = $(window);
return _.extend( offset, {
right: win.width() - offset.left - this.outerWidth(),
bottom: win.height() - offset.top - this.outerHeight()
});
};
$.fn.allPositions = function() {
var position = this.position() || {top: 0, left: 0}, parent = this.parent();
return _.extend( position, {
right: parent.outerWidth() - position.left - this.outerWidth(),
bottom: parent.outerHeight() - position.top - this.outerHeight()
});
};
// wp_localize_script transforms top-level numbers into strings. Undo that.
if ( revisions.settings.to )
revisions.settings.to = parseInt( revisions.settings.to, 10 );
if ( revisions.settings.from )
revisions.settings.from = parseInt( revisions.settings.from, 10 );
// wp_localize_script does not allow for top-level booleans. Fix that.
if ( revisions.settings.compareTwoMode )
revisions.settings.compareTwoMode = revisions.settings.compareTwoMode === '1';
/**
* ========================================================================
* MODELS
* ========================================================================
*/
revisions.model.Slider = Backbone.Model.extend({
defaults: {
value: null,
values: null,
min: 0,
max: 1,
step: 1,
range: false,
compareTwoMode: false
},
initialize: function( options ) {
this.frame = options.frame;
this.revisions = options.revisions;
// Listen for changes to the revisions or mode from outside
this.listenTo( this.frame, 'update:revisions', this.receiveRevisions );
this.listenTo( this.frame, 'change:compareTwoMode', this.updateMode );
// Listen for internal changes
this.listenTo( this, 'change:from', this.handleLocalChanges );
this.listenTo( this, 'change:to', this.handleLocalChanges );
this.listenTo( this, 'change:compareTwoMode', this.updateSliderSettings );
this.listenTo( this, 'update:revisions', this.updateSliderSettings );
// Listen for changes to the hovered revision
this.listenTo( this, 'change:hoveredRevision', this.hoverRevision );
this.set({
max: this.revisions.length - 1,
compareTwoMode: this.frame.get('compareTwoMode'),
from: this.frame.get('from'),
to: this.frame.get('to')
});
this.updateSliderSettings();
},
getSliderValue: function( a, b ) {
return isRtl ? this.revisions.length - this.revisions.indexOf( this.get(a) ) - 1 : this.revisions.indexOf( this.get(b) );
},
updateSliderSettings: function() {
if ( this.get('compareTwoMode') ) {
this.set({
values: [
this.getSliderValue( 'to', 'from' ),
this.getSliderValue( 'from', 'to' )
],
value: null,
range: true // ensures handles cannot cross
});
} else {
this.set({
value: this.getSliderValue( 'to', 'to' ),
values: null,
range: false
});
}
this.trigger( 'update:slider' );
},
// Called when a revision is hovered
hoverRevision: function( model, value ) {
this.trigger( 'hovered:revision', value );
},
// Called when `compareTwoMode` changes
updateMode: function( model, value ) {
this.set({ compareTwoMode: value });
},
// Called when `from` or `to` changes in the local model
handleLocalChanges: function() {
this.frame.set({
from: this.get('from'),
to: this.get('to')
});
},
// Receives revisions changes from outside the model
receiveRevisions: function( from, to ) {
// Bail if nothing changed
if ( this.get('from') === from && this.get('to') === to )
return;
this.set({ from: from, to: to }, { silent: true });
this.trigger( 'update:revisions', from, to );
}
});
revisions.model.Tooltip = Backbone.Model.extend({
defaults: {
revision: null,
offset: {},
hovering: false, // Whether the mouse is hovering
scrubbing: false // Whether the mouse is scrubbing
},
initialize: function( options ) {
this.frame = options.frame;
this.revisions = options.revisions;
this.slider = options.slider;
this.listenTo( this.slider, 'hovered:revision', this.updateRevision );
this.listenTo( this.slider, 'change:hovering', this.setHovering );
this.listenTo( this.slider, 'change:scrubbing', this.setScrubbing );
},
updateRevision: function( revision ) {
this.set({ revision: revision });
},
setHovering: function( model, value ) {
this.set({ hovering: value });
},
setScrubbing: function( model, value ) {
this.set({ scrubbing: value });
}
});
revisions.model.Revision = Backbone.Model.extend({});
revisions.model.Revisions = Backbone.Collection.extend({
model: revisions.model.Revision,
initialize: function() {
_.bindAll( this, 'next', 'prev' );
},
next: function( revision ) {
var index = this.indexOf( revision );
if ( index !== -1 && index !== this.length - 1 )
return this.at( index + 1 );
},
prev: function( revision ) {
var index = this.indexOf( revision );
if ( index !== -1 && index !== 0 )
return this.at( index - 1 );
}
});
revisions.model.Field = Backbone.Model.extend({});
revisions.model.Fields = Backbone.Collection.extend({
model: revisions.model.Field
});
revisions.model.Diff = Backbone.Model.extend({
initialize: function( attributes, options ) {
var fields = this.get('fields');
this.unset('fields');
this.fields = new revisions.model.Fields( fields );
}
});
revisions.model.Diffs = Backbone.Collection.extend({
initialize: function( models, options ) {
_.bindAll( this, 'getClosestUnloaded' );
this.loadAll = _.once( this._loadAll );
this.revisions = options.revisions;
this.requests = {};
},
model: revisions.model.Diff,
ensure: function( id, context ) {
var diff = this.get( id );
var request = this.requests[ id ];
var deferred = $.Deferred();
var ids = {};
var from = id.split(':')[0];
var to = id.split(':')[1];
ids[id] = true;
wp.revisions.log( 'ensure', id );
this.trigger( 'ensure', ids, from, to, deferred.promise() );
if ( diff ) {
deferred.resolveWith( context, [ diff ] );
} else {
this.trigger( 'ensure:load', ids, from, to, deferred.promise() );
_.each( ids, _.bind( function( id ) {
// Remove anything that has an ongoing request
if ( this.requests[ id ] )
delete ids[ id ];
// Remove anything we already have
if ( this.get( id ) )
delete ids[ id ];
}, this ) );
if ( ! request ) {
// Always include the ID that started this ensure
ids[ id ] = true;
request = this.load( _.keys( ids ) );
}
request.done( _.bind( function() {
deferred.resolveWith( context, [ this.get( id ) ] );
}, this ) ).fail( _.bind( function() {
deferred.reject();
}) );
}
return deferred.promise();
},
// Returns an array of proximal diffs
getClosestUnloaded: function( ids, centerId ) {
var self = this;
return _.chain([0].concat( ids )).initial().zip( ids ).sortBy( function( pair ) {
return Math.abs( centerId - pair[1] );
}).map( function( pair ) {
return pair.join(':');
}).filter( function( diffId ) {
return _.isUndefined( self.get( diffId ) ) && ! self.requests[ diffId ];
}).value();
},
_loadAll: function( allRevisionIds, centerId, num ) {
var self = this, deferred = $.Deferred();
diffs = _.first( this.getClosestUnloaded( allRevisionIds, centerId ), num );
if ( _.size( diffs ) > 0 ) {
this.load( diffs ).done( function() {
self._loadAll( allRevisionIds, centerId, num ).done( function() {
deferred.resolve();
});
}).fail( function() {
if ( 1 === num ) { // Already tried 1. This just isn't working. Give up.
deferred.reject();
} else { // Request fewer diffs this time
self._loadAll( allRevisionIds, centerId, Math.ceil( num / 2 ) ).done( function() {
deferred.resolve();
});
}
});
} else {
deferred.resolve();
}
return deferred;
},
load: function( comparisons ) {
wp.revisions.log( 'load', comparisons );
// Our collection should only ever grow, never shrink, so remove: false
return this.fetch({ data: { compare: comparisons }, remove: false }).done( function(){
wp.revisions.log( 'load:complete', comparisons );
});
},
sync: function( method, model, options ) {
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'get-revision-diffs',
post_id: revisions.settings.postId
});
var deferred = wp.ajax.send( options );
var requests = this.requests;
// Record that we're requesting each diff.
if ( options.data.compare ) {
_.each( options.data.compare, function( id ) {
requests[ id ] = deferred;
});
}
// When the request completes, clear the stored request.
deferred.always( function() {
if ( options.data.compare ) {
_.each( options.data.compare, function( id ) {
delete requests[ id ];
});
}
});
return deferred;
// Otherwise, fall back to `Backbone.sync()`.
} else {
return Backbone.Model.prototype.sync.apply( this, arguments );
}
}
});
revisions.model.FrameState = Backbone.Model.extend({
defaults: {
loading: false,
error: false,
compareTwoMode: false
},
initialize: function( attributes, options ) {
var properties = {};
_.bindAll( this, 'receiveDiff' );
this._debouncedEnsureDiff = _.debounce( this._ensureDiff, 200 );
this.revisions = options.revisions;
this.diffs = new revisions.model.Diffs( [], { revisions: this.revisions });
// Set the initial diffs collection provided through the settings
this.diffs.set( revisions.settings.diffData );
// Set up internal listeners
this.listenTo( this, 'change:from', this.changeRevisionHandler );
this.listenTo( this, 'change:to', this.changeRevisionHandler );
this.listenTo( this, 'change:compareTwoMode', this.changeMode );
this.listenTo( this, 'update:revisions', this.updatedRevisions );
this.listenTo( this.diffs, 'ensure:load', this.updateLoadingStatus );
this.listenTo( this, 'update:diff', this.updateLoadingStatus );
// Set the initial revisions, baseUrl, and mode as provided through settings
properties.to = this.revisions.get( revisions.settings.to );
properties.from = this.revisions.get( revisions.settings.from );
properties.compareTwoMode = revisions.settings.compareTwoMode;
properties.baseUrl = revisions.settings.baseUrl;
this.set( properties );
// Start the router if browser supports History API
if ( window.history && window.history.pushState ) {
this.router = new revisions.Router({ model: this });
Backbone.history.start({ pushState: true });
}
},
updateLoadingStatus: function() {
this.set( 'error', false );
this.set( 'loading', ! this.diff() );
},
changeMode: function( model, value ) {
// If we were on the first revision before switching, we have to bump them over one
if ( value && 0 === this.revisions.indexOf( this.get('to') ) ) {
this.set({
from: this.revisions.at(0),
to: this.revisions.at(1)
});
}
},
updatedRevisions: function( from, to ) {
if ( this.get( 'compareTwoMode' ) ) {
// TODO: compare-two loading strategy
} else {
this.diffs.loadAll( this.revisions.pluck('id'), to.id, 40 );
}
},
// Fetch the currently loaded diff.
diff: function() {
return this.diffs.get( this._diffId );
},
// So long as `from` and `to` are changed at the same time, the diff
// will only be updated once. This is because Backbone updates all of
// the changed attributes in `set`, and then fires the `change` events.
updateDiff: function( options ) {
var from, to, diffId, diff;
options = options || {};
from = this.get('from');
to = this.get('to');
diffId = ( from ? from.id : 0 ) + ':' + to.id;
// Check if we're actually changing the diff id.
if ( this._diffId === diffId )
return $.Deferred().reject().promise();
this._diffId = diffId;
this.trigger( 'update:revisions', from, to );
diff = this.diffs.get( diffId );
// If we already have the diff, then immediately trigger the update.
if ( diff ) {
this.receiveDiff( diff );
return $.Deferred().resolve().promise();
// Otherwise, fetch the diff.
} else {
if ( options.immediate ) {
return this._ensureDiff();
} else {
this._debouncedEnsureDiff();
return $.Deferred().reject().promise();
}
}
},
// A simple wrapper around `updateDiff` to prevent the change event's
// parameters from being passed through.
changeRevisionHandler: function( model, value, options ) {
this.updateDiff();
},
receiveDiff: function( diff ) {
// Did we actually get a diff?
if ( _.isUndefined( diff ) || _.isUndefined( diff.id ) ) {
this.set({
loading: false,
error: true
});
} else if ( this._diffId === diff.id ) { // Make sure the current diff didn't change
this.trigger( 'update:diff', diff );
}
},
_ensureDiff: function() {
return this.diffs.ensure( this._diffId, this ).always( this.receiveDiff );
}
});
/**
* ========================================================================
* VIEWS
* ========================================================================
*/
// The frame view. This contains the entire page.
revisions.view.Frame = wp.Backbone.View.extend({
className: 'revisions',
template: wp.template('revisions-frame'),
initialize: function() {
this.listenTo( this.model, 'update:diff', this.renderDiff );
this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode );
this.listenTo( this.model, 'change:loading', this.updateLoadingStatus );
this.listenTo( this.model, 'change:error', this.updateErrorStatus );
this.views.set( '.revisions-control-frame', new revisions.view.Controls({
model: this.model
}) );
},
render: function() {
wp.Backbone.View.prototype.render.apply( this, arguments );
$('html').css( 'overflow-y', 'scroll' );
$('#wpbody-content .wrap').append( this.el );
this.updateCompareTwoMode();
this.renderDiff( this.model.diff() );
this.views.ready();
return this;
},
renderDiff: function( diff ) {
this.views.set( '.revisions-diff-frame', new revisions.view.Diff({
model: diff
}) );
},
updateLoadingStatus: function() {
this.$el.toggleClass( 'loading', this.model.get('loading') );
},
updateErrorStatus: function() {
this.$el.toggleClass( 'diff-error', this.model.get('error') );
},
updateCompareTwoMode: function() {
this.$el.toggleClass( 'comparing-two-revisions', this.model.get('compareTwoMode') );
}
});
// The control view.
// This contains the revision slider, previous/next buttons, the meta info and the compare checkbox.
revisions.view.Controls = wp.Backbone.View.extend({
className: 'revisions-controls',
initialize: function() {
_.bindAll( this, 'setWidth' );
// Add the button view
this.views.add( new revisions.view.Buttons({
model: this.model
}) );
// Add the checkbox view
this.views.add( new revisions.view.Checkbox({
model: this.model
}) );
// Prep the slider model
var slider = new revisions.model.Slider({
frame: this.model,
revisions: this.model.revisions
});
// Prep the tooltip model
var tooltip = new revisions.model.Tooltip({
frame: this.model,
revisions: this.model.revisions,
slider: slider
});
// Add the tooltip view
this.views.add( new revisions.view.Tooltip({
model: tooltip
}) );
// Add the tickmarks view
this.views.add( new revisions.view.Tickmarks({
model: tooltip
}) );
// Add the slider view
this.views.add( new revisions.view.Slider({
model: slider
}) );
// Add the Metabox view
this.views.add( new revisions.view.Metabox({
model: this.model
}) );
},
ready: function() {
this.top = this.$el.offset().top;
this.window = $(window);
this.window.on( 'scroll.wp.revisions', {controls: this}, function(e) {
var controls = e.data.controls;
var container = controls.$el.parent();
var scrolled = controls.window.scrollTop();
var frame = controls.views.parent;
if ( scrolled >= controls.top ) {
if ( ! frame.$el.hasClass('pinned') ) {
controls.setWidth();
container.css('height', container.height() + 'px' );
controls.window.on('resize.wp.revisions.pinning click.wp.revisions.pinning', {controls: controls}, function(e) {
e.data.controls.setWidth();
});
}
frame.$el.addClass('pinned');
} else if ( frame.$el.hasClass('pinned') ) {
controls.window.off('.wp.revisions.pinning');
controls.$el.css('width', 'auto');
frame.$el.removeClass('pinned');
container.css('height', 'auto');
controls.top = controls.$el.offset().top;
} else {
controls.top = controls.$el.offset().top;
}
});
},
setWidth: function() {
this.$el.css('width', this.$el.parent().width() + 'px');
}
});
// The tickmarks view
revisions.view.Tickmarks = wp.Backbone.View.extend({
className: 'revisions-tickmarks',
direction: isRtl ? 'right' : 'left',
initialize: function() {
this.listenTo( this.model, 'change:revision', this.reportTickPosition );
},
reportTickPosition: function( model, revision ) {
var offset, thisOffset, parentOffset, tick, index = this.model.revisions.indexOf( revision );
thisOffset = this.$el.allOffsets();
parentOffset = this.$el.parent().allOffsets();
if ( index === this.model.revisions.length - 1 ) {
// Last one
offset = {
rightPlusWidth: thisOffset.left - parentOffset.left + 1,
leftPlusWidth: thisOffset.right - parentOffset.right + 1
};
} else {
// Normal tick
tick = this.$('div:nth-of-type(' + (index + 1) + ')');
offset = tick.allPositions();
_.extend( offset, {
left: offset.left + thisOffset.left - parentOffset.left,
right: offset.right + thisOffset.right - parentOffset.right
});
_.extend( offset, {
leftPlusWidth: offset.left + tick.outerWidth(),
rightPlusWidth: offset.right + tick.outerWidth()
});
}
this.model.set({ offset: offset });
},
ready: function() {
var tickCount, tickWidth;
tickCount = this.model.revisions.length - 1;
tickWidth = 1 / tickCount;
this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px');
_(tickCount).times( function( index ){
this.$el.append( '<div style="' + this.direction + ': ' + ( 100 * tickWidth * index ) + '%"></div>' );
}, this );
}
});
// The metabox view
revisions.view.Metabox = wp.Backbone.View.extend({
className: 'revisions-meta',
initialize: function() {
// Add the 'from' view
this.views.add( new revisions.view.MetaFrom({
model: this.model,
className: 'diff-meta diff-meta-from'
}) );
// Add the 'to' view
this.views.add( new revisions.view.MetaTo({
model: this.model
}) );
}
});
// The revision meta view (to be extended)
revisions.view.Meta = wp.Backbone.View.extend({
template: wp.template('revisions-meta'),
events: {
'click .restore-revision': 'restoreRevision'
},
initialize: function() {
this.listenTo( this.model, 'update:revisions', this.render );
},
prepare: function() {
return _.extend( this.model.toJSON()[this.type] || {}, {
type: this.type
});
},
restoreRevision: function() {
document.location = this.model.get('to').attributes.restoreUrl;
}
});
// The revision meta 'from' view
revisions.view.MetaFrom = revisions.view.Meta.extend({
className: 'diff-meta diff-meta-from',
type: 'from'
});
// The revision meta 'to' view
revisions.view.MetaTo = revisions.view.Meta.extend({
className: 'diff-meta diff-meta-to',
type: 'to'
});
// The checkbox view.
revisions.view.Checkbox = wp.Backbone.View.extend({
className: 'revisions-checkbox',
template: wp.template('revisions-checkbox'),
events: {
'click .compare-two-revisions': 'compareTwoToggle'
},
initialize: function() {
this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode );
},
ready: function() {
if ( this.model.revisions.length < 3 )
$('.revision-toggle-compare-mode').hide();
},
updateCompareTwoMode: function() {
this.$('.compare-two-revisions').prop( 'checked', this.model.get('compareTwoMode') );
},
// Toggle the compare two mode feature when the compare two checkbox is checked.
compareTwoToggle: function( event ) {
// Activate compare two mode?
this.model.set({ compareTwoMode: $('.compare-two-revisions').prop('checked') });
}
});
// The tooltip view.
// Encapsulates the tooltip.
revisions.view.Tooltip = wp.Backbone.View.extend({
className: 'revisions-tooltip',
template: wp.template('revisions-meta'),
initialize: function( options ) {
this.listenTo( this.model, 'change:offset', this.render );
this.listenTo( this.model, 'change:hovering', this.toggleVisibility );
this.listenTo( this.model, 'change:scrubbing', this.toggleVisibility );
},
prepare: function() {
if ( _.isNull( this.model.get('revision') ) )
return;
else
return _.extend( { type: 'tooltip' }, {
attributes: this.model.get('revision').toJSON()
});
},
render: function() {
var direction, directionVal, flipped, css = {}, position = this.model.revisions.indexOf( this.model.get('revision') ) + 1;
flipped = ( position / this.model.revisions.length ) > 0.5;
if ( isRtl ) {
direction = flipped ? 'left' : 'right';
directionVal = flipped ? 'leftPlusWidth' : direction;
} else {
direction = flipped ? 'right' : 'left';
directionVal = flipped ? 'rightPlusWidth' : direction;
}
otherDirection = 'right' === direction ? 'left': 'right';
wp.Backbone.View.prototype.render.apply( this, arguments );
css[direction] = this.model.get('offset')[directionVal] + 'px';
css[otherDirection] = '';
this.$el.toggleClass( 'flipped', flipped ).css( css );
},
visible: function() {
return this.model.get( 'scrubbing' ) || this.model.get( 'hovering' );
},
toggleVisibility: function( options ) {
if ( this.visible() )
this.$el.stop().show().fadeTo( 100 - this.el.style.opacity * 100, 1 );
else
this.$el.stop().fadeTo( this.el.style.opacity * 300, 0, function(){ $(this).hide(); } );
return;
}
});
// The buttons view.
// Encapsulates all of the configuration for the previous/next buttons.
revisions.view.Buttons = wp.Backbone.View.extend({
className: 'revisions-buttons',
template: wp.template('revisions-buttons'),
events: {
'click .revisions-next .button': 'nextRevision',
'click .revisions-previous .button': 'previousRevision'
},
initialize: function() {
this.listenTo( this.model, 'update:revisions', this.disabledButtonCheck );
},
ready: function() {
this.disabledButtonCheck();
},
// Go to a specific model index
gotoModel: function( toIndex ) {
var attributes = {
to: this.model.revisions.at( toIndex )
};
// If we're at the first revision, unset 'from'.
if ( toIndex )
attributes.from = this.model.revisions.at( toIndex - 1 );
else
this.model.unset('from', { silent: true });
this.model.set( attributes );
},
// Go to the 'next' revision
nextRevision: function() {
var toIndex = this.model.revisions.indexOf( this.model.get('to') ) + 1;
this.gotoModel( toIndex );
},
// Go to the 'previous' revision
previousRevision: function() {
var toIndex = this.model.revisions.indexOf( this.model.get('to') ) - 1;
this.gotoModel( toIndex );
},
// Check to see if the Previous or Next buttons need to be disabled or enabled.
disabledButtonCheck: function() {
var maxVal = this.model.revisions.length - 1,
minVal = 0,
next = $('.revisions-next .button'),
previous = $('.revisions-previous .button'),
val = this.model.revisions.indexOf( this.model.get('to') );
// Disable "Next" button if you're on the last node.
next.prop( 'disabled', ( maxVal === val ) );
// Disable "Previous" button if you're on the first node.
previous.prop( 'disabled', ( minVal === val ) );
}
});
// The slider view.
revisions.view.Slider = wp.Backbone.View.extend({
className: 'wp-slider',
direction: isRtl ? 'right' : 'left',
events: {
'mousemove' : 'mouseMove'
},
initialize: function() {
_.bindAll( this, 'start', 'slide', 'stop', 'mouseMove', 'mouseEnter', 'mouseLeave' );
this.listenTo( this.model, 'update:slider', this.applySliderSettings );
},
ready: function() {
this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px');
this.$el.slider( _.extend( this.model.toJSON(), {
start: this.start,
slide: this.slide,
stop: this.stop
}) );
this.$el.hoverIntent({
over: this.mouseEnter,
out: this.mouseLeave,
timeout: 800
});
this.applySliderSettings();
},
mouseMove: function( e ) {
var zoneCount = this.model.revisions.length - 1, // One fewer zone than models
sliderFrom = this.$el.allOffsets()[this.direction], // "From" edge of slider
sliderWidth = this.$el.width(), // Width of slider
tickWidth = sliderWidth / zoneCount, // Calculated width of zone
actualX = isRtl? $(window).width() - e.pageX : e.pageX; // Flipped for RTL - sliderFrom;
actualX = actualX - sliderFrom; // Offset of mouse position in slider
var currentModelIndex = Math.floor( ( actualX + ( tickWidth / 2 ) ) / tickWidth ); // Calculate the model index
// Ensure sane value for currentModelIndex.
if ( currentModelIndex < 0 )
currentModelIndex = 0;
else if ( currentModelIndex >= this.model.revisions.length )
currentModelIndex = this.model.revisions.length - 1;
// Update the tooltip mode
this.model.set({ hoveredRevision: this.model.revisions.at( currentModelIndex ) });
},
mouseLeave: function() {
this.model.set({ hovering: false });
},
mouseEnter: function() {
this.model.set({ hovering: true });
},
applySliderSettings: function() {
this.$el.slider( _.pick( this.model.toJSON(), 'value', 'values', 'range' ) );
var handles = this.$('a.ui-slider-handle');
if ( this.model.get('compareTwoMode') ) {
// in RTL mode the 'left handle' is the second in the slider, 'right' is first
handles.first()
.toggleClass( 'to-handle', !! isRtl )
.toggleClass( 'from-handle', ! isRtl );
handles.last()
.toggleClass( 'from-handle', !! isRtl )
.toggleClass( 'to-handle', ! isRtl );
} else {
handles.removeClass('from-handle to-handle');
}
},
start: function( event, ui ) {
this.model.set({ scrubbing: true });
// Track the mouse position to enable smooth dragging,
// overrides default jQuery UI step behavior.
$( window ).on( 'mousemove.wp.revisions', { view: this }, function( e ) {
var view = e.data.view,
leftDragBoundary = view.$el.offset().left,
sliderOffset = leftDragBoundary,
sliderRightEdge = leftDragBoundary + view.$el.width(),
rightDragBoundary = sliderRightEdge,
leftDragReset = '0',
rightDragReset = '100%',
handle = $( ui.handle );
// In two handle mode, ensure handles can't be dragged past each other.
// Adjust left/right boundaries and reset points.
if ( view.model.get('compareTwoMode') ) {
var handles = handle.parent().find('.ui-slider-handle');
if ( handle.is( handles.first() ) ) { // We're the left handle
rightDragBoundary = handles.last().offset().left;
rightDragReset = rightDragBoundary - sliderOffset;
} else { // We're the right handle
leftDragBoundary = handles.first().offset().left + handles.first().width();
leftDragReset = leftDragBoundary - sliderOffset;
}
}
// Follow mouse movements, as long as handle remains inside slider.
if ( e.pageX < leftDragBoundary ) {
handle.css( 'left', leftDragReset ); // Mouse to left of slider.
} else if ( e.pageX > rightDragBoundary ) {
handle.css( 'left', rightDragReset ); // Mouse to right of slider.
} else {
handle.css( 'left', e.pageX - sliderOffset ); // Mouse in slider.
}
} );
},
getPosition: function( position ) {
return isRtl ? this.model.revisions.length - position - 1: position;
},
// Responds to slide events
slide: function( event, ui ) {
var attributes, movedRevision;
// Compare two revisions mode
if ( this.model.get('compareTwoMode') ) {
// Prevent sliders from occupying same spot
if ( ui.values[1] === ui.values[0] )
return false;
if ( isRtl )
ui.values.reverse();
attributes = {
from: this.model.revisions.at( this.getPosition( ui.values[0] ) ),
to: this.model.revisions.at( this.getPosition( ui.values[1] ) )
};
} else {
attributes = {
to: this.model.revisions.at( this.getPosition( ui.value ) )
};
// If we're at the first revision, unset 'from'.
if ( this.getPosition( ui.value ) > 0 )
attributes.from = this.model.revisions.at( this.getPosition( ui.value ) - 1 );
else
attributes.from = undefined;
}
movedRevision = this.model.revisions.at( this.getPosition( ui.value ) );
// If we are scrubbing, a scrub to a revision is considered a hover
if ( this.model.get('scrubbing') )
attributes.hoveredRevision = movedRevision;
this.model.set( attributes );
},
stop: function( event, ui ) {
$( window ).off('mousemove.wp.revisions');
this.model.updateSliderSettings(); // To snap us back to a tick mark
this.model.set({ scrubbing: false });
}
});
// The diff view.
// This is the view for the current active diff.
revisions.view.Diff = wp.Backbone.View.extend({
className: 'revisions-diff',
template: wp.template('revisions-diff'),
// Generate the options to be passed to the template.
prepare: function() {
return _.extend({ fields: this.model.fields.toJSON() }, this.options );
}
});
// The revisions router
// takes URLs with #hash fragments and routes them
revisions.Router = Backbone.Router.extend({
initialize: function( options ) {
this.model = options.model;
this.routes = _.object([
[ this.baseUrl( '?from=:from&to=:to' ), 'handleRoute' ],
[ this.baseUrl( '?from=:from&to=:to' ), 'handleRoute' ]
]);
// Maintain state and history when navigating
this.listenTo( this.model, 'update:diff', _.debounce( this.updateUrl, 250 ) );
this.listenTo( this.model, 'change:compareTwoMode', this.updateUrl );
},
baseUrl: function( url ) {
return this.model.get('baseUrl') + url;
},
updateUrl: function() {
var from = this.model.has('from') ? this.model.get('from').id : 0;
var to = this.model.get('to').id;
if ( this.model.get('compareTwoMode' ) )
this.navigate( this.baseUrl( '?from=' + from + '&to=' + to ) );
else
this.navigate( this.baseUrl( '?revision=' + to ) );
},
handleRoute: function( a, b ) {
var from, to, compareTwo = _.isUndefined( b );
if ( ! compareTwo ) {
b = this.model.revisions.get( a );
a = this.model.revisions.prev( b );
b = b ? b.id : 0;
a = a ? a.id : 0;
}
this.model.set({
from: this.model.revisions.get( parseInt( a, 10 ) ),
to: this.model.revisions.get( parseInt( a, 10 ) ),
compareTwoMode: compareTwo
});
}
});
// Initialize the revisions UI.
revisions.init = function() {
revisions.view.frame = new revisions.view.Frame({
model: new revisions.model.FrameState({}, {
revisions: new revisions.model.Revisions( revisions.settings.revisionData )
})
}).render();
};
$( revisions.init );
}(jQuery));
| JavaScript |
var imageEdit;
(function($) {
imageEdit = {
iasapi : {},
hold : {},
postid : '',
intval : function(f) {
return f | 0;
},
setDisabled : function(el, s) {
if ( s ) {
el.removeClass('disabled');
$('input', el).removeAttr('disabled');
} else {
el.addClass('disabled');
$('input', el).prop('disabled', true);
}
},
init : function(postid, nonce) {
var t = this, old = $('#image-editor-' + t.postid),
x = t.intval( $('#imgedit-x-' + postid).val() ),
y = t.intval( $('#imgedit-y-' + postid).val() );
if ( t.postid != postid && old.length )
t.close(t.postid);
t.hold['w'] = t.hold['ow'] = x;
t.hold['h'] = t.hold['oh'] = y;
t.hold['xy_ratio'] = x / y;
t.hold['sizer'] = parseFloat( $('#imgedit-sizer-' + postid).val() );
t.postid = postid;
$('#imgedit-response-' + postid).empty();
$('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
var k = e.keyCode;
if ( 36 < k && k < 41 )
$(this).blur()
if ( 13 == k ) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
},
toggleEditor : function(postid, toggle) {
var wait = $('#imgedit-wait-' + postid);
if ( toggle )
wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast');
else
wait.fadeOut('fast');
},
toggleHelp : function(el) {
$(el).siblings('.imgedit-help').slideToggle('fast');
return false;
},
getTarget : function(postid) {
return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
},
scaleChanged : function(postid, x) {
var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
if ( x ) {
h1 = (w.val() != '') ? Math.round( w.val() / this.hold['xy_ratio'] ) : '';
h.val( h1 );
} else {
w1 = (h.val() != '') ? Math.round( h.val() * this.hold['xy_ratio'] ) : '';
w.val( w1 );
}
if ( ( h1 && h1 > this.hold['oh'] ) || ( w1 && w1 > this.hold['ow'] ) )
warn.css('visibility', 'visible');
else
warn.css('visibility', 'hidden');
},
getSelRatio : function(postid) {
var x = this.hold['w'], y = this.hold['h'],
X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
if ( X && Y )
return X + ':' + Y;
if ( x && y )
return x + ':' + y;
return '1:1';
},
filterHistory : function(postid, setSize) {
// apply undo state to history
var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
if ( history != '' ) {
history = JSON.parse(history);
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop > 0 ) {
while ( pop > 0 ) {
history.pop();
pop--;
}
}
if ( setSize ) {
if ( !history.length ) {
this.hold['w'] = this.hold['ow'];
this.hold['h'] = this.hold['oh'];
return '';
}
// restore
o = history[history.length - 1];
o = o.c || o.r || o.f || false;
if ( o ) {
this.hold['w'] = o.fw;
this.hold['h'] = o.fh;
}
}
// filter the values
for ( n in history ) {
i = history[n];
if ( i.hasOwnProperty('c') ) {
op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
} else if ( i.hasOwnProperty('r') ) {
op[n] = { 'r': i.r.r };
} else if ( i.hasOwnProperty('f') ) {
op[n] = { 'f': i.f.f };
}
}
return JSON.stringify(op);
}
return '';
},
refreshEditor : function(postid, nonce, callback) {
var t = this, data, img;
t.toggleEditor(postid, 1);
data = {
'action': 'imgedit-preview',
'_ajax_nonce': nonce,
'postid': postid,
'history': t.filterHistory(postid, 1),
'rand': t.intval(Math.random() * 1000000)
};
img = $('<img id="image-preview-' + postid + '" />');
img.load( function() {
var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit;
parent.empty().append(img);
// w, h are the new full size dims
max1 = Math.max( t.hold.w, t.hold.h );
max2 = Math.max( $(img).width(), $(img).height() );
t.hold['sizer'] = max1 > max2 ? max2 / max1 : 1;
t.initCrop(postid, img, parent);
t.setCropSelection(postid, 0);
if ( (typeof callback != "unknown") && callback != null )
callback();
if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() == 0 )
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
else
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
t.toggleEditor(postid, 0);
}).error(function(){
$('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>');
t.toggleEditor(postid, 0);
}).attr('src', ajaxurl + '?' + $.param(data));
},
action : function(postid, nonce, action) {
var t = this, data, w, h, fw, fh;
if ( t.notsaved(postid) )
return false;
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid
};
if ( 'scale' == action ) {
w = $('#imgedit-scale-width-' + postid),
h = $('#imgedit-scale-height-' + postid),
fw = t.intval(w.val()),
fh = t.intval(h.val());
if ( fw < 1 ) {
w.focus();
return false;
} else if ( fh < 1 ) {
h.focus();
return false;
}
if ( fw == t.hold.ow || fh == t.hold.oh )
return false;
data['do'] = 'scale';
data['fwidth'] = fw;
data['fheight'] = fh;
} else if ( 'restore' == action ) {
data['do'] = 'restore';
} else {
return false;
}
t.toggleEditor(postid, 1);
$.post(ajaxurl, data, function(r) {
$('#image-editor-' + postid).empty().append(r);
t.toggleEditor(postid, 0);
});
},
save : function(postid, nonce) {
var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0);
if ( '' == history )
return false;
this.toggleEditor(postid, 1);
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'history': history,
'target': target,
'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null,
'do': 'save'
};
$.post(ajaxurl, data, function(r) {
var ret = JSON.parse(r);
if ( ret.error ) {
$('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>');
imageEdit.close(postid);
return;
}
if ( ret.fw && ret.fh )
$('#media-dims-' + postid).html( ret.fw + ' × ' + ret.fh );
if ( ret.thumbnail )
$('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
if ( ret.msg )
$('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
imageEdit.close(postid);
});
},
open : function(postid, nonce) {
var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner');
btn.prop('disabled', true);
spin.show();
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'do': 'open'
};
elem.load(ajaxurl, data, function() {
elem.fadeIn('fast');
head.fadeOut('fast', function(){
btn.removeAttr('disabled');
spin.hide();
});
});
},
imgLoaded : function(postid) {
var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
this.initCrop(postid, img, parent);
this.setCropSelection(postid, 0);
this.toggleEditor(postid, 0);
},
initCrop : function(postid, image, parent) {
var t = this, selW = $('#imgedit-sel-width-' + postid),
selH = $('#imgedit-sel-height-' + postid);
t.iasapi = $(image).imgAreaSelect({
parent: parent,
instance: true,
handles: true,
keys: true,
minWidth: 3,
minHeight: 3,
onInit: function(img, c) {
parent.children().mousedown(function(e){
var ratio = false, sel, defRatio;
if ( e.shiftKey ) {
sel = t.iasapi.getSelection();
defRatio = t.getSelRatio(postid);
ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
}
t.iasapi.setOptions({
aspectRatio: ratio
});
});
},
onSelectStart: function(img, c) {
imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
},
onSelectEnd: function(img, c) {
imageEdit.setCropSelection(postid, c);
},
onSelectChange: function(img, c) {
var sizer = imageEdit.hold.sizer;
selW.val( imageEdit.round(c.width / sizer) );
selH.val( imageEdit.round(c.height / sizer) );
}
});
},
setCropSelection : function(postid, c) {
var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128',
sizer = this.hold['sizer'];
min = min.split(':');
c = c || 0;
if ( !c || ( c.width < 3 && c.height < 3 ) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
this.setDisabled($('#imgedit-crop-sel-' + postid), 0);
$('#imgedit-sel-width-' + postid).val('');
$('#imgedit-sel-height-' + postid).val('');
$('#imgedit-selection-' + postid).val('');
return false;
}
if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
$('#imgedit-selection-' + postid).val('');
return false;
}
sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
$('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
},
close : function(postid, warn) {
warn = warn || false;
if ( warn && this.notsaved(postid) )
return false;
this.iasapi = {};
this.hold = {};
$('#image-editor-' + postid).fadeOut('fast', function() {
$('#media-head-' + postid).fadeIn('fast');
$(this).empty();
});
},
notsaved : function(postid) {
var h = $('#imgedit-history-' + postid).val(),
history = (h != '') ? JSON.parse(h) : new Array(),
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop < history.length ) {
if ( confirm( $('#imgedit-leaving-' + postid).html() ) )
return false;
return true;
}
return false;
},
addStep : function(op, postid, nonce) {
var t = this, elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array(),
undone = $('#imgedit-undone-' + postid),
pop = t.intval(undone.val());
while ( pop > 0 ) {
history.pop();
pop--;
}
undone.val(0); // reset
history.push(op);
elem.val( JSON.stringify(history) );
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled($('#image-redo-' + postid), false);
});
},
rotate : function(angle, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'r': { 'r': angle, 'fw': this.hold['h'], 'fh': this.hold['w'] }}, postid, nonce);
},
flip : function (axis, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'f': { 'f': axis, 'fw': this.hold['w'], 'fh': this.hold['h'] }}, postid, nonce);
},
crop : function (postid, nonce, t) {
var sel = $('#imgedit-selection-' + postid).val(),
w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
h = this.intval( $('#imgedit-sel-height-' + postid).val() );
if ( $(t).hasClass('disabled') || sel == '' )
return false;
sel = JSON.parse(sel);
if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
sel['fw'] = w;
sel['fh'] = h;
this.addStep({ 'c': sel }, postid, nonce);
}
},
undo : function (postid, nonce) {
var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) + 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
var elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array();
t.setDisabled($('#image-redo-' + postid), true);
t.setDisabled(button, pop < history.length);
});
},
redo : function(postid, nonce) {
var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) - 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled(button, pop > 0);
});
},
setNumSelection : function(postid) {
var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
x = this.intval( elX.val() ), y = this.intval( elY.val() ),
img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
sizer = this.hold['sizer'], x1, y1, x2, y2, ias = this.iasapi;
if ( x < 1 ) {
elX.val('');
return false;
}
if ( y < 1 ) {
elY.val('');
return false;
}
if ( x && y && ( sel = ias.getSelection() ) ) {
x2 = sel.x1 + Math.round( x * sizer );
y2 = sel.y1 + Math.round( y * sizer );
x1 = sel.x1;
y1 = sel.y1;
if ( x2 > imgw ) {
x1 = 0;
x2 = imgw;
elX.val( Math.round( x2 / sizer ) );
}
if ( y2 > imgh ) {
y1 = 0;
y2 = imgh;
elY.val( Math.round( y2 / sizer ) );
}
ias.setSelection( x1, y1, x2, y2 );
ias.update();
this.setCropSelection(postid, ias.getSelection());
}
},
round : function(num) {
var s;
num = Math.round(num);
if ( this.hold.sizer > 0.6 )
return num;
s = num.toString().slice(-1);
if ( '1' == s )
return num - 1;
else if ( '9' == s )
return num + 1;
return num;
},
setRatioSelection : function(postid, n, el) {
var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
h = $('#image-preview-' + postid).height();
if ( !this.intval( $(el).val() ) ) {
$(el).val('');
return;
}
if ( x && y ) {
this.iasapi.setOptions({
aspectRatio: x + ':' + y
});
if ( sel = this.iasapi.getSelection(true) ) {
r = Math.ceil( sel.y1 + ((sel.x2 - sel.x1) / (x / y)) );
if ( r > h ) {
r = h;
if ( n )
$('#imgedit-crop-height-' + postid).val('');
else
$('#imgedit-crop-width-' + postid).val('');
}
this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
this.iasapi.update();
}
}
}
}
})(jQuery);
| JavaScript |
(function($) {
var id = 'undefined' !== typeof current_site_id ? '&site_id=' + current_site_id : '';
$(document).ready( function() {
$( '.wp-suggest-user' ).autocomplete({
source: ajaxurl + '?action=autocomplete-user&autocomplete_type=add' + id,
delay: 500,
minLength: 2,
position: ( 'undefined' !== typeof isRtl && isRtl ) ? { my: 'right top', at: 'right bottom', offset: '0, -1' } : { offset: '0, -1' },
open: function() { $(this).addClass('open'); },
close: function() { $(this).removeClass('open'); }
});
});
})(jQuery); | JavaScript |
var wpWidgets;
(function($) {
wpWidgets = {
init : function() {
var rem, sidebars = $('div.widgets-sortables'), isRTL = !! ( 'undefined' != typeof isRtl && isRtl ),
margin = ( isRtl ? 'marginRight' : 'marginLeft' ), the_id;
$('#widgets-right').children('.widgets-holder-wrap').children('.sidebar-name').click(function(){
var c = $(this).siblings('.widgets-sortables'), p = $(this).parent();
if ( !p.hasClass('closed') ) {
c.sortable('disable');
p.addClass('closed');
} else {
p.removeClass('closed');
c.sortable('enable').sortable('refresh');
}
});
$('#widgets-left').children('.widgets-holder-wrap').children('.sidebar-name').click(function() {
$(this).parent().toggleClass('closed');
});
sidebars.each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
$(document.body).bind('click.widgets-toggle', function(e){
var target = $(e.target), css = {}, widget, inside, w;
if ( target.parents('.widget-top').length && ! target.parents('#available-widgets').length ) {
widget = target.closest('div.widget');
inside = widget.children('.widget-inside');
w = parseInt( widget.find('input.widget-width').val(), 10 );
if ( inside.is(':hidden') ) {
if ( w > 250 && inside.closest('div.widgets-sortables').length ) {
css['width'] = w + 30 + 'px';
if ( inside.closest('div.widget-liquid-right').length )
css[margin] = 235 - w + 'px';
widget.css(css);
}
wpWidgets.fixLabels(widget);
inside.slideDown('fast');
} else {
inside.slideUp('fast', function() {
widget.css({'width':'', margin:''});
});
}
e.preventDefault();
} else if ( target.hasClass('widget-control-save') ) {
wpWidgets.save( target.closest('div.widget'), 0, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-remove') ) {
wpWidgets.save( target.closest('div.widget'), 1, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-close') ) {
wpWidgets.close( target.closest('div.widget') );
e.preventDefault();
}
});
sidebars.children('.widget').each(function() {
wpWidgets.appendTitle(this);
if ( $('p.widget-error', this).length )
$('a.widget-action', this).click();
});
$('#widget-list').children('.widget').draggable({
connectToSortable: 'div.widgets-sortables',
handle: '> .widget-top > .widget-title',
distance: 2,
helper: 'clone',
zIndex: 100,
containment: 'document',
start: function(e,ui) {
ui.helper.find('div.widget-description').hide();
the_id = this.id;
},
stop: function(e,ui) {
if ( rem )
$(rem).hide();
rem = '';
}
});
sidebars.sortable({
placeholder: 'widget-placeholder',
items: '> .widget',
handle: '> .widget-top > .widget-title',
cursor: 'move',
distance: 2,
containment: 'document',
start: function(e,ui) {
ui.item.children('.widget-inside').hide();
ui.item.css({margin:'', 'width':''});
},
stop: function(e,ui) {
if ( ui.item.hasClass('ui-draggable') && ui.item.data('draggable') )
ui.item.draggable('destroy');
if ( ui.item.hasClass('deleting') ) {
wpWidgets.save( ui.item, 1, 0, 1 ); // delete widget
ui.item.remove();
return;
}
var add = ui.item.find('input.add_new').val(),
n = ui.item.find('input.multi_number').val(),
id = the_id,
sb = $(this).attr('id');
ui.item.css({margin:'', 'width':''});
the_id = '';
if ( add ) {
if ( 'multi' == add ) {
ui.item.html( ui.item.html().replace(/<[^<>]+>/g, function(m){ return m.replace(/__i__|%i%/g, n); }) );
ui.item.attr( 'id', id.replace('__i__', n) );
n++;
$('div#' + id).find('input.multi_number').val(n);
} else if ( 'single' == add ) {
ui.item.attr( 'id', 'new-' + id );
rem = 'div#' + id;
}
wpWidgets.save( ui.item, 0, 0, 1 );
ui.item.find('input.add_new').val('');
ui.item.find('a.widget-action').click();
return;
}
wpWidgets.saveOrder(sb);
},
receive: function(e, ui) {
var sender = $(ui.sender);
if ( !$(this).is(':visible') || this.id.indexOf('orphaned_widgets') != -1 )
sender.sortable('cancel');
if ( sender.attr('id').indexOf('orphaned_widgets') != -1 && !sender.children('.widget').length ) {
sender.parents('.orphan-sidebar').slideUp(400, function(){ $(this).remove(); });
}
}
}).sortable('option', 'connectWith', 'div.widgets-sortables').parent().filter('.closed').children('.widgets-sortables').sortable('disable');
$('#available-widgets').droppable({
tolerance: 'pointer',
accept: function(o){
return $(o).parent().attr('id') != 'widget-list';
},
drop: function(e,ui) {
ui.draggable.addClass('deleting');
$('#removing-widget').hide().children('span').html('');
},
over: function(e,ui) {
ui.draggable.addClass('deleting');
$('div.widget-placeholder').hide();
if ( ui.draggable.hasClass('ui-sortable-helper') )
$('#removing-widget').show().children('span')
.html( ui.draggable.find('div.widget-title').children('h4').html() );
},
out: function(e,ui) {
ui.draggable.removeClass('deleting');
$('div.widget-placeholder').show();
$('#removing-widget').hide().children('span').html('');
}
});
},
saveOrder : function(sb) {
if ( sb )
$('#' + sb).closest('div.widgets-holder-wrap').find('.spinner').css('display', 'inline-block');
var a = {
action: 'widgets-order',
savewidgets: $('#_wpnonce_widgets').val(),
sidebars: []
};
$('div.widgets-sortables').each( function() {
if ( $(this).sortable )
a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
});
$.post( ajaxurl, a, function() {
$('.spinner').hide();
});
this.resize();
},
save : function(widget, del, animate, order) {
var sb = widget.closest('div.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a;
widget = $(widget);
$('.spinner', widget).show();
a = {
action: 'save-widget',
savewidgets: $('#_wpnonce_widgets').val(),
sidebar: sb
};
if ( del )
a['delete_widget'] = 1;
data += '&' + $.param(a);
$.post( ajaxurl, data, function(r){
var id;
if ( del ) {
if ( !$('input.widget_number', widget).val() ) {
id = $('input.widget-id', widget).val();
$('#available-widgets').find('input.widget-id').each(function(){
if ( $(this).val() == id )
$(this).closest('div.widget').show();
});
}
if ( animate ) {
order = 0;
widget.slideUp('fast', function(){
$(this).remove();
wpWidgets.saveOrder();
});
} else {
widget.remove();
wpWidgets.resize();
}
} else {
$('.spinner').hide();
if ( r && r.length > 2 ) {
$('div.widget-content', widget).html(r);
wpWidgets.appendTitle(widget);
wpWidgets.fixLabels(widget);
}
}
if ( order )
wpWidgets.saveOrder();
});
},
appendTitle : function(widget) {
var title = $('input[id*="-title"]', widget).val() || '';
if ( title )
title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>');
$(widget).children('.widget-top').children('.widget-title').children()
.children('.in-widget-title').html(title);
},
resize : function() {
$('div.widgets-sortables').each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
},
fixLabels : function(widget) {
widget.children('.widget-inside').find('label').each(function(){
var f = $(this).attr('for');
if ( f && f == $('input', this).attr('id') )
$(this).removeAttr('for');
});
},
close : function(widget) {
widget.children('.widget-inside').slideUp('fast', function(){
widget.css({'width':'', margin:''});
});
}
};
$(document).ready(function($){ wpWidgets.init(); });
})(jQuery);
| JavaScript |
(function( exports, $ ){
var api = wp.customize;
/*
* @param options
* - previewer - The Previewer instance to sync with.
* - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'.
*/
api.Setting = api.Value.extend({
initialize: function( id, value, options ) {
var element;
api.Value.prototype.initialize.call( this, value, options );
this.id = id;
this.transport = this.transport || 'refresh';
this.bind( this.preview );
},
preview: function() {
switch ( this.transport ) {
case 'refresh':
return this.previewer.refresh();
case 'postMessage':
return this.previewer.send( 'setting', [ this.id, this() ] );
}
}
});
api.Control = api.Class.extend({
initialize: function( id, options ) {
var control = this,
nodes, radios, settings;
this.params = {};
$.extend( this, options || {} );
this.id = id;
this.selector = '#customize-control-' + id.replace( ']', '' ).replace( '[', '-' );
this.container = $( this.selector );
settings = $.map( this.params.settings, function( value ) {
return value;
});
api.apply( api, settings.concat( function() {
var key;
control.settings = {};
for ( key in control.params.settings ) {
control.settings[ key ] = api( control.params.settings[ key ] );
}
control.setting = control.settings['default'] || null;
control.ready();
}) );
control.elements = [];
nodes = this.container.find('[data-customize-setting-link]');
radios = {};
nodes.each( function() {
var node = $(this),
name;
if ( node.is(':radio') ) {
name = node.prop('name');
if ( radios[ name ] )
return;
radios[ name ] = true;
node = nodes.filter( '[name="' + name + '"]' );
}
api( node.data('customizeSettingLink'), function( setting ) {
var element = new api.Element( node );
control.elements.push( element );
element.sync( setting );
element.set( setting() );
});
});
},
ready: function() {},
dropdownInit: function() {
var control = this,
statuses = this.container.find('.dropdown-status'),
params = this.params,
update = function( to ) {
if ( typeof to === 'string' && params.statuses && params.statuses[ to ] )
statuses.html( params.statuses[ to ] ).show();
else
statuses.hide();
};
var toggleFreeze = false;
// Support the .dropdown class to open/close complex elements
this.container.on( 'click keydown', '.dropdown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
event.preventDefault();
if (!toggleFreeze)
control.container.toggleClass('open');
if ( control.container.hasClass('open') )
control.container.parent().parent().find('li.library-selected').focus();
// Don't want to fire focus and click at same time
toggleFreeze = true;
setTimeout(function () {
toggleFreeze = false;
}, 400);
});
this.setting.bind( update );
update( this.setting() );
}
});
api.ColorControl = api.Control.extend({
ready: function() {
var control = this,
picker = this.container.find('.color-picker-hex');
picker.val( control.setting() ).wpColorPicker({
change: function( event, options ) {
control.setting.set( picker.wpColorPicker('color') );
},
clear: function() {
control.setting.set( false );
}
});
}
});
api.UploadControl = api.Control.extend({
ready: function() {
var control = this;
this.params.removed = this.params.removed || '';
this.success = $.proxy( this.success, this );
this.uploader = $.extend({
container: this.container,
browser: this.container.find('.upload'),
dropzone: this.container.find('.upload-dropzone'),
success: this.success,
plupload: {},
params: {}
}, this.uploader || {} );
if ( control.params.extensions ) {
control.uploader.plupload.filters = [{
title: api.l10n.allowedFiles,
extensions: control.params.extensions
}];
}
if ( control.params.context )
control.uploader.params['post_data[context]'] = this.params.context;
if ( api.settings.theme.stylesheet )
control.uploader.params['post_data[theme]'] = api.settings.theme.stylesheet;
this.uploader = new wp.Uploader( this.uploader );
this.remover = this.container.find('.remove');
this.remover.on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
control.setting.set( control.params.removed );
event.preventDefault();
});
this.removerVisibility = $.proxy( this.removerVisibility, this );
this.setting.bind( this.removerVisibility );
this.removerVisibility( this.setting.get() );
},
success: function( attachment ) {
this.setting.set( attachment.get('url') );
},
removerVisibility: function( to ) {
this.remover.toggle( to != this.params.removed );
}
});
api.ImageControl = api.UploadControl.extend({
ready: function() {
var control = this,
panels;
this.uploader = {
init: function( up ) {
var fallback, button;
if ( this.supports.dragdrop )
return;
// Maintain references while wrapping the fallback button.
fallback = control.container.find( '.upload-fallback' );
button = fallback.children().detach();
this.browser.detach().empty().append( button );
fallback.append( this.browser ).show();
}
};
api.UploadControl.prototype.ready.call( this );
this.thumbnail = this.container.find('.preview-thumbnail img');
this.thumbnailSrc = $.proxy( this.thumbnailSrc, this );
this.setting.bind( this.thumbnailSrc );
this.library = this.container.find('.library');
// Generate tab objects
this.tabs = {};
panels = this.library.find('.library-content');
this.library.children('ul').children('li').each( function() {
var link = $(this),
id = link.data('customizeTab'),
panel = panels.filter('[data-customize-tab="' + id + '"]');
control.tabs[ id ] = {
both: link.add( panel ),
link: link,
panel: panel
};
});
// Bind tab switch events
this.library.children('ul').on( 'click keydown', 'li', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
var id = $(this).data('customizeTab'),
tab = control.tabs[ id ];
event.preventDefault();
if ( tab.link.hasClass('library-selected') )
return;
control.selected.both.removeClass('library-selected');
control.selected = tab;
control.selected.both.addClass('library-selected');
});
// Bind events to switch image urls.
this.library.on( 'click keydown', 'a', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
var value = $(this).data('customizeImageValue');
if ( value ) {
control.setting.set( value );
event.preventDefault();
}
});
if ( this.tabs.uploaded ) {
this.tabs.uploaded.target = this.library.find('.uploaded-target');
if ( ! this.tabs.uploaded.panel.find('.thumbnail').length )
this.tabs.uploaded.both.addClass('hidden');
}
// Select a tab
panels.each( function() {
var tab = control.tabs[ $(this).data('customizeTab') ];
// Select the first visible tab.
if ( ! tab.link.hasClass('hidden') ) {
control.selected = tab;
tab.both.addClass('library-selected');
return false;
}
});
this.dropdownInit();
},
success: function( attachment ) {
api.UploadControl.prototype.success.call( this, attachment );
// Add the uploaded image to the uploaded tab.
if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) {
this.tabs.uploaded.both.removeClass('hidden');
// @todo: Do NOT store this on the attachment model. That is bad.
attachment.element = $( '<a href="#" class="thumbnail"></a>' )
.data( 'customizeImageValue', attachment.get('url') )
.append( '<img src="' + attachment.get('url')+ '" />' )
.appendTo( this.tabs.uploaded.target );
}
},
thumbnailSrc: function( to ) {
if ( /^(https?:)?\/\//.test( to ) )
this.thumbnail.prop( 'src', to ).show();
else
this.thumbnail.hide();
}
});
// Change objects contained within the main customize object to Settings.
api.defaultConstructor = api.Setting;
// Create the collection of Control objects.
api.control = new api.Values({ defaultConstructor: api.Control });
api.PreviewFrame = api.Messenger.extend({
sensitivity: 2000,
initialize: function( params, options ) {
var deferred = $.Deferred(),
self = this;
// This is the promise object.
deferred.promise( this );
this.container = params.container;
this.signature = params.signature;
$.extend( params, { channel: api.PreviewFrame.uuid() });
api.Messenger.prototype.initialize.call( this, params, options );
this.add( 'previewUrl', params.previewUrl );
this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() });
this.run( deferred );
},
run: function( deferred ) {
var self = this,
loaded = false,
ready = false;
if ( this._ready )
this.unbind( 'ready', this._ready );
this._ready = function() {
ready = true;
if ( loaded )
deferred.resolveWith( self );
};
this.bind( 'ready', this._ready );
this.request = $.ajax( this.previewUrl(), {
type: 'POST',
data: this.query,
xhrFields: {
withCredentials: true
}
} );
this.request.fail( function() {
deferred.rejectWith( self, [ 'request failure' ] );
});
this.request.done( function( response ) {
var location = self.request.getResponseHeader('Location'),
signature = self.signature,
index;
// Check if the location response header differs from the current URL.
// If so, the request was redirected; try loading the requested page.
if ( location && location != self.previewUrl() ) {
deferred.rejectWith( self, [ 'redirect', location ] );
return;
}
// Check if the user is not logged in.
if ( '0' === response ) {
self.login( deferred );
return;
}
// Check for cheaters.
if ( '-1' === response ) {
deferred.rejectWith( self, [ 'cheatin' ] );
return;
}
// Check for a signature in the request.
index = response.lastIndexOf( signature );
if ( -1 === index || index < response.lastIndexOf('</html>') ) {
deferred.rejectWith( self, [ 'unsigned' ] );
return;
}
// Strip the signature from the request.
response = response.slice( 0, index ) + response.slice( index + signature.length );
// Create the iframe and inject the html content.
self.iframe = $('<iframe />').appendTo( self.container );
// Bind load event after the iframe has been added to the page;
// otherwise it will fire when injected into the DOM.
self.iframe.one( 'load', function() {
loaded = true;
if ( ready ) {
deferred.resolveWith( self );
} else {
setTimeout( function() {
deferred.rejectWith( self, [ 'ready timeout' ] );
}, self.sensitivity );
}
});
self.targetWindow( self.iframe[0].contentWindow );
self.targetWindow().document.open();
self.targetWindow().document.write( response );
self.targetWindow().document.close();
});
},
login: function( deferred ) {
var self = this,
reject;
reject = function() {
deferred.rejectWith( self, [ 'logged out' ] );
};
if ( this.triedLogin )
return reject();
// Check if we have an admin cookie.
$.get( api.settings.url.ajax, {
action: 'logged-in'
}).fail( reject ).done( function( response ) {
var iframe;
if ( '1' !== response )
reject();
iframe = $('<iframe src="' + self.previewUrl() + '" />').hide();
iframe.appendTo( self.container );
iframe.load( function() {
self.triedLogin = true;
iframe.remove();
self.run( deferred );
});
});
},
destroy: function() {
api.Messenger.prototype.destroy.call( this );
this.request.abort();
if ( this.iframe )
this.iframe.remove();
delete this.request;
delete this.iframe;
delete this.targetWindow;
}
});
(function(){
var uuid = 0;
api.PreviewFrame.uuid = function() {
return 'preview-' + uuid++;
};
}());
api.Previewer = api.Messenger.extend({
refreshBuffer: 250,
/**
* Requires params:
* - container - a selector or jQuery element
* - previewUrl - the URL of preview frame
*/
initialize: function( params, options ) {
var self = this,
rscheme = /^https?/,
url;
$.extend( this, options || {} );
/*
* Wrap this.refresh to prevent it from hammering the servers:
*
* If refresh is called once and no other refresh requests are
* loading, trigger the request immediately.
*
* If refresh is called while another refresh request is loading,
* debounce the refresh requests:
* 1. Stop the loading request (as it is instantly outdated).
* 2. Trigger the new request once refresh hasn't been called for
* self.refreshBuffer milliseconds.
*/
this.refresh = (function( self ) {
var refresh = self.refresh,
callback = function() {
timeout = null;
refresh.call( self );
},
timeout;
return function() {
if ( typeof timeout !== 'number' ) {
if ( self.loading ) {
self.abort();
} else {
return callback();
}
}
clearTimeout( timeout );
timeout = setTimeout( callback, self.refreshBuffer );
};
})( this );
this.container = api.ensure( params.container );
this.allowedUrls = params.allowedUrls;
this.signature = params.signature;
params.url = window.location.href;
api.Messenger.prototype.initialize.call( this, params );
this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) {
var match = to.match( rscheme );
return match ? match[0] : '';
});
// Limit the URL to internal, front-end links.
//
// If the frontend and the admin are served from the same domain, load the
// preview over ssl if the customizer is being loaded over ssl. This avoids
// insecure content warnings. This is not attempted if the admin and frontend
// are on different domains to avoid the case where the frontend doesn't have
// ssl certs.
this.add( 'previewUrl', params.previewUrl ).setter( function( to ) {
var result;
// Check for URLs that include "/wp-admin/" or end in "/wp-admin".
// Strip hashes and query strings before testing.
if ( /\/wp-admin(\/|$)/.test( to.replace(/[#?].*$/, '') ) )
return null;
// Attempt to match the URL to the control frame's scheme
// and check if it's allowed. If not, try the original URL.
$.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) {
$.each( self.allowedUrls, function( i, allowed ) {
if ( 0 === url.indexOf( allowed ) ) {
result = url;
return false;
}
});
if ( result )
return false;
});
// If we found a matching result, return it. If not, bail.
return result ? result : null;
});
// Refresh the preview when the URL is changed (but not yet).
this.previewUrl.bind( this.refresh );
this.scroll = 0;
this.bind( 'scroll', function( distance ) {
this.scroll = distance;
});
// Update the URL when the iframe sends a URL message.
this.bind( 'url', this.previewUrl );
},
query: function() {},
abort: function() {
if ( this.loading ) {
this.loading.destroy();
delete this.loading;
}
},
refresh: function() {
var self = this;
this.abort();
this.loading = new api.PreviewFrame({
url: this.url(),
previewUrl: this.previewUrl(),
query: this.query() || {},
container: this.container,
signature: this.signature
});
this.loading.done( function() {
// 'this' is the loading frame
this.bind( 'synced', function() {
if ( self.preview )
self.preview.destroy();
self.preview = this;
delete self.loading;
self.targetWindow( this.targetWindow() );
self.channel( this.channel() );
self.send( 'active' );
});
this.send( 'sync', {
scroll: self.scroll,
settings: api.get()
});
});
this.loading.fail( function( reason, location ) {
if ( 'redirect' === reason && location )
self.previewUrl( location );
if ( 'logged out' === reason ) {
if ( self.preview ) {
self.preview.destroy();
delete self.preview;
}
self.login().done( self.refresh );
}
if ( 'cheatin' === reason )
self.cheatin();
});
},
login: function() {
var previewer = this,
deferred, messenger, iframe;
if ( this._login )
return this._login;
deferred = $.Deferred();
this._login = deferred.promise();
messenger = new api.Messenger({
channel: 'login',
url: api.settings.url.login
});
iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container );
messenger.targetWindow( iframe[0].contentWindow );
messenger.bind( 'login', function() {
iframe.remove();
messenger.destroy();
delete previewer._login;
deferred.resolve();
});
return this._login;
},
cheatin: function() {
$( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' );
}
});
/* =====================================================================
* Ready.
* ===================================================================== */
api.controlConstructor = {
color: api.ColorControl,
upload: api.UploadControl,
image: api.ImageControl
};
$( function() {
api.settings = window._wpCustomizeSettings;
api.l10n = window._wpCustomizeControlsL10n;
// Check if we can run the customizer.
if ( ! api.settings )
return;
// Redirect to the fallback preview if any incompatibilities are found.
if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) )
return window.location = api.settings.url.fallback;
var body = $( document.body ),
overlay = body.children('.wp-full-overlay'),
query, previewer, parent;
// Prevent the form from saving when enter is pressed.
$('#customize-controls').on( 'keydown', function( e ) {
if ( $( e.target ).is('textarea') )
return;
if ( 13 === e.which ) // Enter
e.preventDefault();
});
// Initialize Previewer
previewer = new api.Previewer({
container: '#customize-preview',
form: '#customize-controls',
previewUrl: api.settings.url.preview,
allowedUrls: api.settings.url.allowed,
signature: 'WP_CUSTOMIZER_SIGNATURE'
}, {
nonce: api.settings.nonce,
query: function() {
return {
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
customized: JSON.stringify( api.get() ),
nonce: this.nonce.preview
};
},
save: function() {
var self = this,
query = $.extend( this.query(), {
action: 'customize_save',
nonce: this.nonce.save
}),
request = $.post( api.settings.url.ajax, query );
api.trigger( 'save', request );
body.addClass('saving');
request.always( function() {
body.removeClass('saving');
});
request.done( function( response ) {
// Check if the user is logged out.
if ( '0' === response ) {
self.preview.iframe.hide();
self.login().done( function() {
self.save();
self.preview.iframe.show();
});
return;
}
// Check for cheaters.
if ( '-1' === response ) {
self.cheatin();
return;
}
api.trigger( 'saved' );
});
}
});
// Refresh the nonces if the preview sends updated nonces over.
previewer.bind( 'nonce', function( nonce ) {
$.extend( this.nonce, nonce );
});
$.each( api.settings.settings, function( id, data ) {
api.create( id, id, data.value, {
transport: data.transport,
previewer: previewer
} );
});
$.each( api.settings.controls, function( id, data ) {
var constructor = api.controlConstructor[ data.type ] || api.Control,
control;
control = api.control.add( id, new constructor( id, {
params: data,
previewer: previewer
} ) );
});
// Check if preview url is valid and load the preview frame.
if ( previewer.previewUrl() )
previewer.refresh();
else
previewer.previewUrl( api.settings.url.home );
// Save and activated states
(function() {
var state = new api.Values(),
saved = state.create('saved'),
activated = state.create('activated');
state.bind( 'change', function() {
var save = $('#save'),
back = $('.back');
if ( ! activated() ) {
save.val( api.l10n.activate ).prop( 'disabled', false );
back.text( api.l10n.cancel );
} else if ( saved() ) {
save.val( api.l10n.saved ).prop( 'disabled', true );
back.text( api.l10n.close );
} else {
save.val( api.l10n.save ).prop( 'disabled', false );
back.text( api.l10n.cancel );
}
});
// Set default states.
saved( true );
activated( api.settings.theme.active );
api.bind( 'change', function() {
state('saved').set( false );
});
api.bind( 'saved', function() {
state('saved').set( true );
state('activated').set( true );
});
activated.bind( function( to ) {
if ( to )
api.trigger( 'activated' );
});
// Expose states to the API.
api.state = state;
}());
// Button bindings.
$('#save').click( function( event ) {
previewer.save();
event.preventDefault();
}).keydown( function( event ) {
if ( 9 === event.which ) // tab
return;
if ( 13 === event.which ) // enter
previewer.save();
event.preventDefault();
});
$('.back').keydown( function( event ) {
if ( 9 === event.which ) // tab
return;
if ( 13 === event.which ) // enter
parent.send( 'close' );
event.preventDefault();
});
$('.upload-dropzone a.upload').keydown( function( event ) {
if ( 13 === event.which ) // enter
this.click();
});
$('.collapse-sidebar').on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
event.preventDefault();
});
// Create a potential postMessage connection with the parent frame.
parent = new api.Messenger({
url: api.settings.url.parent,
channel: 'loader'
});
// If we receive a 'back' event, we're inside an iframe.
// Send any clicks to the 'Return' link to the parent page.
parent.bind( 'back', function() {
$('.back').on( 'click.back', function( event ) {
event.preventDefault();
parent.send( 'close' );
});
});
// Pass events through to the parent.
api.bind( 'saved', function() {
parent.send( 'saved' );
});
// When activated, let the loader handle redirecting the page.
// If no loader exists, redirect the page ourselves (if a url exists).
api.bind( 'activated', function() {
if ( parent.targetWindow() )
parent.send( 'activated', api.settings.url.activated );
else if ( api.settings.url.activated )
window.location = api.settings.url.activated;
});
// Initialize the connection with the parent frame.
parent.send( 'ready' );
// Control visibility for default controls
$.each({
'background_image': {
controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ],
callback: function( to ) { return !! to }
},
'show_on_front': {
controls: [ 'page_on_front', 'page_for_posts' ],
callback: function( to ) { return 'page' === to }
},
'header_textcolor': {
controls: [ 'header_textcolor' ],
callback: function( to ) { return 'blank' !== to }
}
}, function( settingId, o ) {
api( settingId, function( setting ) {
$.each( o.controls, function( i, controlId ) {
api.control( controlId, function( control ) {
var visibility = function( to ) {
control.container.toggle( o.callback( to ) );
};
visibility( setting.get() );
setting.bind( visibility );
});
});
});
});
// Juggle the two controls that use header_textcolor
api.control( 'display_header_text', function( control ) {
var last = '';
control.elements[0].unsync( api( 'header_textcolor' ) );
control.element = new api.Element( control.container.find('input') );
control.element.set( 'blank' !== control.setting() );
control.element.bind( function( to ) {
if ( ! to )
last = api( 'header_textcolor' ).get();
control.setting.set( to ? last : 'blank' );
});
control.setting.bind( function( to ) {
control.element.set( 'blank' !== to );
});
});
// Handle header image data
api.control( 'header_image', function( control ) {
control.setting.bind( function( to ) {
if ( to === control.params.removed )
control.settings.data.set( false );
});
control.library.on( 'click', 'a', function( event ) {
control.settings.data.set( $(this).data('customizeHeaderImageData') );
});
control.uploader.success = function( attachment ) {
var data;
api.ImageControl.prototype.success.call( control, attachment );
data = {
attachment_id: attachment.get('id'),
url: attachment.get('url'),
thumbnail_url: attachment.get('url'),
height: attachment.get('height'),
width: attachment.get('width')
};
attachment.element.data( 'customizeHeaderImageData', data );
control.settings.data.set( data );
};
});
api.trigger( 'ready' );
// Make sure left column gets focus
var topFocus = $('.back');
topFocus.focus();
setTimeout(function () {
topFocus.focus();
}, 200);
});
})( wp, jQuery );
| JavaScript |
// send html to the post editor
var wpActiveEditor;
function send_to_editor(h) {
var ed, mce = typeof(tinymce) != 'undefined', qt = typeof(QTags) != 'undefined';
if ( !wpActiveEditor ) {
if ( mce && tinymce.activeEditor ) {
ed = tinymce.activeEditor;
wpActiveEditor = ed.id;
} else if ( !qt ) {
return false;
}
} else if ( mce ) {
if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
ed = tinymce.activeEditor;
else
ed = tinymce.get(wpActiveEditor);
}
if ( ed && !ed.isHidden() ) {
// restore caret position on IE
if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
if ( h.indexOf('[caption') !== -1 ) {
if ( ed.wpSetImgCaption )
h = ed.wpSetImgCaption(h);
} else if ( h.indexOf('[gallery') !== -1 ) {
if ( ed.plugins.wpgallery )
h = ed.plugins.wpgallery._do_gallery(h);
} else if ( h.indexOf('[embed') === 0 ) {
if ( ed.plugins.wordpress )
h = ed.plugins.wordpress._setEmbed(h);
}
ed.execCommand('mceInsertContent', false, h);
} else if ( qt ) {
QTags.insertContent(h);
} else {
document.getElementById(wpActiveEditor).value += h;
}
try{tb_remove();}catch(e){};
}
// thickbox settings
var tb_position;
(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href ) return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
// store caret position in IE
$(document).ready(function($){
$('a.thickbox').click(function(){
var ed;
if ( typeof(tinymce) != 'undefined' && tinymce.isIE && ( ed = tinymce.get(wpActiveEditor) ) && !ed.isHidden() ) {
ed.focus();
ed.windowManager.insertimagebookmark = ed.selection.getBookmark();
}
});
});
})(jQuery);
| JavaScript |
(function($,undefined) {
wpWordCount = {
settings : {
strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags
clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc.
w : /\S\s+/g, // word-counting regexp
c : /\S/g // char-counting regexp for asian languages
},
block : 0,
wc : function(tx, type) {
var t = this, w = $('.word-count'), tc = 0;
if ( type === undefined )
type = wordCountL10n.type;
if ( type !== 'w' && type !== 'c' )
type = 'w';
if ( t.block )
return;
t.block = 1;
setTimeout( function() {
if ( tx ) {
tx = tx.replace( t.settings.strip, ' ' ).replace( / | /gi, ' ' );
tx = tx.replace( t.settings.clean, '' );
tx.replace( t.settings[type], function(){tc++;} );
}
w.html(tc.toString());
setTimeout( function() { t.block = 0; }, 2000 );
}, 1 );
}
}
$(document).bind( 'wpcountwords', function(e, txt) {
wpWordCount.wc(txt);
});
}(jQuery));
| JavaScript |
jQuery(document).ready( function($) {
$('#link_rel').prop('readonly', true);
$('#linkxfndiv input').bind('click keyup', function() {
var isMe = $('#me').is(':checked'), inputs = '';
$('input.valinp').each( function() {
if (isMe) {
$(this).prop('disabled', true).parent().addClass('disabled');
} else {
$(this).removeAttr('disabled').parent().removeClass('disabled');
if ( $(this).is(':checked') && $(this).val() != '')
inputs += $(this).val() + ' ';
}
});
$('#link_rel').val( (isMe) ? 'me' : inputs.substr(0,inputs.length - 1) );
});
});
| JavaScript |
(function($) {
$(document).ready(function() {
var bgImage = $("#custom-background-image"),
frame;
$('#background-color').wpColorPicker({
change: function( event, ui ) {
bgImage.css('background-color', ui.color.toString());
},
clear: function() {
bgImage.css('background-color', '');
}
});
$('input[name="background-position-x"]').change(function() {
bgImage.css('background-position', $(this).val() + ' top');
});
$('input[name="background-repeat"]').change(function() {
bgImage.css('background-repeat', $(this).val());
});
$('#choose-from-library-link').click( function( event ) {
var $el = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.customBackground = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first();
// Run an AJAX request to set the background image.
$.post( ajaxurl, {
action: 'set-background-image',
attachment_id: attachment.id,
size: 'full'
}).done( function() {
// When the request completes, reload the window.
window.location.reload();
});
});
// Finally, open the modal.
frame.open();
});
});
})(jQuery); | JavaScript |
(function($) {
inlineEditTax = {
init : function() {
var t = this, row = $('#inline-edit');
t.type = $('#the-list').attr('data-wp-lists').substr(5);
t.what = '#'+t.type+'-';
$('#the-list').on('click', 'a.editinline', function(){
inlineEditTax.edit(this);
return false;
});
// prepare the edit row
row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); });
$('a.cancel', row).click(function() { return inlineEditTax.revert(); });
$('a.save', row).click(function() { return inlineEditTax.save(this); });
$('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); });
$('#posts-filter input[type="submit"]').mousedown(function(e){
t.revert();
});
},
toggle : function(el) {
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
edit : function(id) {
var t = this, editRow;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
$(':input[name="name"]', editRow).val( $('.name', rowData).text() );
$(':input[name="slug"]', editRow).val( $('.slug', rowData).text() );
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).eq(0).focus();
return false;
},
save : function(id) {
var params, fields, tax = $('input[name="taxonomy"]').val() || '';
if( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .spinner').show();
params = {
action: 'inline-save-tax',
tax_type: this.type,
tax_ID: id,
taxonomy: tax
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
var row, new_id;
$('table.widefat .spinner').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditTax.what+id).remove();
new_id = $(r).attr('id');
$('#edit-'+id).before(r).remove();
row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id);
row.hide().fadeIn();
} else
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
} else
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
);
return false;
},
revert : function() {
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .spinner').hide();
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
return false;
},
getId : function(o) {
var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditTax.init();});
})(jQuery);
| JavaScript |
jQuery(document).ready(function($) {
$('#the-list').on('click', '.delete-tag', function(e){
var t = $(this), tr = t.parents('tr'), r = true, data;
if ( 'undefined' != showNotice )
r = showNotice.warn();
if ( r ) {
data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
// Remove the term from the parent box and tag cloud
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
tr.children().css('backgroundColor', '#f33');
}
return false;
});
$('#submit').click(function(){
var form = $(this).parents('form');
if ( !validateForm( form ) )
return false;
$.post(ajaxurl, $('#addtag').serialize(), function(r){
$('#ajax-response').empty();
var res = wpAjax.parseAjaxResponse(r, 'ajax-response');
if ( ! res || res.errors )
return;
var parent = form.find('select#parent').val();
if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list.
$('.tags #tag-' + parent).after( res.responses[0].supplemental['noparents'] ); // As the parent exists, Insert the version with - - - prefixed
else
$('.tags').prepend( res.responses[0].supplemental['parents'] ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm
$('.tags .no-items').remove();
if ( form.find('select#parent') ) {
// Parents field exists, Add new term to the list.
var term = res.responses[1].supplemental;
// Create an indent for the Parent field
var indent = '';
for ( var i = 0; i < res.responses[1].position; i++ )
indent += ' ';
form.find('select#parent option:selected').after('<option value="' + term['term_id'] + '">' + indent + term['name'] + '</option>');
}
$('input[type="text"]:visible, textarea:visible', form).val('');
});
return false;
});
});
| JavaScript |
var switchEditors = {
switchto: function(el) {
var aid = el.id, l = aid.length, id = aid.substr(0, l - 5), mode = aid.substr(l - 4);
this.go(id, mode);
},
go: function(id, mode) { // mode can be 'html', 'tmce', or 'toggle'; 'html' is used for the "Text" editor tab.
id = id || 'content';
mode = mode || 'toggle';
var t = this, ed = tinyMCE.get(id), wrap_id, txtarea_el, dom = tinymce.DOM;
wrap_id = 'wp-'+id+'-wrap';
txtarea_el = dom.get(id);
if ( 'toggle' == mode ) {
if ( ed && !ed.isHidden() )
mode = 'html';
else
mode = 'tmce';
}
if ( 'tmce' == mode || 'tinymce' == mode ) {
if ( ed && ! ed.isHidden() )
return false;
if ( typeof(QTags) != 'undefined' )
QTags.closeAllTags(id);
if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop )
txtarea_el.value = t.wpautop( txtarea_el.value );
if ( ed ) {
ed.show();
} else {
ed = new tinymce.Editor(id, tinyMCEPreInit.mceInit[id]);
ed.render();
}
dom.removeClass(wrap_id, 'html-active');
dom.addClass(wrap_id, 'tmce-active');
setUserSetting('editor', 'tinymce');
} else if ( 'html' == mode ) {
if ( ed && ed.isHidden() )
return false;
if ( ed ) {
ed.hide();
} else {
// The TinyMCE instance doesn't exist, run the content through "pre_wpautop()" and show the textarea
if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop )
txtarea_el.value = t.pre_wpautop( txtarea_el.value );
dom.setStyles(txtarea_el, {'display': '', 'visibility': ''});
}
dom.removeClass(wrap_id, 'tmce-active');
dom.addClass(wrap_id, 'html-active');
setUserSetting('editor', 'html');
}
return false;
},
_wp_Nop : function(content) {
var blocklist1, blocklist2, preserve_linebreaks = false, preserve_br = false;
// Protect pre|script tags
if ( content.indexOf('<pre') != -1 || content.indexOf('<script') != -1 ) {
preserve_linebreaks = true;
content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp-temp-lb>');
return a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-temp-lb>');
});
}
// keep <br> tags inside captions and remove line breaks
if ( content.indexOf('[caption') != -1 ) {
preserve_br = true;
content = content.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) {
return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, '');
});
}
// Pretty it up for the source editor
blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset';
content = content.replace(new RegExp('\\s*</('+blocklist1+')>\\s*', 'g'), '</$1>\n');
content = content.replace(new RegExp('\\s*<((?:'+blocklist1+')(?: [^>]*)?)>', 'g'), '\n<$1>');
// Mark </p> if it has any attributes.
content = content.replace(/(<p [^>]+>.*?)<\/p>/g, '$1</p#>');
// Sepatate <div> containing <p>
content = content.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n');
// Remove <p> and <br />
content = content.replace(/\s*<p>/gi, '');
content = content.replace(/\s*<\/p>\s*/gi, '\n\n');
content = content.replace(/\n[\s\u00a0]+\n/g, '\n\n');
content = content.replace(/\s*<br ?\/?>\s*/gi, '\n');
// Fix some block element newline issues
content = content.replace(/\s*<div/g, '\n<div');
content = content.replace(/<\/div>\s*/g, '</div>\n');
content = content.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
content = content.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption');
blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset';
content = content.replace(new RegExp('\\s*<((?:'+blocklist2+')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
content = content.replace(new RegExp('\\s*</('+blocklist2+')>\\s*', 'g'), '</$1>\n');
content = content.replace(/<li([^>]*)>/g, '\t<li$1>');
if ( content.indexOf('<hr') != -1 ) {
content = content.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
}
if ( content.indexOf('<object') != -1 ) {
content = content.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
// Unmark special paragraph closing tags
content = content.replace(/<\/p#>/g, '</p>\n');
content = content.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1');
// Trim whitespace
content = content.replace(/^\s+/, '');
content = content.replace(/[\s\u00a0]+$/, '');
// put back the line breaks in pre|script
if ( preserve_linebreaks )
content = content.replace(/<wp-temp-lb>/g, '\n');
// and the <br> tags in captions
if ( preserve_br )
content = content.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
return content;
},
_wp_Autop : function(pee) {
var preserve_linebreaks = false, preserve_br = false,
blocklist = 'table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary';
if ( pee.indexOf('<object') != -1 ) {
pee = pee.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
pee = pee.replace(/<[^<>]+>/g, function(a){
return a.replace(/[\r\n]+/g, ' ');
});
// Protect pre|script tags
if ( pee.indexOf('<pre') != -1 || pee.indexOf('<script') != -1 ) {
preserve_linebreaks = true;
pee = pee.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
return a.replace(/(\r\n|\n)/g, '<wp-temp-lb>');
});
}
// keep <br> tags inside captions and convert line breaks
if ( pee.indexOf('[caption') != -1 ) {
preserve_br = true;
pee = pee.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) {
// keep existing <br>
a = a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>');
// no line breaks inside HTML tags
a = a.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(b){
return b.replace(/[\r\n\t]+/, ' ');
});
// convert remaining line breaks to <br>
return a.replace(/\s*\n\s*/g, '<wp-temp-br />');
});
}
pee = pee + '\n\n';
pee = pee.replace(/<br \/>\s*<br \/>/gi, '\n\n');
pee = pee.replace(new RegExp('(<(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), '\n$1');
pee = pee.replace(new RegExp('(</(?:'+blocklist+')>)', 'gi'), '$1\n\n');
pee = pee.replace(/<hr( [^>]*)?>/gi, '<hr$1>\n\n'); // hr is self closing block element
pee = pee.replace(/\r\n|\r/g, '\n');
pee = pee.replace(/\n\s*\n+/g, '\n\n');
pee = pee.replace(/([\s\S]+?)\n\n/g, '<p>$1</p>\n');
pee = pee.replace(/<p>\s*?<\/p>/gi, '');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/<p>(<li.+?)<\/p>/gi, '$1');
pee = pee.replace(/<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>');
pee = pee.replace(/<\/blockquote>\s*<\/p>/gi, '</p></blockquote>');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), "$1");
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/\s*\n/gi, '<br />\n');
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')[^>]*>)\\s*<br />', 'gi'), "$1");
pee = pee.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1');
pee = pee.replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]');
pee = pee.replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function(a, b, c) {
if ( c.match(/<p( [^>]*)?>/) )
return a;
return b + '<p>' + c + '</p>';
});
// put back the line breaks in pre|script
if ( preserve_linebreaks )
pee = pee.replace(/<wp-temp-lb>/g, '\n');
if ( preserve_br )
pee = pee.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
return pee;
},
pre_wpautop : function(content) {
var t = this, o = { o: t, data: content, unfiltered: content },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforePreWpautop', [o]);
o.data = t._wp_Nop(o.data);
if ( q )
jQuery('body').trigger('afterPreWpautop', [o]);
return o.data;
},
wpautop : function(pee) {
var t = this, o = { o: t, data: pee, unfiltered: pee },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforeWpautop', [o]);
o.data = t._wp_Autop(o.data);
if ( q )
jQuery('body').trigger('afterWpautop', [o]);
return o.data;
}
}
| JavaScript |
jQuery(document).ready(function($) {
var gallerySortable, gallerySortableInit, w, desc = false;
gallerySortableInit = function() {
gallerySortable = $('#media-items').sortable( {
items: 'div.media-item',
placeholder: 'sorthelper',
axis: 'y',
distance: 2,
handle: 'div.filename',
stop: function(e, ui) {
// When an update has occurred, adjust the order for each item
var all = $('#media-items').sortable('toArray'), len = all.length;
$.each(all, function(i, id) {
var order = desc ? (len - i) : (1 + i);
$('#' + id + ' .menu_order input').val(order);
});
}
} );
}
sortIt = function() {
var all = $('.menu_order_input'), len = all.length;
all.each(function(i){
var order = desc ? (len - i) : (1 + i);
$(this).val(order);
});
}
clearAll = function(c) {
c = c || 0;
$('.menu_order_input').each(function(){
if ( this.value == '0' || c ) this.value = '';
});
}
$('#asc').click(function(){desc = false; sortIt(); return false;});
$('#desc').click(function(){desc = true; sortIt(); return false;});
$('#clear').click(function(){clearAll(1); return false;});
$('#showall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').hide();
$('a.describe-toggle-off, table.slidetoggle').show();
$('img.pinkynail').toggle(false);
return false;
});
$('#hideall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').show();
$('a.describe-toggle-off, table.slidetoggle').hide();
$('img.pinkynail').toggle(true);
return false;
});
// initialize sortable
gallerySortableInit();
clearAll();
if ( $('#media-items>*').length > 1 ) {
w = wpgallery.getWin();
$('#save-all, #gallery-settings').show();
if ( typeof w.tinyMCE != 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) {
wpgallery.mcemode = true;
wpgallery.init();
} else {
$('#insert-gallery').show();
}
}
});
jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup
/* gallery settings */
var tinymce = null, tinyMCE, wpgallery;
wpgallery = {
mcemode : false,
editor : {},
dom : {},
is_update : false,
el : {},
I : function(e) {
return document.getElementById(e);
},
init: function() {
var t = this, li, q, i, it, w = t.getWin();
if ( ! t.mcemode ) return;
li = ('' + document.location.search).replace(/^\?/, '').split('&');
q = {};
for (i=0; i<li.length; i++) {
it = li[i].split('=');
q[unescape(it[0])] = unescape(it[1]);
}
if (q.mce_rdomain)
document.domain = q.mce_rdomain;
// Find window & API
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.setup();
},
getWin : function() {
return window.dialogArguments || opener || parent || top;
},
setup : function() {
var t = this, a, ed = t.editor, g, columns, link, order, orderby;
if ( ! t.mcemode ) return;
t.el = ed.selection.getNode();
if ( t.el.nodeName != 'IMG' || ! ed.dom.hasClass(t.el, 'wpGallery') ) {
if ( (g = ed.dom.select('img.wpGallery')) && g[0] ) {
t.el = g[0];
} else {
if ( getUserSetting('galfile') == '1' ) t.I('linkto-file').checked = "checked";
if ( getUserSetting('galdesc') == '1' ) t.I('order-desc').checked = "checked";
if ( getUserSetting('galcols') ) t.I('columns').value = getUserSetting('galcols');
if ( getUserSetting('galord') ) t.I('orderby').value = getUserSetting('galord');
jQuery('#insert-gallery').show();
return;
}
}
a = ed.dom.getAttrib(t.el, 'title');
a = ed.dom.decode(a);
if ( a ) {
jQuery('#update-gallery').show();
t.is_update = true;
columns = a.match(/columns=['"]([0-9]+)['"]/);
link = a.match(/link=['"]([^'"]+)['"]/i);
order = a.match(/order=['"]([^'"]+)['"]/i);
orderby = a.match(/orderby=['"]([^'"]+)['"]/i);
if ( link && link[1] ) t.I('linkto-file').checked = "checked";
if ( order && order[1] ) t.I('order-desc').checked = "checked";
if ( columns && columns[1] ) t.I('columns').value = ''+columns[1];
if ( orderby && orderby[1] ) t.I('orderby').value = orderby[1];
} else {
jQuery('#insert-gallery').show();
}
},
update : function() {
var t = this, ed = t.editor, all = '', s;
if ( ! t.mcemode || ! t.is_update ) {
s = '[gallery'+t.getSettings()+']';
t.getWin().send_to_editor(s);
return;
}
if (t.el.nodeName != 'IMG') return;
all = ed.dom.decode(ed.dom.getAttrib(t.el, 'title'));
all = all.replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi, '');
all += t.getSettings();
ed.dom.setAttrib(t.el, 'title', all);
t.getWin().tb_remove();
},
getSettings : function() {
var I = this.I, s = '';
if ( I('linkto-file').checked ) {
s += ' link="file"';
setUserSetting('galfile', '1');
}
if ( I('order-desc').checked ) {
s += ' order="DESC"';
setUserSetting('galdesc', '1');
}
if ( I('columns').value != 3 ) {
s += ' columns="'+I('columns').value+'"';
setUserSetting('galcols', I('columns').value);
}
if ( I('orderby').value != 'menu_order' ) {
s += ' orderby="'+I('orderby').value+'"';
setUserSetting('galord', I('orderby').value);
}
return s;
}
};
| JavaScript |
jQuery(function($){
$( 'body' ).bind( 'click.wp-gallery', function(e){
var target = $( e.target ), id, img_size;
if ( target.hasClass( 'wp-set-header' ) ) {
( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' );
e.preventDefault();
} else if ( target.hasClass( 'wp-set-background' ) ) {
id = target.data( 'attachment-id' );
img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val();
jQuery.post(ajaxurl, {
action: 'set-background-image',
attachment_id: id,
size: img_size
}, function(){
var win = window.dialogArguments || opener || parent || top;
win.tb_remove();
win.location.reload();
});
e.preventDefault();
}
});
});
| JavaScript |
/* Plugin Browser Thickbox related JS*/
var tb_position;
jQuery(document).ready(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href )
return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
$('#dashboard_plugins, .plugins').on( 'click', 'a.thickbox', function() {
tb_click.call(this);
$('#TB_title').css({'background-color':'#222','color':'#cfcfcf'});
$('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong> ' + $(this).attr('title') );
return false;
});
/* Plugin install related JS*/
$('#plugin-information #sidemenu a').click( function() {
var tab = $(this).attr('name');
//Flip the tab
$('#plugin-information-header a.current').removeClass('current');
$(this).addClass('current');
//Flip the content.
$('#section-holder div.section').hide(); //Hide 'em all
$('#section-' + tab).show();
return false;
});
$('a.install-now').click( function() {
return confirm( plugininstallL10n.ays );
});
});
| JavaScript |
var postboxes;
(function($) {
postboxes = {
add_postbox_toggles : function(page, args) {
var self = this;
self.init(page, args);
$('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
if ( 'dashboard_browser_nag' == id )
return;
p.toggleClass('closed');
if ( page != 'press-this' )
self.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
self.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
self.pbhide(id);
}
});
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
});
$('.postbox a.dismiss').bind('click.postboxes', function(e) {
var hide_id = $(this).parents('.postbox').attr('id') + '-hide';
$( '#' + hide_id ).prop('checked', false).triggerHandler('click');
return false;
});
$('.hide-postbox-tog').bind('click.postboxes', function() {
var box = $(this).val();
if ( $(this).prop('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
self.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
self.pbhide( box );
}
self.save_state(page);
self._mark_area();
});
$('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){
var n = parseInt($(this).val(), 10);
if ( n ) {
self._pb_edit(n);
self.save_order(page);
}
});
},
init : function(page, args) {
var isMobile = $(document.body).hasClass('mobile');
$.extend( this, args || {} );
$('#wpbody-content').css('overflow','hidden');
$('.meta-box-sortables').sortable({
placeholder: 'sortable-placeholder',
connectWith: '.meta-box-sortables',
items: '.postbox',
handle: '.hndle',
cursor: 'move',
delay: ( isMobile ? 200 : 0 ),
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function(e,ui) {
if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) {
$(this).sortable('cancel');
return;
}
postboxes.save_order(page);
},
receive: function(e,ui) {
if ( 'dashboard_browser_nag' == ui.item[0].id )
$(ui.sender).sortable('cancel');
postboxes._mark_area();
}
});
if ( isMobile ) {
$(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); });
this._pb_change();
}
this._mark_area();
},
save_state : function(page) {
var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','),
hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
closed: closed,
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: page
});
},
save_order : function(page) {
var postVars, page_columns = $('.columns-prefs input:checked').val() || 0;
postVars = {
action: 'meta-box-order',
_ajax_nonce: $('#meta-box-order-nonce').val(),
page_columns: page_columns,
page: page
}
$('.meta-box-sortables').each( function() {
postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(',');
} );
$.post( ajaxurl, postVars );
},
_mark_area : function() {
var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables');
$('#dashboard-widgets .meta-box-sortables:visible').each(function(n, el){
var t = $(this);
if ( visible == 1 || t.children('.postbox:visible').length )
t.removeClass('empty-container');
else
t.addClass('empty-container');
});
if ( side.length ) {
if ( side.children('.postbox:visible').length )
side.removeClass('empty-container');
else if ( $('#postbox-container-1').css('width') == '280px' )
side.addClass('empty-container');
}
},
_pb_edit : function(n) {
var el = $('.metabox-holder').get(0);
el.className = el.className.replace(/columns-\d+/, 'columns-' + n);
},
_pb_change : function() {
var check = $( 'label.columns-prefs-1 input[type="radio"]' );
switch ( window.orientation ) {
case 90:
case -90:
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
break;
case 0:
case 180:
if ( $('#poststuff').length ) {
this._pb_edit(1);
} else {
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
}
break;
}
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
| JavaScript |
(function($) {
inlineEditPost = {
init : function(){
var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit');
t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post';
t.what = '#post-';
// prepare the edit rows
qeRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
bulkRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
$('a.cancel', qeRow).click(function(){
return inlineEditPost.revert();
});
$('a.save', qeRow).click(function(){
return inlineEditPost.save(this);
});
$('td', qeRow).keydown(function(e){
if ( e.which == 13 )
return inlineEditPost.save(this);
});
$('a.cancel', bulkRow).click(function(){
return inlineEditPost.revert();
});
$('#inline-edit .inline-edit-private input[value="private"]').click( function(){
var pw = $('input.inline-edit-password-input');
if ( $(this).prop('checked') ) {
pw.val('').prop('disabled', true);
} else {
pw.prop('disabled', false);
}
});
// add events
$('#the-list').on('click', 'a.editinline', function(){
inlineEditPost.edit(this);
return false;
});
$('#bulk-title-div').parents('fieldset').after(
$('#inline-edit fieldset.inline-edit-categories').clone()
).siblings( 'fieldset:last' ).prepend(
$('#inline-edit label.inline-edit-tags').clone()
);
$('select[name="_status"] option[value="future"]', bulkRow).remove();
$('#doaction, #doaction2').click(function(e){
var n = $(this).attr('id').substr(2);
if ( $('select[name="'+n+'"]').val() == 'edit' ) {
e.preventDefault();
t.setBulk();
} else if ( $('form#posts-filter tr.inline-editor').length > 0 ) {
t.revert();
}
});
$('#post-query-submit').mousedown(function(e){
t.revert();
$('select[name^="action"]').val('-1');
});
},
toggle : function(el){
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
setBulk : function(){
var te = '', type = this.type, tax, c = true;
this.revert();
$('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length);
$('table.widefat tbody').prepend( $('#bulk-edit') );
$('#bulk-edit').addClass('inline-editor').show();
$('tbody th.check-column input[type="checkbox"]').each(function(i){
if ( $(this).prop('checked') ) {
c = false;
var id = $(this).val(), theTitle;
theTitle = $('#inline_'+id+' .post_title').html() || inlineEditL10n.notitle;
te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>';
}
});
if ( c )
return this.revert();
$('#bulk-titles').html(te);
$('#bulk-titles a').click(function(){
var id = $(this).attr('id').substr(1);
$('table.widefat input[value="' + id + '"]').prop('checked', false);
$('#ttle'+id).remove();
});
// enable autocomplete for tags
if ( 'post' == type ) {
// support multi taxonomies?
tax = 'post_tag';
$('tr.inline-editor textarea[name="tax_input['+tax+']"]').suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
}
$('html, body').animate( { scrollTop: 0 }, 'fast' );
},
edit : function(id) {
var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, cur_format, f;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order'];
if ( t.type == 'page' )
fields.push('post_parent', 'page_template');
// add the new blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
// populate the data
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// author no longer has edit caps, so we need to add them to the list of authors
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $(':input[name="post_author"] option', editRow).length == 1 ) {
$('label.inline-edit-author', editRow).hide();
}
// hide unsupported formats, but leave the current format alone
cur_format = $('.post_format', rowData).text();
$('option.unsupported', editRow).each(function() {
var $this = $(this);
if ( $this.val() != cur_format )
$this.remove();
});
for ( f = 0; f < fields.length; f++ ) {
$(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() );
}
if ( $('.comment_status', rowData).text() == 'open' )
$('input[name="comment_status"]', editRow).prop("checked", true);
if ( $('.ping_status', rowData).text() == 'open' )
$('input[name="ping_status"]', editRow).prop("checked", true);
if ( $('.sticky', rowData).text() == 'sticky' )
$('input[name="sticky"]', editRow).prop("checked", true);
// hierarchical taxonomies
$('.post_category', rowData).each(function(){
var term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
//flat taxonomies
$('.tags_input', rowData).each(function(){
var terms = $(this).text(),
taxname = $(this).attr('id').replace('_' + id, ''),
textarea = $('textarea.tax_input_' + taxname, editRow),
comma = inlineEditL10n.comma;
if ( terms ) {
if ( ',' !== comma )
terms = terms.replace(/,/g, comma);
textarea.val(terms);
}
textarea.suggest( ajaxurl + '?action=ajax-tag-search&tax=' + taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
});
// handle the post status
status = $('._status', rowData).text();
if ( 'future' != status )
$('select[name="_status"] option[value="future"]', editRow).remove();
if ( 'private' == status ) {
$('input[name="keep_private"]', editRow).prop("checked", true);
$('input.inline-edit-password-input').val('').prop('disabled', true);
}
// remove the current page and children from the parent dropdown
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if (nextPage.length == 0) break;
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
},
save : function(id) {
var params, fields, page = $('.post_status_page').val() || '';
if ( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .spinner').show();
params = {
action: 'inline-save',
post_type: typenow,
post_ID: id,
edit_date: 'true',
post_status: page
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
$('table.widefat .spinner').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditPost.what+id).remove();
$('#edit-'+id).before(r).remove();
$(inlineEditPost.what+id).hide().fadeIn();
} else {
r = r.replace( /<.[^<>]*?>/g, '' );
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
}
, 'html');
return false;
},
revert : function(){
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .spinner').hide();
if ( 'bulk-edit' == id ) {
$('table.widefat #bulk-edit').removeClass('inline-editor').hide();
$('#bulk-titles').html('');
$('#inlineedit').append( $('#bulk-edit') );
} else {
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
}
return false;
},
getId : function(o) {
var id = $(o).closest('tr').attr('id'),
parts = id.split('-');
return parts[parts.length - 1];
}
};
$( document ).ready( function(){ inlineEditPost.init(); } );
// Show/hide locks on posts
$( document ).on( 'heartbeat-tick.wp-check-locked-posts', function( e, data ) {
var locked = data['wp-check-locked-posts'] || {};
$('#the-list tr').each( function(i, el) {
var key = el.id, row = $(el), lock_data, avatar;
if ( locked.hasOwnProperty( key ) ) {
if ( ! row.hasClass('wp-locked') ) {
lock_data = locked[key];
row.find('.column-title .locked-text').text( lock_data.text );
row.find('.check-column checkbox').prop('checked', false);
if ( lock_data.avatar_src ) {
avatar = $('<img class="avatar avatar-18 photo" width="18" height="18" />').attr( 'src', lock_data.avatar_src.replace(/&/g, '&') );
row.find('.column-title .locked-avatar').empty().append( avatar );
}
row.addClass('wp-locked');
}
} else if ( row.hasClass('wp-locked') ) {
// Make room for the CSS animation
row.removeClass('wp-locked').delay(1000).find('.locked-info span').empty();
}
});
}).on( 'heartbeat-send.wp-check-locked-posts', function( e, data ) {
var check = [];
$('#the-list tr').each( function(i, el) {
if ( el.id )
check.push( el.id );
});
if ( check.length )
data['wp-check-locked-posts'] = check;
});
}(jQuery));
| JavaScript |
/**
* Theme Browsing
*
* Controls visibility of theme details on manage and install themes pages.
*/
jQuery( function($) {
$('#availablethemes').on( 'click', '.theme-detail', function (event) {
var theme = $(this).closest('.available-theme'),
details = theme.find('.themedetaildiv');
if ( ! details.length ) {
details = theme.find('.install-theme-info .theme-details');
details = details.clone().addClass('themedetaildiv').appendTo( theme ).hide();
}
details.toggle();
event.preventDefault();
});
});
/**
* Theme Browser Thickbox
*
* Aligns theme browser thickbox.
*/
var tb_position;
jQuery(document).ready( function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 1040 < width ) ? 1040 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
};
$(window).resize(function(){ tb_position(); });
});
/**
* Theme Install
*
* Displays theme previews on theme install pages.
*/
jQuery( function($) {
if( ! window.postMessage )
return;
var preview = $('#theme-installer'),
info = preview.find('.install-theme-info'),
panel = preview.find('.wp-full-overlay-main'),
body = $( document.body );
preview.on( 'click', '.close-full-overlay', function( event ) {
preview.fadeOut( 200, function() {
panel.empty();
body.removeClass('theme-installer-active full-overlay-active');
});
event.preventDefault();
});
preview.on( 'click', '.collapse-sidebar', function( event ) {
preview.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
event.preventDefault();
});
$('#availablethemes').on( 'click', '.install-theme-preview', function( event ) {
var src;
info.html( $(this).closest('.installable-theme').find('.install-theme-info').html() );
src = info.find( '.theme-preview-url' ).val();
panel.html( '<iframe src="' + src + '" />');
preview.fadeIn( 200, function() {
body.addClass('theme-installer-active full-overlay-active');
});
event.preventDefault();
});
});
var ThemeViewer;
(function($){
ThemeViewer = function( args ) {
function init() {
$( '#filter-click, #mini-filter-click' ).unbind( 'click' ).click( function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
return false;
});
$( '#filter-box :checkbox' ).unbind( 'click' ).click( function() {
var count = $( '#filter-box :checked' ).length,
text = $( '#filter-click' ).text();
if ( text.indexOf( '(' ) != -1 )
text = text.substr( 0, text.indexOf( '(' ) );
if ( count == 0 )
$( '#filter-click' ).text( text );
else
$( '#filter-click' ).text( text + ' (' + count + ')' );
});
/* $('#filter-box :submit').unbind( 'click' ).click(function() {
var features = [];
$('#filter-box :checked').each(function() {
features.push($(this).val());
});
listTable.update_rows({'features': features}, true, function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
});
return false;
}); */
}
// These are the functions we expose
var api = {
init: init
};
return api;
}
})(jQuery);
jQuery( document ).ready( function($) {
theme_viewer = new ThemeViewer();
theme_viewer.init();
});
/**
* Class that provides infinite scroll for Themes admin screens
*
* @since 3.4
*
* @uses ajaxurl
* @uses list_args
* @uses theme_list_args
* @uses $('#_ajax_fetch_list_nonce').val()
* */
var ThemeScroller;
(function($){
ThemeScroller = {
querying: false,
scrollPollingDelay: 500,
failedRetryDelay: 4000,
outListBottomThreshold: 300,
/**
* Initializer
*
* @since 3.4
* @access private
*/
init: function() {
var self = this;
// Get out early if we don't have the required arguments.
if ( typeof ajaxurl === 'undefined' ||
typeof list_args === 'undefined' ||
typeof theme_list_args === 'undefined' ) {
$('.pagination-links').show();
return;
}
// Handle inputs
this.nonce = $('#_ajax_fetch_list_nonce').val();
this.nextPage = ( theme_list_args.paged + 1 );
// Cache jQuery selectors
this.$outList = $('#availablethemes');
this.$spinner = $('div.tablenav.bottom').children( '.spinner' );
this.$window = $(window);
this.$document = $(document);
/**
* If there are more pages to query, then start polling to track
* when user hits the bottom of the current page
*/
if ( theme_list_args.total_pages >= this.nextPage )
this.pollInterval =
setInterval( function() {
return self.poll();
}, this.scrollPollingDelay );
},
/**
* Checks to see if user has scrolled to bottom of page.
* If so, requests another page of content from self.ajax().
*
* @since 3.4
* @access private
*/
poll: function() {
var bottom = this.$document.scrollTop() + this.$window.innerHeight();
if ( this.querying ||
( bottom < this.$outList.height() - this.outListBottomThreshold ) )
return;
this.ajax();
},
/**
* Applies results passed from this.ajax() to $outList
*
* @since 3.4
* @access private
*
* @param results Array with results from this.ajax() query.
*/
process: function( results ) {
if ( results === undefined ) {
clearInterval( this.pollInterval );
return;
}
if ( this.nextPage > theme_list_args.total_pages )
clearInterval( this.pollInterval );
if ( this.nextPage <= ( theme_list_args.total_pages + 1 ) )
this.$outList.append( results.rows );
},
/**
* Queries next page of themes
*
* @since 3.4
* @access private
*/
ajax: function() {
var self = this;
this.querying = true;
var query = {
action: 'fetch-list',
paged: this.nextPage,
s: theme_list_args.search,
tab: theme_list_args.tab,
type: theme_list_args.type,
_ajax_fetch_list_nonce: this.nonce,
'features[]': theme_list_args.features,
'list_args': list_args
};
this.$spinner.show();
$.getJSON( ajaxurl, query )
.done( function( response ) {
self.nextPage++;
self.process( response );
self.$spinner.hide();
self.querying = false;
})
.fail( function() {
self.$spinner.hide();
self.querying = false;
setTimeout( function() { self.ajax(); }, self.failedRetryDelay );
});
}
}
$(document).ready( function($) {
ThemeScroller.init();
});
})(jQuery);
| JavaScript |
(function($){
function check_pass_strength() {
var pass1 = $('#pass1').val(), user = $('#user_login').val(), pass2 = $('#pass2').val(), strength;
$('#pass-strength-result').removeClass('short bad good strong');
if ( ! pass1 ) {
$('#pass-strength-result').html( pwsL10n.empty );
return;
}
strength = passwordStrength(pass1, user, pass2);
switch ( strength ) {
case 2:
$('#pass-strength-result').addClass('bad').html( pwsL10n['bad'] );
break;
case 3:
$('#pass-strength-result').addClass('good').html( pwsL10n['good'] );
break;
case 4:
$('#pass-strength-result').addClass('strong').html( pwsL10n['strong'] );
break;
case 5:
$('#pass-strength-result').addClass('short').html( pwsL10n['mismatch'] );
break;
default:
$('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
}
}
$(document).ready( function() {
var select = $('#display_name');
$('#pass1').val('').keyup( check_pass_strength );
$('#pass2').val('').keyup( check_pass_strength );
$('#pass-strength-result').show();
$('.color-palette').click( function() {
$(this).siblings('input[name="admin_color"]').prop('checked', true);
});
if ( select.length ) {
$('#first_name, #last_name, #nickname').bind( 'blur.user_profile', function() {
var dub = [],
inputs = {
display_nickname : $('#nickname').val() || '',
display_username : $('#user_login').val() || '',
display_firstname : $('#first_name').val() || '',
display_lastname : $('#last_name').val() || ''
};
if ( inputs.display_firstname && inputs.display_lastname ) {
inputs['display_firstlast'] = inputs.display_firstname + ' ' + inputs.display_lastname;
inputs['display_lastfirst'] = inputs.display_lastname + ' ' + inputs.display_firstname;
}
$.each( $('option', select), function( i, el ){
dub.push( el.value );
});
$.each(inputs, function( id, value ) {
if ( ! value )
return;
var val = value.replace(/<\/?[a-z][^>]*>/gi, '');
if ( inputs[id].length && $.inArray( val, dub ) == -1 ) {
dub.push(val);
$('<option />', {
'text': val
}).appendTo( select );
}
});
});
}
});
})(jQuery);
| JavaScript |
jQuery(document).ready( function($) {
var newCat, noSyncChecks = false, syncChecks, catAddAfter;
$('#link_name').focus();
// postboxes
postboxes.add_postbox_toggles('link');
// category tabs
$('#category-tabs a').click(function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('.tabs-panel').hide();
$(t).show();
if ( '#categories-all' == t )
deleteUserSetting('cats');
else
setUserSetting('cats','pop');
return false;
});
if ( getUserSetting('cats') )
$('#category-tabs a[href="#categories-pop"]').click();
// Ajax Cat
newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#link-category-add-submit').click( function() { newCat.focus(); } );
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = $(this), c = th.is(':checked'), id = th.val().toString();
$('#in-link-category-' + id + ', #in-popular-link_category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddAfter = function( r, s ) {
$(s.what + ' response_data', r).each( function() {
var t = $($(this).text());
t.find( 'label' ).each( function() {
var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o;
$('#' + id).change( syncChecks );
o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name );
} );
} );
};
$('#categorychecklist').wpList( {
alt: '',
what: 'link-category',
response: 'category-ajax-response',
addAfter: catAddAfter
} );
$('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');});
$('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');});
if ( 'pop' == getUserSetting('cats') )
$('a[href="#categories-pop"]').click();
$('#category-add-toggle').click( function() {
$(this).parents('div:first').toggleClass( 'wp-hidden-children' );
$('#category-tabs a[href="#categories-all"]').click();
$('#newcategory').focus();
return false;
} );
$('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change();
});
| JavaScript |
var theList, theExtraList, toggleWithKeyboard = false;
(function($) {
var getCount, updateCount, updatePending, dashboardTotals;
setCommentsList = function() {
var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList;
totalInput = $('input[name="_total"]', '#comments-form');
perPageInput = $('input[name="_per_page"]', '#comments-form');
pageInput = $('input[name="_page"]', '#comments-form');
dimAfter = function( r, settings ) {
var c = $('#' + settings.element), editRow, replyID, replyButton;
editRow = $('#replyrow');
replyID = $('#comment_ID', editRow).val();
replyButton = $('#replybtn', editRow);
if ( c.is('.unapproved') ) {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.replyApprove);
c.find('div.comment_status').html('0');
} else {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.reply);
c.find('div.comment_status').html('1');
}
var diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1;
updatePending( diff );
};
// Send current total, page, per_page and url
delBefore = function( settings, list ) {
var wpListsData = $(settings.target).attr('data-wp-lists'), id, el, n, h, a, author, action = false;
settings.data._total = totalInput.val() || 0;
settings.data._per_page = perPageInput.val() || 0;
settings.data._page = pageInput.val() || 0;
settings.data._url = document.location.href;
settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val();
if ( wpListsData.indexOf(':trash=1') != -1 )
action = 'trash';
else if ( wpListsData.indexOf(':spam=1') != -1 )
action = 'spam';
if ( action ) {
id = wpListsData.replace(/.*?comment-([0-9]+).*/, '$1');
el = $('#comment-' + id);
note = $('#' + action + '-undo-holder').html();
el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits.
if ( el.siblings('#replyrow').length && commentReply.cid == id )
commentReply.close();
if ( el.is('tr') ) {
n = el.children(':visible').length;
author = $('.author strong', el).text();
h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>');
} else {
author = $('.comment-author', el).text();
h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>');
}
el.before(h);
$('strong', '#undo-' + id).text(author);
a = $('.undo a', '#undo-' + id);
a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce);
a.attr('data-wp-lists', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1');
a.attr('class', 'vim-z vim-destructive');
$('.avatar', el).clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside');
a.click(function(){
list.wpList.del(this);
$('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){
$(this).remove();
$('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show() });
});
return false;
});
}
return settings;
};
// Updates the current total (stored in the _total input)
updateTotalCount = function( total, time, setConfidentTime ) {
if ( time < lastConfidentTime )
return;
if ( setConfidentTime )
lastConfidentTime = time;
totalInput.val( total.toString() );
};
dashboardTotals = function(n) {
var dash = $('#dashboard_right_now'), total, appr, totalN, apprN;
n = n || 0;
if ( isNaN(n) || !dash.length )
return;
total = $('span.total-count', dash);
appr = $('span.approved-count', dash);
totalN = getCount(total);
totalN = totalN + n;
apprN = totalN - getCount( $('span.pending-count', dash) ) - getCount( $('span.spam-count', dash) );
updateCount(total, totalN);
updateCount(appr, apprN);
};
getCount = function(el) {
var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 );
if ( isNaN(n) )
return 0;
return n;
};
updateCount = function(el, n) {
var n1 = '';
if ( isNaN(n) )
return;
n = n < 1 ? '0' : n.toString();
if ( n.length > 3 ) {
while ( n.length > 3 ) {
n1 = thousandsSeparator + n.substr(n.length - 3) + n1;
n = n.substr(0, n.length - 3);
}
n = n + n1;
}
el.html(n);
};
updatePending = function( diff ) {
$('span.pending-count').each(function() {
var a = $(this), n = getCount(a) + diff;
if ( n < 1 )
n = 0;
a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
updateCount( a, n );
});
dashboardTotals();
};
// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
delAfter = function( r, settings ) {
var total, N, spam, trash, pending,
untrash = $(settings.target).parent().is('span.untrash'),
unspam = $(settings.target).parent().is('span.unspam'),
unapproved = $('#' + settings.element).is('.unapproved');
function getUpdate(s) {
if ( $(settings.target).parent().is('span.' + s) )
return 1;
else if ( $('#' + settings.element).is('.' + s) )
return -1;
return 0;
}
if ( untrash )
trash = -1;
else
trash = getUpdate('trash');
if ( unspam )
spam = -1;
else
spam = getUpdate('spam');
if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) {
// a comment was 'deleted' from another list (e.g. approved, spam, trash) and moved to pending,
// or a trash/spam of a pending comment was undone
pending = 1;
} else if ( unapproved ) {
// a pending comment was trashed/spammed/approved
pending = -1;
}
if ( pending )
updatePending(pending);
$('span.spam-count').each( function() {
var a = $(this), n = getCount(a) + spam;
updateCount(a, n);
});
$('span.trash-count').each( function() {
var a = $(this), n = getCount(a) + trash;
updateCount(a, n);
});
if ( $('#dashboard_right_now').length ) {
N = trash ? -1 * trash : 0;
dashboardTotals(N);
} else {
total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0;
if ( $(settings.target).parent().is('span.undo') )
total++;
else
total--;
if ( total < 0 )
total = 0;
if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) {
total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || '';
if ( total_items_i18n ) {
$('.displaying-num').text( total_items_i18n );
$('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n );
$('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val());
}
updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true );
} else {
updateTotalCount( total, r, false );
}
}
if ( ! theExtraList || theExtraList.size() == 0 || theExtraList.children().size() == 0 || untrash || unspam ) {
return;
}
theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() );
refillTheExtraList();
};
refillTheExtraList = function(ev) {
var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val();
if (! args.paged)
args.paged = 1;
if (args.paged > total_pages) {
return;
}
if (ev) {
theExtraList.empty();
args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php
} else {
args.number = 1;
args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list
}
args.no_placeholder = true;
args.paged ++;
// $.query.get() needs some correction to be sent into an ajax request
if ( true === args.comment_type )
args.comment_type = '';
args = $.extend(args, {
'action': 'fetch-list',
'list_args': list_args,
'_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val()
});
$.ajax({
url: ajaxurl,
global: false,
dataType: 'json',
data: args,
success: function(response) {
theExtraList.get(0).wpList.add( response.rows );
}
});
};
theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } );
theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } )
.bind('wpListDelEnd', function(e, s){
var wpListsData = $(s.target).attr('data-wp-lists'), id = s.element.replace(/[^0-9]+/g, '');
if ( wpListsData.indexOf(':trash=1') != -1 || wpListsData.indexOf(':spam=1') != -1 )
$('#undo-' + id).fadeIn(300, function(){ $(this).show() });
});
};
commentReply = {
cid : '',
act : '',
init : function() {
var row = $('#replyrow');
$('a.cancel', row).click(function() { return commentReply.revert(); });
$('a.save', row).click(function() { return commentReply.send(); });
$('input#author, input#author-email, input#author-url', row).keypress(function(e){
if ( e.which == 13 ) {
commentReply.send();
e.preventDefault();
return false;
}
});
// add events
$('#the-comment-list .column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
$('#doaction, #doaction2, #post-query-submit').click(function(e){
if ( $('#the-comment-list #replyrow').length > 0 )
commentReply.close();
});
this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
/* $(listTable).bind('beforeChangePage', function(){
commentReply.close();
}); */
},
addEvents : function(r) {
r.each(function() {
$(this).find('.column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
});
},
toggle : function(el) {
if ( $(el).css('display') != 'none' )
$(el).find('a.vim-q').click();
},
revert : function() {
if ( $('#the-comment-list #replyrow').length < 1 )
return false;
$('#replyrow').fadeOut('fast', function(){
commentReply.close();
});
return false;
},
close : function() {
var c, replyrow = $('#replyrow');
// replyrow is not showing?
if ( replyrow.parent().is('#com-reply') )
return;
if ( this.cid && this.act == 'edit-comment' ) {
c = $('#comment-' + this.cid);
c.fadeIn(300, function(){ c.show() }).css('backgroundColor', '');
}
// reset the Quicktags buttons
if ( typeof QTags != 'undefined' )
QTags.closeAllTags('replycontent');
$('#add-new-comment').css('display', '');
replyrow.hide();
$('#com-reply').append( replyrow );
$('#replycontent').css('height', '').val('');
$('#edithead input').val('');
$('.error', replyrow).html('').hide();
$('.spinner', replyrow).hide();
this.cid = '';
},
open : function(comment_id, post_id, action) {
var t = this, editRow, rowData, act, c = $('#comment-' + comment_id), h = c.height(), replyButton;
t.close();
t.cid = comment_id;
editRow = $('#replyrow');
rowData = $('#inline-'+comment_id);
action = action || 'replyto';
act = 'edit' == action ? 'edit' : 'replyto';
act = t.act = act + '-comment';
$('#action', editRow).val(act);
$('#comment_post_ID', editRow).val(post_id);
$('#comment_ID', editRow).val(comment_id);
if ( h > 120 )
$('#replycontent', editRow).css('height', (35+h) + 'px');
if ( action == 'edit' ) {
$('#author', editRow).val( $('div.author', rowData).text() );
$('#author-email', editRow).val( $('div.author-email', rowData).text() );
$('#author-url', editRow).val( $('div.author-url', rowData).text() );
$('#status', editRow).val( $('div.comment_status', rowData).text() );
$('#replycontent', editRow).val( $('textarea.comment', rowData).val() );
$('#edithead, #savebtn', editRow).show();
$('#replyhead, #replybtn, #addhead, #addbtn', editRow).hide();
c.after( editRow ).fadeOut('fast', function(){
$('#replyrow').fadeIn(300, function(){ $(this).show() });
});
} else if ( action == 'add' ) {
$('#addhead, #addbtn', editRow).show();
$('#replyhead, #replybtn, #edithead, #editbtn', editRow).hide();
$('#the-comment-list').prepend(editRow);
$('#replyrow').fadeIn(300);
} else {
replyButton = $('#replybtn', editRow);
$('#edithead, #savebtn, #addhead, #addbtn', editRow).hide();
$('#replyhead, #replybtn', editRow).show();
c.after(editRow);
if ( c.hasClass('unapproved') ) {
replyButton.text(adminCommentsL10n.replyApprove);
} else {
replyButton.text(adminCommentsL10n.reply);
}
$('#replyrow').fadeIn(300, function(){ $(this).show() });
}
setTimeout(function() {
var rtop, rbottom, scrollTop, vp, scrollBottom;
rtop = $('#replyrow').offset().top;
rbottom = rtop + $('#replyrow').height();
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
vp = document.documentElement.clientHeight || self.innerHeight || 0;
scrollBottom = scrollTop + vp;
if ( scrollBottom - 20 < rbottom )
window.scroll(0, rbottom - vp + 35);
else if ( rtop - 20 < scrollTop )
window.scroll(0, rtop - 35);
$('#replycontent').focus().keyup(function(e){
if ( e.which == 27 )
commentReply.revert(); // close on Escape
});
}, 600);
return false;
},
send : function() {
var post = {};
$('#replysubmit .error').hide();
$('#replysubmit .spinner').show();
$('#replyrow input').not(':button').each(function() {
var t = $(this);
post[ t.attr('name') ] = t.val();
});
post.content = $('#replycontent').val();
post.id = post.comment_post_ID;
post.comments_listing = this.comments_listing;
post.p = $('[name="p"]').val();
if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') )
post.approve_parent = 1;
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { commentReply.show(x); },
error : function(r) { commentReply.error(r); }
});
return false;
},
show : function(xml) {
var t = this, r, c, id, bg, pid;
if ( typeof(xml) == 'string' ) {
t.error({'responseText': xml});
return false;
}
r = wpAjax.parseAjaxResponse(xml);
if ( r.errors ) {
t.error({'responseText': wpAjax.broken});
return false;
}
t.revert();
r = r.responses[0];
c = r.data;
id = '#comment-' + r.id;
if ( 'edit-comment' == t.act )
$(id).remove();
if ( r.supplemental.parent_approved ) {
pid = $('#comment-' + r.supplemental.parent_approved);
updatePending( -1 );
if ( this.comments_listing == 'moderated' ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){
pid.fadeOut();
});
return;
}
}
$(c).hide()
$('#replyrow').after(c);
id = $(id);
t.addEvents(id);
bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor');
id.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300, function() {
if ( pid && pid.length ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300 )
.removeClass('unapproved').addClass('approved')
.find('div.comment_status').html('1');
}
});
},
error : function(r) {
var er = r.statusText;
$('#replysubmit .spinner').hide();
if ( r.responseText )
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
if ( er )
$('#replysubmit .error').html(er).show();
},
addcomment: function(post_id) {
var t = this;
$('#add-new-comment').fadeOut(200, function(){
t.open(0, post_id, 'add');
$('table.comments-box').css('display', '');
$('#no-comments').remove();
});
}
};
$(document).ready(function(){
var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;
setCommentsList();
commentReply.init();
$(document).delegate('span.delete a.delete', 'click', function(){return false;});
if ( typeof $.table_hotkeys != 'undefined' ) {
make_hotkeys_redirect = function(which) {
return function() {
var first_last, l;
first_last = 'next' == which? 'first' : 'last';
l = $('.tablenav-pages .'+which+'-page:not(.disabled)');
if (l.length)
window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1';
}
};
edit_comment = function(event, current_row) {
window.location = $('span.edit a', current_row).attr('href');
};
toggle_all = function() {
toggleWithKeyboard = true;
$('input:checkbox', '#cb').click().prop('checked', false);
toggleWithKeyboard = false;
};
make_bulk = function(value) {
return function() {
var scope = $('select[name="action"]');
$('option[value="' + value + '"]', scope).prop('selected', true);
$('#doaction').click();
}
};
$.table_hotkeys(
$('table.widefat'),
['a', 'u', 's', 'd', 'r', 'q', 'z', ['e', edit_comment], ['shift+x', toggle_all],
['shift+a', make_bulk('approve')], ['shift+s', make_bulk('spam')],
['shift+d', make_bulk('delete')], ['shift+t', make_bulk('trash')],
['shift+z', make_bulk('untrash')], ['shift+u', make_bulk('unapprove')]],
{ highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last,
prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next') }
);
}
});
})(jQuery);
| JavaScript |
var autosave, autosaveLast = '', autosavePeriodical, autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen, autosaveLockRelease = true;
jQuery(document).ready( function($) {
if ( $('#wp-content-wrap').hasClass('tmce-active') && typeof switchEditors != 'undefined' ) {
autosaveLast = wp.autosave.getCompareString({
post_title : $('#title').val() || '',
content : switchEditors.pre_wpautop( $('#content').val() ) || '',
excerpt : $('#excerpt').val() || ''
});
} else {
autosaveLast = wp.autosave.getCompareString();
}
autosavePeriodical = $.schedule({time: autosaveL10n.autosaveInterval * 1000, func: function() { autosave(); }, repeat: true, protect: true});
//Disable autosave after the form has been submitted
$("#post").submit(function() {
$.cancel(autosavePeriodical);
autosaveLockRelease = false;
});
$('input[type="submit"], a.submitdelete', '#submitpost').click(function(){
blockSave = true;
window.onbeforeunload = null;
$(':button, :submit', '#submitpost').each(function(){
var t = $(this);
if ( t.hasClass('button-primary') )
t.addClass('button-primary-disabled');
else
t.addClass('button-disabled');
});
if ( $(this).attr('id') == 'publish' )
$('#major-publishing-actions .spinner').show();
else
$('#minor-publishing .spinner').show();
});
window.onbeforeunload = function(){
var editor = typeof(tinymce) != 'undefined' ? tinymce.activeEditor : false, compareString;
if ( editor && ! editor.isHidden() ) {
if ( editor.isDirty() )
return autosaveL10n.saveAlert;
} else {
if ( fullscreen && fullscreen.settings.visible ) {
compareString = wp.autosave.getCompareString({
post_title: $('#wp-fullscreen-title').val() || '',
content: $('#wp_mce_fullscreen').val() || '',
excerpt: $('#excerpt').val() || ''
});
} else {
compareString = wp.autosave.getCompareString();
}
if ( compareString != autosaveLast )
return autosaveL10n.saveAlert;
}
};
$(window).unload( function(e) {
if ( ! autosaveLockRelease )
return;
// unload fires (twice) on removing the Thickbox iframe. Make sure we process only the main document unload.
if ( e.target && e.target.nodeName != '#document' )
return;
$.ajax({
type: 'POST',
url: ajaxurl,
async: false,
data: {
action: 'wp-remove-post-lock',
_wpnonce: $('#_wpnonce').val(),
post_ID: $('#post_ID').val(),
active_post_lock: $('#active_post_lock').val()
}
});
} );
// preview
$('#post-preview').click(function(){
if ( $('#auto_draft').val() == '1' && notSaved ) {
autosaveDelayPreview = true;
autosave();
return false;
}
doPreview();
return false;
});
doPreview = function() {
$('input#wp-preview').val('dopreview');
$('form#post').attr('target', 'wp-preview').submit().attr('target', '');
/*
* Workaround for WebKit bug preventing a form submitting twice to the same action.
* https://bugs.webkit.org/show_bug.cgi?id=28633
*/
var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf('safari') != -1 && ua.indexOf('chrome') == -1 ) {
$('form#post').attr('action', function(index, value) {
return value + '?t=' + new Date().getTime();
});
}
$('input#wp-preview').val('');
}
// This code is meant to allow tabbing from Title to Post content.
$('#title').on('keydown.editor-focus', function(e) {
var ed;
if ( e.which != 9 )
return;
if ( !e.ctrlKey && !e.altKey && !e.shiftKey ) {
if ( typeof(tinymce) != 'undefined' )
ed = tinymce.get('content');
if ( ed && !ed.isHidden() ) {
$(this).one('keyup', function(e){
$('#content_tbl td.mceToolbar > a').focus();
});
} else {
$('#content').focus();
}
e.preventDefault();
}
});
// autosave new posts after a title is typed but not if Publish or Save Draft is clicked
if ( '1' == $('#auto_draft').val() ) {
$('#title').blur( function() {
if ( !this.value || $('#auto_draft').val() != '1' )
return;
delayed_autosave();
});
}
// When connection is lost, keep user from submitting changes.
$(document).on('heartbeat-connection-lost.autosave', function( e, error ) {
if ( 'timeout' === error ) {
var notice = $('#lost-connection-notice');
if ( ! wp.autosave.local.hasStorage ) {
notice.find('.hide-if-no-sessionstorage').hide();
}
notice.show();
autosave_disable_buttons();
}
}).on('heartbeat-connection-restored.autosave', function() {
$('#lost-connection-notice').hide();
autosave_enable_buttons();
});
});
function autosave_parse_response( response ) {
var res = wpAjax.parseAjaxResponse(response, 'autosave'), post_id, sup;
if ( res && res.responses && res.responses.length ) {
if ( res.responses[0].supplemental ) {
sup = res.responses[0].supplemental;
jQuery.each( sup, function( selector, value ) {
if ( selector.match(/^replace-/) )
jQuery( '#' + selector.replace('replace-', '') ).val( value );
});
}
// if no errors: add slug UI and update autosave-message
if ( !res.errors ) {
if ( post_id = parseInt( res.responses[0].id, 10 ) )
autosave_update_slug( post_id );
if ( res.responses[0].data ) // update autosave message
jQuery('.autosave-message').text( res.responses[0].data );
}
}
return res;
}
// called when autosaving pre-existing post
function autosave_saved(response) {
blockSave = false;
autosave_parse_response(response); // parse the ajax response
autosave_enable_buttons(); // re-enable disabled form buttons
}
// called when autosaving new post
function autosave_saved_new(response) {
blockSave = false;
var res = autosave_parse_response(response), post_id;
if ( res && res.responses.length && !res.errors ) {
// An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves
post_id = parseInt( res.responses[0].id, 10 );
if ( post_id ) {
notSaved = false;
jQuery('#auto_draft').val('0'); // No longer an auto-draft
}
autosave_enable_buttons();
if ( autosaveDelayPreview ) {
autosaveDelayPreview = false;
doPreview();
}
} else {
autosave_enable_buttons(); // re-enable disabled form buttons
}
}
function autosave_update_slug(post_id) {
// create slug area only if not already there
if ( 'undefined' != makeSlugeditClickable && jQuery.isFunction(makeSlugeditClickable) && !jQuery('#edit-slug-box > *').size() ) {
jQuery.post( ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_title: fullscreen && fullscreen.settings.visible ? jQuery('#wp-fullscreen-title').val() : jQuery('#title').val(),
samplepermalinknonce: jQuery('#samplepermalinknonce').val()
},
function(data) {
if ( data !== '-1' ) {
var box = jQuery('#edit-slug-box');
box.html(data);
if (box.hasClass('hidden')) {
box.fadeIn('fast', function () {
box.removeClass('hidden');
});
}
makeSlugeditClickable();
}
}
);
}
}
function autosave_loading() {
jQuery('.autosave-message').html(autosaveL10n.savingText);
}
function autosave_enable_buttons() {
jQuery(document).trigger('autosave-enable-buttons');
if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) {
// delay that a bit to avoid some rare collisions while the DOM is being updated.
setTimeout(function(){
var parent = jQuery('#submitpost');
parent.find(':button, :submit').removeAttr('disabled');
parent.find('.spinner').hide();
}, 500);
}
}
function autosave_disable_buttons() {
jQuery(document).trigger('autosave-disable-buttons');
jQuery('#submitpost').find(':button, :submit').prop('disabled', true);
// Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
setTimeout( autosave_enable_buttons, 5000 );
}
function delayed_autosave() {
setTimeout(function(){
if ( blockSave )
return;
autosave();
}, 200);
}
autosave = function() {
var post_data = wp.autosave.getPostData(),
compareString,
successCallback;
blockSave = true;
// post_data.content cannot be retrieved at the moment
if ( ! post_data.autosave )
return false;
// No autosave while thickbox is open (media buttons)
if ( jQuery("#TB_window").css('display') == 'block' )
return false;
compareString = wp.autosave.getCompareString( post_data );
// Nothing to save or no change.
if ( compareString == autosaveLast )
return false;
autosaveLast = compareString;
jQuery(document).triggerHandler('wpcountwords', [ post_data["content"] ]);
// Disable buttons until we know the save completed.
autosave_disable_buttons();
if ( post_data["auto_draft"] == '1' ) {
successCallback = autosave_saved_new; // new post
} else {
successCallback = autosave_saved; // pre-existing post
}
jQuery.ajax({
data: post_data,
beforeSend: autosave_loading,
type: "POST",
url: ajaxurl,
success: successCallback
});
return true;
}
// Autosave in localStorage
// set as simple object/mixin for now
window.wp = window.wp || {};
wp.autosave = wp.autosave || {};
(function($){
// Returns the data for saving in both localStorage and autosaves to the server
wp.autosave.getPostData = function() {
var ed = typeof tinymce != 'undefined' ? tinymce.activeEditor : null, post_name, parent_id, cats = [],
data = {
action: 'autosave',
autosave: true,
post_id: $('#post_ID').val() || 0,
autosavenonce: $('#autosavenonce').val() || '',
post_type: $('#post_type').val() || '',
post_author: $('#post_author').val() || '',
excerpt: $('#excerpt').val() || ''
};
if ( ed && !ed.isHidden() ) {
// Don't run while the tinymce spellcheck is on. It resets all found words.
if ( ed.plugins.spellchecker && ed.plugins.spellchecker.active ) {
data.autosave = false;
return data;
} else {
if ( 'mce_fullscreen' == ed.id )
tinymce.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'});
tinymce.triggerSave();
}
}
if ( typeof fullscreen != 'undefined' && fullscreen.settings.visible ) {
data['post_title'] = $('#wp-fullscreen-title').val() || '';
data['content'] = $('#wp_mce_fullscreen').val() || '';
} else {
data['post_title'] = $('#title').val() || '';
data['content'] = $('#content').val() || '';
}
/*
// We haven't been saving tags with autosave since 2.8... Start again?
$('.the-tags').each( function() {
data[this.name] = this.value;
});
*/
$('input[id^="in-category-"]:checked').each( function() {
cats.push(this.value);
});
data['catslist'] = cats.join(',');
if ( post_name = $('#post_name').val() )
data['post_name'] = post_name;
if ( parent_id = $('#parent_id').val() )
data['parent_id'] = parent_id;
if ( $('#comment_status').prop('checked') )
data['comment_status'] = 'open';
if ( $('#ping_status').prop('checked') )
data['ping_status'] = 'open';
if ( $('#auto_draft').val() == '1' )
data['auto_draft'] = '1';
return data;
};
// Concatenate title, content and excerpt. Used to track changes when auto-saving.
wp.autosave.getCompareString = function( post_data ) {
if ( typeof post_data === 'object' ) {
return ( post_data.post_title || '' ) + '::' + ( post_data.content || '' ) + '::' + ( post_data.excerpt || '' );
}
return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' );
};
wp.autosave.local = {
lastSavedData: '',
blog_id: 0,
hasStorage: false,
// Check if the browser supports sessionStorage and it's not disabled
checkStorage: function() {
var test = Math.random(), result = false;
try {
sessionStorage.setItem('wp-test', test);
result = sessionStorage.getItem('wp-test') == test;
sessionStorage.removeItem('wp-test');
} catch(e) {}
this.hasStorage = result;
return result;
},
/**
* Initialize the local storage
*
* @return mixed False if no sessionStorage in the browser or an Object containing all post_data for this blog
*/
getStorage: function() {
var stored_obj = false;
// Separate local storage containers for each blog_id
if ( this.hasStorage && this.blog_id ) {
stored_obj = sessionStorage.getItem( 'wp-autosave-' + this.blog_id );
if ( stored_obj )
stored_obj = JSON.parse( stored_obj );
else
stored_obj = {};
}
return stored_obj;
},
/**
* Set the storage for this blog
*
* Confirms that the data was saved successfully.
*
* @return bool
*/
setStorage: function( stored_obj ) {
var key;
if ( this.hasStorage && this.blog_id ) {
key = 'wp-autosave-' + this.blog_id;
sessionStorage.setItem( key, JSON.stringify( stored_obj ) );
return sessionStorage.getItem( key ) !== null;
}
return false;
},
/**
* Get the saved post data for the current post
*
* @return mixed False if no storage or no data or the post_data as an Object
*/
getData: function() {
var stored = this.getStorage(), post_id = $('#post_ID').val();
if ( !stored || !post_id )
return false;
return stored[ 'post_' + post_id ] || false;
},
/**
* Set (save or delete) post data in the storage.
*
* If stored_data evaluates to 'false' the storage key for the current post will be removed
*
* $param stored_data The post data to store or null/false/empty to delete the key
* @return bool
*/
setData: function( stored_data ) {
var stored = this.getStorage(), post_id = $('#post_ID').val();
if ( !stored || !post_id )
return false;
if ( stored_data )
stored[ 'post_' + post_id ] = stored_data;
else if ( stored.hasOwnProperty( 'post_' + post_id ) )
delete stored[ 'post_' + post_id ];
else
return false;
return this.setStorage(stored);
},
/**
* Save post data for the current post
*
* Runs on a 15 sec. schedule, saves when there are differences in the post title or content.
* When the optional data is provided, updates the last saved post data.
*
* $param data optional Object The post data for saving, minimum 'post_title' and 'content'
* @return bool
*/
save: function( data ) {
var result = false, post_data, compareString;
if ( ! data ) {
post_data = wp.autosave.getPostData();
} else {
post_data = this.getData() || {};
$.extend( post_data, data );
post_data.autosave = true;
}
// Cannot get the post data at the moment
if ( ! post_data.autosave )
return false;
compareString = wp.autosave.getCompareString( post_data );
// If the content, title and excerpt did not change since the last save, don't save again
if ( compareString == this.lastSavedData )
return false;
post_data['save_time'] = (new Date()).getTime();
post_data['status'] = $('#post_status').val() || '';
result = this.setData( post_data );
if ( result )
this.lastSavedData = compareString;
return result;
},
// Initialize and run checkPost() on loading the script (before TinyMCE init)
init: function( settings ) {
var self = this;
// Check if the browser supports sessionStorage and it's not disabled
if ( ! this.checkStorage() )
return;
// Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'.
if ( ! $('#content').length && ! $('#excerpt').length )
return;
if ( settings )
$.extend( this, settings );
if ( !this.blog_id )
this.blog_id = typeof window.autosaveL10n != 'undefined' ? window.autosaveL10n.blog_id : 0;
$(document).ready( function(){ self.run(); } );
},
// Run on DOM ready
run: function() {
var self = this;
// Check if the local post data is different than the loaded post data.
this.checkPost();
// Set the schedule
this.schedule = $.schedule({
time: 15 * 1000,
func: function() { wp.autosave.local.save(); },
repeat: true,
protect: true
});
$('form#post').on('submit.autosave-local', function() {
var editor = typeof tinymce != 'undefined' && tinymce.get('content'), post_id = $('#post_ID').val() || 0;
if ( editor && ! editor.isHidden() ) {
// Last onSubmit event in the editor, needs to run after the content has been moved to the textarea.
editor.onSubmit.add( function() {
wp.autosave.local.save({
post_title: $('#title').val() || '',
content: $('#content').val() || '',
excerpt: $('#excerpt').val() || ''
});
});
} else {
self.save({
post_title: $('#title').val() || '',
content: $('#content').val() || '',
excerpt: $('#excerpt').val() || ''
});
}
wpCookies.set( 'wp-saving-post-' + post_id, 'check' );
});
},
// Strip whitespace and compare two strings
compare: function( str1, str2 ) {
function remove( string ) {
return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
}
return ( remove( str1 || '' ) == remove( str2 || '' ) );
},
/**
* Check if the saved data for the current post (if any) is different than the loaded post data on the screen
*
* Shows a standard message letting the user restore the post data if different.
*
* @return void
*/
checkPost: function() {
var self = this, post_data = this.getData(), content, post_title, excerpt, notice,
post_id = $('#post_ID').val() || 0, cookie = wpCookies.get( 'wp-saving-post-' + post_id );
if ( ! post_data )
return;
if ( cookie ) {
wpCookies.remove( 'wp-saving-post-' + post_id );
if ( cookie == 'saved' ) {
// The post was saved properly, remove old data and bail
this.setData( false );
return;
}
}
// There is a newer autosave. Don't show two "restore" notices at the same time.
if ( $('#has-newer-autosave').length )
return;
content = $('#content').val() || '';
post_title = $('#title').val() || '';
excerpt = $('#excerpt').val() || '';
if ( $('#wp-content-wrap').hasClass('tmce-active') && typeof switchEditors != 'undefined' )
content = switchEditors.pre_wpautop( content );
// cookie == 'check' means the post was not saved properly, always show #local-storage-notice
if ( cookie != 'check' && this.compare( content, post_data.content ) && this.compare( post_title, post_data.post_title ) && this.compare( excerpt, post_data.excerpt ) ) {
return;
}
this.restore_post_data = post_data;
this.undo_post_data = {
content: content,
post_title: post_title,
excerpt: excerpt
};
notice = $('#local-storage-notice');
$('.wrap h2').first().after( notice.addClass('updated').show() );
notice.on( 'click', function(e) {
var target = $( e.target );
if ( target.hasClass('restore-backup') ) {
self.restorePost( self.restore_post_data );
target.parent().hide();
$(this).find('p.undo-restore').show();
} else if ( target.hasClass('undo-restore-backup') ) {
self.restorePost( self.undo_post_data );
target.parent().hide();
$(this).find('p.local-restore').show();
}
e.preventDefault();
});
},
// Restore the current title, content and excerpt from post_data.
restorePost: function( post_data ) {
var editor;
if ( post_data ) {
// Set the last saved data
this.lastSavedData = wp.autosave.getCompareString( post_data );
if ( $('#title').val() != post_data.post_title )
$('#title').focus().val( post_data.post_title || '' );
$('#excerpt').val( post_data.excerpt || '' );
editor = typeof tinymce != 'undefined' && tinymce.get('content');
if ( editor && ! editor.isHidden() && typeof switchEditors != 'undefined' ) {
// Make sure there's an undo level in the editor
editor.undoManager.add();
editor.setContent( post_data.content ? switchEditors.wpautop( post_data.content ) : '' );
} else {
// Make sure the Text editor is selected
$('#content-html').click();
$('#content').val( post_data.content );
}
return true;
}
return false;
}
};
wp.autosave.local.init();
}(jQuery));
| JavaScript |
var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
var items = jQuery('#media-items').children(), postid = post_id || 0;
// Collapse a single item
if ( items.length == 1 ) {
items.removeClass('open').find('.slidetoggle').slideUp(200);
}
// Create a progress bar containing the filename
jQuery('<div class="media-item">')
.attr( 'id', 'media-item-' + fileObj.id )
.addClass('child-of-' + postid)
.append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>',
jQuery('<div class="filename original">').text( ' ' + fileObj.name ))
.appendTo( jQuery('#media-items' ) );
// Disable submit
jQuery('#insert-gallery').prop('disabled', true);
}
function uploadStart() {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(up, file) {
var item = jQuery('#media-item-' + file.id);
jQuery('.bar', item).width( (200 * file.loaded) / file.size );
jQuery('.percent', item).html( file.percent + '%' );
}
// check to see if a large file failed to upload
function fileUploading(up, file) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
if ( max > hundredmb && file.size > hundredmb ) {
setTimeout(function(){
var done;
if ( file.status < 3 && file.loaded == 0 ) { // not uploading
wpFileError(file, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
up.stop(); // stops the whole queue
up.removeFile(file);
up.start(); // restart the queue
}
}, 10000); // wait for 10 sec. for the file to start uploading
}
}
function updateMediaForm() {
var items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( items.length == 1 ) {
items.addClass('open').find('.slidetoggle').show();
jQuery('.insert-gallery').hide();
} else if ( items.length > 1 ) {
items.removeClass('open');
// Only show Gallery button when there are at least two files.
jQuery('.insert-gallery').show();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
}
function uploadSuccess(fileObj, serverData) {
var item = jQuery('#media-item-' + fileObj.id);
// on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match(/media-upload-error|error-div/) ) {
item.html(serverData);
return;
} else {
jQuery('.percent', item).html( pluploadL10n.crunching );
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( post_id && item.hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function setResize(arg) {
if ( arg ) {
if ( uploader.features.jpgresize )
uploader.settings['resize'] = { width: resize_width, height: resize_height, quality: 100 };
else
uploader.settings.multipart_params.image_resize = true;
} else {
delete(uploader.settings.resize);
delete(uploader.settings.multipart_params.image_resize);
}
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
if ( f == 2 && shortform > 2 )
f = shortform;
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
item.append(serverData);
prepareMediaItemInit(fileObj);
} else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('.menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn();
}
// generic error message
function wpQueueError(message) {
jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
}
// file-specific error messages
function wpFileError(fileObj, message) {
itemAjaxError(fileObj.id, message);
}
function itemAjaxError(id, message) {
var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
if ( last_err == id ) // prevent firing an error for the same file twice
return;
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>'
+ '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> '
+ message
+ '</div>').data('last-err', id);
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function uploadComplete() {
jQuery('#insert-gallery').prop('disabled', false);
}
function switchUploader(s) {
if ( s ) {
deleteUserSetting('uploader');
jQuery('.media-upload-form').removeClass('html-uploader');
if ( typeof(uploader) == 'object' )
uploader.refresh();
} else {
setUserSetting('uploader', '1'); // 1 == html uploader
jQuery('.media-upload-form').addClass('html-uploader');
}
}
function dndHelper(s) {
var d = document.getElementById('dnd-helper');
if ( s ) {
d.style.display = 'block';
} else {
d.style.display = 'none';
}
}
function uploadError(fileObj, errorCode, message, uploader) {
var hundredmb = 100 * 1024 * 1024, max;
switch (errorCode) {
case plupload.FAILED:
wpFileError(fileObj, pluploadL10n.upload_failed);
break;
case plupload.FILE_EXTENSION_ERROR:
wpFileError(fileObj, pluploadL10n.invalid_filetype);
break;
case plupload.FILE_SIZE_ERROR:
uploadSizeError(uploader, fileObj);
break;
case plupload.IMAGE_FORMAT_ERROR:
wpFileError(fileObj, pluploadL10n.not_an_image);
break;
case plupload.IMAGE_MEMORY_ERROR:
wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
break;
case plupload.IMAGE_DIMENSIONS_ERROR:
wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
break;
case plupload.GENERIC_ERROR:
wpQueueError(pluploadL10n.upload_failed);
break;
case plupload.IO_ERROR:
max = parseInt(uploader.settings.max_file_size, 10);
if ( max > hundredmb && fileObj.size > hundredmb )
wpFileError(fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
else
wpQueueError(pluploadL10n.io_error);
break;
case plupload.HTTP_ERROR:
wpQueueError(pluploadL10n.http_error);
break;
case plupload.INIT_ERROR:
jQuery('.media-upload-form').addClass('html-uploader');
break;
case plupload.SECURITY_ERROR:
wpQueueError(pluploadL10n.security_error);
break;
/* case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
case plupload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;*/
default:
wpFileError(fileObj, pluploadL10n.default_error);
}
}
function uploadSizeError( up, file, over100mb ) {
var message;
if ( over100mb )
message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>');
else
message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
up.removeFile(file);
}
jQuery(document).ready(function($){
$('.media-upload-form').bind('click.uploader', function(e) {
var target = $(e.target), tr, c;
if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
tr = target.closest('tr');
if ( tr.hasClass('align') )
setUserSetting('align', target.val());
else if ( tr.hasClass('image-size') )
setUserSetting('imgsize', target.val());
} else if ( target.is('button.button') ) { // remember the last used image link url
c = e.target.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
target.siblings('.urlfield').val( target.data('link-url') );
}
} else if ( target.is('a.dismiss') ) {
target.parents('.media-item').fadeOut(200, function(){
$(this).remove();
});
} else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
$('#media-items, p.submit, span.big-file-warning').css('display', 'none');
switchUploader(0);
e.preventDefault();
} else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
$('#media-items, p.submit, span.big-file-warning').css('display', '');
switchUploader(1);
e.preventDefault();
} else if ( target.is('a.describe-toggle-on') ) { // Show
target.parent().addClass('open');
target.siblings('.slidetoggle').fadeIn(250, function(){
var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
if ( H && top && h ) {
b = top + h;
B = S + H;
if ( b > B ) {
if ( b - B < top - S )
window.scrollBy(0, (b - B) + 10);
else
window.scrollBy(0, top - S - 40);
}
}
});
e.preventDefault();
} else if ( target.is('a.describe-toggle-off') ) { // Hide
target.siblings('.slidetoggle').fadeOut(250, function(){
target.parent().removeClass('open');
});
e.preventDefault();
}
});
// init and set the uploader
uploader_init = function() {
uploader = new plupload.Uploader(wpUploaderInit);
$('#image_resize').bind('change', function() {
var arg = $(this).prop('checked');
setResize( arg );
if ( arg )
setUserSetting('upload_resize', '1');
else
deleteUserSetting('upload_resize');
});
uploader.bind('Init', function(up) {
var uploaddiv = $('#plupload-upload-ui');
setResize( getUserSetting('upload_resize', false) );
if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
uploaddiv.addClass('drag-drop');
$('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
uploaddiv.addClass('drag-over');
}).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
uploaddiv.removeClass('drag-over');
});
} else {
uploaddiv.removeClass('drag-drop');
$('#drag-drop-area').unbind('.wp-uploader');
}
if ( up.runtime == 'html4' )
$('.upload-flash-bypass').hide();
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
$('#media-upload-error').html('');
uploadStart();
plupload.each(files, function(file){
if ( max > hundredmb && file.size > hundredmb && up.runtime != 'html5' )
uploadSizeError( up, file, true );
else
fileQueued(file);
});
up.refresh();
up.start();
});
uploader.bind('BeforeUpload', function(up, file) {
// something
});
uploader.bind('UploadFile', function(up, file) {
fileUploading(up, file);
});
uploader.bind('UploadProgress', function(up, file) {
uploadProgress(up, file);
});
uploader.bind('Error', function(up, err) {
uploadError(err.file, err.code, err.message, up);
up.refresh();
});
uploader.bind('FileUploaded', function(up, file, response) {
uploadSuccess(file, response.response);
});
uploader.bind('UploadComplete', function(up, files) {
uploadComplete();
});
}
if ( typeof(wpUploaderInit) == 'object' )
uploader_init();
});
| JavaScript |
window.wp = window.wp || {};
(function( exports, $ ) {
var Uploader;
if ( typeof _wpPluploadSettings === 'undefined' )
return;
/*
* An object that helps create a WordPress uploader using plupload.
*
* @param options - object - The options passed to the new plupload instance.
* Accepts the following parameters:
* - container - The id of uploader container.
* - browser - The id of button to trigger the file select.
* - dropzone - The id of file drop target.
* - plupload - An object of parameters to pass to the plupload instance.
* - params - An object of parameters to pass to $_POST when uploading the file.
* Extends this.plupload.multipart_params under the hood.
*
* @param attributes - object - Attributes and methods for this specific instance.
*/
Uploader = function( options ) {
var self = this,
elements = {
container: 'container',
browser: 'browse_button',
dropzone: 'drop_element'
},
key, error;
this.supports = {
upload: Uploader.browser.supported
};
this.supported = this.supports.upload;
if ( ! this.supported )
return;
// Use deep extend to ensure that multipart_params and other objects are cloned.
this.plupload = $.extend( true, { multipart_params: {} }, Uploader.defaults );
this.container = document.body; // Set default container.
// Extend the instance with options
//
// Use deep extend to allow options.plupload to override individual
// default plupload keys.
$.extend( true, this, options );
// Proxy all methods so this always refers to the current instance.
for ( key in this ) {
if ( $.isFunction( this[ key ] ) )
this[ key ] = $.proxy( this[ key ], this );
}
// Ensure all elements are jQuery elements and have id attributes
// Then set the proper plupload arguments to the ids.
for ( key in elements ) {
if ( ! this[ key ] )
continue;
this[ key ] = $( this[ key ] ).first();
if ( ! this[ key ].length ) {
delete this[ key ];
continue;
}
if ( ! this[ key ].prop('id') )
this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ );
this.plupload[ elements[ key ] ] = this[ key ].prop('id');
}
// If the uploader has neither a browse button nor a dropzone, bail.
if ( ! ( this.browser && this.browser.length ) && ! ( this.dropzone && this.dropzone.length ) )
return;
this.uploader = new plupload.Uploader( this.plupload );
delete this.plupload;
// Set default params and remove this.params alias.
this.param( this.params || {} );
delete this.params;
error = function( message, data, file ) {
if ( file.attachment )
file.attachment.destroy();
Uploader.errors.unshift({
message: message || pluploadL10n.default_error,
data: data,
file: file
});
self.error( message, data, file );
};
this.uploader.init();
this.supports.dragdrop = this.uploader.features.dragdrop && ! Uploader.browser.mobile;
// Generate drag/drop helper classes.
(function( dropzone, supported ) {
var timer, active;
if ( ! dropzone )
return;
dropzone.toggleClass( 'supports-drag-drop', !! supported );
if ( ! supported )
return dropzone.unbind('.wp-uploader');
// 'dragenter' doesn't fire correctly,
// simulate it with a limited 'dragover'
dropzone.bind( 'dragover.wp-uploader', function(){
if ( timer )
clearTimeout( timer );
if ( active )
return;
dropzone.trigger('dropzone:enter').addClass('drag-over');
active = true;
});
dropzone.bind('dragleave.wp-uploader, drop.wp-uploader', function(){
// Using an instant timer prevents the drag-over class from
// being quickly removed and re-added when elements inside the
// dropzone are repositioned.
//
// See http://core.trac.wordpress.org/ticket/21705
timer = setTimeout( function() {
active = false;
dropzone.trigger('dropzone:leave').removeClass('drag-over');
}, 0 );
});
}( this.dropzone, this.supports.dragdrop ));
if ( this.browser ) {
this.browser.on( 'mouseenter', this.refresh );
} else {
this.uploader.disableBrowse( true );
// If HTML5 mode, hide the auto-created file container.
$('#' + this.uploader.id + '_html5_container').hide();
}
this.uploader.bind( 'FilesAdded', function( up, files ) {
_.each( files, function( file ) {
var attributes, image;
// Ignore failed uploads.
if ( plupload.FAILED === file.status )
return;
// Generate attributes for a new `Attachment` model.
attributes = _.extend({
file: file,
uploading: true,
date: new Date(),
filename: file.name,
menuOrder: 0,
uploadedTo: wp.media.model.settings.post.id
}, _.pick( file, 'loaded', 'size', 'percent' ) );
// Handle early mime type scanning for images.
image = /(?:jpe?g|png|gif)$/i.exec( file.name );
// Did we find an image?
if ( image ) {
attributes.type = 'image';
// `jpeg`, `png` and `gif` are valid subtypes.
// `jpg` is not, so map it to `jpeg`.
attributes.subtype = ( 'jpg' === image[0] ) ? 'jpeg' : image[0];
}
// Create the `Attachment`.
file.attachment = wp.media.model.Attachment.create( attributes );
Uploader.queue.add( file.attachment );
self.added( file.attachment );
});
up.refresh();
up.start();
});
this.uploader.bind( 'UploadProgress', function( up, file ) {
file.attachment.set( _.pick( file, 'loaded', 'percent' ) );
self.progress( file.attachment );
});
this.uploader.bind( 'FileUploaded', function( up, file, response ) {
var complete;
try {
response = JSON.parse( response.response );
} catch ( e ) {
return error( pluploadL10n.default_error, e, file );
}
if ( ! _.isObject( response ) || _.isUndefined( response.success ) )
return error( pluploadL10n.default_error, null, file );
else if ( ! response.success )
return error( response.data && response.data.message, response.data, file );
_.each(['file','loaded','size','percent'], function( key ) {
file.attachment.unset( key );
});
file.attachment.set( _.extend( response.data, { uploading: false }) );
wp.media.model.Attachment.get( response.data.id, file.attachment );
complete = Uploader.queue.all( function( attachment ) {
return ! attachment.get('uploading');
});
if ( complete )
Uploader.queue.reset();
self.success( file.attachment );
});
this.uploader.bind( 'Error', function( up, pluploadError ) {
var message = pluploadL10n.default_error,
key;
// Check for plupload errors.
for ( key in Uploader.errorMap ) {
if ( pluploadError.code === plupload[ key ] ) {
message = Uploader.errorMap[ key ];
if ( _.isFunction( message ) )
message = message( pluploadError.file, pluploadError );
break;
}
}
error( message, pluploadError, pluploadError.file );
up.refresh();
});
this.init();
};
// Adds the 'defaults' and 'browser' properties.
$.extend( Uploader, _wpPluploadSettings );
Uploader.uuid = 0;
Uploader.errorMap = {
'FAILED': pluploadL10n.upload_failed,
'FILE_EXTENSION_ERROR': pluploadL10n.invalid_filetype,
'IMAGE_FORMAT_ERROR': pluploadL10n.not_an_image,
'IMAGE_MEMORY_ERROR': pluploadL10n.image_memory_exceeded,
'IMAGE_DIMENSIONS_ERROR': pluploadL10n.image_dimensions_exceeded,
'GENERIC_ERROR': pluploadL10n.upload_failed,
'IO_ERROR': pluploadL10n.io_error,
'HTTP_ERROR': pluploadL10n.http_error,
'SECURITY_ERROR': pluploadL10n.security_error,
'FILE_SIZE_ERROR': function( file ) {
return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
}
};
$.extend( Uploader.prototype, {
/**
* Acts as a shortcut to extending the uploader's multipart_params object.
*
* param( key )
* Returns the value of the key.
*
* param( key, value )
* Sets the value of a key.
*
* param( map )
* Sets values for a map of data.
*/
param: function( key, value ) {
if ( arguments.length === 1 && typeof key === 'string' )
return this.uploader.settings.multipart_params[ key ];
if ( arguments.length > 1 ) {
this.uploader.settings.multipart_params[ key ] = value;
} else {
$.extend( this.uploader.settings.multipart_params, key );
}
},
init: function() {},
error: function() {},
success: function() {},
added: function() {},
progress: function() {},
complete: function() {},
refresh: function() {
var node, attached, container, id;
if ( this.browser ) {
node = this.browser[0];
// Check if the browser node is in the DOM.
while ( node ) {
if ( node === document.body ) {
attached = true;
break;
}
node = node.parentNode;
}
// If the browser node is not attached to the DOM, use a
// temporary container to house it, as the browser button
// shims require the button to exist in the DOM at all times.
if ( ! attached ) {
id = 'wp-uploader-browser-' + this.uploader.id;
container = $( '#' + id );
if ( ! container.length ) {
container = $('<div class="wp-uploader-browser" />').css({
position: 'fixed',
top: '-1000px',
left: '-1000px',
height: 0,
width: 0
}).attr( 'id', 'wp-uploader-browser-' + this.uploader.id ).appendTo('body');
}
container.append( this.browser );
}
}
this.uploader.refresh();
}
});
Uploader.queue = new wp.media.model.Attachments( [], { query: false });
Uploader.errors = new Backbone.Collection();
exports.Uploader = Uploader;
})( wp, jQuery );
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.