<commit_before>import assert from 'assert';
import path from 'path';
import requireAll from 'require-all';
import mapValues from 'lodash-node/modern/object/mapValues';
import isArray from 'lodash-node/modern/lang/isArray';
import RawAdapter from './adapters/raw';
import Serializer from './serializer';

export { Serializer };

/**
 * Create a blackburn middleware function that will patch res.render to use
 * the blackburn serializers and renderers.
 *
 * @method blackburn
 *
 * @param  {Object}  options
 * @param  {String|Object}  options.adapter - the adapter to use to interrogate
 * model instances
 * @param  {String|Object}   options.serializers - either the path to the
 * directory of serializers, or an object whose keys are model types, and
 * whose values are instances of their respective Serializers. Defaults to
 * 'serializers'. The "application" serializer will be used when no type
 * specific serializer is found.
 * @param  {String}          options.renderMethodName - the name of the render
 * method to attach to the response object. Defaults to 'render', which will
 * override the Express default render method.
 *
 * @return {Function}        blackburn middleware function
 */
export default function blackburn(options = {}) {
  let adapter = options.adapter || new RawAdapter();

  // Load serializers
  let serializers;
  options.serializers = options.serializers || './serializers';
  if (typeof options.serializers === 'string') {
    serializers = requireAll(path.join(process.cwd(), options.serializers));
  } else {
    serializers = options.serializers;
  }
  // Ensure they are instantiated
  serializers = mapValues(serializers, (Serializer, name) => {
    return typeof Serializer !== 'function' ? Serializer : new Serializer({
      serializers,
      adapter: options.adapter,
      type: name
    });
  });

  let renderMethodName = options.renderMethodName || 'render';

  return function blackburnMiddleware(req, res, next) {
    res[renderMethodName] = function render(status, payload, opts = {}) {
      // Ensure the status is set
      if (typeof status !== 'number') {
        payload = status;
        status = 200;
      }
      res.status(status);

      let serializer;
      // Serializer name is supplied
      if (typeof opts.serializer === 'string') {
        serializer = serializers[opts.serializer];
      // Serializer instance is supplied
      } else if (opts.serializer) {
        serializer = opts.serializer;
      // No serializer supplied - check the payload to try inferring
      } else {
        let sample = isArray(payload) ? payload[0] : payload;
        let type = adapter.typeForRecord(sample);
        serializer = serializers[type] || serializers.application;
      }
      assert(serializer, `Unable to serialize response! You didn't supply a serializer, no serializer found matched the payload's type, and you didn't supply an application serializer as a fallback.`);
      res.json(serializer.render(payload, opts));
    };
    next();
  };
}
<commit_msg>export built-in adapters and serializers<commit_after>import assert from 'assert';
import path from 'path';
import requireAll from 'require-all';
import mapValues from 'lodash-node/modern/object/mapValues';
import isArray from 'lodash-node/modern/lang/isArray';
import Adapter from './adapter';
import RawAdapter from './adapters/raw';
import Serializer from './serializer';
import JSONAPISerializer from './serializers/json-api';
import RootSerializer from './serializers/root';
import FlatSerializer from './serializers/flat';

export {
  Serializer,
  JSONAPISerializer,
  RootSerializer,
  FlatSerializer,
  Adapter,
  RawAdapter
};

/**
 * Create a blackburn middleware function that will patch res.render to use
 * the blackburn serializers and renderers.
 *
 * @method blackburn
 *
 * @param  {Object}  options
 * @param  {String|Object}  options.adapter - the adapter to use to interrogate
 * model instances
 * @param  {String|Object}   options.serializers - either the path to the
 * directory of serializers, or an object whose keys are model types, and
 * whose values are instances of their respective Serializers. Defaults to
 * 'serializers'. The "application" serializer will be used when no type
 * specific serializer is found.
 * @param  {String}          options.renderMethodName - the name of the render
 * method to attach to the response object. Defaults to 'render', which will
 * override the Express default render method.
 *
 * @return {Function}        blackburn middleware function
 */
export default function blackburn(options = {}) {
  let adapter = options.adapter || new RawAdapter();

  // Load serializers
  let serializers;
  options.serializers = options.serializers || './serializers';
  if (typeof options.serializers === 'string') {
    serializers = requireAll(path.join(process.cwd(), options.serializers));
  } else {
    serializers = options.serializers;
  }
  // Ensure they are instantiated
  serializers = mapValues(serializers, (Serializer, name) => {
    return typeof Serializer !== 'function' ? Serializer : new Serializer({
      serializers,
      adapter: options.adapter,
      type: name
    });
  });

  let renderMethodName = options.renderMethodName || 'render';

  return function blackburnMiddleware(req, res, next) {
    res[renderMethodName] = function render(status, payload, opts = {}) {
      // Ensure the status is set
      if (typeof status !== 'number') {
        payload = status;
        status = 200;
      }
      res.status(status);

      let serializer;
      // Serializer name is supplied
      if (typeof opts.serializer === 'string') {
        serializer = serializers[opts.serializer];
      // Serializer instance is supplied
      } else if (opts.serializer) {
        serializer = opts.serializer;
      // No serializer supplied - check the payload to try inferring
      } else {
        let sample = isArray(payload) ? payload[0] : payload;
        let type = adapter.typeForRecord(sample);
        serializer = serializers[type] || serializers.application;
      }
      assert(serializer, `Unable to serialize response! You didn't supply a serializer, no serializer found matched the payload's type, and you didn't supply an application serializer as a fallback.`);
      res.json(serializer.render(payload, opts));
    };
    next();
  };
}
<|endoftext|>


<commit_before>'use strict';
const { ObjectId } = require('mongodb');

function convertAttachments(config, conns) {
  if (!config.attachment.convert) {
    return Promise.resolve();
  } else {
    return new Promise((resolve, reject) => {

      function cleanupMongo() {
        if (!config.threadAndPost.cleanup) {
          return Promise.resolve();
        }
        console.log('[Attachments][Mongo] Deleting all data in attachment.');
        return new Promise((resolve, reject) => {
          conns.mongo.collection('attachment').deleteMany({}, (err, res) => {
            if (err) {
              reject(err);
            }
            else {
              resolve();
            }
          })
        })
      }

      function fetchAttachments(tail) {
        console.log(`[Attachments][MySQL] Fetching attachments from table: cbs_forum_attachment_${tail}.`);
        return new Promise((resolve, reject) => {
          conns.mysql.query({
            sql:
              `SELECT cbs_forum_attachment_${tail}.*, cbs_forum_attachment.downloads ` +
              `FROM cncalc.cbs_forum_attachment_${tail} ` +
              `INNER JOIN cncalc.cbs_forum_attachment ` +
              `ON cncalc.cbs_forum_attachment.aid = cncalc.cbs_forum_attachment_${tail}.aid`
          }, (err, data) => {
            if (err) {
              reject(err);
            } else {
              resolve(data);
            }
          })
        });
      }

      function prepareUserData() {
        console.log('[Attachments][Mongo] Fetching user data.');
        return new Promise((resolve, reject) => {
          conns.mongo.collection('common_member').find({}).toArray((err, data) => {
            let userMap = {};
            data.forEach(item => userMap[item.uid] = item._id);
            resolve(userMap);
          })
        });
      }

      cleanupMongo().then(async () => {
        let values = await Promise.all([prepareUserData(), ...Array(10).fill(0).map((el, off) => off).concat('unused').map(fetchAttachments)]);
        let uidMap = values.shift();
        let update = {};
        let attachments = values.reduce((a, b) => [...Array.from(a), ...Array.from(b)]);
        // .map(row => {
        //   return {
        //     aid: row.aid,
        //     uid: row.uid,
        //     originalName: row.filename,
        //     fileName: row.attachment,
        //     size: -1,
        //     downloadCount: row.downloads,
        //   }
        // });
        console.log('[Attachments][Mongo] Inserting data into MongoDB...');
        for (let attachment of attachments) {
          let r = await conns.mongo.collection('attachment').insertOne(
            {
              _id: ObjectId(),
              pid: attachment.pid,
              aid: attachment.aid,
              type: attachment.isimage ? 'image' : 'file',
              fileName: attachment.filename,
              filePath: attachment.attachment,
              size: attachment.filesize,
              downloadCount: 0,
              referer: [],
            }
          );
        }

        resolve();
      });
    });
  }
}

module.exports = convertAttachments;
<commit_msg>attachment: fix owner missing.<commit_after>'use strict';
const { ObjectId } = require('mongodb');

function convertAttachments(config, conns) {
  if (!config.attachment.convert) {
    return Promise.resolve();
  } else {
    return new Promise((resolve, reject) => {

      function cleanupMongo() {
        if (!config.threadAndPost.cleanup) {
          return Promise.resolve();
        }
        console.log('[Attachments][Mongo] Deleting all data in attachment.');
        return new Promise((resolve, reject) => {
          conns.mongo.collection('attachment').deleteMany({}, (err, res) => {
            if (err) {
              reject(err);
            }
            else {
              resolve();
            }
          })
        })
      }

      function fetchAttachments(tail) {
        console.log(`[Attachments][MySQL] Fetching attachments from table: cbs_forum_attachment_${tail}.`);
        return new Promise((resolve, reject) => {
          conns.mysql.query({
            sql:
              `SELECT cbs_forum_attachment_${tail}.*, cbs_forum_attachment.downloads ` +
              `FROM cncalc.cbs_forum_attachment_${tail} ` +
              `INNER JOIN cncalc.cbs_forum_attachment ` +
              `ON cncalc.cbs_forum_attachment.aid = cncalc.cbs_forum_attachment_${tail}.aid`
          }, (err, data) => {
            if (err) {
              reject(err);
            } else {
              resolve(data);
            }
          })
        });
      }

      function prepareUserData() {
        console.log('[Attachments][Mongo] Fetching user data.');
        return new Promise((resolve, reject) => {
          conns.mongo.collection('common_member').find({}).toArray((err, data) => {
            let userMap = {};
            data.forEach(item => userMap[item.uid] = item);
            resolve(userMap);
          })
        });
      }

      cleanupMongo().then(async () => {
        let values = await Promise.all([prepareUserData(), ...Array(10).fill(0).map((el, off) => off).concat('unused').map(fetchAttachments)]);
        let uidMap = values.shift();
        let update = {};
        let attachments = values.reduce((a, b) => [...Array.from(a), ...Array.from(b)]);
        // .map(row => {
        //   return {
        //     aid: row.aid,
        //     uid: row.uid,
        //     originalName: row.filename,
        //     fileName: row.attachment,
        //     size: -1,
        //     downloadCount: row.downloads,
        //   }
        // });
        console.log('[Attachments][Mongo] Inserting data into MongoDB...');
        for (let attachment of attachments) {
          let r = await conns.mongo.collection('attachment').insertOne(
            {
              _id: ObjectId(),
              _owner: uidMap[attachment.uid] ? uidMap[attachment.uid]._id : null,
              pid: attachment.pid,
              aid: attachment.aid,
              type: attachment.isimage ? 'image' : 'file',
              fileName: attachment.filename,
              filePath: attachment.attachment,
              size: attachment.filesize,
              downloadCount: 0,
              referer: [],
            }
          );
        }

        resolve();
      });
    });
  }
}

