<commit_before>var run = require('../src/runner');
var CompositeError = require('../src/error/composite');
var _ = require('lodash');
var chai = require('chai');
var nock = require('nock');
var fs = require('fs');
var assert = chai.assert;

describe('Runner process', function () {

    beforeEach(function () {
        nock.cleanAll();
    });

    describe('browserlist filtering', function () {

        it ('should be possible to filter browsers', function (done) {
            setupConsoleResponse();
            run({
                skipCapabilitiesCheck: false,
                browsers: [{
                    browserName: "internet explorer",
                    version: 9
                }, {
                    browserName: "chrome",
                    version: 'latest'
                }],
                after: done
            }, [{
                run: function (remote, desired, doneCb) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                    doneCb();
                }
            }]);
        });

        it('should be possible to bypass browser filtering', function(done) {
            done = _.after(3, done);
            var server = setupConsoleResponse();
            run({
                skipCapabilitiesCheck: true,
                browsers: [{
                    browserName: "internet explorer",
                    version: 9
                }, {
                    browserName: "internet explorer",
                    version: 8
                }],
                after: function (err) {
                    assert.ok(!err);
                    assert.ok(!server.isDone());
                    done();
                }
            }, [{
                run: function (remote, desired, doneCb) {
                    done();
                    doneCb();
                }
            }]);
        });

        it('should throw an error if console is not available', function(done) {
            setupConsoleResponse(404);
            run({
                browsers: [{
                    browserName: "internet explorer",
                    version: 8
                }],
                after: function (err) {
                    assert.ok(err.message);
                    assert.match(err.message, /Could not connect/);
                    done();
                }
            }, [{
                run: function (remote, desired, doneCb) {doneCb();}
            }]);
        });

        it('should throw an error if no requested browser is available', function(done) {
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "internet explorer",
                    version: 9
                }],
                after: function (err) {
                    assert.ok(err.message);
                    assert.match(err.message, /No matching browsers/);
                    done();
                }
            }, [{
                run: function (remote, desired, doneCb) {doneCb();}
            }]);
        });
    });

    describe('lifecycle', function () {

        it('should trigger "after" callback last', function(done) {
            var calls = [];
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],

                after: function (err) {
                    assert.ok(!err);
                    assert.deepEqual(calls, [
                        "test.before",
                        "test",
                        "test.after",
                        "afterEach",
                        "afterBrowser"
                    ]);
                    done();
                },
                afterEach: function () {
                    calls.push("afterEach");
                },
                afterBrowser: function () {
                    calls.push("afterBrowser");
                }
            }, [{
                before: function () {
                    calls.push("test.before");
                },
                after: function () {
                    calls.push("test.after");
                },
                run: function (remote, desired, doneCb) {
                    calls.push("test");
                    doneCb();
                }
            }]);
        });

        it('test.before and test.after recieve the desired browser', function(done) {
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],

                after: function (err) {
                    assert.ok(!err);
                    done();
                }
            }, [{
                before: function (desired) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                },
                after: function (err, desired) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                },
                run: function (remote, desired, doneCb) {
                    doneCb();
                }
            }]);
        });

        it('calls the afterEach and afterBrowser', function(done) {
            var calls = [];
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],

                after: function (err) {
                    assert.ok(!err);
                    assert.deepEqual(calls, [
                        "test.before",
                        "test",
                        "test.after",
                        "afterEach",
                        "test.before",
                        "test",
                        "test.after",
                        "afterEach",
                        "afterBrowser"
                    ]);
                    done();
                },
                afterEach: function (err, desired, test) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                    assert.ok(test.run);
                    calls.push("afterEach");
                },
                afterBrowser: function (err, desired) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                    calls.push("afterBrowser");
                }
            }, [{
                before: function () {
                    calls.push("test.before");
                },
                after: function () {
                    calls.push("test.after");
                },
                run: function (remote, desired, doneCb) {
                    calls.push("test");
                    doneCb();
                }
            }, {
                before: function () {
                    calls.push("test.before");
                },
                after: function () {
                    calls.push("test.after");
                },
                run: function (remote, desired, doneCb) {
                    calls.push("test");
                    doneCb();
                }
            }]);
        });

    });

    describe('error catching', function () {
        var message = 'something';
        var message2 = 'something new';

        it('should catch test error', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    after: function (err) {
                        done();
                    }
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function (err) {
                        assert.equal(err.message, message);
                    }
                }]);
        });
        it('should catch test.before error', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    after: function (err) {
                        done();
                    }
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function (err) {
                        assert.equal(err.message, message);
                    }
                }]);
        });
        it('should be possible to alter error in test.after', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterEach: function (err) {
                        assert.equal(err.message, message2);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function(err) {
                        throw new Error(message2);
                    }
                }]);
        });
        it('should bubble test error to test.after AND afterEach', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterEach: function (err) {
                        assert.equal(err.message, message);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function (err) {
                        assert.equal(err.message, message);
                    }
                }]);
        });
        it('should bubble test error to afterEach', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterEach: function (err) {
                        assert.equal(err.message, message);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    }
                }]);
        });
        it('should bubble test error to afterBrowser', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterBrowser: function (err, browser) {
                        assert.instanceOf(err, CompositeError);
                        assert.equal(err.message, 'Errors where catched for this browser.');
                        err.length = 1;
                        assert.equal(err.errors.pop().message, message);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    }
                }]);
        });
        it('should bubble test error to after', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    after: function (err) {
                        assert.equal(err.message, 'Errors where catched for this run.');
                        done();
                    }
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    }
                }]);
        });
    });

    describe('check test cases can be run through runner', function () {
        var TestCase = require('../src/testCase');
        it('should be possible to run a TestCase', function(done) {
            var called = false;
            var Case2 = TestCase.extend({
                run: function (remote, desired, cb) {
                    called = true;
                    cb();
                }
            });

            run({
                skipCapabilitiesCheck: true,
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],
                after: function (err) {
                    assert.equal(err.message, 'Errors where catched for this run.');
                    done();
                }
            },
            [
                new Case2()
            ]);
        });
    });
});

function setupConsoleResponse(statuscode) {
    var html = fs.readFileSync(__dirname + '/../fixtures/html/console.html');
    return nock('http://127.0.0.1:4444')
        .get('/grid/console')
        .reply(statuscode || 200, html);
}
<commit_msg>Runner test suite fix.<commit_after>var run = require('../src/runner');
var CompositeError = require('../src/error/composite');
var _ = require('lodash');
var chai = require('chai');
var nock = require('nock');
var fs = require('fs');
var assert = chai.assert;

