<commit_before>import Promise from 'bluebird';
import fs from 'fs';
import exec from './exec';
import Handlebars from 'handlebars';
import Pool from './pool.js';
import Registry from './registry';
import * as User from './helper/user';
import convert from './helper/convert';
import * as PHP from './helper/php';
import * as Task from './task';

const readFile  = Promise.promisify(fs.readFile);

const createVhostFolder = async (path, user) => {
    await exec('mkdir -p {{path}}', { path });
    await exec('mkdir -p {{path}}', { path: path + '/temp' });
    await exec('mkdir -p {{path}}', { path: path + '/logs' });
    await exec('mkdir -p {{path}}', { path: path + '/sessions' });
    await exec('mkdir -p {{path}}', { path: path + '/web' });
    await exec('chown -R {{user}}:{{user}} {{path}}', { path, user });
};

const removeVhostFolder = async (path) => {
    await exec('rm -fr {{path}}', { path });
};

const addPool = async (host) => {
    await (new Pool(host)).create();
};

const removePool = async (host) => {
    await (new Pool(host)).remove();
};

// load and compile vhost template
const loadTemplate = readFile(__dirname + '/templates/vhost.hbs', 'utf-8')
    .then(function(template) {
        return Handlebars.compile(template);
    });

class Host {
    constructor(client, name) {
        this.client = client;
        this.name = name;
        this.db = Registry.get('Database');
    }

    async info() {
        let result = await this.db
            .table('host')
            .first('*')
            .where({
                host: this.name,
                client: this.client.name
            })
            .limit(1);
        return result;
    }

    async exists() {
        return !! await this.info();
    }

    async create({ php } = {}) {
        if (await this.exists()) {
            return;
        }

        // get php version to use
        if (php) {
            if (!await PHP.available(php)) {
                throw new Error(`PHP version ${php} is not available`);
            }
        } else {
            php = await PHP.latest();
        }

        // find free username and collect data for database
        const user = await User.free(this.name);
        const hostFolder = convert(this.name, '-a-z0-9_\.');
        const clientInfo = await this.client.info();
        const home = `${clientInfo.path}/${hostFolder}`;

        // insert into database
        await this.db
            .table('host')
            .insert({
                host: this.name,
                client: this.client.name,
                user: user,
                path: home,
                php
            });

        // create user
        await User.create(user, home);

        // create host file
        await this.updateHost();

        // create vhost folder
        await createVhostFolder(home, user);
        await Task.run('apache.vhost.enable', {
            hostname: this.name
        });

        // create fpm pool
        await addPool(this);

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');
    }

    async updateHost() {
        const [ info, template ] = await Promise.all([
            this.info(),
            loadTemplate
        ]);

        const documentRoot = `${info.path}/web`;
        const logsFolder = `${info.path}/logs`;
        let data = template(Object.assign(this, {
            port: 80,
            user: info.user,
            documentRoot,
            logsFolder,
            alias: info.alias? info.alias.split(',') : null
        }));
        await Task.run('apache.vhost.create', {
            hostname: this.name,
            data
        });
    }

    async remove() {
        const info = await this.info();
        if (!info) {
            return;
        }

        await Task.run('apache.vhost.disable', {
            hostname: this.name
        });

        await Promise.all([
            Task.run('apache.vhost.remove', {
                hostname: this.name
            }),
            removePool(this),
            removeVhostFolder(info.path)
        ]);
        User.remove(info.user, `/var/www/backup/${info.user}`);

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');

        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .delete();
    }

    async createAlias(alias) {
        let info = await this.info();
        var currentAlias = info.alias? info.alias.split(',') : [];
        if (currentAlias.indexOf(alias) > -1) {
            return;
        }
        currentAlias.push(alias);
        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .update({
                alias: currentAlias.join(',')
            });
        await this.updateHost();

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');
    }

    async removeAlias(alias) {
        let info = await this.info();
        var currentAlias = info.alias? info.alias.split(',') : [];
        var index = currentAlias.indexOf(alias);
        if (index < 0) {
            return;
        }
        currentAlias.splice(index, 1);
        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .update({
                alias: currentAlias.join(',')
            });
        await this.updateHost();

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');
    }

    async php(php) {
        if (await !this.exists()) {
            throw new Error(`Host "${this.name}" does not exists`);
        }

        // get php version to use
        if (php) {
            if (!await PHP.available(php)) {
                throw new Error(`PHP version ${php} is not available`);
            }
        } else {
            php = await PHP.latest();
        }

        // update database
        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .update({ php });

        await addPool(this);
    }
}

Host.all = async () => {
    const db = Registry.get('Database');
    let result = await db
        .table('host')
        .select('*')
        .orderBy('host');
    return result;
};

Host.allByClient = async (client) => {
    const db = Registry.get('Database');
    let result = await db
        .table('host')
        .select('*')
        .where({
            client: client.name
        })
        .orderBy('host');
    return result;
};

export default Host;
<commit_msg>fix switch php when host does not exist<commit_after>import Promise from 'bluebird';
import fs from 'fs';
import exec from './exec';
import Handlebars from 'handlebars';
import Pool from './pool.js';
import Registry from './registry';
import * as User from './helper/user';
import convert from './helper/convert';
import * as PHP from './helper/php';
import * as Task from './task';

const readFile  = Promise.promisify(fs.readFile);

const createVhostFolder = async (path, user) => {
    await exec('mkdir -p {{path}}', { path });
    await exec('mkdir -p {{path}}', { path: path + '/temp' });
    await exec('mkdir -p {{path}}', { path: path + '/logs' });
    await exec('mkdir -p {{path}}', { path: path + '/sessions' });
    await exec('mkdir -p {{path}}', { path: path + '/web' });
    await exec('chown -R {{user}}:{{user}} {{path}}', { path, user });
};

const removeVhostFolder = async (path) => {
    await exec('rm -fr {{path}}', { path });
};

const addPool = async (host) => {
    await (new Pool(host)).create();
};

const removePool = async (host) => {
    await (new Pool(host)).remove();
};

// load and compile vhost template
const loadTemplate = readFile(__dirname + '/templates/vhost.hbs', 'utf-8')
    .then(function(template) {
        return Handlebars.compile(template);
    });

class Host {
    constructor(client, name) {
        this.client = client;
        this.name = name;
        this.db = Registry.get('Database');
    }

    async info() {
        let result = await this.db
            .table('host')
            .first('*')
            .where({
                host: this.name,
                client: this.client.name
            })
            .limit(1);
        return result;
    }

    async exists() {
        return !! await this.info();
    }

    async create({ php } = {}) {
        if (await this.exists()) {
            return;
        }

        // get php version to use
        if (php) {
            if (!await PHP.available(php)) {
                throw new Error(`PHP version ${php} is not available`);
            }
        } else {
            php = await PHP.latest();
        }

        // find free username and collect data for database
        const user = await User.free(this.name);
        const hostFolder = convert(this.name, '-a-z0-9_\.');
        const clientInfo = await this.client.info();
        const home = `${clientInfo.path}/${hostFolder}`;

        // insert into database
        await this.db
            .table('host')
            .insert({
                host: this.name,
                client: this.client.name,
                user: user,
                path: home,
                php
            });

        // create user
        await User.create(user, home);

        // create host file
        await this.updateHost();

        // create vhost folder
        await createVhostFolder(home, user);
        await Task.run('apache.vhost.enable', {
            hostname: this.name
        });

        // create fpm pool
        await addPool(this);

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');
    }

    async updateHost() {
        const [ info, template ] = await Promise.all([
            this.info(),
            loadTemplate
        ]);

        const documentRoot = `${info.path}/web`;
        const logsFolder = `${info.path}/logs`;
        let data = template(Object.assign(this, {
            port: 80,
            user: info.user,
            documentRoot,
            logsFolder,
            alias: info.alias? info.alias.split(',') : null
        }));
        await Task.run('apache.vhost.create', {
            hostname: this.name,
            data
        });
    }

    async remove() {
        const info = await this.info();
        if (!info) {
            return;
        }

        await Task.run('apache.vhost.disable', {
            hostname: this.name
        });

        await Promise.all([
            Task.run('apache.vhost.remove', {
                hostname: this.name
            }),
            removePool(this),
            removeVhostFolder(info.path)
        ]);
        User.remove(info.user, `/var/www/backup/${info.user}`);

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');

        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .delete();
    }

    async createAlias(alias) {
        let info = await this.info();
        var currentAlias = info.alias? info.alias.split(',') : [];
        if (currentAlias.indexOf(alias) > -1) {
            return;
        }
        currentAlias.push(alias);
        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .update({
                alias: currentAlias.join(',')
            });
        await this.updateHost();

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');
    }

    async removeAlias(alias) {
        let info = await this.info();
        var currentAlias = info.alias? info.alias.split(',') : [];
        var index = currentAlias.indexOf(alias);
        if (index < 0) {
            return;
        }
        currentAlias.splice(index, 1);
        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .update({
                alias: currentAlias.join(',')
            });
        await this.updateHost();

        // reload apache
        await Task.run('apache.configtest');
        await Task.run('apache.reload');
    }

    async php(php) {
        if (!(await this.exists())) {
            throw new Error(`Host "${this.name}" does not exists`);
        }

        // get php version to use
        if (php) {
            if (!await PHP.available(php)) {
                throw new Error(`PHP version ${php} is not available`);
            }
        } else {
            php = await PHP.latest();
        }

        // update database
        await this.db
            .table('host')
            .where({
                client: this.client.name,
                host: this.name
            })
            .update({ php });

        await addPool(this);
    }
}

Host.all = async () => {
    const db = Registry.get('Database');
    let result = await db
        .table('host')
        .select('*')
        .orderBy('host');
    return result;
};

Host.allByClient = async (client) => {
    const db = Registry.get('Database');
    let result = await db
        .table('host')
        .select('*')
        .where({
            client: client.name
        })
        .orderBy('host');
    return result;
};

export default Host;
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var _ = require('underscore');
var reportWriter = require(root_path + '/controllers/fetching/report-writer');
var botFactory = require(root_path + '/controllers/fetching/bot-factory');
var botMaster = require(root_path + '/controllers/fetching/bot-master');
var Report = require(root_path + '/models/report');
var Source = require(root_path + '/models/source');

