<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE

/**
 * @author Toni Dahl
 */

(function ( namespace, undefined ) {

    var ECSky, util;

    util = namespace.util;

    /**
     * ECMaterial constructor
     *
     * @constructor
     * @augments Component
     * @name ECSky
     * @type Function
     * @param {object} sceneMgr Pointer to scene manager.
     */

    ECSky = namespace.ECSky = function ( sceneMgr ) {
        //Inherit component properties
        namespace.Component.call( this, sceneMgr );

        // Default attributes
        //this.createAttribute("material", "RexSkyBox", 'assetref');
        this.createAttribute( "texture", ["rex_sky_front.dds",
                                          "rex_sky_back.dds",
                                          "rex_sky_left.dds",
                                          "rex_sky_right.dds",
                                          "rex_sky_top.dds",
                                          "rex_sky_bot.dds" ], 'assetreflist', "textureRefs" );
        this.createAttribute( "distance", 3, 'real' );
        this.createAttribute( "orientation", [0.0, 0.0, 0.0, 1.0], 'quat' );
        this.createAttribute( "drawfirst", true, 'bool', "drawFirst" );

        // Other properties
        this.defaultTextures = ["rex_sky_front.dds",
                                "rex_sky_back.dds",
                                "rex_sky_left.dds",
                                "rex_sky_right.dds",
                                "rex_sky_top.dds",
                                "rex_sky_bot.dds"];
        this.defaultPath = "default_assets/textures/";
        this.textureAssets = [];
        this.cubeTexture = null;
        this.skyBox = null;

    };

    namespace.storeComponent( 10, "EC_Sky", ECSky );

    ECSky.prototype = util.extend( Object.create( namespace.Component.prototype ),
        {

            onAttributeUpdated: function ( attr ) {
                if ( attr['name'] === "texture" ) {
                    var textures = this.defaultTextures;

                    if ( !this.textureRefs.every( function ( e ) {
                            return textures.indexOf( e ) !== -1;
                        }
                    ) ) {
                        console.warn("EC_Sky: Using different skybox textures than default. " +
                            "Trying to request them from remote storage.");
                        this.defaultPath = "";
                    }
                }

            },

            onParentAdded: function ( parent ) {
                this.getTextures();
            },

            onTextureAssetLoaded: function ( texture ) {
                if ( this.textureAssets.length === 6 ) {
                    console.log( "ECSky: All textures loaded. Creating Sky..." );
                    this.cubeTexture = this.createCubeTexture( this.textureAssets );
                    this.createSky( this.cubeTexture );
                }

            },

            disableSky: function () {

            },

            createSky: function ( cubeTexture ) {
                var shader, material, skyBox, geometry, distance = this.distance;
                //inverse = this.sceneManager.camera.inverse;

                if(!cubeTexture){
                    return;
                }

                //shader = THREE.ShaderLib[ "cube" ];
                //cubeTexture.mapping = new THREE.UVMapping();
                //shader.uniforms[ "tCube" ].value = cubeTexture;
                 /*
                 shader.vertexShader = [
                     "varying vec3 vWorldPosition;",

                     "void main() {",

                     "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
                     "vWorldPosition = worldPosition.xyz;",

                     "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

                     "}"
                 ].join( "\n" );

                 shader.fragmentShader = [
                     "uniform samplerCube tCube;",
                     "uniform float tFlip;",

                     "varying vec3 vWorldPosition;",

                     "void main() {",

                     "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",

                     "}"
                 ].join( "\n" );
                */
                /*material = new THREE.ShaderMaterial( {

                    fragmentShader: shader.fragmentShader,
                    vertexShader: shader.vertexShader,
                    uniforms: shader.uniforms,
                    depthWrite: false,
                    side: THREE.BackSide

                } );*/

                material = new THREE.MeshFaceMaterial( cubeTexture );
                material.depthWrite = false;
                material.side = THREE.BackSide;
                console.log(material)

                geometry = new THREE.CubeGeometry( distance, distance, distance );
                skyBox = this.skyBox = new THREE.Mesh( geometry, material );

                // This has no effect for the top face uv mapping for some reason, hence it has wrong orientation
                skyBox.geometry.faceVertexUvs[0][2] = [new THREE.Vector2(0, 0), new THREE.Vector2(0, 1),
                                                       new THREE.Vector2(1, 1), new THREE.Vector2(1, 0)];
                skyBox.geometry.uvsNeedUpdate = true;

                //this.sceneManager.camera.add(skyBox)
                this.sceneManager.addSkyBox( skyBox );

            },

            createCubeTexture: function ( textures ) {
                var ordered = [], texturesLen = textures.length, name, i, order;

                function checkOrder( name ) {
                    if ( typeof name !== 'string' && name !== '' ) {
                        console.error( "ECSky: Invalid SkyBox texture name!" );
                        return false;
                    }

                    if ( name.indexOf( "front" ) !== -1 ) {
                        return 0;
                    } else if ( name.indexOf( "back" ) !== -1 ) {
                        return 1;
                    } else if ( name.indexOf( "top" ) !== -1 ) {
                        return 2;
                    } else if ( name.indexOf( "bot" ) !== -1 ) {
                        return 3;
                    } else if ( name.indexOf( "left" ) !== -1 ) {
                        return 4;
                    } else if ( name.indexOf( "right" ) !== -1 ) {
                        return 5;
                    } else {
                        console.error( "ECSky: Invalid SkyBox texture: " + name );
                        return false;
                    }
                }

                for ( i = texturesLen; i--; ) {
                    order = checkOrder( textures[i].name );

                    if (!order) {
                        return false;
                    }

                    ordered[order] = textures[i];
                }

                return ordered;
            },

            getTextures: function () {
                var request, texture, i,
                    refs = this.textureRefs,
                    refsLen = refs.length,
                    assetManager = this.sceneManager.assetManager,
                    assets = this.textureAssets,
                    self = this;

                if ( !assetManager ) {
                    throw new Error( ["ECSky: Could not get AssetManager object, texture load failed;"] );
                }

                if ( refs && refsLen === 6 ) {

                    var callBack = function ( asset ) {
                        if ( asset ) {
                            assets.push( asset );
                            self.onTextureAssetLoaded( asset );
                        }
                    };

                    for ( i = refsLen; i--; ) {
                        request = assetManager.requestAsset( refs[i], 'texture', this.defaultPath );
                        if ( request ) {
                            request.add( callBack );
                        } else {
                            texture = assetManager.getAsset( refs[i], 'texture', this.defaultPath );
                            if ( texture ) {
                                assets.push( texture );
                                self.onTextureAssetLoaded( texture );
                            }
                        }
                    }
                }

            }

        } // Prototype end
    );

}( window['webtundra'] = window['webtundra'] || {} ));
<commit_msg>Fixed the sky component to work with the new texture asset handling. Added dynamically changeable skybox faces.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE

/**
 * @author Toni Dahl
 */

