<commit_before>/**
 * CG Space Invaders
 * CG45179 16'17
 *
 * @author: Rui Ventura ( ist181045 )
 * @author: Diogo Freitas ( ist181586 )
 * @author: Sara Azinhal ( ist181700 )
 */

import './lib/threejs/polyfills.js';

import { WebGLRenderer } from './lib/threejs/renderers/WebGLRenderer';
import { Scene } from './lib/threejs/scenes/Scene';

import { OrthographicCamera } from './lib/threejs/cameras/OrthographicCamera';
import { PerspectiveCamera } from './lib/threejs/cameras/PerspectiveCamera';

import { DirectionalLight } from './lib/threejs/lights/DirectionalLight';
import { PointLight } from './lib/threejs/lights/PointLight';

import { Clock } from './lib/threejs/core/Clock';

import { Mesh } from './lib/threejs/objects/Mesh';
import { MeshBasicMaterial } from './lib/threejs/materials/MeshBasicMaterial';
import { PlaneGeometry } from './lib/threejs/geometries/PlaneGeometry';
import { TextureLoader } from './lib/threejs/loaders/TextureLoader';

import { WIDTH, HEIGHT } from './Constants';
import { WINDOW_PIXEL_RATIO, WINDOW_WIDTH, WINDOW_HEIGHT } from './Constants';

import GameHUD from './scenes/GameHUD';

import Field from './objects/Field';
import EnemyShip from './entities/EnemyShip';
import PlayerShip from './entities/PlayerShip';

import * as Keyboard from './Keyboard';

class Game {

	constructor () {

		this.renderer = (function () {

			let renderer = new WebGLRenderer({ antialias: true });

			renderer.setPixelRatio( WINDOW_PIXEL_RATIO );
			renderer.setSize( WINDOW_WIDTH(), WINDOW_HEIGHT() );
			renderer.autoClear = false;

			return renderer;

		})();
		this.scene = new Scene();

		this.gameClock = new Clock( false );

		this.field = new Field( 0, 0, 0, WIDTH - 10, HEIGHT - 10 );

		this.cameras = (function ( self ) {

			let cameras = new Array();

			/* Ortho camera (bird's eye) */
			cameras.push( function () {

				let camera = new OrthographicCamera(
					~WIDTH >> 1, WIDTH >> 1, HEIGHT >> 1, ~HEIGHT >> 1, 1, 2000
				);

				camera.position.set( 0, 100, 0 );
				camera.lookAt( self.scene.position );

				camera.updateProjectionMatrix();

				return camera;

			}());

			/* Back perspective camera */
			cameras.push( function () {

				let camera = new PerspectiveCamera(
					75, WINDOW_WIDTH() / WINDOW_HEIGHT(), 1, 1000
				);

				camera.position.set( 0, 250, ( self.field.height >> 1 ) + 150 );
				camera.lookAt( self.scene.position );

				camera.updateProjectionMatrix();

				return camera;

			}());

			return cameras;

		})( this );
		this.camera = this.cameras[0];

		this.gameObjects = new Array();

		this.playerShip = new PlayerShip( 0, 0, ( this.field.height >> 1 ) - 50,
			new PerspectiveCamera( 75, WINDOW_WIDTH() / WINDOW_HEIGHT(), 1, 1000 ) );

		this.HUD = new GameHUD( this.renderer, this.playerShip.MAX_LIVES );

		this.sun = (function ( self ) {

			let sun = new DirectionalLight( 0xffffff, 2 );

			sun.position.set( ~self.field.width >> 2, 100, self.field.height >> 2 );
			sun.target  = self.scene;

			return sun;

		})( this );
		this.stars = (function ( self, n ) {

			let stars = new Array();

			for ( let i = 0; i < n; ++i ) {

				stars.push( new PointLight( 0xffffff, 0.4 ) );

			}

			return stars;

		}( this, 6 ));

		this.lightsOn = false;

		this.gameOver = false;

		document.body.appendChild( this.renderer.domElement );

		window.addEventListener( 'resize',  this.resize.bind( this ) );
		window.addEventListener( 'keydown', this.keyDown.bind( this ) );
		window.addEventListener( 'keyup',   this.keyUp.bind( this ) );

		this.setup();

		/* HACK: Force a first resize */
		this.resize();

		this.update();

	}

	setup () {

		/* Clear the scene + reset gameObjects array */
		this.scene.children.length = 0;
		this.gameObjects.length = 0;

		/* Build the scene */
		this.scene.add( function ( self ) {

			let bgMesh = new Mesh(
				new PlaneGeometry( 6 * WIDTH, 6 * WIDTH ),
				new MeshBasicMaterial()
			);

			let loader = new TextureLoader();

			bgMesh.rotateX( -Math.PI / 6 );
			bgMesh.position.set( 0, -40, HEIGHT / -2 );

			bgMesh.material.depthWrite = false;
			bgMesh.material.map = loader.load('./resources/bg/game_scene_bg.jpg');

			return bgMesh;

		}( this ));

		this.field.children.forEach( function ( b ) {

			b.type === 'Barrier' && this.gameObjects.push( b );

		}, this );

		this.field.changeMaterial( 0 );
		this.scene.add( this.field );

		this.playerShip = new PlayerShip( 0, 0, ( this.field.height >> 1 ) - 50,
			new PerspectiveCamera( 75, WINDOW_WIDTH() / WINDOW_HEIGHT(), 1, 1000 ) );

		this.HUD.setup();

		this.cameras.length > 2 && this.cameras.pop();
		this.cameras.push( this.playerShip.camera );
		this.camera = this.cameras[0];

		this.gameObjects.push( this.playerShip );
		this.scene.add( this.playerShip );

		let [ nx, nz ] = [ 5, 2 ];
		let [ segX, segZ ] = [
			( this.field.width - 120 ) / nx,
			( ( this.field.height - 120 ) >> 1 ) / nz
		];

		for ( let i = 0; i < nz; ++i ) {

			for ( let j = 0; j < nx; ++j ) {

				let [ posX, posZ ] = [
					segX * ( j - ( ( nx - 1 ) / 2 ) ),
					segZ * ( i - ( ( nz + 1 ) / 2 ) )
				];

				let alien = new EnemyShip( posX, 0, posZ );

				this.gameObjects.push( alien );
				this.scene.add( alien );

			}

		}

		this.lightsOn = false;
		this.sun.visible = false;
		this.scene.add( this.sun );

		this.stars.forEach( function ( star ) {

			star.position.set(
				this.field.width * ( Math.random() - 0.5 ),
				100,
				this.field.height * ( Math.random() - 0.5 )
			);

			star.visible = false;
			this.scene.add( star );

		}, this );

		this.gameOver = false;

	}

	update () {

		if ( this.gameClock.running ) {

			let dt = this.gameClock.getDelta();

			if ( EnemyShip.count === 0 || !this.playerShip.alive ) {

				this.gameOver = true;
				this.gameClock.stop();

			} else {

				if ( this.playerShip.shooting ) {

					let playerBullet = this.playerShip.fire();

					if ( playerBullet !== null ) {

						this.scene.add( playerBullet );
						this.gameObjects.push( playerBullet );

					}

				}

				for ( let i = 0; i < this.gameObjects.length; ++i ) {

					let o1 = this.gameObjects[i];

					o1.update( dt );

					for ( let j = i + 1; j < this.gameObjects.length; ++j ) {

						let o2 = this.gameObjects[j];

						o1.intersect( o2 ) && o1.handleCollision( o2, dt );

					}

					if ( o1.isEntity && !o1.alive ) {

						this.scene.remove( o1 );
						this.gameObjects.splice( i--, 1 );

					}

				}

				if ( this.playerShip.lives < this.HUD.lives ) {

					--this.HUD.lives;
					this.HUD.setVisibility();

				}

			}

		}

		this.renderer.clear();
		this.renderer.setViewport( 0, 0, WINDOW_WIDTH(), WINDOW_HEIGHT() );
		this.renderer.render( this.scene, this.camera );

		this.HUD.update();

		window.requestAnimationFrame( this.update.bind( this ) );

	}

	updateMaterials () {

		this.gameObjects.forEach( function ( obj ) {

			let index = this.lightsOn ? (obj.phong ? 1 : 2) : 0;

			obj.phong = !obj.phong;

			obj.changeMaterial( index );

		}, this );

	}

