<commit_before>var sandclock;

(function() {

  //code snippet from: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
  var clone = function(obj) {
    var copy;

    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
      copy = new Date();
      copy.setTime(obj.getTime());
      return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
      copy = [];
      for (var i = 0, len = obj.length; i < len; i++) {
        copy[i] = clone(obj[i]);
      }
      return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
      copy = {};
      for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
      }
      return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
  }

  var getDefaultOptions = function() {
    var defaultOptions = {
      width: 100,
      height: 240,
      bottleneck: 0.04,
      margins: {
        top: 10,
        left: 10,
        right: 10,
        bottom: 10
      },
      background: "white",
      progress: 0,
      maxTop: 0.5,
      maxBottom: 0.275,
      selector: undefined,
      useTransitions: true,
      fadeinDuration: 400,
      transitionDuration: 2000,
      transitionDelay: 0
    };

    return clone(defaultOptions);
  };

  sandclock = function(selector) {
    if (!(this instanceof sandclock))
      return new sandclock(selector);
    this.options = getDefaultOptions();
    this.options.selector = selector;
  };
  sandclock.prototype.width = function(width) {
    this.options.width = width;
    return this;
  };
  sandclock.prototype.height = function(height) {
    this.options.height = height;
    return this;
  };
  sandclock.prototype.bottleneck = function(bottleneck) {
    this.options.bottleneck = bottleneck;
    return this;
  };
  sandclock.prototype.margins = function(margins) {
    this.options.margins = margins;
    return this;
  };
  sandclock.prototype.progress = function(progress) {

    //save last progress state for update animation
    this.options.oldProgress = this.options.progress;

    this.options.progress = progress;
    return this;
  };
  sandclock.prototype.maxTop = function(maxTop) {
    this.options.maxTop = maxTop;
    return this;
  };
  sandclock.prototype.maxBottom = function(maxBottom) {
    this.options.maxBottom = maxBottom;
    return this;
  };
  sandclock.prototype.transitionDuration = function(transitionDuration) {
    this.options.transitionDuration = transitionDuration;
    return this;
  };
  sandclock.prototype.transitionDelay = function(transitionDelay) {
    this.options.transitionDelay = transitionDelay;
    return this;
  }
  sandclock.prototype.updateOptions = function() {
    var options = this.options;
    if (typeof options.oldProgress === "undefined")
      options.oldProgress = options.progress;
    options.bottleneckInPx = options.width * options.bottleneck;
    options.maxProgressTop = 0.9;
    options.progressStartJet = 0.1;
    options.progressEndJet = 0.9;
    options.currentTop = options.progress <= options.maxProgressTop ?
      options.height / 2 * options.maxTop / options.maxProgressTop * (options.maxProgressTop - options.progress) : 0;
    options.currentBottom = options.height / 2 * options.maxBottom * options.progress;
  };
  sandclock.prototype.update = function() {
    this.updateOptions();
    var options = this.options;

    var canvas = d3.select(options.selector)
      .transition()
      .delay(options.fadeinDuration)
      .style("width", options.width)
      .style("height", options.height);

    var sandTop = canvas.select("rect")
      .transition()
      .delay(options.transitionDelay)
      .duration(options.transitionDuration / 2)
      .ease("cubic")
      .attr("class", "sand")
      .attr("x", 0)
      .attr("y", options.height / 2 - options.currentTop)
      .attr("width", options.width)
      .attr("height", options.currentTop);

    var sandJetY = options.progress >= options.progressEndJet ? options.height / 2 + options.height / 2 * (options.progress - options.progressEndJet) * 10 : options.height / 2;
    var sandJetHeight = options.progress <= options.progressStartJet ? options.height / 2 / (1 - options.progressStartJet) * options.progress * 10 : (options.height - options.currentBottom) / 2;

    var sandJet = canvas.select("rect:nth-child(2)")
      .transition()
      .delay(options.transitionDelay)
      .duration(options.transitionDuration / 2)
      .ease("linear")
      .attr("class", "sand")
      .attr("x", (options.width - options.bottleneckInPx) / 2)
      .attr("y", sandJetY)
      .attr("width", options.bottleneckInPx)
      .attr("height", sandJetHeight);

    var sandBottom = canvas.select("path")
      .transition()
      .delay(options.transitionDelay)
      .duration(options.transitionDuration)
      .attr("class", "sand")
      .attr("d", function() {
        var data = [
          [0, options.height],
          [options.width, options.height],
          [options.width / 2, options.progress <= options.progress.progressStartJet ? options.height : options.height - options.currentBottom]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });
  };
  sandclock.prototype.render = function() {
    this.updateOptions();
    var options = this.options;

    var canvas = d3.select(options.selector)
      .style("width", options.width)
      .style("height", options.height)
      .style("opacity", options.useTransitions ? 0 : 1);

    var sandTop = canvas.append("rect")
      .attr("class", "sand")
      .attr("x", 0)
      .attr("y", options.height / 2 - options.currentTop)
      .attr("width", options.width)
      .attr("height", options.currentTop);

    var sandJetY = options.progress >= options.progressEndJet ? options.height / 2 + options.height / 2 * (options.progress - options.progressEndJet) * 10 : options.height / 2;
    var sandJetHeight = options.progress <= options.progressStartJet ? options.height / 2 / (1 - options.progressStartJet) * options.progress * 10 : (options.height - options.currentBottom) / 2;

    var sandJet = canvas.append("rect")
      .attr("class", "sand")
      .attr("x", (options.width - options.bottleneckInPx) / 2)
      .attr("y", sandJetY)
      .attr("width", options.bottleneckInPx)
      .attr("height", sandJetHeight);

    var sandBottom = canvas.append("path")
      .attr("class", "sand")
      .attr("d", function() {
        var data = [
          [0, options.height],
          [options.width, options.height],
          [options.width / 2, options.progress <= options.progressStartJet ? options.height : options.height - options.currentBottom]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });

    var left = canvas.append("path")
      .attr("class", "background")
      .attr("d", function() {
        var data = [
          [0, 0],
          [0, options.height],
          [(options.width - options.bottleneckInPx) / 2, options.height / 2]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });

    var right = canvas.append("path")
      .attr("class", "background")
      .attr("d", function() {
        var data = [
          [options.width, 0],
          [options.width, options.height],
          [options.width - (options.width - options.bottleneckInPx) / 2, options.height / 2]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });

    if (options.useTransitions) {
      d3.select(options.selector)
        .transition()
        .duration(options.fadeinDuration)
        .style("opacity", 1);
    }
    return this;
  }
}());
<commit_msg>fixed propety accessor name<commit_after>var sandclock;

(function() {

  //code snippet from: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
  var clone = function(obj) {
    var copy;

    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
      copy = new Date();
      copy.setTime(obj.getTime());
      return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
      copy = [];
      for (var i = 0, len = obj.length; i < len; i++) {
        copy[i] = clone(obj[i]);
      }
      return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
      copy = {};
      for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
      }
      return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
  }

  var getDefaultOptions = function() {
    var defaultOptions = {
      width: 100,
      height: 240,
      bottleneck: 0.04,
      margins: {
        top: 10,
        left: 10,
        right: 10,
        bottom: 10
      },
      background: "white",
      progress: 0,
      maxTop: 0.5,
      maxBottom: 0.275,
      selector: undefined,
      useTransitions: true,
      fadeinDuration: 400,
      transitionDuration: 2000,
      transitionDelay: 0
    };

    return clone(defaultOptions);
  };

  sandclock = function(selector) {
    if (!(this instanceof sandclock))
      return new sandclock(selector);
    this.options = getDefaultOptions();
    this.options.selector = selector;
  };
  sandclock.prototype.width = function(width) {
    this.options.width = width;
    return this;
  };
  sandclock.prototype.height = function(height) {
    this.options.height = height;
    return this;
  };
  sandclock.prototype.bottleneck = function(bottleneck) {
    this.options.bottleneck = bottleneck;
    return this;
  };
  sandclock.prototype.margins = function(margins) {
    this.options.margins = margins;
    return this;
  };
  sandclock.prototype.progress = function(progress) {

    //save last progress state for update animation
    this.options.oldProgress = this.options.progress;

    this.options.progress = progress;
    return this;
  };
  sandclock.prototype.maxTop = function(maxTop) {
    this.options.maxTop = maxTop;
    return this;
  };
  sandclock.prototype.maxBottom = function(maxBottom) {
    this.options.maxBottom = maxBottom;
    return this;
  };
  sandclock.prototype.transitionDuration = function(transitionDuration) {
    this.options.transitionDuration = transitionDuration;
    return this;
  };
  sandclock.prototype.transitionDelay = function(transitionDelay) {
    this.options.transitionDelay = transitionDelay;
    return this;
  }
  sandclock.prototype.updateOptions = function() {
    var options = this.options;
    if (typeof options.oldProgress === "undefined")
      options.oldProgress = options.progress;
    options.bottleneckInPx = options.width * options.bottleneck;
    options.maxProgressTop = 0.9;
    options.progressStartJet = 0.1;
    options.progressEndJet = 0.9;
    options.currentTop = options.progress <= options.maxProgressTop ?
      options.height / 2 * options.maxTop / options.maxProgressTop * (options.maxProgressTop - options.progress) : 0;
    options.currentBottom = options.height / 2 * options.maxBottom * options.progress;
  };
  sandclock.prototype.update = function() {
    this.updateOptions();
    var options = this.options;

    var canvas = d3.select(options.selector)
      .transition()
      .delay(options.fadeinDuration)
      .style("width", options.width)
      .style("height", options.height);

    var sandTop = canvas.select("rect")
      .transition()
      .delay(options.transitionDelay)
      .duration(options.transitionDuration / 2)
      .ease("linear")
      .attr("class", "sand")
      .attr("x", 0)
      .attr("y", options.height / 2 - options.currentTop)
      .attr("width", options.width)
      .attr("height", options.currentTop);

    var sandJetY = options.progress >= options.progressEndJet ? options.height / 2 + options.height / 2 * (options.progress - options.progressEndJet) * 10 : options.height / 2;
    var sandJetHeight = options.progress <= options.progressStartJet ? options.height / 2 / (1 - options.progressStartJet) * options.progress * 10 : (options.height - options.currentBottom) / 2;

    var sandJet = canvas.select("rect:nth-child(2)")
      .transition()
      .delay(options.transitionDelay)
      .duration(options.transitionDuration / 2)
      .ease("linear")
      .attr("class", "sand")
      .attr("x", (options.width - options.bottleneckInPx) / 2)
      .attr("y", sandJetY)
      .attr("width", options.bottleneckInPx)
      .attr("height", sandJetHeight);

    var sandBottom = canvas.select("path")
      .transition()
      .delay(options.transitionDelay)
      .duration(options.transitionDuration)
      .ease("linear")
      .attr("class", "sand")
      .attr("d", function() {
        var data = [
          [0, options.height],
          [options.width, options.height],
          [options.width / 2, options.progress <= options.progressStartJet ? options.height : options.height - options.currentBottom]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });
  };
  sandclock.prototype.render = function() {
    this.updateOptions();
    var options = this.options;

    var canvas = d3.select(options.selector)
      .style("width", options.width)
      .style("height", options.height)
      .style("opacity", options.useTransitions ? 0 : 1);

    var sandTop = canvas.append("rect")
      .attr("class", "sand")
      .attr("x", 0)
      .attr("y", options.height / 2 - options.currentTop)
      .attr("width", options.width)
      .attr("height", options.currentTop);

    var sandJetY = options.progress >= options.progressEndJet ? options.height / 2 + options.height / 2 * (options.progress - options.progressEndJet) * 10 : options.height / 2;
    var sandJetHeight = options.progress <= options.progressStartJet ? options.height / 2 / (1 - options.progressStartJet) * options.progress * 10 : (options.height - options.currentBottom) / 2;

    var sandJet = canvas.append("rect")
      .attr("class", "sand")
      .attr("x", (options.width - options.bottleneckInPx) / 2)
      .attr("y", sandJetY)
      .attr("width", options.bottleneckInPx)
      .attr("height", sandJetHeight);

    var sandBottom = canvas.append("path")
      .attr("class", "sand")
      .attr("d", function() {
        var data = [
          [0, options.height],
          [options.width, options.height],
          [options.width / 2, options.progress <= options.progressStartJet ? options.height : options.height - options.currentBottom]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });

    var left = canvas.append("path")
      .attr("class", "background")
      .attr("d", function() {
        var data = [
          [0, 0],
          [0, options.height],
          [(options.width - options.bottleneckInPx) / 2, options.height / 2]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });

    var right = canvas.append("path")
      .attr("class", "background")
      .attr("d", function() {
        var data = [
          [options.width, 0],
          [options.width, options.height],
          [options.width - (options.width - options.bottleneckInPx) / 2, options.height / 2]
        ];
        var path = "M" + data.join("L") + "Z";
        return path;
      });

    if (options.useTransitions) {
      d3.select(options.selector)
        .transition()
        .duration(options.fadeinDuration)
        .style("opacity", 1);
    }
    return this;
  }
}());
<|endoftext|>


<commit_before>/* load command line arguments */
var args = require('yargs').argv;

/* load gulp */
var gulp = require('gulp');

/* load the plugins */
var gulpLoadPlugins    = require('gulp-load-plugins');
var plugins            = gulpLoadPlugins({ scope: ['devDependencies'] });
plugins.del            = require("del");
plugins.mainBowerFiles = require("main-bower-files");
plugins.pngcrush       = require('imagemin-pngcrush');

/* clean tasks */
gulp.task('clean:bower', function (cb) {
	return plugins.del(['dist/bower_components/*'],cb);
});

gulp.task('clean:css-patternlab', function (cb) {
	return plugins.del(['dist/css/patternlab/*'],cb);
});

gulp.task('clean:css-custom', function (cb) {
	return plugins.del(['dist/css/custom/*'],cb);
});

gulp.task('clean:fonts', function (cb) {
	return plugins.del(['dist/fonts/*'],cb);
});

gulp.task('clean:html', function (cb) {
	return plugins.del(['dist/html/*'],cb);
});

gulp.task('clean:js', function (cb) {
	return plugins.del(['dist/js/*'],cb);
});

/* core tasks */
gulp.task('build:bower', ['clean:bower'], function(){
	return gulp.src(plugins.mainBowerFiles())
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest("dist/bower_components"))
		.pipe(gulp.dest("../../../public/styleguide/bower_components"));
});

gulp.task('build:css-general', function() {
	return gulp.src(['src/css/prism-okaidia.css'])
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-patternlab', ['clean:css-patternlab', 'build:css-general'], function() {
	return plugins.rubySass('src/sass/styleguide.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-custom', ['clean:css-custom'], function() {
	return plugins.rubySass('src/sass/styleguide-specific.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(gulp.dest('../../../source/styleguide/css'));
});

gulp.task('build:fonts', ['clean:fonts'], function() {
	return gulp.src('src/fonts/*')
		.pipe(gulp.dest('dist/fonts'))
		.pipe(gulp.dest('../../../public/styleguide/fonts'));
});

gulp.task('build:html', ['clean:html'], function() {
	return gulp.src('src/html/*')
		.pipe(gulp.dest('dist/html'))
		.pipe(gulp.dest('../../../public'));
});

gulp.task('build:js-viewer', ['clean:js'], function() {
	return gulp.src(['src/js/*.js','!src/js/annotations-pattern.js','!src/js/code-pattern.js','!src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-viewer.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('build:js-pattern', ['build:js-viewer'], function() {
	return gulp.src(['src/js/postmessage.js','src/js/annotations-pattern.js','src/js/code-pattern.js','src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-pattern.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('default', ['build:bower', 'build:css-custom', 'build:css-patternlab', 'build:fonts', 'build:html', 'build:js-pattern'], function () {

	if (args.watch !== undefined) {
		gulp.watch(['src/bower_components/**/*'], ['build:bower']);
		gulp.watch(['src/css/prism-okaidia.css'],['build:css-general']);
		gulp.watch(['src/sass/styleguide.scss'], ['build:css-patternlab']);
		gulp.watch(['src/sass/styleguide-specific.scss'], ['build:css-custom']);
		gulp.watch(['src/fonts/*'], ['build:fonts'])
		gulp.watch(['src/html/*'], ['build:html']);
		gulp.watch(['src/js/*'], ['build:js-pattern']);
	}

});
<commit_msg>Remove font tasks<commit_after>/* load command line arguments */
var args = require('yargs').argv;

/* load gulp */
var gulp = require('gulp');

/* load the plugins */
var gulpLoadPlugins    = require('gulp-load-plugins');
var plugins            = gulpLoadPlugins({ scope: ['devDependencies'] });
plugins.del            = require("del");
plugins.mainBowerFiles = require("main-bower-files");
plugins.pngcrush       = require('imagemin-pngcrush');

/* clean tasks */
gulp.task('clean:bower', function (cb) {
	return plugins.del(['dist/bower_components/*'],cb);
});

gulp.task('clean:css-patternlab', function (cb) {
	return plugins.del(['dist/css/patternlab/*'],cb);
});

gulp.task('clean:css-custom', function (cb) {
	return plugins.del(['dist/css/custom/*'],cb);
});

gulp.task('clean:html', function (cb) {
	return plugins.del(['dist/html/*'],cb);
});

gulp.task('clean:js', function (cb) {
	return plugins.del(['dist/js/*'],cb);
});

/* core tasks */
gulp.task('build:bower', ['clean:bower'], function(){
	return gulp.src(plugins.mainBowerFiles())
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest("dist/bower_components"))
		.pipe(gulp.dest("../../../public/styleguide/bower_components"));
});

gulp.task('build:css-general', function() {
	return gulp.src(['src/css/prism-okaidia.css'])
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-patternlab', ['clean:css-patternlab', 'build:css-general'], function() {
	return plugins.rubySass('src/sass/styleguide.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-custom', ['clean:css-custom'], function() {
	return plugins.rubySass('src/sass/styleguide-specific.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(gulp.dest('../../../source/styleguide/css'));
});

gulp.task('build:html', ['clean:html'], function() {
	return gulp.src('src/html/*')
		.pipe(gulp.dest('dist/html'))
		.pipe(gulp.dest('../../../public'));
});

gulp.task('build:js-viewer', ['clean:js'], function() {
	return gulp.src(['src/js/*.js','!src/js/annotations-pattern.js','!src/js/code-pattern.js','!src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-viewer.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('build:js-pattern', ['build:js-viewer'], function() {
	return gulp.src(['src/js/postmessage.js','src/js/annotations-pattern.js','src/js/code-pattern.js','src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-pattern.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('default', ['build:bower', 'build:css-custom', 'build:css-patternlab', 'build:html', 'build:js-pattern'], function () {

	if (args.watch !== undefined) {
		gulp.watch(['src/bower_components/**/*'], ['build:bower']);
		gulp.watch(['src/css/prism-okaidia.css'],['build:css-general']);
		gulp.watch(['src/sass/styleguide.scss'], ['build:css-patternlab']);
		gulp.watch(['src/sass/styleguide-specific.scss'], ['build:css-custom']);
		gulp.watch(['src/html/*'], ['build:html']);
		gulp.watch(['src/js/*'], ['build:js-pattern']);
	}

});
<|endoftext|>


<commit_before>/**
 * Select
 */

import React, { Component, PropTypes } from 'react';
import assign from 'zent-utils/lodash/assign';
import omit from 'zent-utils/lodash/omit';
import cloneDeep from 'zent-utils/lodash/cloneDeep';
import isEqual from 'zent-utils/lodash/isEqual';
import isArray from 'zent-utils/lodash/isArray';
import Trigger from './triggers/Index';
import Popup from './Popup';
import SimpleTrigger from './triggers/SimpleTrigger';
import SelectTrigger from './triggers/SelectTrigger';
import InputTrigger from './triggers/InputTrigger';
import TagsTrigger from './triggers/TagsTrigger';
import { KEY_ESC, KEY_EN, KEY_UP, KEY_DOWN } from './constants';

const noop = () => void 0;

class Select extends Component {

  constructor(props) {
    super(props);

    let data = [];

    /**
     * data支持字符串数组和对象数组两种模式
     *
     * 字符串数组默认value为下标
     * 对象数组需提供value和text
     *
     * @return {object}
     */

    if (props.children) {
      let children = props.children;
      if (!isArray(children)) {
        children = [children];
      }
      data = children.map((item) => {
        let value = item.props.value;
        value = typeof value === 'undefined' ? item : value;
        return assign({}, item.props, {
          value,
          text: item.props.children
        });
      });
    }

    // props.data会将子元素覆盖
    if (props.data) {
      data = props.data;
    }

    if (props.simple) {
      this.trigger = SimpleTrigger;
    } else if (props.search) {
      this.trigger = InputTrigger;
    } else if (props.tags) {
      this.trigger = TagsTrigger;
    } else {
      this.trigger = props.trigger;
    }

    this.state = assign({
      selectedItems: []
    }, props);

    this.formateData(data);

    this.blurHandler = this.blurHandler.bind(this);
    this.keyupHandler = this.keyupHandler.bind(this);
    this.triggerChangeHandler = this.triggerChangeHandler.bind(this);
    this.triggerDeleteHandler = this.triggerDeleteHandler.bind(this);
    this.optionChangedHandler = this.optionChangedHandler.bind(this);
    this.popupFocusHandler = this.popupFocusHandler.bind(this);
    this.popupBlurHandler = this.popupBlurHandler.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    let { open } = this.state;
    // 重置组件data
    open = typeof this.focus === 'undefined' ? open : this.focus;
    let nextState = { ...nextProps, open };
    let selectedItems = [];
    if (nextProps.data === this.state.data
      && nextProps.value === this.state.value
      && nextProps.index === this.state.index
    ) return;
    if (`${nextProps.value}` || `${nextProps.index}`) {
      this.state.selectedItem = this.props.selectedItem;
    }
    this.formateData(nextProps.data, nextProps);
    if (isArray(nextProps.value)) {
      this.sourceData.forEach(item => {
        if (nextProps.value.indexOf(item.value) > -1) {
          selectedItems.push(item);
        }
      });
    }
    nextState.selectedItem = this.state.selectedItem;
    nextState.selectedItems = selectedItems;
    this.setState(nextState);
  }

  // 对data进行处理，增加cid
  formateData(data, props) {
    data = data || this.sourceData;
    props = props || this.props;
    let that = this;
    this.sourceData = cloneDeep(data).map((item) => {
      let result = {};
      if (typeof item === 'object') {
        result.value = item[props.optionValue];
        result.text = item[props.optionText];
        result = { ...item, ...result };
      } else {
        result.value = item;
        result.text = item;
      }
      return result;
    }).map((item, index) => {
      // 显示当前选项，支持value和index
      item.cid = `${index}`;
      if (isArray(props.value) && props.value.indexOf(item.value) > -1) {
        that.state.selectedItems.push(item);
      } else if (typeof props.value === 'object' && isEqual(props.value, item.value)) {
        that.state.selectedItem = item;
      } else if (typeof props.value !== 'undefined' && typeof props.value !== 'object' && `${item.value}` === `${props.value}` ||
          props.index !== 'undefined' && `${index}` === `${props.index}`) {
        that.state.selectedItem = item;
      }

      return item;
    });
    return this.sourceData;
  }

  // 接收trigger改变后的数据，将数据传给popup
  triggerChangeHandler(data) {
    if (data.open) {
      this.focus = true;
      this.props.onOpen();
    }
    this.setState(data);
  }

  triggerDeleteHandler(data) {
    let { selectedItems } = this.state;
    selectedItems = selectedItems.filter(item => item.cid !== data.cid);
    this.setState({
      selectedItems
    }, () => {
      this.props.onDelete(data);
    });
  }

  // 将被选中的option的数据传给trigger
  optionChangedHandler(ev, selectedItem) {
    let result = {};
    const {
      onEmptySelected,
      optionValue,
      optionText,
      tags,
      onChange
    } = this.props;
    let { selectedItems } = this.state;
    if (!selectedItem) {
      onEmptySelected(ev);
      return;
    }
    let args = omit(selectedItem, ['cid']);
    result[optionValue] = selectedItem.value;
    result[optionText] = selectedItem.text;
    let data = { ...args, result };
    if (tags) {
      if (!selectedItems.some(item => item.cid === selectedItem.cid)) {
        selectedItems.push(selectedItem);
      }
    }
    onChange(ev, data);
    this.setState({
      keyword: null,
      selectedItems,
      selectedItem,
      open: this.focus
    });
  }

  popupFocusHandler() {
    this.focus = true;
  }

  popupBlurHandler() {
    this.focus = false;
  }

  // 焦点丢失处理
  blurHandler() {
    let that = this;
    setTimeout(() => {
      that.setState({
        open: this.focus
      });
    }, 0);
  }

  keyupHandler(ev) {
    let code = ev.keyCode;
    if (code === KEY_ESC) {
      this.setState({
        open: false
      });
    } else if ([KEY_EN, KEY_UP, KEY_DOWN].indexOf(code) > -1) {
      ev.preventDefault();
      this.setState({
        keyCode: code
      });
    } else {
      this.setState({
        keyCode: code
      });
    }
  }

  render() {
    let {
      placeholder,
      className,
      disabled,
      emptyText,
      filter = this.props.onFilter,
      onAsyncFilter,
      searchPlaceholder
    } = this.props;

    let {
      selectedItems,
      selectedItem = {},
      extraFilter,
      open,
      keyCode,
      keyword = null
    } = this.state;

    let {
      cid = ''
    } = selectedItem;

    let openCls = open && !disabled ? 'open' : '';
    let disabledCls = disabled ? 'disabled' : '';
    let prefixCls = `${this.props.prefix}-select`;

    return (
      <div tabIndex="0" className={`${prefixCls} ${className} ${openCls} ${disabledCls}`} onBlur={this.blurHandler} onKeyDown={this.keyupHandler}>
        <Trigger
          prefixCls={prefixCls}
          trigger={this.trigger}
          placeholder={placeholder}
          selectedItems={selectedItems}
          open={open}
          keyword={keyword}
          {...selectedItem}
          onChange={this.triggerChangeHandler}
          onDelete={this.triggerDeleteHandler}
        />
        <Popup
          cid={cid}
          prefixCls={prefixCls}
          data={this.sourceData}
          selectedItems={selectedItems}
          extraFilter={extraFilter}
          searchPlaceholder={searchPlaceholder}
          emptyText={emptyText}
          keyCode={keyCode}
          keyword={keyword}
          filter={filter}
          onAsyncFilter={onAsyncFilter}
          onChange={this.optionChangedHandler}
          onFocus={this.popupFocusHandler}
          onBlur={this.popupBlurHandler}
        />

    );
  }
}

Select.propTypes = {
  data: PropTypes.array,
  prefix: PropTypes.string,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  placeholder: PropTypes.string,
  searchPlaceholder: PropTypes.string,
  emptyText: PropTypes.string,
  selectedItem: PropTypes.shape({
    value: PropTypes.any,
    text: PropTypes.string
  }),
  trigger: PropTypes.func,
  optionValue: PropTypes.string,
  optionText: PropTypes.string,
  onChange: PropTypes.func,
  onDelete: PropTypes.func,
  filter: PropTypes.func,
  onAsyncFilter: PropTypes.func,
  onEmptySelected: PropTypes.func,
  onOpen: PropTypes.func
};

Select.defaultProps = {
  prefix: 'zent',
  disabled: false,
  className: '',
  trigger: SelectTrigger,
  open: false,
  placeholder: '请选择',
  searchPlaceholder: '',
  emptyText: '没有找到匹配项',
  selectedItem: {
    value: '',
    text: ''
  },
  selectedItems: [],
  optionValue: 'value',
  optionText: 'text',
  onChange: noop,
  onDelete: noop,
  onEmptySelected: noop,
  onOpen: noop
};

export default Select;
<commit_msg>feat: update<commit_after>/**
 * Select
 */

import React, { Component, PropTypes } from 'react';
import assign from 'zent-utils/lodash/assign';
import omit from 'zent-utils/lodash/omit';
import cloneDeep from 'zent-utils/lodash/cloneDeep';
import isEqual from 'zent-utils/lodash/isEqual';
import isArray from 'zent-utils/lodash/isArray';
import Trigger from './triggers/Index';
import Popup from './Popup';
import SimpleTrigger from './triggers/SimpleTrigger';
import SelectTrigger from './triggers/SelectTrigger';
import InputTrigger from './triggers/InputTrigger';
import TagsTrigger from './triggers/TagsTrigger';
import { KEY_ESC, KEY_EN, KEY_UP, KEY_DOWN } from './constants';

const noop = () => void 0;

class Select extends Component {

  constructor(props) {
    super(props);

    let data = [];

    /**
     * data支持字符串数组和对象数组两种模式
     *
     * 字符串数组默认value为下标
     * 对象数组需提供value和text
     *
     * @return {object}
     */

    if (props.children) {
      let children = props.children;
      if (!isArray(children)) {
        children = [children];
      }
      data = children.map((item) => {
        let value = item.props.value;
        value = typeof value === 'undefined' ? item : value;
        return assign({}, item.props, {
          value,
          text: item.props.children
        });
      });
    }

    // props.data会将子元素覆盖
    if (props.data) {
      data = props.data;
    }

    if (props.simple) {
      this.trigger = SimpleTrigger;
    } else if (props.search) {
      this.trigger = InputTrigger;
    } else if (props.tags) {
      this.trigger = TagsTrigger;
    } else {
      this.trigger = props.trigger;
    }

    this.state = assign({
      selectedItems: []
    }, props);

    this.formateData(data);

    this.blurHandler = this.blurHandler.bind(this);
    this.keyupHandler = this.keyupHandler.bind(this);
    this.triggerChangeHandler = this.triggerChangeHandler.bind(this);
    this.triggerDeleteHandler = this.triggerDeleteHandler.bind(this);
    this.optionChangedHandler = this.optionChangedHandler.bind(this);
    this.popupFocusHandler = this.popupFocusHandler.bind(this);
    this.popupBlurHandler = this.popupBlurHandler.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    let { open } = this.state;
    // 重置组件data
    open = typeof this.focus === 'undefined' ? open : this.focus;
    let nextState = { ...nextProps, open };
    let selectedItems = [];
    if (nextProps.data === this.state.data
      && nextProps.value === this.state.value
      && nextProps.index === this.state.index
    ) return;
    if (`${nextProps.value}` || `${nextProps.index}`) {
      this.state.selectedItem = this.props.selectedItem;
    }
    this.formateData(nextProps.data, nextProps);
    if (isArray(nextProps.value)) {
      this.sourceData.forEach(item => {
        if (nextProps.value.indexOf(item.value) > -1) {
          selectedItems.push(item);
        }
      });
    }
    nextState.selectedItem = this.state.selectedItem;
    nextState.selectedItems = selectedItems;
    this.setState(nextState);
  }

  // 对data进行处理，增加cid
  formateData(data, props) {
    data = data || this.sourceData;
    props = props || this.props;
    let that = this;
    this.sourceData = cloneDeep(data).map((item) => {
      let result = {};
      if (typeof item === 'object') {
        result.value = item[props.optionValue];
        result.text = item[props.optionText];
        result = { ...item, ...result };
      } else {
        result.value = item;
        result.text = item;
      }
      return result;
    }).map((item, index) => {
      // 显示当前选项，支持value和index
      item.cid = `${index}`;
      if (isArray(props.value) && props.value.indexOf(item.value) > -1) {
        that.state.selectedItems.push(item);
      } else if (typeof props.value === 'object' && isEqual(props.value, item.value)) {
        that.state.selectedItem = item;
      } else if (typeof props.value !== 'undefined' && typeof props.value !== 'object' && `${item.value}` === `${props.value}` ||
          props.index !== 'undefined' && `${index}` === `${props.index}`) {
        that.state.selectedItem = item;
      }

      return item;
    });
    return this.sourceData;
  }

  // 接收trigger改变后的数据，将数据传给popup
  triggerChangeHandler(data) {
    if (data.open) {
      this.props.onOpen();
    }
    this.setState(data);
  }

  triggerDeleteHandler(data) {
    let { selectedItems } = this.state;
    selectedItems = selectedItems.filter(item => item.cid !== data.cid);
    this.setState({
      selectedItems
    }, () => {
      this.props.onDelete(data);
    });
  }

  // 将被选中的option的数据传给trigger
  optionChangedHandler(ev, selectedItem) {
    let result = {};
    const {
      onEmptySelected,
      optionValue,
      optionText,
      tags,
      onChange
    } = this.props;
    let { selectedItems } = this.state;
    if (!selectedItem) {
      onEmptySelected(ev);
      return;
    }
    let args = omit(selectedItem, ['cid']);
    result[optionValue] = selectedItem.value;
    result[optionText] = selectedItem.text;
    let data = { ...args, result };
    if (tags) {
      if (!selectedItems.some(item => item.cid === selectedItem.cid)) {
        selectedItems.push(selectedItem);
      }
    }
    onChange(ev, data);
    this.setState({
      keyword: null,
      selectedItems,
      selectedItem,
      open: this.focus
    });
  }

  popupFocusHandler() {
    this.focus = true;
  }

  popupBlurHandler() {
    this.focus = false;
  }

  // 焦点丢失处理
  blurHandler() {
    let that = this;
    setTimeout(() => {
      that.setState({
        open: this.focus
      });
    }, 0);
  }

  keyupHandler(ev) {
    let code = ev.keyCode;
    if (code === KEY_ESC) {
      this.setState({
        open: false
      });
    } else if ([KEY_EN, KEY_UP, KEY_DOWN].indexOf(code) > -1) {
      ev.preventDefault();
      this.setState({
        keyCode: code
      });
    } else {
      this.setState({
        keyCode: code
      });
    }
  }

  render() {
    let {
      placeholder,
      className,
      disabled,
      emptyText,
      filter = this.props.onFilter,
      onAsyncFilter,
      searchPlaceholder
    } = this.props;

    let {
      selectedItems,
      selectedItem = {},
      extraFilter,
      open,
      keyCode,
      keyword = null
    } = this.state;

    let {
      cid = ''
    } = selectedItem;

    let openCls = open && !disabled ? 'open' : '';
    let disabledCls = disabled ? 'disabled' : '';
    let prefixCls = `${this.props.prefix}-select`;

    return (
      <div tabIndex="0" className={`${prefixCls} ${className} ${openCls} ${disabledCls}`} onBlur={this.blurHandler} onKeyDown={this.keyupHandler}>
        <Trigger
          prefixCls={prefixCls}
          trigger={this.trigger}
          placeholder={placeholder}
          selectedItems={selectedItems}
          open={open}
          keyword={keyword}
          {...selectedItem}
          onChange={this.triggerChangeHandler}
          onDelete={this.triggerDeleteHandler}
        />
        <Popup
          cid={cid}
          prefixCls={prefixCls}
          data={this.sourceData}
          selectedItems={selectedItems}
          extraFilter={extraFilter}
          searchPlaceholder={searchPlaceholder}
          emptyText={emptyText}
          keyCode={keyCode}
          keyword={keyword}
          filter={filter}
          onAsyncFilter={onAsyncFilter}
          onChange={this.optionChangedHandler}
          onFocus={this.popupFocusHandler}
          onBlur={this.popupBlurHandler}
        />

    );
  }
}

Select.propTypes = {
  data: PropTypes.array,
  prefix: PropTypes.string,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  placeholder: PropTypes.string,
  searchPlaceholder: PropTypes.string,
  emptyText: PropTypes.string,
  selectedItem: PropTypes.shape({
    value: PropTypes.any,
    text: PropTypes.string
  }),
  trigger: PropTypes.func,
  optionValue: PropTypes.string,
  optionText: PropTypes.string,
  onChange: PropTypes.func,
  onDelete: PropTypes.func,
  filter: PropTypes.func,
  onAsyncFilter: PropTypes.func,
  onEmptySelected: PropTypes.func,
  onOpen: PropTypes.func
};

Select.defaultProps = {
  prefix: 'zent',
  disabled: false,
  className: '',
  trigger: SelectTrigger,
  open: false,
  placeholder: '请选择',
  searchPlaceholder: '',
  emptyText: '没有找到匹配项',
  selectedItem: {
    value: '',
    text: ''
  },
  selectedItems: [],
  optionValue: 'value',
  optionText: 'text',
  onChange: noop,
  onDelete: noop,
  onEmptySelected: noop,
  onOpen: noop
};

export default Select;
<|endoftext|>


<commit_before>cns("sfme.userModules").defineUserModule("ssnake", "main",
(function()
{
    this.sfmeAPI = null;
    this.init = function(sfmeAPI_)
    {
        this.sfmeAPI = sfmeAPI_;

        this.sfmeAPI.defineScenes(
        {
            this_: this,
            scenes: {
                intro: {
                    resources: {
                        textures: {
                            testtext: {
                                type: "text",
                                width: 512,
                                height: 256,
                                textDefinition:
                                {
                                    text: "Super Snake",
                                    fontSize: 55,
                                    fontName: "Georgia",
                                    fillStyle: "white",
                                    strokeStyle: "#555555",
                                    lineWidth: 1,
                                    textBaseline: "middle",
                                    textPosition: [512/2,256/2]
                                }
                            }
                        }
                    },
                    cameras: {
                        camera: {
                            type: "ortho",
                            angle: 45.0,
                            ratio: "normal",
                            zNear: 0.1,
                            zFar: 100.0,
                            left: -50.0,
                            right: 50.0,
                            top: 50,
                            bottom: -50.0,
                            objects: {
                                quad: {
                                    shapeType: "quad_normal",
                                    width: 64.0,
                                    height: 32.0,
                                    position: [0.0, 0.0, -5.0],
                                    material: {
                                        blending: true,
                                        alpha: 1.0,
                                        name: "textured",
                                        textureMode: "attach",
                                        color: [1.0, 1.0, 1.0, 1.0],
                                    },
                                    animations: {
                                        showText: {
                                            animTime: 5000,
                                            onStartAnimation: function()
                                            {

                                            },
                                            onUpdateAnimation: function(parentObject,timePassed)
                                            {
                                                var t = timePassed / this.animTime;
                                                parentObject.material.alpha = t;
                                                return t > 1.0;
                                            },
                                            onEndAnimation: function(parentObject)
                                            {
                                                parentObject.material.alpha = 1.0;
                                                parentObject.parentScene.finishScene();
                                            }
                                        }
                                    },
                                    onCreated: function()
                                    {
                                        this.material.texture = this.parentScene.resources.textures.testtext;
                                    }
                                }
                            }
                        }
                    },
                    backgroundColor: [0.0, 0.0, 0.0, 1.0],
                    onStart: function()
                    {
                        console.log("Started");
                        this.cameras.camera.objects.quad.animations.showText.StartAnimation();
                    }
                },
                game: {
                    resources: {
                        textures: {
                            testtext: {
                                id: "testtext",
                                type: "text",
                                width: 512,
                                height: 64,
                                textDefinition:
                                {
                                    text: "Score:",
                                    fontSize: 55,
                                    fontName: "Georgia",
                                    fillStyle: "white",
                                    strokeStyle: "#555555",
                                    lineWidth: 1,
                                    textBaseline: "top",
                                    textAlign: "left",
                                    textPosition: [0,0]
                                }
                            },
                            hudBackground: {
                                type: "canvas",
                                backgroundColor:    function()
                                                    {
                                                        var context = this.context;
                                                        // add linear gradient
                                                        var grd = context.createLinearGradient(0, 0, 1, context.canvas.height);
                                                        grd.addColorStop(0, "#555555");
                                                        grd.addColorStop(0.5, "#222222");
                                                        grd.addColorStop(1, "#555555");
                                                        return grd;

                                                    },
                                width: 1,
                                height: 32,
                                /*
                                onDraw: function(context)
                                {
                                    // add linear gradient
                                    var grd = context.createLinearGradient(0, 0, context.canvas.width, context.canvas.height);
                                    // light blue
                                    grd.addColorStop(0, '#8ED6FF');
                                    // dark blue
                                    grd.addColorStop(1, '#004CB3');
                                    context.fillStyle = grd;
                                    context.fillRect(0, 0, context.canvas.width, context.canvas.height);
                                }
                                   */
                            }
                        }
                    },
                    boardModel:
                    {
                        getPositionForCell: function(vec)
                        {
                            // TODO: Implement real boards.
                            return [vec[0] * 1, vec[1]  * 1 , -15.0 + (vec[2] * 1)];
                        },
                        getNextCell: function(obj)
                        {
                            return [obj.boardCell[0] + obj.nextDirection[0],
                                    obj.boardCell[1] + obj.nextDirection[1],
                                    obj.boardCell[2] + obj.nextDirection[2]];
                        },
                        setNextCell: function(obj)
                        {
                            obj.boardCell = this.getNextCell(obj);
                        }
                    },
                    lastIndexPart: 0,
                    cameras: {
                        camera2d:
                        {
                            type: "ortho",
                            angle: 45.0,
                            ratio: "normal",
                            zNear: 0.1,
                            zFar: 100.0,
                            left: -50.0,
                            right: 50.0,
                            top: 50,
                            bottom: -50.0,
                            objects: {
                                hudBackgroundObject: {
                                    shapeType: "quad_normal",
                                    width: 200.0,
                                    height: 10.0,
                                    position: [0.0, 45.0, -5.0],

                                    material: {
                                        name: "textured",
                                        textureMode: "attach",
                                        color: [1.0, 1.0, 1.0, 1.0],
                                    },
                                    onCreated: function()
                                    {
                                        this.material.texture = this.parentScene.resources.textures.hudBackground;
                                    }
                                },
                                scoreText: {
                                    shapeType: "quad_normal",
                                    width: 25.0,
                                    height: 10.0,
                                    position: [-37.5, 45.0, -4.0],

                                    material: {
                                        blending: true,
                                        alpha: 1.0,
                                        name: "textured",
                                        textureMode: "attach",
                                        color: [1.0, 1.0, 1.0, 1.0],
                                    },
                                    onCreated: function()
                                    {
                                        this.material.texture = this.parentScene.resources.textures.testtext;
                                    }
                                },
                            }
                        },
                        camera: {
                            type: "perspective",
                            lookAt: {
                                eye: [0.0, 0.0, 0.1],
                                center: [0.0, 0.0, -100.0],
                                vUp: [0.0, 1.0, 0.0]
                            },
                            angle: 45.0,
                            ratio: "normal",
                            zNear: 0.1,
                            zFar: 100.0,
                            objects: {
                                part_0: {
                                    shapeType: "cube",
                                    width: 1.0,
                                    height: 1.0,

                                    material: {
                                        name: "textured",
                                        textureMode: "ignore",
                                        color: [1.0, 0.0, 0.0, 1.0]
                                    },
                                    onUpdate: function(globalTiming)
                                    {
                                        this.partScale = [1.0,1.0,1.0];
                                        var scaleIndex = this.direction[0] !== 0 ? 0 : 1;
                                        this.partScale[scaleIndex] = (globalTiming.currentTime - this.creationTime) / 1000;
                                        var createNew = this.partScale[scaleIndex] >= 1.00;
                                        if (createNew)
                                        {
                                            var remanent = this.partScale[scaleIndex] - 1.00;
                                            this.scale = [1.0, 1.0, 1.0];
                                            this.position = this.parentScene.boardModel.getPositionForCell(this.boardCell);

                                            var newPart = this.createNewPart();

                                            newPart.partScale = [1.0,1.0,1.0];
                                            newPart.direction = vec3.create(newPart.nextDirection);
                                            this.parentScene.boardModel.setNextCell(newPart);
                                            newPart.partScale[scaleIndex] = remanent;
                                            newPart.setFinalPosition();
                                        }
                                        this.setFinalPosition();
                                    },
                                    setFinalPosition: function()
                                    {
                                        var iPosition = this.parentScene.boardModel.getPositionForCell(this.boardCell);
                                        var inp = [
                                            iPosition[0] - (this.direction[0] / 2.0),
                                            iPosition[1] - (this.direction[1] / 2.0),
                                            iPosition[2] - (this.direction[2] / 2.0)
                                        ];
                                        var fp = [inp[0] + ((this.partScale[0] * this.direction[0]) / 2.0),
                                            inp[1] + ((this.partScale[1] * this.direction[1]) / 2.0),
                                            inp[2] + ((this.partScale[2] * this.direction[2]) / 2.0)];
                                        this.scale = vec3.create(this.partScale);
                                        this.position = fp;
                                    },
                                    createNewPart: function()
                                    {
                                        var newPart = this.addClone("part_"+(this.parentScene.lastIndexPart+1));
                                        this.onUpdate = null;
                                        this.parentScene.lastIndexPart++;
                                        newPart.setScale([1.0,1.0,1.0]);
                                        return newPart;
                                    }
                                }
                            }
                        }
                    },
                    backgroundColor: [0.0, 1.0, 0.0, 1.0],
                    onStart: function(globalTiming)
                    {
                        console.log("Started");
                        this.cameras.camera.objects.part_0.boardCell = [0,0,0];// = this.boardModel.getPositionForCell([0,0,0]);
                        this.cameras.camera.objects.part_0.direction = [1,0,0];
                        this.cameras.camera.objects.part_0.nextDirection = [1,0,0];
                        this.cameras.camera.objects.part_0.creationTime = globalTiming.currentTime;
                        this.score = 0;
                    },
                    onUpdate: function(globalTiminig)
                    {
                        this.resources.textures.testtext.textDefinition.setText("Score: "+this.score);
                    },
                    inputController:
                    {
                        delta:0.5,
                        onKeyDown: function(parentObject,e)
                        {
                            var camera = parentObject.cameras.camera.lookAt;
                            if (e.keyCode === 65)
                            {
                                camera.eye[0] -= this.delta;
                            } else if (e.keyCode === 68)
                            {
                                camera.eye[0] += this.delta;
                            } else if (e.keyCode === 87)
                            {
                                camera.eye[1] += this.delta;
                            } else if (e.keyCode === 83)
                            {
                                camera.eye[1] -= this.delta;
                            } else if (e.keyCode === 81)
                            {
                                camera.eye[2] += this.delta;
                            } else if (e.keyCode === 90)
                            {
                                camera.eye[2] -= this.delta;
                            } else if (e.keyCode === 70)
                            {
                                camera.center[0] -= this.delta;
                            } else if (e.keyCode === 72)
                            {
                                camera.center[0] += this.delta;
                            } else if (e.keyCode === 84)
                            {
                                camera.center[1] += this.delta;
                            } else if (e.keyCode === 71)
                            {
                                camera.center[1] -= this.delta;
                            } else if (e.keyCode === 82)
                            {
                                camera.center[2] += this.delta;
                            } else if (e.keyCode === 86)
                            {
                                camera.center[2] -= this.delta;
                            }

//                            console.log("eye:"+camera.eye[0]+","+camera.eye[1]+","+camera.eye[2]);
//                            console.log("center:"+camera.center[0]+","+camera.center[1]+","+camera.center[2]);

                            var camera = parentObject.cameras.camera;
                            var lastPart = camera.findObject("part_"+parentObject.lastIndexPart);

                            if (e.keyCode === 37)
                            {
                                lastPart.nextDirection = [-1.0, 0.0, 0.0];
                            } else if (e.keyCode === 39)
                            {
                                lastPart.nextDirection = [1.0, 0.0, 0.0];
                            } else if (e.keyCode === 38)
                            {
                                lastPart.nextDirection = [0.0, 1.0, 0.0];
                            } else if (e.keyCode === 40)
                            {
                                lastPart.nextDirection = [0.0, -1.0, 0.0];
                            }
                        },
                    }
                }
            },
            state: "init",
            nextScene: function()
            {
                return this.scenes.game;

                switch (this.state)
                {
                    case "init":
                        this.state = "game";
                        return this.scenes.intro;
                        break;
                    case "game":
                        return this.scenes.game;
                        break;

                }
            }
        });
    };
}
));
<commit_msg>Speed factor as variable.<commit_after>cns("sfme.userModules").defineUserModule("ssnake", "main",
(function()
{
    this.sfmeAPI = null;
    this.init = function(sfmeAPI_)
    {
        this.sfmeAPI = sfmeAPI_;

        this.sfmeAPI.defineScenes(
        {
            this_: this,
            scenes: {
                intro: {
                    resources: {
                        textures: {
                            testtext: {
                                type: "text",
                                width: 512,
                                height: 256,
                                textDefinition:
                                {
                                    text: "Super Snake",
                                    fontSize: 55,
                                    fontName: "Georgia",
                                    fillStyle: "white",
                                    strokeStyle: "#555555",
                                    lineWidth: 1,
                                    textBaseline: "middle",
                                    textPosition: [512/2,256/2]
                                }
                            }
                        }
                    },
                    cameras: {
                        camera: {
                            type: "ortho",
                            angle: 45.0,
                            ratio: "normal",
                            zNear: 0.1,
                            zFar: 100.0,
                            left: -50.0,
                            right: 50.0,
                            top: 50,
                            bottom: -50.0,
                            objects: {
                                quad: {
                                    shapeType: "quad_normal",
                                    width: 64.0,
                                    height: 32.0,
                                    position: [0.0, 0.0, -5.0],
                                    material: {
                                        blending: true,
                                        alpha: 1.0,
                                        name: "textured",
                                        textureMode: "attach",
                                        color: [1.0, 1.0, 1.0, 1.0],
                                    },
                                    animations: {
                                        showText: {
                                            animTime: 5000,
                                            onStartAnimation: function()
                                            {

                                            },
                                            onUpdateAnimation: function(parentObject,timePassed)
                                            {
                                                var t = timePassed / this.animTime;
                                                parentObject.material.alpha = t;
                                                return t > 1.0;
                                            },
                                            onEndAnimation: function(parentObject)
                                            {
                                                parentObject.material.alpha = 1.0;
                                                parentObject.parentScene.finishScene();
                                            }
                                        }
                                    },
                                    onCreated: function()
                                    {
                                        this.material.texture = this.parentScene.resources.textures.testtext;
                                    }
                                }
                            }
                        }
                    },
                    backgroundColor: [0.0, 0.0, 0.0, 1.0],
                    onStart: function()
                    {
                        console.log("Started");
                        this.cameras.camera.objects.quad.animations.showText.StartAnimation();
                    }
                },
                game: {
                    resources: {
                        textures: {
                            testtext: {
                                id: "testtext",
                                type: "text",
                                width: 512,
                                height: 64,
                                textDefinition:
                                {
                                    text: "Score:",
                                    fontSize: 55,
                                    fontName: "Georgia",
                                    fillStyle: "white",
                                    strokeStyle: "#555555",
                                    lineWidth: 1,
                                    textBaseline: "top",
                                    textAlign: "left",
                                    textPosition: [0,0]
                                }
                            },
                            hudBackground: {
                                type: "canvas",
                                backgroundColor:    function()
                                                    {
                                                        var context = this.context;
                                                        // add linear gradient
                                                        var grd = context.createLinearGradient(0, 0, 1, context.canvas.height);
                                                        grd.addColorStop(0, "#555555");
                                                        grd.addColorStop(0.5, "#222222");
                                                        grd.addColorStop(1, "#555555");
                                                        return grd;

                                                    },
                                width: 1,
                                height: 32,
                                /*
                                onDraw: function(context)
                                {
                                    // add linear gradient
                                    var grd = context.createLinearGradient(0, 0, context.canvas.width, context.canvas.height);
                                    // light blue
                                    grd.addColorStop(0, '#8ED6FF');
                                    // dark blue
                                    grd.addColorStop(1, '#004CB3');
                                    context.fillStyle = grd;
                                    context.fillRect(0, 0, context.canvas.width, context.canvas.height);
                                }
                                   */
                            }
                        }
                    },
                    boardModel:
                    {
                        getPositionForCell: function(vec)
                        {
                            // TODO: Implement real boards.
                            return [vec[0] * 1, vec[1]  * 1 , -15.0 + (vec[2] * 1)];
                        },
                        getNextCell: function(obj)
                        {
                            return [obj.boardCell[0] + obj.nextDirection[0],
                                    obj.boardCell[1] + obj.nextDirection[1],
                                    obj.boardCell[2] + obj.nextDirection[2]];
                        },
                        setNextCell: function(obj)
                        {
                            obj.boardCell = this.getNextCell(obj);
                        }
                    },
                    lastIndexPart: 0,
                    firstIndexPart: 0,
                    speedFactor: 1000,
                    cameras: {
                        camera2d:
                        {
                            type: "ortho",
                            angle: 45.0,
                            ratio: "normal",
                            zNear: 0.1,
                            zFar: 100.0,
                            left: -50.0,
                            right: 50.0,
                            top: 50,
                            bottom: -50.0,
                            objects: {
                                hudBackgroundObject: {
                                    shapeType: "quad_normal",
                                    width: 200.0,
                                    height: 10.0,
                                    position: [0.0, 45.0, -5.0],

                                    material: {
                                        name: "textured",
                                        textureMode: "attach",
                                        color: [1.0, 1.0, 1.0, 1.0],
                                    },
                                    onCreated: function()
                                    {
                                        this.material.texture = this.parentScene.resources.textures.hudBackground;
                                    }
                                },
                                scoreText: {
                                    shapeType: "quad_normal",
                                    width: 25.0,
                                    height: 10.0,
                                    position: [-37.5, 45.0, -4.0],

                                    material: {
                                        blending: true,
                                        alpha: 1.0,
                                        name: "textured",
                                        textureMode: "attach",
                                        color: [1.0, 1.0, 1.0, 1.0],
                                    },
                                    onCreated: function()
                                    {
                                        this.material.texture = this.parentScene.resources.textures.testtext;
                                    }
                                },
                            }
                        },
                        camera: {
                            type: "perspective",
                            lookAt: {
                                eye: [0.0, 0.0, 0.1],
                                center: [0.0, 0.0, -100.0],
                                vUp: [0.0, 1.0, 0.0]
                            },
                            angle: 45.0,
                            ratio: "normal",
                            zNear: 0.1,
                            zFar: 100.0,
                            objects: {
                                part_0: {
                                    shapeType: "cube",
                                    width: 1.0,
                                    height: 1.0,

                                    material: {
                                        name: "textured",
                                        textureMode: "ignore",
                                        color: [1.0, 0.0, 0.0, 1.0]
                                    },
                                    onUpdate: function(globalTiming)
                                    {
                                        this.partScale = [1.0,1.0,1.0];
                                        var scaleIndex = this.direction[0] !== 0 ? 0 : 1;
                                        this.partScale[scaleIndex] = (globalTiming.currentTime - this.creationTime) / this.parentScene.speedFactor;
                                        var createNew = this.partScale[scaleIndex] >= 1.00;
                                        if (createNew)
                                        {
                                            var remanent = this.partScale[scaleIndex] - 1.00;
                                            this.scale = [1.0, 1.0, 1.0];
                                            this.position = this.parentScene.boardModel.getPositionForCell(this.boardCell);

                                            var newPart = this.createNewPart();

                                            newPart.partScale = [1.0,1.0,1.0];
                                            newPart.direction = vec3.create(newPart.nextDirection);
                                            this.parentScene.boardModel.setNextCell(newPart);
                                            newPart.partScale[scaleIndex] = remanent;
                                            newPart.setFinalPosition();
                                        }
                                        this.setFinalPosition();
                                    },
                                    setFinalPosition: function()
                                    {
                                        var iPosition = this.parentScene.boardModel.getPositionForCell(this.boardCell);
                                        var inp = [
                                            iPosition[0] - (this.direction[0] / 2.0),
                                            iPosition[1] - (this.direction[1] / 2.0),
                                            iPosition[2] - (this.direction[2] / 2.0)
                                        ];
                                        var fp = [inp[0] + ((this.partScale[0] * this.direction[0]) / 2.0),
                                            inp[1] + ((this.partScale[1] * this.direction[1]) / 2.0),
                                            inp[2] + ((this.partScale[2] * this.direction[2]) / 2.0)];
                                        this.scale = vec3.create(this.partScale);
                                        this.position = fp;
                                    },
                                    createNewPart: function()
                                    {
                                        var newPart = this.addClone("part_"+(this.parentScene.lastIndexPart+1));
                                        this.onUpdate = null;
                                        this.parentScene.lastIndexPart++;
                                        newPart.setScale([1.0,1.0,1.0]);
                                        return newPart;
                                    }
                                }
                            }
                        }
                    },
                    backgroundColor: [0.0, 1.0, 0.0, 1.0],
                    onStart: function(globalTiming)
                    {
                        console.log("Started");
                        this.cameras.camera.objects.part_0.boardCell = [0,0,0];// = this.boardModel.getPositionForCell([0,0,0]);
                        this.cameras.camera.objects.part_0.direction = [1,0,0];
                        this.cameras.camera.objects.part_0.nextDirection = [1,0,0];
                        this.cameras.camera.objects.part_0.creationTime = globalTiming.currentTime;
                        this.score = 0;
                    },
                    onUpdate: function(globalTiminig)
                    {
                        this.resources.textures.testtext.textDefinition.setText("Score: "+this.score);
                    },
                    inputController:
                    {
                        delta:0.5,
                        onKeyDown: function(parentObject,e)
                        {
                            var camera = parentObject.cameras.camera.lookAt;
                            if (e.keyCode === 65)
                            {
                                camera.eye[0] -= this.delta;
                            } else if (e.keyCode === 68)
                            {
                                camera.eye[0] += this.delta;
                            } else if (e.keyCode === 87)
                            {
                                camera.eye[1] += this.delta;
                            } else if (e.keyCode === 83)
                            {
                                camera.eye[1] -= this.delta;
                            } else if (e.keyCode === 81)
                            {
                                camera.eye[2] += this.delta;
                            } else if (e.keyCode === 90)
                            {
                                camera.eye[2] -= this.delta;
                            } else if (e.keyCode === 70)
                            {
                                camera.center[0] -= this.delta;
                            } else if (e.keyCode === 72)
                            {
                                camera.center[0] += this.delta;
                            } else if (e.keyCode === 84)
                            {
                                camera.center[1] += this.delta;
                            } else if (e.keyCode === 71)
                            {
                                camera.center[1] -= this.delta;
                            } else if (e.keyCode === 82)
                            {
                                camera.center[2] += this.delta;
                            } else if (e.keyCode === 86)
                            {
                                camera.center[2] -= this.delta;
                            }

//                            console.log("eye:"+camera.eye[0]+","+camera.eye[1]+","+camera.eye[2]);
//                            console.log("center:"+camera.center[0]+","+camera.center[1]+","+camera.center[2]);

                            var camera = parentObject.cameras.camera;
                            var lastPart = camera.findObject("part_"+parentObject.lastIndexPart);

                            if (e.keyCode === 37)
                            {
                                lastPart.nextDirection = [-1.0, 0.0, 0.0];
                            } else if (e.keyCode === 39)
                            {
                                lastPart.nextDirection = [1.0, 0.0, 0.0];
                            } else if (e.keyCode === 38)
                            {
                                lastPart.nextDirection = [0.0, 1.0, 0.0];
                            } else if (e.keyCode === 40)
                            {
                                lastPart.nextDirection = [0.0, -1.0, 0.0];
                            }
                        },
                    }
                }
            },
            state: "init",
            nextScene: function()
            {
                return this.scenes.game;

                switch (this.state)
                {
                    case "init":
                        this.state = "game";
                        return this.scenes.intro;
                        break;
                    case "game":
                        return this.scenes.game;
                        break;

                }
            }
        });
    };
}
));
<|endoftext|>


<commit_before>/* kate-script
* author: Gregor Petrin
* license: BSD
* revision: 1
* kate-version: 3.4
* functions: emmetExpand, emmetWrap, emmetSelectTagPairInwards, emmetSelectTagPairOutwards, emmetMatchingPair, emmetToggleComment ,emmetNext, emmetPrev, emmetSelectNext, emmetSelectPrev, emmetDelete, emmetSplitJoinTab, emmetEvaluateMathExpression, emmetDecrementNumberBy1, emmetDecrementNumberBy10, emmetDecrementNumberBy01, emmetIncrementNumberBy1, emmetIncrementNumberBy10, emmetIncrementNumberBy01
*
*/

// required katepart js libraries
require ("range.js");
require ("emmet/lib.js");
require ("emmet/editor_interface.js");

function help(cmd)
{
	cmds = {
		"emmetExpand" : i18n("Expands the abbreviation using Emmet expressions; see http://code.google.com/p/zen-coding/wiki/ZenHTMLSelectorsEn"),
		"emmetWrap" : i18n("Wraps the selected text in XML tags constructed from the provided Emmet expression (defaults to div)."),
		"emmetMatchingPair" : i18n("Moves the caret to the current tag's pair"),
		"emmetSelectTagPairInwards" : i18n("Select contents of HTML/XML tag, moving inward on continious invocations"),
		"emmetSelectTagPairOutwards" : i18n("Select contents of HTML/XML tag, moving outwards on continious invocations"),
		"emmetNext" : i18n("Move to the next edit point (tag or empty attribute)."),
		"emmetPrev" : i18n("Move to the previous edit point (tag or empty attribute)."),
		"emmetSelectNext" : i18n("Select next edit point (tag or empty attribute)."),
		"emmetSelectPrev" : i18n("Select previous edit point (tag or empty attribute)."),
		"emmetToggleComment" : i18n("Toggle comment of current tag or CSS selector"),
		"emmetDelete" : i18n("Deletes tag under cursor"),
		"emmetSplitJoinTab" : i18n("Splits or joins a tag"),
		"emmetEvaluateMathExpression" : i18n("Evaluates a simple math expression"),
		"emmetDecrementNumberBy1" : i18n("Decrement number under cursor by 1"),
		"emmetDecrementNumberBy10" : i18n("Decrement number under cursor by 10"),
		"emmetDecrementNumberBy01" : i18n("Decrement number under cursor by 0.1"),
		"emmetIncrementNumberBy1" : i18n("Increment number under cursor by 1"),
		"emmetIncrementNumberBy10" : i18n("Increment number under cursor by 10"),
		"emmetIncrementNumberBy01" : i18n("Increment number under cursor by 0.1")
	}
	return cmds[cmd];
}

function action(cmd)
{
		var a = new Object();
		a.icon = "";
		a.category = i18n("Emmet");
		a.shortcut = "";
		a.interactive = false;
		if (cmd == "emmetExpand") {
			a.text = i18n("Expand abbreviation");
		} else if (cmd == "emmetWrap") {
			a.text = i18n("Wrap with tag");
			a.interactive = true;
		} else if (cmd == "emmetMatchingPair") {
			a.text = i18n("Move cursor to matching tag");
		} else if (cmd == "emmetSelectTagPairInwards") {
			a.text = i18n("Select HTML/XML tag contents inwards");
		} else if (cmd == "emmetSelectTagPairOutwards") {
			a.text = i18n("Select HTML/XML tag contents outwards");
		} else if (cmd == "emmetToggleComment") {
			a.text = i18n("Toggle comment");
		} else if (cmd == "emmetNext") {
			a.text = i18n("Go to next edit point");
		} else if (cmd == "emmetPrev") {
			a.text = i18n("Go to previous edit point");
		} else if (cmd == "emmetSelectNext") {
			a.text = i18n("Select next edit point");
		} else if (cmd == "emmetSelectPrev") {
			a.text = i18n("Select previous edit point");
		} else if (cmd == "emmetDelete") {
			a.text = i18n("Delete tag under cursor");
		} else if (cmd == "emmetSplitJoinTab") {
			a.text = i18n("Split or join a tag");
		} else if (cmd == "emmetEvaluateMathExpression") {
			a.text = i18n("Evaluate a simple math expression");
		} else if (cmd == "emmetDecrementNumberBy1") {
			a.text = i18n("Decrement number by 1");
		} else if (cmd == "emmetDecrementNumberBy10") {
			a.text = i18n("Decrement number by 10");
		} else if (cmd == "emmetDecrementNumberBy01") {
			a.text = i18n("Decrement number by 0.1");
		} else if (cmd == "emmetIncrementNumberBy1") {
			a.text = i18n("Increment number by 1");
		} else if (cmd == "emmetIncrementNumberBy10") {
			a.text = i18n("Increment number by 10");
		} else if (cmd == "emmetIncrementNumberBy01") {
			a.text = i18n("Increment number by 0.1");
		}
		return a;
}

//Returns the kate editor interface
function getInterface() {
	var kateInterface = new zen_editor(document, view);
	return kateInterface;
}

function emmetExpand() {
	emmet.require('actions').run('expand_abbreviation', getInterface());
}

function emmetWrap(par) {
	emmet.require('actions').run('wrap_with_abbreviation', getInterface(), par || 'div');
}

function emmetMatchingPair() {
	emmet.require('actions').run('matching_pair', getInterface());
}

function emmetSelectTagPairInwards() {
	emmet.require('actions').run('match_pair', getInterface());
}

function emmetSelectTagPairOutwards() {
	emmet.require('actions').run('match_pair', getInterface());
}

function emmetNext() {
	emmet.require('actions').run('next_edit_point', getInterface());
}

function emmetPrev() {
	emmet.require('actions').run('prev_edit_point', getInterface());
}

function emmetSelectNext() {
	emmet.require('actions').run('select_next_item', getInterface());
}

function emmetSelectPrev() {
	emmet.require('actions').run('select_previous_item', getInterface());
}

function emmetToggleComment() {
	emmet.require('actions').run('toggle_comment', getInterface());
}

function emmetDelete() {
	emmet.require('actions').run('remove_tag', getInterface());
}

function emmetSplitJoinTab() {
	emmet.require('actions').run('split_join_tag', getInterface());
}

function emmetEvaluateMathExpression() {
	emmet.require('actions').run('evaluate_math_expression', getInterface());
}

function emmetIncrementNumberBy1() {
	emmet.require('actions').run('increment_number_by_1', getInterface());
}

function emmetIncrementNumberBy10() {
	emmet.require('actions').run('increment_number_by_10', getInterface());
}

function emmetIncrementNumberBy01() {
	emmet.require('actions').run('increment_number_by_01', getInterface());
}

function emmetDecrementNumberBy1() {
	emmet.require('actions').run('decrement_number_by_1', getInterface());
}

function emmetDecrementNumberBy10() {
	emmet.require('actions').run('decrement_number_by_10', getInterface());
}

function emmetDecrementNumberBy01() {
	emmet.require('actions').run('decrement_number_by_01', getInterface());
}
<commit_msg>Fix typos<commit_after>/* kate-script
* author: Gregor Petrin
* license: BSD
* revision: 1
* kate-version: 3.4
* functions: emmetExpand, emmetWrap, emmetSelectTagPairInwards, emmetSelectTagPairOutwards, emmetMatchingPair, emmetToggleComment ,emmetNext, emmetPrev, emmetSelectNext, emmetSelectPrev, emmetDelete, emmetSplitJoinTab, emmetEvaluateMathExpression, emmetDecrementNumberBy1, emmetDecrementNumberBy10, emmetDecrementNumberBy01, emmetIncrementNumberBy1, emmetIncrementNumberBy10, emmetIncrementNumberBy01
*
*/

// required katepart js libraries
require ("range.js");
require ("emmet/lib.js");
require ("emmet/editor_interface.js");

function help(cmd)
{
	cmds = {
		"emmetExpand" : i18n("Expands the abbreviation using Emmet expressions; see http://code.google.com/p/zen-coding/wiki/ZenHTMLSelectorsEn"),
		"emmetWrap" : i18n("Wraps the selected text in XML tags constructed from the provided Emmet expression (defaults to div)."),
		"emmetMatchingPair" : i18n("Moves the caret to the current tag's pair"),
		"emmetSelectTagPairInwards" : i18n("Select contents of HTML/XML tag, moving inward on continuous invocations"),
		"emmetSelectTagPairOutwards" : i18n("Select contents of HTML/XML tag, moving outwards on continuous invocations"),
		"emmetNext" : i18n("Move to the next edit point (tag or empty attribute)."),
		"emmetPrev" : i18n("Move to the previous edit point (tag or empty attribute)."),
		"emmetSelectNext" : i18n("Select next edit point (tag or empty attribute)."),
		"emmetSelectPrev" : i18n("Select previous edit point (tag or empty attribute)."),
		"emmetToggleComment" : i18n("Toggle comment of current tag or CSS selector"),
		"emmetDelete" : i18n("Deletes tag under cursor"),
		"emmetSplitJoinTab" : i18n("Splits or joins a tag"),
		"emmetEvaluateMathExpression" : i18n("Evaluates a simple math expression"),
		"emmetDecrementNumberBy1" : i18n("Decrement number under cursor by 1"),
		"emmetDecrementNumberBy10" : i18n("Decrement number under cursor by 10"),
		"emmetDecrementNumberBy01" : i18n("Decrement number under cursor by 0.1"),
		"emmetIncrementNumberBy1" : i18n("Increment number under cursor by 1"),
		"emmetIncrementNumberBy10" : i18n("Increment number under cursor by 10"),
		"emmetIncrementNumberBy01" : i18n("Increment number under cursor by 0.1")
	}
	return cmds[cmd];
}

function action(cmd)
{
		var a = new Object();
		a.icon = "";
		a.category = i18n("Emmet");
		a.shortcut = "";
		a.interactive = false;
		if (cmd == "emmetExpand") {
			a.text = i18n("Expand abbreviation");
		} else if (cmd == "emmetWrap") {
			a.text = i18n("Wrap with tag");
			a.interactive = true;
		} else if (cmd == "emmetMatchingPair") {
			a.text = i18n("Move cursor to matching tag");
		} else if (cmd == "emmetSelectTagPairInwards") {
			a.text = i18n("Select HTML/XML tag contents inwards");
		} else if (cmd == "emmetSelectTagPairOutwards") {
			a.text = i18n("Select HTML/XML tag contents outwards");
		} else if (cmd == "emmetToggleComment") {
			a.text = i18n("Toggle comment");
		} else if (cmd == "emmetNext") {
			a.text = i18n("Go to next edit point");
		} else if (cmd == "emmetPrev") {
			a.text = i18n("Go to previous edit point");
		} else if (cmd == "emmetSelectNext") {
			a.text = i18n("Select next edit point");
		} else if (cmd == "emmetSelectPrev") {
			a.text = i18n("Select previous edit point");
		} else if (cmd == "emmetDelete") {
			a.text = i18n("Delete tag under cursor");
		} else if (cmd == "emmetSplitJoinTab") {
			a.text = i18n("Split or join a tag");
		} else if (cmd == "emmetEvaluateMathExpression") {
			a.text = i18n("Evaluate a simple math expression");
		} else if (cmd == "emmetDecrementNumberBy1") {
			a.text = i18n("Decrement number by 1");
		} else if (cmd == "emmetDecrementNumberBy10") {
			a.text = i18n("Decrement number by 10");
		} else if (cmd == "emmetDecrementNumberBy01") {
			a.text = i18n("Decrement number by 0.1");
		} else if (cmd == "emmetIncrementNumberBy1") {
			a.text = i18n("Increment number by 1");
		} else if (cmd == "emmetIncrementNumberBy10") {
			a.text = i18n("Increment number by 10");
		} else if (cmd == "emmetIncrementNumberBy01") {
			a.text = i18n("Increment number by 0.1");
		}
		return a;
}

//Returns the kate editor interface
function getInterface() {
	var kateInterface = new zen_editor(document, view);
	return kateInterface;
}

function emmetExpand() {
	emmet.require('actions').run('expand_abbreviation', getInterface());
}

function emmetWrap(par) {
	emmet.require('actions').run('wrap_with_abbreviation', getInterface(), par || 'div');
}

function emmetMatchingPair() {
	emmet.require('actions').run('matching_pair', getInterface());
}

function emmetSelectTagPairInwards() {
	emmet.require('actions').run('match_pair', getInterface());
}

function emmetSelectTagPairOutwards() {
	emmet.require('actions').run('match_pair', getInterface());
}

function emmetNext() {
	emmet.require('actions').run('next_edit_point', getInterface());
}

function emmetPrev() {
	emmet.require('actions').run('prev_edit_point', getInterface());
}

function emmetSelectNext() {
	emmet.require('actions').run('select_next_item', getInterface());
}

function emmetSelectPrev() {
	emmet.require('actions').run('select_previous_item', getInterface());
}

function emmetToggleComment() {
	emmet.require('actions').run('toggle_comment', getInterface());
}

function emmetDelete() {
	emmet.require('actions').run('remove_tag', getInterface());
}

function emmetSplitJoinTab() {
	emmet.require('actions').run('split_join_tag', getInterface());
}

function emmetEvaluateMathExpression() {
	emmet.require('actions').run('evaluate_math_expression', getInterface());
}

function emmetIncrementNumberBy1() {
	emmet.require('actions').run('increment_number_by_1', getInterface());
}

function emmetIncrementNumberBy10() {
	emmet.require('actions').run('increment_number_by_10', getInterface());
}

function emmetIncrementNumberBy01() {
	emmet.require('actions').run('increment_number_by_01', getInterface());
}

function emmetDecrementNumberBy1() {
	emmet.require('actions').run('decrement_number_by_1', getInterface());
}

function emmetDecrementNumberBy10() {
	emmet.require('actions').run('decrement_number_by_10', getInterface());
}

function emmetDecrementNumberBy01() {
	emmet.require('actions').run('decrement_number_by_01', getInterface());
}
<|endoftext|>


<commit_before>// Establish connection to database
const Sequelize = require('sequelize');
const sequelize = new Sequelize(process.env.PIXELECT_STAGING_DATABASE, process.env.PIXELECT_STAGING_USER, process.env.PIXELECT_STAGING_PASSWORD, {
  host: process.env.PIXELECT_STAGING_HOST,
  port: process.env.PIXELECT_STAGING_PORT,
  dialect: 'mysql',
  pool: {
    max: 10,
    min: 2,
    idle: 10000
  }
});

// Test connection to database
sequelize
  .authenticate()
  .then(() => {
    console.log('Successfully connected to database.');
  })
  .catch(err => {
    console.error('Unable to connect to database:', err);
  });

// User table
const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  lastName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  facebookId: {
    type: Sequelize.STRING,
    allowNull: false
  }
});

// Group table
const Group = sequelize.define('group', {
});
Group.belongsTo(User, {
  foreignKey: {
    name: 'owner',
    allowNull: false
  },
  onDelete: 'CASCADE'
});

// User-Group table
Group.belongsToMany(User, {through: 'UserGroup'});
User.belongsToMany(Group, {through: 'UserGroup'});

// API stuff for future
// To create User
// User.create({
//   firstName: 'Ana',
//   lastName: 'Chua',
//   facebookId: '123'
// });

// To create Group
// Group.create({
//   owner: 1
// });

// To add User to Group
// User.findById(3).then(user => {
//   Group.findById(1).then(group => {
//     user.setGroups([group]);
//   });
// });<commit_msg>Add Photo and Vote<commit_after>// Establish connection to database
const Sequelize = require('sequelize');
const sequelize = new Sequelize(process.env.PIXELECT_STAGING_DATABASE, process.env.PIXELECT_STAGING_USER, process.env.PIXELECT_STAGING_PASSWORD, {
  host: process.env.PIXELECT_STAGING_HOST,
  port: process.env.PIXELECT_STAGING_PORT,
  dialect: 'mysql',
  pool: {
    max: 10,
    min: 2,
    idle: 10000
  }
});

// Test connection to database
sequelize
  .authenticate()
  .then(() => {
    console.log('Successfully connected to database.');
  })
  .catch(err => {
    console.error('Unable to connect to database:', err);
  });

// User table
const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  lastName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  facebookId: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true
  }
});

// Group table
const Group = sequelize.define('group', {
});
Group.belongsTo(User, {
  foreignKey: {
    name: 'owner',
    allowNull: false
  },
  onDelete: 'RESTRICT'
});

// User-Group table
Group.belongsToMany(User, {through: 'user_group'});
User.belongsToMany(Group, {through: 'user_group'});

// Photo table
const Photo = sequelize.define('photo', {
  link: {
    type: Sequelize.STRING,
    allowNull: false
  }
});
Photo.belongsTo(User, {
  foreignKey: {
    allowNull: false
  },
  onDelete: 'RESTRICT'
});
Photo.belongsTo(Group, {
  foreignKey: {
    allowNull: false
  },
  onDelete: 'RESTRICT'
});

// Vote table
const Vote = sequelize.define('vote', {
  isValid: {
    type: Sequelize.BOOLEAN,
    allowNull: false,
    defaultValue: true
  }
});
Photo.belongsToMany(User, {through: 'vote'});
User.belongsToMany(Photo, {through: 'vote'});

// sequelize.sync();

// // API stuff for future
// // To create User
// User.create({
//   firstName: 'Ana',
//   lastName: 'Chua',
//   facebookId: '123'
// });
// User.create({
//   firstName: 'Benny',
//   lastName: 'Chua',
//   facebookId: '456'
// });

// // To create Group
// Group.create({
//   owner: 1
// });

// // To add User to Group
// User.findById(1).then(user => {
//   Group.findById(1).then(group => {
//     user.setGroups([group]);
//   });
// });
// User.findById(2).then(user => {
//   Group.findById(1).then(group => {
//     user.setGroups([group]);
//   });
// });

// // To create Photo
// Photo.create({
//   link: 'http://blahblah',
//   userId: 1,
//   groupId: 1
// });

// To create Vote
// Vote.create({
//   userId: 1,
//   photoId: 1,
//   isValid: false
// });
// Vote.create({
//   userId: 2,
//   photoId: 1
// });<|endoftext|>