module.exports = convertAttachments;
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var fs = require('fs');
var http = require('http');
var https = require('https');
var socks = require('sockx');
var EventEmitter = require('events').EventEmitter;
var util = require('./util');
var logger = require('./util/logger');
var rules = require('./rules');
var setupHttps = require('./https').setup;
var httpsUtil = require('./https/ca');
var rulesUtil = require('./rules/util');
var initDataServer = require('./util/data-server');
var initLogServer = require('./util/log-server');
var pluginMgr = require('./plugins');
var config = require('./config');
var loadService = require('./service');
var initSocketMgr = require('./socket-mgr');
var tunnelProxy = require('./tunnel');
var upgradeProxy = require('./upgrade');
var ca = require('./https/ca');

function handleClientError(err, socket) {
  if (!socket.writable) {
    return socket.destroy(err);
  }
  var errCode = err && err.code;
  var statusCode = errCode === 'HPE_HEADER_OVERFLOW' ? 431 : 400;
  var stack = util.getErrorStack('clientError: Bad request' + (errCode ? ' (' + errCode + ')' : ''));
  socket.end('HTTP/1.1 ' + statusCode + ' Bad Request\r\n\r\n' + stack);
}

function proxy(callback) {
  var app = express();
  var server = http.createServer();
  var proxyEvents = new EventEmitter();
  var middlewares = ['./init', '../biz']
    .concat(require('./inspectors'))
    .concat(config.middlewares)
    .concat(require('./handlers'));
  server.timeout = config.timeout;
  proxyEvents.config = config;
  proxyEvents.server = server;
  app.logger = logger;
  middlewares.forEach(function(mw) {
    mw && app.use((typeof mw == 'string' ? require(mw) : mw).bind(proxyEvents));
  });
  server.on('clientError', handleClientError);
  initSocketMgr(proxyEvents);
  setupHttps(server, proxyEvents);
  exportInterfaces(proxyEvents);
  tunnelProxy(server, proxyEvents);
  upgradeProxy(server);
  initDataServer(proxyEvents);
  initLogServer(proxyEvents);
  rulesUtil.setup(proxyEvents);
  var properties = rulesUtil.properties;
  if (config.disableAllRules) {
    properties.set('disabledAllRules', true);
  } else if (config.disableAllRules === false) {
    properties.set('disabledAllRules', false);
  }
  if (config.disableAllPlugins) {
    properties.set('disabledAllPlugins', true);
  } else if (config.disableAllPlugins === false) {
    properties.set('disabledAllPlugins', false);
  }
  if (config.allowMultipleChoice) {
    properties.set('allowMultipleChoice', true);
  } else if (config.allowMultipleChoice === false) {
    properties.set('allowMultipleChoice', false);
  }
  rulesUtil.addValues(config.values, config.replaceExistValue);
  rulesUtil.addRules(config.rules, config.replaceExistRule);
  config.debug && rules.disableDnsCache();
  var count = 2;
  var execCallback = function() {
    if (--count === 0 && typeof callback === 'function') {
      callback.call(server, proxyEvents);
    }
  };
  util.getBoundIp(function(host) {
    util.checkPort(!config.INADDR_ANY && !host && config.port, function() {
      server.listen(config.port, host, execCallback);
    });
  });
  var createNormalServer = function(port, httpModule, opts) {
    if (!port) {
      return;
    }
    ++count;
    var optionServer = httpModule.createServer(opts);
    var isHttps = !!opts;
    proxyEvents[opts ? 'httpsServer' : 'httpServer'] = optionServer;
    optionServer.on('request', function(req, res) {
      req.isHttps = isHttps;
      app.handle(req, res);
    });
    optionServer.isHttps = isHttps;
    tunnelProxy(optionServer, proxyEvents);
    upgradeProxy(optionServer);
    optionServer.on('clientError', handleClientError);
    util.getBoundIp(function(host) {
      util.checkPort(!config.INADDR_ANY && !host && port, function() {
        optionServer.listen(port, host, execCallback);
      });
    });
  };
  createNormalServer(config.httpPort, http);
  createNormalServer(config.httpsPort, https, ca.SNI_OPTIONS);
  if (config.socksPort) {
    ++count;
    var boundHost;
    var socksServer = socks.createServer(function(info, accept, deny) {
      var dstPort = info.dstPort;
      var connPath = info.dstAddr + ':' + dstPort;
      var headers = { host: connPath };
      if (dstPort != 80 && dstPort != 443) {
        headers['x-whistle-policy'] = 'tunnel';
      }
      var client = http.request({
        method: 'CONNECT',
        agent: false,
        path: connPath,
        host: boundHost,
        port: config.port,
        rejectUnauthorized: false,
        headers: headers
      });
      client.on('error', deny);
      client.on('connect', function(res, socket) {
        socket.on('error', deny);
        if (res.statusCode != 200) {
          return deny();
        }
        var reqSock = accept(true);
        if (reqSock) {
          reqSock.pipe(socket).pipe(reqSock);
        }
      });
      client.end();
    });
    proxyEvents.socksServer = socksServer;
    util.getBoundIp(function(host) {
      boundHost = host || '127.0.0.1';
      util.checkPort(!config.INADDR_ANY && !host && config.socksPort, function() {
        socksServer.listen(config.socksPort, host, execCallback);
      });
      socksServer.useAuth(socks.auth.None());
    });
  }
  require('../biz/init')(proxyEvents, function(){
    server.on('request', app);
    execCallback();
  });
  return proxyEvents;
}

function exportInterfaces(obj) {
  obj.rules = rules;
  obj.util = util;
  obj.rulesUtil = rulesUtil;
  obj.httpsUtil = httpsUtil;
  obj.pluginMgr = pluginMgr;
  obj.logger = logger;
  obj.loadService = loadService;
  obj.setAuth = config.setAuth;
  obj.setUIHost = config.setUIHost;
  obj.setPluginUIHost = config.setPluginUIHost;
  obj.socketMgr = initSocketMgr;
  return obj;
}

process.on('uncaughtException', function(err){
  var stack = util.getErrorStack(err);
  fs.writeFileSync(path.join(process.cwd(), config.name + '.log'), '\r\n' + stack + '\r\n', {flag: 'a'});
  /*eslint no-console: "off"*/
  console.error(stack);
  process.exit(1);
});

module.exports = exportInterfaces(proxy);
<commit_msg>chore: refine handle uncaughtException<commit_after>var express = require('express');
var path = require('path');
var fs = require('fs');
var http = require('http');
var https = require('https');
var socks = require('sockx');
var EventEmitter = require('events').EventEmitter;
var util = require('./util');
var logger = require('./util/logger');
var rules = require('./rules');
var setupHttps = require('./https').setup;
var httpsUtil = require('./https/ca');
var rulesUtil = require('./rules/util');
var initDataServer = require('./util/data-server');
var initLogServer = require('./util/log-server');
var pluginMgr = require('./plugins');
var config = require('./config');
var loadService = require('./service');
var initSocketMgr = require('./socket-mgr');
var tunnelProxy = require('./tunnel');
var upgradeProxy = require('./upgrade');
var ca = require('./https/ca');

function handleClientError(err, socket) {
  if (!socket.writable) {
    return socket.destroy(err);
  }
  var errCode = err && err.code;
  var statusCode = errCode === 'HPE_HEADER_OVERFLOW' ? 431 : 400;
  var stack = util.getErrorStack('clientError: Bad request' + (errCode ? ' (' + errCode + ')' : ''));
  socket.end('HTTP/1.1 ' + statusCode + ' Bad Request\r\n\r\n' + stack);
}

function proxy(callback) {
  var app = express();
  var server = http.createServer();
  var proxyEvents = new EventEmitter();
  var middlewares = ['./init', '../biz']
    .concat(require('./inspectors'))
    .concat(config.middlewares)
    .concat(require('./handlers'));
  server.timeout = config.timeout;
  proxyEvents.config = config;
  proxyEvents.server = server;
  app.logger = logger;
  middlewares.forEach(function(mw) {
    mw && app.use((typeof mw == 'string' ? require(mw) : mw).bind(proxyEvents));
  });
  server.on('clientError', handleClientError);
  initSocketMgr(proxyEvents);
  setupHttps(server, proxyEvents);
  exportInterfaces(proxyEvents);
  tunnelProxy(server, proxyEvents);
  upgradeProxy(server);
  initDataServer(proxyEvents);
  initLogServer(proxyEvents);
  rulesUtil.setup(proxyEvents);
  var properties = rulesUtil.properties;
  if (config.disableAllRules) {
    properties.set('disabledAllRules', true);
  } else if (config.disableAllRules === false) {
    properties.set('disabledAllRules', false);
  }
  if (config.disableAllPlugins) {
    properties.set('disabledAllPlugins', true);
  } else if (config.disableAllPlugins === false) {
    properties.set('disabledAllPlugins', false);
  }
  if (config.allowMultipleChoice) {
    properties.set('allowMultipleChoice', true);
  } else if (config.allowMultipleChoice === false) {
    properties.set('allowMultipleChoice', false);
  }
  rulesUtil.addValues(config.values, config.replaceExistValue);
  rulesUtil.addRules(config.rules, config.replaceExistRule);
  config.debug && rules.disableDnsCache();
  var count = 2;
  var execCallback = function() {
    if (--count === 0 && typeof callback === 'function') {
      callback.call(server, proxyEvents);
    }
  };
  util.getBoundIp(function(host) {
    util.checkPort(!config.INADDR_ANY && !host && config.port, function() {
      server.listen(config.port, host, execCallback);
    });
  });
  var createNormalServer = function(port, httpModule, opts) {
    if (!port) {
      return;
    }
    ++count;
    var optionServer = httpModule.createServer(opts);
    var isHttps = !!opts;
    proxyEvents[opts ? 'httpsServer' : 'httpServer'] = optionServer;
    optionServer.on('request', function(req, res) {
      req.isHttps = isHttps;
      app.handle(req, res);
    });
    optionServer.isHttps = isHttps;
    tunnelProxy(optionServer, proxyEvents);
    upgradeProxy(optionServer);
    optionServer.on('clientError', handleClientError);
    util.getBoundIp(function(host) {
      util.checkPort(!config.INADDR_ANY && !host && port, function() {
        optionServer.listen(port, host, execCallback);
      });
    });
  };
  createNormalServer(config.httpPort, http);
  createNormalServer(config.httpsPort, https, ca.SNI_OPTIONS);
  if (config.socksPort) {
    ++count;
    var boundHost;
    var socksServer = socks.createServer(function(info, accept, deny) {
      var dstPort = info.dstPort;
      var connPath = info.dstAddr + ':' + dstPort;
      var headers = { host: connPath };
      if (dstPort != 80 && dstPort != 443) {
        headers['x-whistle-policy'] = 'tunnel';
      }
      var client = http.request({
        method: 'CONNECT',
        agent: false,
        path: connPath,
        host: boundHost,
        port: config.port,
        rejectUnauthorized: false,
        headers: headers
      });
      client.on('error', deny);
      client.on('connect', function(res, socket) {
        socket.on('error', deny);
        if (res.statusCode != 200) {
          return deny();
        }
        var reqSock = accept(true);
        if (reqSock) {
          reqSock.pipe(socket).pipe(reqSock);
        }
      });
      client.end();
    });
    proxyEvents.socksServer = socksServer;
    util.getBoundIp(function(host) {
      boundHost = host || '127.0.0.1';
      util.checkPort(!config.INADDR_ANY && !host && config.socksPort, function() {
        socksServer.listen(config.socksPort, host, execCallback);
      });
      socksServer.useAuth(socks.auth.None());
    });
  }
  require('../biz/init')(proxyEvents, function(){
    server.on('request', app);
    execCallback();
  });
  return proxyEvents;
}