describe('Runner process', function () {

    beforeEach(function () {
        nock.cleanAll();
    });

    describe('browserlist filtering', function () {

        it ('should be possible to filter browsers', function (done) {
            setupConsoleResponse();
            run({
                skipCapabilitiesCheck: false,
                browsers: [{
                    browserName: "internet explorer",
                    version: 9
                }, {
                    browserName: "chrome",
                    version: 'latest'
                }],
                after: done
            }, [{
                run: function (remote, desired, doneCb) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                    doneCb();
                }
            }]);
        });

        it('should be possible to bypass browser filtering', function(done) {
            done = _.after(3, done);
            var server = setupConsoleResponse();
            run({
                skipCapabilitiesCheck: true,
                browsers: [{
                    browserName: "internet explorer",
                    version: 9
                }, {
                    browserName: "internet explorer",
                    version: 8
                }],
                after: function (err) {
                    assert.ok(!err);
                    assert.ok(!server.isDone());
                    done();
                }
            }, [{
                run: function (remote, desired, doneCb) {
                    done();
                    doneCb();
                }
            }]);
        });

        it('should throw an error if console is not available', function(done) {
            setupConsoleResponse(404);
            run({
                browsers: [{
                    browserName: "internet explorer",
                    version: 8
                }],
                after: function (err) {
                    assert.ok(err.message);
                    assert.match(err.message, /Could not connect/);
                    done();
                }
            }, [{
                run: function (remote, desired, doneCb) {doneCb();}
            }]);
        });

        it('should throw an error if no requested browser is available', function(done) {
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "internet explorer",
                    version: 9
                }],
                after: function (err) {
                    assert.ok(err.message);
                    assert.match(err.message, /No matching browsers/);
                    done();
                }
            }, [{
                run: function (remote, desired, doneCb) {doneCb();}
            }]);
        });
    });

    describe('lifecycle', function () {

        it('should trigger "after" callback last', function(done) {
            var calls = [];
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],

                after: function (err) {
                    assert.ok(!err);
                    assert.deepEqual(calls, [
                        "test.before",
                        "test",
                        "test.after",
                        "afterEach",
                        "afterBrowser"
                    ]);
                    done();
                },
                afterEach: function () {
                    calls.push("afterEach");
                },
                afterBrowser: function () {
                    calls.push("afterBrowser");
                }
            }, [{
                before: function () {
                    calls.push("test.before");
                },
                after: function () {
                    calls.push("test.after");
                },
                run: function (remote, desired, doneCb) {
                    calls.push("test");
                    doneCb();
                }
            }]);
        });

        it('test.before and test.after recieve the desired browser', function(done) {
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],

                after: function (err) {
                    assert.ok(!err);
                    done();
                }
            }, [{
                before: function (desired) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                },
                after: function (err, desired) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                },
                run: function (remote, desired, doneCb) {
                    doneCb();
                }
            }]);
        });

        it('calls the afterEach and afterBrowser', function(done) {
            var calls = [];
            setupConsoleResponse();
            run({
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],

                after: function (err) {
                    assert.ok(!err);
                    assert.deepEqual(calls, [
                        "test.before",
                        "test",
                        "test.after",
                        "afterEach",
                        "test.before",
                        "test",
                        "test.after",
                        "afterEach",
                        "afterBrowser"
                    ]);
                    done();
                },
                afterEach: function (err, desired, test) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                    assert.ok(test.run);
                    calls.push("afterEach");
                },
                afterBrowser: function (err, desired) {
                    assert.deepEqual(desired, {
                        browserName: "chrome",
                        version: 'latest'
                    });
                    calls.push("afterBrowser");
                }
            }, [{
                before: function () {
                    calls.push("test.before");
                },
                after: function () {
                    calls.push("test.after");
                },
                run: function (remote, desired, doneCb) {
                    calls.push("test");
                    doneCb();
                }
            }, {
                before: function () {
                    calls.push("test.before");
                },
                after: function () {
                    calls.push("test.after");
                },
                run: function (remote, desired, doneCb) {
                    calls.push("test");
                    doneCb();
                }
            }]);
        });

    });

    describe('error catching', function () {
        var message = 'something';
        var message2 = 'something new';

        it('should catch test error', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    after: function (err) {
                        done();
                    }
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function (err) {
                        assert.equal(err.message, message);
                    }
                }]);
        });
        it('should catch test.before error', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    after: function (err) {
                        done();
                    }
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function (err) {
                        assert.equal(err.message, message);
                    }
                }]);
        });
        it('should be possible to alter error in test.after', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterEach: function (err) {
                        assert.equal(err.message, message2);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function(err) {
                        throw new Error(message2);
                    }
                }]);
        });
        it('should bubble test error to test.after AND afterEach', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterEach: function (err) {
                        assert.equal(err.message, message);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    },
                    after: function (err) {
                        assert.equal(err.message, message);
                    }
                }]);
        });
        it('should bubble test error to afterEach', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterEach: function (err) {
                        assert.equal(err.message, message);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    }
                }]);
        });
        it('should bubble test error to afterBrowser', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    afterBrowser: function (err, browser) {
                        assert.instanceOf(err, CompositeError);
                        assert.equal(err.message, 'Errors where catched for this browser.');
                        err.length = 1;
                        assert.equal(err.errors.pop().message, message);
                    },
                    after: done
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    }
                }]);
        });
        it('should bubble test error to after', function (done) {
            setupConsoleResponse();
            run({
                    browsers: [{
                        browserName: "chrome",
                        version: 'latest'
                    }],
                    after: function (err) {
                        assert.equal(err.message, 'Errors where catched for this run.');
                        done();
                    }
                }, [{
                    before: function() {
                        throw new Error(message);
                    },
                    run: function () {
                    }
                }]);
        });
    });

    describe('check test cases can be run through runner', function () {
        var TestCase = require('../src/testCase');
        it('should be possible to run a TestCase', function(done) {
            var called = false;
            var Case2 = TestCase.extend({
                run: function (remote, desired, cb) {
                    called = true;
                    cb();
                }
            });

            run({
                skipCapabilitiesCheck: true,
                browsers: [{
                    browserName: "chrome",
                    version: 'latest'
                }],
                after: function (err) {
                    assert.ok(called);
                    done();
                }
            }, [
                new Case2()
            ]);
        });
    });
});

function setupConsoleResponse(statuscode) {
    var html = fs.readFileSync(__dirname + '/../fixtures/html/console.html');
    return nock('http://127.0.0.1:4444')
        .get('/grid/console')
        .reply(statuscode || 200, html);
}
<|endoftext|>


<commit_before>/**
 * Karma test runner for jsonld-signatures.
 *
 * Use environment vars to control, set via karma.conf.js/webpack:
 *
 * Set dirs, manifests, or js to run:
 *   JSONLD_TESTS="r1 r2 ..."
 * Output an EARL report:
 *   EARL=filename
 * Bail with tests fail:
 *   BAIL=true
 *
 * @author Dave Longley
 * @author David I. Lehn
 *
 * Copyright (c) 2011-2018 Digital Bazaar, Inc. All rights reserved.
 */
// FIXME: hack to ensure delay is set first
//mocha.setup({delay: true, ui: 'bdd'});

// jsonld compatibility
//require('core-js/fn/array/includes');
//require('core-js/fn/object/assign');
require('core-js/fn/promise');
require('regenerator-runtime/runtime');

const assert = require('chai').assert;
const common = require('./test-common');
const jsigs = require('..');
const jsonld = require('../node_modules/jsonld/dist/jsonld.js');

//var system = require('system');
const forge = require('../node_modules/node-forge');
window.forge = forge;
const bitcoreMessage = require(
  '../node_modules/bitcore-message/dist/bitcore-message.js');
window.bitcoreMessage = bitcoreMessage;

jsigs.promises({api: jsigs.promises});

const options = {
  assert: assert,
  jsigs: jsigs,
  jsonld: jsonld,
  nodejs: false
};

common(options).then(() => {
  //run();
}).then(() => {
  // FIXME: karma phantomjs does not expose this API
  if(window.phantom && window.phantom.exit) {
    phantom.exit(0);
  }
}).catch(err => {
  console.error(err);
  // FIXME: karma phantomjs does not expose this API
  if(window.phantom && window.phantom.exit) {
    phantom.exit(1);
  }
});
<commit_msg>Require `object/assign` plugin in test-karma.<commit_after>/**
 * Karma test runner for jsonld-signatures.
 *
 * Use environment vars to control, set via karma.conf.js/webpack:
 *
 * Set dirs, manifests, or js to run:
 *   JSONLD_TESTS="r1 r2 ..."
 * Output an EARL report:
 *   EARL=filename
 * Bail with tests fail:
 *   BAIL=true
 *
 * @author Dave Longley
 * @author David I. Lehn
 *
 * Copyright (c) 2011-2018 Digital Bazaar, Inc. All rights reserved.
 */
// FIXME: hack to ensure delay is set first
//mocha.setup({delay: true, ui: 'bdd'});

// jsonld compatibility
//require('core-js/fn/array/includes');
require('core-js/fn/object/assign');
require('core-js/fn/promise');
require('regenerator-runtime/runtime');

const assert = require('chai').assert;
const common = require('./test-common');
const jsigs = require('..');
const jsonld = require('../node_modules/jsonld/dist/jsonld.js');

//var system = require('system');
const forge = require('../node_modules/node-forge');
window.forge = forge;
const bitcoreMessage = require(
  '../node_modules/bitcore-message/dist/bitcore-message.js');
window.bitcoreMessage = bitcoreMessage;

jsigs.promises({api: jsigs.promises});

const options = {
  assert: assert,
  jsigs: jsigs,
  jsonld: jsonld,
  nodejs: false
};

common(options).then(() => {
  //run();
}).then(() => {
  // FIXME: karma phantomjs does not expose this API
  if(window.phantom && window.phantom.exit) {
    phantom.exit(0);
  }
}).catch(err => {
  console.error(err);
  // FIXME: karma phantomjs does not expose this API
  if(window.phantom && window.phantom.exit) {
    phantom.exit(1);
  }
});
<|endoftext|>


