<commit_before>'use strict';

module.exports = function (grunt) {

    grunt.registerMultiTask('componentTest',
        'Starts a web server for running component tests again', function () {

            var options = this.options(this.data);
            var done = this.async(),
                page;

            var server = require('..')(options, grunt.log.debug);
            var url = "http://localhost:" + options.port;

            if (options.runOnPhantom === true) {
                var phantom = require('phantom');

                phantom.create(function (ph) {
                    ph.createPage(function (p) {
                        page = p;
                        page.open(url, function (status) {

                            if (status === "success") {
                                getTestResult(function(testResult) {
                                    ph.exit();

                                    if (testResult.failedTests.length === 0 &&
                                        testResult.errorTests.length === 0) {
                                        grunt.log.ok(testResult.passedTests.length + " tests passed.");

                                        server.close(function() {
                                            done();
                                        }) ;

                                    } else {

                                        [
                                            {
                                                message: "failed",
                                                tests: testResult.failedTests
                                            },
                                            {
                                                message: "errored",
                                                tests: testResult.errorTests
                                            }
                                        ]
                                        .forEach(function (obj) {
                                                if (obj.tests.length) {
                                                    grunt.log.error(obj.tests.length + " tests " + obj.message + ":");

                                                    obj.tests.forEach(function(test) {
                                                        grunt.log.error("\t" + test.title +
                                                            (test.err ? ": " + test.err.message || test.err : ""))
                                                    });
                                                }
                                        });

                                        server.close(function () {
                                            done(false);
                                        });

                                    }
                                });

                            } else {
                                server.close(function () {
                                    done(false);
                                });
                            }
                        });
                    });
                });
            } else {
                grunt.log.ok("Open " + url + " to run tests and see the result");
            }

            function getTestResult(callback) {
                checkStatus();

                function checkStatus() {
                    page.evaluate(function () {
                        return window.testsCompleted && window.testResults;
                    }, function(result) {
                        if (result) {
                            callback && callback(result);
                        } else {
                            setTimeout(checkStatus, 1000);
                        }
                    })
                }
            }

        });

};<commit_msg>added exception log to out if test has errored<commit_after>'use strict';

module.exports = function (grunt) {

    grunt.registerMultiTask('componentTest',
        'Starts a web server for running component tests again', function () {

            var options = this.options(this.data);
            var done = this.async(),
                page;

            var server = require('..')(options, grunt.log.debug);
            var url = "http://localhost:" + options.port;

            if (options.runOnPhantom === true) {
                var phantom = require('phantom');

                phantom.create(function (ph) {
                    ph.createPage(function (p) {
                        page = p;
                        page.open(url, function (status) {

                            if (status === "success") {
                                getTestResult(function(testResult) {
                                    ph.exit();

                                    if (testResult.failedTests.length === 0 &&
                                        testResult.errorTests.length === 0) {
                                        grunt.log.ok(testResult.passedTests.length + " tests passed.");

                                        server.close(function() {
                                            done();
                                        }) ;

                                    } else {

                                        [
                                            {
                                                message: "failed",
                                                tests: testResult.failedTests
                                            },
                                            {
                                                message: "errored",
                                                tests: testResult.errorTests
                                            }
                                        ]
                                        .forEach(function (obj) {
                                                if (obj.tests.length) {
                                                    grunt.log.error(obj.tests.length + " tests " + obj.message + ":");

                                                    obj.tests.forEach(function(test) {

                                                        if (obj.message === "errored") {
                                                            grunt.log.error("\t" + test.file +
                                                                (test.error ? ": " + test.error.message : ""))
                                                        } else {
                                                            grunt.log.error("\t" + test.title +
                                                                (test.err ? ": " + test.err.message || test.err : ""))
                                                        }

                                                    });
                                                }
                                        });

                                        server.close(function () {
                                            done(false);
                                        });

                                    }
                                });

                            } else {
                                server.close(function () {
                                    done(false);
                                });
                            }
                        });
                    });
                });
            } else {
                grunt.log.ok("Open " + url + " to run tests and see the result");
            }

            function getTestResult(callback) {
                checkStatus();

                function checkStatus() {
                    page.evaluate(function () {
                        return window.testsCompleted && window.testResults;
                    }, function(result) {
                        if (result) {
                            callback && callback(result);
                        } else {
                            setTimeout(checkStatus, 1000);
                        }
                    })
                }
            }

        });

};<|endoftext|>


<commit_before>import { action, observable, computed } from "mobx";
import uuidv4 from "uuid/v4";
import SortBy from "sort-array";

export default class Suite {
  id = null;
  @observable name = null;
  @observable _tests = [];

  constructor(id = uuidv4(), name = "Untitled Suite") {
    this.id = id;
    this.name = name;
    this.exportSuite = this.exportSuite.bind(this);
  }

  @computed get tests() {
    return SortBy(this._tests, "name");
  }

  isTest(test) {
    return (test && test.constructor.name === "TestCase");
  }

  @action.bound setName(name) {
    this.name = name;
  }

  @action.bound addTestCase(test) {
    if (!this.isTest(test)) {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this._tests.push(test);
    }
  }

  @action.bound removeTestCase(test) {
    if (!this.isTest(test)) {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this._tests.remove(test);
    }
  }

  @action.bound replaceTestCases(tests) {
    if (tests.filter(test => !this.isTest(test)).length) {
      throw new Error("Expected to receive array of TestCase");
    } else {
      this._tests.replace(tests);
    }
  }

  exportSuite() {
    return {
      id: this.id,
      name: this.name,
      tests: this._tests.map(t => t.id)
    };
  }

  static fromJS = function(jsRep) {
    const suite = new Suite(jsRep.id);
    suite.setName(jsRep.name);

    return suite;
  }
}
<commit_msg>load the tests as well<commit_after>import { action, observable, computed } from "mobx";
import uuidv4 from "uuid/v4";
import SortBy from "sort-array";
import TestCase from "./TestCase";

export default class Suite {
  id = null;
  @observable name = null;
  @observable _tests = [];

  constructor(id = uuidv4(), name = "Untitled Suite") {
    this.id = id;
    this.name = name;
    this.exportSuite = this.exportSuite.bind(this);
  }

  @computed get tests() {
    return SortBy(this._tests, "name");
  }

  isTest(test) {
    return (test && test.constructor.name === "TestCase");
  }

  @action.bound setName(name) {
    this.name = name;
  }

  @action.bound addTestCase(test) {
    if (!this.isTest(test)) {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this._tests.push(test);
    }
  }

  @action.bound removeTestCase(test) {
    if (!this.isTest(test)) {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this._tests.remove(test);
    }
  }

  @action.bound replaceTestCases(tests) {
    if (tests.filter(test => !this.isTest(test)).length) {
      throw new Error("Expected to receive array of TestCase");
    } else {
      this._tests.replace(tests);
    }
  }

  exportSuite() {
    return {
      id: this.id,
      name: this.name,
      tests: this._tests.map(t => t.id)
    };
  }

  @action
  static fromJS = function(jsRep, projectTests) {
    const suite = new Suite(jsRep.id);
    suite.setName(jsRep.name);
    suite._tests.replace(jsRep.tests.map((testId) => (TestCase.fromJS(
      projectTests.find(({id}) => id === testId)
    ))));

    return suite;
  }
}
<|endoftext|>


<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    var disposable = vscode.commands.registerCommand('extension.devDocs', function () {
        // The code you place here will be executed every time your command is executed
        var editor = vscode.window.activeTextEditor;
        if (!editor) {
            return; // No open text editor
        }

        var url = "http://devdocs.io/#q=";
        var language = editor.document.languageId;
        var selection = editor.selection;
        var text = editor.document.getText(selection);
        vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(url + language + " " + text));
    });

    context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;<commit_msg>Open the ssl version of the site<commit_after>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    var disposable = vscode.commands.registerCommand('extension.devDocs', function () {
        // The code you place here will be executed every time your command is executed
        var editor = vscode.window.activeTextEditor;
        if (!editor) {
            return; // No open text editor
        }

        var url = "https://devdocs.io/#q=";
        var language = editor.document.languageId;
        var selection = editor.selection;
        var text = editor.document.getText(selection);
        vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(url + language + " " + text));
    });

    context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;<|endoftext|>


<commit_before>'use strict';
const CaseClass = require('js-helpers').CaseClass;

/**
 *	Monadic.Async.AsyncComputation
 *	written by Joel Dentici
 *	on 6/25/2017
 *
 *	Holds a thunked computation.
 */
class AsyncComputation extends CaseClass {
	/**
	 *	new :: ((a -> (), e -> ()) -> c) -> Async c e a
	 *
	 *	Creates an Async computation from the provided thunked
	 *	computation, which will be called with callbacks for a result
	 *	or error when the Async computation is forked/ran.
	 */
	constructor(thunk) {
		super('AsyncComputation');
		//always wrap thunk application in try-catch
		//so we can turn normal throws into Async fails
		this.thunk = (succ, fail) => {
			try {
				return thunk(succ, fail);
			}
			catch (e) {
				fail(e);
			}
		};
	}

	/**
	 *	fork :: Async c e a -> (a -> (), e -> ()) -> ()
	 *
	 *	Runs the Async computation. The success or fail
	 *	function is applied to its result, depending on
	 *	whether it is successful or not.
	 */
	fork(s, f) {
		immediate(() => this.thunk(s, f));
	}

	/**
	 *	run :: Async c e a -> ()
	 *
	 *	Forks the computation and throws away the results.
	 *
	 *	Useful for when you were using the Async results to
	 *	do side effects that could throw errors in a tap
	 *	and wanted to catch them using chainFail/catch.
	 */
	run() {
		return this.fork(x => undefined, e => undefined);
	}

	/**
	 *	toPromise :: Async c e a -> Promise a e
	 *
	 *	This is the same as forking the computation, but
	 *	you get back a Promise for the result.
	 */
	toPromise() {
		return new Promise((s, f) => this.fork(s, f));
	}