	resize () {

		this.renderer.setSize( WINDOW_WIDTH(), WINDOW_HEIGHT() );

		let size = this.renderer.getSize();
		let ratio = size.width / size.height;

		if ( this.camera.type === 'OrthographicCamera' ) {

			if ( ratio > ( WIDTH / HEIGHT ) ) {

				this.camera.left   = ~( HEIGHT * ratio ) >> 1;
				this.camera.right  = ( HEIGHT * ratio ) >> 1;
				this.camera.top    = HEIGHT >> 1;
				this.camera.bottom = ~HEIGHT >> 1;

			} else {

				this.camera.left   = ~WIDTH >> 1;
				this.camera.right  = WIDTH >> 1;
				this.camera.top    = ( WIDTH / ratio ) >> 1;
				this.camera.bottom = ~( WIDTH / ratio ) >> 1;

			}

		} else {

			this.camera.aspect = ratio;

		}

		this.camera.updateProjectionMatrix();

	}

	keyDown ( event ) {

		if ( this.gameOver ) {

			/* Restart the game */
			if ( event.keyCode === Keyboard.KEY_R ) {

				this.gameOver = false;
				this.setup();

			}

		} else {

			switch ( event.keyCode ) {

				/* Toggle cameras */
				case Keyboard.KEY_1: /* Orthographic (top bird's eye camera) */
				case Keyboard.KEY_2: /* Perspective (back camera) */
				case Keyboard.KEY_3: /* Perspective (player view camera) */

					if ( this.gameClock.running ) {

						this.camera = this.cameras[ event.keyCode - Keyboard.KEY_1 ];
						this.resize();

					}

					break;

				/* Player movement: Left */
				case Keyboard.KEY_A:
				case Keyboard.KEY_LEFT:

					if ( !this.playerShip.moving ) this.playerShip.moving = true;
					this.playerShip.setDirection( -1, 0, 0 );

					break;

				/* Player movement: Right */
				case Keyboard.KEY_D:
				case Keyboard.KEY_RIGHT:

					if ( !this.playerShip.moving ) this.playerShip.moving = true;
					this.playerShip.setDirection( 1, 0, 0 );

					break;

				/* Player action: Toggle shooting */
				case Keyboard.KEY_B:
				case Keyboard.KEY_SPACEBAR:

					this.playerShip.shooting = true;

					break;

				/* Show / hide stars */
				case Keyboard.KEY_C:

					this.stars.forEach( function( star ) {

						star.visible = !star.visible;

					});

					break;

				/* Toggle lights */
				case Keyboard.KEY_L:

					this.lightsOn = !this.lightsOn;
					this.updateMaterials();

					break;

				case Keyboard.KEY_H: /* Toggle playerShip flashlight */

					this.playerShip.toggleFlashlight();

					break;

				/* Toggle Gouraud / Lambert Shading */
				case Keyboard.KEY_G:

					this.updateMaterials();
					break;

				/* Toggle the sun (day/night modes) */
				case Keyboard.KEY_N:

					this.sun.visible = !this.sun.visible;

					break;

				/* Start / Stop the game (clock) */
				case Keyboard.KEY_S:

					this.gameClock.running ? this.gameClock.stop() : this.gameClock.start();

					break;

				/* Toggle wireframe of the objects in the scene */
				case Keyboard.KEY_W:

					this.scene.traverse( function( node ) {

						if ( node.isMesh ) {

							node.material.wireframe = !node.material.wireframe;

						}

					});

					break;

				default: break;

			}
		}

	}

	keyUp ( event ) {

		switch ( event.keyCode ) {

			case Keyboard.KEY_A:
			case Keyboard.KEY_LEFT:
			case Keyboard.KEY_D:
			case Keyboard.KEY_RIGHT:

				this.playerShip.moving = false;

				break;

			case Keyboard.KEY_B:
			case Keyboard.KEY_SPACEBAR:

				this.playerShip.shooting = false;

				break;

			default: break;

		}
	}

}

new Game();
<commit_msg>Done with background, redo wireframe toggling<commit_after>/**
 * CG Space Invaders
 * CG45179 16'17
 *
 * @author: Rui Ventura ( ist181045 )
 * @author: Diogo Freitas ( ist181586 )
 * @author: Sara Azinhal ( ist181700 )
 */

import './lib/threejs/polyfills.js';
import * as THREE from './lib/threejs/constants';

import { WebGLRenderer } from './lib/threejs/renderers/WebGLRenderer';
import { Scene } from './lib/threejs/scenes/Scene';

import { OrthographicCamera } from './lib/threejs/cameras/OrthographicCamera';
import { PerspectiveCamera } from './lib/threejs/cameras/PerspectiveCamera';

import { DirectionalLight } from './lib/threejs/lights/DirectionalLight';
import { PointLight } from './lib/threejs/lights/PointLight';

import { Clock } from './lib/threejs/core/Clock';

import { Mesh } from './lib/threejs/objects/Mesh';
import { MeshBasicMaterial } from './lib/threejs/materials/MeshBasicMaterial';
import { PlaneGeometry } from './lib/threejs/geometries/PlaneGeometry';
import { TextureLoader } from './lib/threejs/loaders/TextureLoader';

import { WIDTH, HEIGHT } from './Constants';
import { WINDOW_PIXEL_RATIO, WINDOW_WIDTH, WINDOW_HEIGHT } from './Constants';

import GameHUD from './scenes/GameHUD';

import Field from './objects/Field';
import EnemyShip from './entities/EnemyShip';
import PlayerShip from './entities/PlayerShip';

import * as Keyboard from './Keyboard';

class Game {

	constructor () {

		this.renderer = (function () {

			let renderer = new WebGLRenderer({ antialias: true });

			renderer.setPixelRatio( WINDOW_PIXEL_RATIO );
			renderer.setSize( WINDOW_WIDTH(), WINDOW_HEIGHT() );
			renderer.autoClear = false;

			return renderer;

		})();
		this.scene = new Scene();

		this.gameClock = new Clock( false );

		this.field = new Field( 0, 0, 0, WIDTH - 10, HEIGHT - 10 );

		this.cameras = (function ( self ) {

			let cameras = new Array();

			/* Ortho camera (bird's eye) */
			cameras.push( function () {

				let camera = new OrthographicCamera(
					~WIDTH >> 1, WIDTH >> 1, HEIGHT >> 1, ~HEIGHT >> 1, 1, 2000
				);

				camera.position.set( 0, 100, 0 );
				camera.lookAt( self.scene.position );

				camera.updateProjectionMatrix();

				return camera;

			}());

			/* Back perspective camera */
			cameras.push( function () {

				let camera = new PerspectiveCamera(
					75, WINDOW_WIDTH() / WINDOW_HEIGHT(), 1, 1000
				);

				camera.position.set( 0, 250, ( self.field.height >> 1 ) + 150 );
				camera.lookAt( self.scene.position );

				camera.updateProjectionMatrix();

				return camera;

			}());

			return cameras;

		})( this );
		this.camera = this.cameras[0];

		this.gameObjects = new Array();

		this.playerShip = new PlayerShip( 0, 0, ( this.field.height >> 1 ) - 50,
			new PerspectiveCamera( 75, WINDOW_WIDTH() / WINDOW_HEIGHT(), 1, 1000 ) );

		this.HUD = new GameHUD( this.renderer, this.playerShip.MAX_LIVES );

		this.sun = (function ( self ) {

			let sun = new DirectionalLight( 0xffffff, 1 );

			sun.position.set( ~self.field.width >> 2, 100, self.field.height >> 2 );
			sun.target = self.scene;

			return sun;

		})( this );
		this.stars = (function ( self, n ) {

			let stars = new Array();

			for ( let i = 0; i < n; ++i ) {

				stars.push( new PointLight( 0xffffff, 0.5 ) );

			}

			return stars;

		}( this, 6 ));

		this.lightsOn = false;

		this.gameOver = false;

		document.body.appendChild( this.renderer.domElement );

		window.addEventListener( 'resize',  this.resize.bind( this ) );
		window.addEventListener( 'keydown', this.keyDown.bind( this ) );
		window.addEventListener( 'keyup',   this.keyUp.bind( this ) );

		this.setup();

		/* HACK: Force a first resize */
		this.resize();

		this.update();

	}

