<commit_before>#!/usr/bin/env node

const childProcess = require('child_process')
const crypto = require('crypto')
const fs = require('fs')
const { hashElement } = require('folder-hash')
const path = require('path')
const unknownArgs = []

const args = require('minimist')(process.argv, {
  string: ['only'],
  unknown: arg => unknownArgs.push(arg)
})

const utils = require('./lib/utils')

const BASE = path.resolve(__dirname, '../..')
const NPM_CMD = process.platform === 'win32' ? 'npm.cmd' : 'npm'

const specHashPath = path.resolve(__dirname, '../spec/.hash')

let only = null
if (args.only) {
  only = args.only.split(',')
  console.log('Only running:', only)
} else {
  console.log('Will trigger all spec runners')
}

async function main () {
  const [lastSpecHash, lastSpecInstallHash] = loadLastSpecHash()
  const [currentSpecHash, currentSpecInstallHash] = await getSpecHash()
  const somethingChanged = (currentSpecHash !== lastSpecHash) ||
      (lastSpecInstallHash !== currentSpecInstallHash)

  if (somethingChanged) {
    await installSpecModules()
    await getSpecHash().then(saveSpecHash)
  }

  if (!fs.existsSync(path.resolve(__dirname, '../electron.d.ts'))) {
    console.log('Generating electron.d.ts as it is missing')
    generateTypeDefinitions()
  }

  await runElectronTests()
}