(function ( namespace, undefined ) {

    var ECSky, util;

    util = namespace.util;

    /**
     * ECMaterial constructor
     *
     * @constructor
     * @augments Component
     * @name ECSky
     * @type Function
     * @param {object} sceneMgr Pointer to scene manager.
     */

    ECSky = namespace.ECSky = function ( sceneMgr ) {
        //Inherit component properties
        namespace.Component.call( this, sceneMgr );

        // Default attributes
        //this.createAttribute("material", "RexSkyBox", 'assetref');
        this.createAttribute( "texture", ["rex_sky_front.dds",
                                          "rex_sky_back.dds",
                                          "rex_sky_left.dds",
                                          "rex_sky_right.dds",
                                          "rex_sky_top.dds",
                                          "rex_sky_bot.dds" ], 'assetreflist', "textureRefs" );
        this.createAttribute( "distance", 3, 'real' );
        this.createAttribute( "orientation", [0.0, 0.0, 0.0, 1.0], 'quat' );
        this.createAttribute( "drawfirst", true, 'bool', "drawFirst" );

        // Other properties
        this.defaultTextures = ["rex_sky_front.dds",
                                "rex_sky_back.dds",
                                "rex_sky_left.dds",
                                "rex_sky_right.dds",
                                "rex_sky_top.dds",
                                "rex_sky_bot.dds"];
        this.defaultPath = "default_assets/textures/";
        this.storagePath = this.defaultPath;
        this.texturesLoaded = 0;
        this.texturesNeeded = [];

        this.cubeMaterial = null;
        this.skyBox = null;

    };

    namespace.storeComponent( 10, "EC_Sky", ECSky );

    ECSky.prototype = util.extend( Object.create( namespace.Component.prototype ),
        {

            onAttributeUpdated: function ( attr ) {
                if ( attr['name'] === "texture" ) {
                    var textures = this.defaultTextures, refs = this.textureRefs;

                    this.texturesNeeded =  refs.filter(function(elem, pos) {
                        return refs.indexOf(elem) === pos;
                    });

                    if ( !refs.every( function ( e ) {
                            return textures.indexOf( e ) !== -1;
                        }
                    ) ) {
                        console.warn("EC_Sky: Using different skybox textures than default. " +
                            "Trying to request them from the remote storage.");
                        this.storagePath = "";
                    }else{
                        this.storagePath = this.defaultPath;
                    }
                    console.warn(this.texturesNeeded)
                    this.getTextures();
                }

            },

            onParentAdded: function ( parent ) {
            },

            onTextureAssetLoaded: function ( texture ) {
                console.warn(texture)
                if ( this.texturesLoaded === this.texturesNeeded.length ) {
                    console.log( "ECSky: All textures loaded. Creating Sky..." );
                    this.texturesLoaded = 0;
                    this.createSky(this.createFaceMaterials());
                }

            },

            disableSky: function () {

            },

            createSky: function (faceMaterials) {
                var shader, material, skyBox, geometry, distance = this.distance;
                console.warn(faceMaterials)
                if(!faceMaterials){
                    return;
                }

                material = this.cubeMaterial =  new THREE.MeshFaceMaterial( faceMaterials );

                if ( !this.skyBox ) {
                    geometry = new THREE.CubeGeometry( distance, distance, distance );
                    skyBox = this.skyBox = new THREE.Mesh( geometry, material );

                    skyBox.geometry.faceVertexUvs[0][0] = [new THREE.Vector2( 0, 0 ), new THREE.Vector2( 0, 1 ),
                                                           new THREE.Vector2( 1, 1 ), new THREE.Vector2( 1, 0 )];
                    skyBox.geometry.faceVertexUvs[0][1] = [new THREE.Vector2( 0, 0 ), new THREE.Vector2( 0, 1 ),
                                                           new THREE.Vector2( 1, 1 ), new THREE.Vector2( 1, 0 )];
                    skyBox.geometry.faceVertexUvs[0][2] = [new THREE.Vector2( 1, 0 ), new THREE.Vector2( 0, 0 ),
                                                           new THREE.Vector2( 0, 1 ), new THREE.Vector2( 1, 1 )];
                    skyBox.geometry.faceVertexUvs[0][3] = [new THREE.Vector2( 1, 0 ), new THREE.Vector2( 0, 0 ),
                                                           new THREE.Vector2( 0, 1 ), new THREE.Vector2( 1, 1 )];
                    skyBox.geometry.faceVertexUvs[0][4] = [new THREE.Vector2( 0, 0 ), new THREE.Vector2( 0, 1 ),
                                                           new THREE.Vector2( 1, 1 ), new THREE.Vector2( 1, 0 )];
                    skyBox.geometry.faceVertexUvs[0][5] = [new THREE.Vector2( 0, 0 ), new THREE.Vector2( 0, 1 ),
                                                           new THREE.Vector2( 1, 1 ), new THREE.Vector2( 1, 0 )];
                    skyBox.geometry.uvsNeedUpdate = true;

                    this.skyBox = skyBox;
                    this.sceneManager.addSkyBox( skyBox );
                } else {
                    this.skyBox.material = material;
                    this.skyBox.uvsNeedUpdate = true;
                }

            },

            checkTextureOrder: function ( name, index ) {
                if ( name.indexOf( "front" ) !== -1 ) {
                    return 0;
                } else if ( name.indexOf( "back" ) !== -1 ) {
                    return 1;
                } else if ( name.indexOf( "top" ) !== -1 ) {
                    return 2;
                } else if ( name.indexOf( "bot" ) !== -1 ) {
                    return 3;
                } else if ( name.indexOf( "left" ) !== -1 ) {
                    return 4;
                } else if ( name.indexOf( "right" ) !== -1 ) {
                    return 5;
                } else {
                    if(index === 0){
                        return 0;
                    } else if ( index === 1 ){
                        return 1;
                    } else if ( index === 2 ){
                        return 4;
                    } else if ( index === 3 ) {
                        return 5;
                    } else if ( index === 4) {
                        return 2;
                    } else if ( index === 5) {
                        return 3;
                    } else {
                        return -1;
                    }
                }
            },

            createFaceMaterials: function ( ) {
                var ordered = [],  texture, refs = this.textureRefs, assetManager = this.sceneManager.assetManager,
                    i, order;

                for ( i = refs.length; i--; ) {
                    texture = assetManager.getAsset( refs[i], 'texture', this.storagePath );

                    if ( texture ) {
                        order = this.checkTextureOrder( texture.name, i );

                        if ( order === -1 ) {
                            continue;
                        }

                        ordered[order] = new THREE.MeshBasicMaterial( {map: texture, side: THREE.BackSide, depthWrite: false} );
                    }
                }

                return ordered;
            },

            getTextures: function () {
                var request, texture, i,
                    refs = this.texturesNeeded,
                    assetManager = this.sceneManager.assetManager,
                    self = this;

                if ( !assetManager ) {
                    throw new Error( ["ECSky: Could not get AssetManager object, texture load failed;"] );
                }

                if ( refs ) {

                    var callBack = function ( asset ) {
                        if ( asset ) {
                            self.texturesLoaded += 1;
                            self.onTextureAssetLoaded( asset );
                        }
                    };

                    for ( i = refs.length; i--; ) {
                        request = assetManager.requestAsset( refs[i], 'texture', this.storagePath );
                        if ( request ) {
                            request.add( callBack );
                        } else {
                            texture = assetManager.getAsset( refs[i], 'texture', this.storagePath );
                            if ( texture ) {
                                this.texturesLoaded += 1;
                                this.onTextureAssetLoaded( texture );
                            }
                        }
                    }
                }
            }

        } // Prototype end
    );

}( window['webtundra'] = window['webtundra'] || {} ));
<|endoftext|>