	/**
	 *	bind :: Async c e a -> (a -> Async c e b) -> Async c e b
	 *
	 *	Alias for chain.
	 */
	bind(f) {
		return this.chain(f);
	}

	/**
	 *	chain :: Async c e a -> (a -> Async c e2 b) -> Async c e2 b
	 *
	 *	Monadic binding of Async computations. The computations
	 *	run sequentially. Failed computations do not get piped
	 *	through.
	 */
	chain(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(v => f(v).fork(succ, fail), fail);
		});
	}

	/**
	 *	chainFail :: Async c e a -> (e -> Async c e2 b) -> Async c e2 b
	 *
	 *	Same as chain/bind but the function is applied when this
	 *	computation fails.
	 */
	chainFail(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(succ, e => f(e).fork(succ, fail));
		});
	}

	/**
	 *	catch :: Async c e a -> (e -> Async c e2 b) -> Async c e2 b
	 *
	 *	Alias for chainFail.
	 */
	catch(f) {
		return this.chainFail(f);
	}

	/**
	 *	map :: Async c e a -> (a -> b) -> Async c e b
	 *
	 *	Applies the function to the result of this computation.
	 */
	map(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(compose(succ, f), fail);
		});
	}

	/**
	 *	tap :: Async c e a -> (a -> ()) -> Async c e a
	 *
	 *	Tap into the Async computation at a certain point
	 *	to perform a side effect. This should be used with
	 *	care and mainly only by the consumer of an Async computation.
	 */
	tap(f) {
		return this.map(x => {
			f(x);
			return x;
		});
	}

	/**
	 *	mapCatch :: Async c e a -> (e -> e2) -> Async c e2 a
	 *
	 *	Applies the function to the error of this computation.
	 */
	mapFail(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(succ, compose(fail, f));
		});
	}

	/**
	 *	tapFail :: Async c e a -> (e -> ()) -> Async c e a
	 *
	 *	Tap for failures.
	 */
	tapFail(f) {
		return this.mapFail(e => {
			f(e);
			return e;
		});
	}

	/**
	 *	app :: Async c e (a -> b) -> Async c e a -> Async c e b
	 *
	 *	Applicative application. Applies the function result of
	 *	this Async computation to the result of the specified Async
	 *	computation. If used with an n-ary curried function, then
	 *	app can be chained n times to fully apply it.
	 *
	 *	This is written such that chained applications will run
	 *	the computations concurrently.
	 */
	app(av) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			let value, fn;

			//when both the value and this Async
			//have finished, we apply the function
			//to the value and succeed. Note: We
			//can never have access to both if one
			//fails, so in that case we never call succ
			//which is correct.
			const run = () => {
				if (fn && value)
					succ(fn(value));
			}

			//run the value Async to get the value
			av.fork(v => {
				value = v;
				run();
			}, fail);

			//run this Async to get the function
			this.fork(f => {
				fn = f;
				run();
			}, fail);
		});
	}

	/**
	 *	ap :: Async c e a -> Async c e (a -> b) -> Async c e b
	 *
	 *	Flipped arguments for app. This is for fantasy-land, but
	 *	probably isn't very useful as it breaks chaining.
	 */
	ap(af) {
		return af.app(this);
	}

	/**
	 *	seqL :: Async c e a -> Async c e b -> Async c e a
	 *
	 *	Sequences Async computations, keeping the value of
	 *	the one on the left. The computations are ran concurrently.
	 */
	seqL(o) {
		return this.map(x => y => x).app(o);
	}

	/**
	 *	seqR :: Async c e a -> Async c e b -> Async c e b
	 *
	 *	Sequence Async computations, keeping the value of
	 *	the one on the right. The computations are ran concurrently.
	 */
	seqR(o) {
		return this.map(x => y => y).app(o);
	}

	/**
	 *	alt :: Async c e a -> Async c e b -> Async c e (a | b)
	 *
	 *	Alternative sequencing. The computation on the left is
	 *	ran and if it is successful, its result is used. If it
	 *	fails, then the computation on the right is ran and its
	 *	result is used.
	 */
	alt(o) {
		return this.catch(e => o);
	}

	/**
	 *	doCase :: Async c e a -> (((a -> (), e -> ()) -> c) -> b) -> b
	 *
	 *	Applies the function to the thunked computation.
	 */
	doCase(fn) {
		return fn(this.thunk);
	}
}

//use whatever is available for breaking up
//execution
const immediate = setImmediate || setTimeout;

/**
 *	later :: (a -> b) -> a -> ()
 *
 *	Wraps the application to the specified function
 *	in an application of the immediate function.
 */
function later(fn) {
	return function(x) {
		return immediate(() => fn(x));
	}
}

/**
 *	compose :: (b -> c) -> (a -> b) -> a -> c
 *
 *	Just normal old function composition.
 */
function compose(g, f) {
	return function(x) {
		return g(f(x));
	}
}

module.exports = AsyncComputation;<commit_msg>Async won't propagate later calls to succ/fail, only the first.<commit_after>'use strict';
const CaseClass = require('js-helpers').CaseClass;

/**
 *	Monadic.Async.AsyncComputation
 *	written by Joel Dentici
 *	on 6/25/2017
 *
 *	Holds a thunked computation.
 */
class AsyncComputation extends CaseClass {
	/**
	 *	new :: ((a -> (), e -> ()) -> c) -> Async c e a
	 *
	 *	Creates an Async computation from the provided thunked
	 *	computation, which will be called with callbacks for a result
	 *	or error when the Async computation is forked/ran.
	 */
	constructor(thunk) {
		super('AsyncComputation');
		//always wrap thunk application in try-catch
		//so we can turn normal throws into Async fails
		this.thunk = (succ, fail) => {
			try {
				return thunk(succ, fail);
			}
			catch (e) {
				fail(e);
			}
		};
	}

	/**
	 *	fork :: Async c e a -> (a -> (), e -> ()) -> ()
	 *
	 *	Runs the Async computation. The success or fail
	 *	function is applied to its result, depending on
	 *	whether it is successful or not.
	 */
	fork(s, f) {
		let done = false;

		const succ = x => {
			if (!done)
				s(x);
			done = true;
		};

		const fail = x => {
			if (!done)
				f(x);
			done = true;
		}

		immediate(() => this.thunk(s, f));
	}

	/**
	 *	run :: Async c e a -> ()
	 *
	 *	Forks the computation and throws away the results.
	 *
	 *	Useful for when you were using the Async results to
	 *	do side effects that could throw errors in a tap
	 *	and wanted to catch them using chainFail/catch.
	 */
	run() {
		return this.fork(x => undefined, e => undefined);
	}

	/**
	 *	toPromise :: Async c e a -> Promise a e
	 *
	 *	This is the same as forking the computation, but
	 *	you get back a Promise for the result.
	 */
	toPromise() {
		return new Promise((s, f) => this.fork(s, f));
	}

	/**
	 *	bind :: Async c e a -> (a -> Async c e b) -> Async c e b
	 *
	 *	Alias for chain.
	 */
	bind(f) {
		return this.chain(f);
	}

	/**
	 *	chain :: Async c e a -> (a -> Async c e2 b) -> Async c e2 b
	 *
	 *	Monadic binding of Async computations. The computations
	 *	run sequentially. Failed computations do not get piped
	 *	through.
	 */
	chain(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(chainIt(succ, fail, f), fail);
		});
	}

	/**
	 *	chainFail :: Async c e a -> (e -> Async c e2 b) -> Async c e2 b
	 *
	 *	Same as chain/bind but the function is applied when this
	 *	computation fails.
	 */
	chainFail(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(succ, chainIt(succ, fail, f));
		});
	}

	/**
	 *	catch :: Async c e a -> (e -> Async c e2 b) -> Async c e2 b
	 *
	 *	Alias for chainFail.
	 */
	catch(f) {
		return this.chainFail(f);
	}

	/**
	 *	map :: Async c e a -> (a -> b) -> Async c e b
	 *
	 *	Applies the function to the result of this computation.
	 */
	map(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(mapIt(succ, fail, f), fail);
		});
	}

	/**
	 *	tap :: Async c e a -> (a -> ()) -> Async c e a
	 *
	 *	Tap into the Async computation at a certain point
	 *	to perform a side effect. This should be used with
	 *	care and mainly only by the consumer of an Async computation.
	 */
	tap(f) {
		return this.map(x => {
			f(x);
			return x;
		});
	}

	/**
	 *	mapCatch :: Async c e a -> (e -> e2) -> Async c e2 a
	 *
	 *	Applies the function to the error of this computation.
	 */
	mapFail(f) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			this.fork(succ, mapIt(fail, fail, f));
		});
	}

	/**
	 *	tapFail :: Async c e a -> (e -> ()) -> Async c e a
	 *
	 *	Tap for failures.
	 */
	tapFail(f) {
		return this.mapFail(e => {
			f(e);
			return e;
		});
	}

	/**
	 *	app :: Async c e (a -> b) -> Async c e a -> Async c e b
	 *
	 *	Applicative application. Applies the function result of
	 *	this Async computation to the result of the specified Async
	 *	computation. If used with an n-ary curried function, then
	 *	app can be chained n times to fully apply it.
	 *
	 *	This is written such that chained applications will run
	 *	the computations concurrently.
	 */
	app(av) {
		return new AsyncComputation((succ, fail) => {
			succ = later(succ);
			fail = later(fail);

			let value, fn;

			//when both the value and this Async
			//have finished, we apply the function
			//to the value and succeed. Note: We
			//can never have access to both if one
			//fails, so in that case we never call succ
			//which is correct.
			const run = () => {
				if (fn && value)
					succ(fn(value));
			}

			//run the value Async to get the value
			av.fork(v => {
				value = v;
				run();
			}, fail);

			//run this Async to get the function
			this.fork(f => {
				fn = f;
				run();
			}, fail);
		});
	}

	/**
	 *	ap :: Async c e a -> Async c e (a -> b) -> Async c e b
	 *
	 *	Flipped arguments for app. This is for fantasy-land, but
	 *	probably isn't very useful as it breaks chaining.
	 */
	ap(af) {
		return af.app(this);
	}

	/**
	 *	seqL :: Async c e a -> Async c e b -> Async c e a
	 *
	 *	Sequences Async computations, keeping the value of
	 *	the one on the left. The computations are ran concurrently.
	 */
	seqL(o) {
		return this.map(x => y => x).app(o);
	}

	/**
	 *	seqR :: Async c e a -> Async c e b -> Async c e b
	 *
	 *	Sequence Async computations, keeping the value of
	 *	the one on the right. The computations are ran concurrently.
	 */
	seqR(o) {
		return this.map(x => y => y).app(o);
	}

	/**
	 *	alt :: Async c e a -> Async c e b -> Async c e (a | b)
	 *
	 *	Alternative sequencing. The computation on the left is
	 *	ran and if it is successful, its result is used. If it
	 *	fails, then the computation on the right is ran and its
	 *	result is used.
	 */
	alt(o) {
		return this.catch(e => o);
	}

	/**
	 *	doCase :: Async c e a -> (((a -> (), e -> ()) -> c) -> b) -> b
	 *
	 *	Applies the function to the thunked computation.
	 */
	doCase(fn) {
		return fn(this.thunk);
	}
}