function generateTypeDefinitions () {
  const { status } = childProcess.spawnSync('npm', ['run', 'create-typescript-definitions'], {
    cwd: path.resolve(__dirname, '..'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error(`Electron typescript definition generation failed with exit code: ${status}.`)
  }
}

function loadLastSpecHash () {
  return fs.existsSync(specHashPath)
    ? fs.readFileSync(specHashPath, 'utf8').split('\n')
    : [null, null]
}

function saveSpecHash ([newSpecHash, newSpecInstallHash]) {
  fs.writeFileSync(specHashPath, `${newSpecHash}\n${newSpecInstallHash}`)
}

async function runElectronTests () {
  const errors = []
  const runners = [
    ['Remote based specs', 'remote', runRemoteBasedElectronTests],
    ['Main process specs', 'main', runMainProcessElectronTests]
  ]

  const mochaFile = process.env.MOCHA_FILE
  for (const runner of runners) {
    if (only && !only.includes(runner[1])) {
      console.info('\nSkipping:', runner[0])
      continue
    }
    try {
      console.info('\nRunning:', runner[0])
      if (mochaFile) {
        process.env.MOCHA_FILE = mochaFile.replace('.xml', `-${runner[1]}.xml`)
      }
      await runner[2]()
    } catch (err) {
      errors.push([runner[0], err])
    }
  }

  if (errors.length !== 0) {
    for (const err of errors) {
      console.error('\n\nRunner Failed:', err[0])
      console.error(err[1])
    }
    throw new Error('Electron test runners have failed')
  }
}

async function runRemoteBasedElectronTests () {
  let exe = path.resolve(BASE, utils.getElectronExec())
  const runnerArgs = ['electron/spec', unknownArgs.slice(2)]
  if (process.platform === 'linux') {
    runnerArgs.unshift(path.resolve(__dirname, 'dbus_mock.py'), exe)
    exe = 'python'
  }

  const { status } = childProcess.spawnSync(exe, runnerArgs, {
    cwd: path.resolve(__dirname, '../..'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error(`Electron tests failed with code ${status}.`)
  }
}

async function runMainProcessElectronTests () {
  const exe = path.resolve(BASE, utils.getElectronExec())

  const { status } = childProcess.spawnSync(exe, ['electron/spec-main', ...unknownArgs.slice(2)], {
    cwd: path.resolve(__dirname, '../..'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error(`Electron tests failed with code ${status}.`)
  }
}

async function installSpecModules () {
  const nodeDir = path.resolve(BASE, `out/${utils.OUT_DIR}/gen/node_headers`)
  const env = Object.assign({}, process.env, {
    npm_config_nodedir: nodeDir,
    npm_config_msvs_version: '2017'
  })
  const { status } = childProcess.spawnSync(NPM_CMD, ['install'], {
    env,
    cwd: path.resolve(__dirname, '../spec'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error('Failed to npm install in the spec folder')
  }
}

function getSpecHash () {
  return Promise.all([
    (async () => {
      const hasher = crypto.createHash('SHA256')
      hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package.json')))
      hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package-lock.json')))
      return hasher.digest('hex')
    })(),
    (async () => {
      const specNodeModulesPath = path.resolve(__dirname, '../spec/node_modules')
      if (!fs.existsSync(specNodeModulesPath)) {
        return null
      }
      const { hash } = await hashElement(specNodeModulesPath, {
        folders: {
          exclude: ['.bin']
        }
      })
      return hash
    })()
  ])
}

main().catch((error) => {
  console.error('An error occurred inside the spec runner:', error)
  process.exit(1)
})
<commit_msg>build: spread runner args onto the runner<commit_after>#!/usr/bin/env node

const childProcess = require('child_process')
const crypto = require('crypto')
const fs = require('fs')
const { hashElement } = require('folder-hash')
const path = require('path')
const unknownArgs = []

const args = require('minimist')(process.argv, {
  string: ['only'],
  unknown: arg => unknownArgs.push(arg)
})

const utils = require('./lib/utils')

const BASE = path.resolve(__dirname, '../..')
const NPM_CMD = process.platform === 'win32' ? 'npm.cmd' : 'npm'

const specHashPath = path.resolve(__dirname, '../spec/.hash')

let only = null
if (args.only) {
  only = args.only.split(',')
  console.log('Only running:', only)
} else {
  console.log('Will trigger all spec runners')
}

async function main () {
  const [lastSpecHash, lastSpecInstallHash] = loadLastSpecHash()
  const [currentSpecHash, currentSpecInstallHash] = await getSpecHash()
  const somethingChanged = (currentSpecHash !== lastSpecHash) ||
      (lastSpecInstallHash !== currentSpecInstallHash)

  if (somethingChanged) {
    await installSpecModules()
    await getSpecHash().then(saveSpecHash)
  }

  if (!fs.existsSync(path.resolve(__dirname, '../electron.d.ts'))) {
    console.log('Generating electron.d.ts as it is missing')
    generateTypeDefinitions()
  }

  await runElectronTests()
}

function generateTypeDefinitions () {
  const { status } = childProcess.spawnSync('npm', ['run', 'create-typescript-definitions'], {
    cwd: path.resolve(__dirname, '..'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error(`Electron typescript definition generation failed with exit code: ${status}.`)
  }
}

function loadLastSpecHash () {
  return fs.existsSync(specHashPath)
    ? fs.readFileSync(specHashPath, 'utf8').split('\n')
    : [null, null]
}

function saveSpecHash ([newSpecHash, newSpecInstallHash]) {
  fs.writeFileSync(specHashPath, `${newSpecHash}\n${newSpecInstallHash}`)
}

async function runElectronTests () {
  const errors = []
  const runners = [
    ['Remote based specs', 'remote', runRemoteBasedElectronTests],
    ['Main process specs', 'main', runMainProcessElectronTests]
  ]

  const mochaFile = process.env.MOCHA_FILE
  for (const runner of runners) {
    if (only && !only.includes(runner[1])) {
      console.info('\nSkipping:', runner[0])
      continue
    }
    try {
      console.info('\nRunning:', runner[0])
      if (mochaFile) {
        process.env.MOCHA_FILE = mochaFile.replace('.xml', `-${runner[1]}.xml`)
      }
      await runner[2]()
    } catch (err) {
      errors.push([runner[0], err])
    }
  }

  if (errors.length !== 0) {
    for (const err of errors) {
      console.error('\n\nRunner Failed:', err[0])
      console.error(err[1])
    }
    throw new Error('Electron test runners have failed')
  }
}

async function runRemoteBasedElectronTests () {
  let exe = path.resolve(BASE, utils.getElectronExec())
  const runnerArgs = ['electron/spec', ...unknownArgs.slice(2)]
  if (process.platform === 'linux') {
    runnerArgs.unshift(path.resolve(__dirname, 'dbus_mock.py'), exe)
    exe = 'python'
  }

  const { status } = childProcess.spawnSync(exe, runnerArgs, {
    cwd: path.resolve(__dirname, '../..'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error(`Electron tests failed with code ${status}.`)
  }
}

async function runMainProcessElectronTests () {
  const exe = path.resolve(BASE, utils.getElectronExec())

  const { status } = childProcess.spawnSync(exe, ['electron/spec-main', ...unknownArgs.slice(2)], {
    cwd: path.resolve(__dirname, '../..'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error(`Electron tests failed with code ${status}.`)
  }
}

async function installSpecModules () {
  const nodeDir = path.resolve(BASE, `out/${utils.OUT_DIR}/gen/node_headers`)
  const env = Object.assign({}, process.env, {
    npm_config_nodedir: nodeDir,
    npm_config_msvs_version: '2017'
  })
  const { status } = childProcess.spawnSync(NPM_CMD, ['install'], {
    env,
    cwd: path.resolve(__dirname, '../spec'),
    stdio: 'inherit'
  })
  if (status !== 0) {
    throw new Error('Failed to npm install in the spec folder')
  }
}

function getSpecHash () {
  return Promise.all([
    (async () => {
      const hasher = crypto.createHash('SHA256')
      hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package.json')))
      hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package-lock.json')))
      return hasher.digest('hex')
    })(),
    (async () => {
      const specNodeModulesPath = path.resolve(__dirname, '../spec/node_modules')
      if (!fs.existsSync(specNodeModulesPath)) {
        return null
      }
      const { hash } = await hashElement(specNodeModulesPath, {
        folders: {
          exclude: ['.bin']
        }
      })
      return hash
    })()
  ])
}

main().catch((error) => {
  console.error('An error occurred inside the spec runner:', error)
  process.exit(1)
})
<|endoftext|>


<commit_before>Polymer({
  is: 'steroid-polyter',

  //Routes added container
  routes: {},

  //Polymer elements rendered container
  instances: {},

  //Default elements container.
  defaultElements: {},

  //Default added extensions.
  defaultExtensions: null,

  _defaultRendered: false,

  _defaultHooks: {},

  _hashbang: false,
  //Route called previous actual.
  previousRoute: null,

  //Route lifecycle
  _stopped: false,
  _triggered: false,

  // Stop the route lifecycle
  stop: function () {
    this._stopped = true;
  },

  _unStop: function () {
    var aux = this._stopped;
    this._stopped = false;
    return aux;
  },

  //Redirect to another route.
  redirect: function (route) {
    this.stop();
    //TODO: make something here!
    //this.previousRoute = this.router.path;
    this.beforeRedirect = this.router.path;
    setTimeout(function () { //Put the redirect at the end of de heap
      page.redirect(route);
    }, 0);
  },

  //This hook run before start loading things.
  run: function (route) {

    if (this._defaultHooks.run) {
      this._defaultHooks.run.call(this);
    }

    if (route && route.run) {
      route.run.call(this);
    }
    return this._unStop();
  },

  //Here you can put async code and wait for it
  wait: function (route, cb) {
    if (this._defaultHooks.wait) {
     this._defaultHooks.wait.call(this, function () {
       if (route && route.wait) {
         route.wait.call(this, cb);
       }
       else {
           cb();
       }
     });
     return;
   }

   if (route && route.wait) {
     route.wait.call(this, cb);
   }
   else {
       cb();
   }
  },

  //Here you have the extensions instances
  before: function (route) {

    if (this._defaultHooks.before) {
      this._defaultHooks.before.call(this);
    }

    if (route && route.before) {
      route.before.call(this);
    }

    return this._unStop();
  },

  //Here you have the element instances
  action: function (route) {

    if (this._defaultHooks.action) {
      this._defaultHooks.action.call(this);
    }

    if (route && route.action) {
        route.action.call(this);
    }

    return this._unStop();
  },

  //Here the elements are rendered
  after: function (route, routeName) {

    if (this._defaultHooks.after) {
      this._defaultHooks.after.call(this);
    }

    if (route && route.after) {
      route.after.call(this);
    }
    this.previousRoute = routeName;
    return this._unStop();
  },

  //Before stop the route
  onStop: function (routeName) {
    this.stopped = false;
    var pRoute = this.routes[this.previousRoute];

    if (this.previousRoute && pRoute) {
      if (this._defaultHooks.stop) {
        this._defaultHooks.stop.call(this);
      }

      if (pRoute.stop) {
        pRoute.stop.call(this);
      }
    }
  },

  created: function () {
    Polyter = this;
    console.log('### Polyter created ###');
  },

  // Extensions container
  ext: {},

  _injectExtensions: function (extName) {
    if (extName instanceof Array) {

      if (this.defaultExtensions) {
        extName = _.union(extName, this.defaultExtensions);
      }
    }
    else {
      extName = this.defaultExtensions;
    }

    for (var i = extName.length; i-- > 0;) {
      if (!this.ext[extName[i]]) {
        this.ext[extName[i]] = document.createElement(extName[i]);
        //TODO: add factoryImpl call.
      }
    }

  },

  _callFactoryImpl: function () {
    for (var ext in this.ext) {
      if (this.ext.hasOwnProperty(ext)) {
        if (typeof this.ext[ext].factoryImpl == 'function') {
          this.ext[ext].factoryImpl.call(this.ext[ext]);
        }
      }
    }
  },

  _clearInstances: function (elementName) {
    var instances = Object.getOwnPropertyNames(this.instances),
        def = _.values(this.defaultElements);

    def.push(elementName);

    var diff = _.difference(instances, def);

    for (var i = diff.length; i-- > 0;) {
      var inst = this.instances[diff[i]];

      if (inst.remove) {
        inst.remove();
      }
      else if (inst.parentNode) {
        inst.parentNode.removeChild(inst);
      }

      delete this.instances[diff[i]]; //TODO: make sure of this!
    }

  },

  _instantiateDef: function () {
    for (var region in this.defaultElements) {
      if (this.defaultElements.hasOwnProperty(region)) {
        var name = this.defaultElements[region];

        if (name) {
          this._instantiate(name);
        }
      }
    }
  },

  _instantiate: function (elementName) {

    if (!this.instances[elementName]) {
      this.instances[elementName] = document.createElement(elementName);
    }

    this.instances[elementName].name = elementName;
    //TODO: make this better.
    this.instances[elementName].ext = this.ext;
    this.instances[elementName].router = this.router;
  },

  _renderDef: function () {
    for (var region in this.defaultElements) {
      if (this.defaultElements.hasOwnProperty(region)) {
        var name = this.defaultElements[region];

        if (name) {
          this._render(name, region);
        }
      }
    }
  },

  _render: function (elementName, region) {
    this.schema[region ? region : 'main'].appendChild(this.instances[elementName]);
  },

  //Load the elements with attr region on it like schema elements.
  loadSchema: function () {
    if (!this.schema) {
      var _this = this;

      _this.schema = {};

      _.each(Polymer.dom(_this).querySelectorAll('*[region]'), function (el) {
        var region = el.attributes.region;
        if (region && region.value) {
          _this.schema[region.value] = el;
        }
      });

    }
  },

  _updateCtx: function () {
    for (var region in this.defaultElements) {
      if (this.defaultElements.hasOwnProperty(region)) {
        var name = this.defaultElements[region];

        if (name && this.instances[name]) {
          this.instances[name].router = this.router;
        }
      }
    }
  },

  //Add a route with options.
  addRoute: function (routeName, options) {
    var _this = this;

    //We need load the schema here?
    this.loadSchema();

    var route = options;

    this.routes[routeName] = route;
    console.log('Adding route! ', routeName);
    page(routeName, function (ctx) {
      _this.executed = true;

      if (_this._triggered) {
        _this.router = ctx;
        _this._triggered = false;
        return;
      }

      _this.onStop(routeName);

      //_.extend(_this, ctx);
      //TODO: check why params is rewrited by pages!
      _this.router = ctx;

      if (_this.run(route)) {
        return;
      }

      _this._injectExtensions(route.extensions);

      _this._updateCtx();

      _this.wait(route, function () {
        if (_this.before(route)) {
          return;
        }

        _this._callFactoryImpl();

        var elements = route.layout;
        if (elements) {
          //TODO: Do the logic for the elements here
          _this.defaultAux = _this.defaultElements;
          _this.defaultElements = elements;
        }

        if (routeName === _this.previousRoute && _this.instances[route.element]) {
          _this.instances[route.element].router = ctx;
        }
        else {

          //TODO: make this more clean
          if (!_this._defaultRendered) {
            _this._instantiateDef();
          }

          _this._instantiate(route.element);

          if (_this.action(route)) {
            return;
          }
          _this._clearInstances(route.element);

          //TODO: make this more clean
          if (!_this._defaultRendered) {
            _this._renderDef();
            _this._defaultRendered = true;
          }

          _this._render(route.element, route.region);
        }

        if (_this.after(route, routeName)) {
          return;
        }

        if (_this.defaultAux) {
          _this.defaultElements = _this.defaultAux;
          _this.defaultAux = null;
          _this._defaultRendered = false;
        }
      });

    });

    //TODO: this is not very clean!
    if (!_this.executed) {
      if (!_this.started) {
        page.start({hashbang: _this._hashbang});
        _this.started = true;
        console.log('### Polyter Started ###');
      }
      else {
        _this.go(window.location.hash);
      }
    }
    else {
      page.startEvent();
    }

  },

  //Add a default configuration
  defaultConfig: function (options) {
    //Load layout
    if (!options) return;

    var layEl = options.layout;

    if (layEl) {
      this.defaultElements = layEl;
    }

    //Default Extensions
    if (options.extensions instanceof Array) {
      this.defaultExtensions = options.extensions;
    }

    //Default hooks
    if (options.hooks) {
      var hooks = options.hooks;
      for (var hook in hooks) {
        if (hooks.hasOwnProperty(hook)) {
          if (typeof hooks[hook] === 'function') {
            this._defaultHooks[hook] = hooks[hook];
          }
        }
      }
    }

    //Load hashband
    if (options.hashbang) {
      this._hashbang = true;
    }

  },

  //Go to another route with extra options like {trigger: false}.
  go: function (route, options) { //TODO: {trigger: false, ...};
    if (route) {
      //this.stop();
      if (options) {
        if (options.silent === true) {
          this._triggered = true;
          page.show(route, undefined, undefined, false);
          window.history.replaceState(undefined, undefined, route);
        }
        else if (options.trigger === false) {
          this._triggered = true;
          page.show(route);
        }
      }
      else {
        page.show(route);
      }
    }
  },

  back: function () {
    window.history.back();
  }
});
<commit_msg>Unstop on redirect<commit_after>Polymer({
  is: 'steroid-polyter',

  //Routes added container
  routes: {},

  //Polymer elements rendered container
  instances: {},

  //Default elements container.
  defaultElements: {},

  //Default added extensions.
  defaultExtensions: null,

  _defaultRendered: false,

  _defaultHooks: {},

  _hashbang: false,
  //Route called previous actual.
  previousRoute: null,

  //Route lifecycle
  _stopped: false,
  _triggered: false,

  // Stop the route lifecycle
  stop: function () {
    this._stopped = true;
  },

  _unStop: function () {
    var aux = this._stopped;
    this._stopped = false;
    return aux;
  },

  //Redirect to another route.
  redirect: function (route) {
    this.stop();
    //TODO: make something here!
    //this.previousRoute = this.router.path;
    this.beforeRedirect = this.router.path;
    var _this = this;
    setTimeout(function () {
      _this._unStop();//Put the redirect at the end of de heap
      page.redirect(route);
    }, 0);
  },

  //This hook run before start loading things.
  run: function (route) {

    if (this._defaultHooks.run) {
      this._defaultHooks.run.call(this);
    }

    if (route && route.run) {
      route.run.call(this);
    }
    return this._unStop();
  },

  //Here you can put async code and wait for it
  wait: function (route, cb) {
    if (this._defaultHooks.wait) {
     this._defaultHooks.wait.call(this, function () {
       if (route && route.wait) {
         route.wait.call(this, cb);
       }
       else {
           cb();
       }
     });
     return;
   }

   if (route && route.wait) {
     route.wait.call(this, cb);
   }
   else {
       cb();
   }
  },

  //Here you have the extensions instances
  before: function (route) {

    if (this._defaultHooks.before) {
      this._defaultHooks.before.call(this);
    }

    if (route && route.before) {
      route.before.call(this);
    }

    return this._unStop();
  },

  //Here you have the element instances
  action: function (route) {

    if (this._defaultHooks.action) {
      this._defaultHooks.action.call(this);
    }

    if (route && route.action) {
        route.action.call(this);
    }

    return this._unStop();
  },

  //Here the elements are rendered
  after: function (route, routeName) {

    if (this._defaultHooks.after) {
      this._defaultHooks.after.call(this);
    }

    if (route && route.after) {
      route.after.call(this);
    }
    this.previousRoute = routeName;
    return this._unStop();
  },

  //Before stop the route
  onStop: function (routeName) {
    this.stopped = false;
    var pRoute = this.routes[this.previousRoute];

    if (this.previousRoute && pRoute) {
      if (this._defaultHooks.stop) {
        this._defaultHooks.stop.call(this);
      }

      if (pRoute.stop) {
        pRoute.stop.call(this);
      }
    }
  },

  created: function () {
    Polyter = this;
    console.log('### Polyter created ###');
  },

  // Extensions container
  ext: {},

  _injectExtensions: function (extName) {
    if (extName instanceof Array) {

      if (this.defaultExtensions) {
        extName = _.union(extName, this.defaultExtensions);
      }
    }
    else {
      extName = this.defaultExtensions;
    }

    for (var i = extName.length; i-- > 0;) {
      if (!this.ext[extName[i]]) {
        this.ext[extName[i]] = document.createElement(extName[i]);
        //TODO: add factoryImpl call.
      }
    }

  },

  _callFactoryImpl: function () {
    for (var ext in this.ext) {
      if (this.ext.hasOwnProperty(ext)) {
        if (typeof this.ext[ext].factoryImpl == 'function') {
          this.ext[ext].factoryImpl.call(this.ext[ext]);
        }
      }
    }
  },

  _clearInstances: function (elementName) {
    var instances = Object.getOwnPropertyNames(this.instances),
        def = _.values(this.defaultElements);

    def.push(elementName);

    var diff = _.difference(instances, def);

    for (var i = diff.length; i-- > 0;) {
      var inst = this.instances[diff[i]];

      if (inst.remove) {
        inst.remove();
      }
      else if (inst.parentNode) {
        inst.parentNode.removeChild(inst);
      }

      delete this.instances[diff[i]]; //TODO: make sure of this!
    }

  },

  _instantiateDef: function () {
    for (var region in this.defaultElements) {
      if (this.defaultElements.hasOwnProperty(region)) {
        var name = this.defaultElements[region];

        if (name) {
          this._instantiate(name);
        }
      }
    }
  },

  _instantiate: function (elementName) {

    if (!this.instances[elementName]) {
      this.instances[elementName] = document.createElement(elementName);
    }

    this.instances[elementName].name = elementName;
    //TODO: make this better.
    this.instances[elementName].ext = this.ext;
    this.instances[elementName].router = this.router;
  },

  _renderDef: function () {
    for (var region in this.defaultElements) {
      if (this.defaultElements.hasOwnProperty(region)) {
        var name = this.defaultElements[region];

        if (name) {
          this._render(name, region);
        }
      }
    }
  },

  _render: function (elementName, region) {
    this.schema[region ? region : 'main'].appendChild(this.instances[elementName]);
  },

  //Load the elements with attr region on it like schema elements.
  loadSchema: function () {
    if (!this.schema) {
      var _this = this;

      _this.schema = {};

      _.each(Polymer.dom(_this).querySelectorAll('*[region]'), function (el) {
        var region = el.attributes.region;
        if (region && region.value) {
          _this.schema[region.value] = el;
        }
      });

    }
  },

  _updateCtx: function () {
    for (var region in this.defaultElements) {
      if (this.defaultElements.hasOwnProperty(region)) {
        var name = this.defaultElements[region];

        if (name && this.instances[name]) {
          this.instances[name].router = this.router;
        }
      }
    }
  },

  //Add a route with options.
  addRoute: function (routeName, options) {
    var _this = this;

    //We need load the schema here?
    this.loadSchema();

    var route = options;

    this.routes[routeName] = route;
    console.log('Adding route! ', routeName);
    page(routeName, function (ctx) {
      _this.executed = true;

      if (_this._triggered) {
        _this.router = ctx;
        _this._triggered = false;
        return;
      }

      _this.onStop(routeName);

      //_.extend(_this, ctx);
      //TODO: check why params is rewrited by pages!
      _this.router = ctx;

      if (_this.run(route)) {
        return;
      }

      _this._injectExtensions(route.extensions);

      _this._updateCtx();

      _this.wait(route, function () {
        if (_this.before(route)) {
          return;
        }

        _this._callFactoryImpl();

        var elements = route.layout;
        if (elements) {
          //TODO: Do the logic for the elements here
          _this.defaultAux = _this.defaultElements;
          _this.defaultElements = elements;
        }

        if (routeName === _this.previousRoute && _this.instances[route.element]) {
          _this.instances[route.element].router = ctx;
        }
        else {

          //TODO: make this more clean
          if (!_this._defaultRendered) {
            _this._instantiateDef();
          }

          _this._instantiate(route.element);

          if (_this.action(route)) {
            return;
          }
          _this._clearInstances(route.element);

          //TODO: make this more clean
          if (!_this._defaultRendered) {
            _this._renderDef();
            _this._defaultRendered = true;
          }

          _this._render(route.element, route.region);
        }

        if (_this.after(route, routeName)) {
          return;
        }

        if (_this.defaultAux) {
          _this.defaultElements = _this.defaultAux;
          _this.defaultAux = null;
          _this._defaultRendered = false;
        }
      });

    });

    //TODO: this is not very clean!
    if (!_this.executed) {
      if (!_this.started) {
        page.start({hashbang: _this._hashbang});
        _this.started = true;
        console.log('### Polyter Started ###');
      }
      else {
        _this.go(window.location.hash);
      }
    }
    else {
      page.startEvent();
    }

  },

  //Add a default configuration
  defaultConfig: function (options) {
    //Load layout
    if (!options) return;

    var layEl = options.layout;

    if (layEl) {
      this.defaultElements = layEl;
    }

    //Default Extensions
    if (options.extensions instanceof Array) {
      this.defaultExtensions = options.extensions;
    }

    //Default hooks
    if (options.hooks) {
      var hooks = options.hooks;
      for (var hook in hooks) {
        if (hooks.hasOwnProperty(hook)) {
          if (typeof hooks[hook] === 'function') {
            this._defaultHooks[hook] = hooks[hook];
          }
        }
      }
    }

    //Load hashband
    if (options.hashbang) {
      this._hashbang = true;
    }

  },

  //Go to another route with extra options like {trigger: false}.
  go: function (route, options) { //TODO: {trigger: false, ...};
    if (route) {
      //this.stop();
      if (options) {
        if (options.silent === true) {
          this._triggered = true;
          page.show(route, undefined, undefined, false);
          window.history.replaceState(undefined, undefined, route);
        }
        else if (options.trigger === false) {
          this._triggered = true;
          page.show(route);
        }
      }
      else {
        page.show(route);
      }
    }
  },

  back: function () {
    window.history.back();
  }
});
<|endoftext|>


<commit_before>var FullScreen = {
    showBottomTimer: null,
    $bottom: null,
    $button: null,
    documentElem: null,
    isOn: false,

    init: function() {
        var self = FullScreen;
        self.documentElem = document.documentElement;

        document.addEventListener("fullscreenchange", function () {
            if (!document.fullscreen) {
                self.off();
            }
        }, false);

        document.addEventListener("mozfullscreenchange", function () {
            if (!document.mozFullScreen) {
                self.off();
            }
        }, false);

        document.addEventListener("webkitfullscreenchange", function () {
            if (!document.webkitIsFullScreen) {
                self.off();
            }
        }, false);

        self.$bottom = $('#bottom');
        self.$button = $('#bottom .fullscreen');
        self.$button.click(self.toggle);
    },
    on: function() {
        var self = FullScreen;
        self.$button.addClass('on');
        $('body').addClass('fullscreen');
        $('body.fullscreen').mousemove(self.mouseMove);

        // Try native fullscreen
        if (self.documentElem.requestFullscreen) {
            self.documentElem.requestFullscreen();
        }
        else if (self.documentElem.mozRequestFullScreen) {
            self.documentElem.mozRequestFullScreen();
        }
        else if (self.documentElem.webkitRequestFullScreen) {
            self.documentElem.webkitRequestFullScreen();
        }

        player.fullScreenOn();
        self.isOn = true;
    },
    off: function() {
        var self = FullScreen;
        self.$button.removeClass('on');
        $('body.fullscreen').unbind('mousemove');
        $('body').removeClass('fullscreen');

        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }

        player.fullScreenOff();
        self.isOn = false;
    },
    toggle: function() {
        var self = FullScreen;
        if (!self.isOn) {
            self.on();
        } else {
            self.off();
        }
    },
    mouseMove: function() {
        var self = FullScreen;
        if (self.showBottomTimer === null) {
            self.$bottom.addClass('on');
            self.showBottomTimer = setTimeout(function() {
                self.$bottom.removeClass('on');
                self.showBottomTimer = null;
            }, 1000);
        }
    }
};<commit_msg>Make double clicking on player toggle fullscreen<commit_after>var FullScreen = {
    showBottomTimer: null,
    $bottom: null,
    $button: null,
    documentElem: null,
    isOn: false,

    init: function() {
        var self = FullScreen;
        self.documentElem = document.documentElement;

        document.addEventListener("fullscreenchange", function () {
            if (!document.fullscreen) {
                self.off();
            }
        }, false);

        document.addEventListener("mozfullscreenchange", function () {
            if (!document.mozFullScreen) {
                self.off();
            }
        }, false);

        document.addEventListener("webkitfullscreenchange", function () {
            if (!document.webkitIsFullScreen) {
                self.off();
            }
        }, false);

        self.$bottom = $('#bottom');
        self.$button = $('#bottom .fullscreen');
        self.$button.click(self.toggle);

        // Make double clicking on player enter fullscreen.
        // In fullscreen, .players doesn't receive click events
        // when YouTube is playing, but #right does.
        $('.players').dblclick(function(event) {
            if (player.getCurrentVideo() && player.getCurrentVideo().type === 'youtube') {
                if (!self.isOn) {
                    self.on();
                }
            } else {
                self.toggle();
            }
        });
        $('#right').dblclick(function(event) {
            if (player.getCurrentVideo() && player.getCurrentVideo().type === 'youtube' && self.isOn) {
                self.off();
            }
        });
    },
    on: function() {
        var self = FullScreen;
        self.$button.addClass('on');
        $('body').addClass('fullscreen');
        $('body.fullscreen').mousemove(self.mouseMove);

        // Try native fullscreen
        if (self.documentElem.requestFullscreen) {
            self.documentElem.requestFullscreen();
        }
        else if (self.documentElem.mozRequestFullScreen) {
            self.documentElem.mozRequestFullScreen();
        }
        else if (self.documentElem.webkitRequestFullScreen) {
            self.documentElem.webkitRequestFullScreen();
        }

        player.fullScreenOn();
        self.isOn = true;
    },
    off: function() {
        var self = FullScreen;
        self.$button.removeClass('on');
        $('body.fullscreen').unbind('mousemove');
        $('body').removeClass('fullscreen');

        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }

        player.fullScreenOff();
        self.isOn = false;
    },
    toggle: function() {
        var self = FullScreen;
        if (!self.isOn) {
            self.on();
        } else {
            self.off();
        }
    },
    mouseMove: function() {
        var self = FullScreen;
        if (self.showBottomTimer === null) {
            self.$bottom.addClass('on');
            self.showBottomTimer = setTimeout(function() {
                self.$bottom.removeClass('on');
                self.showBottomTimer = null;
            }, 1000);
        }
    }
};
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import styles from '@sambego/storybook-styles';
import { Box, Counter } from '../components';
import { baseStyles, centerStyles } from '../.storybook/styles';

const colors = ['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua'];
const sizes = ['small', 'medium'];

storiesOf('Counters', module)
  .addDecorator((story, context) => withInfo('common info')(story)(context))
  .addDecorator(checkA11y)
  .addDecorator(styles({ ...baseStyles, ...centerStyles }))
  .add('colors', () => (
    <Box>
      {colors.map((color, index) => <Counter count={99} color={color} key={index} marginHorizontal={1} />)}
      <Counter count={99} inactive marginHorizontal={1} />
    </Box>
  ))
  .add('size', () => (
    <Box>
      {sizes.map((size, index) => <Counter count={99} color="neutral" key={index} size={size} marginHorizontal={1} />)}
    </Box>
  ))
  .add('no count', () => (
    <Box>
      {sizes.map((size, index) => <Counter color="neutral" key={index} size={size} marginHorizontal={2} />)}
    </Box>
  ))
  .add('maximum count', () => (
    <Box>
      <Counter count={116} color="neutral" maxCount={99} />
    </Box>
  ));
<commit_msg>Storybook: updated the Counter stories<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import styles from '@sambego/storybook-styles';
import { Box, Counter } from '../components';
import { baseStyles, centerStyles } from '../.storybook/styles';

const colors = ['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby'];
const sizes = ['small', 'medium'];

storiesOf('Counters', module)
  .addDecorator((story, context) => withInfo('common info')(story)(context))
  .addDecorator(checkA11y)
  .addDecorator(styles({ ...baseStyles, ...centerStyles }))
  .add('colors', () => (
    <Box>
      {colors.map((color, index) => <Counter count={99} color={color} key={index} marginHorizontal={3} />)}
    </Box>
  ))
  .add('sizes', () => (
    <Box>
      {sizes.map((size, index) => <Counter count={99} color="ruby" key={index} size={size} marginHorizontal={3} />)}
    </Box>
  ))
  .add('maximum count', () => (
    <Box>
      <Counter count={116} color="ruby" maxCount={99} />
    </Box>
  ));
<|endoftext|>


<commit_before>(function($){

    var validator = (function() {
      var init = function() {
        $('form[data-validate="form"]').formValidation({
          feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
          },
          submitButtons: 'button[data-validate="form"]'
        })
        .on('success.field.fv', function(e, data) {
          if (data.fv.getInvalidFields().length > 0) {
            $('button[data-validate="form"]').prop('disabled', true);
          } else {
            $('button[data-validate="form"]').prop('disabled', false);
          }
        })
        .on('err.field.fv', function(e, data) {
          $('button[data-validate="form"]').prop('disabled', true);
        })
        .on('input', function(e, data) {
          if(typeof $('#' + e.target.id).attr('data-fv') == 'undefined') {
            $('button[data-validate="form"]').prop('disabled', false);
          }
        })
        .on('change', function(e, data) {
          if(typeof $('#' + e.target.id).attr('data-fv') == 'undefined') {
            $('button[data-validate="form"]').prop('disabled', false);
          }
        });
      };

      var reinit = function() {
        $('form[data-validate="modal"]').formValidation({
          feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
          },
          submitButtons: 'button[data-validate="modal"]'
        });
      };

      return {
        init: init,
        reinit: reinit
      };
    })();

    $.extend(true, window, {
      core: {
        validator: validator
      }
    });

    $(function() {
        core.validator.init();
    });

}(jQuery));<commit_msg>autohide & validate datepicker<commit_after>(function($){

    var validator = (function() {
      var init = function() {
        $('form[data-validate="form"]').formValidation({
          feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
          },
          submitButtons: 'button[data-validate="form"]'
        })
        .on('success.field.fv', function(e, data) {
          if (data.fv.getInvalidFields().length > 0) {
            $('button[data-validate="form"]').prop('disabled', true);
          } else {
            $('button[data-validate="form"]').prop('disabled', false);
          }
        })
        .on('err.field.fv', function(e, data) {
          $('button[data-validate="form"]').prop('disabled', true);
        })
        .on('input', function(e, data) {
          if(typeof $('#' + e.target.id).attr('data-fv') == 'undefined') {
            $('button[data-validate="form"]').prop('disabled', false);
          }
        })
        .on('change', function(e, data) {
          if(typeof $('#' + e.target.id).attr('data-fv') == 'undefined') {
            $('button[data-validate="form"]').prop('disabled', false);
          }
        })
        .on('changeDate', function(e){
          $('#' + e.target.id).datepicker('hide').trigger('input');
          $('button[data-validate="form"]').prop('disabled', false);
        });
      };

      var reinit = function() {
        $('form[data-validate="modal"]').formValidation({
          feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
          },
          submitButtons: 'button[data-validate="modal"]'
        });
      };

      return {
        init: init,
        reinit: reinit
      };
    })();

    $.extend(true, window, {
      core: {
        validator: validator
      }
    });

    $(function() {
        core.validator.init();
    });

}(jQuery));<|endoftext|>


<commit_before>'use strict'

/**
 * Module dependencies
 */

var lodash = require('lodash')
var pluck = require('lodash.pluck')
var util = require('util')
var validator = require('lx-valid')

/**
 * Add a format extension for UUID
 */

var uuidFormat = /[0-9a-f]{22}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
validator.validate.formatExtensions.uuid = uuidFormat

/**
 * Format extension for url that allows localhost
 */

var urlFormat = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/
validator.validate.formatExtensions.url = urlFormat

/**
 * Validate function
 *
 * After validating, we transform the array of errors objects
 * provided by validator.validate into an object keyed by
 * property, for easier lookup.
 */

function validate (data, schema) {
  var validation, errorProperties

  validation = validator.validate(data, {properties: schema})
  errorProperties = pluck(validation.errors, 'property')
  validation.errors = lodash.zipObject(errorProperties, validation.errors)
  return new ValidationError(validation)
}

/**
 * Validation error
 */

function ValidationError (validation) {
  lodash.extend(this, validation)
  this.name = 'ValidationError'
  this.message = 'Validation error.'
  this.statusCode = 400
}

util.inherits(ValidationError, Error)
validate.ValidationError = ValidationError

/**
 * Exports
 */

module.exports = { validate }
<commit_msg>feat(validator): export ValidationError directly on the module<commit_after>'use strict'

/**
 * Module dependencies
 */

var lodash = require('lodash')
var pluck = require('lodash.pluck')
var util = require('util')
var validator = require('lx-valid')

/**
 * Add a format extension for UUID
 */

var uuidFormat = /[0-9a-f]{22}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
validator.validate.formatExtensions.uuid = uuidFormat

/**
 * Format extension for url that allows localhost
 */

var urlFormat = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/
validator.validate.formatExtensions.url = urlFormat

/**
 * Validate function
 *
 * After validating, we transform the array of errors objects
 * provided by validator.validate into an object keyed by
 * property, for easier lookup.
 */

function validate (data, schema) {
  var validation, errorProperties

  validation = validator.validate(data, {properties: schema})
  errorProperties = pluck(validation.errors, 'property')
  validation.errors = lodash.zipObject(errorProperties, validation.errors)
  return new ValidationError(validation)
}

/**
 * Validation error
 */

function ValidationError (validation) {
  lodash.extend(this, validation)
  this.name = 'ValidationError'
  this.message = 'Validation error.'
  this.statusCode = 400
}

util.inherits(ValidationError, Error)
validate.ValidationError = ValidationError

/**
 * Exports
 */

module.exports = { validate, ValidationError }
<|endoftext|>


<commit_before>var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var PLUGIN_NAME = "CameraPreview";

var CameraPreview = function() {};

function isFunction(obj) {
    return !!(obj && obj.constructor && obj.call && obj.apply);
};

CameraPreview.startCamera = function(options, onSuccess, onError) {
    options = options || {};
    options.x = options.x || 0;
    options.y = options.y || 0;
    options.width = options.width || window.screen.width;
    options.height = options.height || window.screen.height;
    options.camera = options.camera || CameraPreview.CAMERA_DIRECTION.FRONT;
    if (typeof(options.tapPhoto) === 'undefined') {
        options.tapPhoto = true;
    }
    options.previewDrag = options.previewDrag || false;
    options.toBack = options.toBack || false;
    if (typeof(options.alpha) === 'undefined') {
        options.alpha = 1;
    }

    exec(onSuccess, onError, PLUGIN_NAME, "startCamera", [options.x, options.y, options.width, options.height, options.camera, options.tapPhoto, options.previewDrag, options.toBack, options.alpha]);
};

CameraPreview.stopCamera = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "stopCamera", []);
};

CameraPreview.switchCamera = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "switchCamera", []);
};

CameraPreview.hide = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "hideCamera", []);
};

CameraPreview.show = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "showCamera", []);
};

