<commit_before>'use strict';

module.exports = function(grunt) {

	var pkg, bower, taskName, name;

	pkg = grunt.file.readJSON('package.json');
	bower = grunt.file.readJSON('bower.json');
	name = pkg.name.toLowerCase();

	grunt.initConfig({
		pkg: pkg,
		bowerJSON: bower,
		banner:	'/*!\n' +
						' * <%= pkg.name %> v<%= pkg.version %>\n' +
						' * Website <%= pkg.website %>\n' +
						' * Copyright 2015 <%= pkg.author %>\n' +
						' * The <%= pkg.license %> License\n' +
						' */\n' +
						'/*!\n' +
						' * Bootstrap v<%= twbs.version %> (<%= twbs.homepage %>)\n' +
						' * Copyright 2011-<%= grunt.template.today("yyyy") %> <%= twbs.author %>\n' +
						' * Licensed under the <%= twbs.license %> license\n' +
						' */\n',
		// bannerの調整
		replace: {
			// バナーの追加
			banner: {
				src: ['dist/css/bootstrap**.css'],
				dest: 'dist/css/',
				replacements: [
					{
						from: '@charset "UTF-8";',
						to: '@charset "UTF-8";\n<%= banner %>'
					}
				]
			}
		},
		// cssmin
		cssmin: {
			minify: {
				expand: true,
				cwd: 'dist/css/',
				src: ['bootstrap.css'],
				dest: 'dist/css/',
				ext: '.min.css',
				options: {
					advanced: false,
					keepSpecialComments: '*',
					compatibility: 'ie8',
				}
			}
		},
		// SCSSのコンパイル
		sass: {
			options: {
				sourcemap: 'none',
				unixNewlines: true,
				style: 'expanded',
				bundleExec: true,
				loadPath: ['bower_components/bootstrap-sass/assets/stylesheets/']
			},
			bootstrap: {
				files: [{
					expand: true,
					cwd: 'scss',
					src: ['**/*.scss'],
					dest: 'dist/css/',
					ext: '.css'
				}]
			},
			assets: {
				options: {
					loadPath: ['scss/']
				},
				files: [{
					expand: true,
					cwd: 'src/scss',
					src: ['**/*.scss'],
					dest: 'dist/assets/css/',
					ext: '.css'
				}]
			}
		},
		csscomb: {
			options: {
				config: 'bower_components/bootstrap/less/.csscomb.json'
			},
			bootstrap: {
				files: {
					'dist/css/bootstrap.css': ['dist/css/bootstrap.css']
				}
			},
			assets: {
				expand: true,
				cwd: 'dist/assets/css/',
				src: ['**/*.css'],
				dest: 'dist/assets/css',
				ext: '.css'
			}
		},
		autoprefixer: {
			bootstrap: {
				files: {
					'dist/css/bootstrap.css': ['dist/css/bootstrap.css']
				}
			},
			assets: {
				expand: true,
				cwd: 'dist/assets/css/',
				src: ['**/*.css'],
				dest: 'dist/assets/css',
				ext: '.css'
			}
		},
		// SCSSのLinter
		scsslint: {
			options: {
				bundleExec: true,
				config: '.scss-lint.yml',
				reporterOutput: null,
				colorizeOutput: true
			},
			bootstrap: ['scss/**/*.scss'],
			assets: ['src/scss/**/*.scss']
		},
		// clean
		clean: {
			build: {
				src: ['bower_components/**/*', 'dist/css/**/*', 'dist/js/**/*', 'dist/fonts/**/*']
			}
		},
		// bowerのインストール
		bower: {
			install: {
				options: {
					targetDir: 'dist/',
					layout: function(type, component, source) {
						return type;
					}
				}
			}
		},
		// ファイル更新監視
		watch: {
			// 自動コンパイル
			bootstrap: {
				files: ['scss/**/*.scss', 'src/scss/**/*.scss'],
				tasks: ['scsslint', 'css']
			}
		},
		// テストサーバ
		connect: {
			server: {
				options: {
					port: 8000,
					hostname: '*',
					base: 'dist'
				}
			}
		},
		compress: {
			main: {
				options: {
					archive: 'data/bootstrap-'+ name +'-'+ pkg.version +'-dist.zip'
				},
				files: [
					{
						//CSS
						expand: true,
						cwd: "dist/css/",
						src: ["bootstrap**.css"],
						dest: name +"/css"
					},
					{
						// Font
						expand: true,
						cwd: "dist/fonts/",
						src: ["**/*"],
						dest: name +"/fonts"
					},
					{
						// JavaScript
						expand: true,
						cwd: "dist/js/",
						src: ["bootstrap.**js"],
						dest: name +"/js"
					},
					{
						// Sample html
						expand: true,
						cwd: "dist/",
						src: ["bootstrap.html"],
						dest: name
					},
					{
						// README
						src: ["README.md"],
						dest: name
					}
				]
			}
		}
	});

	// GruntFile.jsに記載されているパッケージを自動読み込み
	for(taskName in pkg.devDependencies) {
		if(taskName.substring(0, 6) == 'grunt-') {
			grunt.loadNpmTasks(taskName);
		}
	}

	// 本家Bootstrapのautoprefixerの設定を読み込む
	grunt.task.registerTask('getTwbsConfig', 'Get config from bootstrap', function() {
		try {
			var configBridge = grunt.file.readJSON('bower_components/bootstrap/grunt/configBridge.json');
			var twbsPkg = grunt.file.readJSON('bower_components/bootstrap/package.json');
			grunt.verbose.ok();
		} catch (e) {
			grunt.verbose.or.write("Loading Bootstrap config...").error().error(e.message);
			grunt.fail.fatal('Do you install bower component? Try "grunt bower:install"');
		}
		grunt.config.merge({
			twbs: twbsPkg,
			autoprefixer: {
				options: {
					browsers: configBridge.config.autoprefixerBrowsers
				}
			}
		});
	});

	// テスト
	grunt.registerTask('test', ['scsslint']);

	// CSSビルド
	grunt.registerTask('css', ['sass', 'autoprefixer']);

	// 最適化
	grunt.registerTask('optimize', ['csscomb', 'cssmin:minify']);

	// 開発用
	grunt.registerTask('server', ['bower:install', 'getTwbsConfig', 'test', 'css', 'connect', 'watch']);

	// ビルドタスク
	grunt.registerTask('build', ['clean:build', 'bower:install', 'getTwbsConfig', 'test', 'css', 'optimize', 'replace:banner']);

	// 配布用パッケージ作成
	grunt.registerTask('package', ['build', 'compress:main']);

	grunt.registerTask('eatwarnings', function() {
		grunt.warn = grunt.fail.warn = function(warning) {
			grunt.log.error(warning);
		};
	});

};
<commit_msg>Honoka ForkでHonokaの著作権表示をするように<commit_after>'use strict';

module.exports = function(grunt) {

	var pkg, bower, taskName, name;

	pkg = grunt.file.readJSON('package.json');
	bower = grunt.file.readJSON('bower.json');
	name = pkg.name.toLowerCase();

	grunt.initConfig({
		pkg: pkg,
		bowerJSON: bower,
		banner:	'/*!\n' +
						' * <%= pkg.name %> v<%= pkg.version %>\n' +
						' * Website <%= pkg.website %>\n' +
						' * Copyright 2015 <%= pkg.author %>\n' +
						' * The <%= pkg.license %> License\n' +
						(
							pkg.name !== "Honoka" ?
								' * Based on Honoka (http://honokak.osaka/) by windyakin\n'
							:
								''
						) +
						' */\n' +
						'/*!\n' +
						' * Bootstrap v<%= twbs.version %> (<%= twbs.homepage %>)\n' +
						' * Copyright 2011-<%= grunt.template.today("yyyy") %> <%= twbs.author %>\n' +
						' * Licensed under the <%= twbs.license %> license\n' +
						' */\n',
		// bannerの調整
		replace: {
			// バナーの追加
			banner: {
				src: ['dist/css/bootstrap**.css'],
				dest: 'dist/css/',
				replacements: [
					{
						from: '@charset "UTF-8";',
						to: '@charset "UTF-8";\n<%= banner %>'
					}
				]
			}
		},
		// cssmin
		cssmin: {
			minify: {
				expand: true,
				cwd: 'dist/css/',
				src: ['bootstrap.css'],
				dest: 'dist/css/',
				ext: '.min.css',
				options: {
					advanced: false,
					keepSpecialComments: '*',
					compatibility: 'ie8',
				}
			}
		},
		// SCSSのコンパイル
		sass: {
			options: {
				sourcemap: 'none',
				unixNewlines: true,
				style: 'expanded',
				bundleExec: true,
				loadPath: ['bower_components/bootstrap-sass/assets/stylesheets/']
			},
			bootstrap: {
				files: [{
					expand: true,
					cwd: 'scss',
					src: ['**/*.scss'],
					dest: 'dist/css/',
					ext: '.css'
				}]
			},
			assets: {
				options: {
					loadPath: ['scss/']
				},
				files: [{
					expand: true,
					cwd: 'src/scss',
					src: ['**/*.scss'],
					dest: 'dist/assets/css/',
					ext: '.css'
				}]
			}
		},
		csscomb: {
			options: {
				config: 'bower_components/bootstrap/less/.csscomb.json'
			},
			bootstrap: {
				files: {
					'dist/css/bootstrap.css': ['dist/css/bootstrap.css']
				}
			},
			assets: {
				expand: true,
				cwd: 'dist/assets/css/',
				src: ['**/*.css'],
				dest: 'dist/assets/css',
				ext: '.css'
			}
		},
		autoprefixer: {
			bootstrap: {
				files: {
					'dist/css/bootstrap.css': ['dist/css/bootstrap.css']
				}
			},
			assets: {
				expand: true,
				cwd: 'dist/assets/css/',
				src: ['**/*.css'],
				dest: 'dist/assets/css',
				ext: '.css'
			}
		},
		// SCSSのLinter
		scsslint: {
			options: {
				bundleExec: true,
				config: '.scss-lint.yml',
				reporterOutput: null,
				colorizeOutput: true
			},
			bootstrap: ['scss/**/*.scss'],
			assets: ['src/scss/**/*.scss']
		},
		// clean
		clean: {
			build: {
				src: ['bower_components/**/*', 'dist/css/**/*', 'dist/js/**/*', 'dist/fonts/**/*']
			}
		},
		// bowerのインストール
		bower: {
			install: {
				options: {
					targetDir: 'dist/',
					layout: function(type, component, source) {
						return type;
					}
				}
			}
		},
		// ファイル更新監視
		watch: {
			// 自動コンパイル
			bootstrap: {
				files: ['scss/**/*.scss', 'src/scss/**/*.scss'],
				tasks: ['scsslint', 'css']
			}
		},
		// テストサーバ
		connect: {
			server: {
				options: {
					port: 8000,
					hostname: '*',
					base: 'dist'
				}
			}
		},
		compress: {
			main: {
				options: {
					archive: 'data/bootstrap-'+ name +'-'+ pkg.version +'-dist.zip'
				},
				files: [
					{
						//CSS
						expand: true,
						cwd: "dist/css/",
						src: ["bootstrap**.css"],
						dest: name +"/css"
					},
					{
						// Font
						expand: true,
						cwd: "dist/fonts/",
						src: ["**/*"],
						dest: name +"/fonts"
					},
					{
						// JavaScript
						expand: true,
						cwd: "dist/js/",
						src: ["bootstrap.**js"],
						dest: name +"/js"
					},
					{
						// Sample html
						expand: true,
						cwd: "dist/",
						src: ["bootstrap.html"],
						dest: name
					},
					{
						// README
						src: ["README.md"],
						dest: name
					}
				]
			}
		}
	});

	// GruntFile.jsに記載されているパッケージを自動読み込み
	for(taskName in pkg.devDependencies) {
		if(taskName.substring(0, 6) == 'grunt-') {
			grunt.loadNpmTasks(taskName);
		}
	}

	// 本家Bootstrapのautoprefixerの設定を読み込む
	grunt.task.registerTask('getTwbsConfig', 'Get config from bootstrap', function() {
		try {
			var configBridge = grunt.file.readJSON('bower_components/bootstrap/grunt/configBridge.json');
			var twbsPkg = grunt.file.readJSON('bower_components/bootstrap/package.json');
			grunt.verbose.ok();
		} catch (e) {
			grunt.verbose.or.write("Loading Bootstrap config...").error().error(e.message);
			grunt.fail.fatal('Do you install bower component? Try "grunt bower:install"');
		}
		grunt.config.merge({
			twbs: twbsPkg,
			autoprefixer: {
				options: {
					browsers: configBridge.config.autoprefixerBrowsers
				}
			}
		});
	});

	// テスト
	grunt.registerTask('test', ['scsslint']);

	// CSSビルド
	grunt.registerTask('css', ['sass', 'autoprefixer']);

	// 最適化
	grunt.registerTask('optimize', ['csscomb', 'cssmin:minify']);

	// 開発用
	grunt.registerTask('server', ['bower:install', 'getTwbsConfig', 'test', 'css', 'connect', 'watch']);

	// ビルドタスク
	grunt.registerTask('build', ['clean:build', 'bower:install', 'getTwbsConfig', 'test', 'css', 'optimize', 'replace:banner']);

	// 配布用パッケージ作成
	grunt.registerTask('package', ['build', 'compress:main']);

	grunt.registerTask('eatwarnings', function() {
		grunt.warn = grunt.fail.warn = function(warning) {
			grunt.log.error(warning);
		};
	});

};
<|endoftext|>