function exportInterfaces(obj) {
  obj.rules = rules;
  obj.util = util;
  obj.rulesUtil = rulesUtil;
  obj.httpsUtil = httpsUtil;
  obj.pluginMgr = pluginMgr;
  obj.logger = logger;
  obj.loadService = loadService;
  obj.setAuth = config.setAuth;
  obj.setUIHost = config.setUIHost;
  obj.setPluginUIHost = config.setPluginUIHost;
  obj.socketMgr = initSocketMgr;
  return obj;
}

process.on('uncaughtException', function(err){
  if (!err || err.code !== 'ERR_IPC_CHANNEL_CLOSED') {
    var stack = util.getErrorStack(err);
    fs.writeFileSync(path.join(process.cwd(), config.name + '.log'), '\r\n' + stack + '\r\n', {flag: 'a'});
    /*eslint no-console: "off"*/
    console.error(stack);
  }
  process.exit(1);
});

module.exports = exportInterfaces(proxy);
<|endoftext|>


<commit_before>define (["./_default-component-plugin"], function (DefaultPlugin) {
	var IgniteUIGridPlugin = IgniteUIGridPlugin || DefaultPlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getName: function () {
			return "igGrid";
		},
		_getWidgetName: function () {
			return "igGrid";
		},
		getMarkup: function (descriptor) {
			return "

";
		},
		getCodeEditorScriptSnippet: function (descriptor) {
			var code = "";
			var opts = descriptor.options;
			var lineCount = 7;
			var xtraMarkup = ",\n\t\t\t\t\tfeatures: [\n" + "\t\t\t\t\t]";
			//A.T. - we can either drop with no features in the code editor
			// or an empty array - empty arr makes it easier to manage with markers
			code = "\t\t\t\t$(\"#" + descriptor.id + "\").igGrid({\n" +
				"\t\t\t\t\theight: " + opts.height + ",\n" +
				"\t\t\t\t\twidth: " + opts.width + xtraMarkup;
			if (descriptor.data && window[descriptor.data]) {
				code += ",\n\t\t\t\t\tdataSource: " + descriptor.data;
			}
			var props = this.settings.packageInfo.components[descriptor.type].properties;
			for (var key in opts) {
				if (opts.hasOwnProperty(key) && key !== "dataSource" && key !== "height" && key !== "width") {
					if (props[key].type === "string") {
						code += ",\n\t\t\t\t\t" + key + ": \"" + opts[key] + "\"";
					} else {
						code += ",\n\t\t\t\t\t" + key + ": " + opts[key];
					}
					lineCount++;
				}
			}
			code += "\n\t\t\t\t});\n";
			return {codeString: code, lineCount: lineCount};
			//return this.evalTemplate("grid.code.js", descriptor);
		},
		addExtraMarkers: function (descriptor) {
			// we don't want to hardcode this value but find it in the current range
			// it may well happen that someone adds lots of options and extra code *above* the features or any other object
			var featuresRange = this.settings.editor.find("features", {start: descriptor.marker.range.start});
			featuresRange = new descriptor.rclass(featuresRange.start.row, 0, featuresRange.start.row + 1, 0);
			featuresRange.start = this.settings.editor.getSession().doc.createAnchor(featuresRange.start);
			featuresRange.end = this.settings.editor.getSession().doc.createAnchor(featuresRange.end);
			descriptor.marker.extraMarkers["features"] = {range: featuresRange};
		},
		/*
		render: function(descriptor) {
			// THIS IS WHERE WE PUT FULLY CUSTOM EDITORS FOR COMPONENTS
		},
		*/
		openPropertyEditor: function(descriptor) {
			// columns, features, dataSource, etc. - also reuse those UIs
			// when something gets changed in this editor, we want to also update the code editor as well as the component itself
			var p = descriptor.propName, packageInfo = this.settings.packageInfo, session = descriptor.editorSession, $this = this;
			if (p === "features") {
				// open features editor
				var list;
				var contents = $("
features editor
").appendTo("body").dialog({
					height: 400,
					width: 300,
					buttons: [
						{
							text: "Save", click: function() {
								// save features
								var elem;
								if (descriptor.iframe.jQuery) {
									elem = descriptor.iframe.jQuery($("#designer-frame").contents().find("#" + descriptor.element.attr("id")));
								} else {
									elem = descriptor.element;
								}
								// get list of enabled features
								var checkboxes = list.find("input:checked");
								// now iterate through the existing features, if the feature is already there, don't do anything
								// we need some object model to add/remove features easily
								// get the features string from the code editor
								// if there is none, create one
								// add new features
								// bring back the features to the code and update (recreate the grid)
								var gridCode = session.getTextRange(descriptor.codeMarker.range);
								//var gridObj = $this.toObject(gridCode);
								// check if there are extra markers associated with this object
								var fmarker = null;
								if (descriptor.codeMarker.extraMarkers && (fmarker = descriptor.codeMarker.extraMarkers["features"])) {
									// find the code inside of the marker and modify it
								} else {
									// there are no "features" defined, so we need to insert that
									// find out what the intentation is
									fmarker = descriptor.codeMarker.extraMarkers["features"] = {};
									//just construct the new code and insert it below the fmarker
									// features: [
									// 	<new code gets here>
									// ]
								}
								var opts = elem.data("igGrid")._originalOptions;
								// wipe features (TODO)
								opts.features = [];
								var featuresCode = "";
								var tabStr = "\t\t\t\t\t\t";
								var count = 0, featuresCount = checkboxes.length;
								checkboxes.each(function () {
									var name = $(this).closest("li").attr("data-name");
									opts.features.push({name: name});
									featuresCode += tabStr + "{ name: \"" + name + "\"}";
									if (count < featuresCount - 1) {
										featuresCode += ",\n";
									} else {
										featuresCode += "\n";
									}
									count++;
								});
								elem.igGrid("destroy");
								elem.igGrid(opts);
								// update code in the editor. replace features: [ ] with new stuff
								var newRange = new fmarker.range.constructor(fmarker.range.start.row + 1, 0, fmarker.range.end.row, 0);
								session.replace(newRange, featuresCode);
								//var featuresCode = session.getTextRange(fmarker.range);
								$(this).dialog("close");
							}
						},
						{
							text: "Close", click: function() {
								$(this).dialog("close");
							}
						}
					]
				});
				// add features to contents and attach actions
				list = $("

").appendTo(contents).addClass("list-group");
				var features = packageInfo.components[descriptor.type].properties.features; // TODO: be more defensive here
				if (!features.loaded) { // load the metadata for every feature, if it's not already loaded
					var featureNames = features.components;
					features.components = []; // we're overwriting the names with an associative array of objects
					for (var i = 0; i < featureNames.length; i++) {
						var featureName = featureNames[i];
						if (featureName) {
							try {
								var url = packageInfo.configPath + "/" + featureName + ".json";
								// load metadata for every feature
								var json = $.ajax({ // TODO: we could refactor this usage into a shared func on package info perhaps
									type: "GET",
									url: url,
									cache: true,
									dataType: "json",
									async: false
								});
								features.components[featureName] = $.parseJSON(json.responseText);
							} catch (e) {
								console.error("Could not load feature info for '" + featureName + "'. Error: " + e);
							}
						}
					}
					features.loaded = true;
				}
				for (featureName in features.components) {
					if (features.components.hasOwnProperty(featureName)) {
						var feature = features.components[featureName];
						var featureDataName = feature.name.substr(9);
						var item = $("

").appendTo(list).addClass("list-group-item")
							.text(feature.title).attr("data-name", featureDataName);
						$("<input type=\"checkbox\">").prependTo(item).css("margin-right", 20).attr("id", featureName);
						//$("").addClass("icon-cog").appendTo(item);
					}
				}
				// set default values
				var enabledFeatures;
				if (descriptor.iframe.jQuery && descriptor.iframe.jQuery(descriptor.element.data("igGrid"))) {
					enabledFeatures = descriptor.iframe.jQuery($("#designer-frame").contents().find("#" + descriptor.element.attr("id"))).data("igGrid").options.features;
				} else {
					enabledFeatures = descriptor.element.data("igGrid").options.features;
				}
				for (var i = 0; enabledFeatures && i < enabledFeatures.length; i++) {
					list.find("input[id=grid" + enabledFeatures[i].name.toLowerCase() + "]").attr("checked", true);
				}
				// add Ok and Cancel buttons
				/*
					// enable/disable a feature in the grid
					// this also means editing the markup in the editor
					// need to recreate the grid to enable / disable features?
					if ($(this).is(":checked")) {

					} else {

					}
				*/
				/*
					var buttonGroup = $("

").css("padding-left", 30).appendTo(contents);
					$("

").addClass("btn").addClass("btn-primary").addClass("ok-button-features").text("Save").appendTo(buttonGroup);
					$("

").addClass("btn").addClass("cancel-button-features").text("Cancel").appendTo(buttonGroup);
				*/
			} else if (p === "columns") {

			} else if (p === "dataSource") {

			}
		},
		_content: null,
		_wrapper: null,
		_headerLeft: null,
		renderSummary: function (container, descriptor) {
			var markup = ''
			markup += this._renderInteractions();
			markup += this._renderActions();
			markup += this._renderProperties();
			markup += this._renderCustomFooter();
			container.html(markup);
		},
		render: function (container, descriptor) {
			var content = container.closest('.adorner-content'),
				adorner = content.closest('.adorners');
			container.remove();
			if (!this._content) {
				this._content = adorner;
				this._wrapper = $('.adorner-wrapper');
				this._attachEvents(adorner, descriptor);
			}
		},
		_renderInteractions: function () {
			return '
INTERACTIONS
';
		},
		_renderActions: function () {
			return '
ACTIONS
Add ColumnAdd Row';
		},
		_renderProperties: function () {
			return '
PROPERTIES
';
		},
		_renderCustomFooter: function () {
			return '
All Events & Properties
';
		},
		_customizeHeader: function (descriptor) {
			var header = this._content.children('.adorner-header'),
				left = header.children('.adorner-hleft');
			this._headerLeft = left.html();
			left.html(this._renderCustomHeader(descriptor));
		},
		_renderCustomHeader: function (descriptor) {
			return ' Back';
		},
		_restoreHeader: function (descriptor) {
			var header = this._content.children('.adorner-header'),
				left = header.children('.adorner-hleft');
			left.html(this._headerLeft);
		},
		_attachEvents: function (adorner, descriptor) {
			var self = this;
			adorner.on('click', '.adorner-custom-action', function (event) {
				var action = $(this).attr('data-action');
				self._dispatchAction(action, descriptor);
				event.stopPropagation();
				return false;
			});
		},
		_dispatchAction: function (action, descriptor) {
			switch (action) {
			case 'add-column':
				this.addColumnAction(descriptor);
				break;
			case 'add-row':
				this.addRowAction(descriptor);
				break;
			case 'full-view':
				this.fullViewTransition(descriptor);
				break;
			case 'custom-view':
				this.customViewTransition(descriptor);
				break;
			default:
				break;
			}
		},
		addColumnAction: function (descriptor) {
			alert('Add Column Action triggered.');
		},
		addRowAction: function (descriptor) {
			alert('Add Row Action triggered.');
		},
		fullViewTransition: function (descriptor) {
			this._wrapper.animate({left: -250}, 250);
			this._customizeHeader(descriptor);
			//this._content.animate({left: 0}, 250);
		},
		customViewTransition: function (descriptor) {
			this._wrapper.animate({left: 0}, 250);
			this._restoreHeader();
		}
	});
	return IgniteUIGridPlugin;
});
<commit_msg>#160920 Fixing an issue with the event handlers for actions. Fixing the adorner content css to not be absolutely positioned with left<commit_after>define (["./_default-component-plugin"], function (DefaultPlugin) {
	var IgniteUIGridPlugin = IgniteUIGridPlugin || DefaultPlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getName: function () {
			return "igGrid";
		},
		_getWidgetName: function () {
			return "igGrid";
		},
		getMarkup: function (descriptor) {
			return "

";
		},
		getCodeEditorScriptSnippet: function (descriptor) {
			var code = "";
			var opts = descriptor.options;
			var lineCount = 7;
			var xtraMarkup = ",\n\t\t\t\t\tfeatures: [\n" + "\t\t\t\t\t]";
			//A.T. - we can either drop with no features in the code editor
			// or an empty array - empty arr makes it easier to manage with markers
			code = "\t\t\t\t$(\"#" + descriptor.id + "\").igGrid({\n" +
				"\t\t\t\t\theight: " + opts.height + ",\n" +
				"\t\t\t\t\twidth: " + opts.width + xtraMarkup;
			if (descriptor.data && window[descriptor.data]) {
				code += ",\n\t\t\t\t\tdataSource: " + descriptor.data;
			}
			var props = this.settings.packageInfo.components[descriptor.type].properties;
			for (var key in opts) {
				if (opts.hasOwnProperty(key) && key !== "dataSource" && key !== "height" && key !== "width") {
					if (props[key].type === "string") {
						code += ",\n\t\t\t\t\t" + key + ": \"" + opts[key] + "\"";
					} else {
						code += ",\n\t\t\t\t\t" + key + ": " + opts[key];
					}
					lineCount++;
				}
			}
			code += "\n\t\t\t\t});\n";
			return {codeString: code, lineCount: lineCount};
			//return this.evalTemplate("grid.code.js", descriptor);
		},
		addExtraMarkers: function (descriptor) {
			// we don't want to hardcode this value but find it in the current range
			// it may well happen that someone adds lots of options and extra code *above* the features or any other object
			var featuresRange = this.settings.editor.find("features", {start: descriptor.marker.range.start});
			featuresRange = new descriptor.rclass(featuresRange.start.row, 0, featuresRange.start.row + 1, 0);
			featuresRange.start = this.settings.editor.getSession().doc.createAnchor(featuresRange.start);
			featuresRange.end = this.settings.editor.getSession().doc.createAnchor(featuresRange.end);
			descriptor.marker.extraMarkers["features"] = {range: featuresRange};
		},
		/*
		render: function(descriptor) {
			// THIS IS WHERE WE PUT FULLY CUSTOM EDITORS FOR COMPONENTS
		},
		*/
		openPropertyEditor: function(descriptor) {
			// columns, features, dataSource, etc. - also reuse those UIs
			// when something gets changed in this editor, we want to also update the code editor as well as the component itself
			var p = descriptor.propName, packageInfo = this.settings.packageInfo, session = descriptor.editorSession, $this = this;
			if (p === "features") {
				// open features editor
				var list;
				var contents = $("
features editor
").appendTo("body").dialog({
					height: 400,
					width: 300,
					buttons: [
						{
							text: "Save", click: function() {
								// save features
								var elem;
								if (descriptor.iframe.jQuery) {
									elem = descriptor.iframe.jQuery($("#designer-frame").contents().find("#" + descriptor.element.attr("id")));
								} else {
									elem = descriptor.element;
								}
								// get list of enabled features
								var checkboxes = list.find("input:checked");
								// now iterate through the existing features, if the feature is already there, don't do anything
								// we need some object model to add/remove features easily
								// get the features string from the code editor
								// if there is none, create one
								// add new features
								// bring back the features to the code and update (recreate the grid)
								var gridCode = session.getTextRange(descriptor.codeMarker.range);
								//var gridObj = $this.toObject(gridCode);
								// check if there are extra markers associated with this object
								var fmarker = null;
								if (descriptor.codeMarker.extraMarkers && (fmarker = descriptor.codeMarker.extraMarkers["features"])) {
									// find the code inside of the marker and modify it
								} else {
									// there are no "features" defined, so we need to insert that
									// find out what the intentation is
									fmarker = descriptor.codeMarker.extraMarkers["features"] = {};
									//just construct the new code and insert it below the fmarker
									// features: [
									// 	<new code gets here>
									// ]
								}
								var opts = elem.data("igGrid")._originalOptions;
								// wipe features (TODO)
								opts.features = [];
								var featuresCode = "";
								var tabStr = "\t\t\t\t\t\t";
								var count = 0, featuresCount = checkboxes.length;
								checkboxes.each(function () {
									var name = $(this).closest("li").attr("data-name");
									opts.features.push({name: name});
									featuresCode += tabStr + "{ name: \"" + name + "\"}";
									if (count < featuresCount - 1) {
										featuresCode += ",\n";
									} else {
										featuresCode += "\n";
									}
									count++;
								});
								elem.igGrid("destroy");
								elem.igGrid(opts);
								// update code in the editor. replace features: [ ] with new stuff
								var newRange = new fmarker.range.constructor(fmarker.range.start.row + 1, 0, fmarker.range.end.row, 0);
								session.replace(newRange, featuresCode);
								//var featuresCode = session.getTextRange(fmarker.range);
								$(this).dialog("close");
							}
						},
						{
							text: "Close", click: function() {
								$(this).dialog("close");
							}
						}
					]
				});
				// add features to contents and attach actions
				list = $("

").appendTo(contents).addClass("list-group");
				var features = packageInfo.components[descriptor.type].properties.features; // TODO: be more defensive here
				if (!features.loaded) { // load the metadata for every feature, if it's not already loaded
					var featureNames = features.components;
					features.components = []; // we're overwriting the names with an associative array of objects
					for (var i = 0; i < featureNames.length; i++) {
						var featureName = featureNames[i];
						if (featureName) {
							try {
								var url = packageInfo.configPath + "/" + featureName + ".json";
								// load metadata for every feature
								var json = $.ajax({ // TODO: we could refactor this usage into a shared func on package info perhaps
									type: "GET",
									url: url,
									cache: true,
									dataType: "json",
									async: false
								});
								features.components[featureName] = $.parseJSON(json.responseText);
							} catch (e) {
								console.error("Could not load feature info for '" + featureName + "'. Error: " + e);
							}
						}
					}
					features.loaded = true;
				}
				for (featureName in features.components) {
					if (features.components.hasOwnProperty(featureName)) {
						var feature = features.components[featureName];
						var featureDataName = feature.name.substr(9);
						var item = $("

").appendTo(list).addClass("list-group-item")
							.text(feature.title).attr("data-name", featureDataName);
						$("<input type=\"checkbox\">").prependTo(item).css("margin-right", 20).attr("id", featureName);
						//$("").addClass("icon-cog").appendTo(item);
					}
				}
				// set default values
				var enabledFeatures;
				if (descriptor.iframe.jQuery && descriptor.iframe.jQuery(descriptor.element.data("igGrid"))) {
					enabledFeatures = descriptor.iframe.jQuery($("#designer-frame").contents().find("#" + descriptor.element.attr("id"))).data("igGrid").options.features;
				} else {
					enabledFeatures = descriptor.element.data("igGrid").options.features;
				}
				for (var i = 0; enabledFeatures && i < enabledFeatures.length; i++) {
					list.find("input[id=grid" + enabledFeatures[i].name.toLowerCase() + "]").attr("checked", true);
				}
				// add Ok and Cancel buttons
				/*
					// enable/disable a feature in the grid
					// this also means editing the markup in the editor
					// need to recreate the grid to enable / disable features?
					if ($(this).is(":checked")) {

					} else {

					}
				*/
				/*
					var buttonGroup = $("

").css("padding-left", 30).appendTo(contents);
					$("

").addClass("btn").addClass("btn-primary").addClass("ok-button-features").text("Save").appendTo(buttonGroup);
					$("

").addClass("btn").addClass("cancel-button-features").text("Cancel").appendTo(buttonGroup);
				*/
			} else if (p === "columns") {

			} else if (p === "dataSource") {

			}
		},
		_content: null,
		_wrapper: null,
		_headerLeft: null,
		renderSummary: function (container, descriptor) {
			var markup = ''
			markup += this._renderInteractions();
			markup += this._renderActions();
			markup += this._renderProperties();
			markup += this._renderCustomFooter();
			container.html(markup);
		},
		render: function (container, descriptor) {
			var content = container.closest('.adorner-content'),
				adorner = content.closest('.adorners');
			container.remove();
			if (!this._content) {
				this._content = adorner;
				this._wrapper = $('.adorner-wrapper');
				this._attachEvents(adorner, descriptor);
			}
		},
		_renderInteractions: function () {
			return '
INTERACTIONS
';
		},
		_renderActions: function () {
			return '
ACTIONS
Add ColumnAdd Row';
		},
		_renderProperties: function () {
			return '
PROPERTIES
';
		},
		_renderCustomFooter: function () {
			return '
All Events & Properties
';
		},
		_customizeHeader: function (descriptor) {
			var header = this._content.children('.adorner-header'),
				left = header.children('.adorner-hleft');
			this._headerLeft = left.html();
			left.html(this._renderCustomHeader(descriptor));
		},
		_renderCustomHeader: function (descriptor) {
			return ' Back';
		},
		_restoreHeader: function (descriptor) {
			var header = this._content.children('.adorner-header'),
				left = header.children('.adorner-hleft');
			left.html(this._headerLeft);
		},
		_attachEvents: function (adorner, descriptor) {
			var self = this;
			adorner.off();
			adorner.on('click', '.adorner-custom-action', function (event) {
				var action = $(this).attr('data-action');
				if (self[action]) {
					self[action](descriptor);
				}
				event.stopPropagation();
				return false;
			});
		},
		addColumn: function (descriptor) {
			alert('Add Column Action triggered.');
		},
		addRow: function (descriptor) {
			alert('Add Row Action triggered.');
		},
		summaryView: function (descriptor) {
			this._wrapper.animate({left: -250}, 250);
			this._customizeHeader(descriptor);
		},
		customView: function (descriptor) {
			this._wrapper.animate({left: 0}, 250);
			this._restoreHeader();
		}
	});
	return IgniteUIGridPlugin;
});
<|endoftext|>