describe('Report writer', function() {

  describe('base functions', function() {
    beforeEach(function(done) {
      bot = botFactory.create({sourceType: 'dummy', keywords: 'Lorem ipsum'});
      bot.start();
      done();
    });

    it('should fetch reports from available bots', function(done) {
      bot.once('reports', function() {
        var report_data = reportWriter.fetch(this);
        expect(report_data).to.have.property('content');
        expect(report_data.content).to.contain('Lorem ipsum');
        done();
      });
    });

    it('should write reports to database', function(done) {
      bot.once('reports', function() {
        var report_data = reportWriter.fetch(this);
        reportWriter.write(report_data, function(err, report) {
          if (err) return done(err);
          expect(report).to.have.property('_id');
          Report.findById(report._id, function(err, found) {
            if (err) return done(err);
            expect(found).to.be.an.instanceof(Report);
            expect(found).to.have.property('_id');
            expect(found._id.toString()).to.equal(report._id.toString());
            done();
          });
        });
      });
    });
  });

  describe('bot processing function', function() {
    before(function(done) {
      bot = botFactory.create({sourceType: 'twitter', keywords: 'http'});
      bot.start();
      // Stream data for ~1.5 seconds, then stop
      setTimeout(function() {
        bot.stop();
        done();
      }, 1500);
    });

    it('should process all queued reports from a single bot', function(done) {
      expect(bot.isEmpty()).to.be.false;
      reportWriter.processBot(bot, function(err) {
        if (err) return done(err);
        expect(bot.isEmpty()).to.be.true;
        Report.find(function(err, reports) {
          if (err) return done(err);
          expect(reports).to.be.an.instanceof(Array);
          expect(reports).to.not.be.empty;
          reports = _.filter(reports, function(report) {
            return report.content && report.content.indexOf('http') > -1;
          });
          expect(reports).to.not.be.empty;
          done();
        });
      });
    });
  });

  describe('master processing function', function() {
    before(function(done) {
      botMaster.kill();

      // Mark report writer as busy so that we can manually control processing
      reportWriter.busy = true;

      // Create sources for the most common words in English
      Source.create({type: 'twitter', keywords: 'the'});
      Source.create({type: 'twitter', keywords: 'be'});
      Source.create({type: 'twitter', keywords: 'to'});

      // Queue starting bots after sources are loaded
      process.nextTick(function() {
        botMaster.start();
        done();
      });
    });

    // Stream data for ~4 seconds
    before(function(done) {
      this.timeout(5000);
      setTimeout(function() {
        botMaster.stop();
        done();
      }, 4000);
    });

    it('should process all queued reports from all bots', function(done) {
      // Verify that at there are queued reports
      var haveData = _.any(botMaster.bots, function(bot) {
        return !bot.isEmpty();
      });
      expect(haveData).to.be.true;
      // Mark report writer as no longer busy
      reportWriter.busy = false;
      // Process all queued data
      reportWriter.process(function() {
        var haveData = _.any(botMaster.bots, function(bot) {
          return !bot.isEmpty();
        });
        expect(haveData).to.be.false;
        done();
      });
    });
  });

});
<commit_msg>Verify that same number of queued reports were written to the database.<commit_after>var expect = require('chai').expect;
var _ = require('underscore');
var reportWriter = require(root_path + '/controllers/fetching/report-writer');
var botFactory = require(root_path + '/controllers/fetching/bot-factory');
var botMaster = require(root_path + '/controllers/fetching/bot-master');
var Report = require(root_path + '/models/report');
var Source = require(root_path + '/models/source');

describe('Report writer', function() {

  describe('base functions', function() {
    beforeEach(function(done) {
      bot = botFactory.create({sourceType: 'dummy', keywords: 'Lorem ipsum'});
      bot.start();
      done();
    });

    it('should fetch reports from available bots', function(done) {
      bot.once('reports', function() {
        var report_data = reportWriter.fetch(this);
        expect(report_data).to.have.property('content');
        expect(report_data.content).to.contain('Lorem ipsum');
        done();
      });
    });

    it('should write reports to database', function(done) {
      bot.once('reports', function() {
        var report_data = reportWriter.fetch(this);
        reportWriter.write(report_data, function(err, report) {
          if (err) return done(err);
          expect(report).to.have.property('_id');
          Report.findById(report._id, function(err, found) {
            if (err) return done(err);
            expect(found).to.be.an.instanceof(Report);
            expect(found).to.have.property('_id');
            expect(found._id.toString()).to.equal(report._id.toString());
            done();
          });
        });
      });
    });
  });

  describe('bot processing function', function() {
    before(function(done) {
      bot = botFactory.create({sourceType: 'twitter', keywords: 'http'});
      bot.start();
      // Stream data for ~1.5 seconds, then stop
      setTimeout(function() {
        bot.stop();
        done();
      }, 1500);
    });

    it('should process all queued reports from a single bot', function(done) {
      expect(bot.isEmpty()).to.be.false;
      reportWriter.processBot(bot, function(err) {
        if (err) return done(err);
        expect(bot.isEmpty()).to.be.true;
        Report.find(function(err, reports) {
          if (err) return done(err);
          expect(reports).to.be.an.instanceof(Array);
          expect(reports).to.not.be.empty;
          reports = _.filter(reports, function(report) {
            return report.content && report.content.indexOf('http') > -1;
          });
          expect(reports).to.not.be.empty;
          done();
        });
      });
    });
  });

  describe('master processing function', function() {
    before(function(done) {
      botMaster.kill();

      // Mark report writer as busy so that we can manually control processing
      reportWriter.busy = true;

      // Create sources for the most common words in English
      Source.create({type: 'twitter', keywords: 'the'});
      Source.create({type: 'twitter', keywords: 'be'});
      Source.create({type: 'twitter', keywords: 'to'});

      // Queue starting bots after sources are loaded
      process.nextTick(function() {
        botMaster.start();
        done();
      });
    });

    // Stream data for ~4 seconds
    before(function(done) {
      this.timeout(5000);
      setTimeout(function() {
        botMaster.stop();
        done();
      }, 4000);
    });

    // Count queued and database data
    before(function(done) {
       // Verify that at there are queued reports
      queueCount = _.reduce(botMaster.bots, function(count, bot) {
        return count + bot.queue.count;
      }, 0);

      // Verify number of reports in database
      reportCount = 0;
      Report.find(function(err, reports) {
        reportCount = reports.length;
        done();
      });
    });

    it('should process all queued reports from all bots', function(done) {
     expect(queueCount).to.be.greaterThan(0);
      // Mark report writer as no longer busy
      reportWriter.busy = false;
      // Process all queued data
      reportWriter.process(function() {
        // Verify that bots are all empty
        var haveData = _.any(botMaster.bots, function(bot) {
          return !bot.isEmpty();
        });
        expect(haveData).to.be.false;

        // Verify that reports were inserted into database
        Report.find(function(err, reports) {
          expect(reports.length).to.equal(queueCount + reportCount);
          done();
        });
      });
    });
  });

});
<|endoftext|>


<commit_before>$(document).ready(function() {
  var weeklyhours = "https://api3.libcal.com/api_hours_grid.php?iid=1176&format=json&weeks=1&callback=?";
  var fourweeks = "https://api3.libcal.com/api_hours_grid.php?iid=1176&format=json&weeks=4&callback=?";

  //read in JSON from libcal
  $.getJSON(fourweeks, function(data) {

    //declare variable inside callback function to store all the HTML   //that we want to output as our table of hours.
    var myHTML = '

Day	Date	Open	Close
';

    //for each array of location objects...

    $.each(data.locations, function(index, location_object) {
      //console.log("location_object " + index);
      //console.log("location_object.name " + location_object.name);

      //location_object.weeks contains an array of week_objects
      //loop through each one
      $.each(location_object.weeks, function(index, week_object) {
        //console.log("week " + index);
        //console.log("week " + week_object)

        //week_objects have sets of properties for each day in the form of day objects
        $.each(week_object, function(day, day_object) {
          //console.log(day);

          //add additional class on the day the library is open (the current day)
          var open = day_object.times.currently_open;
          if (open){
                myHTML += '
';
              }
          else {
            myHTML += '
'
          }
          myHTML += '' + day + "	" + day_object.date + "	";
          //console.log("currently open "+ day_object.times.currently_open);
          //console.log("date " + day_object.date);
          //day objects have properties we care about
          $.each(day_object.times.hours, function(index, value) {
            // console.log("set of hours " + index)
            // console.log("from " + value.from);
            //console.log("to " + value.to);
            if (index > 0) {
              myHTML += "
		";
            }
            myHTML += "" + value.from + "	" + value.to + "
";
          });

        });
      });
 myHTML += "
";
    });
    $('#week').html(myHTML);

  });

});<commit_msg>update hours-grid.js<commit_after>$(document).ready(function() {
  var weeklyhours = "https://api3.libcal.com/api_hours_grid.php?iid=1176&format=json&weeks=1&callback=?";

  //read in JSON from libcal
  $.getJSON(weeklyhours, function(data) {

    //declare variable inside callback function to store all the HTML   //that we want to output as our table of hours.
    var myHTML = '

Day	Date	Open	Close
';

    //for each array of location objects...

    $.each(data.locations, function(index, location_object) {
      //console.log("location_object " + index);
      //console.log("location_object.name " + location_object.name);

      //location_object.weeks contains an array of week_objects
      //loop through each one
      $.each(location_object.weeks, function(index, week_object) {
        //console.log("week " + index);
        //console.log("week " + week_object)

        //week_objects have sets of properties for each day in the form of day objects
        $.each(week_object, function(day, day_object) {
          //console.log(day);

          //add additional class on the day the library is open (the current day)
          var open = day_object.times.currently_open;
          if (open){
                myHTML += '
';
              }
          else {
            myHTML += '
';
          }
          myHTML += '' + day + "	" + day_object.date + "	";
          //console.log("currently open "+ day_object.times.currently_open);
          //console.log("date " + day_object.date);
          //day objects have properties we care about
          $.each(day_object.times.hours, function(index, value) {
            // console.log("set of hours " + index)
            // console.log("from " + value.from);
            //console.log("to " + value.to);
            if (index > 0) {
              myHTML += "
		";
            }
            myHTML += "" + value.from + "	" + value.to + "
";
          });

        });
      });
 myHTML += "
";
    });
    $('#week').html(myHTML);

  });

});<|endoftext|>