<commit_before>/**
_enyo.Object_ implements the property publishing system.
Published properties are declared by providing a _published_ property within a call to
_enyo.kind_. Getter and setter methods are automatically generated for
properties declared this way. Also, setters for published properties
trigger _<propertyName>Changed_ methods by convention.

	enyo.kind({
		name: "MyObject",
		kind: enyo.Object,

		// declare 'published' properties
		published: {
			myValue: 3
		},

		// these methods will be automatically generated:
		//	getMyValue: function() ...
		//	setMyValue: function(inValue) ...

		// optional method that is called whenever setMyValue is called
		myValueChanged: function(inOldValue) {
			this.delta = this.myValue - inOldValue;
		}
	});

In the above example, _myValue_ becomes a regular property on the MyObject
prototype (with a default value of 3), and the getter and setter methods are generated
as noted in the comments.

	myobj = new MyObject();
	var x = myobj.getMyValue(); // x gets 3

You may choose to declare a _changed_ method to observe set calls on a property.
The _myValueChanged_ method in the example above is called whenever _setMyValue_ is called.

	myobj.setMyValue(7); // myValue becomes 7; myValueChanged side-effect sets delta to 4

_Changed_ methods are called whenever setters are invoked, whether the actual value has changed
or not.

Published properties are stored as regular properties on the object prototype, so it's possible
to query or set their values directly (changed methods are not called if you set a property directly).

	var x = myobj.myValue;

enyo.Object also provides some utility functions for its subkinds.
*/
enyo.kind({
	name: "enyo.Object",
	//* @protected
	constructor: function() {
		enyo._objectCount++;
	},
	_setProperty: function(n, v, cf) {
		if (this[cf]) {
			var old = this[n];
			this[n] = v;
			if (old !== v) {
				this[cf](old);
			}
		} else {
			this[n] = v;
		}
	},
	//* @public
	destroyObject: function(inName) {
		if (this[inName] && this[inName].destroy) {
			this[inName].destroy();
		}
		this[inName] = null;
	},
	getProperty: function(n) {
		return this[n];
	},
	setProperty: function(n, v) {
		var setter = "set" + enyo.cap(n);
		if (this[setter]) {
			this[setter](v);
		} else {
			this._setProperty(n, v, n + "Changed");
		}
	},
	/**
		Sends a log message to the console, prepended with the name of the kind and method from which log was invoked. Multiple arguments are coerced to String and joined with spaces.

			enyo.kind({
				name: "MyObject",
				kind: enyo.Object,
				hello: function() {
					this.log("says", "hi");
					// shows in the console: MyObject.hello: says hi
				}
			});
	*/
	log: function() {
		enyo.logging.log("log", [arguments.callee.caller.nom + ": "].concat(enyo.cloneArray(arguments)));
	},
	//* Same as _log_, except uses the console's warn method (if it exists).
	warn: function() {
		this._log("warn", arguments);
	},
	//* Same as _log_, except uses the console's error method (if it exists).
	error: function() {
		this._log("error", arguments);
	},
	//* @protected
	_log: function(inMethod, inArgs) {
		if (enyo.logging.shouldLog(inMethod)) {
			try {
				throw new Error();
			} catch(x) {
				enyo.logging._log(inMethod, [inArgs.callee.caller.nom + ": "].concat(enyo.cloneArray(inArgs)));
				console.log(x.stack);
			}
		}
	}
});

//* @protected

enyo._objectCount = 0;

enyo.Object.subclass = function(ctor, props) {
	this.publish(ctor, props);
};

enyo.Object.publish = function(ctor, props) {
	var pp = props.published;
	if (pp) {
		var cp = ctor.prototype;
		for (var n in pp) {
			enyo.Object.addGetterSetter(n, pp[n], cp);
		}
	}
};

enyo.Object.addGetterSetter = function(inName, inValue, inProto) {
	var priv_n = inName;
	inProto[priv_n] = inValue;
	//
	var cap_n = enyo.cap(priv_n);
	var get_n = "get" + cap_n;
	if (!inProto[get_n]) {
		inProto[get_n] = function() {
			return this.getProperty(priv_n);
		};
	}
	//
	var set_n = "set" + cap_n;
	var change_n = priv_n + "Changed";
	if (!inProto[set_n]) {
		inProto[set_n] = function(v) {
			this._setProperty(priv_n, v, change_n);
		};
	}
};
<commit_msg>Slight factoring of _setProperty into _setProperty and setPropertyValue<commit_after>/**
_enyo.Object_ implements the property publishing system.
Published properties are declared by providing a _published_ property within a call to
_enyo.kind_. Getter and setter methods are automatically generated for
properties declared this way. Also, setters for published properties
trigger _<propertyName>Changed_ methods by convention.

	enyo.kind({
		name: "MyObject",
		kind: enyo.Object,

		// declare 'published' properties
		published: {
			myValue: 3
		},

		// these methods will be automatically generated:
		//	getMyValue: function() ...
		//	setMyValue: function(inValue) ...

		// optional method that is called whenever setMyValue is called
		myValueChanged: function(inOldValue) {
			this.delta = this.myValue - inOldValue;
		}
	});

In the above example, _myValue_ becomes a regular property on the MyObject
prototype (with a default value of 3), and the getter and setter methods are generated
as noted in the comments.

	myobj = new MyObject();
	var x = myobj.getMyValue(); // x gets 3

You may choose to declare a _changed_ method to observe set calls on a property.
The _myValueChanged_ method in the example above is called whenever _setMyValue_ is called.

	myobj.setMyValue(7); // myValue becomes 7; myValueChanged side-effect sets delta to 4

_Changed_ methods are called whenever setters are invoked, whether the actual value has changed
or not.

Published properties are stored as regular properties on the object prototype, so it's possible
to query or set their values directly (changed methods are not called if you set a property directly).

	var x = myobj.myValue;

enyo.Object also provides some utility functions for its subkinds.
*/
enyo.kind({
	name: "enyo.Object",
	//* @protected
	constructor: function() {
		enyo._objectCount++;
	},
	setPropertyValue: function(n, v, cf) {
		if (this[cf]) {
			var old = this[n];
			this[n] = v;
			this[cf](old);
		} else {
			this[n] = v;
		}
	},
	_setProperty: function(n, v, cf) {
		this.setPropertyValue(n, v, (this[n] !== v) && cf);
	},
	//* @public
	destroyObject: function(inName) {
		if (this[inName] && this[inName].destroy) {
			this[inName].destroy();
		}
		this[inName] = null;
	},
	getProperty: function(n) {
		return this[n];
	},
	setProperty: function(n, v) {
		var setter = "set" + enyo.cap(n);
		if (this[setter]) {
			this[setter](v);
		} else {
			this._setProperty(n, v, n + "Changed");
		}
	},
	/**
		Sends a log message to the console, prepended with the name of the kind and method from which log was invoked. Multiple arguments are coerced to String and joined with spaces.

			enyo.kind({
				name: "MyObject",
				kind: enyo.Object,
				hello: function() {
					this.log("says", "hi");
					// shows in the console: MyObject.hello: says hi
				}
			});
	*/
	log: function() {
		enyo.logging.log("log", [arguments.callee.caller.nom + ": "].concat(enyo.cloneArray(arguments)));
	},
	//* Same as _log_, except uses the console's warn method (if it exists).
	warn: function() {
		this._log("warn", arguments);
	},
	//* Same as _log_, except uses the console's error method (if it exists).
	error: function() {
		this._log("error", arguments);
	},
	//* @protected
	_log: function(inMethod, inArgs) {
		if (enyo.logging.shouldLog(inMethod)) {
			try {
				throw new Error();
			} catch(x) {
				enyo.logging._log(inMethod, [inArgs.callee.caller.nom + ": "].concat(enyo.cloneArray(inArgs)));
				console.log(x.stack);
			}
		}
	}
});