<commit_before>/****************************************************************************
 Copyright (c) 2008-2010 Ricardo Quesada
 Copyright (c) 2011-2012 cocos2d-x.org
 Copyright (c) 2013-2014 Chukong Technologies Inc.

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/
var TAG_LABEL1 = 550;
var TAG_LABEL2 = 551;
var TAG_LABEL3 = 552;
var TAG_LABEL4 = 553;

var fontIdx = 0;

var fontList = [

    // System Fonts
    "Verdana",
    "Lucida Sans Unicode",
    "Bookman Old Style",
    "Symbol",
    "Georgia",
    "Trebuchet MS",
    "Comic Sans MS",
    "Arial Black",
    "Tahoma",
    "Impact",

    // custom TTF
    "American Typewriter",
    "Marker Felt",
    "A Damn Mess",
    "Abberancy",
    "Abduction",
    "Paint Boy",
    "Schwarzwald",
    "Scissor Cuts"
];

function nextFontTestAction() {
    fontIdx++;
    fontIdx = fontIdx % fontList.length;

    if(window.sideIndexBar){
        fontIdx = window.sideIndexBar.changeTest(fontIdx, 16);
    }

    return fontList[fontIdx];
}

function backFontTestAction() {
    fontIdx--;
    if (fontIdx < 0) {
        fontIdx += fontList.length;
    }

    if(window.sideIndexBar){
        fontIdx = window.sideIndexBar.changeTest(fontIdx, 16);
    }

    return fontList[fontIdx];
}

function restartFontTestAction() {
    return fontList[fontIdx];
}
FontTestScene = TestScene.extend({

    runThisTest:function (num) {

        fontIdx = num || fontIdx;

        var layer = FontTest.create();
        this.addChild(layer);

        director.runScene(this);
    }
});

FontTest = BaseTestLayer.extend({
    ctor:function () {
        this._super(cc.color(0,0,0,255), cc.color(98,99,117,255));

        this.showFont(restartFontTestAction());

    },
    showFont:function (pFont) {
        this.removeChildByTag(TAG_LABEL1, true);
        this.removeChildByTag(TAG_LABEL2, true);
        this.removeChildByTag(TAG_LABEL3, true);
        this.removeChildByTag(TAG_LABEL4, true);

        var winSize = director.getWinSize();

        var top = cc.LabelTTF.create(pFont, pFont, 24);
        var left = cc.LabelTTF.create("alignment left", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_LEFT);
        var center = cc.LabelTTF.create("alignment center", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_CENTER);
        var right = cc.LabelTTF.create("alignment right", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_RIGHT);

        top.x = winSize.width / 2;
        top.y = winSize.height * 3 / 4;
        left.x = winSize.width / 2;
        left.y = winSize.height / 2;
        center.x = winSize.width / 2;
        center.y = winSize.height * 3 / 8;
        right.x = winSize.width / 2;
        right.y = winSize.height / 4;

        this.addChild(left, 0, TAG_LABEL1);
        this.addChild(right, 0, TAG_LABEL2);
        this.addChild(center, 0, TAG_LABEL3);
        this.addChild(top, 0, TAG_LABEL4);

    },

    onBackCallback:function (sender) {
        this.showFont(backFontTestAction());
    },
    onRestartCallback:function (sender) {
        this.showFont(restartFontTestAction());
    },
    onNextCallback:function (sender) {
        this.showFont(nextFontTestAction());
    },
    subtitle:function () {
        return "Font test";
    },
    title:function () {
        return "" + fontList[fontIdx];
    },

    // automation
    numberOfPendingTests:function() {
        return ( (fontList.length-1) - fontIdx );
    },
    getTestNumber:function() {
        return fontIdx;
    }

});

FontTest.create = function () {
    return new FontTest();
};
<commit_msg>issue #5685: replace create function with operator new in FontTest.js<commit_after>/****************************************************************************
 Copyright (c) 2008-2010 Ricardo Quesada
 Copyright (c) 2011-2012 cocos2d-x.org
 Copyright (c) 2013-2014 Chukong Technologies Inc.

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/
var TAG_LABEL1 = 550;
var TAG_LABEL2 = 551;
var TAG_LABEL3 = 552;
var TAG_LABEL4 = 553;

var fontIdx = 0;

var fontList = [

    // System Fonts
    "Verdana",
    "Lucida Sans Unicode",
    "Bookman Old Style",
    "Symbol",
    "Georgia",
    "Trebuchet MS",
    "Comic Sans MS",
    "Arial Black",
    "Tahoma",
    "Impact",

    // custom TTF
    "American Typewriter",
    "Marker Felt",
    "A Damn Mess",
    "Abberancy",
    "Abduction",
    "Paint Boy",
    "Schwarzwald",
    "Scissor Cuts"
];

function nextFontTestAction() {
    fontIdx++;
    fontIdx = fontIdx % fontList.length;

    if(window.sideIndexBar){
        fontIdx = window.sideIndexBar.changeTest(fontIdx, 16);
    }

    return fontList[fontIdx];
}

function backFontTestAction() {
    fontIdx--;
    if (fontIdx < 0) {
        fontIdx += fontList.length;
    }

    if(window.sideIndexBar){
        fontIdx = window.sideIndexBar.changeTest(fontIdx, 16);
    }

    return fontList[fontIdx];
}

function restartFontTestAction() {
    return fontList[fontIdx];
}
FontTestScene = TestScene.extend({

    runThisTest:function (num) {

        fontIdx = num || fontIdx;

        var layer = new FontTest();
        this.addChild(layer);

        director.runScene(this);
    }
});

FontTest = BaseTestLayer.extend({
    ctor:function () {
        this._super(cc.color(0,0,0,255), cc.color(98,99,117,255));

        this.showFont(restartFontTestAction());

    },
    showFont:function (pFont) {
        this.removeChildByTag(TAG_LABEL1, true);
        this.removeChildByTag(TAG_LABEL2, true);
        this.removeChildByTag(TAG_LABEL3, true);
        this.removeChildByTag(TAG_LABEL4, true);

        var winSize = director.getWinSize();

        var top = new cc.LabelTTF(pFont, pFont, 24);
        var left = new cc.LabelTTF("alignment left", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_LEFT);
        var center = new cc.LabelTTF("alignment center", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_CENTER);
        var right = new cc.LabelTTF("alignment right", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_RIGHT);

        top.x = winSize.width / 2;
        top.y = winSize.height * 3 / 4;
        left.x = winSize.width / 2;
        left.y = winSize.height / 2;
        center.x = winSize.width / 2;
        center.y = winSize.height * 3 / 8;
        right.x = winSize.width / 2;
        right.y = winSize.height / 4;

        this.addChild(left, 0, TAG_LABEL1);
        this.addChild(right, 0, TAG_LABEL2);
        this.addChild(center, 0, TAG_LABEL3);
        this.addChild(top, 0, TAG_LABEL4);

    },

    onBackCallback:function (sender) {
        this.showFont(backFontTestAction());
    },
    onRestartCallback:function (sender) {
        this.showFont(restartFontTestAction());
    },
    onNextCallback:function (sender) {
        this.showFont(nextFontTestAction());
    },
    subtitle:function () {
        return "Font test";
    },
    title:function () {
        return "" + fontList[fontIdx];
    },

    // automation
    numberOfPendingTests:function() {
        return ( (fontList.length-1) - fontIdx );
    },
    getTestNumber:function() {
        return fontIdx;
    }

});
<|endoftext|>


<commit_before>/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
   Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License.
   You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and limitations under the License.*/