<commit_before>"use strict";

jsns.define("hr.http", ["hr.eventhandler"],
function (exports, module, EventHandler) {

    var customizeRequestEvent = new EventHandler();
    exports.customizeRequest = customizeRequestEvent.modifier;

    var customizePromiseEvent = new EventHandler();
    exports.customizePromise = customizePromiseEvent.modifier;

    function extractData(xhr) {
        var data;
        var contentType = xhr.getResponseHeader('content-type');
        if (contentType && contentType.search(/application\/json/) !== -1) {
            try {
                data = JSON.parse(xhr.response);
            }
            catch (err) {
                data = xhr.response;
            }
        }
        else {
            data = xhr.response;
        }
        return data;
    }

    //Helper function to handle results
    function handleResult(xhr, success, fail) {
        if (xhr.status === 200) {
            if (success !== undefined) {
                success(extractData(xhr));
            }
        }
        else {
            if (fail !== undefined) {
                fail(extractData(xhr));
            }
        }
    }

    /**
     * Post data to a url. Returns a promise to get the result.
     * @param {string} url - The url to post to
     * @param {object} data - The data to post
     */
    function post(url, data) {
        return ajax(url, 'POST', data);
    }
    exports.post = post;

    /**
     * Put data to a url. Returns a promise with the result.
     * @param {string} url - The url to put to
     * @param {object} data - The data to put
     */
    function put(url, data, success, fail) {
        return ajax(url, 'PUT', data);
    }
    exports.put = put;

    /**
     * Delete data at a url. Returns a promise with the result.
     * @param {string} url - The url to delete to
     * @param {object} data - Data to include
     */
    function del(url, data, success, fail) {
        ajax(url, 'DELETE', data);
    }
    exports.delete = del;

    /**
     * Get data from a url. Returns a promise with the result.
     * @param {string} url - The url to get data from
     * @param {type} [cache=false] - True to use cached results, false to always get, default false.
     */
    function get(url, cache) {
        if (cache === undefined || cache === false) {
            if (url.indexOf('?') > -1) {
                url += '&';
            }
            else {
                url += '?';
            }
            url += 'noCache=' + new Date().getTime();
        }

        return setupXhr(url, 'GET', function () {
            return undefined;
        }, function () {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            return xhr;
        });
    }
    exports.get = get;

    /**
     * A more raw ajax call if needed.
     * @param {string} url - The url to call
     * @param {string} method - The method to use
     * @param {object} data - The data to send
     */
    function ajax(url, method, data) {
        return setupXhr(url, method, function () {
            return JSON.stringify(data);
        }, function () {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.setRequestHeader('Content-Type', 'application/json');
            return xhr;
        });
    }
    exports.ajax = ajax;

    /**
     * Upload a file to a url
     * @param {string} url - The url to upload to
     * @param {object|FormData} data - The data to upload, if this is already form data it will be used directly, otherwise
     * data will be sent directly as a file.
     */
    function upload(url, data) {
        return setupXhr(url, 'POST', function () {
            var formData = null;

            if (data instanceof FormData) {
                formData = data;
            }
            else {
                formData = new FormData();
                formData.append('file', data);
            }

            return formData;
        }, function () {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url);
            return xhr;
        });
    }
    exports.upload = upload;

    function setupXhr(url, method, dataBuilder, xhrBuilder) {
        //Customize requests and build up promise chain for any customizations
        var customPromises = customizePromiseEvent.fire(url, method);

        //Assemble final chain
        if (customPromises === undefined || customPromises.length === 0) {
            return buildRequestPromise(url, method, dataBuilder, xhrBuilder);
        }
        else {
            return Promise.all(customPromises)
                   .then(function (res) {
                       return buildRequestPromise(url, method, dataBuilder, xhrBuilder);
                   });
        }
    }

    function buildRequestPromise(url, method, dataBuilder, xhrBuilder) {
        //Build promise for request
        return new Promise(function (resolve, reject) {
            //Common xhr setup
            var xhr = xhrBuilder();
            xhr.withCredentials = true;
            customizeRequestEvent.fire(xhr, url, method);

            xhr.onload = function () {
                handleResult(xhr, resolve, reject);
            };

            var data = dataBuilder();

            if (data === undefined) {
                xhr.send();
            }
            else {
                xhr.send(data);
            }
        });
    }
});<commit_msg>Fixed status codes that are considered ok.<commit_after>"use strict";

jsns.define("hr.http", ["hr.eventhandler"],
function (exports, module, EventHandler) {

    var customizeRequestEvent = new EventHandler();
    exports.customizeRequest = customizeRequestEvent.modifier;

    var customizePromiseEvent = new EventHandler();
    exports.customizePromise = customizePromiseEvent.modifier;

    function extractData(xhr) {
        var data;
        var contentType = xhr.getResponseHeader('content-type');
        if (contentType && contentType.search(/application\/json/) !== -1) {
            try {
                data = JSON.parse(xhr.response);
            }
            catch (err) {
                data = xhr.response;
            }
        }
        else {
            data = xhr.response;
        }
        return data;
    }

    //Helper function to handle results
    function handleResult(xhr, success, fail) {
        if (xhr.status > 199 && xhr.status < 300) {
            if (success !== undefined) {
                success(extractData(xhr));
            }
        }
        else {
            if (fail !== undefined) {
                fail(extractData(xhr));
            }
        }
    }

    /**
     * Post data to a url. Returns a promise to get the result.
     * @param {string} url - The url to post to
     * @param {object} data - The data to post
     */
    function post(url, data) {
        return ajax(url, 'POST', data);
    }
    exports.post = post;

    /**
     * Put data to a url. Returns a promise with the result.
     * @param {string} url - The url to put to
     * @param {object} data - The data to put
     */
    function put(url, data, success, fail) {
        return ajax(url, 'PUT', data);
    }
    exports.put = put;

    /**
     * Delete data at a url. Returns a promise with the result.
     * @param {string} url - The url to delete to
     * @param {object} data - Data to include
     */
    function del(url, data, success, fail) {
        ajax(url, 'DELETE', data);
    }
    exports.delete = del;

    /**
     * Get data from a url. Returns a promise with the result.
     * @param {string} url - The url to get data from
     * @param {type} [cache=false] - True to use cached results, false to always get, default false.
     */
    function get(url, cache) {
        if (cache === undefined || cache === false) {
            if (url.indexOf('?') > -1) {
                url += '&';
            }
            else {
                url += '?';
            }
            url += 'noCache=' + new Date().getTime();
        }

        return setupXhr(url, 'GET', function () {
            return undefined;
        }, function () {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            return xhr;
        });
    }
    exports.get = get;

    /**
     * A more raw ajax call if needed.
     * @param {string} url - The url to call
     * @param {string} method - The method to use
     * @param {object} data - The data to send
     */
    function ajax(url, method, data) {
        return setupXhr(url, method, function () {
            return JSON.stringify(data);
        }, function () {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.setRequestHeader('Content-Type', 'application/json');
            return xhr;
        });
    }
    exports.ajax = ajax;

    /**
     * Upload a file to a url
     * @param {string} url - The url to upload to
     * @param {object|FormData} data - The data to upload, if this is already form data it will be used directly, otherwise
     * data will be sent directly as a file.
     */
    function upload(url, data) {
        return setupXhr(url, 'POST', function () {
            var formData = null;

            if (data instanceof FormData) {
                formData = data;
            }
            else {
                formData = new FormData();
                formData.append('file', data);
            }

            return formData;
        }, function () {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url);
            return xhr;
        });
    }
    exports.upload = upload;

    function setupXhr(url, method, dataBuilder, xhrBuilder) {
        //Customize requests and build up promise chain for any customizations
        var customPromises = customizePromiseEvent.fire(url, method);

        //Assemble final chain
        if (customPromises === undefined || customPromises.length === 0) {
            return buildRequestPromise(url, method, dataBuilder, xhrBuilder);
        }
        else {
            return Promise.all(customPromises)
                   .then(function (res) {
                       return buildRequestPromise(url, method, dataBuilder, xhrBuilder);
                   });
        }
    }

    function buildRequestPromise(url, method, dataBuilder, xhrBuilder) {
        //Build promise for request
        return new Promise(function (resolve, reject) {
            //Common xhr setup
            var xhr = xhrBuilder();
            xhr.withCredentials = true;
            customizeRequestEvent.fire(xhr, url, method);

            xhr.onload = function () {
                handleResult(xhr, resolve, reject);
            };

            var data = dataBuilder();

            if (data === undefined) {
                xhr.send();
            }
            else {
                xhr.send(data);
            }
        });
    }
});<|endoftext|>


<commit_before>import {
  assign,
  compact,
  find,
  times,
  last,
} from 'lodash';
import cached from './fields/cached';
import date from './fields/date';
import money, { amount } from './fields/money';
import numeral from './fields/numeral';
import gravity from '../lib/loaders/gravity';
import Artwork from './artwork';
import Sale, { auctionState } from './sale';
import {
  GraphQLObjectType,
  GraphQLString,
  GraphQLNonNull,
  GraphQLInt,
  GraphQLBoolean,
  GraphQLList,
} from 'graphql';

export const isBiddable = (sale, { artwork: { sold } }) => (
  !sold &&
  sale.sale_type === 'auction' &&
  auctionState(sale) === 'open'
);