<commit_before>// Saves options to chrome.storage
document.addEventListener("DOMContentLoaded", function() {
    document.addEventListener('DOMContentLoaded', restore_options);
    document.getElementById('token-form').addEventListener('submit', save_options);
});

function save_options(e) {
    e.preventDefault();
    let form = e.currentTarget;

    let trackerApiToken = document.getElementById('tracker-token').value;
    chrome.storage.sync.set({
        trackerApiToken: trackerApiToken
    }, function() {
        flashSuccessMessage(form);
        getCurrentTrackerTabs(reloadProjectTabs);
    });
}

function flashSuccessMessage(form) {
    form.classList.add('success');
    setTimeout(() => {
        form.classList.remove('success');
    }, 1500);
}

function restore_options() {
    chrome.storage.sync.get('trackerApiToken', function(options) {
        document.getElementById('tracker-token').value = options.trackerApiToken || "";
    });
}

function getCurrentTrackerTabs(callback) {
    return chrome.tabs.query({
        url: "*://www.pivotaltracker.com/*"
    }, callback)
}

function reloadProjectTabs(allTrackerTabs) {
    let projectRegex = /:\/\/www.pivotaltracker.com\/n\/projects/;

    allTrackerTabs.forEach(function(tab) {
        if (tab.url.match(projectRegex)) {
            chrome.tabs.discard(tab.id);
        }
    });
}<commit_msg>Close options page after user submits their tracker API token<commit_after>// Saves options to chrome.storage
document.addEventListener("DOMContentLoaded", function() {
    document.addEventListener('DOMContentLoaded', restore_options);
    document.getElementById('token-form').addEventListener('submit', save_options);
});

function save_options(e) {
    e.preventDefault();
    let form = e.currentTarget;

    let trackerApiToken = document.getElementById('tracker-token').value;
    chrome.storage.sync.set({
        trackerApiToken: trackerApiToken
    }, function() {
        flashSuccessMessage(form);
        getCurrentTrackerTabs().then(reloadProjectTabs).then(closeOptionsPage);
    });
}

function flashSuccessMessage(form) {
    form.classList.add('success');
    setTimeout(() => {
        form.classList.remove('success');
    }, 1500);
}

function restore_options() {
    chrome.storage.sync.get('trackerApiToken', function(options) {
        document.getElementById('tracker-token').value = options.trackerApiToken || "";
    });
}

function closeOptionsPage() {
    setTimeout(() => {
        chrome.tabs.getCurrent(function(tab) {
            chrome.tabs.remove(tab.id, function() { });
        });
    }, 1000);

}

function getCurrentTrackerTabs() {
    return new Promise((resolve) => {
        chrome.tabs.query({
            url: "*://www.pivotaltracker.com/*"
        }, resolve)
    });
}

function reloadProjectTabs(allTrackerTabs) {
    let projectRegex = /:\/\/www.pivotaltracker.com\/n\/projects/;

    allTrackerTabs.forEach(function(tab) {
        if (tab.url.match(projectRegex)) {
            chrome.tabs.discard(tab.id);
        }
    });
}<|endoftext|>


<commit_before>/**
 * @providesModule ZeroProj.Redux.Store
 */

/* eslint-disable no-underscore-dangle */

import { applyMiddleware, createStore, compose } from 'redux';
import reducers from '../reducers';

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export default createStore(
  reducers,
  composeEnhancer(applyMiddleware(
    // Redux middleware
  ))
);

/* eslint-enable no-underscore-dangle */
<commit_msg>Configure Redux store to work with redux-devtools-extensions & react-native-debugger<commit_after>/**
 * @providesModule ZeroProj.Redux.Store
 */

/* eslint-disable no-underscore-dangle */

import { applyMiddleware, createStore, compose } from 'redux';
import reducers from '../reducers';

/**
 * Configure to work with `redux-devtools-extensions` & `react-native-debugger`
 * https://github.com/jhen0409/react-native-debugger
 * https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup
 */
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export default createStore(
  reducers,
  composeEnhancer(applyMiddleware(
    // Redux middleware
  ))
);

/* eslint-enable no-underscore-dangle */
<|endoftext|>