define.class('$ui/view', function(icon, label){
	// Simple toggle button: a rectangle with a textlabel and an icon

	this.attributes = {
		// The label for the button
		text: Config({type: String, value: ""}),

		icon: Config({type: String, value: "check"}),

		// Font size in device-pixels.
		fontsize: Config({type: float, value: 14}),

		// Gradient color 1
		col1: Config({meta:"color", type: vec4, value: vec4("#404040"), duration: 1.0}),
		// Gradient color 2
		col2: Config({meta:"color", type: vec4, value: vec4("#404040"), duration: 1.0}),

		// Color of the label text in neutral state
		textcolor: Config({meta:"color", type: vec4, value: vec4("#404040")}),

		// Color of the label text in pressed-down state
		textactivecolor: Config({meta:"color", type: vec4, value: vec4("green")}),

		// First gradient color for the button background in neutral state
		buttoncolor1: Config({meta:"color", type: vec4, value: vec4("#fffff0")}),
		// Second gradient color for the button background in neutral state
		buttoncolor2: Config({meta:"color", type: vec4, value: vec4("#ffffff")}),

		// First gradient color for the button background in hovered state
		hovercolor1: Config({meta:"color", type: vec4, value: vec4("#f0f0f0")}),
		// Second gradient color for the button background in hovered state
		hovercolor2: Config({meta:"color", type: vec4, value: vec4("#f8f8f8")}),

		// First gradient color for the button background in pressed state
		pressedcolor1: Config({meta:"color", type: vec4, value: vec4("#d0d0f0")}),
		// Second gradient color for the button background in pressed state
		pressedcolor2: Config({meta:"color", type: vec4, value: vec4("#d0d0f0")}),

		// fires when button is clicked
		click:Config({type:Event}),
		value:Config({type:Boolean, value:false}),

		bgcolor: '#eee',
		fgcolor: vec4("#404040"),
		buttonres: {},
		padding: 8,
		borderradius: 3,
		borderwidth: 2,
		margin: 4,
		pickalpha:-1,
		bordercolor: vec4("lightgray"),
		alignItems: "center"
	}

	this.style = {
		icon:{
			fgcolor:Config({motion:'linear', duration:0.1})
		}
	}

	this.hardrect = {
		color: function(){
			return mix(view.col1, view.col2, (uv.y)/0.8)
		}
	}

	// the hover state when someone hovers over the button
	this.statehover = function(){
		this.col1 = this.hovercolor1
		this.col2 = this.hovercolor2
	}

	// the normal button state
	this.statenormal = function(){
		this.col1 = this.buttoncolor1
		this.col2 = this.buttoncolor2
	}

	// clicked state
	this.stateclick = function(){
		//this.animate({col1:{0:vec4('red'),3:vec4('green')}})
		this.col1 = this.pressedcolor1
		this.col2 = this.pressedcolor2

		this.value  = !(this.value);
	}

	this.init = function(){
		this.statenormal()
	}

	this.pointerover = function(){this.statehover()}
	this.pointerout = function(){this.statenormal()}
	this.pointerstart = function(){this.stateclick()}
	this.pointerend = function(event){
		this.statenormal()
		if (event.isover){
			this.emit('click',event)
		}
	}

	this.flexdirection = 'row'

	this.render = function(){
		var cb = [];

		cb.push(icon({
			fgcolor:(!!(this.value) ? this.textactivecolor : this.textcolor),
			icon: this.icon,
			fontsize:this.fontsize,
			bgcolor:"transparent",
			drawtarget:"color"
		}));

		if (this.text) {
			cb.push(label({
				bgcolor:NaN,
				drawtarget:"color",
				padding:vec4(10,0,0,0),
				text:this.text,
				fontsize:this.fontsize,
				fgcolor:(!!(this.value) ? this.textactivecolor : this.textcolor)
			}))
		}

		return cb;
	}

	// Basic usage of the button.
	var checkbox = this.constructor
	this.constructor.examples = {
		Usage:function(){
			return [
				checkbox({value:true}),
				checkbox({text:"With an icon!", icon:"flask" }),
				checkbox({
					icon:"square-o",
					text:"Checkbox Unselected (FALSE)",
					borderwidth:0,
					bgcolor:"transparent",
					textcolor:"white",
					textactivecolor:"white",
					click:function(){
						this.icon = this.value ? "check-square-o" : "square-o"
						this.text = "Checkbox " + (this.value ? "Selected (TRUE)" : "Unselected (FALSE)")
					}
				}),
				checkbox({
					icon:undefined,
					text:"Using bg image",
					textcolor:"white",
					bgimage:"$resources/textures/purplecloud.png",
					bgimagemode:"stretch",
					click:function(){
						this.bgimage = this.value ? "$resources/textures/bluecloud.png" : "$resources/textures/purplecloud.png";
					}
				})
			]
		}
	}
})
<commit_msg>tweak example<commit_after>/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
   Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License.
   You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and limitations under the License.*/

define.class('$ui/view', function(icon, label){
	// Simple toggle button: a rectangle with a textlabel and an icon

	this.attributes = {
		// The label for the button
		text: Config({type: String, value: ""}),

		icon: Config({type: String, value: "check"}),

		// Font size in device-pixels.
		fontsize: Config({type: float, value: 14}),

		// Gradient color 1
		col1: Config({meta:"color", type: vec4, value: vec4("#404040"), duration: 1.0}),
		// Gradient color 2
		col2: Config({meta:"color", type: vec4, value: vec4("#404040"), duration: 1.0}),

		// Color of the label text in neutral state
		textcolor: Config({meta:"color", type: vec4, value: vec4("#404040")}),

		// Color of the label text in pressed-down state
		textactivecolor: Config({meta:"color", type: vec4, value: vec4("green")}),

		// First gradient color for the button background in neutral state
		buttoncolor1: Config({meta:"color", type: vec4, value: vec4("#fffff0")}),
		// Second gradient color for the button background in neutral state
		buttoncolor2: Config({meta:"color", type: vec4, value: vec4("#ffffff")}),

		// First gradient color for the button background in hovered state
		hovercolor1: Config({meta:"color", type: vec4, value: vec4("#f0f0f0")}),
		// Second gradient color for the button background in hovered state
		hovercolor2: Config({meta:"color", type: vec4, value: vec4("#f8f8f8")}),

		// First gradient color for the button background in pressed state
		pressedcolor1: Config({meta:"color", type: vec4, value: vec4("#d0d0f0")}),
		// Second gradient color for the button background in pressed state
		pressedcolor2: Config({meta:"color", type: vec4, value: vec4("#d0d0f0")}),

		// fires when button is clicked
		click:Config({type:Event}),
		value:Config({type:Boolean, value:false}),

		bgcolor: '#eee',
		fgcolor: vec4("#404040"),
		buttonres: {},
		padding: 8,
		borderradius: 3,
		borderwidth: 2,
		margin: 4,
		pickalpha:-1,
		bordercolor: vec4("lightgray"),
		alignItems: "center"
	}

	this.style = {
		icon:{
			fgcolor:Config({motion:'linear', duration:0.1})
		}
	}

	this.hardrect = {
		color: function(){
			return mix(view.col1, view.col2, (uv.y)/0.8)
		}
	}

	// the hover state when someone hovers over the button
	this.statehover = function(){
		this.col1 = this.hovercolor1
		this.col2 = this.hovercolor2
	}

	// the normal button state
	this.statenormal = function(){
		this.col1 = this.buttoncolor1
		this.col2 = this.buttoncolor2
	}

	// clicked state
	this.stateclick = function(){
		//this.animate({col1:{0:vec4('red'),3:vec4('green')}})
		this.col1 = this.pressedcolor1
		this.col2 = this.pressedcolor2

		this.value  = !(this.value);
	}

	this.init = function(){
		this.statenormal()
	}

	this.pointerover = function(){this.statehover()}
	this.pointerout = function(){this.statenormal()}
	this.pointerstart = function(){this.stateclick()}
	this.pointerend = function(event){
		this.statenormal()
		if (event.isover){
			this.emit('click',event)
		}
	}

	this.flexdirection = 'row'

	this.render = function(){
		var cb = [];

		cb.push(icon({
			fgcolor:(!!(this.value) ? this.textactivecolor : this.textcolor),
			icon: this.icon,
			fontsize:this.fontsize,
			bgcolor:"transparent",
			drawtarget:"color"
		}));

		if (this.text) {
			cb.push(label({
				bgcolor:NaN,
				drawtarget:"color",
				padding:vec4(10,0,0,0),
				text:this.text,
				fontsize:this.fontsize,
				fgcolor:(!!(this.value) ? this.textactivecolor : this.textcolor)
			}))
		}

		return cb;
	}

	// Basic usage of the button.
	var checkbox = this.constructor
	this.constructor.examples = {
		Usage:function(){
			return [
				checkbox({
					bgcolor:"transparent",
					textcolor:"transparent",
					value:true
				}),
				checkbox({text:"With an icon!", icon:"flask" }),
				checkbox({
					icon:"square-o",
					text:"Checkbox Unselected (FALSE)",
					borderwidth:0,
					bgcolor:"transparent",
					textcolor:"white",
					textactivecolor:"white",
					click:function(){
						this.icon = this.value ? "check-square-o" : "square-o"
						this.text = "Checkbox " + (this.value ? "Selected (TRUE)" : "Unselected (FALSE)")
					}
				}),
				checkbox({
					icon:undefined,
					text:"Using bg image",
					textcolor:"white",
					bgimage:"$resources/textures/purplecloud.png",
					bgimagemode:"stretch",
					click:function(){
						this.bgimage = this.value ? "$resources/textures/bluecloud.png" : "$resources/textures/purplecloud.png";
					}
				})
			]
		}
	}
})
<|endoftext|>