<commit_before>exports.utils = require('./utils');
exports.Network = require('./network');
exports.VM = require('./vm');
exports.Block = require('./block');
exports.Blockchain = require('./blockchain');
exports.Transaction = require('./transaction');
exports.Account = require('./account');
exports.rlp = require('rlp');
exports.Trie = require('merkle-patricia-tree');
<commit_msg>add bloom<commit_after>exports.utils = require('./utils');
exports.Network = require('./network');
exports.VM = require('./vm');
exports.Block = require('./block');
exports.Blockchain = require('./blockchain');
exports.Transaction = require('./transaction');
exports.Account = require('./account');
exports.rlp = require('rlp');
exports.Trie = require('merkle-patricia-tree');
exports.bloom = require('./bloom.js');
<|endoftext|>


<commit_before>/*!
 * Float Labels
 *
 * @version: 3.2.1
 * @author: Paul Ryley (http://geminilabs.io)
 * @url: https://geminilabs.github.io/float-labels.js
 * @license: MIT
 */

/** global: NodeList, Option */

;(function( window, document, undefined )
{
	"use strict";

	var Plugin = function( el, options )
	{
		this.el = this.isString( el ) ? document.querySelectorAll( el ) : el;
		if( !NodeList.prototype.isPrototypeOf( this.el ))return;
		this.config = [];
		this.options = options;
		this.selectors = [];
		this.init();
		this.destroy = function() {
			this.loop( function( el ) {
				el.removeEventListener( 'reset', this.events.reset );
				this.removeClasses( el );
			}, function( field ) {
				this.reset( field );
			});
		};
		this.rebuild = function() {
			this.loop( null, function( field ) {
				this.floatLabel( field, true );
			});
		};
	};

	Plugin.prototype = {

		defaults: {
			customEvent: null,
			customLabel: null,
			customPlaceholder: null,
			exclude: '.no-label',
			inputRegex: /email|number|password|search|tel|text|url/,
			prefix: 'fl-',
			prioritize: 'label', // label|placeholder
			requiredClass: 'required',
			style: 0, // 0|1|2
			transform: 'input,select,textarea'
		},

		/** @return void */
		init: function()
		{
			this.initEvents();
			this.loop( function( el, i ) {
				var style = this.config[i].style;
				el.addEventListener( 'reset', this.events.reset );
				el.classList.add( this.prefixed( 'form' ));
				if( style ) {
					el.classList.add( this.prefixed( 'style-' + style ));
				}
			}, function( field ) {
				this.floatLabel( field );
			});
		},

		/** @return void */
		initEvents: function()
		{
			this.events = {
				blur: this.onBlur.bind( this ),
				change: this.onInput.bind( this ),
				focus: this.onFocus.bind( this ),
				input: this.onInput.bind( this ),
				reset: this.onReset.bind( this ),
			};
		},

		/** @return null|void */
		build: function( el )
		{
			var labelEl = this.getLabel( el );
			if( !labelEl )return;
			el.classList.add( this.prefixed( el.tagName.toLowerCase() ));
			this.setLabel( labelEl, el );
			this.setPlaceholder( labelEl, el );
			this.wrapLabel( labelEl, el );
			this.handleEvents( el, 'add' );
			if( typeof this.config[this.current].customEvent === 'function' ) {
				this.config[this.current].customEvent.call( this, el );
			}
		},

		/** @return Element */
		createEl: function( tag, attributes )
		{
			var el = ( typeof tag === 'string' ) ? document.createElement( tag ) : tag;
			attributes = attributes || {};
			for( var key in attributes ) {
				if( !attributes.hasOwnProperty( key ))continue;
				el.setAttribute( key, attributes[key] );
			}
			return el;
		},

		/** @return object */
		extend: function()
		{
			var args = [].slice.call( arguments );
			var result = args[0];
			var extenders = args.slice(1);
			Object.keys( extenders ).forEach( function( i ) {
				for( var key in extenders[i] ) {
					if( !extenders[i].hasOwnProperty( key ))continue;
					result[key] = extenders[i][key];
				}
			});
			return result;
		},

		/** @return null|void */
		floatLabel: function( el, rebuild )
		{
			if( !el.getAttribute( 'id' ) || (
				el.tagName === 'INPUT' && !this.config[this.current].inputRegex.test( el.getAttribute( 'type' ))
			))return;
			if( this.hasParent( el )) {
				if( rebuild !== true )return;
				this.reset( el );
			}
			this.build( el );
		},

		/** @return string|false */
		getLabel: function( el )
		{
			var label = 'label[for="' + el.getAttribute( 'id' ) + '"]';
			var labelEl = this.el[this.current].querySelectorAll( label );
			// check for multiple labels with identical 'for' attributes
			if( labelEl.length > 1 ) {
				labelEl = el.parentNode.querySelectorAll( label );
			}
			if( labelEl.length === 1 ) {
				return labelEl[0];
			}
			return false;
		},

		/** @return string */
		getLabelText: function( labelEl, el )
		{
			var labelText = labelEl.textContent.replace( /[*:]/g, '' ).trim();
			var placeholderText = el.getAttribute( 'placeholder' );
			if( !labelText || ( labelText && placeholderText && this.config[this.current].prioritize === 'placeholder' )) {
				labelText = placeholderText;
			}
			return labelText;
		},

		/** @return void */
		handleEvents: function( el, action )
		{
			var events = this.events;
			['blur','input','focus'].forEach( function( event ) {
				if( el.type === 'file' && event === 'input' ) {
					event = 'change';
				}
				el[ action + 'EventListener']( event, events[event] );
			});
		},

		/** @return bool */
		hasParent: function( el )
		{
			return el.parentNode.classList.contains( this.prefixed( 'wrap' ));
		},

		/** @return bool */
		isString: function( str ) {
			return Object.prototype.toString.call( str ) === "[object String]";
		},

		/** @return void */
		loop: function( elCallback, fieldCallback ) {
			for( var i = 0; i < this.el.length; ++i ) {
				if( typeof this.selectors[i] === 'undefined' ) {
					var config = this.extend( {}, this.defaults, this.options, this.el[i].getAttribute( 'data-options' ));
					var exclude = ':not(' + config.exclude.split( /[\s,]+/ ).join( '):not(' ) + ')';
					this.selectors[i] = config.transform.replace( /,/g, exclude + ',' ) + exclude;
					this.config[i] = config;
				}
				var fields = this.el[i].querySelectorAll( this.selectors[i] );
				this.current = i;
				if( typeof elCallback === 'function' ) {
					elCallback.call( this, this.el[i], i );
				}
				for( var x = 0; x < fields.length; ++x ) {
					if( typeof fieldCallback === 'function' ) {
						fieldCallback.call( this, fields[x], i );
					}
				}
			}
		},

		/** @return void */
		onBlur: function( ev )
		{
			ev.target.parentNode.classList.remove( this.prefixed( 'has-focus' ));
		},

		/** @return void */
		onInput: function( ev )
		{
			var event = ev.target.value.length ? 'add' : 'remove';
			ev.target.parentNode.classList[event]( this.prefixed( 'is-active' ));
		},

		/** @return void */
		onFocus: function( ev )
		{
			ev.target.parentNode.classList.add( this.prefixed( 'has-focus' ));
		},

		/** @return void */
		onReset: function()
		{
			var fields = this.el[this.current].querySelectorAll( this.selectors[this.current] );
			for( var i = 0; i < fields.length; ++i ) {
				fields[i].parentNode.classList.remove( this.prefixed( 'is-active' ));
			}
		},

		/** @return string */
		prefixed: function( value )
		{
			return this.config[this.current].prefix + value;
		},

		/** @return void */
		removeClasses: function( el )
		{
			var prefix = this.config[this.current].prefix;
			var classes = el.className.split( ' ' ).filter( function( c ) {
				return c.lastIndexOf( prefix, 0 ) !== 0;
			});
			el.className = classes.join( ' ' ).trim();
		},

		/** @return null|void */
		reset: function( el )
		{
			var parent = el.parentNode;
			if( !this.hasParent( el ))return;
			var fragment = document.createDocumentFragment();
			while( parent.firstElementChild ) {
				var childEl = parent.firstElementChild;
				this.removeClasses( childEl );
				fragment.appendChild( childEl );
			}
			parent.parentNode.replaceChild( fragment, parent );
			this.resetPlaceholder( el );
			this.handleEvents( el, 'remove' );
		},

		/** @return void */
		resetPlaceholder: function( el )
		{
			var dataPlaceholder = 'data-placeholder';
			var originalPlaceholder = el.getAttribute( dataPlaceholder );
			if( originalPlaceholder !== null ) {
				el.removeAttribute( dataPlaceholder );
				el.setAttribute( 'placeholder', originalPlaceholder );
			}
		},

		/** @return void */
		setLabel: function( labelEl, el )
		{
			labelEl.classList.add( this.prefixed( 'label' ));
			labelEl.textContent = this.getLabelText( labelEl, el );
			if( typeof this.config[this.current].customLabel === 'function' ) {
				labelEl.textContent = this.config[this.current].customLabel.call( this, labelEl, el );
			}
		},

		/** @return void */
		setPlaceholder: function( labelEl, el )
		{
			var placeholderText = el.getAttribute( 'placeholder' );
			if( this.config[this.current].prioritize === 'label' || !placeholderText ) {
				if( placeholderText ) {
					el.setAttribute( 'data-placeholder', placeholderText );
				}
				placeholderText = this.getLabelText( labelEl, el );
			}
			if( typeof this.config[this.current].customPlaceholder === 'function' ) {
				placeholderText = this.config[this.current].customPlaceholder.call( this, placeholderText, el, labelEl );
			}
			if( el.tagName === 'SELECT' ) {
				this.setSelectPlaceholder( el, placeholderText );
			}
			else {
				el.setAttribute( 'placeholder', placeholderText );
			}
		},

		/** @return void */
		setSelectPlaceholder: function( el, placeholderText )
		{
			var childEl = el.firstElementChild;
			if( childEl.hasAttribute( 'value' ) && childEl.value ) {
				el.insertBefore( new Option( placeholderText, '', true, true ), childEl );
			}
			else {
				childEl.setAttribute( 'value', '' );
			}
			if( childEl.textContent === '' ) {
				childEl.textContent = placeholderText;
			}
		},

		/** @return void */
		wrapLabel: function( labelEl, el )
		{
			var wrapper = this.createEl( 'div', {
				class: this.prefixed( 'wrap' ) + ' ' + this.prefixed( 'wrap-' + el.tagName.toLowerCase() ),
			});
			if( el.hasAttribute( 'value' ) && el.value.length ) {
				wrapper.classList.add( this.prefixed( 'is-active' ));
			}
			if( el.getAttribute( 'required' ) !== null || el.classList.contains( this.config[this.current].requiredClass )) {
				wrapper.classList.add( this.prefixed( 'is-required' ));
			}
			el.parentNode.insertBefore( wrapper, el );
			wrapper.appendChild( labelEl );
			wrapper.appendChild( el );
		},
	};

	window.FloatLabels = Plugin;

})( window, document );
<commit_msg>Handle inputs that have a value without the value attribute (#14)<commit_after>/*!
 * Float Labels
 *
 * @version: 3.2.1
 * @author: Paul Ryley (http://geminilabs.io)
 * @url: https://geminilabs.github.io/float-labels.js
 * @license: MIT
 */

/** global: NodeList, Option */

;(function( window, document, undefined )
{
	"use strict";

	var Plugin = function( el, options )
	{
		this.el = this.isString( el ) ? document.querySelectorAll( el ) : el;
		if( !NodeList.prototype.isPrototypeOf( this.el ))return;
		this.config = [];
		this.options = options;
		this.selectors = [];
		this.init();
		this.destroy = function() {
			this.loop( function( el ) {
				el.removeEventListener( 'reset', this.events.reset );
				this.removeClasses( el );
			}, function( field ) {
				this.reset( field );
			});
		};
		this.rebuild = function() {
			this.loop( null, function( field ) {
				this.floatLabel( field, true );
			});
		};
	};

	Plugin.prototype = {

		defaults: {
			customEvent: null,
			customLabel: null,
			customPlaceholder: null,
			exclude: '.no-label',
			inputRegex: /email|number|password|search|tel|text|url/,
			prefix: 'fl-',
			prioritize: 'label', // label|placeholder
			requiredClass: 'required',
			style: 0, // 0|1|2
			transform: 'input,select,textarea'
		},

		/** @return void */
		init: function()
		{
			this.initEvents();
			this.loop( function( el, i ) {
				var style = this.config[i].style;
				el.addEventListener( 'reset', this.events.reset );
				el.classList.add( this.prefixed( 'form' ));
				if( style ) {
					el.classList.add( this.prefixed( 'style-' + style ));
				}
			}, function( field ) {
				this.floatLabel( field );
			});
		},

		/** @return void */
		initEvents: function()
		{
			this.events = {
				blur: this.onBlur.bind( this ),
				change: this.onInput.bind( this ),
				focus: this.onFocus.bind( this ),
				input: this.onInput.bind( this ),
				reset: this.onReset.bind( this ),
			};
		},

		/** @return null|void */
		build: function( el )
		{
			var labelEl = this.getLabel( el );
			if( !labelEl )return;
			el.classList.add( this.prefixed( el.tagName.toLowerCase() ));
			this.setLabel( labelEl, el );
			this.setPlaceholder( labelEl, el );
			this.wrapLabel( labelEl, el );
			this.handleEvents( el, 'add' );
			if( typeof this.config[this.current].customEvent === 'function' ) {
				this.config[this.current].customEvent.call( this, el );
			}
		},

		/** @return Element */
		createEl: function( tag, attributes )
		{
			var el = ( typeof tag === 'string' ) ? document.createElement( tag ) : tag;
			attributes = attributes || {};
			for( var key in attributes ) {
				if( !attributes.hasOwnProperty( key ))continue;
				el.setAttribute( key, attributes[key] );
			}
			return el;
		},

		/** @return object */
		extend: function()
		{
			var args = [].slice.call( arguments );
			var result = args[0];
			var extenders = args.slice(1);
			Object.keys( extenders ).forEach( function( i ) {
				for( var key in extenders[i] ) {
					if( !extenders[i].hasOwnProperty( key ))continue;
					result[key] = extenders[i][key];
				}
			});
			return result;
		},

		/** @return null|void */
		floatLabel: function( el, rebuild )
		{
			if( !el.getAttribute( 'id' ) || (
				el.tagName === 'INPUT' && !this.config[this.current].inputRegex.test( el.getAttribute( 'type' ))
			))return;
			if( this.hasParent( el )) {
				if( rebuild !== true )return;
				this.reset( el );
			}
			this.build( el );
		},

		/** @return string|false */
		getLabel: function( el )
		{
			var label = 'label[for="' + el.getAttribute( 'id' ) + '"]';
			var labelEl = this.el[this.current].querySelectorAll( label );
			// check for multiple labels with identical 'for' attributes
			if( labelEl.length > 1 ) {
				labelEl = el.parentNode.querySelectorAll( label );
			}
			if( labelEl.length === 1 ) {
				return labelEl[0];
			}
			return false;
		},

		/** @return string */
		getLabelText: function( labelEl, el )
		{
			var labelText = labelEl.textContent.replace( /[*:]/g, '' ).trim();
			var placeholderText = el.getAttribute( 'placeholder' );
			if( !labelText || ( labelText && placeholderText && this.config[this.current].prioritize === 'placeholder' )) {
				labelText = placeholderText;
			}
			return labelText;
		},

		/** @return void */
		handleEvents: function( el, action )
		{
			var events = this.events;
			['blur','input','focus'].forEach( function( event ) {
				if( el.type === 'file' && event === 'input' ) {
					event = 'change';
				}
				el[ action + 'EventListener']( event, events[event] );
			});
		},

		/** @return bool */
		hasParent: function( el )
		{
			return el.parentNode.classList.contains( this.prefixed( 'wrap' ));
		},

		/** @return bool */
		isString: function( str ) {
			return Object.prototype.toString.call( str ) === "[object String]";
		},

		/** @return void */
		loop: function( elCallback, fieldCallback ) {
			for( var i = 0; i < this.el.length; ++i ) {
				if( typeof this.selectors[i] === 'undefined' ) {
					var config = this.extend( {}, this.defaults, this.options, this.el[i].getAttribute( 'data-options' ));
					var exclude = ':not(' + config.exclude.split( /[\s,]+/ ).join( '):not(' ) + ')';
					this.selectors[i] = config.transform.replace( /,/g, exclude + ',' ) + exclude;
					this.config[i] = config;
				}
				var fields = this.el[i].querySelectorAll( this.selectors[i] );
				this.current = i;
				if( typeof elCallback === 'function' ) {
					elCallback.call( this, this.el[i], i );
				}
				for( var x = 0; x < fields.length; ++x ) {
					if( typeof fieldCallback === 'function' ) {
						fieldCallback.call( this, fields[x], i );
					}
				}
			}
		},

		/** @return void */
		onBlur: function( ev )
		{
			ev.target.parentNode.classList.remove( this.prefixed( 'has-focus' ));
		},

		/** @return void */
		onInput: function( ev )
		{
			var event = ev.target.value.length ? 'add' : 'remove';
			ev.target.parentNode.classList[event]( this.prefixed( 'is-active' ));
		},

		/** @return void */
		onFocus: function( ev )
		{
			ev.target.parentNode.classList.add( this.prefixed( 'has-focus' ));
		},

		/** @return void */
		onReset: function()
		{
			var fields = this.el[this.current].querySelectorAll( this.selectors[this.current] );
			for( var i = 0; i < fields.length; ++i ) {
				fields[i].parentNode.classList.remove( this.prefixed( 'is-active' ));
			}
		},

		/** @return string */
		prefixed: function( value )
		{
			return this.config[this.current].prefix + value;
		},

		/** @return void */
		removeClasses: function( el )
		{
			var prefix = this.config[this.current].prefix;
			var classes = el.className.split( ' ' ).filter( function( c ) {
				return c.lastIndexOf( prefix, 0 ) !== 0;
			});
			el.className = classes.join( ' ' ).trim();
		},

		/** @return null|void */
		reset: function( el )
		{
			var parent = el.parentNode;
			if( !this.hasParent( el ))return;
			var fragment = document.createDocumentFragment();
			while( parent.firstElementChild ) {
				var childEl = parent.firstElementChild;
				this.removeClasses( childEl );
				fragment.appendChild( childEl );
			}
			parent.parentNode.replaceChild( fragment, parent );
			this.resetPlaceholder( el );
			this.handleEvents( el, 'remove' );
		},

		/** @return void */
		resetPlaceholder: function( el )
		{
			var dataPlaceholder = 'data-placeholder';
			var originalPlaceholder = el.getAttribute( dataPlaceholder );
			if( originalPlaceholder !== null ) {
				el.removeAttribute( dataPlaceholder );
				el.setAttribute( 'placeholder', originalPlaceholder );
			}
		},

		/** @return void */
		setLabel: function( labelEl, el )
		{
			labelEl.classList.add( this.prefixed( 'label' ));
			labelEl.textContent = this.getLabelText( labelEl, el );
			if( typeof this.config[this.current].customLabel === 'function' ) {
				labelEl.textContent = this.config[this.current].customLabel.call( this, labelEl, el );
			}
		},

		/** @return void */
		setPlaceholder: function( labelEl, el )
		{
			var placeholderText = el.getAttribute( 'placeholder' );
			if( this.config[this.current].prioritize === 'label' || !placeholderText ) {
				if( placeholderText ) {
					el.setAttribute( 'data-placeholder', placeholderText );
				}
				placeholderText = this.getLabelText( labelEl, el );
			}
			if( typeof this.config[this.current].customPlaceholder === 'function' ) {
				placeholderText = this.config[this.current].customPlaceholder.call( this, placeholderText, el, labelEl );
			}
			if( el.tagName === 'SELECT' ) {
				this.setSelectPlaceholder( el, placeholderText );
			}
			else {
				el.setAttribute( 'placeholder', placeholderText );
			}
		},

		/** @return void */
		setSelectPlaceholder: function( el, placeholderText )
		{
			var childEl = el.firstElementChild;
			if( childEl.hasAttribute( 'value' ) && childEl.value ) {
				el.insertBefore( new Option( placeholderText, '', true, true ), childEl );
			}
			else {
				childEl.setAttribute( 'value', '' );
			}
			if( childEl.textContent === '' ) {
				childEl.textContent = placeholderText;
			}
		},

		/** @return void */
		wrapLabel: function( labelEl, el )
		{
			var wrapper = this.createEl( 'div', {
				class: this.prefixed( 'wrap' ) + ' ' + this.prefixed( 'wrap-' + el.tagName.toLowerCase() ),
			});
			if( el.value !== undefined && el.value.length ) {
				wrapper.classList.add( this.prefixed( 'is-active' ));
			}
			if( el.getAttribute( 'required' ) !== null || el.classList.contains( this.config[this.current].requiredClass )) {
				wrapper.classList.add( this.prefixed( 'is-required' ));
			}
			el.parentNode.insertBefore( wrapper, el );
			wrapper.appendChild( labelEl );
			wrapper.appendChild( el );
		},
	};

	window.FloatLabels = Plugin;

})( window, document );
<|endoftext|>


<commit_before>var Exercise = require('./exercise');
var Food = require('./food');

$(document).ready(function() {

  var holdFoods = document.getElementById("hold-foods-table");
  var holdExercises = document.getElementById("hold-exercises-table");
  var exercises = JSON.parse(localStorage.getItem("hold-exercises-table"));
  var foods = JSON.parse(localStorage.getItem('hold-foods-table'));
  var addBreakfast = document.getElementById("add-breakfast");
  var addLunch = document.getElementById("add-lunch");
  var addDinner = document.getElementById("add-dinner");
  var addSnacks = document.getElementById("add-snack");
  var addExercises = document.getElementById("add-exercise");
  var holdBreakfast = document.getElementById("breakfast-table");
  var holdLunch = document.getElementById("lunch-table");
  var holdDinner = document.getElementById("dinner-table");
  var holdSnacks = document.getElementById("snack-table");
  var holdCompletedExercises = document.getElementById("completed-exercise-table");
  var dateBlock = document.getElementById("date-holder");

  $(addBreakfast).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdBreakfast);
  });

  $(addLunch).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdLunch);
  });

  $(addDinner).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdDinner);
  });

  $(addSnacks).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdSnacks);
  });

  $(addExercises).on("click", function(e){
    var selectedExercises = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedExercises, holdCompletedExercises);
    storeDay(dateBlock.innerHTML);
  });

  function setTableItems(selectedItems, specificTable){
    for (var i = 0; i <= Object.keys(selectedItems).length; i++) {
      var specificRow = selectedItems[i]
      specificTable.innerHTML += specificRow.innerHTML;
      var dateBlock = document.getElementById("date-holder");
      storeDay(dateBlock.innerHTML);
    };
  };

  var storeDay = function(date) {
    var diaryJSON = localStorage.getItem('diary');
    if(diaryJSON === null){
      diaryJSON = '{}';
    }
    var allDays = JSON.parse(diaryJSON);

    var breakfastArray = $('#breakfast-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var lunchArray = $('#lunch-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var dinnerArray = $('#dinner-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var snacksArray = $('#snack-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var exerciseArray = $('#exercises-table tr').slice(1).map(function(index, row){
      var exerciseName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: exerciseName, calories: calories};
    })

    allDays[date]["breakfast"] = breakfastArray;
    allDays[date]["lunch"] = lunchArray;
    allDays[date]["dinner"] = dinnerArray;
    allDays[date]["snacks"] = snacksArray;
    allDays[date]["exercises"] = exerciseArray;
    debugger
    diaryJSON = JSON.stringify(allDays);
    localStorage.setItem('diary', diaryJSON);
  };

  function displayDate() {
    var today = new Date();
    today.setDate(today.getDate());
    dateBlock.innerHTML = today.toLocaleDateString();
    storeDay(dateBlock.innerHTML);
  };

  function nextDate() {
    var date = new Date();

    $("#next-day").on("click", function(e){
      date.setDate(date.getDate() + 1);
      document.getElementById('date-holder').innerHTML = date.toLocaleDateString();
    });

    $("#previous-day").on("click", function(e){
      date.setDate(date.getDate() - 1);
      document.getElementById('date-holder').innerHTML = date.toLocaleDateString();
    });

  };

  function setFood(){
    for (var i = 1; i <= Object.keys(foods).length; i++) {
      holdFoods.innerHTML += "
<input type='checkbox' id='foods-checkbox'/>" + " " + foods[i].food + "	" + foods[i].calories + "
";
    }
  };

  function setExercises(){
    for (var i = 1; i <= Object.keys(exercises).length; i++) {
      holdExercises.innerHTML += "
<input type='checkbox' id='exercises-checkbox'/>" + " " + exercises[i].exercise + "	" + exercises[i].calories + "
";
    }
  };

  displayDate();
  nextDate();
  setFood();
  setExercises();

});
<commit_msg>data is storing properly to localStorage<commit_after>var Exercise = require('./exercise');
var Food = require('./food');