	setup () {

		/* Clear the scene + reset gameObjects array */
		this.scene.children.length = 0;
		this.gameObjects.length = 0;

		/* Build the scene */
		this.scene.add( function () {

			let bgMesh = new Mesh(

				new PlaneGeometry( 10 * WIDTH, 8 * WIDTH ),
				new MeshBasicMaterial()

			);

			let loader = new TextureLoader();
			let texture = loader.load( './resources/bg/game_scene_bg.jpg' );
			texture.wrapS = THREE.RepeatWrapping;
			texture.wrapT = THREE.RepeatWrapping;
			texture.repeat.multiplyScalar( 7 );

			bgMesh.rotateX( -Math.PI / 6 );
			bgMesh.position.set( 0, -20, HEIGHT / -2 );

			bgMesh.material.map = texture;

			return bgMesh;

		}());

		this.field.children.forEach( function ( b ) {

			b.type === 'Barrier' && this.gameObjects.push( b );

		}, this );

		this.field.changeMaterial( 0 );
		this.scene.add( this.field );

		this.playerShip = new PlayerShip( 0, 0, ( this.field.height >> 1 ) - 50,
			new PerspectiveCamera( 75, WINDOW_WIDTH() / WINDOW_HEIGHT(), 1, 1000 ) );

		this.HUD.setup();

		this.cameras.length > 2 && this.cameras.pop();
		this.cameras.push( this.playerShip.camera );
		this.camera = this.cameras[0];

		this.gameObjects.push( this.playerShip );
		this.scene.add( this.playerShip );

		let [ nx, nz ] = [ 5, 2 ];
		let [ segX, segZ ] = [
			( this.field.width - 120 ) / nx,
			( ( this.field.height - 120 ) >> 1 ) / nz
		];

		for ( let i = 0; i < nz; ++i ) {

			for ( let j = 0; j < nx; ++j ) {

				let [ posX, posZ ] = [
					segX * ( j - ( ( nx - 1 ) / 2 ) ),
					segZ * ( i - ( ( nz + 1 ) / 2 ) )
				];

				let alien = new EnemyShip( posX, 0, posZ );

				this.gameObjects.push( alien );
				this.scene.add( alien );

			}

		}

		this.lightsOn = false;
		this.sun.visible = false;
		this.scene.add( this.sun );

		this.stars.forEach( function ( star ) {

			star.position.set(
				this.field.width * ( Math.random() - 0.5 ),
				100,
				this.field.height * ( Math.random() - 0.5 )
			);

			star.visible = false;
			this.scene.add( star );

		}, this );

		this.gameOver = false;

	}

	update () {

		if ( this.gameClock.running ) {

			let dt = this.gameClock.getDelta();

			if ( EnemyShip.count === 0 || !this.playerShip.alive ) {

				this.gameOver = true;
				this.gameClock.stop();

			} else {

				if ( this.playerShip.shooting ) {

					let playerBullet = this.playerShip.fire();

					if ( playerBullet !== null ) {

						this.scene.add( playerBullet );
						this.gameObjects.push( playerBullet );

					}

				}

				for ( let i = 0; i < this.gameObjects.length; ++i ) {

					let o1 = this.gameObjects[i];

					o1.update( dt );

					for ( let j = i + 1; j < this.gameObjects.length; ++j ) {

						let o2 = this.gameObjects[j];

						o1.intersect( o2 ) && o1.handleCollision( o2, dt );

					}

					if ( o1.isEntity && !o1.alive ) {

						this.scene.remove( o1 );
						this.gameObjects.splice( i--, 1 );

					}

				}

				if ( this.playerShip.lives < this.HUD.lives ) {

					--this.HUD.lives;
					this.HUD.setVisibility();

				}

			}

		}

		this.renderer.clear();
		this.renderer.setViewport( 0, 0, WINDOW_WIDTH(), WINDOW_HEIGHT() );
		this.renderer.render( this.scene, this.camera );

		this.HUD.update();

		window.requestAnimationFrame( this.update.bind( this ) );

	}

	updateMaterials () {

		this.gameObjects.forEach( function ( obj ) {

			let index = this.lightsOn ? (obj.phong ? 1 : 2) : 0;

			obj.phong = !obj.phong;

			obj.changeMaterial( index );

		}, this );

	}

	resize () {

		this.renderer.setSize( WINDOW_WIDTH(), WINDOW_HEIGHT() );

		let size = this.renderer.getSize();
		let ratio = size.width / size.height;

		if ( this.camera.type === 'OrthographicCamera' ) {

			if ( ratio > ( WIDTH / HEIGHT ) ) {

				this.camera.left   = ~( HEIGHT * ratio ) >> 1;
				this.camera.right  = ( HEIGHT * ratio ) >> 1;
				this.camera.top    = HEIGHT >> 1;
				this.camera.bottom = ~HEIGHT >> 1;

			} else {

				this.camera.left   = ~WIDTH >> 1;
				this.camera.right  = WIDTH >> 1;
				this.camera.top    = ( WIDTH / ratio ) >> 1;
				this.camera.bottom = ~( WIDTH / ratio ) >> 1;

			}

		} else {

			this.camera.aspect = ratio;

		}

		this.camera.updateProjectionMatrix();

	}

	keyDown ( event ) {

		if ( this.gameOver ) {

			/* Restart the game */
			if ( event.keyCode === Keyboard.KEY_R ) {

				this.gameOver = false;
				this.setup();

			}

		} else {

			switch ( event.keyCode ) {

				/* Toggle cameras */
				case Keyboard.KEY_1: /* Orthographic (top bird's eye camera) */
				case Keyboard.KEY_2: /* Perspective (back camera) */
				case Keyboard.KEY_3: /* Perspective (player view camera) */

					if ( this.gameClock.running ) {

						this.camera = this.cameras[ event.keyCode - Keyboard.KEY_1 ];
						this.resize();

					}

					break;

				/* Player movement: Left */
				case Keyboard.KEY_A:
				case Keyboard.KEY_LEFT:

					if ( !this.playerShip.moving ) this.playerShip.moving = true;
					this.playerShip.setDirection( -1, 0, 0 );

					break;

				/* Player movement: Right */
				case Keyboard.KEY_D:
				case Keyboard.KEY_RIGHT:

					if ( !this.playerShip.moving ) this.playerShip.moving = true;
					this.playerShip.setDirection( 1, 0, 0 );

					break;

				/* Player action: Toggle shooting */
				case Keyboard.KEY_B:
				case Keyboard.KEY_SPACEBAR:

					this.playerShip.shooting = true;

					break;

				/* Show / hide stars */
				case Keyboard.KEY_C:

					this.stars.forEach( function( star ) {

						star.visible = !star.visible;

					});

					break;

				/* Toggle lights */
				case Keyboard.KEY_L:

					this.lightsOn = !this.lightsOn;
					this.updateMaterials();

					break;

				case Keyboard.KEY_H: /* Toggle playerShip flashlight */

					this.playerShip.toggleFlashlight();

					break;

				/* Toggle Gouraud / Lambert Shading */
				case Keyboard.KEY_G:

					this.updateMaterials();
					break;

				/* Toggle the sun (day/night modes) */
				case Keyboard.KEY_N:

					this.sun.visible = !this.sun.visible;

					break;

				/* Start / Stop the game (clock) */
				case Keyboard.KEY_S:

					this.gameClock.running ? this.gameClock.stop() : this.gameClock.start();

					break;

				/* Toggle wireframe of the objects in the scene */
				case Keyboard.KEY_W:

					this.gameObjects.forEach( function( obj ) {

						obj.traverse( function ( node ) {

							if ( node.isMesh ) {

								node.material.wireframe = !node.material.wireframe;

							}

						});

					});

					break;

				default: break;

			}
		}

	}

	keyUp ( event ) {

		switch ( event.keyCode ) {

			case Keyboard.KEY_A:
			case Keyboard.KEY_LEFT:
			case Keyboard.KEY_D:
			case Keyboard.KEY_RIGHT:

				this.playerShip.moving = false;

				break;

			case Keyboard.KEY_B:
			case Keyboard.KEY_SPACEBAR:

				this.playerShip.shooting = false;

				break;

			default: break;

		}
	}

}

new Game();
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var sqlite3 = require('sqlite3').verbose();
var multiline = require('multiline');

var ERRORS = Object.freeze({
    EEXIST: 'EEXIST',
    SQLITE_CONSTRAINT: 'SQLITE_CONSTRAINT'
});

var configPath = path.join(__dirname, '../.ledger', 'config.json');
var dataPath = path.join(__dirname, '../.ledger', 'ledger.db');

var db = new sqlite3.Database(dataPath);

var api = exports;

api.init = function (callback) {
    mkdirp(dataPath, function (err) {
        if (err) {
            if (err.code !== ERRORS.EEXIST) {
                throw err;
            }
        }

        db.run(multiline(function () {/*
            CREATE TABLE IF NOT EXISTS projects (
                id INTEGER PRIMARY KEY,
                name TEXT UNIQUE,
                checkout TEXT,
                hours INTEGER,
                minutes INTEGER,
                seconds INTEGER
            );
        */}), function (err) {
            if (err) {
                throw err;
            }

            db.run(multiline(function () {/*
                CREATE TABLE IF NOT EXISTS records (
                    id INTEGER PRIMARY KEY,
                    project TEXT,
                    checkout TEXT,
                    checkin TEXT,
                    hours INTEGER,
                    minutes INTEGER,
                    seconds INTEGER
                );
            */}), function (err) {
                if (err) {
                    throw err;
                }

                callback();
            });
        });
    });
};