const SaleArtworkType = new GraphQLObjectType({
  name: 'SaleArtwork',
  fields: () => {
    return {
      cached,
      _id: {
        type: GraphQLString,
      },
      id: {
        type: GraphQLString,
      },
      sale_id: {
        type: GraphQLString,
      },
      sale: {
        type: Sale.type,
        resolve: ({ sale, sale_id }) => {
          if (!!sale) return sale;
          return gravity(`sale/${sale_id}`);
        },
      },
      position: {
        type: GraphQLInt,
      },
      lot_number: {
        type: GraphQLString,
      },
      currency: {
        type: GraphQLString,
        description: 'Currency abbreviation (e.g. "USD")',
      },
      symbol: {
        type: GraphQLString,
        description: 'Currency symbol (e.g. "$")',
      },
      reserve_status: {
        type: GraphQLString,
      },
      is_with_reserve: {
        type: GraphQLBoolean,
        resolve: ({ reserve_status }) => reserve_status !== 'no_reserve',
      },
      is_bid_on: {
        type: GraphQLBoolean,
        resolve: ({ bidder_positions_count }) => bidder_positions_count !== 0,
      },
      is_biddable: {
        type: GraphQLBoolean,
        description: 'Can bids be placed on the artwork?',
        resolve: saleArtwork => {
          if (!!saleArtwork.sale) {
            return isBiddable(saleArtwork.sale, saleArtwork);
          }

          return gravity(`sale/${saleArtwork.sale_id}`)
            .then(sale => isBiddable(sale, saleArtwork));
        },
      },
      reserve_message: {
        type: GraphQLString,
        resolve: ({ bidder_positions_count, reserve_status }) => {
          if (reserve_status === 'reserve_met') {
            return 'Reserve met';
          } else if (bidder_positions_count === 0 && reserve_status === 'reserve_not_met') {
            return 'This work has a reserve';
          }
          return null;
        },
      },
      reserve: money({
        name: 'SaleArtworkReserve',
        resolve: ({ display_reserve_dollars, reserve_cents }) => ({
          cents: reserve_cents,
          display: display_reserve_dollars,
        }),
      }),
      low_estimate: money({
        name: 'SaleArtworkLowEstimate',
        resolve: ({ display_low_estimate_dollars, low_estimate_cents }) => ({
          cents: low_estimate_cents,
          display: display_low_estimate_dollars,
        }),
      }),
      high_estimate: money({
        name: 'SaleArtworkHighEstimate',
        resolve: ({ display_high_estimate_dollars, high_estimate_cents }) => ({
          cents: high_estimate_cents,
          display: display_high_estimate_dollars,
        }),
      }),
      opening_bid: money({
        name: 'SaleArtworkOpeningBid',
        resolve: ({ display_opening_bid_dollars, opening_bid_cents }) => ({
          cents: opening_bid_cents,
          display: display_opening_bid_dollars,
        }),
      }),
      minimum_next_bid: money({
        name: 'SaleArtworkMinimumNextBid',
        resolve: ({ display_minimum_next_bid_dollars, minimum_next_bid_cents }) => ({
          cents: minimum_next_bid_cents,
          display: display_minimum_next_bid_dollars,
        }),
      }),
      current_bid: money({
        name: 'SaleArtworkCurrentBid',
        resolve: saleArtwork => ({
          cents: saleArtwork.highest_bid_amount_cents || saleArtwork.opening_bid_cents,
          display: (
            saleArtwork.display_highest_bid_amount_dollars ||
            saleArtwork.display_opening_bid_dollars
          ),
        }),
      }),
      highest_bid: {
        type: new GraphQLObjectType({
          name: 'SaleArtworkHighestBid',
          fields: {
            id: {
              type: GraphQLString,
            },
            created_at: date,
            is_cancelled: {
              type: GraphQLBoolean,
              resolve: ({ cancelled }) => cancelled,
            },
            amount: amount(({ amount_cents }) => amount_cents),
            cents: {
              type: GraphQLInt,
              resolve: ({ amount_cents }) => amount_cents,
            },
            display: {
              type: GraphQLString,
              resolve: ({ display_amount_dollars }) => display_amount_dollars,
            },
            amount_cents: {
              type: GraphQLInt,
              deprecationReason: 'Favor `cents`',
            },
          },
        }),
        resolve: ({ symbol, highest_bid }) =>
          assign({ symbol }, highest_bid),
      },
      artwork: {
        type: Artwork.type,
        resolve: ({ artwork }) => artwork,
      },
      estimate: {
        type: GraphQLString,
        resolve: ({
          display_low_estimate_dollars,
          display_high_estimate_dollars,
          display_estimate_dollars,
        }) => {
          return compact([
            display_low_estimate_dollars,
            display_high_estimate_dollars,
          ]).join('–') || display_estimate_dollars;
        },
      },
      counts: {
        resolve: x => x,
        type: new GraphQLObjectType({
          name: 'SaleArtworkCounts',
          fields: {
            bidder_positions: numeral(({ bidder_positions_count }) =>
              bidder_positions_count),
          },
        }),
      },
      low_estimate_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `low_estimate`',
      },
      high_estimate_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `high_estimate',
      },
      opening_bid_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `opening_bid`',
      },
      minimum_next_bid_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `minimum_next_bid`',
      },
      bidder_positions_count: {
        type: GraphQLInt,
        deprecationReason: 'Favor `counts.bidder_positions`',
      },
      bid_increments: {
        type: new GraphQLList(GraphQLInt),
        resolve: ({ minimum_next_bid_cents }) => {
          return gravity('/increments').then((res) => {
            const deflt = find(res, { key: 'default' });
            const increments = [minimum_next_bid_cents];
            times(100, () => {
              const bid = last(increments);
              const bucket = find(deflt.increments, (inc) =>
                bid >= inc.from && bid <= inc.to
              ) || last(deflt.increments);
              const nextBid = bid + bucket.amount;
              if (!bucket.to) return increments.push(nextBid);
              const nextBidBucket = find(deflt.increments, (inc) =>
                nextBid >= inc.from && nextBid <= inc.to
              );
              if (!nextBidBucket) return increments.push(nextBid);
              if (nextBid === nextBidBucket.from) increments.push(nextBid);
              else increments.push(bid + nextBidBucket.amount);
            });
            return increments;
          });
        },
      },
    };
  },
});

const SaleArtwork = {
  type: SaleArtworkType,
  description: 'A Sale Artwork',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The slug or ID of the SaleArtwork',
    },
  },
  resolve: (root, { id }) => {
    return gravity(`sale_artwork/${id}`);
  },
};

export default SaleArtwork;
<commit_msg>increments using strategy<commit_after>import {
  assign,
  compact,
  find,
  times,
  last,
} from 'lodash';
import cached from './fields/cached';
import date from './fields/date';
import money, { amount } from './fields/money';
import numeral from './fields/numeral';
import gravity from '../lib/loaders/gravity';
import Artwork from './artwork';
import Sale, { auctionState } from './sale';
import {
  GraphQLObjectType,
  GraphQLString,
  GraphQLNonNull,
  GraphQLInt,
  GraphQLBoolean,
  GraphQLList,
} from 'graphql';

export const isBiddable = (sale, { artwork: { sold } }) => (
  !sold &&
  sale.sale_type === 'auction' &&
  auctionState(sale) === 'open'
);

const SaleArtworkType = new GraphQLObjectType({
  name: 'SaleArtwork',
  fields: () => {
    return {
      cached,
      _id: {
        type: GraphQLString,
      },
      id: {
        type: GraphQLString,
      },
      sale_id: {
        type: GraphQLString,
      },
      sale: {
        type: Sale.type,
        resolve: ({ sale, sale_id }) => {
          if (!!sale) return sale;
          return gravity(`sale/${sale_id}`);
        },
      },
      position: {
        type: GraphQLInt,
      },
      lot_number: {
        type: GraphQLString,
      },
      currency: {
        type: GraphQLString,
        description: 'Currency abbreviation (e.g. "USD")',
      },
      symbol: {
        type: GraphQLString,
        description: 'Currency symbol (e.g. "$")',
      },
      reserve_status: {
        type: GraphQLString,
      },
      is_with_reserve: {
        type: GraphQLBoolean,
        resolve: ({ reserve_status }) => reserve_status !== 'no_reserve',
      },
      is_bid_on: {
        type: GraphQLBoolean,
        resolve: ({ bidder_positions_count }) => bidder_positions_count !== 0,
      },
      is_biddable: {
        type: GraphQLBoolean,
        description: 'Can bids be placed on the artwork?',
        resolve: saleArtwork => {
          if (!!saleArtwork.sale) {
            return isBiddable(saleArtwork.sale, saleArtwork);
          }

          return gravity(`sale/${saleArtwork.sale_id}`)
            .then(sale => isBiddable(sale, saleArtwork));
        },
      },
      reserve_message: {
        type: GraphQLString,
        resolve: ({ bidder_positions_count, reserve_status }) => {
          if (reserve_status === 'reserve_met') {
            return 'Reserve met';
          } else if (bidder_positions_count === 0 && reserve_status === 'reserve_not_met') {
            return 'This work has a reserve';
          }
          return null;
        },
      },
      reserve: money({
        name: 'SaleArtworkReserve',
        resolve: ({ display_reserve_dollars, reserve_cents }) => ({
          cents: reserve_cents,
          display: display_reserve_dollars,
        }),
      }),
      low_estimate: money({
        name: 'SaleArtworkLowEstimate',
        resolve: ({ display_low_estimate_dollars, low_estimate_cents }) => ({
          cents: low_estimate_cents,
          display: display_low_estimate_dollars,
        }),
      }),
      high_estimate: money({
        name: 'SaleArtworkHighEstimate',
        resolve: ({ display_high_estimate_dollars, high_estimate_cents }) => ({
          cents: high_estimate_cents,
          display: display_high_estimate_dollars,
        }),
      }),
      opening_bid: money({
        name: 'SaleArtworkOpeningBid',
        resolve: ({ display_opening_bid_dollars, opening_bid_cents }) => ({
          cents: opening_bid_cents,
          display: display_opening_bid_dollars,
        }),
      }),
      minimum_next_bid: money({
        name: 'SaleArtworkMinimumNextBid',
        resolve: ({ display_minimum_next_bid_dollars, minimum_next_bid_cents }) => ({
          cents: minimum_next_bid_cents,
          display: display_minimum_next_bid_dollars,
        }),
      }),
      current_bid: money({
        name: 'SaleArtworkCurrentBid',
        resolve: saleArtwork => ({
          cents: saleArtwork.highest_bid_amount_cents || saleArtwork.opening_bid_cents,
          display: (
            saleArtwork.display_highest_bid_amount_dollars ||
            saleArtwork.display_opening_bid_dollars
          ),
        }),
      }),
      highest_bid: {
        type: new GraphQLObjectType({
          name: 'SaleArtworkHighestBid',
          fields: {
            id: {
              type: GraphQLString,
            },
            created_at: date,
            is_cancelled: {
              type: GraphQLBoolean,
              resolve: ({ cancelled }) => cancelled,
            },
            amount: amount(({ amount_cents }) => amount_cents),
            cents: {
              type: GraphQLInt,
              resolve: ({ amount_cents }) => amount_cents,
            },
            display: {
              type: GraphQLString,
              resolve: ({ display_amount_dollars }) => display_amount_dollars,
            },
            amount_cents: {
              type: GraphQLInt,
              deprecationReason: 'Favor `cents`',
            },
          },
        }),
        resolve: ({ symbol, highest_bid }) =>
          assign({ symbol }, highest_bid),
      },
      artwork: {
        type: Artwork.type,
        resolve: ({ artwork }) => artwork,
      },
      estimate: {
        type: GraphQLString,
        resolve: ({
          display_low_estimate_dollars,
          display_high_estimate_dollars,
          display_estimate_dollars,
        }) => {
          return compact([
            display_low_estimate_dollars,
            display_high_estimate_dollars,
          ]).join('–') || display_estimate_dollars;
        },
      },
      counts: {
        resolve: x => x,
        type: new GraphQLObjectType({
          name: 'SaleArtworkCounts',
          fields: {
            bidder_positions: numeral(({ bidder_positions_count }) =>
              bidder_positions_count),
          },
        }),
      },
      low_estimate_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `low_estimate`',
      },
      high_estimate_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `high_estimate',
      },
      opening_bid_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `opening_bid`',
      },
      minimum_next_bid_cents: {
        type: GraphQLInt,
        deprecationReason: 'Favor `minimum_next_bid`',
      },
      bidder_positions_count: {
        type: GraphQLInt,
        deprecationReason: 'Favor `counts.bidder_positions`',
      },
      bid_increments: {
        type: new GraphQLList(GraphQLInt),
        resolve: ({ minimum_next_bid_cents, sale_id }) => {
          return gravity(`sale/${sale_id}`).then((sale) => {
            return gravity('increments', {
              key: sale.increment_strategy
            }).then((incrs) => {
              const incr = incrs[0].increments;
              const increments = [minimum_next_bid_cents];
              times(100, () => {
                const bid = last(increments);
                const bucket = find(incr, (inc) =>
                  bid >= inc.from && bid <= inc.to
                ) || last(incr);
                const nextBid = bid + bucket.amount;
                if (!bucket.to) return increments.push(nextBid);
                const nextBidBucket = find(incr, (inc) =>
                  nextBid >= inc.from && nextBid <= inc.to
                );
                if (!nextBidBucket) return increments.push(nextBid);
                if (nextBid === nextBidBucket.from) increments.push(nextBid);
                else increments.push(bid + nextBidBucket.amount);
              });
              return increments;
            });
          });
        },
      },
    };
  },
});