CameraPreview.takePicture = function(opts, onSuccess, onError) {
    if (!opts) {
        opts = {};
    } else if (isFunction(opts)) {
        onSuccess = opts;
        opts = {};
    }

    if (!isFunction(onSuccess)) {
        return false;
    }

    opts.width = opts.width || 0;
    opts.height = opts.height || 0;

    if (!opts.quality || opts.quality > 100 || opts.quality < 0) {
        opts.quality = 85;
    }

    exec(onSuccess, onError, PLUGIN_NAME, "takePicture", [opts.width, opts.height, opts.quality]);
};

CameraPreview.setColorEffect = function(effect, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setColorEffect", [effect]);
};

CameraPreview.setZoom = function(zoom, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setZoom", [zoom]);
};

CameraPreview.getMaxZoom = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getMaxZoom", []);
};

CameraPreview.getZoom = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getZoom", []);
};

CameraPreview.setPreviewSize = function(dimensions, onSuccess, onError) {
    dimensions = dimensions || {};
    dimensions.width = dimensions.width || window.screen.width;
    dimensions.height = dimensions.height || window.screen.height;

    return exec(onSuccess, onError, PLUGIN_NAME, "setPreviewSize", [dimensions.width, dimensions.height]);
};

CameraPreview.getSupportedPictureSizes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getSupportedPictureSizes", []);
};