$(document).ready(function() {

  var holdFoods = document.getElementById("hold-foods-table");
  var holdExercises = document.getElementById("hold-exercises-table");
  var exercises = JSON.parse(localStorage.getItem("hold-exercises-table"));
  var foods = JSON.parse(localStorage.getItem('hold-foods-table'));
  var addBreakfast = document.getElementById("add-breakfast");
  var addLunch = document.getElementById("add-lunch");
  var addDinner = document.getElementById("add-dinner");
  var addSnacks = document.getElementById("add-snack");
  var addExercises = document.getElementById("add-exercise");
  var holdBreakfast = document.getElementById("breakfast-table");
  var holdLunch = document.getElementById("lunch-table");
  var holdDinner = document.getElementById("dinner-table");
  var holdSnacks = document.getElementById("snack-table");
  var holdCompletedExercises = document.getElementById("completed-exercise-table");
  var dateBlock = document.getElementById("date-holder");

  $(addBreakfast).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdBreakfast);
  });

  $(addLunch).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdLunch);
  });

  $(addDinner).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdDinner);
  });

  $(addSnacks).on("click", function(e){
    var selectedFoods = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedFoods, holdSnacks);
  });

  $(addExercises).on("click", function(e){
    var selectedExercises = $('input[type=checkbox]:checked').parent().parent();
    setTableItems(selectedExercises, holdCompletedExercises);
    storeDay(dateBlock.innerHTML);
  });

  function setTableItems(selectedItems, specificTable){
    for (var i = 0; i <= Object.keys(selectedItems).length; i++) {
      var specificRow = selectedItems[i]
      specificTable.innerHTML += specificRow.innerHTML;
      var dateBlock = document.getElementById("date-holder");
      storeDay(dateBlock.innerHTML);
    };
  };

  var storeDay = function(date) {
    var diaryJSON = localStorage.getItem('diary');
    if(diaryJSON === null){
      diaryJSON = '{}';
    }
    var allDays = JSON.parse(diaryJSON);

    var breakfastArray = $('#breakfast-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var lunchArray = $('#lunch-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var dinnerArray = $('#dinner-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var snacksArray = $('#snack-table tr').slice(1).map(function(index, row){
      var foodName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: foodName, calories: calories};
    })

    var exerciseArray = $('#exercises-table tr').slice(1).map(function(index, row){
      var exerciseName = row.cells[0].textContent;
      var calories = row.cells[1].textContent;
      return {name: exerciseName, calories: calories};
    })

    allDays[date]["breakfast"] = JSON.stringify(breakfastArray[0]);
    allDays[date]["lunch"] = JSON.stringify(lunchArray[0]);
    allDays[date]["dinner"] = JSON.stringify(dinnerArray[0]);
    allDays[date]["snacks"] = JSON.stringify(snacksArray[0]);
    allDays[date]["exercises"] = JSON.stringify(exerciseArray[0]);
    diaryJSON = JSON.stringify(allDays);
    localStorage.setItem('diary', diaryJSON);
    debugger
  };

  function displayDate() {
    var today = new Date();
    today.setDate(today.getDate());
    dateBlock.innerHTML = today.toLocaleDateString();
    storeDay(dateBlock.innerHTML);
  };

  function nextDate() {
    var date = new Date();

    $("#next-day").on("click", function(e){
      date.setDate(date.getDate() + 1);
      document.getElementById('date-holder').innerHTML = date.toLocaleDateString();
      storeDay(dateBlock.innerHTML);
    });

    $("#previous-day").on("click", function(e){
      date.setDate(date.getDate() - 1);
      document.getElementById('date-holder').innerHTML = date.toLocaleDateString();
      storeDay(dateBlock.innerHTML);
    });

  };

  function setFood(){
    for (var i = 1; i <= Object.keys(foods).length; i++) {
      holdFoods.innerHTML += "
<input type='checkbox' id='foods-checkbox'/>" + " " + foods[i].food + "	" + foods[i].calories + "
";
    }
  };

  function setExercises(){
    for (var i = 1; i <= Object.keys(exercises).length; i++) {
      holdExercises.innerHTML += "
<input type='checkbox' id='exercises-checkbox'/>" + " " + exercises[i].exercise + "	" + exercises[i].calories + "
";
    }
  };

  displayDate();
  nextDate();
  setFood();
  setExercises();

});
<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    naming = require('bem-naming'),
    PassThrough = require('stream').PassThrough,
    sep = path.sep;