const SaleArtwork = {
  type: SaleArtworkType,
  description: 'A Sale Artwork',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The slug or ID of the SaleArtwork',
    },
  },
  resolve: (root, { id }) => {
    return gravity(`sale_artwork/${id}`);
  },
};

export default SaleArtwork;
<|endoftext|>


<commit_before>var Waterline = require('../../lib/waterline'),
    assert = require('assert');

describe('Waterline Collection', function() {
  var User, status = 0;

  before(function(done) {

    var adapter_1 = {
      identity: 'foo',
      registerConnection: function(connection, collections, cb) {
        status++;
        cb();
      }
    };

    var adapter_2 = {
      identity: 'bar',
      registerConnection: function(connection, collections, cb) {
        status++;
        cb();
      }
    };

    var Model = Waterline.Collection.extend({
      attributes: {},
      connection: ['my_foo', 'my_bar'],
      tableName: 'tests'
    });

    var waterline = new Waterline();
    waterline.loadCollection(Model);

    var connections = {
      'my_foo': {
        adapter: 'foo'
      },
      'my_bar': {
        adapter: 'bar'
      }
    };

    waterline.initialize({ adapters: { 'foo': adapter_1, 'bar': adapter_2 }, connections: connections }, function(err, colls) {
      if(err) return done(err);
      User = colls.collections.tests;
      done();
    });
  });

  describe('multiple adapters', function() {

    it('should call registerCollection on all adapters', function() {
      assert(status == 2);
    });

  });
});
<commit_msg>improve multi-adapter tests<commit_after>var Waterline = require('../../lib/waterline');
var assert = require('assert');
var _ = require('lodash');

describe('Waterline Collection', function() {
  var User;
  var status = 0;
  var adapter_1 = {
    identity: 'foo',
    registerConnection: function(connection, collections, cb) {
      status++;
      cb();
    },
    baseMethod: function () {
      return 'base foo';
    }
  };

  var adapter_2 = {
    identity: 'bar',
    registerConnection: function(connection, collections, cb) {
      status++;
      cb();
    },
    baseMethod: function () {
      return 'base bar';
    },
    customMethod: function () {
      return 'custom bar'
    }
  };
  var Model = Waterline.Collection.extend({
    attributes: {},
    connection: ['my_foo', 'my_bar'],
    tableName: 'tests'
  });

  before(function(done) {
    var waterline = new Waterline();
    waterline.loadCollection(Model);

    var connections = {
      'my_foo': {
        adapter: 'foo'
      },
      'my_bar': {
        adapter: 'bar'
      }
    };

    waterline.initialize({
        adapters: {
          'foo': adapter_1,
          'bar': adapter_2
        },
        connections: connections
      },
      function(err, colls) {
        if (err) return done(err);
        User = colls.collections.tests;
        done();
      }
    );
  });

  describe('multiple adapters', function() {

    it('should call registerCollection on all adapters', function() {
      assert.equal(status, 2);
    });

    it('should expose an adapter\'s custom methods', function () {
      assert(_.isFunction(User.customMethod));
      assert.equal(User.customMethod(), 'custom bar');
    });

    it('should give precedence to adapters earlier in the list', function () {
      assert(_.isFunction(User.baseMethod));
      assert.equal(User.baseMethod(), 'base foo');
    });

  });
});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import s from './theme.css';

const factory = (baseType, type, defaultElement) => {
  class Text extends PureComponent {
    static propTypes = {
      children: PropTypes.node,
      className: PropTypes.string,
      color: PropTypes.oneOf(['white', 'neutral', 'mint', 'teal', 'violet', 'ruby', 'gold', 'aqua']),
      element: PropTypes.node,
      soft: PropTypes.bool,
    };

    static defaultProps = {
      element: null,
      soft: false,
    };

    isSoft(color) {
      if (color !== 'white') {
        return false;
      }

      return this.props.soft;
    }

    render() {
      const { children, className, color, element } = this.props;

      const isSoft = this.isSoft(color);

      const classNames = cx(
        s[baseType],
        s[type],
        s[color],
        {
          [s['soft']]: isSoft,
        },
        className,
      );

      const Element = element || defaultElement;

      return (
        <Element data-teamleader-ui={baseType} className={classNames}>
          {children}
        </Element>
      );
    }
  }

  return Text;
};

export { factory as textFactory };
<commit_msg>Converted Text component to use our new Box component<commit_after>import React, { PureComponent } from 'react';
import Box from '../box';
import PropTypes from 'prop-types';
import cx from 'classnames';
import s from './theme.css';

const factory = (baseType, type, defaultElement) => {
  class Text extends PureComponent {
    static propTypes = {
      children: PropTypes.node,
      className: PropTypes.string,
      color: PropTypes.oneOf(['white', 'neutral', 'mint', 'teal', 'violet', 'ruby', 'gold', 'aqua']),
      element: PropTypes.node,
      soft: PropTypes.bool,
    };

    static defaultProps = {
      element: null,
      soft: false,
    };

    isSoft(color) {
      if (color !== 'white') {
        return false;
      }

      return this.props.soft;
    }

    render() {
      const { children, className, color, element, ...props } = this.props;

      const isSoft = this.isSoft(color);

      const classNames = cx(
        s[baseType],
        s[type],
        s[color],
        {
          [s['soft']]: isSoft,
        },
        className,
      );

      const Element = element || defaultElement;

      return (
        <Box className={classNames} data-teamleader-ui={baseType} element={Element} {...props}>
          {children}
        </Box>
      );
    }
  }

  return Text;
};

export { factory as textFactory };
<|endoftext|>