CameraPreview.setFlashMode = function(flashMode, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setFlashMode", [flashMode]);
};

CameraPreview.tapToFocus = function(xPoint, yPoint, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "tapToFocus", [xPoint, yPoint]);
};

CameraPreview.getExposureModes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureModes", []);
};

CameraPreview.getExposureMode = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureMode", []);
};

CameraPreview.setExposureMode = function(lock, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setExposureMode", [lock]);
};

CameraPreview.getExposureCompensation = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureCompensation", []);
};

CameraPreview.setExposureCompensation = function(exposureCompensation, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setExposureCompensation", [exposureCompensation]);
};

CameraPreview.getExposureCompensationRange = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureCompensationRange", []);
};

CameraPreview.EXPOSURE_MODE = {
    LOCK: 'lock',
    AUTO: 'auto', // IOS Only
    CONTINUOUS: 'continuous', // IOS Only
    CUSTOM: 'custom' // IOS Only
};

CameraPreview.FLASH_MODE = {
    OFF: 'off',
    ON: 'on',
    AUTO: 'auto',
    TORCH: 'torch' // Android Only
};

CameraPreview.COLOR_EFFECT = {
    AQUA: 'aqua', // Android Only
    BLACKBOARD: 'blackboard', // Android Only
    MONO: 'mono',
    NEGATIVE: 'negative',
    NONE: 'none',
    POSTERIZE: 'posterize',
    SEPIA: 'sepia',
    SOLARIZE: 'solarize', // Android Only
    WHITEBOARD: 'whiteboard' // Android Only
};