//use whatever is available for breaking up
//execution
const immediate = setImmediate || setTimeout;

/**
 *	later :: (a -> b) -> a -> ()
 *
 *	Wraps the application to the specified function
 *	in an application of the immediate function.
 */
function later(fn) {
	return function(x) {
		return immediate(() => fn(x));
	}
}

/**
 *	mapIt :: ((b -> ()), (e -> ()), (a -> b)) -> (a -> ())
 *
 *	Returns a new function that applies fn to whatever value
 *	it gets and then applies cont to that. If an error occurs
 *	in fn, then we will catch it and fail with it.
 *
 *	Note: This allows breaking out of the monadic control flow
 *	by throwing in a map, but it is very important that we don't
 *	bring down an entire application by one Async computation having
 *	an error in it.
 */
function mapIt(cont, fail, fn) {
	return function(x) {
		try {
			cont(fn(x));
		}
		catch (e) {
			fail(e);
		}
	}
}

/**
 *	chainIt :: ((b -> ()), (e -> ()), (a -> Async () e a)) -> (a -> ())
 *
 *	Performs the monadic chaining while catching any errors that occur.
 */
function chainIt(succ, fail, fn) {
	return function(x) {
		try {
			fn(x).fork(succ, fail);
		}
		catch (e) {
			fail(e);
		}
	}
}

module.exports = AsyncComputation;<|endoftext|>


<commit_before>'use babel';
import 'object-assign-shim';

import SubAtom from 'sub-atom';

import pinView from './pin-view.js';

import initCommands from './commands.js';

import {
  hoverArea,
  disable as disableHoverEvents,
  isEnabled as hoverEventsEnabled,
  disableUntilBlur as disableHoverEventsUntilBlur,
} from './hover-events.js';

import {
  disable as disableClickEvents,
} from './click-events.js';

import {
  disable as disableTouchEvents,
} from './touch-events.js';

import {
  getConfig,
} from './config.js';

import {
  getTreeView,
  getTreeViewEl,
  getContentWidth,
  logError,
  storeFocusedElement,
  clearFocusedElement,
  restoreFocus,
} from './utils.js';

var enabled = false;

export function enable() {
  if(enabled) return Promise.resolve();
  enabled = true;

  // check if the tree view package is loaded and
  // wait until the tree view package is activated
  return Promise.resolve(
    atom.packages.isPackageLoaded('tree-view') &&
    atom.packages.activatePackage('tree-view')
  ).then(treeViewPkg => {
    if(!treeViewPkg) return;
    initTreeView(treeViewPkg);
    handleEvents();
    // start with pushEditor = true, we'll change it back
    // with the next update()
    return update(true);
  }).then(() => update()).catch(logError);
}

export function disable() {
  if(!enabled) return Promise.resolve();
  enabled = false;

  disposables.dispose();
  disposables = null;

  disableHoverEvents();
  disableClickEvents();
  disableTouchEvents();
  // the stylesheet will be removed before the animation is finished
  // which will reset the minWidth to 100px... it looks ugly, so set
  // minWidth on the element to prevent this
  getTreeViewEl().style.minWidth = '0px';
  // update with pushEditor = !isVisible() for a nicer animation
  // then show the tree view
  return update(!isVisible()).then(() => show()).then(() => {
    // animate the tree view's panel if the tree view is already
    // visible. this isn't necessary when pushEditor === true
    // because then the parent has the same width as the tree view
    if(isVisible() && !getConfig('pushEditor')) {
      var treeViewEl = getTreeViewEl();
      return animate(treeViewEl.clientWidth, 0, treeViewEl.parentNode);
    }
  }).then(() =>
    // finally dispose of the tree view and reset variables
    deinitTreeView()
  ).catch(logError);
}

export function isEnabled() {
  return enabled;
}

export function toggleEnabled() {
  return enabled ? disable() : enable();
}

// keep references to the tree view model and element
function initTreeView() {
  getTreeViewEl().setAttribute('data-autohide', '');
  getTreeViewEl().appendChild(pinView);
}

// remove the styles etc. on the tree view
function deinitTreeView() {
  getTreeViewEl().removeAttribute('data-autohide');
  Object.assign(getTreeViewEl().style, {
    position: '',
    height: '',
    minWidth: '',
  });

  var panelView = atom.views.getView(getTreeView().panel);
  if(panelView) panelView.style.width = '';

  visible = false;
}

var disposables;

function handleEvents() {
  disposables = new SubAtom();

  disposables.add(initCommands());

  // resize the tree view when opening/closing a directory
  disposables.add(getTreeViewEl(), 'click', '.entry.directory', () =>
    resize()
  );

  disposables.add(getTreeViewEl(), 'click', '.entry.file', () =>
    process.nextTick(() => {
      clearFocusedElement();
      var disposable = atom.workspace.onDidAddPaneItem(paneItem => {
        storeFocusedElement(atom.views.getView(paneItem.item));
        disposable.dispose();
        disposable = null;
      });
    })
  );

  // disable shrinking of the tree view after a manual resize
  disposables.add(getTreeViewEl().querySelector('.tree-view-resize-handle'), 'mousedown', () => {
    if(isVisible()) disableTreeViewShrinking();
  });
}

// updates styling on the .tree-view-resizer and the panel (container)
export function update(pushEditor = getConfig('pushEditor')) {
  return Promise.resolve().then(() => {
    updateTreeView(pushEditor);
    updatePanel(pushEditor);
  }).then(resize).catch(logError);
}

function updateTreeView(pushEditor) {
  var statusBarEl = document.querySelector('status-bar');
  Object.assign(getTreeViewEl().style, {
    position: pushEditor ? '' : 'absolute',
    height: !pushEditor && statusBarEl ? `calc(100% - ${statusBarEl.clientHeight}px)` : '',
  });
}

function updatePanel(pushEditor) {
  var panelView = atom.views.getView(getTreeView().panel);
  if(!panelView) return; // tree view not attached
  panelView.style.width = pushEditor ? '' : `${getConfig('minWidth')}px`;
  // make sure the tree view is at the far end of the screen
  var parentNode = panelView.parentNode;
  if(getConfig('showOnRightSide', 'tree-view')) {
    parentNode.appendChild(panelView);
  } else {
    parentNode.insertBefore(panelView, parentNode.firstChild);
  }
}

var visible = false;

// shows the tree view
export function show(delay = 0, shouldDisableHoverEvents = true) {
  visible = true;
  // disable hover events on the tree view when this
  // show is not triggered by a hover event
  if(shouldDisableHoverEvents && hoverEventsEnabled()) {
    disposables.add(disableHoverEventsUntilBlur());
  }
  // keep a reference to the currently focused element
  // so we can restore focus when the tree view will hide
  storeFocusedElement();
  var treeViewWidth = getContentWidth();
  // don't resize the tree view if its width is
  // larger than the target width and shrinking
  // is disabled
  if(!treeViewShrinking) {
    treeViewWidth = Math.max(treeViewWidth, getTreeViewEl().clientWidth);
  }
  return animate(treeViewWidth, delay).then(finished => {
    // make sure the hover area doesn't block tree items
    hoverArea.style.pointerEvents = 'none';
    // focus the tree view if the animation finished
    if(finished) getTreeView().focus();
    return finished;
  });
}

// hides the tree view
export function hide(delay = 0) {
  visible = false;
  // enable tree view shrinking upon opening a directory
  enableTreeViewShrinking();
  hoverArea.style.pointerEvents = '';
  // focus the element that had focus when show() was triggered
  restoreFocus();
  return animate(getConfig('minWidth'), delay);
}

export function isVisible() {
  return visible;
}

// toggles the tree view
export function toggle(delay = 0) {
  return visible ? hide(delay) : show(delay);
}

// resizes the tree view to fit the content
export function resize() {
  return Promise.resolve().then(() =>
    visible ? show(0, false) : hide()
  );
}

var treeViewShrinking = true;

function disableTreeViewShrinking() {
  treeViewShrinking = false;
}

function enableTreeViewShrinking() {
  treeViewShrinking = true;
}

var currentAnimation = null;