function nested(item, add, walk, done) {
    var basename = item.basename,
        filename = item.filename,
        parent = path.basename(item.dirname),
        grandParent = path.basename(path.dirname(item.dirname)),
        depth = filename.split(sep).length - item.level.split(sep).length;

    if ((depth === 1 && naming.isBlock(item.notation)) ||
        (depth === 2 && naming.isBlockMod(parent + basename)) ||
        (depth === 2 && naming.isElem(parent + basename)) ||
        (depth === 3 && naming.isElemMod(grandParent + parent + basename))
    ) {
        return walk(filename, done);
    }

    add(item);
    done();
}

module.exports = function (levels) {
    var output = new PassThrough({ objectMode: true });

    function scan(level, callback) {
        var entities = {};

        walk(level, callback);

        function walk(dir, callback) {
            fs.readdir(dir, function (err, items) {
                if (err) { return; }

                var n = 0,
                    l = items.length;

                for (var i = 0; i < l; ++i) {
                    var basename = items[i],
                        filename = path.join(dir, basename),
                        splited = basename.split('.'),
                        bemname = splited.shift();

                    nested({
                        level: level,
                        basename: basename,
                        bemname: bemname,
                        dirname: dir,
                        filename: filename,
                        notation: naming.parse(bemname),
                        tech: splited.join('.')
                    }, add, walk, done);
                }

                function done(err) {
                    err && callback(err);

                    ++n === l && callback(null, entities);
                }
            });
        }

        function add(item) {
            var notation = item.notation;

            if (notation && item.tech) {
                var obj = item.notation;

                obj.level = item.level;
                obj.tech = item.tech;
                obj.path = item.filename;

                output.write(obj);
            }
        }
    }

    var n = 0,
        l = levels.length;

    if (l === 0) {
        output.end();
    } else {
        for (var i = 0; i < l; ++i) {
            scan(levels[i], scancb);
        }
    }

    function scancb(err) {
        if (err) {
            output.emit('error', err);
        }

        ++n === l && output.end();
    }

    return output;
};
<commit_msg>Fixed bug with scan of not existing level<commit_after>var fs = require('fs'),
    path = require('path'),
    naming = require('bem-naming'),
    PassThrough = require('stream').PassThrough,
    sep = path.sep;