<commit_before>core.service("AbstractRepo", function ($q, $rootScope, $timeout, ApiResponseActions, ValidationStore, WsApi) {

    return function AbstractRepo(modelName, model, mapping) {

        var abstractRepo = this;

        var list = [];

        var defer = $q.defer();

        var actionCbs = {};

        angular.forEach(ApiResponseActions, function (action) {
            actionCbs[action] = [];
        });

        var validations = {};

        var pendingChanges;

        $rootScope.$on("$locationChangeSuccess", function () {
            angular.forEach(actionCbs, function (actionCbs) {
                actionCbs.length = 0;
            });
        });

        abstractRepo.mapping = mapping;

        abstractRepo.ValidationResults = {};

        abstractRepo.unshift = function (modelJson) {
            list.unshift(new model(modelJson));
        };

        abstractRepo.contains = function (model) {
            var contains = false;
            for (var i in list) {
                if (list[i].id === model.id) {
                    contains = true;
                }
            }
            return contains;
        };

        abstractRepo.add = function (modelJson) {
            if (!abstractRepo.contains(modelJson)) {
                list.push(new model(modelJson));
            }
        };

        abstractRepo.addAll = function (modelJsons) {
            for (var i in modelJsons) {
                abstractRepo.add(modelJsons[i]);
            }
        };

        abstractRepo.remove = function (modelToRemove) {
            for (var i in list) {
                if (list[i].id === modelToRemove.id) {
                    list.splice(i, 1);
                    break;
                }
            }
        };

        abstractRepo.empty = function () {
            list.length = 0;
        };

        abstractRepo.getEntityName = function () {
            return modelName;
        };

        abstractRepo.getValidations = function () {
            return validations;
        };

        abstractRepo.count = function () {
            return list.length;
        };

        abstractRepo.getAll = function () {
            if (mapping.lazy) {
                fetch();
            }
            return abstractRepo.getContents();
        };

        abstractRepo.getContents = function () {
            return list;
        };

        abstractRepo.save = function (model) {
            abstractRepo.clearValidationResults();
            var promise = $q(function (resolve) {
                if (model.dirty()) {
                    model.updateRequested = true;
                    model._syncShadow();
                    angular.extend(mapping.update, {
                        data: model
                    });
                    WsApi.fetch(mapping.update).then(function (res) {
                        resolve(res);
                    });
                } else {
                    var payload = {};
                    payload[model.constructor.name] = model;
                    resolve({
                        body: angular.toJson({
                            payload: payload,
                            meta: {
                                type: "SUCCESS"
                            }
                        })
                    });
                }
            });
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                } else {
                    model.acceptPendingUpdate();
                }
            });
            return promise;
        };

        abstractRepo.saveAll = function () {
            abstractRepo.clearValidationResults();
            angular.forEach(list, function (model) {
                abstractRepo.save(model);
            });
        };

        abstractRepo.ready = function () {
            return defer.promise;
        };

        abstractRepo.reset = function () {
            defer = $q.defer();
            fetch();
        };

        abstractRepo.findById = function (id) {
            for (var i in list) {
                if (list[i].id == id) {
                    return list[i];
                }
            }
        };

        abstractRepo.delete = function (model) {
            abstractRepo.clearValidationResults();
            model.deleteRequested = true;
            model._syncShadow();
            angular.extend(mapping.remove, {
                data: model
            });
            var promise = WsApi.fetch(mapping.remove);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                } else {
                    model.acceptPendingDelete();
                }
            });
            return promise;
        };

        abstractRepo.deleteById = function (id) {
            abstractRepo.clearValidationResults();
            var promise = abstractRepo.findById(id).delete();
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.create = function (model) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.create, {
                'data': model
            });
            var promise = WsApi.fetch(abstractRepo.mapping.create);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.update = function (model) {
            abstractRepo.clearValidationResults();
            var promise = abstractRepo.save(model);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.type === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.listen = function (cbOrAction, cb) {
            if (typeof cbOrAction === "function") {
                actionCbs[ApiResponseActions.ANY].push(cbOrAction);
            } else {
                actionCbs[cbOrAction].push(cb);
            }
        };

        abstractRepo.acceptPendingChanges = function () {
            list.length = 0;
            angular.forEach(pendingChanges, function (modelObj) {
                list.push(new model(modelObj));
            });
            delete pendingChanges;
        };

        abstractRepo.changesPending = function () {
            return pendingChanges !== undefined;
        };

        // additiona core level repo methods and variables

        // these should be added through decoration
        abstractRepo.sort = function (facet) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.sort, {
                'method': 'sort/' + facet
            });
            var promise = WsApi.fetch(abstractRepo.mapping.sort);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.reorder = function (src, dest) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.reorder, {
                'method': 'reorder/' + src + '/' + dest
            });
            var promise = WsApi.fetch(abstractRepo.mapping.reorder);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.getValidationResults = function () {
            return abstractRepo.ValidationResults;
        };

        abstractRepo.clearValidationResults = function () {
            delete abstractRepo.ValidationResults.messages;
        };

        var build = function (data) {
            return $q(function (resolve) {
                list.length = 0;
                angular.forEach(data, function (modelJson) {
                    abstractRepo.add(modelJson);
                });
                resolve();
            });
        };

        var unwrap = function (res) {
            var repoObj = {};
            var payload = angular.fromJson(res.body).payload;
            var keys = Object.keys(payload);
            angular.forEach(keys, function (key) {
                angular.extend(repoObj, payload[key]);
            });
            return repoObj;
        };

        var fetch = function () {
            if (abstractRepo.mapping.all !== undefined) {
                WsApi.fetch(abstractRepo.mapping.all).then(function (res) {
                    build(unwrap(res)).then(function () {
                        defer.resolve(res);
                    });
                });
            }
        };

        var acceptPendingModelUpdate = function (model, pending) {
            var combinationOperation = model.getCombinationOperation();
            if (combinationOperation === 'extend') {
                angular.forEach(pending, function (datum) {
                    angular[combinationOperation](model, pending);
                });
            }
            angular[combinationOperation](model, pending);
            model.updatePending = false;
            model.updateRequested = false;
            model.acceptPendingUpdate = function () {
                console.warn("No update pending!");
            };
            model._syncShadow();
        };

        var acceptPendingModelDelete = function (model, i) {
            list.splice(i, 1);
            model.deletePending = false;
            model.deleteRequested = false;
            model.acceptPendingDelete = function () {
                console.warn("No delete pending!");
            };
        };

        var runActionCBs = function (action, resObj) {
            angular.forEach(actionCbs[action], function (cb) {
                cb(resObj);
            });
        };

        if (abstractRepo.mapping.validations && modelName !== undefined && modelName !== null && modelName.length > 0) {
            validations = ValidationStore.getValidations(modelName);
        }

        // TODO: remove when all repos upgraded!!!
        if (abstractRepo.mapping.listen) {
            WsApi.listen(abstractRepo.mapping.listen).then(null, null, function (res) {
                build(unwrap(res)).then(function () {
                    runActionCBs(ApiResponseActions.ANY, angular.fromJson(res.body));
                });
            });
        }

        if (abstractRepo.mapping.channel) {

            WsApi.listen(abstractRepo.mapping.channel).then(null, null, function (res) {

                var resObj = angular.fromJson(res.body);
                var modelObj = unwrap(res);

                switch (resObj.meta.action) {
                case ApiResponseActions.CREATE:
                    abstractRepo.add(modelObj);
                    break;
                case ApiResponseActions.READ:
                case ApiResponseActions.UPDATE:
                    var existingModelToUpdate = abstractRepo.findById(modelObj.id);
                    if (existingModelToUpdate.updateRequested || !existingModelToUpdate.dirty()) {
                        acceptPendingModelUpdate(existingModelToUpdate, modelObj);
                    } else {
                        existingModelToUpdate.updatePending = true;
                        existingModelToUpdate.acceptPendingUpdate = function () {
                            acceptPendingModelUpdate(existingModelToUpdate, modelObj);
                        };
                        console.warn("Update attempted on dirty model", existingModelToUpdate);
                    }
                    break;
                case ApiResponseActions.DELETE:
                    for (var i in list) {
                        var existingModelToDelete = list[i];
                        if (existingModelToDelete.id === modelObj.id) {
                            if (existingModelToDelete.deleteRequested || !existingModelToDelete.dirty()) {
                                acceptPendingModelDelete(existingModelToDelete, i);
                            } else {
                                existingModelToDelete.deletePending = true;
                                /*jshint loopfunc: true */
                                existingModelToDelete.acceptPendingDelete = function () {
                                    acceptPendingModelDelete(existingModelToDelete, i);
                                };
                                console.warn("Delete attempted on dirty model", existingModelToDelete);
                            }
                            break;
                        }
                    }
                    break;
                case ApiResponseActions.REMOVE:
                case ApiResponseActions.REORDER:
                case ApiResponseActions.SORT:
                case ApiResponseActions.BROADCAST:
                    var repoDirty = false;
                    for (var j in list) {
                        repoDirty = list[j].dirty();
                        if (repoDirty) break;
                    }
                    pendingChanges = unwrap(res);
                    if (!repoDirty) {
                        abstractRepo.acceptPendingChanges();
                    } else {
                        console.warn(resObj.meta.action + " attempted on dirty repo");
                    }
                    break;
                }
                runActionCBs(resObj.meta.action, resObj);
                runActionCBs(ApiResponseActions.ANY, resObj);
            });
        }

        if (!mapping.lazy) {
            fetch();
        }

        return abstractRepo;
    };

});
<commit_msg>some repo methods to assist in update and delete managed via broadcast<commit_after>core.service("AbstractRepo", function ($q, $rootScope, $timeout, ApiResponseActions, ValidationStore, WsApi) {

    return function AbstractRepo(modelName, model, mapping) {

        var abstractRepo = this;

        var list = [];

        var defer = $q.defer();

        var actionCbs = {};

        angular.forEach(ApiResponseActions, function (action) {
            actionCbs[action] = [];
        });

        var validations = {};

        var pendingChanges;

        $rootScope.$on("$locationChangeSuccess", function () {
            angular.forEach(actionCbs, function (actionCbs) {
                actionCbs.length = 0;
            });
        });

        abstractRepo.mapping = mapping;

        abstractRepo.ValidationResults = {};

        abstractRepo.unshift = function (modelJson) {
            list.unshift(new model(modelJson));
        };

        abstractRepo.contains = function (model) {
            var contains = false;
            for (var i in list) {
                if (list[i].id === model.id) {
                    contains = true;
                }
            }
            return contains;
        };

        abstractRepo.add = function (modelJson) {
            if (!abstractRepo.contains(modelJson)) {
                list.push(new model(modelJson));
            }
        };

        abstractRepo.addAll = function (modelJsons) {
            for (var i in modelJsons) {
                abstractRepo.add(modelJsons[i]);
            }
        };

        abstractRepo.remove = function (modelToRemove) {
            for (var i in list) {
                if (list[i].id === modelToRemove.id) {
                    list.splice(i, 1);
                    break;
                }
            }
        };

        abstractRepo.empty = function () {
            list.length = 0;
        };

        abstractRepo.getEntityName = function () {
            return modelName;
        };

        abstractRepo.getValidations = function () {
            return validations;
        };

        abstractRepo.count = function () {
            return list.length;
        };

        abstractRepo.getAll = function () {
            if (mapping.lazy) {
                fetch();
            }
            return abstractRepo.getContents();
        };

        abstractRepo.getContents = function () {
            return list;
        };

        abstractRepo.setToUpdate = function(id) {
            var modelToUpdate = abstractRepo.findById(id);
            setToUpdate(modelToUpdate);
        };

        abstractRepo.save = function (model) {
            abstractRepo.clearValidationResults();
            var promise = $q(function (resolve) {
                if (model.dirty()) {
                    setToUpdate(model);
                    angular.extend(mapping.update, {
                        data: model
                    });
                    WsApi.fetch(mapping.update).then(function (res) {
                        resolve(res);
                    });
                } else {
                    var payload = {};
                    payload[model.constructor.name] = model;
                    resolve({
                        body: angular.toJson({
                            payload: payload,
                            meta: {
                                type: "SUCCESS"
                            }
                        })
                    });
                }
            });
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                } else {
                    model.acceptPendingUpdate();
                }
            });
            return promise;
        };

        abstractRepo.saveAll = function () {
            abstractRepo.clearValidationResults();
            angular.forEach(list, function (model) {
                abstractRepo.save(model);
            });
        };

        abstractRepo.ready = function () {
            return defer.promise;
        };

        abstractRepo.reset = function () {
            defer = $q.defer();
            fetch();
        };

        abstractRepo.findById = function (id) {
            for (var i in list) {
                if (list[i].id == id) {
                    return list[i];
                }
            }
        };

        abstractRepo.setToDelete = function(id) {
            var modelToDelete = abstractRepo.findById(id);
            setToDelete(modelToDelete);
        };

        abstractRepo.delete = function (model) {
            abstractRepo.clearValidationResults();
            setToDelete(model);
            angular.extend(mapping.remove, {
                data: model
            });
            var promise = WsApi.fetch(mapping.remove);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                } else {
                    model.acceptPendingDelete();
                }
            });
            return promise;
        };

        abstractRepo.deleteById = function (id) {
            abstractRepo.clearValidationResults();
            var promise = abstractRepo.findById(id).delete();
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.create = function (model) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.create, {
                'data': model
            });
            var promise = WsApi.fetch(abstractRepo.mapping.create);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.update = function (model) {
            abstractRepo.clearValidationResults();
            var promise = abstractRepo.save(model);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.type === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.listen = function (cbOrAction, cb) {
            if (typeof cbOrAction === "function") {
                actionCbs[ApiResponseActions.ANY].push(cbOrAction);
            } else {
                actionCbs[cbOrAction].push(cb);
            }
        };

        abstractRepo.acceptPendingChanges = function () {
            list.length = 0;
            angular.forEach(pendingChanges, function (modelObj) {
                list.push(new model(modelObj));
            });
            delete pendingChanges;
        };

        abstractRepo.changesPending = function () {
            return pendingChanges !== undefined;
        };

        // additiona core level repo methods and variables

        // these should be added through decoration
        abstractRepo.sort = function (facet) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.sort, {
                'method': 'sort/' + facet
            });
            var promise = WsApi.fetch(abstractRepo.mapping.sort);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.reorder = function (src, dest) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.reorder, {
                'method': 'reorder/' + src + '/' + dest
            });
            var promise = WsApi.fetch(abstractRepo.mapping.reorder);
            promise.then(function (res) {
                var message = angular.fromJson(res.body);
                if (message.meta.status === "INVALID") {
                    angular.extend(abstractRepo, message.payload);
                }
            });
            return promise;
        };

        abstractRepo.getValidationResults = function () {
            return abstractRepo.ValidationResults;
        };

        abstractRepo.clearValidationResults = function () {
            delete abstractRepo.ValidationResults.messages;
        };

        var build = function (data) {
            return $q(function (resolve) {
                list.length = 0;
                angular.forEach(data, function (modelJson) {
                    abstractRepo.add(modelJson);
                });
                resolve();
            });
        };

        var unwrap = function (res) {
            var repoObj = {};
            var payload = angular.fromJson(res.body).payload;
            var keys = Object.keys(payload);
            angular.forEach(keys, function (key) {
                angular.extend(repoObj, payload[key]);
            });
            return repoObj;
        };

        var fetch = function () {
            if (abstractRepo.mapping.all !== undefined) {
                WsApi.fetch(abstractRepo.mapping.all).then(function (res) {
                    build(unwrap(res)).then(function () {
                        defer.resolve(res);
                    });
                });
            }
        };

        var setToUpdate = function(model) {
            console.log('update', model);
            model.updateRequested = true;
            model._syncShadow();
        };

        var setToDelete = function(model) {
            console.log('delete', model);
            model.updateDelete = true;
            model._syncShadow();
        };

        var acceptPendingModelUpdate = function (model, pending) {
            var combinationOperation = model.getCombinationOperation();
            if (combinationOperation === 'extend') {
                angular.forEach(pending, function (datum) {
                    angular[combinationOperation](model, pending);
                });
            }
            angular[combinationOperation](model, pending);
            model.updatePending = false;
            model.updateRequested = false;
            model.acceptPendingUpdate = function () {
                console.warn("No update pending!");
            };
            model._syncShadow();
        };

        var acceptPendingModelDelete = function (model, i) {
            list.splice(i, 1);
            model.deletePending = false;
            model.deleteRequested = false;
            model.acceptPendingDelete = function () {
                console.warn("No delete pending!");
            };
        };

        var runActionCBs = function (action, resObj) {
            angular.forEach(actionCbs[action], function (cb) {
                cb(resObj);
            });
        };

        if (abstractRepo.mapping.validations && modelName !== undefined && modelName !== null && modelName.length > 0) {
            validations = ValidationStore.getValidations(modelName);
        }

        // TODO: remove when all repos upgraded!!!
        if (abstractRepo.mapping.listen) {
            WsApi.listen(abstractRepo.mapping.listen).then(null, null, function (res) {
                build(unwrap(res)).then(function () {
                    runActionCBs(ApiResponseActions.ANY, angular.fromJson(res.body));
                });
            });
        }

        if (abstractRepo.mapping.channel) {

            WsApi.listen(abstractRepo.mapping.channel).then(null, null, function (res) {

                var resObj = angular.fromJson(res.body);
                var modelObj = unwrap(res);

                switch (resObj.meta.action) {
                case ApiResponseActions.CREATE:
                    abstractRepo.add(modelObj);
                    break;
                case ApiResponseActions.READ:
                case ApiResponseActions.UPDATE:
                    var existingModelToUpdate = abstractRepo.findById(modelObj.id);
                    if (existingModelToUpdate.updateRequested || !existingModelToUpdate.dirty()) {
                        acceptPendingModelUpdate(existingModelToUpdate, modelObj);
                    } else {
                        existingModelToUpdate.updatePending = true;
                        existingModelToUpdate.acceptPendingUpdate = function () {
                            acceptPendingModelUpdate(existingModelToUpdate, modelObj);
                        };
                        console.warn(resObj.meta.action + " attempted on dirty model", existingModelToUpdate);
                    }
                    break;
                case ApiResponseActions.DELETE:
                    for (var i in list) {
                        var existingModelToDelete = list[i];
                        if (existingModelToDelete.id === modelObj.id) {
                            if (existingModelToDelete.deleteRequested || !existingModelToDelete.dirty()) {
                                acceptPendingModelDelete(existingModelToDelete, i);
                            } else {
                                existingModelToDelete.deletePending = true;
                                /*jshint loopfunc: true */
                                existingModelToDelete.acceptPendingDelete = function () {
                                    acceptPendingModelDelete(existingModelToDelete, i);
                                };
                                console.warn(resObj.meta.action + " attempted on dirty model", existingModelToDelete);
                            }
                            break;
                        }
                    }
                    break;
                case ApiResponseActions.REMOVE:
                case ApiResponseActions.REORDER:
                case ApiResponseActions.SORT:
                case ApiResponseActions.BROADCAST:
                    var repoDirty = false;
                    for (var j in list) {
                        repoDirty = list[j].dirty();
                        if (repoDirty) break;
                    }
                    pendingChanges = modelObj;
                    if (!repoDirty) {
                        abstractRepo.acceptPendingChanges();
                    } else {
                        console.warn(resObj.meta.action + " attempted on dirty repo");
                    }
                    break;
                }
                runActionCBs(resObj.meta.action, resObj);
                runActionCBs(ApiResponseActions.ANY, resObj);
            });
        }

        if (!mapping.lazy) {
            fetch();
        }

        return abstractRepo;
    };

});
<|endoftext|>