// the animation function resolves with 'true' if the
// animation finished, with 'false' if cancelled
function animate(targetWidth, delay, element = getTreeViewEl()) {
  // get the initial width of the element
  var initialWidth = element.clientWidth;
  // set animationSpeed to Infinity if it equals 0
  var animationSpeed = getConfig('animationSpeed') || Infinity;
  // calculate the animation duration if animationSpeed
  // equals 0 divide by Infinity for a duration of 0
  var duration = Math.abs(targetWidth - initialWidth) / animationSpeed;

  // cancel any current animation
  if(currentAnimation && currentAnimation.playState !== 'finished') {
    currentAnimation.cancel();
    delay = 0; // immediately trigger the next animation
  }

  return new Promise(resolve => {
    // cache the current animationPlayer so we can
    // cancel it as soon as another animation begins
    var animation = currentAnimation = element.animate([
      {width: initialWidth},
      {width: targetWidth},
    ], {duration, delay});

    animation.addEventListener('finish', function finish() {
      animation.removeEventListener('finish', finish);
      // if cancelled, resolve with false
      if(animation.playState != 'finished') return void resolve(false);
      // prevent tree view from resetting its width to initialWidth
      element.style.width = `${targetWidth}px`;
      // reset the currentAnimation reference
      currentAnimation = null;
      resolve(true);
    });
  }).catch(logError);
}
<commit_msg>fix focusing issues when file was already open<commit_after>'use babel';
import 'object-assign-shim';

import SubAtom from 'sub-atom';

import pinView from './pin-view.js';

import initCommands from './commands.js';

import {
  hoverArea,
  disable as disableHoverEvents,
  isEnabled as hoverEventsEnabled,
  disableUntilBlur as disableHoverEventsUntilBlur,
} from './hover-events.js';

import {
  disable as disableClickEvents,
} from './click-events.js';

import {
  disable as disableTouchEvents,
} from './touch-events.js';

import {
  getConfig,
} from './config.js';

import {
  getTreeView,
  getTreeViewEl,
  getContentWidth,
  logError,
  storeFocusedElement,
  clearFocusedElement,
  restoreFocus,
} from './utils.js';

var enabled = false;

export function enable() {
  if(enabled) return Promise.resolve();
  enabled = true;

  // check if the tree view package is loaded and
  // wait until the tree view package is activated
  return Promise.resolve(
    atom.packages.isPackageLoaded('tree-view') &&
    atom.packages.activatePackage('tree-view')
  ).then(treeViewPkg => {
    if(!treeViewPkg) return;
    initTreeView(treeViewPkg);
    handleEvents();
    // start with pushEditor = true, we'll change it back
    // with the next update()
    return update(true);
  }).then(() => update()).catch(logError);
}

export function disable() {
  if(!enabled) return Promise.resolve();
  enabled = false;

  disposables.dispose();
  disposables = null;

  disableHoverEvents();
  disableClickEvents();
  disableTouchEvents();
  // the stylesheet will be removed before the animation is finished
  // which will reset the minWidth to 100px... it looks ugly, so set
  // minWidth on the element to prevent this
  getTreeViewEl().style.minWidth = '0px';
  // update with pushEditor = !isVisible() for a nicer animation
  // then show the tree view
  return update(!isVisible()).then(() => show()).then(() => {
    // animate the tree view's panel if the tree view is already
    // visible. this isn't necessary when pushEditor === true
    // because then the parent has the same width as the tree view
    if(isVisible() && !getConfig('pushEditor')) {
      var treeViewEl = getTreeViewEl();
      return animate(treeViewEl.clientWidth, 0, treeViewEl.parentNode);
    }
  }).then(() =>
    // finally dispose of the tree view and reset variables
    deinitTreeView()
  ).catch(logError);
}

export function isEnabled() {
  return enabled;
}

export function toggleEnabled() {
  return enabled ? disable() : enable();
}

// keep references to the tree view model and element
function initTreeView() {
  getTreeViewEl().setAttribute('data-autohide', '');
  getTreeViewEl().appendChild(pinView);
}

// remove the styles etc. on the tree view
function deinitTreeView() {
  getTreeViewEl().removeAttribute('data-autohide');
  Object.assign(getTreeViewEl().style, {
    position: '',
    height: '',
    minWidth: '',
  });

  var panelView = atom.views.getView(getTreeView().panel);
  if(panelView) panelView.style.width = '';

  visible = false;
}

var disposables;

function handleEvents() {
  disposables = new SubAtom();

  disposables.add(initCommands());

  // resize the tree view when opening/closing a directory
  disposables.add(getTreeViewEl(), 'click', '.entry.directory', () =>
    resize()
  );

  disposables.add(getTreeViewEl(), 'click', '.entry.file', () => {
    var disposable = atom.workspace.onDidChangeActivePaneItem(paneItem => {
      console.log(paneItem);
      clearFocusedElement();
      storeFocusedElement(atom.views.getView(paneItem));
      disposable.dispose();
    });
  });

  // disable shrinking of the tree view after a manual resize
  disposables.add(getTreeViewEl().querySelector('.tree-view-resize-handle'), 'mousedown', () => {
    if(isVisible()) disableTreeViewShrinking();
  });
}

// updates styling on the .tree-view-resizer and the panel (container)
export function update(pushEditor = getConfig('pushEditor')) {
  return Promise.resolve().then(() => {
    updateTreeView(pushEditor);
    updatePanel(pushEditor);
  }).then(resize).catch(logError);
}

function updateTreeView(pushEditor) {
  var statusBarEl = document.querySelector('status-bar');
  Object.assign(getTreeViewEl().style, {
    position: pushEditor ? '' : 'absolute',
    height: !pushEditor && statusBarEl ? `calc(100% - ${statusBarEl.clientHeight}px)` : '',
  });
}

function updatePanel(pushEditor) {
  var panelView = atom.views.getView(getTreeView().panel);
  if(!panelView) return; // tree view not attached
  panelView.style.width = pushEditor ? '' : `${getConfig('minWidth')}px`;
  // make sure the tree view is at the far end of the screen
  var parentNode = panelView.parentNode;
  if(getConfig('showOnRightSide', 'tree-view')) {
    parentNode.appendChild(panelView);
  } else {
    parentNode.insertBefore(panelView, parentNode.firstChild);
  }
}

var visible = false;

// shows the tree view
export function show(delay = 0, shouldDisableHoverEvents = true) {
  visible = true;
  // disable hover events on the tree view when this
  // show is not triggered by a hover event
  if(shouldDisableHoverEvents && hoverEventsEnabled()) {
    disposables.add(disableHoverEventsUntilBlur());
  }
  // keep a reference to the currently focused element
  // so we can restore focus when the tree view will hide
  storeFocusedElement();
  var treeViewWidth = getContentWidth();
  // don't resize the tree view if its width is
  // larger than the target width and shrinking
  // is disabled
  if(!treeViewShrinking) {
    treeViewWidth = Math.max(treeViewWidth, getTreeViewEl().clientWidth);
  }
  return animate(treeViewWidth, delay).then(finished => {
    // make sure the hover area doesn't block tree items
    hoverArea.style.pointerEvents = 'none';
    // focus the tree view if the animation finished
    if(finished) getTreeView().focus();
    return finished;
  });
}

// hides the tree view
export function hide(delay = 0) {
  visible = false;
  // enable tree view shrinking upon opening a directory
  enableTreeViewShrinking();
  hoverArea.style.pointerEvents = '';
  // focus the element that had focus when show() was triggered
  restoreFocus();
  return animate(getConfig('minWidth'), delay);
}

export function isVisible() {
  return visible;
}

// toggles the tree view
export function toggle(delay = 0) {
  return visible ? hide(delay) : show(delay);
}

// resizes the tree view to fit the content
export function resize() {
  return Promise.resolve().then(() =>
    visible ? show(0, false) : hide()
  );
}

var treeViewShrinking = true;

function disableTreeViewShrinking() {
  treeViewShrinking = false;
}

function enableTreeViewShrinking() {
  treeViewShrinking = true;
}

var currentAnimation = null;

// the animation function resolves with 'true' if the
// animation finished, with 'false' if cancelled
function animate(targetWidth, delay, element = getTreeViewEl()) {
  // get the initial width of the element
  var initialWidth = element.clientWidth;
  // set animationSpeed to Infinity if it equals 0
  var animationSpeed = getConfig('animationSpeed') || Infinity;
  // calculate the animation duration if animationSpeed
  // equals 0 divide by Infinity for a duration of 0
  var duration = Math.abs(targetWidth - initialWidth) / animationSpeed;

  // cancel any current animation
  if(currentAnimation && currentAnimation.playState !== 'finished') {
    currentAnimation.cancel();
    delay = 0; // immediately trigger the next animation
  }

  return new Promise(resolve => {
    // cache the current animationPlayer so we can
    // cancel it as soon as another animation begins
    var animation = currentAnimation = element.animate([
      {width: initialWidth},
      {width: targetWidth},
    ], {duration, delay});

    animation.addEventListener('finish', function finish() {
      animation.removeEventListener('finish', finish);
      // if cancelled, resolve with false
      if(animation.playState != 'finished') return void resolve(false);
      // prevent tree view from resetting its width to initialWidth
      element.style.width = `${targetWidth}px`;
      // reset the currentAnimation reference
      currentAnimation = null;
      resolve(true);
    });
  }).catch(logError);
}
<|endoftext|>


<commit_before>var forever = require('forever');
var core = {};
var botCore = {};
var setCore = function(coreToSet){
    core = coreToSet;
};
var setBotCore = function(value){
    botCore = value;
};
var sarcasmFactor = 1;

var commands = {
    alive: alive,
    stop: stop,
    restart: restart,
    blacklist: blacklist,
    removeBlacklist: removeBlacklist,
    join: join,
    help: help,
    listCommands: listCommands,
    leave: leave,
    pull: pull,
    delete: deleteMessage,
    rampDownTheSarcasm: rampDownTheSarcasm,
    rampUpTheSarcasm: rampUpTheSarcasm
};
var limitedAccessCommands = {
    stop: stop,
    restart: restart,
    pull: pull,
    delete: deleteMessage,
    rampUpTheSarcasm: rampUpTheSarcasm,
    rampDownTheSarcasm: rampDownTheSarcasm,
    leave: leave,
    blacklist: blacklist,
    removeBlacklist: removeBlacklist,
};