//* @protected

enyo._objectCount = 0;

enyo.Object.subclass = function(ctor, props) {
	this.publish(ctor, props);
};

enyo.Object.publish = function(ctor, props) {
	var pp = props.published;
	if (pp) {
		var cp = ctor.prototype;
		for (var n in pp) {
			enyo.Object.addGetterSetter(n, pp[n], cp);
		}
	}
};

enyo.Object.addGetterSetter = function(inName, inValue, inProto) {
	var priv_n = inName;
	inProto[priv_n] = inValue;
	//
	var cap_n = enyo.cap(priv_n);
	var get_n = "get" + cap_n;
	if (!inProto[get_n]) {
		inProto[get_n] = function() {
			return this.getProperty(priv_n);
		};
	}
	//
	var set_n = "set" + cap_n;
	var change_n = priv_n + "Changed";
	if (!inProto[set_n]) {
		inProto[set_n] = function(v) {
			this._setProperty(priv_n, v, change_n);
		};
	}
};
<|endoftext|>


<commit_before>define(function(require) {
var Backbone = require('backbone'),
    ContentView = require('streamhub-backbone/views/ContentView'),
    FeedTickerView = require('streamhub-ticker/views/FeedTickerView');

var TickerView = Backbone.View.extend(
{
    initialize: function (opts) {
        this.$el.addClass(this.className);
        this.$el.hide();
        this.feedCollection = opts.feedCollection;
        this.childViews = {};

        this.sources = opts.sources || {};

        this.collection.on('add', this._insertItem, this);
        this.collection.on('initialDataLoaded', this.render, this);

        if (this.feedCollection) {
            this.feedCollection.on('add', this._addFeedItem, this);
        }
    },
    className: "hub-TickerView",
    render: function () {
        // todo : create sub divs
        this.$el.fadeIn();
    }
});

TickerView.prototype._insertItem = function (item, col) {
    var itemEl = $(document.createElement('div'));
    var feedEl = $(document.createElement('div'));
    itemEl.append(feedEl);
    var contentEl = $(document.createElement('div'));
    itemEl.append(contentEl);

    var json = item.toJSON();

    if (!json.author) { return; }

    itemEl
      .addClass('hub-item')
      .attr('data-hub-contentid', json.id)
      .attr('data-hub-createdAt', item.get('createdAt'))
      .attr('data-hub-source-id', item.get('sourceId'));

    feedEl.addClass('item-feed-view');
    contentEl.addClass('item-content-view');
    contentEl.addClass($('
' + item.get('bodyHtml') + '
').children().first().attr('class'));

    var contentView = new ContentView({
        model: item,
        el: contentEl
    });

    var subCol = new Backbone.Collection();
    subCol.comparator = function(i) { return i.get('createdAt');};

    var feedView = new FeedTickerView({
        collection: subCol,
        el: feedEl,
        sources: this.sources
    });
    feedView.render();

    this.childViews[item.get('createdAt')] = {feedView:feedView, item: item};

    this._animateAdd(itemEl, col, col.indexOf(item));

    //this._rebalanceFeedItems(item, col);

    return itemEl;
};

TickerView.prototype._animateAdd = function(itemEl, col, index) {
    var prev = col.at(index-1);
    var next = col.at(index+1);
    var origScrollWidth = this.$el[0].scrollWidth;

    if (col._initialized) {
        this.$el.append(itemEl);
    } else {
    	this.$el.prepend(itemEl);
    }
    /*    prevEl = this.$el.find('.hub-item[data-hub-contentid="' + prev.get('id') + '"]');
	    if (col._initialized) { debugger;}
        itemEl.insertAfter(prevEl);
    }*/
    var newScrollWidth = this.$el[0].scrollWidth;
    var diff = newScrollWidth - origScrollWidth;

    if (!this.paused && col._initialized) {
        this.$el.animate({
            scrollLeft: this.$el.scrollLeft() + diff
        }, 500);
    } else if (!col._initialized) {
        this.$el.scrollLeft(this.$el.scrollLeft() + diff);
    }
};

TickerView.prototype._rebalanceFeedItems = function(item, col) {
    var index = col.indexOf(item);
    var createdAt = item.get('createdAt');
    var feedCol = this.childViews[createdAt].feedView.collection;

    // this is going to trace backwards, then forewards along the the feed items,
    // in each collection, moving feed item that need to be in this newly added item's collection
    var prev;
    var prevFeedItem;
    var prevCursor = 0;
    while (!prevFeedItem || prevFeedItem.get('createdAt') > createdAt) {
        while (!prevFeedItem) {
            prev = null;
            prevCursor++;
            var prevItem = col.at(index-prevCursor);
            if (prevItem) {
                prev = this.childViews[prevItem.get('id')];
            }
            if (!prev) { break; }
            prevFeedItem = prev.item.collection.last()
        }
        if (!prev) { break; }
        if (prevFeedItem.get('createdAt') > createdAt) {
            console.log("Shuffled from prev: ", prevFeedItem.get('createdAt'), ' > ', createdAt);
            prev.item.collection.remove(prevFeedItem);
            feedCol.add(prevFeedItem);
        }
        prevFeedItem = prev.item.collection.last()
    }

    var next;
    var nextFeedItem;
    var nextCursor = 0;

    while (!nextFeedItem || nextFeedItem.get('createdAt') < createdAt) {
        while (!nextFeedItem) {
            next = null;
            nextCursor++;
            var nextItem = col.at(index+nextCursor);
            if (nextItem) {
                next = this.childViews[nextItem.get('id')];
            }
            if (!next) { break; }
            nextFeedItem = next.item.collection.first()
        }
        if (!next) { break; }
        if (nextFeedItem.get('createdAt') < createdAt) {
            console.log("Shuffled from next: ", nextFeedItem.get('createdAt'), ' < ', createdAt);
            next.item.collection.remove(nextFeedItem);
            feedCol.add(nextFeedItem);
        }
        nextFeedItem = next.item.collection.first()
    }
};

TickerView.prototype._addFeedItem = function(item, col) {
    // parse the tree
    var itemCreatedAt = item.get('createdAt');
    var keys = Object.keys(this.childViews).sort();

    if (keys.length == 0) {
        return;
    }

    for (var i = 0; i < keys.length; i++) {
        if (itemCreatedAt > keys[i] && (i == keys.length - 1 || itemCreatedAt < keys[i+1])) {
            var feedView = this.childViews[keys[i]].feedView;
            feedView.collection.add(item);
            break;
        }
    }

};

return TickerView;
});
<commit_msg>finalized ticker protocol<commit_after>define(function(require) {
var Backbone = require('backbone'),
    ContentView = require('streamhub-backbone/views/ContentView'),
    FeedTickerView = require('streamhub-ticker/views/FeedTickerView');

var TickerView = Backbone.View.extend(
{
    initialize: function (opts) {
        this.$el.addClass(this.className);
        this.$el.hide();
        this.feedCollection = opts.feedCollection;
        this.childViews = {};
        this.metaElement = opts.metaElement;

        this.sources = opts.sources || {};

        this.collection.on('add', this._insertItem, this);
        this.collection.on('initialDataLoaded', this.render, this);

        if (this.feedCollection) {
            this.feedCollection.on('add', this._addFeedItem, this);
        }
    },
    className: "hub-TickerView",
    render: function () {
        // todo : create sub divs
        this.$el.fadeIn();
    }
});

TickerView.prototype._insertItem = function (item, col) {
    if (!item.get('author')) { return; }

    var feedEl = $(document.createElement('div'));
    feedEl.addClass('item-feed-view');

    var contentEl = $(document.createElement('div'));
    contentEl.addClass('item-content-view');

    var itemEl = $(document.createElement('div'));
    itemEl.append(feedEl);
    itemEl.append(contentEl);

    var itemMetaEl = $('
' + item.get('bodyHtml') + '
').find(this.metaElement);
	var	itemMeta = {};
	try { itemMeta = JSON.parse(itemMetaEl.text()); } catch (ex) {}

    itemEl
      .addClass('hub-item')
      .attr('data-hub-contentid', item.get('id'))
      .attr('data-hub-createdAt', item.get('createdAt'))
      .attr('data-hub-source-id', item.get('sourceId'));

    if (itemMeta['eventType']) {
    	itemEl.attr('data-hub-event-type', itemMeta['eventType']);
    }
    if (itemMeta['eventUrl']) {
    	itemEl.attr('data-hub-event-url', itemMeta['eventUrl']);
    	contentEl.css('background', 'url(' + itemMeta['eventUrl'] + ') no-repeat 0px 0px');
    }
    if (itemMeta['eventImportant']) {
    	itemEl.attr('data-hub-event-important', itemMeta['eventImportant']);
    }

    var contentView = new ContentView({
        model: item,
        el: contentEl
    });

    var subCol = new Backbone.Collection();
    subCol.comparator = function(i) { return i.get('createdAt');};

    var feedView = new FeedTickerView({
        collection: subCol,
        el: feedEl,
        sources: this.sources
    });
    feedView.render();

    this.childViews[item.get('createdAt')] = {feedView:feedView, item: item};

    this._animateAdd(itemEl, col, col.indexOf(item));

    //this._rebalanceFeedItems(item, col);

    return itemEl;
};

TickerView.prototype._animateAdd = function(itemEl, col, index) {
    var prev = col.at(index-1);
    var next = col.at(index+1);
    var origScrollWidth = this.$el[0].scrollWidth;

    if (col._initialized) {
        this.$el.append(itemEl);
    } else {
    	this.$el.append(itemEl);
    }
    /*    prevEl = this.$el.find('.hub-item[data-hub-contentid="' + prev.get('id') + '"]');
        itemEl.insertAfter(prevEl);
    }*/
    var newScrollWidth = this.$el[0].scrollWidth;
    var diff = newScrollWidth - origScrollWidth;

    if (!this.paused && col._initialized) {
        this.$el.animate({
            scrollLeft: this.$el.scrollLeft() + diff
        }, 500);
    } else if (!col._initialized) {
        this.$el.scrollLeft(this.$el.scrollLeft() + diff);
    }
};

TickerView.prototype._rebalanceFeedItems = function(item, col) {
    var index = col.indexOf(item);
    var createdAt = item.get('createdAt');
    var feedCol = this.childViews[createdAt].feedView.collection;

    // this is going to trace backwards, then forewards along the the feed items,
    // in each collection, moving feed item that need to be in this newly added item's collection
    var prev;
    var prevFeedItem;
    var prevCursor = 0;
    while (!prevFeedItem || prevFeedItem.get('createdAt') > createdAt) {
        while (!prevFeedItem) {
            prev = null;
            prevCursor++;
            var prevItem = col.at(index-prevCursor);
            if (prevItem) {
                prev = this.childViews[prevItem.get('id')];
            }
            if (!prev) { break; }
            prevFeedItem = prev.item.collection.last()
        }
        if (!prev) { break; }
        if (prevFeedItem.get('createdAt') > createdAt) {
            console.log("Shuffled from prev: ", prevFeedItem.get('createdAt'), ' > ', createdAt);
            prev.item.collection.remove(prevFeedItem);
            feedCol.add(prevFeedItem);
        }
        prevFeedItem = prev.item.collection.last()
    }

    var next;
    var nextFeedItem;
    var nextCursor = 0;

    while (!nextFeedItem || nextFeedItem.get('createdAt') < createdAt) {
        while (!nextFeedItem) {
            next = null;
            nextCursor++;
            var nextItem = col.at(index+nextCursor);
            if (nextItem) {
                next = this.childViews[nextItem.get('id')];
            }
            if (!next) { break; }
            nextFeedItem = next.item.collection.first()
        }
        if (!next) { break; }
        if (nextFeedItem.get('createdAt') < createdAt) {
            console.log("Shuffled from next: ", nextFeedItem.get('createdAt'), ' < ', createdAt);
            next.item.collection.remove(nextFeedItem);
            feedCol.add(nextFeedItem);
        }
        nextFeedItem = next.item.collection.first()
    }
};

TickerView.prototype._addFeedItem = function(item, col) {
    // parse the tree
    var itemCreatedAt = item.get('createdAt');
    var keys = Object.keys(this.childViews).sort();

    if (keys.length == 0) {
        return;
    }

    for (var i = 0; i < keys.length; i++) {
        if (itemCreatedAt > keys[i] && (i == keys.length - 1 || itemCreatedAt < keys[i+1])) {
            var feedView = this.childViews[keys[i]].feedView;
            feedView.collection.add(item);
            break;
        }
    }

};

return TickerView;
});
<|endoftext|>


<commit_before>/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, strict:true, trailing:true, white:true */
/*global XT:true, XM:true, XV: true */

// global objects
XT = {};
XM = {};
XV = {};

var assert = require('assert'),
  zombie = require('zombie');
(function () {
  "use strict";

  var loadApp = function (username, password, masterCallback) {
    zombie.visit('http://localhost:2000', {debug: false}, function (e, browser) {
      //
      // This is the login screen
      //
      browser
        .fill('id', username)
        .fill('password', password)
        .pressButton('submit', function () {
          //
          // We skip the scope screen because we're using a user that only has one org
          //
          // Note: make sure the app is built

          // not quite sure why zombie doesn't do this redirect, but oh well.
          browser.visit('http://localhost:2000/client/index.html', function (e, browser) {
            browser.wait(function (window) {
              // this function defines what we're waiting for: for the app state to be 6 (= RUNNING)
              return window.XT.app.state === 6;
            }, function () {
              // this is the function that gets run when the above function returns true

              // add the global objects to our global namespace
              XM = browser.window.XM;
              XT = browser.window.XT;
              XV = browser.window.XV;

              // give control back to whoever called us
              masterCallback();
            });
          });
        });
    });
  };

  exports.loadAdd = loadApp;

  var sampleUse = function () {
    loadApp('admin', 'somenew', function () {
      //console.log("App is loaded");
      //console.log(XM.incidentCategories.toJSON());
      //console.log(XT.session.schema.toJSON());
      process.exit(0);
    });
  };

}());

<commit_msg>issue #19379: updated zombie script<commit_after>/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, strict:true, trailing:true, white:true */
/*global XT:true, XM:true, XV: true */

// global objects
XT = {};
XM = {};
XV = {};

var assert = require('assert'),
  zombie = require('zombie');
(function () {
  "use strict";

  var loadApp = function (username, password, masterCallback) {
    zombie.visit('http://localhost', {debug: false}, function (e, browser) {
      //
      // This is the login screen
      //
      browser
        .fill('id', username)
        .fill('password', password)
        .pressButton('submit', function () {
          //
          // We skip the scope screen because we're using a user that only has one org
          //
          // Note: make sure the app is built

          // not quite sure why zombie doesn't do this redirect, but oh well.
          browser.visit('http://localhost/client/index.html', function (e, browser) {
            browser.wait(function (window) {
              // this function defines what we're waiting for: for the app state to be 6 (= RUNNING)
              return window.XT.app.state === 6;
            }, function () {
              // this is the function that gets run when the above function returns true

              // add the global objects to our global namespace
              XM = browser.window.XM;
              XT = browser.window.XT;
              XV = browser.window.XV;

              // give control back to whoever called us
              masterCallback();
            });
          });
        });
    });
  };

  exports.loadAdd = loadApp;

  var sampleUse = function () {
    var secondsToWait = 10;

    setTimeout(function () {
      console.log("app did not load in " + secondsToWait + " seconds");
      process.exit(1);
    }, secondsToWait * 1000);

    loadApp('admin', 'somenew', function () {
      console.log("app loaded successfully");
      process.exit(0);
    });
  };

  sampleUse();

}());

<|endoftext|>


<commit_before>function makeOption(id, title) {
    return "<option value='" + id + "'>" + title + "</option>";
}

function attachSelect(modal) {

    // Attach to any 'select' inputs on the modal
    // Provide search filtering of dropdown items
    $(modal + ' .select').select2({
        dropdownParent: $(modal),
        dropdownAutoWidth: true,
    });
}

function afterForm(response, options) {

    // Should we show alerts immediately or cache them?
    var cache = (options.follow && response.url) ||
                options.redirect ||
                options.reload;

    // Display any messages
    if (response.success) {
        showAlertOrCache("alert-success", response.success, cache);
    }
    if (response.info) {
        showAlertOrCache("alert-info", response.info, cache);
    }
    if (response.warning) {
        showAlertOrCache("alert-warning", response.warning, cache);
    }
    if (response.danger) {
        showAlertOrCache("alert-danger", response.danger, cache);
    }

    // Was a callback provided?
    if (options.success) {
        options.success();
    }
    else if (options.follow && response.url) {
        window.location.href = response.url;
    }
    else if (options.redirect) {
        window.location.href = options.redirect;
    }
    else if (options.reload) {
        location.reload();
    }

}

function modalSetTitle(modal, title='') {
    $(modal + ' #modal-title').html(title);
}

function modalSetContent(modal, content='') {
    $(modal).find('.modal-form-content').html(content);
}

function modalSetButtonText(modal, text) {
    $(modal).find("#modal-form-submit").html(text);
}

function closeModal(modal='#modal-form') {
    $(modal).modal('hide');
}

function openModal(modal, title='', content='') {

    $(modal).on('shown.bs.modal', function() {
        $(modal + ' .modal-form-content').scrollTop(0);
    });

    // Prevent 'enter' key from submitting the form using the normal method
    $(modal).on('keydown', '.js-modal-form', function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();

            // Simulate a click on the 'Submit' button
            $(modal).find("#modal-form-submit").click();

            return false;
        }
    });

    modalSetTitle(modal, title);
    modalSetContent(modal, content);

    $(modal).modal({
        backdrop: 'static',
        keyboard: false,
    });
    $(modal).modal('show');
}

function launchDeleteForm(url, options = {}) {

    var modal = options.modal || '#modal-delete';

    $(modal).on('shown.bs.modal', function() {
        $(modal + ' .modal-form-content').scrollTop(0);
    });

    // Un-bind any attached click listeners
    $(modal).off('click', '#modal-form-delete');

    // Request delete form data
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        beforeSend: function() {
            openModal(modal);
        },
        success: function (response) {
            if (response.title) {
                modalSetTitle(modal, response.title);
            }
            if (response.html_data) {
                modalSetContent(modal, response.html_data);
            }
            else {
                alert('JSON response missing HTML data');
                $(modal).modal('hide');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Error requesting JSON data:\n' + thrownError);
            $(modal).modal('hide');
        }
    });

    $(modal).on('click', '#modal-form-delete', function() {

        var form = $(modal).find('#delete-form');

        $.ajax({
            url: url,
            data: form.serialize(),
            type: 'post',
            dataType: 'json',
            success: function (response) {
                $(modal).modal('hide');
                afterForm(response, options);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Error deleting item:\n' + thrownError);
                $(modal).modal('hide');
            }
        });
    });
}