api.checkout = function () {
    var config = loadConfig();

    if (config.project === null) {
        console.log('You do not have a current project');

        return;
    }

    loadProject(config.project.name, function (project) {
        if (project.checkout !== null) {
            console.log('You already have ' + project.name + ' checked out.');

            return;
        }

        project.checkout = new Date().toISOString();

        updateProject(project, function () {
            console.log('Checkout ' + config.project.name + '.');
        });
    });
};

api.checkin = function () {
    var config = loadConfig();

    if (config.project === null) {
        console.log('You do not have a current project');

        return;
    }

    loadProject(config.project.name, function (project) {
        if (project.checkout === null) {
            console.log('You do not have a project checked out.');

            return;
        }

        var then = new Date(project.checkout);
        var now = new Date();

        var delta = now - then;

        var seconds = Math.floor(delta / 1000);

        var minutes = Math.floor(seconds / 60);
        seconds -= minutes * 60;

        var hours = Math.floor(minutes / 60);
        minutes -= hours * 60;

        var currentYear = now.getFullYear();
        var currentWeek = now.getWeek();

        var record = {
            checkout: then.toISOString(),
            checkin: now.toISOString(),
            project: config.project.name,
            time: {
                hours: hours,
                minutes: minutes,
                seconds: seconds
            }
        };

        addRecord(record, function () {
            project.checkout = null;
            project.hours += record.time.hours;
            project.minutes += record.time.minutes;
            project.seconds += record.time.seconds;

            updateProject(project, function () {
                console.log('Checkin ' + config.project.name + '.');
            });
        });
    });
};

api.createProject = function (name) {
    var config = loadConfig();

    addProject(name, function () {
        if (config.project === null) {
            config.project = {
                name: name
            };
        }

        fs.writeFile(configPath, JSON.stringify(config), function (err) {
            if (err) {
                throw err;
            }

            console.log('Created project: ' + name);
        });
    });
};

api.listProjects = function () {
    loadProjects(function (projects) {
        console.log(projects);
    });
};

api.changeProject = function (name) {
    var config = loadConfig();

    loadProject(name, function (project) {
        if (project === undefined) {
            console.log('Could not find project: ' + name);

            return;
        }

        config.project.name = project.name;

        fs.writeFile(configPath, JSON.stringify(config), function (err) {
            if (err) {
                throw err;
            }

            console.log('Switched to project: ' + name);
        });
    });
}

api.deleteProject = function (name) {
    var config = loadConfig();

    deleteProject(name, function () {
        console.log('Deleted project: ' + name);
    });
};

function loadConfig() {
    var config;

    try {
        config = require(configPath);
    } catch (e) {
        config = {
            project: null
        };

        fs.writeFile(configPath, JSON.stringify(config), function (err) {
            if (err) {
                throw err;
            }
        });
    } finally {
        return config;
    }
}

function addRecord(record, callback) {
    db.run(multiline(function () {/*
        INSERT INTO records (project, checkout, checkin, hours, minutes, seconds)
        VALUES ($project, $checkout, $checkin, $hours, $minutes, $seconds);
    */}), {
        $project: record.project,
        $checkout: record.checkout,
        $checkin: record.checkin,
        $hours: record.time.hours,
        $minutes: record.time.minutes,
        $seconds: record.time.seconds
    }, function (err) {
        if (err) {
            throw err;
        }

        callback();
    });
}

function addProject(name, callback) {
    db.run(multiline(function () {/*
        INSERT INTO projects (name, checkout, hours, minutes, seconds)
        VALUES ($name, NULL, 0, 0, 0);
    */}), {
        $name: name
    }, function (err) {
        if (err) {
            if (err.code === ERRORS.SQLITE_CONSTRAINT) {
                console.log('A project named "' + name + '" already exists');

                return;
            }

            throw err;
        }

        callback();
    });
}

function loadProjects(callback) {
    db.all(multiline(function () {/*
        SELECT * FROM projects;
    */}), function (err, projects) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback(projects);
        }
    });
}

function loadProject(name, callback) {
    db.get(multiline(function () {/*
        SELECT * FROM projects
        WHERE name = $name;
    */}), {
        $name: name
    }, function (err, project) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback(project);
        }
    });
}

function updateProject(project, callback) {
    db.run(multiline(function () {/*
        UPDATE projects
        SET checkout = $checkout,
            hours = $hours,
            minutes = $minutes,
            seconds = $seconds
        WHERE name = $name;
    */}), {
        $name: project.name,
        $checkout: project.checkout,
        $hours: project.hours,
        $minutes: project.minutes,
        $seconds: project.seconds
    }, function (err, project) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback(project);
        }
    });
}

function deleteProject(name, callback) {
    db.run(multiline(function () {/*
        DELETE FROM projects
        WHERE name = $name;
    */}), {
        $name: name
    }, function (err) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback();
        }
    });
}

Date.prototype.getWeek = function () {
    var date = new Date(this.getTime());

    date.setHours(0, 0, 0, 0);

    date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);

    var weekOne = new Date(date.getFullYear(), 0, 4);

    return 1 + Math.round(((date.getTime() - weekOne.getTime()) / 86400000 - 3 + (weekOne.getDay() + 6) % 7) / 7);
};
<commit_msg>List project names and hours<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var sqlite3 = require('sqlite3').verbose();
var multiline = require('multiline');

var ERRORS = Object.freeze({
    EEXIST: 'EEXIST',
    SQLITE_CONSTRAINT: 'SQLITE_CONSTRAINT'
});

var configPath = path.join(__dirname, '../.ledger', 'config.json');
var dataPath = path.join(__dirname, '../.ledger', 'ledger.db');

var db = new sqlite3.Database(dataPath);

var api = exports;

api.init = function (callback) {
    mkdirp(dataPath, function (err) {
        if (err) {
            if (err.code !== ERRORS.EEXIST) {
                throw err;
            }
        }

        db.run(multiline(function () {/*
            CREATE TABLE IF NOT EXISTS projects (
                id INTEGER PRIMARY KEY,
                name TEXT UNIQUE,
                checkout TEXT,
                hours INTEGER,
                minutes INTEGER,
                seconds INTEGER
            );
        */}), function (err) {
            if (err) {
                throw err;
            }

            db.run(multiline(function () {/*
                CREATE TABLE IF NOT EXISTS records (
                    id INTEGER PRIMARY KEY,
                    project TEXT,
                    checkout TEXT,
                    checkin TEXT,
                    hours INTEGER,
                    minutes INTEGER,
                    seconds INTEGER
                );
            */}), function (err) {
                if (err) {
                    throw err;
                }

                callback();
            });
        });
    });
};

api.checkout = function () {
    var config = loadConfig();

    if (config.project === null) {
        console.log('You do not have a current project');

        return;
    }

    loadProject(config.project.name, function (project) {
        if (project.checkout !== null) {
            console.log('You already have ' + project.name + ' checked out.');

            return;
        }

        project.checkout = new Date().toISOString();

        updateProject(project, function () {
            console.log('Checkout ' + config.project.name + '.');
        });
    });
};

api.checkin = function () {
    var config = loadConfig();

    if (config.project === null) {
        console.log('You do not have a current project');

        return;
    }

    loadProject(config.project.name, function (project) {
        if (project.checkout === null) {
            console.log('You do not have a project checked out.');

            return;
        }

        var then = new Date(project.checkout);
        var now = new Date();

        var delta = now - then;

        var seconds = Math.floor(delta / 1000);

        var minutes = Math.floor(seconds / 60);
        seconds -= minutes * 60;

        var hours = Math.floor(minutes / 60);
        minutes -= hours * 60;

        var currentYear = now.getFullYear();
        var currentWeek = now.getWeek();

        var record = {
            checkout: then.toISOString(),
            checkin: now.toISOString(),
            project: config.project.name,
            time: {
                hours: hours,
                minutes: minutes,
                seconds: seconds
            }
        };

        addRecord(record, function () {
            project.checkout = null;
            project.hours += record.time.hours;
            project.minutes += record.time.minutes;
            project.seconds += record.time.seconds;

            updateProject(project, function () {
                console.log('Checkin ' + config.project.name + '.');
            });
        });
    });
};

api.createProject = function (name) {
    var config = loadConfig();

    addProject(name, function () {
        if (config.project === null) {
            config.project = {
                name: name
            };
        }

        fs.writeFile(configPath, JSON.stringify(config), function (err) {
            if (err) {
                throw err;
            }

            console.log('Created project: ' + name);
        });
    });
};

api.listProjects = function () {
    loadProjects(function (projects) {
        projects.forEach(function (project) {
            console.log(project.name + ': ' + project.hours + ' hours.');
        });
    });
};