CameraPreview.CAMERA_DIRECTION = {
    BACK: 'back',
    FRONT: 'front'
};

module.exports = CameraPreview;<commit_msg>New getSupportedFlashModes() method<commit_after>var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var PLUGIN_NAME = "CameraPreview";

var CameraPreview = function() {};

function isFunction(obj) {
    return !!(obj && obj.constructor && obj.call && obj.apply);
};

CameraPreview.startCamera = function(options, onSuccess, onError) {
    options = options || {};
    options.x = options.x || 0;
    options.y = options.y || 0;
    options.width = options.width || window.screen.width;
    options.height = options.height || window.screen.height;
    options.camera = options.camera || CameraPreview.CAMERA_DIRECTION.FRONT;
    if (typeof(options.tapPhoto) === 'undefined') {
        options.tapPhoto = true;
    }
    options.previewDrag = options.previewDrag || false;
    options.toBack = options.toBack || false;
    if (typeof(options.alpha) === 'undefined') {
        options.alpha = 1;
    }

    exec(onSuccess, onError, PLUGIN_NAME, "startCamera", [options.x, options.y, options.width, options.height, options.camera, options.tapPhoto, options.previewDrag, options.toBack, options.alpha]);
};

CameraPreview.stopCamera = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "stopCamera", []);
};

CameraPreview.switchCamera = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "switchCamera", []);
};

CameraPreview.hide = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "hideCamera", []);
};

CameraPreview.show = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "showCamera", []);
};

CameraPreview.takePicture = function(opts, onSuccess, onError) {
    if (!opts) {
        opts = {};
    } else if (isFunction(opts)) {
        onSuccess = opts;
        opts = {};
    }

    if (!isFunction(onSuccess)) {
        return false;
    }

    opts.width = opts.width || 0;
    opts.height = opts.height || 0;

    if (!opts.quality || opts.quality > 100 || opts.quality < 0) {
        opts.quality = 85;
    }

    exec(onSuccess, onError, PLUGIN_NAME, "takePicture", [opts.width, opts.height, opts.quality]);
};

CameraPreview.setColorEffect = function(effect, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setColorEffect", [effect]);
};

CameraPreview.setZoom = function(zoom, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setZoom", [zoom]);
};

CameraPreview.getMaxZoom = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getMaxZoom", []);
};

CameraPreview.getZoom = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getZoom", []);
};

CameraPreview.setPreviewSize = function(dimensions, onSuccess, onError) {
    dimensions = dimensions || {};
    dimensions.width = dimensions.width || window.screen.width;
    dimensions.height = dimensions.height || window.screen.height;

    return exec(onSuccess, onError, PLUGIN_NAME, "setPreviewSize", [dimensions.width, dimensions.height]);
};

CameraPreview.getSupportedPictureSizes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getSupportedPictureSizes", []);
};

CameraPreview.getSupportedFlashModes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getSupportedFlashModes", []);
};

CameraPreview.setFlashMode = function(flashMode, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setFlashMode", [flashMode]);
};

CameraPreview.tapToFocus = function(xPoint, yPoint, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "tapToFocus", [xPoint, yPoint]);
};

CameraPreview.getExposureModes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureModes", []);
};

CameraPreview.getExposureMode = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureMode", []);
};

CameraPreview.setExposureMode = function(lock, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setExposureMode", [lock]);
};

CameraPreview.getExposureCompensation = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureCompensation", []);
};

CameraPreview.setExposureCompensation = function(exposureCompensation, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setExposureCompensation", [exposureCompensation]);
};

CameraPreview.getExposureCompensationRange = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureCompensationRange", []);
};

CameraPreview.EXPOSURE_MODE = {
    LOCK: 'lock',
    AUTO: 'auto', // IOS Only
    CONTINUOUS: 'continuous', // IOS Only
    CUSTOM: 'custom' // IOS Only
};

CameraPreview.FLASH_MODE = {
    OFF: 'off',
    ON: 'on',
    AUTO: 'auto',
    RED_EYE: 'red-eye', // Android Only
    TORCH: 'torch'
};

CameraPreview.COLOR_EFFECT = {
    AQUA: 'aqua', // Android Only
    BLACKBOARD: 'blackboard', // Android Only
    MONO: 'mono',
    NEGATIVE: 'negative',
    NONE: 'none',
    POSTERIZE: 'posterize',
    SEPIA: 'sepia',
    SOLARIZE: 'solarize', // Android Only
    WHITEBOARD: 'whiteboard' // Android Only
};

CameraPreview.CAMERA_DIRECTION = {
    BACK: 'back',
    FRONT: 'front'
};

module.exports = CameraPreview;<|endoftext|>


<commit_before>/*
 * grunt-data-uri
 * http://github.com/ahomu/grunt-data-uri
 * http://aho.mu
 *
 * Copyright (c) 2012 ahomu
 * Licensed under the MIT license.
 */