<commit_before>"use strict";

  var WAT;
  var buildForWindows, buildForWindowsPhone;
  var createHeaderElement, createStageElement, moveWebView, createWebViewForModalDialog, createTransitionOverlay;

  var self = {
      init: function (WATRef) {
          if (!WAT) {
              WAT = WATRef;

              // add base stylesheet
              var base = document.createElement("link");
              base.setAttribute("rel", "stylesheet");
              base.setAttribute("type", "text/css");
              base.href = "css/base.css";
              document.head.appendChild(base);

              if (WAT.environment.isWindows) {
                  // build wrapper html for windows
                  var content = document.createElement("div");
                  content.id = "content";
                  content.classList.add("content");
                  content.classList.add("customColor");
                  document.body.appendChild(content);
                  WAT.components.content = content;

                  buildForWindows();
              }
              else {
                  // build wrapper html for windows phone
                  buildForWindowsPhone();
              }

              // hide cordova app div
              document.getElementsByClassName("app")[0].style.display = "none";

              // remove cordova's stylesheet
              var cordovaStyles = document.getElementsByTagName("link")[0];
              cordovaStyles.parentNode.removeChild(cordovaStyles);

              // add base wrapper styles
              var styles = document.createElement("link");
              styles.setAttribute("rel", "stylesheet");
              styles.setAttribute("type", "text/css");
              styles.href = "css/wrapper-styles.css";
              document.head.appendChild(styles);

              createTransitionOverlay();
          }
      }
  };

  buildForWindows = function () {
      createHeaderElement();
      createStageElement();
      createWebViewForModalDialog(document.body);
      moveWebView();
  };

  buildForWindowsPhone = function () {
      // add theme styles for Windows Phone
      var theme = document.createElement("link");
      theme.setAttribute("rel", "stylesheet");
      theme.setAttribute("type", "text/css");
      theme.href = "css/ui-themed.theme-dark.css";
      document.head.appendChild(theme);

      // add wrapper styles for windows phone
      var linkElem = document.createElement("link");
      linkElem.setAttribute("rel", "stylesheet");
      linkElem.setAttribute("type", "text/css");
      linkElem.href = "css/wrapper-phone.css";
      document.head.appendChild(linkElem);

      // viewport parent div
      var viewport = document.createElement("div");
      viewport.id = "viewport";
      viewport.classList.add("viewport");

      // surface div
      var surface = document.createElement("div");
      surface.id = "surface";
      surface.classList.add("surface");
      surface.style.zIndex = WAT.components.webView.zIndex + 100;

      // nav drawer div
      var navDrawer = document.createElement("div");
      navDrawer.id = "navDrawer";
      navDrawer.classList.add("navDrawer");

      // search box
      var searchBox = document.createElement("input");
      searchBox.type = "text";
      searchBox.name = "search-box";
      searchBox.id = "search-box";
      searchBox.classList.add("search-box");

      // TODO: enable search box when wat_search is implemented.
      searchBox.style.display = "none";

      navDrawer.appendChild(searchBox);
      WAT.components.navDrawer = navDrawer;

      // navdrawer list view
      var listview = document.createElement("div");
      listview.id = "navDrawerListView";
      listview.classList.add("win-selectionstylefilled");

      navDrawer.appendChild(listview);

      surface.appendChild(navDrawer);

      // up a level
      var content = document.createElement("div");
      content.id = "content";
      content.classList.add("content");
      document.body.appendChild(content);
      WAT.components.content = content;

      createStageElement();

      surface.appendChild(content);

      viewport.appendChild(surface);
      document.body.appendChild(viewport);

      createHeaderElement();
      createWebViewForModalDialog(WAT.components.stage);

      moveWebView();
  };

  // Windows Wrapper HTML functions
  createHeaderElement = function () {
      // header div
      var header = document.createElement("div");
      header.id = "header";
      header.classList.add("header");
      header.style.zIndex = WAT.components.webView.style.zIndex + 100;

      if (!WAT.environment.isWindows) {
          // hamburger
          var hamburger = document.createElement("div");
          hamburger.id = "hamburger";
          hamburger.classList.add("hamburger");
          header.appendChild(hamburger);
      }

      // logo div
      var logoArea = document.createElement("div");
      logoArea.classList.add("logoarea");

      // logo img
      var logoImage = document.createElement("img");
      logoImage.id = "logo";
      logoArea.appendChild(logoImage);
      header.appendChild(logoArea);

      // title
      var title = document.createElement("h1");
      title.id = "title";
      title.classList.add("titlearea");
      title.classList.add("win-type-ellipsis");
      header.appendChild(title);

      // search box
      var searchbox = document.createElement("div");
      searchbox.id = "search-box";
      searchbox.classList.add("search-box");

      // TODO: enable search box when wat_search is implemented.
      searchbox.style.display = "none";

      header.appendChild(searchbox);

      WAT.components.content.appendChild(header);

      WAT.components.header = header;
      WAT.components.logo = logoImage;
      WAT.components.title = title;
  }

  createStageElement = function () {
      var stage = document.createElement("div");
      stage.id = "stage";
      stage.classList.add("stage");
      WAT.components.stage = stage;
      WAT.components.content.appendChild(stage);
  };

  moveWebView = function () {
      var webView = WAT.components.webView;
      webView.id = "main-view";
      WAT.components.stage.appendChild(webView);
  };

  createWebViewForModalDialog = function (appendToElement) {
       var modalStage = document.createElement("div");
       modalStage.id = "modal-stage";
       modalStage.classList.add("stage");
       modalStage.classList.add("overlay-stage");
       modalStage.style.zIndex = WAT.components.webView.style.zIndex + 100;

       var webView = document.createElement("x-ms-webview");
       webView.id = "dialog-view";
       webView.classList.add("modal-content");

       var button = document.createElement("button");
       button.id = "close";
       button.classList.add("win-closebutton");
       button.innerText = "X";

       modalStage.appendChild(webView);
       modalStage.appendChild(button);
       appendToElement.appendChild(modalStage);

       WAT.components.dialogView = webView;
       WAT.components.closeButton = button;
  };

  createTransitionOverlay = function () {
      var overlay = document.createElement("div");
      overlay.classList.add("webview-overlay");

      if (WAT.environment.isWindows) {
          overlay.style.zIndex = WAT.components.webView.style.zIndex + 1;
          overlay.classList.add("fadeOut");

          var svg = document.createElement("svg");
          svg.setAttribute("preserveAspectRatio", true);

          var defs = document.createElement("defs");
          var filter = document.createElement("filter");
          filter.id = "filtersPicture";

          var blur = document.createElement("feGaussianBlur");
          blur.setAttribute("stdDeviation", "2");

          filter.appendChild(blur);
          defs.appendChild(filter);

          var image = new Image();
          image.setAttribute("x", "0");
          image.setAttribute("y", "0");
          image.setAttribute("height", "100%");
          image.setAttribute("width", "100%");
          image.setAttribute("filter", "url(#filtersPicture)");

          svg.appendChild(defs);
          svg.appendChild(image);
          overlay.appendChild(svg);
      }

      WAT.components.stage.appendChild(overlay);

      var transparent = document.createElement("div");
      transparent.classList.add("transparent-overlay");
      transparent.style.zIndex = WAT.components.webView.style.zIndex + 200;

      WAT.components.stage.appendChild(transparent);

      var div = document.createElement("div");
      div.classList.add("loading-wrapper");
      div.id = "loading-wrapper";
      div.style.zIndex = WAT.components.webView.style.zIndex + 200;

      var progress = document.createElement("progress");
      progress.id = "page-load-progress";
      progress.classList.add("loading-progress");
      progress.classList.add("win-ring");
      progress.classList.add("win-large");
      progress.style.zIndex = WAT.components.webView.style.zIndex + 200;

      div.appendChild(progress);
      WAT.components.stage.appendChild(div);
  };

  module.exports = self; // export
<commit_msg>[windows] removing cordova div and styles removal code<commit_after>"use strict";

  var WAT;
  var buildForWindows, buildForWindowsPhone;
  var createHeaderElement, createStageElement, moveWebView, createWebViewForModalDialog, createTransitionOverlay;

  var self = {
      init: function (WATRef) {
          if (!WAT) {
              WAT = WATRef;

              // add base stylesheet
              var base = document.createElement("link");
              base.setAttribute("rel", "stylesheet");
              base.setAttribute("type", "text/css");
              base.href = "css/base.css";
              document.head.appendChild(base);

              if (WAT.environment.isWindows) {
                  // build wrapper html for windows
                  var content = document.createElement("div");
                  content.id = "content";
                  content.classList.add("content");
                  content.classList.add("customColor");
                  document.body.appendChild(content);
                  WAT.components.content = content;

                  buildForWindows();
              }
              else {
                  // build wrapper html for windows phone
                  buildForWindowsPhone();
              }

              // add base wrapper styles
              var styles = document.createElement("link");
              styles.setAttribute("rel", "stylesheet");
              styles.setAttribute("type", "text/css");
              styles.href = "css/wrapper-styles.css";
              document.head.appendChild(styles);

              createTransitionOverlay();
          }
      }
  };

  buildForWindows = function () {
      createHeaderElement();
      createStageElement();
      createWebViewForModalDialog(document.body);
      moveWebView();
  };

  buildForWindowsPhone = function () {
      // add theme styles for Windows Phone
      var theme = document.createElement("link");
      theme.setAttribute("rel", "stylesheet");
      theme.setAttribute("type", "text/css");
      theme.href = "css/ui-themed.theme-dark.css";
      document.head.appendChild(theme);

      // add wrapper styles for windows phone
      var linkElem = document.createElement("link");
      linkElem.setAttribute("rel", "stylesheet");
      linkElem.setAttribute("type", "text/css");
      linkElem.href = "css/wrapper-phone.css";
      document.head.appendChild(linkElem);

      // viewport parent div
      var viewport = document.createElement("div");
      viewport.id = "viewport";
      viewport.classList.add("viewport");

      // surface div
      var surface = document.createElement("div");
      surface.id = "surface";
      surface.classList.add("surface");
      surface.style.zIndex = WAT.components.webView.zIndex + 100;

      // nav drawer div
      var navDrawer = document.createElement("div");
      navDrawer.id = "navDrawer";
      navDrawer.classList.add("navDrawer");

      // search box
      var searchBox = document.createElement("input");
      searchBox.type = "text";
      searchBox.name = "search-box";
      searchBox.id = "search-box";
      searchBox.classList.add("search-box");

      // TODO: enable search box when wat_search is implemented.
      searchBox.style.display = "none";

      navDrawer.appendChild(searchBox);
      WAT.components.navDrawer = navDrawer;

      // navdrawer list view
      var listview = document.createElement("div");
      listview.id = "navDrawerListView";
      listview.classList.add("win-selectionstylefilled");

      navDrawer.appendChild(listview);

      surface.appendChild(navDrawer);

      // up a level
      var content = document.createElement("div");
      content.id = "content";
      content.classList.add("content");
      document.body.appendChild(content);
      WAT.components.content = content;

      createStageElement();

      surface.appendChild(content);

      viewport.appendChild(surface);
      document.body.appendChild(viewport);

      createHeaderElement();
      createWebViewForModalDialog(WAT.components.stage);

      moveWebView();
  };

  // Windows Wrapper HTML functions
  createHeaderElement = function () {
      // header div
      var header = document.createElement("div");
      header.id = "header";
      header.classList.add("header");
      header.style.zIndex = WAT.components.webView.style.zIndex + 100;

      if (!WAT.environment.isWindows) {
          // hamburger
          var hamburger = document.createElement("div");
          hamburger.id = "hamburger";
          hamburger.classList.add("hamburger");
          header.appendChild(hamburger);
      }

      // logo div
      var logoArea = document.createElement("div");
      logoArea.classList.add("logoarea");

      // logo img
      var logoImage = document.createElement("img");
      logoImage.id = "logo";
      logoArea.appendChild(logoImage);
      header.appendChild(logoArea);

      // title
      var title = document.createElement("h1");
      title.id = "title";
      title.classList.add("titlearea");
      title.classList.add("win-type-ellipsis");
      header.appendChild(title);

      // search box
      var searchbox = document.createElement("div");
      searchbox.id = "search-box";
      searchbox.classList.add("search-box");

      // TODO: enable search box when wat_search is implemented.
      searchbox.style.display = "none";

      header.appendChild(searchbox);

      WAT.components.content.appendChild(header);

      WAT.components.header = header;
      WAT.components.logo = logoImage;
      WAT.components.title = title;
  }

  createStageElement = function () {
      var stage = document.createElement("div");
      stage.id = "stage";
      stage.classList.add("stage");
      WAT.components.stage = stage;
      WAT.components.content.appendChild(stage);
  };

  moveWebView = function () {
      var webView = WAT.components.webView;
      webView.id = "main-view";
      WAT.components.stage.appendChild(webView);
  };

  createWebViewForModalDialog = function (appendToElement) {
       var modalStage = document.createElement("div");
       modalStage.id = "modal-stage";
       modalStage.classList.add("stage");
       modalStage.classList.add("overlay-stage");
       modalStage.style.zIndex = WAT.components.webView.style.zIndex + 100;

       var webView = document.createElement("x-ms-webview");
       webView.id = "dialog-view";
       webView.classList.add("modal-content");

       var button = document.createElement("button");
       button.id = "close";
       button.classList.add("win-closebutton");
       button.innerText = "X";

       modalStage.appendChild(webView);
       modalStage.appendChild(button);
       appendToElement.appendChild(modalStage);

       WAT.components.dialogView = webView;
       WAT.components.closeButton = button;
  };

  createTransitionOverlay = function () {
      var overlay = document.createElement("div");
      overlay.classList.add("webview-overlay");

      if (WAT.environment.isWindows) {
          overlay.style.zIndex = WAT.components.webView.style.zIndex + 1;
          overlay.classList.add("fadeOut");

          var svg = document.createElement("svg");
          svg.setAttribute("preserveAspectRatio", true);

          var defs = document.createElement("defs");
          var filter = document.createElement("filter");
          filter.id = "filtersPicture";

          var blur = document.createElement("feGaussianBlur");
          blur.setAttribute("stdDeviation", "2");

          filter.appendChild(blur);
          defs.appendChild(filter);

          var image = new Image();
          image.setAttribute("x", "0");
          image.setAttribute("y", "0");
          image.setAttribute("height", "100%");
          image.setAttribute("width", "100%");
          image.setAttribute("filter", "url(#filtersPicture)");

          svg.appendChild(defs);
          svg.appendChild(image);
          overlay.appendChild(svg);
      }

      WAT.components.stage.appendChild(overlay);

      var transparent = document.createElement("div");
      transparent.classList.add("transparent-overlay");
      transparent.style.zIndex = WAT.components.webView.style.zIndex + 200;

      WAT.components.stage.appendChild(transparent);

      var div = document.createElement("div");
      div.classList.add("loading-wrapper");
      div.id = "loading-wrapper";
      div.style.zIndex = WAT.components.webView.style.zIndex + 200;

      var progress = document.createElement("progress");
      progress.id = "page-load-progress";
      progress.classList.add("loading-progress");
      progress.classList.add("win-ring");
      progress.classList.add("win-large");
      progress.style.zIndex = WAT.components.webView.style.zIndex + 200;

      div.appendChild(progress);
      WAT.components.stage.appendChild(div);
  };

  module.exports = self; // export