api.changeProject = function (name) {
    var config = loadConfig();

    loadProject(name, function (project) {
        if (project === undefined) {
            console.log('Could not find project: ' + name);

            return;
        }

        config.project.name = project.name;

        fs.writeFile(configPath, JSON.stringify(config), function (err) {
            if (err) {
                throw err;
            }

            console.log('Switched to project: ' + name);
        });
    });
}

api.deleteProject = function (name) {
    var config = loadConfig();

    deleteProject(name, function () {
        console.log('Deleted project: ' + name);
    });
};

function loadConfig() {
    var config;

    try {
        config = require(configPath);
    } catch (e) {
        config = {
            project: null
        };

        fs.writeFile(configPath, JSON.stringify(config), function (err) {
            if (err) {
                throw err;
            }
        });
    } finally {
        return config;
    }
}

function addRecord(record, callback) {
    db.run(multiline(function () {/*
        INSERT INTO records (project, checkout, checkin, hours, minutes, seconds)
        VALUES ($project, $checkout, $checkin, $hours, $minutes, $seconds);
    */}), {
        $project: record.project,
        $checkout: record.checkout,
        $checkin: record.checkin,
        $hours: record.time.hours,
        $minutes: record.time.minutes,
        $seconds: record.time.seconds
    }, function (err) {
        if (err) {
            throw err;
        }

        callback();
    });
}

function addProject(name, callback) {
    db.run(multiline(function () {/*
        INSERT INTO projects (name, checkout, hours, minutes, seconds)
        VALUES ($name, NULL, 0, 0, 0);
    */}), {
        $name: name
    }, function (err) {
        if (err) {
            if (err.code === ERRORS.SQLITE_CONSTRAINT) {
                console.log('A project named "' + name + '" already exists');

                return;
            }

            throw err;
        }

        callback();
    });
}

function loadProjects(callback) {
    db.all(multiline(function () {/*
        SELECT * FROM projects;
    */}), function (err, projects) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback(projects);
        }
    });
}

function loadProject(name, callback) {
    db.get(multiline(function () {/*
        SELECT * FROM projects
        WHERE name = $name;
    */}), {
        $name: name
    }, function (err, project) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback(project);
        }
    });
}

function updateProject(project, callback) {
    db.run(multiline(function () {/*
        UPDATE projects
        SET checkout = $checkout,
            hours = $hours,
            minutes = $minutes,
            seconds = $seconds
        WHERE name = $name;
    */}), {
        $name: project.name,
        $checkout: project.checkout,
        $hours: project.hours,
        $minutes: project.minutes,
        $seconds: project.seconds
    }, function (err, project) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback(project);
        }
    });
}

function deleteProject(name, callback) {
    db.run(multiline(function () {/*
        DELETE FROM projects
        WHERE name = $name;
    */}), {
        $name: name
    }, function (err) {
        if (err) {
            throw err;
        }

        if (typeof callback === typeof Function) {
            callback();
        }
    });
}

Date.prototype.getWeek = function () {
    var date = new Date(this.getTime());

    date.setHours(0, 0, 0, 0);

    date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);

    var weekOne = new Date(date.getFullYear(), 0, 4);

    return 1 + Math.round(((date.getTime() - weekOne.getTime()) / 86400000 - 3 + (weekOne.getDay() + 6) % 7) / 7);
};
<|endoftext|>


<commit_before>module.exports = Document;

var UIElement = require('./uiElement');

function Document(container) {
  if (!(this instanceof Document)){
    return new Document(container);
  }

  UIElement.call(this);

  this._ownerDocument = this;

  if (container && container.localName === 'svg') {
    this._dom = container;
  } else {
    this._dom = require('../utils/svg')('svg');
    container.appendChild(this._dom);
  }
}

Document.prototype = Object.create(UIElement.prototype);
Document.prototype.constructor = Document;
<commit_msg>Added `addDef` method<commit_after>module.exports = Document;

var UIElement = require('./uiElement');

function Document(container) {
  if (!(this instanceof Document)){
    return new Document(container);
  }

  UIElement.call(this);

  this._ownerDocument = this;

  if (container && container.localName === 'svg') {
    this._dom = container;
  } else {
    this._dom = require('../utils/svg')('svg');
    container.appendChild(this._dom);
  }
}

Document.prototype = Object.create(UIElement.prototype);
Document.prototype.constructor = Document;

Document.prototype.addDef = function (defsMarkup) {
  if (!defsMarkup) throw new Error('DefsMarkup is required argument for Document.addDef() method');

  var defs = getDefsElement(this._dom);
  var defContent = require('../utils/domParser')(defsMarkup);
  for (var i = 0; i < defContent.length; ++i) {
    defs.appendChild(defContent[i]);
  }
};

function getDefsElement(svgRoot) {
  var children = svgRoot.childNodes;
  for (var i = 0; children.length; ++i) {
    if (children[i].localName === 'defs') return children[i];
  }

  var defs = require('../utils/svg')('defs');
  svgRoot.appendChild(defs);
  return defs;
}
<|endoftext|>


<commit_before>/**
 * @file List component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import ListGroup from '../_ListGroup';
import ListItem from '../_ListItem';
import Tip from '../Tip';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Event from '../_vendors/Event';

export default class List extends Component {

    static Mode = ListItem.Mode;
    static SEPARATOR = Symbol('SEPARATOR');

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: this.initValue(props)
        };

        this.initValue = ::this.initValue;
        this.isItemChecked = ::this.isItemChecked;
        this.listItemTouchTapHandler = ::this.listItemTouchTapHandler;
        this.listItemSelectHandler = ::this.listItemSelectHandler;
        this.listItemDeselectHandler = ::this.listItemDeselectHandler;
        this.wheelHandler = ::this.wheelHandler;

    }

    initValue(props) {

        if (!props) {
            return;
        }

        const {value, mode} = props;

        if (!mode) {
            return;
        }

        if (value) {
            return value;
        }

        switch (mode) {
            case List.Mode.CHECKBOX:
                return [];
            case List.Mode.RADIO:
                return null;
            default:
                return value;
        }

    }

    isItemChecked(item) {

        const {mode, valueField, displayField} = this.props,
            {value} = this.state;

        if (!item || !value) {
            return false;
        }

        if (mode === List.Mode.CHECKBOX) {
            return _.isArray(value) && value.filter(valueItem => {
                return Util.isValueEqual(valueItem, item, valueField, displayField);
            }).length > 0;
        } else if (mode === List.Mode.RADIO) {
            return Util.isValueEqual(value, item, valueField, displayField);
        }

    }

    listItemTouchTapHandler(value, index) {

        const {mode} = this.props;

        if (mode !== List.Mode.NORMAL) {
            return;
        }

        this.setState({
            value
        }, () => {
            const {onItemTouchTap, onChange} = this.props;
            onItemTouchTap && onItemTouchTap(value, index);
            onChange && onChange(value, index);
        });

    }

    listItemSelectHandler(item, index) {

        const {mode} = this.props;

        if (mode === List.Mode.NORMAL) {
            return;
        }

        let {value} = this.state;

        if (mode === List.Mode.CHECKBOX) {

            if (!value || !_.isArray(value)) {
                value = [];
            }

            value.push(item);

        } else if (mode === List.Mode.RADIO) {
            value = item;
        }

        this.setState({
            value
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(value, index);
        });

    }

    listItemDeselectHandler(item, index) {

        const {mode} = this.props;

        if (mode !== List.Mode.CHECKBOX) {
            return;
        }

        const {valueField, displayField} = this.props;
        let {value} = this.state;

        if (!value || !_.isArray(value)) {
            value = [];
        } else {
            value = value.filter(valueItem => {
                return Util.getValueByValueField(valueItem, valueField, displayField)
                    != Util.getValueByValueField(item, valueField, displayField);
            });
        }

        this.setState({
            value
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(value, index);
        });

    }

    wheelHandler(e) {
        const {shouldPreventContainerScroll, onWheel} = this.props;
        shouldPreventContainerScroll && Event.preventContainerScroll(e);
        onWheel && onWheel(e);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: this.initValue(nextProps)
            });
        }
    }

    render() {

        const {
                children, className, style, theme, data,
                valueField, displayField, descriptionField, disabled, isLoading, mode, renderer
            } = this.props,
            listClassName = (className ? ' ' + className : '');

        return (

                {
                    _.isArray(data) && data.length > 0 ?
                        (
                            data.map((item, index) => {

                                if (!item) {
                                    return null;
                                }

                                if (item === List.SEPARATOR) {
                                    return

;
                                }

                                return typeof item === 'object' ?
                                    (
                                        <ListItem key={index}
                                                  {...item}
                                                  index={index}
                                                  theme={item.theme || theme}
                                                  data={item}
                                                  checked={this.isItemChecked(item)}
                                                  value={Util.getValueByValueField(item, valueField, displayField)}
                                                  text={Util.getTextByDisplayField(item, displayField, valueField)}
                                                  desc={item[descriptionField] || null}
                                                  disabled={disabled || item.disabled}
                                                  isLoading={isLoading || item.isLoading}
                                                  mode={mode}
                                                  renderer={renderer}
                                                  onTouchTap={(e) => {
                                                      this.listItemTouchTapHandler(item, index);
                                                      item.onTouchTap && item.onTouchTap(e);
                                                  }}
                                                  onSelect={() => {
                                                      this.listItemSelectHandler(item, index);
                                                  }}
                                                  onDeselect={() => {
                                                      this.listItemDeselectHandler(item, index);
                                                  }}/>
                                    )
                                    :
                                    (
                                        <ListItem key={index}
                                                  index={index}
                                                  theme={item.theme || theme}
                                                  data={item}
                                                  checked={this.isItemChecked(item)}
                                                  value={item}
                                                  text={item}
                                                  disabled={disabled}
                                                  isLoading={isLoading}
                                                  mode={mode}
                                                  renderer={renderer}
                                                  onTouchTap={() => {
                                                      this.listItemTouchTapHandler(item, index);
                                                  }}
                                                  onSelect={() => {
                                                      this.listItemSelectHandler(item, index);
                                                  }}
                                                  onDeselect={() => {
                                                      this.listItemDeselectHandler(item, index);
                                                  }}/>
                                    );

                            })
                        )
                        :
                        null
                }

                {children}

        );
    }
};

List.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * Children passed into the ListItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        /**
         * The CSS class name of the list button.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the list button.
         */
        style: PropTypes.object,

        /**
         * The theme of the list button.
         */
        theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

        /**
         * The text value of the list button.Type can be string or number.
         */
        value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The list item's display text. Type can be string, number or bool.
         */
        text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The desc value of the list button. Type can be string or number.
         */
        desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * If true,the list item will be disabled.
         */
        disabled: PropTypes.bool,

        /**
         * If true,the button will be have loading effect.
         */
        isLoading: PropTypes.bool,

        /**
         * If true,the element's ripple effect will be disabled.
         */
        disableTouchRipple: PropTypes.bool,

        /**
         * Use this property to display an icon. It will display on the left.
         */
        iconCls: PropTypes.string,

        /**
         * Use this property to display an icon. It will display on the right.
         */
        rightIconCls: PropTypes.string,

        /**
         * The message of tip.
         */
        tip: PropTypes.string,

        /**
         * The position of tip.
         */
        tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

        /**
         * If true,the item will have center displayed ripple effect.
         */
        rippleDisplayCenter: PropTypes.bool,

        /**
         * You can create a complicated renderer callback instead of value and desc prop.
         */
        itemRenderer: PropTypes.func,

        /**
         * Callback function fired when a list item touch-tapped.
         */
        onTouchTap: PropTypes.func

    }), PropTypes.string, PropTypes.number])).isRequired,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the list will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the list will be at loading status.
     */
    isLoading: PropTypes.bool,

    /**
     * The mode of listItem.Can be normal,checkbox.
     */
    mode: PropTypes.oneOf(Util.enumerateValue(ListItem.Mode)),

    shouldPreventContainerScroll: PropTypes.bool,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the list-item select.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when the list changed.
     */
    onChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func

};