module.exports = function (grunt) {

    'use strict';

    var fs = require('fs'),
        path = require('path'),
        datauri = require('datauri');

    var RE_CSS_URLFUNC = /(?:url\(["']?)(.*?)(?:["']?\))/,
        util = grunt.util || grunt.utils, // for 0.4.0
        gruntfileDir = path.resolve('./'),
        expandFiles;

    if (grunt.file.expandFiles) {
        expandFiles = grunt.file.expandFiles;
    } else {
        expandFiles = function (files) {
            return grunt.file.expand({filter: 'isFile'}, files);
        };
    }

    grunt.registerMultiTask('dataUri', 'Convert your css file image path!!', function () {
        // @memo this.file(0.3.x), this.files(0.4.0a) -> safe using this.data.src|dest

        var options = this.options ? this.options() : this.data.options, // for 0.4.0
            srcFiles = expandFiles(this.data.src),
            destDir = path.resolve(this.data.dest),
            haystack = [];

        var imageExtensions = options.imageExtensions ? options.imageExtensions : ['jpg','png','gif'];
        var imageExtensionRegex = createImgExtensionRegex(imageExtensions);

        expandFiles(options.target).forEach(function (imgPath) {
            haystack.push(path.resolve(imgPath));
        });

        srcFiles.forEach(function (src) {
            var content = grunt.file.read(src),
                matches = content.match(new RegExp(RE_CSS_URLFUNC.source, 'g')),
                outputTo = destDir + '/' + path.basename(src),
                baseDir,
                uris;

            // Detect baseDir for using traversal image files
            baseDir = options.baseDir ? path.resolve(options.baseDir)    // specified base dir
                : path.resolve(path.dirname(src)); // detected from src

            // Not found image path
            if (!matches) {
                grunt.log.subhead('SRC: file uri not found on ' + src);
                grunt.file.write(outputTo, content);
                grunt.log.ok('Skipped');
                grunt.log.ok('=> ' + outputTo);
                return;
            }

            // Change base to src(css, html, js) existing dir
            grunt.file.setBase(baseDir);

            // List uniq image URIs
            uris = util._.uniq(matches.map(function (m) {
                return m.match(RE_CSS_URLFUNC)[1];
            }));

            // Exclude external http resource
            uris = uris.filter(function (u) {
                return !u.match('(data:|http)');
            });

            // Exclude non image extensions
            uris = uris.filter(function (u) {
                return u.match(imageExtensionRegex);
            });

            grunt.log.subhead('SRC: ' + uris.length + ' file uri found on ' + src);

            // Process urls
            uris.forEach(function (uri) {
                var src, replacement, needle, fixedUri;

                // fixed current dir when specified uri is like root
                fixedUri = uri.indexOf('/') === 0 ? '.' + uri : uri;

                // Resolve image realpath
                needle = path.resolve(fixedUri);

                // Assume file existing cause found from haystack
                if (haystack.indexOf(needle) !== -1) {
                    // check if file exceeds the max bytes
                    var fileSize = getFileSize(needle);
                    if (options.maxBytes && fileSize > options.maxBytes) {
                        // file is over the max size
                        grunt.log.ok('Skipping (size ' + fileSize + ' > ' + options.maxBytes + '): ' + uri);
                    } else {
                        // Encoding to Data uri
                        replacement = datauri(needle);
                        grunt.log.ok('Encode: ' + needle);
                    }
                } else {
                    if (options.fixDirLevel) {
                        // Diff of directory level
                        replacement = adjustDirectoryLevel(fixedUri, destDir, baseDir);
                        grunt.log.ok('Adjust: ' + uri + ' -> ' + replacement);
                    } else {
                        replacement = uri;
                        grunt.log.ok('Ignore: ' + uri);
                    }
                }

                content = content.replace(new RegExp(uri, 'g'), replacement);
            });

            // Revert base to gruntjs executing current dir
            grunt.file.setBase(gruntfileDir);
            grunt.file.write(outputTo, content);
            grunt.log.ok('=> ' + outputTo);
        });
    });

    /**
     *
     * @param imageExtensions
     * @returns {*|string}
     */
    function createImgExtensionRegex(imageExtensions){
        if(imageExtensions.length == 0){
            return [];
        }
        imageExtensions[0] = '\\.' + imageExtensions[0];
        return imageExtensions.join('|\\.');
    }

    /**
     * @param fullPath
     * @param options
     * @return {boolean} the file size, or undefined if not found
     */
    function getFileSize(fullPath) {
        if (!fs.existsSync(fullPath)) {
            return false;
        }

        var stats = fs.statSync(fullPath);
        if (!stats.isFile()) {
            return false;
        }
        return stats.size;
    }

    /**
     * @method adjustDirectoryLevel
     * @param {String} relativePath
     * @param {String} toDir
     * @param {String} fromDir
     * @return {String} resolvedPath
     */
    function adjustDirectoryLevel(relativePath, toDir, fromDir) {
        // fix ../path/to/img.jpg to path/to/img.jpg
        var resolvedPath = relativePath.replace(/^\.\//, '');

        if (toDir === fromDir) {
            // both toDir and fromDir are same base.
        }
        else if (fromDir.indexOf(toDir) === 0) {
            // fromDir is shallow than toDir
            path.relative(fromDir, toDir).split('/').forEach(function () {
                resolvedPath = resolvedPath.replace(/^\.\.\//, '');
            });
        }
        else if (toDir.indexOf(fromDir) === 0) {
            // toDir is depp than fromDir
            path.relative(fromDir, toDir).split('/').forEach(function () {
                resolvedPath = '../' + resolvedPath;
            });
        }
        return resolvedPath;
    }

};<commit_msg>a little bit of refactor - trying now to convert every uri instead of just from the haystack<commit_after>/*
 * grunt-data-uri
 * http://github.com/ahomu/grunt-data-uri
 * http://aho.mu
 *
 * Copyright (c) 2012 ahomu
 * Licensed under the MIT license.
 */
module.exports = function (grunt) {

    'use strict';

    var fs = require('fs'),
        path = require('path'),
        datauri = require('datauri');

    var RE_CSS_URLFUNC = /(?:url\(["']?)(.*?)(?:["']?\))/,
        util = grunt.util || grunt.utils, // for 0.4.0
        gruntfileDir = path.resolve('./');

    grunt.registerMultiTask('dataUri', 'Convert your css file image path!!', function () {
        // @memo this.file(0.3.x), this.files(0.4.0a) -> safe using this.data.src|dest

        var options = this.data.options,
            srcFiles = grunt.file.expand({filter: 'isFile'}, this.data.src),
            destDir = path.resolve(this.data.dest),
            haystack = [];

        options.imageExtensions = options.imageExtensions ? options.imageExtensions : ['jpg','png','gif'];
        options.imageExtensionRegex = options.imageExtensionRegex ? options.imageExtensionRegex : createImgExtensionRegex(options.imageExtensions);
        options.maxBytes = options.maxBytes ? options.maxBytes : '2048';

        grunt.file.expand({filter: 'isFile'}, options.target).forEach(function (imgPath) {
            grunt.log.ok('path ' + path.resolve(imgPath));
            haystack.push(path.resolve(imgPath));
        });

        grunt.log.ok('haystack size ' + haystack.length);

        srcFiles.forEach(function (src) {
            var content = grunt.file.read(src),
                matches = content.match(new RegExp(RE_CSS_URLFUNC.source, 'g')),
                outputTo = destDir + '/' + path.basename(src),
                baseDir,
                uris;

            // Detect baseDir for using traversal image files
            baseDir = options.baseDir ? path.resolve(options.baseDir)    // specified base dir
                : path.resolve(path.dirname(src)); // detected from src

            // Not found image path
            if (!matches) {
                grunt.log.subhead('SRC: file uri not found on ' + src);
                grunt.file.write(outputTo, content);
                grunt.log.ok('Skipped');
                grunt.log.ok('=> ' + outputTo);
                return;
            }

            // Change base to src(css, html, js) existing dir
            grunt.file.setBase(baseDir);

            // List uniq image URIs
            uris = util._.uniq(matches.map(function (m) {
                return m.match(RE_CSS_URLFUNC)[1];
            }));

            // Exclude external http resource
            uris = uris.filter(function (u) {
                return !u.match('(data:|http)');
            });

            // Exclude non image extensions
            uris = uris.filter(function (u) {
                return u.match(options.imageExtensionRegex);
            });

            grunt.log.subhead('SRC: ' + uris.length + ' file uri found on ' + src);

            // Process urls
            uris.forEach(function (uri) {
                var replacement,
                    needle,
                    fixedUri = fixUri(uri);

                // Resolve image realpath
                needle = path.resolve(fixedUri);

                // Assume file existing cause found from haystack
                if (haystack.indexOf(needle) !== -1) {
                    // check if file exceeds the max bytes
                    replacement = needle;
                } else {
                    // Diff of directory level
                    replacement = adjustDirectoryLevel(fixedUri, destDir, baseDir);
                    grunt.log.ok('Adjust: ' + fixedUri + ' -> ' + replacement);
                }

                var fileSize = getFileSize(replacement);
                grunt.log.ok('filesize: ' + fileSize);
                if (!fileSize){
                    grunt.log.warn('file not found. ' + replacement);
                    replacement = false;
                }

                if(fileSize > options.maxBytes) {
                    // file is over the max size
                    grunt.log.warn('Skipping (size ' + fileSize + ' > ' + options.maxBytes + '): ' + replacement);
                    replacement = false;
                }

                if(replacement){
                    // Encoding to Data uri
                    grunt.log.ok('Encode: ' + replacement);
                    replacement = datauri(replacement);
                    content = content.replace(new RegExp(uri, 'g'), replacement);
                }
            });

            // Revert base to gruntjs executing current dir
            grunt.file.setBase(gruntfileDir);
            grunt.file.write(outputTo, content);
            grunt.log.ok('=> ' + outputTo);
        });
    });

    /**
     *
     * @param imageExtensions
     * @returns {*|string}
     */
    function createImgExtensionRegex(imageExtensions){
        if(imageExtensions.length == 0){
            return [];
        }
        imageExtensions[0] = '\\.' + imageExtensions[0];
        return imageExtensions.join('|\\.');
    }

    /**
     * @param fullPath
     * @param options
     * @return {boolean} the file size, or undefined if not found
     */
    function getFileSize(fullPath) {
        if (!fs.existsSync(fullPath)) {
            return false;
        }

        var stats = fs.statSync(fullPath);
        if (!stats.isFile()) {
            return false;
        }
        return stats.size;
    }

    /**
     * @method adjustDirectoryLevel
     * @param {String} relativePath
     * @param {String} toDir
     * @param {String} fromDir
     * @return {String} resolvedPath
     */
    function adjustDirectoryLevel(relativePath, toDir, fromDir) {
        // fix ../path/to/img.jpg to path/to/img.jpg
        var resolvedPath = relativePath.replace(/^\.\//, '');

        if (toDir === fromDir) {
            // both toDir and fromDir are same base.
        }
        else if (fromDir.indexOf(toDir) === 0) {
            // fromDir is shallow than toDir
            path.relative(fromDir, toDir).split('/').forEach(function () {
                resolvedPath = resolvedPath.replace(/^\.\.\//, '');
            });
        }
        else if (toDir.indexOf(fromDir) === 0) {
            // toDir is depp than fromDir
            path.relative(fromDir, toDir).split('/').forEach(function () {
                resolvedPath = '../' + resolvedPath;
            });
        }

        return resolvedPath;
    }

    function fixUri(uri){
        // fixed current dir when specified uri is like root
        if(uri.indexOf('/') === 0){
            return '.' + uri;
        }

        return uri;
    }
};<|endoftext|>


<commit_before>var exec = require('cordova/exec');
var TAG = "NativeStorage.js";

function inBrowser() {
    return (window.cordova && window.cordova.platformId === 'browser') || !window.phonegap || !window.cordova;
}

/* Method for storage in localstorage if run in browser */
NativeStorage.prototype.setInLocalStorage = function (reference, variable, success, error) {
    try {
        var varAsString = JSON.stringify(variable);
        console.log("Saving: "+varAsString);
        localStorage.setItem(reference, varAsString);
        success(varAsString);
    } catch (err) {
        error(err);
    }

};

NativeStorage.prototype.getFromLocalStorage = function (reference, success, error) {
    try {
        var obj = JSON.parse(localStorage.getItem(reference));
        console.log("Reading: "+obj);
        success(obj);
    } catch (err) {
        error(err);
    }
};

function NativeStorage() {
    console.log(TAG + ": is created");
    if(inBrowser()){
        console.log("browser detected!");
        if(!window.localStorage) console.log("ALERT! localstorage isn't supported");
    }
}

NativeStorage.prototype.set = function(reference, value, success, error) {
    if (reference === null) {
        error("The reference can't be null");
    }
    if (value === null) {
        error("a Null value isn't supported");
    }
    switch (typeof value) {
        case 'undefined':
            error("an undefined type isn't supported");
            break;
        case 'boolean':
            {
                this.putBoolean(reference, value, success, error);
                break;
            }
        case 'number':
            {
                // Good now check if it's a float or an int
                if (value === +value) {
                    if (value === (value | 0)) {
                        // it's an int
                        this.putInt(reference, value, success, error);
                    } else if (value !== (value | 0)) {
                        this.putDouble(reference, value, success, error);
                    }
                }
                else error("The value doesn't seem to be a number");
                break;
            }
        case 'string': {
            this.putString(reference, value, success, error);
            break;
        }
        case 'object': {
            this.putObject(reference, value, success, error);
            break;
        }
        default:
            error("The type isn't supported or isn't been recognized");
    }
};

/* removing */
NativeStorage.prototype.remove = function(reference, success, error) {
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }

    if(inBrowser()){
        try {
            localStorage.removeItem(reference);
            success();
        }catch(e){error(e);}
    }else{
        exec(success, error, "NativeStorage", "remove", [reference]);
    }
};

/* boolean storage */
NativeStorage.prototype.putBoolean = function(reference, aBoolean, success, error) {
    //console.log(TAG+": putBoolean");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }

    if (aBoolean === null) {
        error("a Null value isn't supported"); return;
    }

    if (typeof aBoolean === 'boolean') {
        if(inBrowser()){
            this.setInLocalStorage(reference,aBoolean, success, error);
        }else {
            exec(success, error, "NativeStorage", "putBoolean", [reference, aBoolean]);
        }
    }
    else error("Only boolean types are supported");
};

NativeStorage.prototype.getBoolean = function(reference, success, error) {
    //console.log(TAG+": getBoolean");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
            this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getBoolean", [reference]);
    }
};

/* int storage */
NativeStorage.prototype.putInt = function(reference, anInt, success, error) {
    //console.log(TAG+": putInt");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }

    if(inBrowser()){
        this.setInLocalStorage(reference,anInt, success, error);
    }else {
        exec(success, error, "NativeStorage", "putInt", [reference, anInt]);
    }
};

NativeStorage.prototype.getInt = function(reference, success, error) {
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getInt", [reference]);
    }
};

/* float storage */
NativeStorage.prototype.putDouble = function(reference, aFloat, success, error) {
    //console.log(TAG+": putFloat");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.setInLocalStorage(reference,aFloat, success, error);
    }else {
        exec(success, error, "NativeStorage", "putDouble", [reference, aFloat]);
    }
};

NativeStorage.prototype.getDouble = function(reference, success, error) {
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getDouble", [reference]);
    }
};

/* string storage */
NativeStorage.prototype.putString = function(reference, s, success, error) {
    //console.log(TAG+": putString");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.setInLocalStorage(reference, s, success, error);
    }else {
        exec(success, error, "NativeStorage", "putString", [reference, s]);
    }
};

NativeStorage.prototype.getString = function(reference, success, error) {
    //console.log(TAG+": getString");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getString", [reference]);
    }
};

/* object storage */
NativeStorage.prototype.putObject = function(reference, obj, success, error) {
    if(inBrowser()){
        this.setInLocalStorage(reference, obj, success, error);
    }else {
        var objAsString = "";
        try {
            objAsString = JSON.stringify(obj);
        } catch (err) {
            error(err);
        }
        this.putString(reference, objAsString, success, error);
    }
};

NativeStorage.prototype.getObject = function(reference, success, error) {
    //console.log(TAG+": getObject");
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        this.getString(reference, function (data) {
            var obj = {};
            try {
                obj = JSON.parse(data);
                success(obj);
            } catch (err) {
                error(err);
            }
        }, error);
    }
};

var nativeStorage = new NativeStorage();
module.exports = nativeStorage;<commit_msg>Fixed bug in inBrowser function<commit_after>var exec = require('cordova/exec');
var TAG = "NativeStorage.js";

function inBrowser() {
    return (window.cordova && window.cordova.platformId === 'browser') || !(window.phonegap || window.cordova);
}

/* Method for storage in localstorage if run in browser */
NativeStorage.prototype.setInLocalStorage = function (reference, variable, success, error) {
    try {
        var varAsString = JSON.stringify(variable);
        console.log("Saving: "+varAsString);
        localStorage.setItem(reference, varAsString);
        success(varAsString);
    } catch (err) {
        error(err);
    }

};

NativeStorage.prototype.getFromLocalStorage = function (reference, success, error) {
    try {
        var obj = JSON.parse(localStorage.getItem(reference));
        console.log("Reading: "+obj);
        success(obj);
    } catch (err) {
        error(err);
    }
};

function NativeStorage() {
    console.log(TAG + ": is created");
    if(inBrowser()){
        console.log("browser detected!");
        if(!window.localStorage) console.log("ALERT! localstorage isn't supported");
    }
}

NativeStorage.prototype.set = function(reference, value, success, error) {
    if (reference === null) {
        error("The reference can't be null");
    }
    if (value === null) {
        error("a Null value isn't supported");
    }
    switch (typeof value) {
        case 'undefined':
            error("an undefined type isn't supported");
            break;
        case 'boolean':
            {
                this.putBoolean(reference, value, success, error);
                break;
            }
        case 'number':
            {
                // Good now check if it's a float or an int
                if (value === +value) {
                    if (value === (value | 0)) {
                        // it's an int
                        this.putInt(reference, value, success, error);
                    } else if (value !== (value | 0)) {
                        this.putDouble(reference, value, success, error);
                    }
                }
                else error("The value doesn't seem to be a number");
                break;
            }
        case 'string': {
            this.putString(reference, value, success, error);
            break;
        }
        case 'object': {
            this.putObject(reference, value, success, error);
            break;
        }
        default:
            error("The type isn't supported or isn't been recognized");
    }
};

/* removing */
NativeStorage.prototype.remove = function(reference, success, error) {
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }

    if(inBrowser()){
        try {
            localStorage.removeItem(reference);
            success();
        }catch(e){error(e);}
    }else{
        exec(success, error, "NativeStorage", "remove", [reference]);
    }
};

/* boolean storage */
NativeStorage.prototype.putBoolean = function(reference, aBoolean, success, error) {
    //console.log(TAG+": putBoolean");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }

    if (aBoolean === null) {
        error("a Null value isn't supported"); return;
    }

    if (typeof aBoolean === 'boolean') {
        if(inBrowser()){
            this.setInLocalStorage(reference,aBoolean, success, error);
        }else {
            exec(success, error, "NativeStorage", "putBoolean", [reference, aBoolean]);
        }
    }
    else error("Only boolean types are supported");
};

NativeStorage.prototype.getBoolean = function(reference, success, error) {
    //console.log(TAG+": getBoolean");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
            this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getBoolean", [reference]);
    }
};