<|endoftext|>


<commit_before>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import {Provider} from 'react-redux';
import ReactDOM from 'react-dom';
import {ContextMenuProvider} from 'flipper';
import {precachedIcons} from './utils/icons.js';
import GK from './fb-stubs/GK.js';
import {init as initLogger} from './fb-stubs/Logger';
import App from './App.js';
import BugReporter from './fb-stubs/BugReporter.js';
import {createStore} from 'redux';
import {persistStore} from 'redux-persist';
import reducers from './reducers/index.js';
import dispatcher from './dispatcher/index.js';
import TooltipProvider from './ui/components/TooltipProvider.js';
import config from './utils/processConfig.js';
import {initLauncherHooks} from './utils/launcher.js';
import initCrashReporter from './utils/electronCrashReporter';
const path = require('path');

const store = createStore(
  reducers,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
);
persistStore(store);

const logger = initLogger(store);
const bugReporter = new BugReporter(logger, store);
dispatcher(store, logger);
GK.init();

const AppFrame = () => (
  <TooltipProvider>
    <ContextMenuProvider>
      <Provider store={store}>
        <App logger={logger} bugReporter={bugReporter} />
      </Provider>
    </ContextMenuProvider>
  </TooltipProvider>
);

function init() {
  // $FlowFixMe: this element exists!
  ReactDOM.render(<AppFrame />, document.getElementById('root'));
  // $FlowFixMe: service workers exist!
  navigator.serviceWorker
    .register(
      process.env.NODE_ENV === 'production'
        ? path.join(__dirname, 'serviceWorker.js')
        : './serviceWorker.js',
    )
    .then(r => {
      (r.installing || r.active).postMessage({precachedIcons});
    })
    .catch(console.error);

  initLauncherHooks(config(), store);
  const sessionId = store.getState().application.sessionId;
  initCrashReporter(sessionId || '');
}

// make init function callable from outside
window.Flipper.init = init;
<commit_msg>Explicitly type service worker registration<commit_after>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import {Provider} from 'react-redux';
import ReactDOM from 'react-dom';
import {ContextMenuProvider} from 'flipper';
import {precachedIcons} from './utils/icons.js';
import GK from './fb-stubs/GK.js';
import {init as initLogger} from './fb-stubs/Logger';
import App from './App.js';
import BugReporter from './fb-stubs/BugReporter.js';
import {createStore} from 'redux';
import {persistStore} from 'redux-persist';
import reducers from './reducers/index.js';
import dispatcher from './dispatcher/index.js';
import TooltipProvider from './ui/components/TooltipProvider.js';
import config from './utils/processConfig.js';
import {initLauncherHooks} from './utils/launcher.js';
import initCrashReporter from './utils/electronCrashReporter';
const path = require('path');

const store = createStore(
  reducers,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
);
persistStore(store);

const logger = initLogger(store);
const bugReporter = new BugReporter(logger, store);
dispatcher(store, logger);
GK.init();

const AppFrame = () => (
  <TooltipProvider>
    <ContextMenuProvider>
      <Provider store={store}>
        <App logger={logger} bugReporter={bugReporter} />
      </Provider>
    </ContextMenuProvider>
  </TooltipProvider>
);

function init() {
  // $FlowFixMe: this element exists!
  ReactDOM.render(<AppFrame />, document.getElementById('root'));
  // $FlowFixMe: service workers exist!
  navigator.serviceWorker
    .register(
      process.env.NODE_ENV === 'production'
        ? path.join(__dirname, 'serviceWorker.js')
        : './serviceWorker.js',
    )
    .then((r: ServiceWorkerRegistration) => {
      const client = r.installing || r.active;
      if (client != null) {
        client.postMessage({precachedIcons});
      } else {
        console.error('Service worker registration failed: ', r);
      }
    })
    .catch(console.error);

  initLauncherHooks(config(), store);
  const sessionId = store.getState().application.sessionId;
  initCrashReporter(sessionId || '');
}

// make init function callable from outside
window.Flipper.init = init;
<|endoftext|>


<commit_before>const parcel = require("parcel-bundler");
const path = require("path");
const fs = require("fs");
const copy = require("recursive-copy");
const childProcess = require("child_process");
const logLevel = 2;

async function main() {
  console.log(`Bundling metal...`);
  const metalFile = path.join(__dirname, "./metal.ts");
  const metalOptions = { target: "electron", logLevel };
  const metalBundler = new parcel(metalFile, metalOptions);
  await metalBundler.bundle();

  console.log(`Bundling chrome...`);
  const chromeFile = path.join(__dirname, "./index.html");
  const chromeOptions = { target: "electron", logLevel };
  const chromeBundler = new parcel(chromeFile, chromeOptions);
  await chromeBundler.serve();

  console.log(`Copying incidentals...`);
  await copy("src/main.js", "dist/main.js", {overwrite: true});
  await copy("src/static/", "dist/static/", {overwrite: true});

  console.log(`Starting up electron!`);
  const el = childProcess.spawn(`node_modules\\.bin\\electron.cmd`, [
    "."
  ], {
    stdio: "inherit",
  });
  el.on("error", (e) => {
    console.log(`Electron process error:\n${e.stack}`);
    process.exit(1);
  });

  el.on("close", () => {
    console.log(`Electron returned!`);
    process.exit(0);
  });
}

main().catch((e) => {
  console.log(`Fatal error:\n${e.stack}`);
  process.exit(1);
});
<commit_msg>Fix electron path for non-windows<commit_after>const parcel = require("parcel-bundler");
const path = require("path");
const fs = require("fs");
const copy = require("recursive-copy");
const childProcess = require("child_process");
const logLevel = 2;

async function main() {
  console.log(`Bundling metal...`);
  const metalFile = path.join(__dirname, "./metal.ts");
  const metalOptions = { target: "electron", logLevel };
  const metalBundler = new parcel(metalFile, metalOptions);
  await metalBundler.bundle();

  console.log(`Bundling chrome...`);
  const chromeFile = path.join(__dirname, "./index.html");
  const chromeOptions = { target: "electron", logLevel };
  const chromeBundler = new parcel(chromeFile, chromeOptions);
  await chromeBundler.serve();

  console.log(`Copying incidentals...`);
  await copy("src/main.js", "dist/main.js", {overwrite: true});
  await copy("src/static/", "dist/static/", {overwrite: true});

  console.log(`Starting up electron!`);
  let electronPath = `node_modules/.bin/electron`;
  if (process.platform === "win32") {
    electronPath = `node_modules\\.bin\\electron`;
  }

  const el = childProcess.spawn(electronPath, [
    "."
  ], {
    stdio: "inherit",
  });
  el.on("error", (e) => {
    console.log(`Electron process error:\n${e.stack}`);
    process.exit(1);
  });

  el.on("close", () => {
    console.log(`Electron returned!`);
    process.exit(0);
  });
}

main().catch((e) => {
  console.log(`Fatal error:\n${e.stack}`);
  process.exit(1);
});
<|endoftext|>


<commit_before>/*jslint browser: true, plusplus: true, nomen: true, white: false*/
/*global $, console, jqPlot, jQuery*/