List.defaultProps = {

    className: '',
    style: null,
    theme: Theme.DEFAULT,

    data: [],

    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    mode: ListItem.Mode.NORMAL,
    shouldPreventContainerScroll: true

};<commit_msg>update List<commit_after>/**
 * @file List component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import ListGroup from '../_ListGroup';
import ListItem from '../_ListItem';
import Tip from '../Tip';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Event from '../_vendors/Event';

export default class List extends Component {

    static Mode = ListItem.Mode;
    static SEPARATOR = Symbol('SEPARATOR');

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: this.initValue(props)
        };

        this.initValue = ::this.initValue;
        this.isItemChecked = ::this.isItemChecked;
        this.listItemTouchTapHandler = ::this.listItemTouchTapHandler;
        this.listItemSelectHandler = ::this.listItemSelectHandler;
        this.listItemDeselectHandler = ::this.listItemDeselectHandler;
        this.wheelHandler = ::this.wheelHandler;

    }

    initValue(props) {

        if (!props) {
            return;
        }

        const {value, mode} = props;

        if (!mode) {
            return;
        }

        if (value) {
            return value;
        }

        switch (mode) {
            case List.Mode.CHECKBOX:
                return [];
            case List.Mode.RADIO:
                return null;
            default:
                return value;
        }

    }

    isItemChecked(item) {

        const {mode, valueField, displayField} = this.props,
            {value} = this.state;

        if (!item || !value) {
            return false;
        }

        if (mode === List.Mode.CHECKBOX) {
            return _.isArray(value) && value.filter(valueItem => {
                return Util.isValueEqual(valueItem, item, valueField, displayField);
            }).length > 0;
        } else if (mode === List.Mode.RADIO) {
            return Util.isValueEqual(value, item, valueField, displayField);
        }

    }

    listItemTouchTapHandler(value, index) {

        const {mode} = this.props;

        if (mode !== List.Mode.NORMAL) {
            return;
        }

        this.setState({
            value
        }, () => {
            const {onItemTouchTap, onChange} = this.props;
            onItemTouchTap && onItemTouchTap(value, index);
            onChange && onChange(value, index);
        });

    }

    listItemSelectHandler(item, index) {

        const {mode} = this.props;

        if (mode === List.Mode.NORMAL) {
            return;
        }

        let {value} = this.state;

        if (mode === List.Mode.CHECKBOX) {

            if (!value || !_.isArray(value)) {
                value = [];
            }

            value.push(item);

        } else if (mode === List.Mode.RADIO) {
            value = item;
        }

        this.setState({
            value
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(value, index);
        });

    }

    listItemDeselectHandler(item, index) {

        const {mode} = this.props;

        if (mode !== List.Mode.CHECKBOX) {
            return;
        }

        const {valueField, displayField} = this.props;
        let {value} = this.state;

        if (!value || !_.isArray(value)) {
            value = [];
        } else {
            value = value.filter(valueItem => {
                return Util.getValueByValueField(valueItem, valueField, displayField)
                    != Util.getValueByValueField(item, valueField, displayField);
            });
        }

        this.setState({
            value
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(value, index);
        });

    }

    wheelHandler(e) {
        const {shouldPreventContainerScroll, onWheel} = this.props;
        shouldPreventContainerScroll && Event.preventContainerScroll(e);
        onWheel && onWheel(e);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: this.initValue(nextProps)
            });
        }
    }

    render() {

        const {
                children, className, style, theme, data,
                valueField, displayField, descriptionField, disabled, isLoading, mode, renderer
            } = this.props,
            listClassName = (className ? ' ' + className : '');

        return (

                {
                    _.isArray(data) && data.length > 0 ?
                        (
                            data.map((item, index) => {

                                if (item === List.SEPARATOR) {
                                    return

;
                                }

                                return typeof item === 'object' ?
                                    (
                                        <ListItem key={index}
                                                  {...item}
                                                  index={index}
                                                  theme={item.theme || theme}
                                                  data={item}
                                                  checked={this.isItemChecked(item)}
                                                  value={Util.getValueByValueField(item, valueField, displayField)}
                                                  text={Util.getTextByDisplayField(item, displayField, valueField)}
                                                  desc={item[descriptionField] || null}
                                                  disabled={disabled || item.disabled}
                                                  isLoading={isLoading || item.isLoading}
                                                  mode={mode}
                                                  renderer={renderer}
                                                  onTouchTap={(e) => {
                                                      this.listItemTouchTapHandler(item, index);
                                                      item.onTouchTap && item.onTouchTap(e);
                                                  }}
                                                  onSelect={() => {
                                                      this.listItemSelectHandler(item, index);
                                                  }}
                                                  onDeselect={() => {
                                                      this.listItemDeselectHandler(item, index);
                                                  }}/>
                                    )
                                    :
                                    (
                                        <ListItem key={index}
                                                  index={index}
                                                  theme={item.theme || theme}
                                                  data={item}
                                                  checked={this.isItemChecked(item)}
                                                  value={item}
                                                  text={item}
                                                  disabled={disabled}
                                                  isLoading={isLoading}
                                                  mode={mode}
                                                  renderer={renderer}
                                                  onTouchTap={() => {
                                                      this.listItemTouchTapHandler(item, index);
                                                  }}
                                                  onSelect={() => {
                                                      this.listItemSelectHandler(item, index);
                                                  }}
                                                  onDeselect={() => {
                                                      this.listItemDeselectHandler(item, index);
                                                  }}/>
                                    );

                            })
                        )
                        :
                        null
                }

                {children}

        );
    }
};

List.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * Children passed into the ListItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        /**
         * The CSS class name of the list button.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the list button.
         */
        style: PropTypes.object,

        /**
         * The theme of the list button.
         */
        theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

        /**
         * The text value of the list button.Type can be string or number.
         */
        value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The list item's display text. Type can be string, number or bool.
         */
        text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The desc value of the list button. Type can be string or number.
         */
        desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * If true,the list item will be disabled.
         */
        disabled: PropTypes.bool,

        /**
         * If true,the button will be have loading effect.
         */
        isLoading: PropTypes.bool,

        /**
         * If true,the element's ripple effect will be disabled.
         */
        disableTouchRipple: PropTypes.bool,

        /**
         * Use this property to display an icon. It will display on the left.
         */
        iconCls: PropTypes.string,

        /**
         * Use this property to display an icon. It will display on the right.
         */
        rightIconCls: PropTypes.string,

        /**
         * The message of tip.
         */
        tip: PropTypes.string,

        /**
         * The position of tip.
         */
        tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

        /**
         * If true,the item will have center displayed ripple effect.
         */
        rippleDisplayCenter: PropTypes.bool,

        /**
         * You can create a complicated renderer callback instead of value and desc prop.
         */
        itemRenderer: PropTypes.func,

        /**
         * Callback function fired when a list item touch-tapped.
         */
        onTouchTap: PropTypes.func

    }), PropTypes.string, PropTypes.number])).isRequired,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the list will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the list will be at loading status.
     */
    isLoading: PropTypes.bool,

    /**
     * The mode of listItem.Can be normal,checkbox.
     */
    mode: PropTypes.oneOf(Util.enumerateValue(ListItem.Mode)),

    shouldPreventContainerScroll: PropTypes.bool,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the list-item select.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when the list changed.
     */
    onChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func

};