/* int storage */
NativeStorage.prototype.putInt = function(reference, anInt, success, error) {
    //console.log(TAG+": putInt");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }

    if(inBrowser()){
        this.setInLocalStorage(reference,anInt, success, error);
    }else {
        exec(success, error, "NativeStorage", "putInt", [reference, anInt]);
    }
};

NativeStorage.prototype.getInt = function(reference, success, error) {
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getInt", [reference]);
    }
};

/* float storage */
NativeStorage.prototype.putDouble = function(reference, aFloat, success, error) {
    //console.log(TAG+": putFloat");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.setInLocalStorage(reference,aFloat, success, error);
    }else {
        exec(success, error, "NativeStorage", "putDouble", [reference, aFloat]);
    }
};

NativeStorage.prototype.getDouble = function(reference, success, error) {
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getDouble", [reference]);
    }
};

/* string storage */
NativeStorage.prototype.putString = function(reference, s, success, error) {
    //console.log(TAG+": putString");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.setInLocalStorage(reference, s, success, error);
    }else {
        exec(success, error, "NativeStorage", "putString", [reference, s]);
    }
};

NativeStorage.prototype.getString = function(reference, success, error) {
    //console.log(TAG+": getString");
    if (reference === null) {
        error("Null reference isn't supported"); return;
    }
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        exec(success, error, "NativeStorage", "getString", [reference]);
    }
};

/* object storage */
NativeStorage.prototype.putObject = function(reference, obj, success, error) {
    if(inBrowser()){
        this.setInLocalStorage(reference, obj, success, error);
    }else {
        var objAsString = "";
        try {
            objAsString = JSON.stringify(obj);
        } catch (err) {
            error(err);
        }
        this.putString(reference, objAsString, success, error);
    }
};

NativeStorage.prototype.getObject = function(reference, success, error) {
    //console.log(TAG+": getObject");
    if(inBrowser()){
        this.getFromLocalStorage(reference, success, error);
    }else {
        this.getString(reference, function (data) {
            var obj = {};
            try {
                obj = JSON.parse(data);
                success(obj);
            } catch (err) {
                error(err);
            }
        }, error);
    }
};

var nativeStorage = new NativeStorage();
module.exports = nativeStorage;<|endoftext|>