/**
 * jqPlot
 * Pure JavaScript plotting plugin using jQuery
 *
 * Version: @VERSION
 * Revision: @REVISION
 *
 * Copyright (c) 2009-2013 Chris Leonello
 * jqPlot is currently available for use in all personal or commercial projects
 * under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
 * version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
 * choose the license that best suits your project and use it accordingly.
 *
 * Although not required, the author would appreciate an email letting him
 * know of any substantial use of jqPlot.  You can reach the author at:
 * chris at jqplot  or see http://www.jqplot.com/info.php .
 *
 * If you are feeling kind and generous, consider supporting the project by
 * making a donation at: http://www.jqplot.com/donate.php .
 *
 * sprintf functions contained in jqplot.sprintf.js by Ash Searle:
 *
 *     version 2007.04.27
 *     author Ash Searle
 *     http://hexmen.com/blog/2007/03/printf-sprintf/
 *     http://hexmen.com/js/sprintf.js
 *     The author (Ash Searle) has placed this code in the public domain:
 *     "This code is unrestricted: you are free to use it however you like."
 *
 */

 /**
 *
 * This is a boot loader for the source version of jqplot.
 * It will load all of the necessary core jqplot files that
 * are concated together in the distribution.
 *
 */

(function () {
    "use strict";
    var jqutils = {};

    jqutils.loadjscssfile = function (filename, filetype) {
        var fileref;
        if (filetype === "js") { //if filename is a external JavaScript file
            fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename);
        } else if (filetype === "css") { //if filename is an external CSS file
            fileref = document.createElement("link");
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", filename);
        }
        if (fileref) {
            try {
                if (filetype === "js") {
                    document.write("<scr" + "ipt type='text/javascript' src='" + filename + "'></scr" + "ipt>\n");
                } else {
                    document.getElementsByTagName("head")[0].appendChild(fileref);
                }
            } catch (e) {
                document.getElementsByTagName("head")[0].appendChild(fileref);
                // avoid memory leak
                fileref = null;
            }
        }
    };

    jqutils.getRootNode = function () {
        var scripts, pat, minpat, i, src, m, minified;

        // figure out the path to this loader
        if (document && document.getElementsByTagName) {
            scripts = document.getElementsByTagName("script");
            pat = /jquery\.jqplot\.js/i;
            minpat = /jquery\.jqplot\.min\.js/i;

            for (i = 0; i < scripts.length; i++) {
                src = scripts[i].getAttribute("src");
                console.log("test: ".concat(src));
                if (!src) {
                    continue;
                }
                m = src.match(pat);
                minified = src.match(minpat);

                if (m) {
                    return {
                        node: scripts[i],
                        root: src.substring(0, m.index),
                        minified: false
                    };
                } else if (minified) {
                    return {
                        node: scripts[i],
                        root: src.substring(0, minified.index),
                        minified: true
                    };
                }
            }
        }
    };

    var files = ['jqplot.core.js', 'jqplot.linearTickGenerator.js', 'jqplot.linearAxisRenderer.js', 'jqplot.axisTickRenderer.js', 'jqplot.axisLabelRenderer.js', 'jqplot.tableLegendRenderer.js', 'jqplot.lineRenderer.js', 'jqplot.markerRenderer.js', 'jqplot.divTitleRenderer.js', 'jqplot.canvasGridRenderer.js', 'jqplot.linePattern.js', 'jqplot.shadowRenderer.js', 'jqplot.shapeRenderer.js', 'jqplot.sprintf.js', 'jsdate.js', 'jqplot.themeEngine.js', 'jqplot.toImage.js', 'jqplot.effects.core.js', 'jqplot.effects.blind.js', 'jqplot.stairsRenderer.js'],
        minfiles = ['jqplot.core.min.js', 'jqplot.linearTickGenerator.min.js', 'jqplot.linearAxisRenderer.min.js', 'jqplot.axisTickRenderer.min.js', 'jqplot.axisLabelRenderer.min.js', 'jqplot.tableLegendRenderer.min.js', 'jqplot.lineRenderer.min.js', 'jqplot.markerRenderer.min.js', 'jqplot.divTitleRenderer.min.js', 'jqplot.canvasGridRenderer.min.js', 'jqplot.linePattern.min.js', 'jqplot.shadowRenderer.min.js', 'jqplot.shapeRenderer.min.js', 'jqplot.sprintf.min.js', 'jsdate.min.js', 'jqplot.themeEngine.min.js', 'jqplot.toImage.min.js', 'jqplot.effects.core.min.js', 'jqplot.effects.blind.min.js', 'jqplot.stairsRenderer.min.js'],
        i,
        rootNode,
        rn,
        pp,
        fileref;

    rootNode = jqutils.getRootNode();
    rn = rootNode.root;

    if (rootNode.minified) {
        files = minfiles;
    }

    for (i = 0; i < files.length; i++) {
        pp = rn + files[i];
        fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", pp);
        jqutils.loadjscssfile(pp, "js");
    }

    jqutils.loadjscssfile(rn + 'font-awesome.min.css', 'css');

})();<commit_msg>Changed jquery.jqplot<commit_after>/*jslint browser: true, plusplus: true, nomen: true, white: false*/
/*global $, console, jqPlot, jQuery*/

/**
 * jqPlot
 * Pure JavaScript plotting plugin using jQuery
 *
 * Version: @VERSION
 * Revision: @REVISION
 *
 * Copyright (c) 2009-2013 Chris Leonello
 * jqPlot is currently available for use in all personal or commercial projects
 * under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
 * version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
 * choose the license that best suits your project and use it accordingly.
 *
 * Although not required, the author would appreciate an email letting him
 * know of any substantial use of jqPlot.  You can reach the author at:
 * chris at jqplot  or see http://www.jqplot.com/info.php .
 *
 * If you are feeling kind and generous, consider supporting the project by
 * making a donation at: http://www.jqplot.com/donate.php .
 *
 * sprintf functions contained in jqplot.sprintf.js by Ash Searle:
 *
 *     version 2007.04.27
 *     author Ash Searle
 *     http://hexmen.com/blog/2007/03/printf-sprintf/
 *     http://hexmen.com/js/sprintf.js
 *     The author (Ash Searle) has placed this code in the public domain:
 *     "This code is unrestricted: you are free to use it however you like."
 *
 */

 /**
 *
 * This is a boot loader for the source version of jqplot.
 * It will load all of the necessary core jqplot files that
 * are concated together in the distribution.
 *
 */

(function () {
    "use strict";
    var jqutils = {};

    jqutils.loadjscssfile = function (filename, filetype) {
        var fileref;
        if (filetype === "js") { //if filename is a external JavaScript file
            fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename);
        } else if (filetype === "css") { //if filename is an external CSS file
            fileref = document.createElement("link");
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", filename);
        }
        if (fileref) {
            try {
                if (filetype === "js") {
                    document.write("<scr" + "ipt type='text/javascript' src='" + filename + "'></scr" + "ipt>\n");
                } else {
                    document.getElementsByTagName("head")[0].appendChild(fileref);
                }
            } catch (e) {
                document.getElementsByTagName("head")[0].appendChild(fileref);
                // avoid memory leak
                fileref = null;
            }
        }
    };

    jqutils.getRootNode = function () {
        var scripts, pat, minpat, i, src, m, minified;

        // figure out the path to this loader
        if (document && document.getElementsByTagName) {
            scripts = document.getElementsByTagName("script");
            pat = /jquery\.jqplot\.js/i;
            minpat = /jquery\.jqplot\.min\.js/i;

            for (i = 0; i < scripts.length; i++) {
                src = scripts[i].getAttribute("src");
                console.log("test: ".concat(src));
                if (!src) {
                    continue;
                }
                m = src.match(pat);
                minified = src.match(minpat);

                if (m) {
                    return {
                        node: scripts[i],
                        root: src.substring(0, m.index),
                        minified: false
                    };
                } else if (minified) {
                    return {
                        node: scripts[i],
                        root: src.substring(0, minified.index),
                        minified: true
                    };
                }
            }
        }
    };

    var files = ['jqplot.core.js', 'jqplot.linearTickGenerator.js', 'jqplot.linearAxisRenderer.js', 'jqplot.axisTickRenderer.js', 'jqplot.axisLabelRenderer.js', 'jqplot.tableLegendRenderer.js', 'jqplot.lineRenderer.js', 'jqplot.markerRenderer.js', 'jqplot.divTitleRenderer.js', 'jqplot.canvasGridRenderer.js', 'jqplot.linePattern.js', 'jqplot.shadowRenderer.js', 'jqplot.shapeRenderer.js', 'jqplot.sprintf.js', 'jsdate.js', 'jqplot.themeEngine.js', 'jqplot.toImage.js', 'jqplot.effects.core.js', 'jqplot.effects.blind.js', 'jqplot.stairsRenderer.js'],
        minfiles = ['jqplot.core.min.js', 'jqplot.linearTickGenerator.min.js', 'jqplot.linearAxisRenderer.min.js', 'jqplot.axisTickRenderer.min.js', 'jqplot.axisLabelRenderer.min.js', 'jqplot.tableLegendRenderer.min.js', 'jqplot.lineRenderer.min.js', 'jqplot.markerRenderer.min.js', 'jqplot.divTitleRenderer.min.js', 'jqplot.canvasGridRenderer.min.js', 'jqplot.linePattern.min.js', 'jqplot.shadowRenderer.min.js', 'jqplot.shapeRenderer.min.js', 'jqplot.sprintf.min.js', 'jsdate.min.js', 'jqplot.themeEngine.min.js', 'jqplot.toImage.min.js', 'jqplot.effects.core.min.js', 'jqplot.effects.blind.min.js', 'jqplot.stairsRenderer.min.js'],
        i,
        rootNode,
        rn,
        pp,
        fileref;

    rootNode = jqutils.getRootNode();
    rn = rootNode.root;

    if (rootNode.minified) {
        files = minfiles;
    }

    for (i = 0; i < files.length; i++) {
        pp = rn + files[i];
        fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", pp);
        jqutils.loadjscssfile(pp, "js");
    }

    jqutils.loadjscssfile(rn + 'font-awesome.min.css', 'css');

}());<|endoftext|>