function injectModalForm(modal, form_html) {
    // Inject the form data into the modal window
    $(modal).find('.modal-form-content').html(form_html);
    attachSelect(modal);
}

function handleModalForm(url, options) {

    var modal = options.modal || '#modal-form';

    var form = $(modal).find('.js-modal-form');

    var _form = $(modal).find(".js-modal-form");

    form.ajaxForm({
        url: url,
        dataType: 'json',
        type: 'post'
    });

    form.submit(function() {
        alert('form submit');
        return false;
    });

    // Un-bind any attached click listeners
    $(modal).off('click', '#modal-form-submit');

    $(modal).on('click', '#modal-form-submit', function() {
        $(modal).find('.js-modal-form').ajaxSubmit({
            url: url,
            // POST was successful
            success: function(response, status, xhr, f) {
                if ('form_valid' in response) {
                    // Form data was validated correctly
                    if (response.form_valid) {
                        $(modal).modal('hide');
                        afterForm(response, options);
                    }
                    // Form was returned, invalid!
                    else {
                        if (response.html_form) {
                            injectModalForm(modal, response.html_form);
                        }
                        else {
                            alert('HTML form data missing from server response');
                        }
                    }
                }
                else {
                    $(modal).modal('hide');
                    afterForm(response, options);
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert('Error posting form data:\n' + thrownError);
                $(modal).modal('hide');
            },
            complete: function(xhr) {
                //TODO
            }
        });
    });
}

/*
 * launchModalForm
 * Opens a model window and fills it with a requested form
 * If the form is loaded successfully, calls handleModalForm
 */
function launchModalForm(url, options = {}) {

    var modal = options.modal || '#modal-form';

    // Form the ajax request to retrieve the django form data
    ajax_data = {
        url: url,
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
            openModal(modal);
        },
        success: function(response) {
            if (response.title) {
                modalSetTitle(modal, response.title);
            }

            if (response.submit_text) {
                modalSetButtonText(response.submit_text);
            }

            if (response.html_form) {
                injectModalForm(modal, response.html_form);
                handleModalForm(modal, url, options);

            } else {
                alert('JSON response missing form data');
                $(modal).modal('hide');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Error requesting form data:\n' + thrownError);
            $(modal).modal('hide');
        }
    };

    // Add in extra request data if provided
    if (options.data) {
        ajax_data.data = options.data;
    }

    // Send the AJAX request
    $.ajax(ajax_data);
}<commit_msg>Consolidated modal code<commit_after>function makeOption(id, title) {
    return "<option value='" + id + "'>" + title + "</option>";
}

function attachSelect(modal) {

    // Attach to any 'select' inputs on the modal
    // Provide search filtering of dropdown items
    $(modal + ' .select').select2({
        dropdownParent: $(modal),
        dropdownAutoWidth: true,
    });
}

function afterForm(response, options) {

    // Should we show alerts immediately or cache them?
    var cache = (options.follow && response.url) ||
                options.redirect ||
                options.reload;

    // Display any messages
    if (response.success) {
        showAlertOrCache("alert-success", response.success, cache);
    }
    if (response.info) {
        showAlertOrCache("alert-info", response.info, cache);
    }
    if (response.warning) {
        showAlertOrCache("alert-warning", response.warning, cache);
    }
    if (response.danger) {
        showAlertOrCache("alert-danger", response.danger, cache);
    }

    // Was a callback provided?
    if (options.success) {
        options.success();
    }
    else if (options.follow && response.url) {
        window.location.href = response.url;
    }
    else if (options.redirect) {
        window.location.href = options.redirect;
    }
    else if (options.reload) {
        location.reload();
    }

}

function modalSetTitle(modal, title='') {
    $(modal + ' #modal-title').html(title);
}

function modalSetContent(modal, content='') {
    $(modal).find('.modal-form-content').html(content);
}

function modalSetButtonText(modal, text) {
    $(modal).find("#modal-form-submit").html(text);
}

function closeModal(modal='#modal-form') {
    $(modal).modal('hide');
}

function openModal(options) {

    var modal = options.modal || '#modal-form';

    $(modal).on('shown.bs.modal', function() {
        $(modal + ' .modal-form-content').scrollTop(0);
    });

    // Prevent 'enter' key from submitting the form using the normal method
    $(modal).on('keydown', '.js-modal-form', function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();

            // Simulate a click on the 'Submit' button
            $(modal).find("#modal-form-submit").click();

            return false;
        }
    });

    if (options.title) {
        modalSetTitle(modal, options.title);
    }

    if (options.content) {
        modalSetContent(modal, options.content);
    }

    if (options.buttonText) {
        modalSetButtonText(modal, options.buttonText);
    }

    $(modal).modal({
        backdrop: 'static',
        keyboard: false,
    });
    $(modal).modal('show');
}