<commit_before>/*
 * grunt-includes
 * https://github.com/vanetix/grunt-includes
 *
 * Copyright (c) 2013 Matt McFarland
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  /**
   * Dependencies
   */

  var path = require('path');

  /**
   * Regex for parsing includes
   */

  var defaultRegexp = /^(\s*)include\s+"(\S+)"\s*$/;

  /**
   * Regex for matching new lines
   */

  var newlineRegexp = /\r?\n/g;

  /**
   * Core `grunt-includes` task
   * Iterates over all source files and calls `recurse(path)` on each
   */

  grunt.registerMultiTask('includes', 'Include other files within files.', function() {
    var banner;

    /**
     * Default options
     */

    var opts = this.options({
      debug: false,
      banner: '',
      silent: false,
      duplicates: true,
      includeRegexp: defaultRegexp,
      includePath: '',
      filenamePrefix: '',
      filenameSuffix: ''
    });

    // Render banner
    banner = grunt.template.process(opts.banner);

    this.files.forEach(function(f) {
      var src, cwd = f.cwd;

      src = f.src.filter(function(p) {
        if(cwd) {
          p = path.join(f.cwd, p);
        }

        if(grunt.file.isFile(p)) {
          return true;
        } else {
          grunt.log.warn('Source file "' + p + '" not found.');
          return false;
        }
      });

      if(src.length > 1 && isFilename(f.dest)) {
        grunt.log.warn('Source file cannot be more than one when dest is a file.');
      }

      src.forEach(function(p) {
        var fileName = f.flatten ? path.basename(p) : p;
        var outFile = isFilename(f.dest) ? f.dest : path.join(f.dest, fileName);

        if(cwd) {
          p = path.join(cwd, p);
        }

        grunt.file.write(outFile, banner + recurse(p, opts));

        if(!opts.silent) {
          grunt.log.oklns('Saved ' + outFile);
        }
      });

    });
  });

  /**
   * Checks if `p` is a filepath, being it has an extension.
   *
   * @param {String} p
   * @return {Boolean}
   */

  function isFilename(p) {
    return !!path.extname(p);
  }

  /**
   * Returns the comment style for file `p`
   *
   * @param {String} p
   * @return {String}
   */

  function commentStyle(p) {
    var comments,
        ext = path.extname(p).slice(1);

    comments = {
      js: "/* %s */",
      css: "/* %s */",
      html: "<!-- %s -->"
    };

    return comments[ext] || '/* %s */';
  }

  /**
   * Returns the new line style for file `p`
   *
   * @param {String} p
   * @return {String}
   */

  function newlineStyle(p) {
    var matches = grunt.file.read(p).match(newlineRegexp);

    return (matches && matches[0]) || grunt.util.linefeed;
  }

  /**
   * Helper for `includes` builds all includes for `p`
   *
   * @param {String} p
   * @return {String}
   */

  function recurse(p, opts, included, indents) {
    var src, next, match, error, comment,
        newline, compiled, indent, fileLocation;

    if(!grunt.file.isFile(p)) {
      grunt.log.warn('Included file "' + p + '" not found.');
      return 'Error including "' + p + '".';
    }

    indents = indents || '';
    comment = commentStyle(p);
    newline = newlineStyle(p);
    included = included || [];

    /**
     * If `opts.duplicates` is false and file has been included,
     * error
     */

    if(!opts.duplicates && ~included.indexOf(p)) {
      error = 'Duplicate include: ' + p + ' skipping.';
      grunt.log.error(error);

      if(opts.debug) {
        return comment.replace(/%s/g, error);
      } else {
        return '';
      }
    }

    /**
     * At this point the file is considered included
     */

    included.push(p);

    /**
     * Split the file on newlines
     */

    src = grunt.file.read(p).split(newline);

    /**
     * Loop through the file calling `recurse` if an include is found
     */

    compiled = src.map(function(line) {
      match = line.match(opts.includeRegexp);

      /**
       * If the line has an include statement, recurse
       */

      if(match) {
        fileLocation = match[2];
        indent = match[1];

        if (!fileLocation) {
          fileLocation = indent;
          indent = '';
        }

        fileLocation = opts.filenamePrefix + fileLocation + opts.filenameSuffix;
        next = path.join((opts.includePath || path.dirname(p)), fileLocation);
        line = recurse(next, opts, included, indents + indent);

        /**
         * Include debug comments if `opts.debug`
         */

        if(opts.debug) {
          line = comment.replace(/%s/g, 'Begin: ' + next) +
                 newline + line + newline + comment.replace(/%s/g, 'End: ' + next);
        }
      }

      // If there are indents and not a match, add them to the line
      return line && indents && !match ? indents + line : line;
    });

    return  compiled.join(newline);
  }

};
<commit_msg>Don't remove other text in the same line of include directive<commit_after>/*
 * grunt-includes
 * https://github.com/vanetix/grunt-includes
 *
 * Copyright (c) 2013 Matt McFarland
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  /**
   * Dependencies
   */

  var path = require('path');

  /**
   * Regex for parsing includes
   */

  var defaultRegexp = /^(\s*)include\s+"(\S+)"\s*$/;

  /**
   * Regex for matching new lines
   */

  var newlineRegexp = /\r?\n/g;

  /**
   * Core `grunt-includes` task
   * Iterates over all source files and calls `recurse(path)` on each
   */

  grunt.registerMultiTask('includes', 'Include other files within files.', function() {
    var banner;

    /**
     * Default options
     */

    var opts = this.options({
      debug: false,
      banner: '',
      silent: false,
      duplicates: true,
      includeRegexp: defaultRegexp,
      includePath: '',
      filenamePrefix: '',
      filenameSuffix: ''
    });

    // Render banner
    banner = grunt.template.process(opts.banner);

    this.files.forEach(function(f) {
      var src, cwd = f.cwd;

      src = f.src.filter(function(p) {
        if(cwd) {
          p = path.join(f.cwd, p);
        }

        if(grunt.file.isFile(p)) {
          return true;
        } else {
          grunt.log.warn('Source file "' + p + '" not found.');
          return false;
        }
      });

      if(src.length > 1 && isFilename(f.dest)) {
        grunt.log.warn('Source file cannot be more than one when dest is a file.');
      }

      src.forEach(function(p) {
        var fileName = f.flatten ? path.basename(p) : p;
        var outFile = isFilename(f.dest) ? f.dest : path.join(f.dest, fileName);

        if(cwd) {
          p = path.join(cwd, p);
        }

        grunt.file.write(outFile, banner + recurse(p, opts));

        if(!opts.silent) {
          grunt.log.oklns('Saved ' + outFile);
        }
      });

    });
  });

  /**
   * Checks if `p` is a filepath, being it has an extension.
   *
   * @param {String} p
   * @return {Boolean}
   */

  function isFilename(p) {
    return !!path.extname(p);
  }

  /**
   * Returns the comment style for file `p`
   *
   * @param {String} p
   * @return {String}
   */

  function commentStyle(p) {
    var comments,
        ext = path.extname(p).slice(1);

    comments = {
      js: "/* %s */",
      css: "/* %s */",
      html: "<!-- %s -->"
    };

    return comments[ext] || '/* %s */';
  }

  /**
   * Returns the new line style for file `p`
   *
   * @param {String} p
   * @return {String}
   */

  function newlineStyle(p) {
    var matches = grunt.file.read(p).match(newlineRegexp);

    return (matches && matches[0]) || grunt.util.linefeed;
  }

  /**
   * Helper for `includes` builds all includes for `p`
   *
   * @param {String} p
   * @return {String}
   */

  function recurse(p, opts, included, indents) {
    var src, next, match, error, comment,
        newline, compiled, indent, fileLocation;

    if(!grunt.file.isFile(p)) {
      grunt.log.warn('Included file "' + p + '" not found.');
      return 'Error including "' + p + '".';
    }

    indents = indents || '';
    comment = commentStyle(p);
    newline = newlineStyle(p);
    included = included || [];

    /**
     * If `opts.duplicates` is false and file has been included,
     * error
     */

    if(!opts.duplicates && ~included.indexOf(p)) {
      error = 'Duplicate include: ' + p + ' skipping.';
      grunt.log.error(error);

      if(opts.debug) {
        return comment.replace(/%s/g, error);
      } else {
        return '';
      }
    }

    /**
     * At this point the file is considered included
     */

    included.push(p);

    /**
     * Split the file on newlines
     */

    src = grunt.file.read(p).split(newline);

    /**
     * Loop through the file calling `recurse` if an include is found
     */

    compiled = src.map(function(line) {
      match = line.match(opts.includeRegexp);

      /**
       * If the line has an include statement, recurse
       */

      if(match) {
        fileLocation = match[2];
        indent = match[1];

        if (!fileLocation) {
          fileLocation = indent;
          indent = '';
        }

        fileLocation = opts.filenamePrefix + fileLocation + opts.filenameSuffix;
        next = path.join((opts.includePath || path.dirname(p)), fileLocation);
        var oldLine = line;
        line = recurse(next, opts, included, indents + indent);

        /**
         * Include debug comments if `opts.debug`
         */

        if(opts.debug) {
          line = comment.replace(/%s/g, 'Begin: ' + next) +
                 newline + line + newline + comment.replace(/%s/g, 'End: ' + next);
        }
        line = oldLine.replace(opts.includeRegexp, line);
      }

      // If there are indents and not a match, add them to the line
      return line && indents && !match ? indents + line : line;
    });

    return  compiled.join(newline);
  }

};
<|endoftext|>


<commit_before>/*
* grunt-jscs
* https://github.com/dsheiko/grunt-jscs
*
* Copyright (c) 2013 Dmitry Sheiko
* Licensed under the MIT license.
* @jscs standard:Jquery
*/
"use strict";

// External libs.
var path = require( "path" );
var exec = require( "child_process" ).exec;

exports.init = function( grunt ) {
	var exports = {},
		defaults = {
			// Default options
			standard: false,
			report: false,
			reportFile: false
		},
		argv = [ "node", "jscs" ],
		done = null,
		config = {},
		/**
		* Builds phpunit command
		* @param {string} fileDest
		* @return string
		*/
		buildArgv = function( fileDest ) {

			if ( grunt.option( "standard" ) || config.standard ) {
				// Define the code sniffer standard.
				argv.push( " --standard=" + config.standard );
			}

			if ( grunt.option( "report" ) || config.report ) {
				argv.push( " --report=" + config.report );
			}

			if ( grunt.option( "report-file" ) || config.reportFile ) {
				argv.push( " --report-file=" + config.reportFile );
			}

			argv.push( fileDest );

			return argv;
		};

	/**
	* Setup task before running it
	*
	* @param Object runner
	*/
	exports.setup = function( runner ) {

		var cmd,
				where = runner.data.join( " " );
		config = runner.options( defaults );

		buildArgv( where );

		cmd = argv.join( " " );

		grunt.log.writeln( "Starting jscs on " + where );
		grunt.verbose.writeln( "Exec: " + cmd );

		done = runner.async();
	};

	/**
	* Runs phpunit command with options
	*
	*/
	exports.run = function() {
	var jscodesniffer = require( "jscodesniffer" );
	jscodesniffer( argv, process.cwd() );
	};

	return exports;
};<commit_msg>task was bearing the pipeline because of redudand async call<commit_after>/*
* grunt-jscs
* https://github.com/dsheiko/grunt-jscs
*
* Copyright (c) 2013 Dmitry Sheiko
* Licensed under the MIT license.
* @jscs standard:Jquery
*/
"use strict";

// External libs.
var path = require( "path" );
var exec = require( "child_process" ).exec;

exports.init = function( grunt ) {
	var exports = {},
		defaults = {
			// Default options
			standard: false,
			report: false,
			reportFile: false
		},
		argv = [ "node", "jscs" ],
		config = {},
		/**
		* Builds phpunit command
		* @param {string} fileDest
		* @return string
		*/
		buildArgv = function( fileDest ) {

			if ( grunt.option( "standard" ) || config.standard ) {
				// Define the code sniffer standard.
				argv.push( " --standard=" + config.standard );
			}

			if ( grunt.option( "report" ) || config.report ) {
				argv.push( " --report=" + config.report );
			}

			if ( grunt.option( "report-file" ) || config.reportFile ) {
				argv.push( " --report-file=" + config.reportFile );
			}

			argv.push( fileDest );

			return argv;
		};

	/**
	* Setup task before running it
	*
	* @param Object runner
	*/
	exports.setup = function( runner ) {

		var cmd,
				where = runner.data.join( " " );
		config = runner.options( defaults );

		buildArgv( where );

		cmd = argv.join( " " );

		grunt.log.writeln( "Starting jscs on " + where );
		grunt.verbose.writeln( "Exec: " + cmd );
	};

	/**
	* Runs phpunit command with options
	*
	*/
	exports.run = function() {
		var jscodesniffer = require( "jscodesniffer" );
		jscodesniffer( argv, process.cwd() );
	};

	return exports;
};<|endoftext|>