<commit_before>/**
 * @overview
 * Logic for creating new Titanium apps.
 *
 * @copyright
 * Copyright (c) 2009-2014 by Appcelerator, Inc. All Rights Reserved.
 *
 * @license
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var appc = require('node-appc'),
	Creator = require('./creator'),
	fs = require('fs'),
	http = require('http'),
	path = require('path'),
	request = require('request'),
	temp = require('temp'),
	ti = require('titanium-sdk'),
	util = require('util'),
	uuid = require('node-uuid'),
	wrench = require('wrench'),
	__ = appc.i18n(__dirname).__;

module.exports = AppCreator;

function AppCreator() {
	Creator.apply(this, arguments);
}

util.inherits(AppCreator, Creator);

AppCreator.prototype.run = function run(callback) {
	this.logger.info(__('Creating Titanium Mobile application project'));

	var i, l, dir,
		template = this.cli.argv.template || 'default',
		searchPaths = [ appc.fs.resolvePath(this.sdk.path, 'templates', this.cli.argv.type) ],
		additionalPaths = this.config.get('paths.templates');

	this.cli.env.os.sdkPaths.forEach(function (dir) {
		if (fs.existsSync(dir = appc.fs.resolvePath(dir)) && searchPaths.indexOf(dir) == -1) {
			searchPaths.push(dir);
		}
	});

	if (additionalPaths) {
		(Array.isArray(additionalPaths) ? additionalPaths : [ additionalPaths ]).forEach(function (p) {
			if (p && fs.existsSync(p = appc.fs.resolvePath(p)) && searchPaths.indexOf(p) == -1) {
				searchPaths.push(p);
			}
		});
	}

	if (fs.existsSync(template)) {
		if (fs.statSync(template).isDirectory()) {
			copyFiles.call(this, template, callback);
			return;
		}

		if (/\.zip$/.test(template)) {
			unzipFile.call(this, template, callback);
			return;
		}
	} else {
		if (/^https?\:\/\/.+/.test(template)) {
			downloadFile.call(this, template, callback);
			return;
		}

		for (i = 0, l = searchPaths.length; i < l; i++) {
			if (fs.existsSync(dir = path.join(searchPaths[i], template))) {
				copyFiles.call(this, dir);
				return;
			}
		}
	}

	this.logger.error(__('Unable to find template "%s"', template));
	callback(true);
};

function copyFiles(templateDir, alldone) {
	this.templateDir = templateDir;
	this.cli.scanHooks(path.join(this.templateDir, 'hooks'));

	appc.async.series(this, [
		function (next) {
			var dir = path.join(this.templateDir, 'template');
			if (fs.existsSync(dir)) {
				this.cli.createHook('create.copyFiles', this, function (templateDir, projectDir, opts, done) {
					appc.fs.copyDirSyncRecursive(templateDir, projectDir, opts);
					done();
				})(dir, this.projectDir, { logger: this.logger.debug }, next);
			} else {
				next();
			}
		},

		function (next) {
			var params = {
					id: this.id,
					name: this.projectName,
					url: this.url,
					version: '1.0',
					guid: uuid.v4(),
					'deployment-targets': {},
					'sdk-version': this.sdk.name
				},
				tiappFile = path.join(this.projectDir, 'tiapp.xml');

			if (this.platforms.original.indexOf('ios') != -1) {
				this.platforms.original.indexOf('ipad') != -1 || this.platforms.original.push('ipad');
				this.platforms.original.indexOf('iphone') != -1 || this.platforms.original.push('iphone');
			}

			ti.availablePlatformsNames.forEach(function (p) {
				if (p != 'ios') {
					params['deployment-targets'][p] = this.platforms.original.indexOf(p) != -1;
				}
			}, this);

			this.cli.createHook('create.populateTiappXml', this, function (tiapp, params, done) {
				// read and populate the tiapp.xml
				this.projectConfig = appc.util.mix(tiapp, params);
				this.projectConfig.save(tiappFile);
				done();
			}.bind(this))(fs.existsSync(tiappFile) ? new ti.tiappxml(tiappFile) : new ti.tiappxml(), params, next);
		},

		function (next) {
			var dir = path.join(this.projectDir, 'Resources');
			fs.existsSync(dir) || wrench.mkdirSyncRecursive(dir);
			next();
		},

		function (next) {
			this.cli.addAnalyticsEvent('project.create.mobile', {
				dir: this.projectDir,
				name: this.projectName,
				publisher: this.projectConfig.publisher,
				url: this.projectConfig.url,
				image: this.projectConfig.image,
				appid: this.id,
				description: this.projectConfig.description,
				type: 'mobile',
				guid: this.projectConfig.guid,
				version: this.projectConfig.version,
				copyright: this.projectConfig.copyright,
				runtime: '1.0',
				date: (new Date()).toDateString()
			});
			next();
		}
	], alldone);
}

function unzipFile(zipFile, alldone) {
	var dir = temp.mkdirSync({ prefix: 'titanium-' });
	fs.existsSync(dir) || wrench.mkdirSyncRecursive(dir);
	this.logger.info(__('Extracting %s', zipFile.cyan));
	appc.zip.unzip(zipFile, dir, null, function() {
		copyFiles.call(this, dir, function () {
			wrench.rmdirSyncRecursive(dir);
			alldone();
		});
	}.bind(this));
}

function downloadFile(url, alldone) {
	var _t = this,
		tempName = temp.path({ suffix: '.zip' }),
		tempDir = path.dirname(tempName);
	fs.existsSync(tempDir) || wrench.mkdirSyncRecursive(tempDir);

	this.logger.info(__('Downloading %s', url.cyan));

	var tempStream = fs.createWriteStream(tempName),
		req = request({
			url: url,
			proxy: this.config.get('cli.httpProxyServer'),
			rejectUnauthorized: this.config.get('cli.rejectUnauthorized', true)
		});

	req.pipe(tempStream);

	req.on('error', function (err) {
		fs.existsSync(tempName) && fs.unlinkSync(tempName);
		this.logger.log();
		this.logger.error(__('Failed to download template: %s', url) + '\n');
		alldone(true);
	}.bind(this));

	req.on('response', function (req) {
		if (req.statusCode >= 400) {
			// something went wrong, abort
			_t.logger.error(__('Request failed with HTTP status code %s %s', req.statusCode, http.STATUS_CODES[req.statusCode] || ''));
			alldone(true);
			return;
		}

		tempStream.on('close', function () {
			unzipFile.call(_t, tempName, alldone);
		});
	});
}<commit_msg>[TIMOB-16620] Added missing callback.<commit_after>/**
 * @overview
 * Logic for creating new Titanium apps.
 *
 * @copyright
 * Copyright (c) 2009-2014 by Appcelerator, Inc. All Rights Reserved.
 *
 * @license
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var appc = require('node-appc'),
	Creator = require('./creator'),
	fs = require('fs'),
	http = require('http'),
	path = require('path'),
	request = require('request'),
	temp = require('temp'),
	ti = require('titanium-sdk'),
	util = require('util'),
	uuid = require('node-uuid'),
	wrench = require('wrench'),
	__ = appc.i18n(__dirname).__;

module.exports = AppCreator;

function AppCreator() {
	Creator.apply(this, arguments);
}

util.inherits(AppCreator, Creator);

AppCreator.prototype.run = function run(callback) {
	this.logger.info(__('Creating Titanium Mobile application project'));

	var i, l, dir,
		template = this.cli.argv.template || 'default',
		searchPaths = [ appc.fs.resolvePath(this.sdk.path, 'templates', this.cli.argv.type) ],
		additionalPaths = this.config.get('paths.templates');

	this.cli.env.os.sdkPaths.forEach(function (dir) {
		if (fs.existsSync(dir = appc.fs.resolvePath(dir)) && searchPaths.indexOf(dir) == -1) {
			searchPaths.push(dir);
		}
	});

	if (additionalPaths) {
		(Array.isArray(additionalPaths) ? additionalPaths : [ additionalPaths ]).forEach(function (p) {
			if (p && fs.existsSync(p = appc.fs.resolvePath(p)) && searchPaths.indexOf(p) == -1) {
				searchPaths.push(p);
			}
		});
	}

	if (fs.existsSync(template)) {
		if (fs.statSync(template).isDirectory()) {
			copyFiles.call(this, template, callback);
			return;
		}

		if (/\.zip$/.test(template)) {
			unzipFile.call(this, template, callback);
			return;
		}
	} else {
		if (/^https?\:\/\/.+/.test(template)) {
			downloadFile.call(this, template, callback);
			return;
		}

		for (i = 0, l = searchPaths.length; i < l; i++) {
			if (fs.existsSync(dir = path.join(searchPaths[i], template))) {
				copyFiles.call(this, dir, callback);
				return;
			}
		}
	}

	this.logger.error(__('Unable to find template "%s"', template));
	callback(true);
};

function copyFiles(templateDir, alldone) {
	this.templateDir = templateDir;
	this.cli.scanHooks(path.join(this.templateDir, 'hooks'));

	appc.async.series(this, [
		function (next) {
			var dir = path.join(this.templateDir, 'template');
			if (fs.existsSync(dir)) {
				this.cli.createHook('create.copyFiles', this, function (templateDir, projectDir, opts, done) {
					appc.fs.copyDirSyncRecursive(templateDir, projectDir, opts);
					done();
				})(dir, this.projectDir, { logger: this.logger.debug }, next);
			} else {
				next();
			}
		},

		function (next) {
			var params = {
					id: this.id,
					name: this.projectName,
					url: this.url,
					version: '1.0',
					guid: uuid.v4(),
					'deployment-targets': {},
					'sdk-version': this.sdk.name
				},
				tiappFile = path.join(this.projectDir, 'tiapp.xml');

			if (this.platforms.original.indexOf('ios') != -1) {
				this.platforms.original.indexOf('ipad') != -1 || this.platforms.original.push('ipad');
				this.platforms.original.indexOf('iphone') != -1 || this.platforms.original.push('iphone');
			}

			ti.availablePlatformsNames.forEach(function (p) {
				if (p != 'ios') {
					params['deployment-targets'][p] = this.platforms.original.indexOf(p) != -1;
				}
			}, this);

			this.cli.createHook('create.populateTiappXml', this, function (tiapp, params, done) {
				// read and populate the tiapp.xml
				this.projectConfig = appc.util.mix(tiapp, params);
				this.projectConfig.save(tiappFile);
				done();
			}.bind(this))(fs.existsSync(tiappFile) ? new ti.tiappxml(tiappFile) : new ti.tiappxml(), params, next);
		},

		function (next) {
			var dir = path.join(this.projectDir, 'Resources');
			fs.existsSync(dir) || wrench.mkdirSyncRecursive(dir);
			next();
		},

		function (next) {
			this.cli.addAnalyticsEvent('project.create.mobile', {
				dir: this.projectDir,
				name: this.projectName,
				publisher: this.projectConfig.publisher,
				url: this.projectConfig.url,
				image: this.projectConfig.image,
				appid: this.id,
				description: this.projectConfig.description,
				type: 'mobile',
				guid: this.projectConfig.guid,
				version: this.projectConfig.version,
				copyright: this.projectConfig.copyright,
				runtime: '1.0',
				date: (new Date()).toDateString()
			});
			next();
		}
	], alldone);
}

function unzipFile(zipFile, alldone) {
	var dir = temp.mkdirSync({ prefix: 'titanium-' });
	fs.existsSync(dir) || wrench.mkdirSyncRecursive(dir);
	this.logger.info(__('Extracting %s', zipFile.cyan));
	appc.zip.unzip(zipFile, dir, null, function() {
		copyFiles.call(this, dir, function () {
			wrench.rmdirSyncRecursive(dir);
			alldone();
		});
	}.bind(this));
}

function downloadFile(url, alldone) {
	var _t = this,
		tempName = temp.path({ suffix: '.zip' }),
		tempDir = path.dirname(tempName);
	fs.existsSync(tempDir) || wrench.mkdirSyncRecursive(tempDir);

	this.logger.info(__('Downloading %s', url.cyan));

	var tempStream = fs.createWriteStream(tempName),
		req = request({
			url: url,
			proxy: this.config.get('cli.httpProxyServer'),
			rejectUnauthorized: this.config.get('cli.rejectUnauthorized', true)
		});

	req.pipe(tempStream);

	req.on('error', function (err) {
		fs.existsSync(tempName) && fs.unlinkSync(tempName);
		this.logger.log();
		this.logger.error(__('Failed to download template: %s', url) + '\n');
		alldone(true);
	}.bind(this));

	req.on('response', function (req) {
		if (req.statusCode >= 400) {
			// something went wrong, abort
			_t.logger.error(__('Request failed with HTTP status code %s %s', req.statusCode, http.STATUS_CODES[req.statusCode] || ''));
			alldone(true);
			return;
		}

		tempStream.on('close', function () {
			unzipFile.call(_t, tempName, alldone);
		});
	});
}<|endoftext|>


<commit_before>Template.worker.events({
  'click button': function (event) {
    var people = Session.get('people');
    var person = people[event.target.id];
    if (Session.get('score') >= person.price) {
      person.numberOwned += 1;
      people[event.target.id] = person;

      Session.setPersistent({
        score: Session.get('score') - person.price,
        boostrate: Session.get('boostrate') + person.boostrate,
        people: people
      });
    }
  }
});
<commit_msg>Add helper for people<commit_after>Template.worker.helpers({
  people: function () {
    people = []
    _.forEach(Session.get('people'), function(person, key) {
      person.class_ = key;
      people.push(person);
    });
    return people;
  }
});

Template.worker.events({
  'click button': function (event) {
    var people = Session.get('people');
    var person = people[event.target.id];
    if (Session.get('score') >= person.price) {
      person.numberOwned += 1;
      person.price *= 1.2
      person.price = Math.round(person.price);
      people[event.target.id] = person;

      Session.setPersistent({
        score: Session.get('score') - person.price,
        boostrate: Session.get('boostrate') + person.boostrate,
        people: people
      });
    }
  }
});
<|endoftext|>


<commit_before>var path = require("path")
var fs = require("fs")

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd())
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath)
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

var nodePaths = (process.env.NODE_PATH || "")
  .split(process.platform === "win32" ? ";" : ":")
  .filter(Boolean)
  .map(resolveApp)

// config after eject: we're in ./config/
module.exports = {
  appBuild: resolveApp("../build/resources/main/assets/client"),
  appHtml: resolveApp("public/index.html"),
  appIndexJs: resolveApp("src/index.js"),
  appPackageJson: resolveApp("package.json"),
  appSrc: resolveApp("src"),
  clientBuild: resolveApp("build"),
  testsSetup: resolveApp("src/setupTests.js"),
  appNodeModules: resolveApp("node_modules"),
  ownNodeModules: resolveApp("node_modules"),
  nodePaths: nodePaths
}

// config before publish: we're in ./packages/react-scripts/config/
if (__dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) {
  module.exports = {
    appBuild: resolveOwn('../../../build'),
    appHtml: resolveOwn('../template/public/index.html'),
    appIndexJs: resolveOwn('../template/src/index.js'),
    appPackageJson: resolveOwn('../package.json'),
    appSrc: resolveOwn('../template/src'),
    testsSetup: resolveOwn('../template/src/setupTests.js'),
    appNodeModules: resolveOwn('../node_modules'),
    ownNodeModules: resolveOwn('../node_modules'),
    nodePaths: nodePaths
  }
}
<commit_msg>Remove obsolete code<commit_after>var path = require("path")
var fs = require("fs")

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd())
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath)
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

var nodePaths = (process.env.NODE_PATH || "")
  .split(process.platform === "win32" ? ";" : ":")
  .filter(Boolean)
  .map(resolveApp)

// config after eject: we're in ./config/
module.exports = {
  appBuild: resolveApp("../build/resources/main/assets/client"),
  appHtml: resolveApp("public/index.html"),
  appIndexJs: resolveApp("src/index.js"),
  appPackageJson: resolveApp("package.json"),
  appSrc: resolveApp("src"),
  clientBuild: resolveApp("build"),
  testsSetup: resolveApp("src/setupTests.js"),
  appNodeModules: resolveApp("node_modules"),
  ownNodeModules: resolveApp("node_modules"),
  nodePaths: nodePaths
}
<|endoftext|>


<commit_before>var actionTemplates = null;

var actions = {
    user: {
        ban: {
            url: "mod/toggle_ban",
            btnStyle: "danger",
            callback: function(data, elem) {
                elem.text(`${data.banned ? "Unban" : "Ban"}`);
            },
            buttonText: function(data) {
                return data.banned ? "Unban" : "Ban";
            }
        },
        activation: {
            url: "mod/toggle_active",
            btnStyle: "warning",
            callback: function(data, elem) {
                elem.text(`${data.deactivated ? "Activate" : "Deactivate"}`);
            },
            buttonText: function(data) {
                return data.deactivated ? "Activate" : "Deactivate";
            }
        },
        mod: {
            url: "admin/toggle_mod",
            btnStyle: "info",
            adminOnly: true,
            callback: function(data, elem) {
                elem.text(`${data.moderator ? "Remove" : "Give"} Moderator`);
            },
            buttonText: function(data) {
                return `${data.moderator ? "Remove" : "Give"} Moderator`
            }
        }
    },
    server: {
        reloadConfig: {
            url: "admin/reload_config",
            btnStyle: "success",
            adminOnly: true,
            callback: (data, elem) => {
                elem.text(actions.server.reloadConfig.buttonText(data));
                alert("Successfully reloaded configuration from file.")
            },
            buttonText: data => "Reload Config"
        },
        refreshClients: {
            url: "admin/refresh_clients",
            btnStyle: "danger",
            adminOnly: true,
            callback: (data, elem) => {
                elem.text(actions.server.refreshClients.buttonText(data));
                alert("Successfully refreshed all clients currently connected to websockets.")
            },
            buttonText: data => "Refresh All Clients"
        }
    }
}
var renderAction = function(actionName, data = {}, type = "user") {
    var action = actions[type][actionName];
    return `<a href="javascript:void(0)" class="btn btn-${action.btnStyle} ${type}-action-btn" data-admin-only=${action.adminOnly === true} data-${type}-action="${actionName}">${action.buttonText(data)}</a>`;
}

var renderUserActions = function(user) {
    var currentUserID = $("body").data("user-id");
    var currentIsAdmin = $("body").data("user-is-admin");
    var currentIsMod = $("body").data("user-is-mod");
    var canTouchUser = (currentIsMod && !(user.moderator || user.admin)) || (currentIsAdmin && !user.admin);
    if(user._id) user.id = user._id;
    if(currentUserID == user.id || !canTouchUser) return ``;
    return `

        View Similar
        ${renderAction("ban", user)}
        ${renderAction("activation", user)}
        ${renderAction("mod", user)}

`
}

var renderServerActions = function() {
    return `

        ${renderAction("reloadConfig", {}, "server")}
        ${renderAction("refreshClients", {}, "server")}
        Broadcast message</button>

`
}

$("body").on("click", ".user-action-btn", function() {
    function handleError(data) {
        var error = "An unknown error occurred."
        if(data && typeof data.error !== 'undefined' && data.error.message) error = data.error.message;
        alert("Couldn't perform action on user: " + error);
    }
    var userID = $(this).parent().data("user-id");
    var action = actions.user[$(this).data("user-action")];
    var originalText = $(this).html();
    $(this).addClass("disabled");
    $(this).html(`<i class="fa fa-circle-o-notch fa-spin"></i> ${originalText}`);
    var elem = $(this);
    $.get(`/api/${action.url}/`, {id: userID}).done(function(data) {
        if(!data.success) return handleError(data);
        action.callback(data, elem);
    }).fail(function(res) {
        handleError(typeof res.responseJSON === 'undefined' ? null : res.responseJSON);
        if(action.callbackModifiesText !== false) elem.html(originalText);
    }).always(function() {
        elem.removeClass("disabled");
        if(action.callbackModifiesText === false) elem.html(originalText);
    });
});

$("body").on("click", ".server-action-btn", function() {
    function handleError(data) {
        var error = "An unknown error occurred."
        if(data && typeof data.error !== 'undefined' && data.error.message) error = data.error.message;
        alert("Couldn't perform action: " + error);
    }
    var action = actions.server[$(this).data("server-action")];
    var originalText = $(this).html();
    $(this).addClass("disabled");
    $(this).html(`<i class="fa fa-circle-o-notch fa-spin"></i> ${originalText}`);
    var elem = $(this);
    $.get(`/api/${action.url}/`).done(function(data) {
        if(!data.success) return handleError(data);
        action.callback(data, elem);
    }).fail(function(res) {
        handleError(typeof res.responseJSON === 'undefined' ? null : res.responseJSON);
        if(action.callbackModifiesText !== false) elem.html(originalText);
    }).always(function() {
        elem.removeClass("disabled");
        if(action.callbackModifiesText === false) elem.html(originalText);
    });
});

$("#broadcastForm").submit(function(e) {
    e.preventDefault();
    $.post("/api/admin/broadcast", {
        title: $(this).find("#inputBroadcastTitle").val(),
        message: $(this).find("#inputBroadcastMessage").val(),
        style: $(this).find("#inputBroadcastStyle").val(),
        timeout: $(this).find("#inputBroadcastTimeout").val()
    }).done(function(data) {
        if(!data.success) return alert("Couldn't send broadcast");
        $('#broadcastModal').modal('hide');
        alert("Successfully sent out broadcast to all connected clients.");
    }).fail(function() {
        alert("Couldn't send broadcast");
    })
})

function getRowForAction(action) {
    var actionTemplate = actionTemplates[action.action];
    var randomString = function(length) {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for(var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }
    function parseActionTemplate(template, action) {
        return eval('`' + template.replace(/\${/g, '${action.info.') + '`');
    }

    var row = $("
").addClass("action").attr("data-action-id", action.id);
    var username = "Deleted user";
    var actionTxt = `<span class="action-str" title="${actionTemplate.displayName} - ${actionTemplate.category}">${actionTemplate.inlineDisplayName.toLowerCase()}`;
    if(action.performingUser) username = `<strong><a href="/@${action.performingUser.username}">${action.performingUser.username}</a></strong>`;
    var moreInfoCtn = null;
    var sentenceEnd = "";
    var otherLines = "";
    if(Object.keys(action.info).length > 0) {
        if(typeof actionTemplate.sentenceEndTextFormatting !== 'undefined') sentenceEnd = parseActionTemplate(actionTemplate.sentenceEndTextFormatting, action);
        if(typeof actionTemplate.otherLinesTextFormatting !== 'undefined') otherLines = "
" + parseActionTemplate(actionTemplate.otherLinesTextFormatting, action);
        if(typeof actionTemplate.hideInfo === 'undefined' || !actionTemplate.hideInfo) {
            var moreInfoCtn = $("
").addClass("info-collapse-ctn");
            var id = `info-collapse-${randomString(16)}-${action.id}`;
            var infoCtn = $("
").addClass("collapse info-collapse").attr("id", id).appendTo(moreInfoCtn);
            var infoList = $("
").appendTo(infoCtn);
            Object.keys(action.info).forEach(key => {
                var value = action.info[key];
                if(typeof value !== 'object') {
                    var thisRow = $("
").appendTo(infoList);
                    $("").text(key).appendTo(thisRow);
                    $("").text(`: ${value}`).appendTo(thisRow);
                }
            })
            var seeMoreLink = $("").attr("role", "button").addClass("see-more-toggle").attr("data-toggle", "collapse").attr("href", `#${id}`).attr("aria-expanded", "false").attr("aria-controls", id).text("See more").appendTo(moreInfoCtn);
            infoCtn.on("show.bs.collapse", () => seeMoreLink.text("See less")).on("hide.bs.collapse", () => seeMoreLink.text("See more"))
        }
    }
    var text = `${username} ${actionTxt}${sentenceEnd}</span>.${otherLines}`;
    if(typeof actionTemplate.requiresModerator !== 'undefined' && actionTemplate.requiresModerator) {
        var modUsername = "Deleted moderator"
        if(action.moderatingUser) modUsername = `<strong><a href="/@${action.moderatingUser.username}">${action.moderatingUser.username}</a></strong>`;
        var text = `${modUsername} ${actionTxt} ${username}${sentenceEnd}</span>.${otherLines}`
    }
    $("
").addClass("text").html(text).appendTo(row);
    if(moreInfoCtn) moreInfoCtn.appendTo(row);
    $("<time>").addClass("timeago").attr("datetime", action.date).attr("title", new Date(action.date).toLocaleString()).text($.timeago(action.date)).appendTo(row);
    return row;
}

function fetchActions(lastID, modOnly, limit, callback) {
    $.get("/api/mod/actions", {lastID: lastID, limit: limit, modOnly: modOnly}).done(function(data) {
        if(!data.success || !data.actions || !data.actionTemplates) return callback(null);
        actionTemplates = data.actionTemplates;
        callback(data.actions, data.lastID);
    }).fail(function() {
        callback(null, null);
    });
}

function addToContainerForResponse(container, data, lastID, modOnly, limit, allowsShowMore) {
    data.forEach(action => getRowForAction(action).appendTo(container));
    if(allowsShowMore && lastID) {
        var loading = false;
        $("").addClass("btn btn-primary btn-xs").text("Load more").appendTo(container).on("click", function() {
            var btn = $(this);
            if(!loading) {
                loading = true;
                btn.html(" Loading...").addClass("disabled");
                fetchActions(lastID, modOnly, limit, function(data, lastID) {
                    if(!data) {
                        loading = false;
                        return alert("Couldn't load more actions.")
                    }
                    btn.remove();
                    addToContainerForResponse(container, data, lastID, modOnly, limit, allowsShowMore);
                })
            }
        })
    }
}

function loadRecentActionsIntoContainer(container, limit = null, modOnly = false, allowsShowMore = true) {
    container.html(" Loading...");
    fetchActions(null, modOnly, limit, function(data, lastID) {
        if(!data) return $(container).text("Couldn't load mod actions");
        container.html("");
        addToContainerForResponse(container, data, lastID, modOnly, limit, allowsShowMore);
    });
}<commit_msg>Better formatting for log info<commit_after>var actionTemplates = null;

var actions = {
    user: {
        ban: {
            url: "mod/toggle_ban",
            btnStyle: "danger",
            callback: function(data, elem) {
                elem.text(`${data.banned ? "Unban" : "Ban"}`);
            },
            buttonText: function(data) {
                return data.banned ? "Unban" : "Ban";
            }
        },
        activation: {
            url: "mod/toggle_active",
            btnStyle: "warning",
            callback: function(data, elem) {
                elem.text(`${data.deactivated ? "Activate" : "Deactivate"}`);
            },
            buttonText: function(data) {
                return data.deactivated ? "Activate" : "Deactivate";
            }
        },
        mod: {
            url: "admin/toggle_mod",
            btnStyle: "info",
            adminOnly: true,
            callback: function(data, elem) {
                elem.text(`${data.moderator ? "Remove" : "Give"} Moderator`);
            },
            buttonText: function(data) {
                return `${data.moderator ? "Remove" : "Give"} Moderator`
            }
        }
    },
    server: {
        reloadConfig: {
            url: "admin/reload_config",
            btnStyle: "success",
            adminOnly: true,
            callback: (data, elem) => {
                elem.text(actions.server.reloadConfig.buttonText(data));
                alert("Successfully reloaded configuration from file.")
            },
            buttonText: data => "Reload Config"
        },
        refreshClients: {
            url: "admin/refresh_clients",
            btnStyle: "danger",
            adminOnly: true,
            callback: (data, elem) => {
                elem.text(actions.server.refreshClients.buttonText(data));
                alert("Successfully refreshed all clients currently connected to websockets.")
            },
            buttonText: data => "Refresh All Clients"
        }
    }
}
var renderAction = function(actionName, data = {}, type = "user") {
    var action = actions[type][actionName];
    return `<a href="javascript:void(0)" class="btn btn-${action.btnStyle} ${type}-action-btn" data-admin-only=${action.adminOnly === true} data-${type}-action="${actionName}">${action.buttonText(data)}</a>`;
}

var renderUserActions = function(user) {
    var currentUserID = $("body").data("user-id");
    var currentIsAdmin = $("body").data("user-is-admin");
    var currentIsMod = $("body").data("user-is-mod");
    var canTouchUser = (currentIsMod && !(user.moderator || user.admin)) || (currentIsAdmin && !user.admin);
    if(user._id) user.id = user._id;
    if(currentUserID == user.id || !canTouchUser) return ``;
    return `

        View Similar
        ${renderAction("ban", user)}
        ${renderAction("activation", user)}
        ${renderAction("mod", user)}

`
}

var renderServerActions = function() {
    return `

        ${renderAction("reloadConfig", {}, "server")}
        ${renderAction("refreshClients", {}, "server")}
        Broadcast message</button>

`
}

$("body").on("click", ".user-action-btn", function() {
    function handleError(data) {
        var error = "An unknown error occurred."
        if(data && typeof data.error !== 'undefined' && data.error.message) error = data.error.message;
        alert("Couldn't perform action on user: " + error);
    }
    var userID = $(this).parent().data("user-id");
    var action = actions.user[$(this).data("user-action")];
    var originalText = $(this).html();
    $(this).addClass("disabled");
    $(this).html(`<i class="fa fa-circle-o-notch fa-spin"></i> ${originalText}`);
    var elem = $(this);
    $.get(`/api/${action.url}/`, {id: userID}).done(function(data) {
        if(!data.success) return handleError(data);
        action.callback(data, elem);
    }).fail(function(res) {
        handleError(typeof res.responseJSON === 'undefined' ? null : res.responseJSON);
        if(action.callbackModifiesText !== false) elem.html(originalText);
    }).always(function() {
        elem.removeClass("disabled");
        if(action.callbackModifiesText === false) elem.html(originalText);
    });
});

$("body").on("click", ".server-action-btn", function() {
    function handleError(data) {
        var error = "An unknown error occurred."
        if(data && typeof data.error !== 'undefined' && data.error.message) error = data.error.message;
        alert("Couldn't perform action: " + error);
    }
    var action = actions.server[$(this).data("server-action")];
    var originalText = $(this).html();
    $(this).addClass("disabled");
    $(this).html(`<i class="fa fa-circle-o-notch fa-spin"></i> ${originalText}`);
    var elem = $(this);
    $.get(`/api/${action.url}/`).done(function(data) {
        if(!data.success) return handleError(data);
        action.callback(data, elem);
    }).fail(function(res) {
        handleError(typeof res.responseJSON === 'undefined' ? null : res.responseJSON);
        if(action.callbackModifiesText !== false) elem.html(originalText);
    }).always(function() {
        elem.removeClass("disabled");
        if(action.callbackModifiesText === false) elem.html(originalText);
    });
});

$("#broadcastForm").submit(function(e) {
    e.preventDefault();
    $.post("/api/admin/broadcast", {
        title: $(this).find("#inputBroadcastTitle").val(),
        message: $(this).find("#inputBroadcastMessage").val(),
        style: $(this).find("#inputBroadcastStyle").val(),
        timeout: $(this).find("#inputBroadcastTimeout").val()
    }).done(function(data) {
        if(!data.success) return alert("Couldn't send broadcast");
        $('#broadcastModal').modal('hide');
        alert("Successfully sent out broadcast to all connected clients.");
    }).fail(function() {
        alert("Couldn't send broadcast");
    })
})

function getRowForAction(action) {
    var actionTemplate = actionTemplates[action.action];
    var randomString = function(length) {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for(var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }
    function parseActionTemplate(template, action) {
        return eval('`' + template.replace(/\${/g, '${action.info.') + '`');
    }

    var row = $("
").addClass("action").attr("data-action-id", action.id);
    var username = "Deleted user";
    var actionTxt = `<span class="action-str" title="${actionTemplate.displayName} - ${actionTemplate.category}">${actionTemplate.inlineDisplayName.toLowerCase()}`;
    if(action.performingUser) username = `<strong><a href="/@${action.performingUser.username}">${action.performingUser.username}</a></strong>`;
    var moreInfoCtn = null;
    var sentenceEnd = "";
    var otherLines = "";
    if(Object.keys(action.info).length > 0) {
        if(typeof actionTemplate.sentenceEndTextFormatting !== 'undefined') sentenceEnd = parseActionTemplate(actionTemplate.sentenceEndTextFormatting, action);
        if(typeof actionTemplate.otherLinesTextFormatting !== 'undefined') otherLines = "
" + parseActionTemplate(actionTemplate.otherLinesTextFormatting, action);
        if(typeof actionTemplate.hideInfo === 'undefined' || !actionTemplate.hideInfo) {
            var moreInfoCtn = $("
").addClass("info-collapse-ctn");
            var id = `info-collapse-${randomString(16)}-${action.id}`;
            var infoCtn = $("
").addClass("collapse info-collapse").attr("id", id).appendTo(moreInfoCtn);
            var infoList = $("<samp>").appendTo(infoCtn);
            Object.keys(action.info).forEach(key => {
                var value = action.info[key];
                if(typeof value !== 'object') {
                    $("").text(key + ":").appendTo(infoList);
                    $("").html(` ${value}<br>`).appendTo(infoList);
                }
            })
            var seeMoreLink = $("").attr("role", "button").addClass("see-more-toggle").attr("data-toggle", "collapse").attr("href", `#${id}`).attr("aria-expanded", "false").attr("aria-controls", id).text("See more").appendTo(moreInfoCtn);
            infoCtn.on("show.bs.collapse", () => seeMoreLink.text("See less")).on("hide.bs.collapse", () => seeMoreLink.text("See more"))
        }
    }
    var text = `${username} ${actionTxt}${sentenceEnd}</span>.${otherLines}`;
    if(typeof actionTemplate.requiresModerator !== 'undefined' && actionTemplate.requiresModerator) {
        var modUsername = "Deleted moderator"
        if(action.moderatingUser) modUsername = `<strong><a href="/@${action.moderatingUser.username}">${action.moderatingUser.username}</a></strong>`;
        var text = `${modUsername} ${actionTxt} ${username}${sentenceEnd}</span>.${otherLines}`
    }
    $("
").addClass("text").html(text).appendTo(row);
    if(moreInfoCtn) moreInfoCtn.appendTo(row);
    $("<time>").addClass("timeago").attr("datetime", action.date).attr("title", new Date(action.date).toLocaleString()).text($.timeago(action.date)).appendTo(row);
    return row;
}

function fetchActions(lastID, modOnly, limit, callback) {
    $.get("/api/mod/actions", {lastID: lastID, limit: limit, modOnly: modOnly}).done(function(data) {
        if(!data.success || !data.actions || !data.actionTemplates) return callback(null);
        actionTemplates = data.actionTemplates;
        callback(data.actions, data.lastID);
    }).fail(function() {
        callback(null, null);
    });
}

function addToContainerForResponse(container, data, lastID, modOnly, limit, allowsShowMore) {
    data.forEach(action => getRowForAction(action).appendTo(container));
    if(allowsShowMore && lastID) {
        var loading = false;
        $("").addClass("btn btn-primary btn-xs").text("Load more").appendTo(container).on("click", function() {
            var btn = $(this);
            if(!loading) {
                loading = true;
                btn.html(" Loading...").addClass("disabled");
                fetchActions(lastID, modOnly, limit, function(data, lastID) {
                    if(!data) {
                        loading = false;
                        return alert("Couldn't load more actions.")
                    }
                    btn.remove();
                    addToContainerForResponse(container, data, lastID, modOnly, limit, allowsShowMore);
                })
            }
        })
    }
}

function loadRecentActionsIntoContainer(container, limit = null, modOnly = false, allowsShowMore = true) {
    container.html(" Loading...");
    fetchActions(null, modOnly, limit, function(data, lastID) {
        if(!data) return $(container).text("Couldn't load mod actions");
        container.html("");
        addToContainerForResponse(container, data, lastID, modOnly, limit, allowsShowMore);
    });
}<|endoftext|>