function launchDeleteForm(url, options = {}) {

    var modal = options.modal || '#modal-delete';

    $(modal).on('shown.bs.modal', function() {
        $(modal + ' .modal-form-content').scrollTop(0);
    });

    // Un-bind any attached click listeners
    $(modal).off('click', '#modal-form-delete');

    // Request delete form data
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        beforeSend: function() {
            openModal({modal: modal});
        },
        success: function (response) {
            if (response.title) {
                modalSetTitle(modal, response.title);
            }
            if (response.html_data) {
                modalSetContent(modal, response.html_data);
            }
            else {
                alert('JSON response missing HTML data');
                $(modal).modal('hide');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Error requesting JSON data:\n' + thrownError);
            $(modal).modal('hide');
        }
    });

    $(modal).on('click', '#modal-form-delete', function() {

        var form = $(modal).find('#delete-form');

        $.ajax({
            url: url,
            data: form.serialize(),
            type: 'post',
            dataType: 'json',
            success: function (response) {
                $(modal).modal('hide');
                afterForm(response, options);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Error deleting item:\n' + thrownError);
                $(modal).modal('hide');
            }
        });
    });
}

function injectModalForm(modal, form_html) {
    // Inject the form data into the modal window
    $(modal).find('.modal-form-content').html(form_html);
    attachSelect(modal);
}