function nested(item, add, walk, done) {
    var basename = item.basename,
        filename = item.filename,
        parent = path.basename(item.dirname),
        grandParent = path.basename(path.dirname(item.dirname)),
        depth = filename.split(sep).length - item.level.split(sep).length;

    if ((depth === 1 && naming.isBlock(item.notation)) ||
        (depth === 2 && naming.isBlockMod(parent + basename)) ||
        (depth === 2 && naming.isElem(parent + basename)) ||
        (depth === 3 && naming.isElemMod(grandParent + parent + basename))
    ) {
        return walk(filename, done);
    }

    add(item);
    done();
}

module.exports = function (levels) {
    var output = new PassThrough({ objectMode: true });

    function scan(level, callback) {
        var entities = {};

        walk(level, callback);

        function walk(dir, callback) {
            fs.readdir(dir, function (err, items) {
                if (err) return callback(err);

                var n = 0,
                    l = items.length;

                for (var i = 0; i < l; ++i) {
                    var basename = items[i],
                        filename = path.join(dir, basename),
                        splited = basename.split('.'),
                        bemname = splited.shift();

                    nested({
                        level: level,
                        basename: basename,
                        bemname: bemname,
                        dirname: dir,
                        filename: filename,
                        notation: naming.parse(bemname),
                        tech: splited.join('.')
                    }, add, walk, done);
                }

                function done(err) {
                    err && callback(err);

                    ++n === l && callback(null, entities);
                }
            });
        }

        function add(item) {
            var notation = item.notation;

            if (notation && item.tech) {
                var obj = item.notation;

                obj.level = item.level;
                obj.tech = item.tech;
                obj.path = item.filename;

                output.write(obj);
            }
        }
    }

    var n = 0,
        l = levels.length;

    if (l === 0) {
        output.end();
    } else {
        for (var i = 0; i < l; ++i) {
            scan(levels[i], scancb);
        }
    }

    function scancb(err) {
        if (err) {
            output.emit('error', err);
        }

        ++n === l && output.end();
    }

    return output;
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */

var Identify = require('segmentio-facade').Identify;
var alias = require('@segment/alias');
var convertDates = require('@segment/convert-dates');
var integration = require('@segment/analytics.js-integration');

/**
 * Expose `Customerio` integration.
 */

var Customerio = module.exports = integration('Customer.io')
  .global('_cio')
  .option('siteId', '')
  .tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');

/**
 * Initialize.
 *
 * http://customer.io/docs/api/javascript.html
 *
 * @api public
 */

Customerio.prototype.initialize = function() {
  window._cio = window._cio || [];
  /* eslint-disable */
  (function(){var a,b,c; a = function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })();
  /* eslint-enable */
  this.load(this.ready);
};

/**
 * Loaded?
 *
 * @api private
 * @return {boolean}
 */

Customerio.prototype.loaded = function() {
  return !!(window._cio && window._cio.push !== Array.prototype.push);
};

/**
 * Page.
 *
 * https://learn.customer.io/api/#apipageview_event
 *
 * @api public
 * @param {Page} page
 */
Customerio.prototype.page = function(page) {
  var name = page.name();
  var data = page.properties();

  if (!name) {
    name = data.url;
  }

  window._cio.page(name, data);
};

/**
 * Identify.
 *
 * http://customer.io/docs/api/javascript.html#section-Identify_customers
 *
 * @api public
 * @param {Identify} identify
 */

Customerio.prototype.identify = function(identify) {
  if (!identify.userId()) return this.debug('user id required');
  var traits = identify.traits({ createdAt: 'created' });
  traits = alias(traits, { created: 'created_at' });
  traits = convertDates(traits, convertDate);
  window._cio.identify(traits);
};

/**
 * Group.
 *
 * @api public
 * @param {Group} group
 */

Customerio.prototype.group = function(group) {
  var traits = group.traits();
  var user = this.analytics.user();

  traits = alias(traits, function(trait) {
    return 'Group ' + trait;
  });

  this.identify(new Identify({
    userId: user.id(),
    traits: traits
  }));
};

/**
 * Track.
 *
 * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event
 *
 * @api public
 * @param {Track} track
 */

Customerio.prototype.track = function(track) {
  var properties = track.properties();
  properties = convertDates(properties, convertDate);
  window._cio.track(track.event(), properties);
};

/**
 * Convert a date to the format Customer.io supports.
 *
 * @api private
 * @param {Date} date
 * @return {number}
 */

function convertDate(date) {
  return Math.floor(date.getTime() / 1000);
}
<commit_msg>Refactor for name handling<commit_after>'use strict';

/**
 * Module dependencies.
 */

var Identify = require('segmentio-facade').Identify;
var alias = require('@segment/alias');
var convertDates = require('@segment/convert-dates');
var integration = require('@segment/analytics.js-integration');

/**
 * Expose `Customerio` integration.
 */

var Customerio = module.exports = integration('Customer.io')
  .global('_cio')
  .option('siteId', '')
  .tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');

/**
 * Initialize.
 *
 * http://customer.io/docs/api/javascript.html
 *
 * @api public
 */

Customerio.prototype.initialize = function() {
  window._cio = window._cio || [];
  /* eslint-disable */
  (function(){var a,b,c; a = function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })();
  /* eslint-enable */
  this.load(this.ready);
};

/**
 * Loaded?
 *
 * @api private
 * @return {boolean}
 */

Customerio.prototype.loaded = function() {
  return !!(window._cio && window._cio.push !== Array.prototype.push);
};

/**
 * Page.
 *
 * https://learn.customer.io/api/#apipageview_event
 *
 * @api public
 * @param {Page} page
 */

Customerio.prototype.page = function(page) {
  var name = page.name() || page.url();
  window._cio.page(name, page.properties());
};

/**
 * Identify.
 *
 * http://customer.io/docs/api/javascript.html#section-Identify_customers
 *
 * @api public
 * @param {Identify} identify
 */

Customerio.prototype.identify = function(identify) {
  if (!identify.userId()) return this.debug('user id required');
  var traits = identify.traits({ createdAt: 'created' });
  traits = alias(traits, { created: 'created_at' });
  traits = convertDates(traits, convertDate);
  window._cio.identify(traits);
};

/**
 * Group.
 *
 * @api public
 * @param {Group} group
 */

Customerio.prototype.group = function(group) {
  var traits = group.traits();
  var user = this.analytics.user();

  traits = alias(traits, function(trait) {
    return 'Group ' + trait;
  });

  this.identify(new Identify({
    userId: user.id(),
    traits: traits
  }));
};

/**
 * Track.
 *
 * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event
 *
 * @api public
 * @param {Track} track
 */

Customerio.prototype.track = function(track) {
  var properties = track.properties();
  properties = convertDates(properties, convertDate);
  window._cio.track(track.event(), properties);
};

/**
 * Convert a date to the format Customer.io supports.
 *
 * @api private
 * @param {Date} date
 * @return {number}
 */

function convertDate(date) {
  return Math.floor(date.getTime() / 1000);
}
<|endoftext|>