List.defaultProps = {

    className: '',
    style: null,
    theme: Theme.DEFAULT,

    data: [],

    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    mode: ListItem.Mode.NORMAL,
    shouldPreventContainerScroll: true

};<|endoftext|>


<commit_before>/**
 *
 */
function ScratchOffAgent() {
    this.canvas = document.createElement("canvas");
    this.canvas.id = "ScratchOffCanvas";
    this.canvas.width = innerWidth;
    this.canvas.height = innerHeight;

    this.context = this.canvas.getContext("2d");
    this.resetBlackCover();

    this.lastX = -1;
    this.lastY = -1;

    this.erasing = false;
    this.active = false;
    this.onMouseDown = undefined;
    this.onMouseUp = undefined;

    this.setBrushSize(14);

    this.canvas.addEventListener("mousedown", this.mouseDown.bind(this));
    this.canvas.addEventListener("mousemove", this.mouseMove.bind(this));
    this.canvas.addEventListener("mouseup", this.mouseUp.bind(this));

    this.canvas.addEventListener("touchstart", this.mouseDown.bind(this));
    this.canvas.addEventListener("touchmove", this.touchMove.bind(this));
    this.canvas.addEventListener("touchend", this.mouseUp.bind(this));

    document.body.addEventListener("mouseout", this.mouseUp.bind(this));

    document.body.appendChild(this.canvas);
};

/**
 *
 */
ScratchOffAgent.prototype.resetBlackCover = function () {
    this.context.globalCompositeOperation = "source-over";

    this.context.fillStyle = "#000000";
    this.context.fillRect(0, 0, innerWidth, innerHeight);

    this.context.globalCompositeOperation = "destination-out";
    this.context.lineCap = "round";
};

/**
 *
 */
ScratchOffAgent.prototype.mouseDown = function (event) {
    this.active = true;
    this.context.beginPath();

    if(this.onMouseDown) {
        this.onMouseDown(event);
    }
};

/**
 *
 */
ScratchOffAgent.prototype.mouseUp = function (event) {
    this.active = false;
    this.context.save();

    if(this.onMouseUp) {
        this.onMouseUp(event);
    }
};

/**
 *
 */
ScratchOffAgent.prototype.mouseMove = function (event) {
    if(
        this.active
        && this.lastX !== -1
        // && Math.abs(event.clientX - this.lastX) < 140
        // && Math.abs(event.clientY - this.lastY) < 140
    ) {
        this.context.moveTo(this.lastX, this.lastY);
        this.context.lineTo(event.clientX, event.clientY);
        this.context.stroke();
    }

    this.lastX = event.clientX;
    this.lastY = event.clientY;
};

/**
 *
 */
ScratchOffAgent.prototype.touchMove = function (event) {
    this.mouseMove(event.touches[0]);

    event.preventDefault();
    event.stopPropagation();
};

/**
 *
 */
ScratchOffAgent.prototype.setBrushSize = function (size) {
    this.context.lineWidth = size;
};

/**
 *
 */
ScratchOffAgent.prototype.toggleErasor = function (event) {
    if(this.erasing) {
        this.context.globalCompositeOperation = "destination-out";
        this.erasing = false;
        event.target.className = event.target.className.replace(" active", "");
    } else {
        this.context.globalCompositeOperation = "source-over";
        this.erasing = true;
    }

    if(event) {
        event.preventDefault();
        event.stopPropagation();
    }
};

/**
 *
 */
ScratchOffAgent.prototype.useUploadedImage = function (dataURL) {
    var image = new Image();
    image.onload = this.drawImage.bind(this, image);
    image.src = dataURL;
};

/**
 *
 */
ScratchOffAgent.prototype.drawImage = function (image) {
    var dummy = document.createElement("canvas"),
        dummyContext = dummy.getContext("2d"),
        dummyData, bytes, length, sum, i;

    dummy.width = this.canvas.width;
    dummy.height = this.canvas.height;
    dummyContext.drawImage(image, 0, 0, dummy.width, dummy.height);
    dummyData = dummyContext.getImageData(0, 0, dummy.width, dummy.height);

    bytes = dummyData.data;
    length = dummyData.width * dummyData.height * 4;

    for(i = 0; i < length; i += 4) {
        sum = bytes[i] + bytes[i + 1] + bytes[i + 2];
        bytes[i] = bytes[i + 1] = bytes[i + 2] = 0;
        bytes[i + 3] = sum < 7 ? 255 : 0;
    }

    dummyData.data = bytes;
    this.context.putImageData(dummyData, 0, 0);
};<commit_msg>Switched foreground images to grayscale<commit_after>/**
 *
 */
function ScratchOffAgent() {
    this.canvas = document.createElement("canvas");
    this.canvas.id = "ScratchOffCanvas";
    this.canvas.width = innerWidth;
    this.canvas.height = innerHeight;

    this.context = this.canvas.getContext("2d");
    this.resetBlackCover();

    this.lastX = -1;
    this.lastY = -1;

    this.erasing = false;
    this.active = false;
    this.onMouseDown = undefined;
    this.onMouseUp = undefined;

    this.setBrushSize(14);

    this.canvas.addEventListener("mousedown", this.mouseDown.bind(this));
    this.canvas.addEventListener("mousemove", this.mouseMove.bind(this));
    this.canvas.addEventListener("mouseup", this.mouseUp.bind(this));

    this.canvas.addEventListener("touchstart", this.mouseDown.bind(this));
    this.canvas.addEventListener("touchmove", this.touchMove.bind(this));
    this.canvas.addEventListener("touchend", this.mouseUp.bind(this));

    document.body.addEventListener("mouseout", this.mouseUp.bind(this));

    document.body.appendChild(this.canvas);
};

/**
 *
 */
ScratchOffAgent.prototype.resetBlackCover = function () {
    this.context.globalCompositeOperation = "source-over";

    this.context.fillStyle = "#000000";
    this.context.fillRect(0, 0, innerWidth, innerHeight);

    this.context.globalCompositeOperation = "destination-out";
    this.context.lineCap = "round";
};

/**
 *
 */
ScratchOffAgent.prototype.mouseDown = function (event) {
    this.active = true;
    this.context.beginPath();

    if(this.onMouseDown) {
        this.onMouseDown(event);
    }
};

/**
 *
 */
ScratchOffAgent.prototype.mouseUp = function (event) {
    this.active = false;
    this.context.save();

    if(this.onMouseUp) {
        this.onMouseUp(event);
    }
};

/**
 *
 */
ScratchOffAgent.prototype.mouseMove = function (event) {
    if(
        this.active
        && this.lastX !== -1
        // && Math.abs(event.clientX - this.lastX) < 140
        // && Math.abs(event.clientY - this.lastY) < 140
    ) {
        this.context.moveTo(this.lastX, this.lastY);
        this.context.lineTo(event.clientX, event.clientY);
        this.context.stroke();
    }

    this.lastX = event.clientX;
    this.lastY = event.clientY;
};