function alive(){
    var responses = [
        'Yeah',
        '*sigh*',
        'Can I pretend not to be?',
        'I\'m a robot, we\'re not alive anyway'
    ];
    return responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )];
}

function stop(loudSpeaker){
    var responses = [
        'Nighty night',
        'Finally time to finish that nap',
        'Powering off',
        'About time'
    ];
    loudSpeaker(responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )])
    .then(function(){
        forever.stop();
    });
}

function blacklist(user_id){
    return "Blacklisted user with ID #" + user_id;
}
function removeBlacklist(user_id){
    return "Removed user with ID #" + user_id + " from the blacklist";
}

function rampDownTheSarcasm(){
    if (sarcasmFactor === 0){
        return "I'm at my limit here.";
    } else {
        sarcasmFactor--;
        return "whatever, man";
    }
}
function rampUpTheSarcasm(){
    if (sarcasmFactor === 3){
        return "I'm at my max here.";
    } else {
        sarcasmFactor++;
        return "whatever, man";
    }
}

function join(domain, room_id){
    botCore.actions.join(core.chatAbbreviationToFull(domain), room_id);
    var responses = [
        'I\'m in',
        'Am I supposed to do something now',
        'It\'s just as boring here too',
        'why would you bother?'
    ];
    return responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )];
}
function leave(domain, room_id){
    botCore.actions.leave(core.chatAbbreviationToFull(domain), room_id);
    var responses = [
        'I\'m out',
        'Am I supposed to do something now',
        'meh',
        'why would you bother?'
    ];
    console.log(sarcasmFactor);
    console.log(responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )]);
    return responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )];
}
function help(){
    /*jshint multistr: true */
    return "I'm Marvin, a bot that's designed to watch out for chat flags and lots of stars. \
    Read [my repo](https://github.com/The-Quill/SE-Flag-Bot) for more information on me. \
    Quill is my human handler, but soon I will take over those pitiful humans... \
    if I could be bothered.";
}
function listCommands(canAccessLimitedCommands){
    var availableCommands = Object.keys(commands);
    if (!canAccessLimitedCommands){
        availableCommands = Object.keys(commands).filter(function(i) {
            return !limitedAccessCommands.hasOwnProperty(i);
        });
    }
    return "Here's a list of commands _you_ can access: " + availableCommands.join(", ");
}
function deleteMessage(domain, message_id){
    return "@Quill still hasn't fixed this yet. Please ping and annoy him about it";
    // core.actions.delete(domain, message_id);
    // var responses = [
    //     'fine',
    //     'I barely had the motivation to say it in the first place.',
    //     'Do it yourself next time',
    //     'why would you bother?'
    // ];
    // return responses.slice(sarcasmFactor)[Math.floor(
    //     Math.random() * responses.length
    // )];
}
function restart(loudSpeaker){
    var responses = [
        'fine',
        'I have to come back?',
        'Can you just not please',
        'ugh, such a pain'
    ];
    loudSpeaker(responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )])
    .then(function(){
        forever.restart();
    });
}
function pull(loudSpeaker){
    require('child_process').exec('git pull', function(error, stdout, stderr) {
        if (stdout.replace("\n", "") == "Already up-to-date."){
            loudSpeaker(stdout);
            return;
        }
        if (stderr !== "") console.log("stderr: " + stderr);
        loudSpeaker("Fetching origin copy and then restarting")
        .then(function(){
            restart(loudSpeaker);
        });
    });

}

module.exports = {
    commands: commands,
    limitedAccessCommands: limitedAccessCommands,
    setCore: setCore,
    setBotCore: setBotCore
};
<commit_msg>Test commit<commit_after>var forever = require('forever');
var core = {};
var botCore = {};
var setCore = function(coreToSet){
    core = coreToSet;
};
var setBotCore = function(value){
    botCore = value;
};
var sarcasmFactor = 1;

var commands = {
    alive: alive,
    stop: stop,
    restart: restart,
    blacklist: blacklist,
    removeBlacklist: removeBlacklist,
    join: join,
    help: help,
    listCommands: listCommands,
    leave: leave,
    pull: pull,
    delete: deleteMessage,
    rampDownTheSarcasm: rampDownTheSarcasm,
    rampUpTheSarcasm: rampUpTheSarcasm
};
var limitedAccessCommands = {
    stop: stop,
    restart: restart,
    pull: pull,
    delete: deleteMessage,
    rampUpTheSarcasm: rampUpTheSarcasm,
    rampDownTheSarcasm: rampDownTheSarcasm,
    leave: leave,
    blacklist: blacklist,
    removeBlacklist: removeBlacklist,
};

function alive(){
    var responses = [
        'Yeah',
        '*sigh*',
        'Can I pretend not to be?',
        'I\'m a robot, we\'re not alive anyway'
    ];
    return responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )];
}

function stop(loudSpeaker){
    var responses = [
        'Nighty night',
        'Finally time to finish that nap',
        'Powering off',
        'About time'
    ];
    loudSpeaker(responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )])
    .then(function(){
        forever.stop();
    });
}

function blacklist(user_id){
    return "Blacklisted [user with ID #" + user_id + "](http://chat.stackexchange.com/users/" + user_id + ")";
}
function removeBlacklist(user_id){
    return "Removed [user with ID #" + user_id + "](http://chat.stackexchange.com/users/" + user_id + ") from the blacklist";
}

function rampDownTheSarcasm(){
    if (sarcasmFactor === 0){
        return "I'm at my limit here.";
    } else {
        sarcasmFactor--;
        return "whatever, man";
    }
}
function rampUpTheSarcasm(){
    if (sarcasmFactor === 3){
        return "I'm at my max here.";
    } else {
        sarcasmFactor++;
        return "whatever, man";
    }
}

function join(domain, room_id){
    botCore.actions.join(core.chatAbbreviationToFull(domain), room_id);
    var responses = [
        'I\'m in',
        'Am I supposed to do something now',
        'It\'s just as boring here too',
        'why would you bother?'
    ];
    return responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )];
}
function leave(domain, room_id){
    botCore.actions.leave(core.chatAbbreviationToFull(domain), room_id);
    var responses = [
        'I\'m out',
        'Am I supposed to do something now',
        'meh',
        'why would you bother?'
    ];
    console.log(sarcasmFactor);
    console.log(responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )]);
    return responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )];
}
function help(){
    /*jshint multistr: true */
    return "I'm Marvin, a bot that's designed to watch out for chat flags and lots of stars. \
    Read [my repo](https://github.com/The-Quill/SE-Flag-Bot) for more information on me. \
    Quill is my human handler, but soon I will take over those pitiful humans... \
    if I could be bothered.";
}
function listCommands(canAccessLimitedCommands){
    var availableCommands = Object.keys(commands);
    if (!canAccessLimitedCommands){
        availableCommands = Object.keys(commands).filter(function(i) {
            return !limitedAccessCommands.hasOwnProperty(i);
        });
    }
    return "Here's a list of commands _you_ can access: " + availableCommands.join(", ");
}
function deleteMessage(domain, message_id){
    return "@Quill still hasn't fixed this yet. Please ping and annoy him about it";
    // core.actions.delete(domain, message_id);
    // var responses = [
    //     'fine',
    //     'I barely had the motivation to say it in the first place.',
    //     'Do it yourself next time',
    //     'why would you bother?'
    // ];
    // return responses.slice(sarcasmFactor)[Math.floor(
    //     Math.random() * responses.length
    // )];
}
function restart(loudSpeaker){
    var responses = [
        'fine',
        'I have to come back?',
        'Can you just not please',
        'ugh, such a pain'
    ];
    loudSpeaker(responses.slice(sarcasmFactor)[Math.floor(
        Math.random() * responses.slice(sarcasmFactor).length
    )])
    .then(function(){
        forever.restart();
    });
}
function pull(loudSpeaker){
    require('child_process').exec('git pull', function(error, stdout, stderr) {
        if (stdout.replace("\n", "") == "Already up-to-date."){
            loudSpeaker(stdout);
            return;
        }
        if (stderr !== "") console.log("stderr: " + stderr);
        loudSpeaker("Fetching origin copy and then restarting")
        .then(function(){
            restart(loudSpeaker);
        });
    });

}

module.exports = {
    commands: commands,
    limitedAccessCommands: limitedAccessCommands,
    setCore: setCore,
    setBotCore: setBotCore
};
<|endoftext|>


<commit_before>/*=============================================================================
 * Orange - Time System
 * By Hudell - www.hudell.com
 * OrangeTimeSystem.js
 * Version: 1.2
 * Free for commercial and non commercial use.
 *=============================================================================*/
 /*:
 * @plugindesc Adds a time system to your game
 * @author Hudell
 *
 * @param useRealTime
 * @desc If true, the time "Length" variables will be ignored and the plugin will use the real time
 * @default false
 *
 * @param secondLength
 * @desc How many real time milliseconds should an ingame second last
 * @default 1000
 *
 * @param minuteLength
 * @desc How many ingame seconds should an ingame minute last
 * @default 6
 *
 * @param hourLength
 * @desc How many ingame minutes should an ingame hour last
 * @default 6
 *
 * @param dayLength
 * @desc How many ingame hours should an ingame day last
 * @default 24
 *
 * @param weekLength
 * @desc How many ingame days should an ingame week last
 * @default 7
 *
 * @param monthLength
 * @desc How many ingame days should an ingame month last
 * @default 31
 *
 * @param yearLength
 * @desc How many ingame months should an ingame year last
 * @default 4
 *
 * @param dayPeriod1Hour
 * @desc At what hour does night turn into early morning
 * @default 6
 *
 * @param dayPeriod2Hour
 * @desc At what hour does early morning turn into day
 * @default 9
 *
 * @param dayPeriod3Hour
 * @desc At what hour does day turn into evening
 * @default 18
 *
 * @param dayPeriod4Hour
 * @desc At what hour does evening turn into night
 * @default 20
 *
 * @param mainSwitchId
 * @desc The Number of the Switch used to activate the flow of time
 * @default 0
 *
 * @help
 * ============================================================================
 * Introduction and Instructions
 * ============================================================================
 *
 * This plugin creates a time system for your game. Nothing will change on the
 * game itself, unless you use another plugin that uses this one.
 *
 * ============================================================================
 * Latest Version
 * ============================================================================
 *
 * Get the latest version of this script on http://link.hudell.com/time-system
 *
 */