function handleModalForm(url, options) {

    var modal = options.modal || '#modal-form';

    var form = $(modal).find('.js-modal-form');

    var _form = $(modal).find(".js-modal-form");

    form.ajaxForm({
        url: url,
        dataType: 'json',
        type: 'post'
    });

    form.submit(function() {
        alert('form submit');
        return false;
    });

    // Un-bind any attached click listeners
    $(modal).off('click', '#modal-form-submit');

    $(modal).on('click', '#modal-form-submit', function() {
        $(modal).find('.js-modal-form').ajaxSubmit({
            url: url,
            // POST was successful
            success: function(response, status, xhr, f) {
                if ('form_valid' in response) {
                    // Form data was validated correctly
                    if (response.form_valid) {
                        $(modal).modal('hide');
                        afterForm(response, options);
                    }
                    // Form was returned, invalid!
                    else {
                        if (response.html_form) {
                            injectModalForm(modal, response.html_form);
                        }
                        else {
                            alert('HTML form data missing from server response');
                        }
                    }
                }
                else {
                    $(modal).modal('hide');
                    afterForm(response, options);
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert('Error posting form data:\n' + thrownError);
                $(modal).modal('hide');
            },
            complete: function(xhr) {
                //TODO
            }
        });
    });
}

/*
 * launchModalForm
 * Opens a model window and fills it with a requested form
 * If the form is loaded successfully, calls handleModalForm
 */
function launchModalForm(url, options = {}) {

    var modal = options.modal || '#modal-form';

    // Form the ajax request to retrieve the django form data
    ajax_data = {
        url: url,
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
            openModal({modal: modal});
        },
        success: function(response) {
            if (response.title) {
                modalSetTitle(modal, response.title);
            }

            if (response.submit_text) {
                modalSetButtonText(response.submit_text);
            }

            if (response.html_form) {
                injectModalForm(modal, response.html_form);
                handleModalForm(url, options);

            } else {
                alert('JSON response missing form data');
                $(modal).modal('hide');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Error requesting form data:\n' + thrownError);
            $(modal).modal('hide');
        }
    };

    // Add in extra request data if provided
    if (options.data) {
        ajax_data.data = options.data;
    }

    // Send the AJAX request
    $.ajax(ajax_data);
}<|endoftext|>


<commit_before>import React from 'react';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {addNavigateHandlers, Scene} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

var stateNavigator = new StateNavigator([
  {key: 'home', title: 'Home'},
  {key: 'notifications', title: 'Notifications'},
  {key: 'tweet', title: 'Tweet', trackCrumbTrail: true},
  {key: 'timeline', title: 'Timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
home.renderScene = () => <Home tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

for(var key in stateNavigator.states) {
  var state = stateNavigator.states[key];
  state.getCrumbStyle = from => from ? 'scale_in' : 'scale_out';
  state.getUnmountStyle = from => from ? 'slide_in' : 'slide_out';
}

timeline.getTitle = ({sceneTitle}) => sceneTitle;

var stateNavigators = [stateNavigator, new StateNavigator(stateNavigator)];
stateNavigator.navigate('home');
stateNavigators[1].navigate('notifications');

addNavigateHandlers(stateNavigators);

export default ({crumb, tab = 0}) => (
  <NavigationHandler stateNavigator={stateNavigators[tab]}>
    <Scene crumb={crumb} tab={tab} />
  </NavigationHandler>
);
<commit_msg>Created the twitter tab bar component layout<commit_after>import React from 'react';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBarIOS, TabBarItemIOS} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

var stateNavigator = new StateNavigator([
  {key: 'home', title: 'Home'},
  {key: 'notifications', title: 'Notifications'},
  {key: 'tweet', title: 'Tweet', trackCrumbTrail: true},
  {key: 'timeline', title: 'Timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
home.renderScene = () => <Home tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

timeline.getTitle = ({sceneTitle}) => sceneTitle;

var notificationsNavigator = new StateNavigator(stateNavigator);
stateNavigator.navigate('home');
notificationsNavigator.navigate('notifications');

export default () => (
  <TabBarIOS>
    <NavigationHandler stateNavigator={stateNavigator}>
      <NavigationStack
        crumbStyle={from => from ? 'scale_in' : 'scale_out'}
        unmountStyle={from => from ? 'scale_in' : 'scale_out'}>
        <TabBarItemIOS title="Home" />
      </NavigationStack>
    </NavigationHandler>
    <NavigationHandler stateNavigator={notificationsNavigator}>
      <NavigationStack
        crumbStyle={from => from ? 'scale_in' : 'scale_out'}
        unmountStyle={from => from ? 'scale_in' : 'scale_out'}>
        <TabBarItemIOS title="Notifications" />
      </NavigationStack>
    </NavigationHandler>
  </TabBarIOS>
);
<|endoftext|>


<commit_before>/* globals describe, it, expect */
var Rx = require('../dist/cjs/Rx');
var Subscriber = Rx.Subscriber;

describe('Subscriber', function () {
  it('should have the rxSubscriber symbol', function () {
    var sub = new Subscriber();
    expect(sub[Rx.Symbol.rxSubscriber]()).toBe(sub);
  });
});<commit_msg>test(Subscriber): add test for no error propagation<commit_after>/* globals describe, it, expect */
var Rx = require('../dist/cjs/Rx');
var Subscriber = Rx.Subscriber;

describe('Subscriber', function () {
  it('should have the rxSubscriber symbol', function () {
    var sub = new Subscriber();
    expect(sub[Rx.Symbol.rxSubscriber]()).toBe(sub);
  });

  describe('when created through create()', function () {
    it('should not call error() if next() handler throws an error', function () {
      var errorSpy = jasmine.createSpy('error');
      var completeSpy = jasmine.createSpy('complete');

      var subscriber = Subscriber.create(
        function next(value) {
          if (value === 2) {
            throw 'error!';
          }
        },
        errorSpy,
        completeSpy
      );

      subscriber.next(1);
      expect(function () {
        subscriber.next(2);
      }).toThrow('error!');

      expect(errorSpy).not.toHaveBeenCalled();
      expect(completeSpy).not.toHaveBeenCalled();
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>Fixed check propositionSelected before sent to submit at PostToPre<commit_after><|endoftext|>


<commit_before><commit_msg>Quantity widget text and wired up forgot password<commit_after><|endoftext|>


<commit_before><commit_msg>Rollback box item model when change frequency modal is closed<commit_after><|endoftext|>


<commit_before><commit_msg>Update report.server.controller.js<commit_after><|endoftext|>


<commit_before>var pathMatch = require('../lib/path_match');

describe('pathMatch', function () {
  xit('returns the object that has an exact-matching verb and path to the input', function () {

    var routeDefinitions = [
      { verb: 'get', path: '/about' },
      { verb: 'get', path: '/' },
      { verb: 'post', path: '/' },
      { verb: 'get', path: '/contact' },
    ];

    expect(pathMatch(routeDefinitions, 'get', '/contact')).toEqual({ verb: 'get', path: '/contact'});
    expect(pathMatch(routeDefinitions, 'get', '/about')).toEqual({ verb: 'get', path: '/about'});
    expect(pathMatch(routeDefinitions, 'get', '/')).toEqual({ verb: 'get', path: '/'});
    expect(pathMatch(routeDefinitions, 'post', '/')).toEqual({ verb: 'post', path: '/'});
  });

  xit('returns null if the verb does not match any in array', function () {

    var routeDefinitions = [
      { verb: 'get', path: '/about' },
      { verb: 'get', path: '/' },
      { verb: 'post', path: '/' },
      { verb: 'get', path: '/contact' },
    ];

    expect(pathMatch(routeDefinitions, 'post', '/about')).toEqual(null);
  });

  xit('returns the object that matches the path to your route definitions even when it contains dynamic segments', function () {
    var routeDefinitions = [
      { verb: 'get', path: '/artists/:artist_name/albums' },
      { verb: 'get', path: '/artists/:artist_name/albums/:album_id' },
      { verb: 'get', path: '/:name' },
    ];

    expect(pathMatch(routeDefinitions, 'get', '/SammyJ')).toEqual({ verb: 'get', path: '/:name' });
    expect(pathMatch(routeDefinitions, 'get', '/artists/bjork/albums')).toEqual({ verb: 'get', path: '/artists/:artist_name/albums' });
    expect(pathMatch(routeDefinitions, 'get', '/artists/bjork/albums/29943')).toEqual({ verb: 'get', path: '/artists/:artist_name/albums/:album_id' });
  });

  it('returns the first matching object even if there is a better one later', function () {
    var routeDefinitions = [
      { verb: 'get', path: '/:id' },
      { verb: 'get', path: '/new' },
    ];

    expect(pathMatch(routeDefinitions, 'get', '/new')).toEqual({ verb: 'get', path: '/:id' });
  });

});
<commit_msg>reactivated all tests<commit_after>var pathMatch = require('../lib/path_match');

describe('pathMatch', function () {
  it('returns the object that has an exact-matching verb and path to the input', function () {

    var routeDefinitions = [
      { verb: 'get', path: '/about' },
      { verb: 'get', path: '/' },
      { verb: 'post', path: '/' },
      { verb: 'get', path: '/contact' },
    ];

    expect(pathMatch(routeDefinitions, 'get', '/contact')).toEqual({ verb: 'get', path: '/contact'});
    expect(pathMatch(routeDefinitions, 'get', '/about')).toEqual({ verb: 'get', path: '/about'});
    expect(pathMatch(routeDefinitions, 'get', '/')).toEqual({ verb: 'get', path: '/'});
    expect(pathMatch(routeDefinitions, 'post', '/')).toEqual({ verb: 'post', path: '/'});
  });

  it('returns null if the verb does not match any in array', function () {

    var routeDefinitions = [
      { verb: 'get', path: '/about' },
      { verb: 'get', path: '/' },
      { verb: 'post', path: '/' },
      { verb: 'get', path: '/contact' },
    ];

    expect(pathMatch(routeDefinitions, 'post', '/about')).toEqual(null);
  });

  it('returns the object that matches the path to your route definitions even when it contains dynamic segments', function () {
    var routeDefinitions = [
      { verb: 'get', path: '/artists/:artist_name/albums' },
      { verb: 'get', path: '/artists/:artist_name/albums/:album_id' },
      { verb: 'get', path: '/:name' },
    ];

    expect(pathMatch(routeDefinitions, 'get', '/SammyJ')).toEqual({ verb: 'get', path: '/:name' });
    expect(pathMatch(routeDefinitions, 'get', '/artists/bjork/albums')).toEqual({ verb: 'get', path: '/artists/:artist_name/albums' });
    expect(pathMatch(routeDefinitions, 'get', '/artists/bjork/albums/29943')).toEqual({ verb: 'get', path: '/artists/:artist_name/albums/:album_id' });
  });

  it('returns the first matching object even if there is a better one later', function () {
    var routeDefinitions = [
      { verb: 'get', path: '/:id' },
      { verb: 'get', path: '/new' },
    ];

    expect(pathMatch(routeDefinitions, 'get', '/new')).toEqual({ verb: 'get', path: '/:id' });
  });

});
<|endoftext|>


<commit_before>
var Regularity = require('../lib/regularity.js');

describe("Regularity", function() {
    var regularity;

    beforeEach(function() {
        regularity = new Regularity();
    });

    it("is an object constructor", function() {
        expect(typeof regularity).toBe('object');
    });

    describe("return from done()", function() {
        it("is a RegExp instance", function() {
            expect(regularity.done() instanceof RegExp).toBe(true);
        });

        it ("returns an empty regexp by default", function() {
            expect(regularity.done()).toEqual(new RegExp());
        });
    });

    describe("escapes regexp special characters", function() {
        var charactersToBeEscaped = [ '*', '.', '?', '^', '+',
        '$', '|', '(', ')', '[', ']', '{', '}' ];

        charactersToBeEscaped.forEach(function testEscapedChar(character) {
            it("escapes '" + character + "'", function() {
                var currentRegex = regularity.append(character).done();

                expect(currentRegex.source).toBe("\\" + character);
            });
        });
    });

    describe("#startWith", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.startWith('a').done();
        });

        it("matches in the positive case", function(){
            expect(regex.test('abcde')).toBe(true);
        });

        it("does not match in the negative case", function(){
            expect(regex.test('edcba')).toBe(false);
        });
    });

    describe("#endWith", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.endWith('a').done();
        });

        it("matches in the positive case", function(){
            expect(regex.test('edcba')).toBe(true);
        });

        it("does not match in the negative case", function(){
            expect(regex.test('abcde')).toBe(false);
        });
    });

    describe("#maybe", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.maybe('a').done();
        });

        it("matches when the pattern is present", function(){
            expect(regex.test('aaaa')).toBe(true);
        });

        it("matches when the pattern isn't present", function(){
            expect(regex.test('bbbb')).toBe(true);
        });
    });

    describe("#oneOf", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.oneOf(['a','bb','ccc']).done();
        });

        it("matches the first one", function(){
            expect(regex.test('addd')).toBe(true);
        });

        it("matches the second one", function(){
            expect(regex.test('dbb')).toBe(true);
        });

        it("matches the third one", function() {
            expect(regex.test('zkcccl')).toBe(true);
        });

        it("does not match when neither are present", function(){
            expect(regex.test('bccddd')).toBe(true);
        });
    });

    describe("#between", function(){
        it("doesn't match under lower bound", function(){
            var regex = regularity.between([2,3], 'a').done();
            expect(regex.test('addd')).toBe(false);
        });
    });

});

// append: [Function],

// between: [Function],

// zeroOrMore: [Function],

// oneOrMore: [Function],

// atLeast: [Function],

// atMost: [Function],

// insensitive: [Function],

// global: [Function],

// multiLine: [Function],

// done: [Function],

// regexp: [Function] }

<commit_msg>Add more comprehensive tests for 'between'.<commit_after>
var Regularity = require('../lib/regularity.js');

describe("Regularity", function() {
    var regularity;

    beforeEach(function() {
        regularity = new Regularity();
    });

    it("is an object constructor", function() {
        expect(typeof regularity).toBe('object');
    });

    describe("return from done()", function() {
        it("is a RegExp instance", function() {
            expect(regularity.done() instanceof RegExp).toBe(true);
        });

        it ("returns an empty regexp by default", function() {
            expect(regularity.done()).toEqual(new RegExp());
        });
    });

    describe("escapes regexp special characters", function() {
        var charactersToBeEscaped = [ '*', '.', '?', '^', '+',
        '$', '|', '(', ')', '[', ']', '{', '}' ];

        charactersToBeEscaped.forEach(function testEscapedChar(character) {
            it("escapes '" + character + "'", function() {
                var currentRegex = regularity.append(character).done();

                expect(currentRegex.source).toBe("\\" + character);
            });
        });
    });

    describe("#startWith", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.startWith('a').done();
        });

        it("matches in the positive case", function(){
            expect(regex.test('abcde')).toBe(true);
        });

        it("does not match in the negative case", function(){
            expect(regex.test('edcba')).toBe(false);
        });
    });

    describe("#endWith", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.endWith('a').done();
        });

        it("matches in the positive case", function(){
            expect(regex.test('edcba')).toBe(true);
        });

        it("does not match in the negative case", function(){
            expect(regex.test('abcde')).toBe(false);
        });
    });

    describe("#maybe", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.maybe('a').done();
        });

        it("matches when the pattern is present", function(){
            expect(regex.test('aaaa')).toBe(true);
        });

        it("matches when the pattern isn't present", function(){
            expect(regex.test('bbbb')).toBe(true);
        });
    });

    describe("#oneOf", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.oneOf(['a','bb','ccc']).done();
        });

        it("matches the first one", function(){
            expect(regex.test('addd')).toBe(true);
        });

        it("matches the second one", function(){
            expect(regex.test('dbb')).toBe(true);
        });

        it("matches the third one", function() {
            expect(regex.test('zkcccl')).toBe(true);
        });

        it("does not match when neither are present", function(){
            expect(regex.test('bccddd')).toBe(true);
        });
    });

    describe("#between", function(){
        var regex;
        beforeEach(function() {
            regex = regularity.between([3, 5], 'a').done();
        });

        it("matches when there is the right amount of consecutive occurences", function() {
            expect(regex.test('aaadd')).toBe(true);
            expect(regex.test('llaaaa')).toBe(true);
            expect(regex.test('lmaaaaakl')).toBe(true);
        });

        it("doesn't match when the count is less than the lower bound", function(){
            expect(regex.test('addd')).toBe(false);
            expect(regex.test('aadkb')).toBe(false);
        });

        // see https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_special_characters
        it("*does* match when the count is more than the upper bound", function() {
            expect(regex.test('daaaaaalk')).toBe(true);
            expect(regex.test('dmaaaaaaaaaalm')).toBe(true);
        });

        it("doesn't match when there are enough occurences but they are not consecutive", function() {
            expect(regex.test('azaazza')).toBe(false);
            expect(regex.test('zkalaamaa')).toBe(false);
            expect(regex.test('azakalaamaama')).toBe(false);
        });
    });

});