/**
 *
 */
ScratchOffAgent.prototype.touchMove = function (event) {
    this.mouseMove(event.touches[0]);

    event.preventDefault();
    event.stopPropagation();
};

/**
 *
 */
ScratchOffAgent.prototype.setBrushSize = function (size) {
    this.context.lineWidth = size;
};

/**
 *
 */
ScratchOffAgent.prototype.toggleErasor = function (event) {
    if(this.erasing) {
        this.context.globalCompositeOperation = "destination-out";
        this.erasing = false;
        event.target.className = event.target.className.replace(" active", "");
    } else {
        this.context.globalCompositeOperation = "source-over";
        this.erasing = true;
    }

    if(event) {
        event.preventDefault();
        event.stopPropagation();
    }
};

/**
 *
 */
ScratchOffAgent.prototype.useUploadedImage = function (dataURL) {
    var image = new Image();
    image.onload = this.drawImage.bind(this, image);
    image.src = dataURL;
};

/**
 *
 */
ScratchOffAgent.prototype.drawImage = function (image) {
    var dummy = document.createElement("canvas"),
        dummyContext = dummy.getContext("2d"),
        dummyData, bytes, length, sum, i;

    dummy.width = this.canvas.width;
    dummy.height = this.canvas.height;
    dummyContext.drawImage(image, 0, 0, dummy.width, dummy.height);
    dummyData = dummyContext.getImageData(0, 0, dummy.width, dummy.height);

    bytes = dummyData.data;
    length = dummyData.width * dummyData.height * 4;

    for(i = 0; i < length; i += 4) {
        sum = bytes[i] + bytes[i + 1] + bytes[i + 2];
        bytes[i] = bytes[i + 1] = bytes[i + 2] = 0;
        bytes[i + 3] = (sum / 4) | 0;
    }

    dummyData.data = bytes;
    this.context.putImageData(dummyData, 0, 0);
};<|endoftext|>


<commit_before>'use strict';

function ApplicationController($scope, $location, $http, applicationState, Choko) {
  $scope.state = {};

  $scope.changeState = function() {
    var path = $location.path() || '/home';

    $http.get(path).success(function(data) {
      // Rebuild the layout only when context changes.
      if ($scope.contexts instanceof Array && $scope.contexts.toString() == data.data.contexts.toString()) {
        // Update only panels in content region, and page information.
        // @todo: get the region the page-content panel is attached to
        // dinamically currently this is hadcoded to 'content' and will not work
        // if the page-content panel is attacehd to a different region.
        $scope.panels['content'] = data.data.panels['content'];
        $scope.page = data.data.page;
      }
      else {
        // Merge data from the server.
        angular.extend($scope, data.data);

        // Store scope as application state.
        applicationState.set($scope);
      }
    });
  }

  $scope.$watch(function() {
    return $location.path();
  }, function(){
    $scope.changeState();
  });
}
//ApplicationController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function PanelController($scope, $location, applicationState, Choko) {
  if ($scope.panel.type && $scope.panel.type !== 'default') {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.panel;
    ViewController($scope, $location, applicationState, Choko);
  }

  if ($scope.panel.bare) {
    $scope.template = $scope.panel.template || 'templates/panel-content.html';
  }
  else {
    $scope.template = 'templates/panel.html';
  }
}
//PanelController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function PageController($scope, $location, applicationState, Choko) {
  $scope.title = $scope.page.title;

  if (!$scope.page.type || $scope.page.type === 'default') {
    $scope.items = $scope.page.items || {};
  }
  else {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.page;
    ViewController($scope, $location, applicationState, Choko);
  }
}
//PageController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function RowController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.row.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/row.html';
  }
}
//RowController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ColumnController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.column.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/column.html';
  }
}
//ColumnController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function RegionController($scope, $location, applicationState, Choko) {
}
//RegionController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function NavigationController($scope, $location, applicationState, Choko) {
  $scope.isActive = function(route) {
    //var regexp = new RegExp('^' + pattern + '.*$', ["i"]);
    return route === $location.path();
  };
}
//NavigationController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ItemController($scope, $location, applicationState, Choko) {
}
//ItemController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ViewController($scope, $location, applicationState, Choko) {
  // Handle 'list' type views.
  if ($scope.view.type === 'list' && $scope.view.itemType) {
    $scope.items = {};

    Choko.get({type: $scope.view.itemType}, function(response) {
      $scope.items = response;
    });
  }

  // Handle 'item' type views.
  if ($scope.view.type === 'item' && $scope.view.itemType) {
    $scope.item = {};

    Choko.get({type: $scope.view.itemType, key: $scope.view.itemKey}, function(response) {
      if ($scope.view.path) {
        $scope.title = response.title;
      }
      $scope.item = response;
    });
  }
}
//ViewController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];
<commit_msg>Improving title rendering on dynamic loading pages.<commit_after>'use strict';

function ApplicationController($scope, $location, $http, applicationState, Choko) {
  $scope.state = {};

  $scope.changeState = function() {
    var path = $location.path() || '/home';

    $http.get(path).success(function(data) {
      // Rebuild the layout only when context changes.
      if ($scope.contexts instanceof Array && $scope.contexts.toString() == data.data.contexts.toString()) {
        // Update only panels in content region, and page information.
        // @todo: get the region the page-content panel is attached to
        // dinamically currently this is hadcoded to 'content' and will not work
        // if the page-content panel is attacehd to a different region.
        $scope.panels['content'] = data.data.panels['content'];
        $scope.page = data.data.page;
      }
      else {
        // Merge data from the server.
        angular.extend($scope, data.data);

        // Store scope as application state.
        applicationState.set($scope);
      }
    });
  }

  $scope.$watch(function() {
    return $location.path();
  }, function(){
    $scope.changeState();
  });
}
//ApplicationController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function PanelController($scope, $location, applicationState, Choko) {
  if ($scope.panel.type && $scope.panel.type !== 'default') {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.panel;
    ViewController($scope, $location, applicationState, Choko);
  }

  if ($scope.panel.bare) {
    $scope.template = $scope.panel.template || 'templates/panel-content.html';
  }
  else {
    $scope.template = 'templates/panel.html';
  }
}
//PanelController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function PageController($scope, $location, applicationState, Choko) {
  if (!$scope.page.type || $scope.page.type === 'default') {
    $scope.items = $scope.page.items || {};
    $scope.title = $scope.page.title;
  }
  else {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.page;
    ViewController($scope, $location, applicationState, Choko);
  }
}
//PageController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function RowController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.row.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/row.html';
  }
}
//RowController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ColumnController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.column.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/column.html';
  }
}
//ColumnController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function RegionController($scope, $location, applicationState, Choko) {
}
//RegionController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function NavigationController($scope, $location, applicationState, Choko) {
  $scope.isActive = function(route) {
    //var regexp = new RegExp('^' + pattern + '.*$', ["i"]);
    return route === $location.path();
  };
}
//NavigationController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ItemController($scope, $location, applicationState, Choko) {
}
//ItemController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ViewController($scope, $location, applicationState, Choko) {
  // Handle 'list' type views.
  if ($scope.view.type === 'list' && $scope.view.itemType) {
    $scope.items = {};

    Choko.get({type: $scope.view.itemType}, function(response) {
      $scope.title = $scope.page.title;
      $scope.items = response;
    });
  }

  // Handle 'item' type views.
  if ($scope.view.type === 'item' && $scope.view.itemType) {
    $scope.item = {};

    Choko.get({type: $scope.view.itemType, key: $scope.view.itemKey}, function(response) {
      if ($scope.view.path) {
        $scope.title = response.title;
      }
      $scope.item = response;
    });
  }
}
//ViewController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];
<|endoftext|>


<commit_before><commit_msg>add code back to searchbar<commit_after>import React from 'react';
import { Input, Button } from 'semantic-ui-react';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';

class SearchBar extends React.Component{
  constructor(props) {
    super(props);

    this.state = {
      term: ''
    };

    this.onInputChange=this.onInputChange.bind(this);
    this.onFormSubmit=this.onFormSubmit.bind(this);

  }

  onInputChange(event) {
    console.log(event.target.value);
    this.setState({ term: event.target.value })
  }

  onFormSubmit(event) {
    event.preventDefault();
    this.props.fetchWeather(this.state.term); {/* Accesses the fetchWeather method inside props  */}
    this.setState({ term: ''}); {/* Resets the search bar   */}
  }

  render() {
    return(
      <div>
        <form onSubmit={this.onFormSubmit} >
          <Input
            action="Search"
            placeholder="Enter a city"
            size="massive"
            value={this.state.term}
            onChange={this.onInputChange}
          />
          {/* <Button primary>Submit</Button> */}
        </form>
      </div>
    );
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchWeather}, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchBar);
<|endoftext|>