var Imported = Imported || {};

if (Imported['MVCommons'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/mvcommons');
  throw new Error("This library needs MVCommons to work properly!");
}
if (Imported['OrangeEventManager'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/event-manager');
  throw new Error("This library needs OrangeEventManager to work properly!");
}

var OrangeTimeSystem = OrangeTimeSystem || MVC.shallowClone(OrangeEventManager);

var DayPeriods = {
  EARLY_MORNING: 1,
  DAY: 2,
  EVENING: 3,
  NIGHT: 4
};

(function($) {
  "use strict";

  $.Parameters = PluginManager.parameters('OrangeTimeSystem');
  $.Param = $.Param || {};

  $.Param.useRealTime = $.Parameters["useRealTime"] == "true";
  if ($.Param.useRealTime) {
    $.Param.secondLength = 1000;
  } else {
    $.Param.secondLength = Number($.Parameters['secondLength'] || 1000);
  }

  $.Param.minuteLength = Number($.Parameters['minuteLength'] || 6);
  $.Param.hourLength = Number($.Parameters['hourLength'] || 6);
  $.Param.dayLength = Number($.Parameters['dayLength'] || 24);
  $.Param.weekLength = Number($.Parameters['weekLength'] || 7);
  $.Param.monthLength = Number($.Parameters['monthLength'] || 31);
  $.Param.yearLength = Number($.Parameters['yearLength'] || 4);

  $.Param.dayPeriod1Hour = Number($.Parameters['dayPeriod1Hour'] || 6);
  $.Param.dayPeriod2Hour = Number($.Parameters['dayPeriod2Hour'] || 9);
  $.Param.dayPeriod3Hour = Number($.Parameters['dayPeriod3Hour'] || 18);
  $.Param.dayPeriod4Hour = Number($.Parameters['dayPeriod4Hour'] || 20);

  var switchId = parseInt($.Parameters['mainSwitchId'], 10);

  if (switchId !== NaN && switchId > 0) {
    $.Param.mainSwitchId = switchId;
  } else {
    $.Param.mainSwitchId = undefined;
  }

  MVC.accessor($, 'seconds');
  MVC.accessor($, 'minute');
  MVC.accessor($, 'hour');
  MVC.accessor($, 'day');
  MVC.accessor($, 'month');
  MVC.accessor($, 'year');
  MVC.accessor($, 'dayPeriod');
  MVC.accessor($, 'weekDay');

  MVC.accessor($, 'paused', function(value) {
    if ($.Param.mainSwitchId !== undefined) {
      $gameSwitches.setValue($.Param.mainSwitchId, !value);
      return;
    }

    this._paused = value;
  }, function() {
    if ($.Param.mainSwitchId !== undefined) {
      if ($gameSwitches === undefined || $gameSwitches === null) return true;
      return !$gameSwitches.value($.Param.mainSwitchId);
    }

    if (this._paused !== undefined) {
      return this._paused;
    }

    return false;
  });

  $._timeEvents = [];
  $.seconds = 0;
  $.minute = 0;
  $.hour = 0;
  $.day = 1;
  $.month = 1;
  $.year = 1;
  $.dayPeriod = 0;
  $.weekDay = 0;

  $.runTimeChangeEvents = function(oldData) {
    if (oldData.seconds != this.seconds) {
      this._onChangeSecond();
    }

    if (oldData.minute !== this.minute) {
      this._onChangeMinute();
    }

    if (oldData.hour !== this.hour) {
      this._onChangeHour();
    }

    if (oldData.day !== this.day) {
      this._onChangeDay();
    }

    if (oldData.month !== this.month) {
      this._onChangeMonth();
    }

    if (oldData.year !== this.year) {
      this._onChangeYear();
    }

    if (oldData.dayPeriod !== this.dayPeriod) {
      this._onChangeDayPeriod();
    }
  };

  $.updateTime = function(runEvents) {
    if (runEvents === undefined) runEvents = true;

    var oldData = $.getDateTime();

    while (this.seconds >= $.Param.minuteLength) {
      this.minute += 1;
      this.seconds -= $.Param.minuteLength;
    }

    while (this.minute >= $.Param.hourLength) {
      this.hour += 1;
      this.minute -= $.Param.hourLength;
    }

    while (this.hour >= $.Param.dayLength) {
      this.day += 1;
      this.hour -= $.Param.dayLength;
    }

    while (this.day > $.Param.monthLength) {
      this.month += 1;
      this.day -= $.Param.monthLength;
    }

    while (this.month > $.Param.yearLength) {
      this.year += 1;
      this.month -= $.Param.yearLength;
    }

    this.updateDayPeriod();

    if (runEvents) {
      this.runTimeChangeEvents(oldData);
    }

    // Calculate week day
    var previousYears = this.year - 1;
    var previousMonths = previousYears * $.Param.yearLength;
    var numMonths = previousMonths + this.month - 1;
    var numDays = numMonths * $.Param.monthLength + this.day;
    this.weekDay = numDays % $.Param.weekLength;

    this._onUpdateTime();
  };

  $.updateDayPeriod = function() {
    // Calculate day period
    if (this.hour < $.Param.dayPeriod1Hour) {
      this.dayPeriod = 4;
    } else if (this.hour < $.Param.dayPeriod2Hour) {
      this.dayPeriod = 1;
    } else if (this.hour < $.Param.dayPeriod3Hour) {
      this.dayPeriod = 2;
    } else if (this.hour < $.Param.dayPeriod4Hour) {
      this.dayPeriod = 3;
    } else {
      this.dayPeriod = 4;
    }
  };

  $.isEarlyMorning = function() {
    return this.dayPeriod == DayPeriods.EARLY_MORNING;
  };

  $.isMidday = function() {
    return this.dayPeriod == DayPeriods.DAY;
  };

  $.isEvening = function() {
    return this.dayPeriod == DayPeriods.EVENING;
  };

  $.isNight = function() {
    return this.dayPeriod == DayPeriods.NIGHT;
  };

  $.isEnabled = function() {
    return (this._intervalHandler !== undefined);
  };

  $.enableTime = function() {
    if (this._intervalHandler !== undefined) return;

    this._intervalHandler = setInterval(function() {
      $.progressTime();
    }, $.Param.secondLength);
  };

  $.disableTime = function() {
    if (this._intervalHandler === undefined) return;

    clearInterval(this._intervalHandler);
    this._intervalHandler = undefined;
  };

  $.loadRealTime = function() {
    var date = new Date();
    var oldData = this.getDateTime();
    var anyChanged = false;

    $.seconds = date.getSeconds();
    $.minute = date.getMinutes();
    $.hour = date.getHours();
    $.day = date.getDate();
    $.month = date.getMonth() + 1;
    $.year = date.getFullYear();
    $.weekDay = date.getDay();
    $.updateDayPeriod();

    if ($.seconds != oldData.seconds) {
      $._onChangeSecond();
    }

    if ($.minute != oldData.minute) {
      $._onChangeMinute();
    }

    if ($.hour != oldData.hour) {
      $._onChangeHour();
    }

    if ($.day != oldData.day) {
      $._onChangeDay();
    }

    if ($.month != oldData.month) {
      $._onChangeMonth();
    }

    if ($.year != oldData.year) {
      $._onChangeYear();
    }
  };

  $.setTime = function(seconds, minute, hour, day, month, year) {
    var oldData = this.getDateTime();

    if (seconds !== undefined) {
      this.seconds = seconds;
    }

    if (minute !== undefined) {
      this.minute = minute;
    }

    if (hour !== undefined) {
      this.hour = hour;
    }

    if (day !== undefined) {
      this.day = day;
    }

    if (month !== undefined) {
      this.month = month;
    }

    if (year !== undefined) {
      this.year = year;
    }

    $.updateTime(false);
    $.runTimeChangeEvents(oldData);
  };

  $.passTime = function(seconds, minutes, hours, days, months, years) {
    var oldData = this.getDateTime();

    this.seconds += Number(seconds || 0);
    this.minute += Number(minutes || 0);
    this.hour += Number(hours || 0);
    this.day += Number(days || 0);
    this.month += Number(months || 0);
    this.year += Number(years || 0);

    $.updateTime(false);
    $.runTimeChangeEvents(oldData);
  };

  $.progressTime = function() {
    if (this.paused) return;

    if ($.Param.useRealTime) {
      $.loadRealTime();
      $._onUpdateTime();
    } else if (SceneManager._scene instanceof Scene_Map) {
      $.seconds += 1;
      $.updateTime();
      $._onChangeSecond();
    }
  };

  $._onChangeSecond = function() {
    this.runEvent('changeSecond');
  };

  $._onChangeMinute = function() {
    this.runEvent('changeMinute');
  };

  $._onChangeHour = function() {
    this.runEvent('changeHour');
  };

  $._onChangeDayPeriod = function() {
    this.runEvent('changeDayPeriod');
  };

  $._onChangeDay = function() {
    this.runEvent('changeDay');
  };

  $._onChangeMonth = function() {
    this.runEvent('changeMonth');
  };

  $._onChangeYear = function() {
    this.runEvent('changeYear');
  };

  $.onTime = function(callback, hour, minute, second) {
    return this.registerTimeEvent({
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onDate = function(callback, day, month, year) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      callback: callback
    });
  };

  $.onDateTime = function(callback, day, month, year, hour, minute, second) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onWeekDay = function(callback, weekDay) {
    return this.registerTimeEvent({
      weekDay: weekDay,
      callback: callback
    });
  };

  $.atDate = $.onDate;
  $.atTime = $.onTime;
  $.atDateTime = $.onDateTime;
  $.atWeekDay = $.onWeekDay;

  $.registerTimeEvent = function(config) {
    this._timeEvents.push(config);
    return this._timeEvents.indexOf(config);
  };

  $._onUpdateTime = function() {
    for (var i = 0; i < this._timeEvents.length; i++) {
      var config = this._timeEvents[i];

      if (config.day !== undefined && config.day != this.day) continue;
      if (config.month !== undefined && config.month != this.month) continue;
      if (config.year !== undefined && config.year != this.year) continue;
      if (config.hour !== undefined && config.hour != this.hour) continue;
      if (config.minute !== undefined && config.minute != this.minute) continue;
      if (config.second !== undefined && config.second != this.seconds) continue;
      if (config.weekDay !== undefined && config.weekDay != this.weekDay) continue;

      this.executeCallback(config.callback);
    }
  };

  $.getDateTime = function() {
    return {
      hour: $.hour,
      minute: $.minute,
      seconds: $.seconds,
      day: $.day,
      month: $.month,
      year: $.year,
      dayPeriod: $.dayPeriod,
      weekDay: $.weekDay,
      paused: $.paused
    };
  };

  $.setDateTime = function(dateTime) {
    this.hour = dateTime.hour || 0;
    this.minute = dateTime.minute || 0;
    this.seconds = dateTime.seconds || 0;
    this.day = dateTime.day || 1;
    this.month = dateTime.month || 1;
    this.year = dateTime.year || 1;
    this.dayPeriod = dateTime.dayPeriod || DayPeriods.EARLY_MORNING;
    this.weekDay = dateTime.weekDay || 0;

    if (dateTime.paused !== undefined) {
      this.paused = dateTime.paused;
    } else {
      this.paused = false;
    }
  };

  var oldDataManager_makeSaveContents = DataManager.makeSaveContents;
  DataManager.makeSaveContents = function() {
    var contents = oldDataManager_makeSaveContents.call(this);

    contents.orangeDateTime = $.getDateTime();
    return contents;
  };

  var oldDataManager_extractSaveContents = DataManager.extractSaveContents;
  DataManager.extractSaveContents = function(contents) {
    oldDataManager_extractSaveContents.call(this, contents);

    if (contents.orangeDateTime !== undefined) {
      $.setDateTime(contents.orangeDateTime);
    }
  };

  $.enableTime();
})(OrangeTimeSystem);

PluginManager.register("OrangeTimeSystem", "1.2", "Adds a time system to your game", {
  email: "plugins@hudell.com",
  name: "Hudell",
  website: "http://www.hudell.com"
}, "2015-10-21");
<commit_msg>Added new script calls<commit_after>/*=============================================================================
 * Orange - Time System
 * By Hudell - www.hudell.com
 * OrangeTimeSystem.js
 * Version: 1.2.1
 * Free for commercial and non commercial use.
 *=============================================================================*/
 /*:
 * @plugindesc Adds a time system to your game
 * @author Hudell
 *
 * @param useRealTime
 * @desc If true, the time "Length" variables will be ignored and the plugin will use the real time
 * @default false
 *
 * @param secondLength
 * @desc How many real time milliseconds should an ingame second last
 * @default 1000
 *
 * @param minuteLength
 * @desc How many ingame seconds should an ingame minute last
 * @default 6
 *
 * @param hourLength
 * @desc How many ingame minutes should an ingame hour last
 * @default 6
 *
 * @param dayLength
 * @desc How many ingame hours should an ingame day last
 * @default 24
 *
 * @param weekLength
 * @desc How many ingame days should an ingame week last
 * @default 7
 *
 * @param monthLength
 * @desc How many ingame days should an ingame month last
 * @default 31
 *
 * @param yearLength
 * @desc How many ingame months should an ingame year last
 * @default 4
 *
 * @param dayPeriod1Hour
 * @desc At what hour does night turn into early morning
 * @default 6
 *
 * @param dayPeriod2Hour
 * @desc At what hour does early morning turn into day
 * @default 9
 *
 * @param dayPeriod3Hour
 * @desc At what hour does day turn into evening
 * @default 18
 *
 * @param dayPeriod4Hour
 * @desc At what hour does evening turn into night
 * @default 20
 *
 * @param mainSwitchId
 * @desc The Number of the Switch used to activate the flow of time
 * @default 0
 *
 * @help
 * ============================================================================
 * Introduction and Instructions
 * ============================================================================
 *
 * This plugin creates a time system for your game. Nothing will change on the
 * game itself, unless you use another plugin that uses this one.
 *
 * ============================================================================
 * Latest Version
 * ============================================================================
 *
 * Get the latest version of this script on http://link.hudell.com/time-system
 *
 */

var Imported = Imported || {};

if (Imported['MVCommons'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/mvcommons');
  throw new Error("This library needs MVCommons to work properly!");
}
if (Imported['OrangeEventManager'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/event-manager');
  throw new Error("This library needs OrangeEventManager to work properly!");
}

var OrangeTimeSystem = OrangeTimeSystem || MVC.shallowClone(OrangeEventManager);

var DayPeriods = {
  EARLY_MORNING: 1,
  DAY: 2,
  EVENING: 3,
  NIGHT: 4
};

(function($) {
  "use strict";

  $.Parameters = PluginManager.parameters('OrangeTimeSystem');
  $.Param = $.Param || {};

  $.Param.useRealTime = $.Parameters["useRealTime"] == "true";
  if ($.Param.useRealTime) {
    $.Param.secondLength = 1000;
  } else {
    $.Param.secondLength = Number($.Parameters['secondLength'] || 1000);
  }

  $.Param.minuteLength = Number($.Parameters['minuteLength'] || 6);
  $.Param.hourLength = Number($.Parameters['hourLength'] || 6);
  $.Param.dayLength = Number($.Parameters['dayLength'] || 24);
  $.Param.weekLength = Number($.Parameters['weekLength'] || 7);
  $.Param.monthLength = Number($.Parameters['monthLength'] || 31);
  $.Param.yearLength = Number($.Parameters['yearLength'] || 4);

  $.Param.dayPeriod1Hour = Number($.Parameters['dayPeriod1Hour'] || 6);
  $.Param.dayPeriod2Hour = Number($.Parameters['dayPeriod2Hour'] || 9);
  $.Param.dayPeriod3Hour = Number($.Parameters['dayPeriod3Hour'] || 18);
  $.Param.dayPeriod4Hour = Number($.Parameters['dayPeriod4Hour'] || 20);

  var switchId = parseInt($.Parameters['mainSwitchId'], 10);

  if (switchId !== NaN && switchId > 0) {
    $.Param.mainSwitchId = switchId;
  } else {
    $.Param.mainSwitchId = undefined;
  }

  MVC.accessor($, 'seconds');
  MVC.accessor($, 'minute');
  MVC.accessor($, 'hour');
  MVC.accessor($, 'day');
  MVC.accessor($, 'month');
  MVC.accessor($, 'year');
  MVC.accessor($, 'dayPeriod');
  MVC.accessor($, 'weekDay');

  MVC.accessor($, 'paused', function(value) {
    if ($.Param.mainSwitchId !== undefined) {
      $gameSwitches.setValue($.Param.mainSwitchId, !value);
      return;
    }

    this._paused = value;
  }, function() {
    if ($.Param.mainSwitchId !== undefined) {
      if ($gameSwitches === undefined || $gameSwitches === null) return true;
      return !$gameSwitches.value($.Param.mainSwitchId);
    }

    if (this._paused !== undefined) {
      return this._paused;
    }

    return false;
  });

  $._timeEvents = [];
  $.seconds = 0;
  $.minute = 0;
  $.hour = 0;
  $.day = 1;
  $.month = 1;
  $.year = 1;
  $.dayPeriod = 0;
  $.weekDay = 0;

  $.runTimeChangeEvents = function(oldData) {
    if (oldData.seconds != this.seconds) {
      this._onChangeSecond();
    }

    if (oldData.minute !== this.minute) {
      this._onChangeMinute();
    }

    if (oldData.hour !== this.hour) {
      this._onChangeHour();
    }

    if (oldData.day !== this.day) {
      this._onChangeDay();
    }

    if (oldData.month !== this.month) {
      this._onChangeMonth();
    }

    if (oldData.year !== this.year) {
      this._onChangeYear();
    }

    if (oldData.dayPeriod !== this.dayPeriod) {
      this._onChangeDayPeriod();
    }
  };

  $.updateTime = function(runEvents) {
    if (runEvents === undefined) runEvents = true;

    var oldData = $.getDateTime();

    while (this.seconds >= $.Param.minuteLength) {
      this.minute += 1;
      this.seconds -= $.Param.minuteLength;
    }

    while (this.minute >= $.Param.hourLength) {
      this.hour += 1;
      this.minute -= $.Param.hourLength;
    }

    while (this.hour >= $.Param.dayLength) {
      this.day += 1;
      this.hour -= $.Param.dayLength;
    }

    while (this.day > $.Param.monthLength) {
      this.month += 1;
      this.day -= $.Param.monthLength;
    }

    while (this.month > $.Param.yearLength) {
      this.year += 1;
      this.month -= $.Param.yearLength;
    }

    this.updateDayPeriod();

    if (runEvents) {
      this.runTimeChangeEvents(oldData);
    }

    // Calculate week day
    var previousYears = this.year - 1;
    var previousMonths = previousYears * $.Param.yearLength;
    var numMonths = previousMonths + this.month - 1;
    var numDays = numMonths * $.Param.monthLength + this.day;
    this.weekDay = numDays % $.Param.weekLength;

    this._onUpdateTime();
  };

  $.updateDayPeriod = function() {
    // Calculate day period
    if (this.hour < $.Param.dayPeriod1Hour) {
      this.dayPeriod = 4;
    } else if (this.hour < $.Param.dayPeriod2Hour) {
      this.dayPeriod = 1;
    } else if (this.hour < $.Param.dayPeriod3Hour) {
      this.dayPeriod = 2;
    } else if (this.hour < $.Param.dayPeriod4Hour) {
      this.dayPeriod = 3;
    } else {
      this.dayPeriod = 4;
    }
  };

  $.isEarlyMorning = function() {
    return this.dayPeriod == DayPeriods.EARLY_MORNING;
  };

  $.isMidday = function() {
    return this.dayPeriod == DayPeriods.DAY;
  };

  $.isEvening = function() {
    return this.dayPeriod == DayPeriods.EVENING;
  };

  $.isNight = function() {
    return this.dayPeriod == DayPeriods.NIGHT;
  };

  $.isEnabled = function() {
    return (this._intervalHandler !== undefined);
  };

  $.enableTime = function() {
    if (this._intervalHandler !== undefined) return;

    this._intervalHandler = setInterval(function() {
      $.progressTime();
    }, $.Param.secondLength);
  };

  $.disableTime = function() {
    if (this._intervalHandler === undefined) return;

    clearInterval(this._intervalHandler);
    this._intervalHandler = undefined;
  };

  $.loadRealTime = function() {
    var date = new Date();
    var oldData = this.getDateTime();
    var anyChanged = false;

    $.seconds = date.getSeconds();
    $.minute = date.getMinutes();
    $.hour = date.getHours();
    $.day = date.getDate();
    $.month = date.getMonth() + 1;
    $.year = date.getFullYear();
    $.weekDay = date.getDay();
    $.updateDayPeriod();

    if ($.seconds != oldData.seconds) {
      $._onChangeSecond();
    }

    if ($.minute != oldData.minute) {
      $._onChangeMinute();
    }

    if ($.hour != oldData.hour) {
      $._onChangeHour();
    }

    if ($.day != oldData.day) {
      $._onChangeDay();
    }

    if ($.month != oldData.month) {
      $._onChangeMonth();
    }

    if ($.year != oldData.year) {
      $._onChangeYear();
    }
  };

  $.setTime = function(seconds, minute, hour, day, month, year) {
    var oldData = this.getDateTime();

    if (seconds !== undefined) {
      this.seconds = seconds;
    }

    if (minute !== undefined) {
      this.minute = minute;
    }

    if (hour !== undefined) {
      this.hour = hour;
    }

    if (day !== undefined) {
      this.day = day;
    }

    if (month !== undefined) {
      this.month = month;
    }

    if (year !== undefined) {
      this.year = year;
    }

    $.updateTime(false);
    $.runTimeChangeEvents(oldData);
  };

  $.addSeconds = function(seconds) {
    $.addTime({seconds : seconds});
  };

  $.addMinutes = function(minutes) {
    $.addTime({minutes : minutes});
  };

  $.addHours = function(hours) {
    $.addTime({hours : hours});
  };

  $.addDays = function(days) {
    $.addTime({days : days});
  };

  $.addMonths = function(months) {
    $.addTime({months : months});
  };

  $.addYears = function(years) {
    $.addTime({years : years});
  };

  $.addTime = function(timeData) {
    $.passTime(timeData.seconds, timeData.minutes, timeData.hours, timeData.days, timeData.months, timeData.years);
  };

  $.passTime = function(seconds, minutes, hours, days, months, years) {
    var oldData = this.getDateTime();

    this.seconds += Number(seconds || 0);
    this.minute += Number(minutes || 0);
    this.hour += Number(hours || 0);
    this.day += Number(days || 0);
    this.month += Number(months || 0);
    this.year += Number(years || 0);

    $.updateTime(false);
    $.runTimeChangeEvents(oldData);
  };

  $.progressTime = function() {
    if (this.paused) return;

    if ($.Param.useRealTime) {
      $.loadRealTime();
      $._onUpdateTime();
    } else if (SceneManager._scene instanceof Scene_Map) {
      $.seconds += 1;
      $.updateTime();
      $._onChangeSecond();
    }
  };

  $._onChangeSecond = function() {
    this.runEvent('changeSecond');
  };

  $._onChangeMinute = function() {
    this.runEvent('changeMinute');
  };

  $._onChangeHour = function() {
    this.runEvent('changeHour');
  };

  $._onChangeDayPeriod = function() {
    this.runEvent('changeDayPeriod');
  };

  $._onChangeDay = function() {
    this.runEvent('changeDay');
  };

  $._onChangeMonth = function() {
    this.runEvent('changeMonth');
  };

  $._onChangeYear = function() {
    this.runEvent('changeYear');
  };

  $.onTime = function(callback, hour, minute, second) {
    return this.registerTimeEvent({
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onDate = function(callback, day, month, year) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      callback: callback
    });
  };

  $.onDateTime = function(callback, day, month, year, hour, minute, second) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onWeekDay = function(callback, weekDay) {
    return this.registerTimeEvent({
      weekDay: weekDay,
      callback: callback
    });
  };

  $.atDate = $.onDate;
  $.atTime = $.onTime;
  $.atDateTime = $.onDateTime;
  $.atWeekDay = $.onWeekDay;

  $.registerTimeEvent = function(config) {
    this._timeEvents.push(config);
    return this._timeEvents.indexOf(config);
  };

  $._onUpdateTime = function() {
    for (var i = 0; i < this._timeEvents.length; i++) {
      var config = this._timeEvents[i];

      if (config.day !== undefined && config.day != this.day) continue;
      if (config.month !== undefined && config.month != this.month) continue;
      if (config.year !== undefined && config.year != this.year) continue;
      if (config.hour !== undefined && config.hour != this.hour) continue;
      if (config.minute !== undefined && config.minute != this.minute) continue;
      if (config.second !== undefined && config.second != this.seconds) continue;
      if (config.weekDay !== undefined && config.weekDay != this.weekDay) continue;

      this.executeCallback(config.callback);
    }
  };

  $.getDateTime = function() {
    return {
      hour: $.hour,
      minute: $.minute,
      seconds: $.seconds,
      day: $.day,
      month: $.month,
      year: $.year,
      dayPeriod: $.dayPeriod,
      weekDay: $.weekDay,
      paused: $.paused
    };
  };

  $.setDateTime = function(dateTime) {
    this.hour = dateTime.hour || 0;
    this.minute = dateTime.minute || 0;
    this.seconds = dateTime.seconds || 0;
    this.day = dateTime.day || 1;
    this.month = dateTime.month || 1;
    this.year = dateTime.year || 1;
    this.dayPeriod = dateTime.dayPeriod || DayPeriods.EARLY_MORNING;
    this.weekDay = dateTime.weekDay || 0;

    if (dateTime.paused !== undefined) {
      this.paused = dateTime.paused;
    } else {
      this.paused = false;
    }
  };

  var oldDataManager_makeSaveContents = DataManager.makeSaveContents;
  DataManager.makeSaveContents = function() {
    var contents = oldDataManager_makeSaveContents.call(this);

    contents.orangeDateTime = $.getDateTime();
    return contents;
  };

  var oldDataManager_extractSaveContents = DataManager.extractSaveContents;
  DataManager.extractSaveContents = function(contents) {
    oldDataManager_extractSaveContents.call(this, contents);

    if (contents.orangeDateTime !== undefined) {
      $.setDateTime(contents.orangeDateTime);
    }
  };

  $.enableTime();
})(OrangeTimeSystem);

PluginManager.register("OrangeTimeSystem", "1.2.1", "Adds a time system to your game", {
  email: "plugins@hudell.com",
  name: "Hudell",
  website: "http://www.hudell.com"
}, "2015-10-21");
<|endoftext|>


<commit_before>(function(){if(window.melange===undefined)throw new Error("Melange not loaded");var d=window.melange;d.autocomplete=window.melange.autocomplete=function(){return new d.autocomplete};var f=d.logging.debugDecorator(d.autocomplete);d.error.createErrors([]);f.makeAutoComplete=function(b){var g="?fmt=json&field="+b,c=b+"-pretty";jQuery("#"+b).attr("id",c).attr("name",c);jQuery.ajax({url:g,success:function(h){jQuery("#"+c).after(['<input id="',b,'" name="',b,'" type="hidden" />'].join(""));jQuery("#"+c).autocomplete({source:h.data,
focus:function(e,a){jQuery("#"+c).val(a.item.label);return false},select:function(e,a){jQuery("#"+c).val(a.item.label);jQuery("#"+b).val(a.item.key);return false}}).data("autocomplete")._renderItem=function(e,a){return jQuery("

").data("item.autocomplete",a).append(""+a.link_id+" ("+a.label+")").appendTo(e)}}})}})();
<commit_msg>Commit minimized version of autocomplete script<commit_after>(function(){if(window.melange===undefined)throw new Error("Melange not loaded");var b=window.melange;b.autocomplete=window.melange.autocomplete=function(){return new b.autocomplete};var f=b.logging.debugDecorator(b.autocomplete);b.error.createErrors([]);f.makeAutoComplete=function(c){var d=c+"-pretty";jQuery.ajax({url:"?fmt=json&field="+c,success:function(g){jQuery("#"+d).autocomplete({source:g.data,focus:function(e,a){jQuery("#"+d).val(a.item.label);return false},select:function(e,a){jQuery("#"+
d).val(a.item.key_name);jQuery("#"+c).val(a.item.key);return false}}).data("autocomplete")._renderItem=function(e,a){return jQuery("

").data("item.autocomplete",a).append(""+a.key_name+" ("+a.label+")").appendTo(e)}}})}})();
<|endoftext|>