// append: [Function],

// between: [Function],

// zeroOrMore: [Function],

// oneOrMore: [Function],

// atLeast: [Function],

// atMost: [Function],

// insensitive: [Function],

// global: [Function],

// multiLine: [Function],

// done: [Function],

// regexp: [Function] }

<|endoftext|>


<commit_before>/*
 * All source files are created and managed by type in `src`.
 *
 * There three output directories:
 *
 *  - `local` - Development and testing
 *  - `build` - Intermediate directory prior to optimizations and/or
 *      concatentation
 *  - `dist` - Final output for release purposes. This carries over
 *      to the master branch to be copied in the root of the repo.
 *
 *  Each Grunt task has a target named `local` which performs copying,
 *  compiling or symlinking in the `local` directory for development.
 *  Additional targets may be defined for `build` or `dist` depending on
 *  the requirements.
 *
 *  Shared options for a task should be defined first, followed by each
 *  task entry. Each task can define it's own set of options to override
 *  the shared ones defined for the task.
 *
 */

module.exports = function(grunt) {
    'use strict';

    var pkg = grunt.file.readJSON('package.json');

    grunt.initConfig({

        pkg: pkg,

        srcDir: 'src',
        specDir: 'spec',

        localDir: 'local',
        buildDir: 'build',
        distDir: 'dist',

        connect: {
            server: {
                options: {
                    host: '127.0.0.1',
                    port: 8125
                }
            }
        },

        watch: {
            coffee: {
                tasks: ['coffee:local'],
                files: [
                    '<%= srcDir %>/coffee/**/*'
                ]
            },

            tests: {
                tasks: ['jasmine:local:build'],
                files: ['<%= specDir %>/**/*']
            },

            sass: {
                tasks: ['sass:local'],
                files: ['<%= srcDir %>/scss/**/*']
            }
        },

        coffee: {
            options: {
                bare: true,
            },

            // Output to 'local' for development
            local: {
                options: {
                    sourceMap: true
                },
                expand: true,
                cwd: '<%= srcDir %>/coffee',
                dest: '<%= localDir %>/js',
                src: '**/*.coffee',
                rename: function(dest, src) {
                    return dest + '/' + src.replace('.coffee', '.js');
                }
            },

            // Compiles files to the 'build' directory for distribution
            build: {
                expand: true,
                cwd: '<%= srcDir %>/coffee',
                dest: '<%= buildDir %>/js',
                src: '**/*.coffee',
                rename: function(dest, src) {
                    return dest + '/' + src.replace('.coffee', '.js');
                }
            }
        },

        sass: {
            local: {
                options: {
                    trace: true,
                    sourcemap: true
                },
                files: {
                    '<%= localDir %>/css/style.css': '<%= srcDir %>/scss/style.scss'
                }
            },

            dist: {
                options: {
                    quiet: true,
                    style: 'compressed'
                },
                files: {
                    '<%= distDir %>/css/style.css': '<%= srcDir %>/scss/style.scss'
                }
            }
        },

        copy: {
            local: {
                files: [
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/js',
                        src: ['**/*'],
                        dest: '<%= localDir %>/js'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/css',
                        src: ['**/*'],
                        dest: '<%= localDir %>/css'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/font',
                        src: ['**/*'],
                        dest: '<%= localDir %>/font'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/img',
                        src: ['**/*'],
                        dest: '<%= localDir %>/img'
                    }
                ]
            },

            build: {
                files: [
                     {
                        expand: true,
                        cwd: '<%= srcDir %>/templates',
                        src: ['**/*'],
                        dest: '<%= buildDir %>/js/templates'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/js',
                        src: ['**/*'],
                        dest: '<%= buildDir %>/js'
                    }
                ]
            },

            dist: {
                files: [
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/css',
                        src: ['**/*'],
                        dest: '<%= distDir %>/css'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/font',
                        src: ['**/*'],
                        dest: '<%= distDir %>/font'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/img',
                        src: ['**/*'],
                        dest: '<%= distDir %>/img'
                    },
                    {
                        expand: true,
                        src: ['bower.json', 'package.json'],
                        dest: '<%= distDir %>'
                    }
                ]
            }
        },

        // Only applicable for development, e.g. local
        symlink: {
            options: {
                type: 'dir'
            },

            templates: {
                relativeSrc: '../../<%= srcDir %>/templates',
                dest: '<%= localDir %>/js/templates'
            },

            extensions: {
                relativeSrc: '../../<%= srcDir %>/extensions',
                dest: '<%= localDir %>/js/extensions'
            }
        },

        requirejs: {
            options: {
                baseUrl: '.',
                inlineText: true,
                preserveLicenseComments: false,
                wrap: false,
                logLevel: 1,
                throwWhen: {
                    optimize: true
                },

                // RequireJS plugin configs
                config: {
                    tpl: {
                        variable: 'data'
                    }
                },

                modules: [{
                    name: 'cilantro',
                    include: ['cilantro/ui']
                }],

                // Post analysis of built files
                done: function(done, output) {
                    var dups = require('rjs-build-analysis').duplicates(output);

                    if (dups.length > 0) {
                        grunt.log.subhead('Duplicates found in RequireJS build:');
                        grunt.log.warn(dups);
                        done(new Error('r.js built duplicate modules, please check the `excludes` option.'));
                    }

                    done();
                }
            },

            dist: {
                options: {
                    appDir: 'build/js',
                    dir: 'dist/js',
                    optimize: 'uglify2',
                    removeCombined: true
                }
            }
        },

        // Removes output directories
        clean: {
            local: ['local'],
            build: ['build'],
            dist: ['dist'],
            postdist: [
                '<%= distDir %>/js/templates',
                '<%= distDir %>/js/build.txt'
            ]
        },

        jasmine : {
            options : {
                specs : '<%= specDir %>/**/*',
                host: 'http://127.0.0.1:8125',
                keepRunner: true,
                template: require('grunt-template-jasmine-requirejs'),
            },

            local: {
                options: {
                    templateOptions: {
                        requireConfig: {
                            baseUrl: '<%= localDir %>/js',
                            config: {
                                tpl: {
                                    variable: 'data'
                                }
                            }
                        }
                    }
                }
            },

            dist: {
                options: {
                    templateOptions: {
                        requireConfig: {
                            baseUrl: '<%= distDir %>/js',
                            config: {
                                tpl: {
                                    variable: 'data'
                                }
                            }
                        }
                    }
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-symlink');

    grunt.registerTask('local', [
        'sass:local',
        'coffee:local',
        'copy:local',
        'symlink',
        'jasmine:local:build'
    ]);

    grunt.registerTask('dist', [
        'clean:build',
        'coffee:build',
        'copy:build',
        'clean:dist',
        'requirejs:dist',
        'sass:dist',
        'copy:dist',
        'clean:postdist'
    ]);

    grunt.registerTask('work', [
        'local',
        'watch'
    ]);

    grunt.registerTask('test', [
        'connect',
        'jasmine:local'
    ]);

    var shell = require('shelljs');

    function run(cmd) {
        grunt.log.ok(cmd);
        shell.exec(cmd);
    }

    grunt.registerTask('release', 'Create a release on master', function() {
        run('git checkout master');
        run('rm -rf font css img js');
        run('cp -r dist/* .');
        run('git add .');
        run('git commit -m "' + pkg.version + ' Release"');
        run('git tag ' + pkg.version);
    });
};
<commit_msg>Rename task release to tag-release, add dist to release<commit_after>/*
 * All source files are created and managed by type in `src`.
 *
 * There three output directories:
 *
 *  - `local` - Development and testing
 *  - `build` - Intermediate directory prior to optimizations and/or
 *      concatentation
 *  - `dist` - Final output for release purposes. This carries over
 *      to the master branch to be copied in the root of the repo.
 *
 *  Each Grunt task has a target named `local` which performs copying,
 *  compiling or symlinking in the `local` directory for development.
 *  Additional targets may be defined for `build` or `dist` depending on
 *  the requirements.
 *
 *  Shared options for a task should be defined first, followed by each
 *  task entry. Each task can define it's own set of options to override
 *  the shared ones defined for the task.
 *
 */

module.exports = function(grunt) {
    'use strict';

    var pkg = grunt.file.readJSON('package.json');

    grunt.initConfig({

        pkg: pkg,

        srcDir: 'src',
        specDir: 'spec',

        localDir: 'local',
        buildDir: 'build',
        distDir: 'dist',

        connect: {
            server: {
                options: {
                    host: '127.0.0.1',
                    port: 8125
                }
            }
        },

        watch: {
            coffee: {
                tasks: ['coffee:local'],
                files: [
                    '<%= srcDir %>/coffee/**/*'
                ]
            },

            tests: {
                tasks: ['jasmine:local:build'],
                files: ['<%= specDir %>/**/*']
            },

            sass: {
                tasks: ['sass:local'],
                files: ['<%= srcDir %>/scss/**/*']
            }
        },

        coffee: {
            options: {
                bare: true,
            },

            // Output to 'local' for development
            local: {
                options: {
                    sourceMap: true
                },
                expand: true,
                cwd: '<%= srcDir %>/coffee',
                dest: '<%= localDir %>/js',
                src: '**/*.coffee',
                rename: function(dest, src) {
                    return dest + '/' + src.replace('.coffee', '.js');
                }
            },

            // Compiles files to the 'build' directory for distribution
            build: {
                expand: true,
                cwd: '<%= srcDir %>/coffee',
                dest: '<%= buildDir %>/js',
                src: '**/*.coffee',
                rename: function(dest, src) {
                    return dest + '/' + src.replace('.coffee', '.js');
                }
            }
        },

        sass: {
            local: {
                options: {
                    trace: true,
                    sourcemap: true
                },
                files: {
                    '<%= localDir %>/css/style.css': '<%= srcDir %>/scss/style.scss'
                }
            },

            dist: {
                options: {
                    quiet: true,
                    style: 'compressed'
                },
                files: {
                    '<%= distDir %>/css/style.css': '<%= srcDir %>/scss/style.scss'
                }
            }
        },

        copy: {
            local: {
                files: [
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/js',
                        src: ['**/*'],
                        dest: '<%= localDir %>/js'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/css',
                        src: ['**/*'],
                        dest: '<%= localDir %>/css'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/font',
                        src: ['**/*'],
                        dest: '<%= localDir %>/font'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/img',
                        src: ['**/*'],
                        dest: '<%= localDir %>/img'
                    }
                ]
            },

            build: {
                files: [
                     {
                        expand: true,
                        cwd: '<%= srcDir %>/templates',
                        src: ['**/*'],
                        dest: '<%= buildDir %>/js/templates'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/js',
                        src: ['**/*'],
                        dest: '<%= buildDir %>/js'
                    }
                ]
            },

            dist: {
                files: [
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/css',
                        src: ['**/*'],
                        dest: '<%= distDir %>/css'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/font',
                        src: ['**/*'],
                        dest: '<%= distDir %>/font'
                    },
                    {
                        expand: true,
                        cwd: '<%= srcDir %>/img',
                        src: ['**/*'],
                        dest: '<%= distDir %>/img'
                    },
                    {
                        expand: true,
                        src: ['bower.json', 'package.json'],
                        dest: '<%= distDir %>'
                    }
                ]
            }
        },

        // Only applicable for development, e.g. local
        symlink: {
            options: {
                type: 'dir'
            },

            templates: {
                relativeSrc: '../../<%= srcDir %>/templates',
                dest: '<%= localDir %>/js/templates'
            },

            extensions: {
                relativeSrc: '../../<%= srcDir %>/extensions',
                dest: '<%= localDir %>/js/extensions'
            }
        },

        requirejs: {
            options: {
                baseUrl: '.',
                inlineText: true,
                preserveLicenseComments: false,
                wrap: false,
                logLevel: 1,
                throwWhen: {
                    optimize: true
                },

                // RequireJS plugin configs
                config: {
                    tpl: {
                        variable: 'data'
                    }
                },

                modules: [{
                    name: 'cilantro',
                    include: ['cilantro/ui']
                }],

                // Post analysis of built files
                done: function(done, output) {
                    var dups = require('rjs-build-analysis').duplicates(output);

                    if (dups.length > 0) {
                        grunt.log.subhead('Duplicates found in RequireJS build:');
                        grunt.log.warn(dups);
                        done(new Error('r.js built duplicate modules, please check the `excludes` option.'));
                    }

                    done();
                }
            },

            dist: {
                options: {
                    appDir: 'build/js',
                    dir: 'dist/js',
                    optimize: 'uglify2',
                    removeCombined: true
                }
            }
        },

        // Removes output directories
        clean: {
            local: ['local'],
            build: ['build'],
            dist: ['dist'],
            postdist: [
                '<%= distDir %>/js/templates',
                '<%= distDir %>/js/build.txt'
            ]
        },

        jasmine : {
            options : {
                specs : '<%= specDir %>/**/*',
                host: 'http://127.0.0.1:8125',
                keepRunner: true,
                template: require('grunt-template-jasmine-requirejs'),
            },

            local: {
                options: {
                    templateOptions: {
                        requireConfig: {
                            baseUrl: '<%= localDir %>/js',
                            config: {
                                tpl: {
                                    variable: 'data'
                                }
                            }
                        }
                    }
                }
            },

            dist: {
                options: {
                    templateOptions: {
                        requireConfig: {
                            baseUrl: '<%= distDir %>/js',
                            config: {
                                tpl: {
                                    variable: 'data'
                                }
                            }
                        }
                    }
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-symlink');

    grunt.registerTask('local', [
        'sass:local',
        'coffee:local',
        'copy:local',
        'symlink',
        'jasmine:local:build'
    ]);

    grunt.registerTask('dist', [
        'clean:build',
        'coffee:build',
        'copy:build',
        'clean:dist',
        'requirejs:dist',
        'sass:dist',
        'copy:dist',
        'clean:postdist'
    ]);

    grunt.registerTask('work', [
        'local',
        'watch'
    ]);

    grunt.registerTask('test', [
        'connect',
        'jasmine:local'
    ]);

    var shell = require('shelljs');

    function run(cmd) {
        grunt.log.ok(cmd);
        shell.exec(cmd);
    }

    grunt.registerTask('tag-release', 'Create a release on master', function() {
        run('git checkout master');
        run('rm -rf font css img js');
        run('cp -r dist/* .');
        run('git add .');
        run('git commit -m "' + pkg.version + ' Release"');
        run('git tag ' + pkg.version);
    });

    grunt.registerTask('release', [
        'dist',
        'tag-release'
    ]);

};
<|endoftext|>


<commit_before>/* jshint camelcase:false */
module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        connect: {
            uses_defaults: {}
        },
        copy: {
            main: {
                expand: true,
                cwd: 'src/',
                src: '**',
                dest: 'dist/'
            }
        },
        clean: {
            main: ['dist']
        },
        'gh-pages': {
            options: {
                base: 'dist'
            },
            all: {
                src: ['**']
            }
        },
        jshint: {
            main: {
                // must use src for newer to work
                src: ['src/app/**.js']
            },
            options: {
                jshintrc: '.jshintrc'
            }
        },
        watch: {
            jshint: {
                files: ['src/app/**.js'],
                tasks: ['jshint:main']
            },
            src: {
                files: ['**'],
                options: {
                    livereload: true
                }
            }
        }
    });

    // Loading dependencies
    for (var key in grunt.file.readJSON('package.json').devDependencies) {
        if (key !== 'grunt' && key.indexOf('grunt') === 0) {
            grunt.loadNpmTasks(key);
        }
    }

    // Default task.
    grunt.registerTask('default', [
        'jshint',
        'connect',
        'watch'
    ]);

    grunt.registerTask('publish', [
        'clean:main',
        'copy:main',
        'gh-pages'
    ]);
};<commit_msg>fix gh-pages<commit_after>/* jshint camelcase:false */
module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        connect: {
            uses_defaults: {}
        },
        copy: {
            main: {
                expand: true,
                cwd: 'src/',
                src: '**',
                dest: 'dist/'
            }
        },
        clean: {
            main: ['dist']
        },
        'gh-pages': {
            options: {
                base: 'dist'
            },
            src: ['**']
        },
        jshint: {
            main: {
                // must use src for newer to work
                src: ['src/app/**.js']
            },
            options: {
                jshintrc: '.jshintrc'
            }
        },
        watch: {
            jshint: {
                files: ['src/app/**.js'],
                tasks: ['jshint:main']
            },
            src: {
                files: ['**'],
                options: {
                    livereload: true
                }
            }
        }
    });

    // Loading dependencies
    for (var key in grunt.file.readJSON('package.json').devDependencies) {
        if (key !== 'grunt' && key.indexOf('grunt') === 0) {
            grunt.loadNpmTasks(key);
        }
    }

    // Default task.
    grunt.registerTask('default', [
        'jshint',
        'connect',
        'watch'
    ]);

    grunt.registerTask('publish', [
        'clean:main',
        'copy:main',
        'gh-pages'
    ]);
};<|endoftext|>