<commit_before>//
// A widget to make app fullscreen
//
var FullScreenWidget = function() {

    //var fullscreenContainer = jQuery('<div>', {class:'fullscreen-container'} );
    var fullscreenContainer = jQuery('#fullscreen-widget');
    var fullscreenButton  = jQuery('<div>', {id:'fullscreen-button'} );
    fullscreenButton.appendTo(fullscreenContainer);
    //fullscreenContainer.appendTo(menuAndContentHolder);
    var fullscreen = false;
    fullscreenButton.click(function(e) {
        if (screenfull.enabled) {
            screenfull.toggle();
        }
    });
    function requestFullScreen(element) {
        // Supports most browsers and their versions.
        var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;

        if (requestMethod) { // Native full screen.
            requestMethod.call(element);
        } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }

        fullscreen = !fullscreen;
        if(fullscreen){
            $('#fullscreen-button').addClass("exit");
        }
        else{
            $('#fullscreen-button').removeClass("exit");
        }
    }

    /*!
    * screenfull
    * v3.3.2 - 2017-10-27
    * (c) Sindre Sorhus; MIT License
    */

    !function(){"use strict";var a="undefined"!=typeof window&&void 0!==window.document?window.document:{},b="undefined"!=typeof module&&module.exports,c="undefined"!=typeof Element&&"ALLOW_KEYBOARD_INPUT"in Element,d=function(){for(var b,c=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],d=0,e=c.length,f={};d<e;d++)if((b=c[d])&&b[1]in a){for(d=0;d<b.length;d++)f[c[0][d]]=b[d];return f}return!1}(),e={change:d.fullscreenchange,error:d.fullscreenerror},f={request:function(b){var e=d.requestFullscreen;b=b||a.documentElement,/ Version\/5\.1(?:\.\d+)? Safari\//.test(navigator.userAgent)?b[e]():b[e](c&&Element.ALLOW_KEYBOARD_INPUT)},exit:function(){a[d.exitFullscreen]()},toggle:function(a){this.isFullscreen?this.exit():this.request(a)},onchange:function(a){this.on("change",a)},onerror:function(a){this.on("error",a)},on:function(b,c){var d=e[b];d&&a.addEventListener(d,c,!1)},off:function(b,c){var d=e[b];d&&a.removeEventListener(d,c,!1)},raw:d};if(!d)return void(b?module.exports=!1:window.screenfull=!1);Object.defineProperties(f,{isFullscreen:{get:function(){return Boolean(a[d.fullscreenElement])}},element:{enumerable:!0,get:function(){return a[d.fullscreenElement]}},enabled:{enumerable:!0,get:function(){return Boolean(a[d.fullscreenEnabled])}}}),b?module.exports=f:window.screenfull=f}();

    if (screenfull.enabled) {
        screenfull.on('change', function () {
            if (screenfull.isFullscreen) {
                $('#fullscreen-button').addClass("exit");
            } else {
                $('#fullscreen-button').removeClass("exit");
            }
        });
    }

}
<commit_msg>clean up comments and obsolete code<commit_after>//
// A widget to make app fullscreen
//
var FullScreenWidget = function() {

    var fullscreenContainer = jQuery('#fullscreen-widget');
    var fullscreenButton  = jQuery('<div>', {id:'fullscreen-button'} );
    fullscreenButton.appendTo(fullscreenContainer);
    var fullscreen = false;
    fullscreenButton.click(function(e) {
        if (screenfull.enabled) {
            screenfull.toggle();
        }
    });
    //
    // function to enter or exit fullscreen
    //
    function requestFullScreen(element) {
        // Supports most browsers and their versions.
        var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;

        if (requestMethod) { // Native full screen.
            requestMethod.call(element);
        } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }

        fullscreen = !fullscreen;
        if(fullscreen){
            $('#fullscreen-button').addClass("exit");
        }
        else{
            $('#fullscreen-button').removeClass("exit");
        }
    }

    /*!
    * screenfull
    * v3.3.2 - 2017-10-27
    * (c) Sindre Sorhus; MIT License
    */

    !function(){"use strict";var a="undefined"!=typeof window&&void 0!==window.document?window.document:{},b="undefined"!=typeof module&&module.exports,c="undefined"!=typeof Element&&"ALLOW_KEYBOARD_INPUT"in Element,d=function(){for(var b,c=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],d=0,e=c.length,f={};d<e;d++)if((b=c[d])&&b[1]in a){for(d=0;d<b.length;d++)f[c[0][d]]=b[d];return f}return!1}(),e={change:d.fullscreenchange,error:d.fullscreenerror},f={request:function(b){var e=d.requestFullscreen;b=b||a.documentElement,/ Version\/5\.1(?:\.\d+)? Safari\//.test(navigator.userAgent)?b[e]():b[e](c&&Element.ALLOW_KEYBOARD_INPUT)},exit:function(){a[d.exitFullscreen]()},toggle:function(a){this.isFullscreen?this.exit():this.request(a)},onchange:function(a){this.on("change",a)},onerror:function(a){this.on("error",a)},on:function(b,c){var d=e[b];d&&a.addEventListener(d,c,!1)},off:function(b,c){var d=e[b];d&&a.removeEventListener(d,c,!1)},raw:d};if(!d)return void(b?module.exports=!1:window.screenfull=!1);Object.defineProperties(f,{isFullscreen:{get:function(){return Boolean(a[d.fullscreenElement])}},element:{enumerable:!0,get:function(){return a[d.fullscreenElement]}},enabled:{enumerable:!0,get:function(){return Boolean(a[d.fullscreenEnabled])}}}),b?module.exports=f:window.screenfull=f}();

    if (screenfull.enabled) {
        screenfull.on('change', function () {
            if (screenfull.isFullscreen) {
                $('#fullscreen-button').addClass("exit");
            } else {
                $('#fullscreen-button').removeClass("exit");
            }
        });
    }

}
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import Cropper from 'react-cropper';

export default class CropperWrapper extends React.Component {
  props: {
    updatePhotoEdit:  (b: Blob) => void,
    photo:            Object,
  };

  cropperHelper = () => {
    const { updatePhotoEdit } = this.props;
    this.refs.cropper.getCroppedCanvas().toBlob(blob => updatePhotoEdit(blob));
  };

  render () {
    const { photo } = this.props;
    return <Cropper
      ref='cropper'
      className="photo-active-item cropper"
      src={photo.preview}
      aspectRatio={ 1 / 1 }
      guides={false}
      cropend={this.cropperHelper}
      ready={this.cropperHelper}
    />;
  }
}
<commit_msg>Fixed IE11 support for image upload (#1402)<commit_after>// @flow
import React from 'react';
import Cropper from 'react-cropper';

export default class CropperWrapper extends React.Component {
  props: {
    updatePhotoEdit:  (b: Blob) => void,
    photo:            Object,
  };

  cropperHelper = () => {
    const { updatePhotoEdit } = this.props;
    let canvas = this.refs.cropper.getCroppedCanvas();
    if (canvas.toBlob !== undefined) {
      canvas.toBlob(blob => updatePhotoEdit(blob));
    } else if (canvas.msToBlob !== undefined) {
      let blob = canvas.msToBlob();
      updatePhotoEdit(blob);
    }
  };

  render () {
    const { photo } = this.props;
    return <Cropper
      ref='cropper'
      className="photo-active-item cropper"
      src={photo.preview}
      aspectRatio={ 1 / 1 }
      guides={false}
      cropend={this.cropperHelper}
      ready={this.cropperHelper}
    />;
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('service-worker.js', {
      scope: './'
    }).then(function(registration) {
      // Check to see if there's an updated version of service-worker.js with new files to cache:
      // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method
      // Note: registration.update() is not yet widely implemented.
      if (typeof registration.update == 'function') {
        registration.update();
      }

      registration.onupdatefound = function() {
        // The updatefound event implies that registration.installing is set; see
        // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
        var installingWorker = registration.installing;
        installingWorker.onstatechange = function() {
          // TODO: How do we handle i18n of these strings?
          switch (installingWorker.state) {
            case 'installed':
              if (navigator.serviceWorker.controller) {
                // Define a handler that will be used for the next io-toast tap, at which point it
                // be automatically removed.
                var tapHandler = function() {
                  window.location.reload();
                };

                IOWA.Elements.Toast.showMessage('Tap here or refresh the page for the latest content.',
                  tapHandler);
              } else {
                IOWA.Elements.Toast.showMessage('Caching complete. This site is ready to work offline!');
              }
              break;

            case 'redundant':
              throw 'The installing service worker became redundant.';
          }
        };
      };
    }).catch(function(e) {
      IOWA.Analytics.trackError('navigator.serviceWorker.register() error', e);
      console.error('Service worker registration failed:', e);
    });
  }

  function afterImports() {
    IOWA.Elements.init();
    IOWA.Router.init();
  }

  window.addEventListener('core-media-change', function(e) {
    // Disable swipping on tablet/desktop.
    if (e.target.id === 'mq-phone') {
      var isPhoneSize = e.detail.matches;
      IOWA.Elements.Drawer.querySelector('[drawer]').hidden = !isPhoneSize;
      IOWA.Elements.Drawer.disableSwipe = !isPhoneSize;
    }
  });

  window.addEventListener('keydown', function(e) {
    // ESC closes any overlays.
    if (e.keyCode === 27) {
      var template = IOWA.Elements.Template;
      if (template.photoGalleryActive) {
        template.togglePhotoGallery();
      }
      if (IOWA.Elements.Template.fullscreenVideoActive) {
        template.closeVideoCard && template.closeVideoCard();
        template.closeVideoSection && template.closeVideoSection();
      }
    }
  });

  window.addEventListener('resize', function() {
    IOWA.Util.resizeRipple(IOWA.Elements.Ripple);
    IOWA.Elements.Drawer.closeDrawer();
  });

  if (IOWA.Util.supportsHTMLImports) {
    afterImports();
  } else {
    document.addEventListener('polymer-ready', afterImports);
  }
})();
<commit_msg>Fix build<commit_after>/**
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('service-worker.js', {
      scope: './'
    }).then(function(registration) {
      // Check to see if there's an updated version of service-worker.js with new files to cache:
      // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method
      // Note: registration.update() is not yet widely implemented.
      if (typeof registration.update == 'function') {
        registration.update();
      }

      registration.onupdatefound = function() {
        // The updatefound event implies that registration.installing is set; see
        // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
        var installingWorker = registration.installing;
        installingWorker.onstatechange = function() {
          // TODO: How do we handle i18n of these strings?
          switch (installingWorker.state) {
            case 'installed':
              if (navigator.serviceWorker.controller) {
                // Define a handler that will be used for the next io-toast tap, at which point it
                // be automatically removed.
                var tapHandler = function() {
                  window.location.reload();
                };

                IOWA.Elements.Toast.showMessage('Tap here or refresh the page for the latest content.',
                  tapHandler);
              } else {
                IOWA.Elements.Toast.showMessage('Caching complete. This site is ready to work offline!');
              }
              break;

            case 'redundant':
              throw 'The installing service worker became redundant.';
          }
        };
      };
    }).catch(function(e) {
      IOWA.Analytics.trackError('navigator.serviceWorker.register() error', e);
      console.error('Service worker registration failed:', e);
    });
  }

  function afterImports() {
    IOWA.Elements.init();
    IOWA.Router.init();
  }

  window.addEventListener('core-media-change', function(e) {
    // Disable swipping on tablet/desktop.
    if (e.target.id === 'mq-phone') {
      var isPhoneSize = e.detail.matches;
      IOWA.Elements.Drawer.querySelector('[drawer]').hidden = !isPhoneSize;
      IOWA.Elements.Drawer.disableSwipe = !isPhoneSize;
    }
  });

  window.addEventListener('keydown', function(e) {
    // ESC closes any overlays.
    if (e.keyCode === 27) {
      var template = IOWA.Elements.Template;
      if (template.photoGalleryActive) {
        template.togglePhotoGallery();
      }
      if (IOWA.Elements.Template.fullscreenVideoActive) {
        if (template.closeVideoCard) {
          template.closeVideoCard();
        }
        if (template.closeVideoSection) {
          template.closeVideoSection();
        }
      }
    }
  });

  window.addEventListener('resize', function() {
    IOWA.Util.resizeRipple(IOWA.Elements.Ripple);
    IOWA.Elements.Drawer.closeDrawer();
  });

  if (IOWA.Util.supportsHTMLImports) {
    afterImports();
  } else {
    document.addEventListener('polymer-ready', afterImports);
  }
})();
<|endoftext|>


<commit_before>var URLS = {
    'heartbeat': '/api/heartbeat/',
    'species': '/api/species/',
    'magnifications': '/api/magnifications/',
    'development_stages': '/api/development-stages/',
    'probes': '/api/probes/',
    'images': '/api/images/',
    'classify': '/api/classify/',
    'subregions': '/api/subregions/',
    'image_sets': '/api/image-sets/',
    'anatomy_probe_map': '/api/anatomy-probe-map/',
    'train_model': '/api/train-model/'
};

var service = angular.module('IHCApp');

service.factory(
    'Heartbeat',
    function ($resource) {
        return $resource(
            URLS.heartbeat,
            {},
            {}
        );
    }
).factory(
    'Species',
    function ($resource) {
        return $resource(
            URLS.species,
            {},
            {}
        );
    }
).factory(
    'Magnification',
    function ($resource) {
        return $resource(
            URLS.magnifications,
            {},
            {}
        );
    }
).factory(
    'DevelopmentStage',
    function ($resource) {
        return $resource(
            URLS.development_stages,
            {},
            {}
        );
    }
).factory(
    'ImageSet',
    function ($resource) {
        return $resource(
            URLS.image_sets + ':image_set_id',
            {},
            {}
        );
    }
).factory(
    'Probe',
    function ($resource) {
        return $resource(
            URLS.probes,
            {},
            {}
        );
    }
).factory(
    'AnatomyProbeMap',
    function ($resource) {
        return $resource(
            URLS.anatomy_probe_map,
            {},
            {}
        );
    }
).factory('Classify',
    function($resource) {
        return $resource(
            URLS.classify,
            {},
            {}
        );
    }
).factory(
    'Subregion',
    function($resource) {
        return $resource(
            URLS.subregions + ':id',
            {},
            {
                save: {
                    method: 'POST',
                    isArray: true
                }
            }
        );
    }
).factory(
    'Image',
    function ($resource) {
        return  $resource(
            URLS.images + ':id',
            {},
            {}
        );
    }
).factory(
    'TrainModel',
    function ($resource) {
        return  $resource(
            URLS.train_model + ':id',
            {},
            {}
        );
    }
);
<commit_msg>add client side support for ProbeProteinMap API<commit_after>var URLS = {
    'heartbeat': '/api/heartbeat/',
    'species': '/api/species/',
    'magnifications': '/api/magnifications/',
    'development_stages': '/api/development-stages/',
    'probes': '/api/probes/',
    'images': '/api/images/',
    'classify': '/api/classify/',
    'subregions': '/api/subregions/',
    'image_sets': '/api/image-sets/',
    'probe_protein_map': '/api/probe-protein-map/',
    'train_model': '/api/train-model/'
};

var service = angular.module('IHCApp');

service.factory(
    'Heartbeat',
    function ($resource) {
        return $resource(
            URLS.heartbeat,
            {},
            {}
        );
    }
).factory(
    'Species',
    function ($resource) {
        return $resource(
            URLS.species,
            {},
            {}
        );
    }
).factory(
    'Magnification',
    function ($resource) {
        return $resource(
            URLS.magnifications,
            {},
            {}
        );
    }
).factory(
    'DevelopmentStage',
    function ($resource) {
        return $resource(
            URLS.development_stages,
            {},
            {}
        );
    }
).factory(
    'ImageSet',
    function ($resource) {
        return $resource(
            URLS.image_sets + ':image_set_id',
            {},
            {}
        );
    }
).factory(
    'Probe',
    function ($resource) {
        return $resource(
            URLS.probes,
            {},
            {}
        );
    }
).factory(
    'ProbeProteinMap',
    function ($resource) {
        return $resource(
            URLS.probe_protein_map,
            {},
            {}
        );
    }
).factory('Classify',
    function($resource) {
        return $resource(
            URLS.classify,
            {},
            {}
        );
    }
).factory(
    'Subregion',
    function($resource) {
        return $resource(
            URLS.subregions + ':id',
            {},
            {
                save: {
                    method: 'POST',
                    isArray: true
                }
            }
        );
    }
).factory(
    'Image',
    function ($resource) {
        return  $resource(
            URLS.images + ':id',
            {},
            {}
        );
    }
).factory(
    'TrainModel',
    function ($resource) {
        return  $resource(
            URLS.train_model + ':id',
            {},
            {}
        );
    }
);
<|endoftext|>


<commit_before>import React from 'react';
import {Contact} from '@travi/matt.travi.org-components';
import SiteLayout from '../components/layout';

export default function () {
  return (
    <SiteLayout>
      <Contact />
    </SiteLayout>
  );
}
<commit_msg>fix(contact): named the form<commit_after>import React from 'react';
import {Contact} from '@travi/matt.travi.org-components';
import SiteLayout from '../components/layout';

export default function () {
  return (
    <SiteLayout>
      <Contact name="contact" />
    </SiteLayout>
  );
}
<|endoftext|>