<commit_before>'use strict';

module.exports = function (grunt) {

    // https://github.com/shootaroo/jit-grunt
    require('jit-grunt')(grunt);

    var module = grunt.option("module") || 'login';

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        connect: {
            server: {
                options: {
                    port: 8080,
                    base: './'
                }
            }
        },

        ts: {

            dev: {
                src: ['**/*.ts', '!node_modules/**', '!.tscache/**'],
                vs: {
                    project: 'UI.csproj',
                    config: 'Debug',
                    ignoreFiles: true
                }
            },

            debug: {
                vs: {
                    project: 'UI.csproj',
                    config: 'Debug'
                }
            },

            release: {
                vs: {
                    project: 'UI.csproj',
                    config: 'Release'
                }
            }
        },

        watch: {
            files: ['./**/*.ts', '!./node_modules/**'],
            tasks: ['ts:dev']
        },

        open: {
            dev: {
                path: 'http://localhost:8080/' + module + '/' + module + '.html'
            }
        }

    });

    grunt.registerTask('default', ['ts:dev', 'connect', 'open', 'watch']);

};
<commit_msg>fix grunt-ts<commit_after>'use strict';

module.exports = function (grunt) {

    // https://github.com/shootaroo/jit-grunt
    require('jit-grunt')(grunt);

    var module = grunt.option("module") || 'login';

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        connect: {
            server: {
                options: {
                    port: 8080,
                    base: './'
                }
            }
        },

        ts: {
            options: {
                failOnTypeErrors: false
            },
            dev: {
                src: ['**/*.ts', '!node_modules/**', '!.tscache/**']
            },
            debug: {
                src: ['**/*.ts', '!node_modules/**', '!.tscache/**']
            },
            release: {
                src: ['**/*.ts', '!node_modules/**', '!.tscache/**'],
                options: {
                    sourceMap: false
                }
            }
        },

        watch: {
            files: ['./**/*.ts', '!./node_modules/**'],
            tasks: ['ts:dev']
        },

        open: {
            dev: {
                path: 'http://localhost:8080/' + module + '/' + module + '.html'
            }
        }

    });

    grunt.registerTask('default', ['ts:dev', 'connect', 'open', 'watch']);

};
<|endoftext|>


<commit_before>/*
 * grunt-aco2less
 * https://github.com/teemualap/grunt-aco2less
 *
 * Copyright (c) 2013 Teemu Alapoikela
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js'
      ],
      options: {
        jshintrc: '.jshintrc'
      },
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['tmp'],
    },

    // Configuration to be run (and then tested).
    aco2less: {
      aco: {
        options: {
        },
        files: {
          'tmp/test.less': ['test/fixtures/test.aco']
        }
      }
    }

  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');

  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'aco2less']);

};
<commit_msg>updated tasks<commit_after>/*
 * grunt-aco2less
 * https://github.com/teemualap/grunt-aco2less
 *
 * Copyright (c) 2013 Teemu Alapoikela
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js'
      ],
      options: {
        jshintrc: '.jshintrc'
      },
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['tmp'],
    },

    // Configuration to be run (and then tested).
    aco2less: {
      aco: {
        options: {
        },
        files: {
          'tmp/test.less': ['test/fixtures/*.aco']
        }
      }
    }

  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');

  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'aco2less']);

};
<|endoftext|>