<commit_before>var   fs = require('fs')
, Script = process.binding('evals').Script

;(function(){ if(typeof(from)!=="undefined"&&from){module.exports=from;return from}; return (function(){
  var root, From, Acquisition, ResolutionMutator, paths, extensions, filename, undefined, u = undefined
    , legacyRequire, compileScript, executeScript, constructCompiler, constructExecuter
    , absoluteMut, relativeMut, repositoryMut, subdirMut, libMut, initializerMut, extensionMut
    , absoluteResolver, relativeResolver, packageResolver
    , absoluteCompiler, relativeCompiler, packageCompiler
    , absoluteExecuter, relativeExecuter, packageExecuter
    , from, acquisition, export, import

  // No poopy.js to do our work for us here! )-:
  ;(function(){ var super = Function
    ;((From = function(blueprint){ var that
      (that = function(){return from.apply(that, arguments)})['__proto__'] = From.prototype

      if (!(blueprint && blueprint.imports)) that.imports = new(Object)()
      if (blueprint) Object.keys(blueprint).forEach(function(key){
        that[key] = blueprint[key] }); return that })
    .prototype = (function(){ var C; (C = new(Function)()).prototype = super.prototype; return new(C)() })())
      .constructor = From })()

  // =================
  // = Configuration =
  // =================

  /* This will override `require.paths`, if not empty */                                  ;From.prototype.paths =
  paths = undefined

  /* `.js` is first, by default, because we want to let library authros create
     JavaScript ‘loader’ files for their native extensions */                        ;From.prototype.extensions =
  extensions = ['', '.js', '.node']

  /* This will be defined differently for each `from` we create */                     ;From.prototype.filename =
  filename = undefined

  // ============
  // = Plumbing =
  // ============

  legacyRequire = function(from){ return function(path){ var exports
    return ((exports = require(path)) && exports.library === "from" ? from : exports) }}

  compileScript = function(source, filename){ var script;
    try { script = new(Script)(source.replace(/^\#\!.*\n/, '')) }
    catch (error) { if (SyntaxError.prototype.isPrototypeOf(error) &&
                          new(RegExp)("from-new.js").test(error.stack.split('\n')[1])) {
      console.error("OOPS: The following syntax error does *not* exist where it is reported!")
      console.error("  \\   Due to a bug in V8, the error is being reported as existing in `from.js`")
      console.error("  /   but it in fact originates from the following file:") }
      console.error("  \\ < "+filename+" >")
      throw error }

    // TODO: Figure out a way to get this out of the `Script` instance itself… it must store it somewhere
    script.filename = filename; return script }

  executeScript = function(script, imports, injections){ var sources, from, sandbox = new(Object)()
    for (source in (sources = [global, { from:(from = new(From)({ filename:script.filename, imports:imports })),
                                            imports:from.imports, require:legacyRequire(from),
                                            __filename:script.filename, global:sandbox }, injections]))
      for (variable in sources[source]) if (sources[source].hasOwnProperty(variable))
        sandbox[variable] = sources[source][variable]
    return script.runInNewContext(sandbox) }

  constructCompiler = function(resolver){ return function(pathBit, _){
    resolver(pathBit, function(e, pathBit){ if(e)return _(e)
      fs.readFile(pathBit, 'utf8', function(e, source){ if(e)return _(e)
        _(u, compileScript(source.toString(), pathBit), pathBit) }) }) }}
  constructExecuter = function(compiler){ return function(pathBit, imports, injections, _){
    compiler(pathBit, function(e, script, pathBit){ if(e)return _(e)
      process.nextTick(function(){ _(u, executeScript(script, imports, injections)) }) }) }}

  ;(function(){ var super = Function
    ;((Acquisition = function(blueprint){ var that
      (that = function(){return acquisition.apply(that, arguments)})['__proto__'] = Acquisition.prototype

      if (blueprint) Object.keys(blueprint).forEach(function(key){
        that[key] = blueprint[key] }); return that })
    .prototype = (function(){ var C; (C = new(Function)()).prototype = super.prototype; return new(C)() })())
      .constructor = From })()

  ;(function(){ var super = Function
    ;((ResolutionMutator = function(body, blueprint){ var that
      (that = function(){return that.body.apply(that, arguments)})['__proto__'] = ResolutionMutator.prototype

      if (typeof(body) === "function") that.body = body
      else throw new(Error)("ResolutionMutators cannot be created without a body")

      if (blueprint) Object.keys(blueprint).forEach(function(key){
        that[key] = blueprint[key] }); return that })
    .prototype = (function(){ var C; (C = new(Function)()).prototype = super.prototype; return new(C)() })())
      .constructor = From })()

  // =======================
  // = Low-level porcelain =
  // =======================
                                                                                ;From.prototype.extensionMut =
  extensionMut = new(ResolutionMutator)(function(path, query){ /* … */ })        ;From.prototype.initializerMut =
  initializerMut = new(ResolutionMutator)(function(path, query){ /* … */ })              ;From.prototype.libMut =
  libMut = new(ResolutionMutator)(function(path, query){ /* … */ })                   ;From.prototype.subdirMut =
  subdirMut = new(ResolutionMutator)(function(path, query){ /* … */ })            ;From.prototype.repositoryMut =
  repositoryMut = new(ResolutionMutator)(function(path, query){ /* … */ })          ;From.prototype.relativeMut =
  relativeMut = new(ResolutionMutator)(function(path, query){ /* … */ })            ;From.prototype.absoluteMut =
  absoluteMut = new(ResolutionMutator)(function(path, query){ /* … */ })
                                                                                ;From.prototype.resolveAbsolute =
  absoluteResolver = function(pathBit, _){
    // TODO: Windows support? What about drive names (C:/) and such?
    if (pathBit[0] !== '/' && pathBit[0] !== '~') return _(new(Error)("Path is not absolute."))

    // TODO: Support `~elliottcable/foo` type paths. (I have no idea, remotely, how to do this.)
    if (pathBit[0] === '~') pathBit = process.env['HOME'] + pathBit.substring(1)

    // Probably the most simplistic function in this library, we don’t
    // really have to ‘resolve’ an absolute path. We simply have to check
    // if it exists, and is a file.
    fs.stat(pathBit, function(e, file){ if(e)return _(e)
      if (file.isFile) return _(u, pathBit)
                  else return _(new(Error)("Path does not refer to a file.")) }) }
                                                                                ;From.prototype.compileAbsolute =
  absoluteCompiler = constructCompiler(absoluteResolver)                        ;From.prototype.executeAbsolute =
  absoluteExecuter = constructExecuter(absoluteCompiler)

  // ========================
  // = High-level porcelain =
  // ========================

  // This is the most common interface to `from`: you call this method with the paths to files you want, and a
  // callback that expects to be handed the library objects from those files.
  //
  // If you like, you can also omit the callback, and receive an `Acquisition` object, that you can then call at
  // a later date with a callback.
  from = function(pathBit, pathBit, pathBit /* ... */, _){ var acquisition, paths
    if (typeof(_ = arguments[arguments.length - 1]) !== "function") _ = undefined

           acquisition = new(Acquisition)({ from:this, paths:Array.prototype.slice.call(arguments, 0, _? -1:u) })
    if (_) acquisition (_)
    return acquisition
  }

  // Since `from` hands you back an `Acquisition` if you don’t provide a callback, you can call *it* with a
  // callback after having modified the `Acquisition`. This is utilized via something like:
  //
  //     from('something', 'somewhere/somethingElse')(function(something, somethingElse){
  //
  //     })
  //
  // (Notice that the *return value* of `from()` is what is called with the parenthesis, via `from()()`!)
  acquisition = function(_){ var that = this, iterate

    ;(iterate = function(res, index){ if (typeof(that.paths[index]) === "undefined") return _.call(u,res)
      absoluteExecuter(that.paths[index], that.exports[index], undefined, function(e, result){ if(e)throw e
        if (that.imports[index]) Object.keys(that.imports[index]).forEach(function(key){ var n
          that.from.imports[key] = result[(n = that.imports[index][key]) ? n : key] })
        res[index] = result; iterate(res, ++index) }) })(new(Array)(), 0)

    return that }

  // These two methods process `exports` and `imports`, respectively. The former takes objects containing
  // variable associations of the form `{"externalName": localVariable}` (notice that we pass localVariable
  // directly), while the latter takes associations of the form `{"localName", "externalName"}`.
  //
  // `export()`s are taken from the local namespace (i.e. whatever values you hand in in the association
  // objects) and placed into the `imports` object *of the file being acquired* (hence, “exporting” values to the
  // external file), while `import()`s are taken from the return value (presumably, then, the library-object) of
  // the file being acquired and placed into the `imports` object *of the file doing the acquiring* (i.e. where
  // `from()` was called from… hence, “importing” values from the external file).
                                                                                ;Acquisition.prototype.export =
  export = function(variable, variable, variable /* ... */){
    this.exports = Array.prototype.slice.call(arguments); return this }           ;Acquisition.prototype.import =
  import = function(variable, variable, variable /* ... */){
    this.imports = Array.prototype.slice.call(arguments); return this }

  root = new(From)({ filename:filename, root:true })
if (typeof(module) !== "undefined") (module.exports = root).library = "from"; return root })() })()
<commit_msg>(bug minor) Ensuring `acquisition`s properly return the return value of the callback<commit_after>var   fs = require('fs')
, Script = process.binding('evals').Script

;(function(){ if(typeof(from)!=="undefined"&&from){module.exports=from;return from}; return (function(){
  var root, From, Acquisition, ResolutionMutator, paths, extensions, filename, undefined, u = undefined
    , legacyRequire, compileScript, executeScript, constructCompiler, constructExecuter
    , absoluteMut, relativeMut, repositoryMut, subdirMut, libMut, initializerMut, extensionMut
    , absoluteResolver, relativeResolver, packageResolver
    , absoluteCompiler, relativeCompiler, packageCompiler
    , absoluteExecuter, relativeExecuter, packageExecuter
    , from, acquisition, export, import

  // No poopy.js to do our work for us here! )-:
  ;(function(){ var super = Function
    ;((From = function(blueprint){ var that
      (that = function(){return from.apply(that, arguments)})['__proto__'] = From.prototype

      if (!(blueprint && blueprint.imports)) that.imports = new(Object)()
      if (blueprint) Object.keys(blueprint).forEach(function(key){
        that[key] = blueprint[key] }); return that })
    .prototype = (function(){ var C; (C = new(Function)()).prototype = super.prototype; return new(C)() })())
      .constructor = From })()

  // =================
  // = Configuration =
  // =================

  /* This will override `require.paths`, if not empty */                                  ;From.prototype.paths =
  paths = undefined

  /* `.js` is first, by default, because we want to let library authros create
     JavaScript ‘loader’ files for their native extensions */                        ;From.prototype.extensions =
  extensions = ['', '.js', '.node']

  /* This will be defined differently for each `from` we create */                     ;From.prototype.filename =
  filename = undefined

  // ============
  // = Plumbing =
  // ============

  legacyRequire = function(from){ return function(path){ var exports
    return ((exports = require(path)) && exports.library === "from" ? from : exports) }}

  compileScript = function(source, filename){ var script;
    try { script = new(Script)(source.replace(/^\#\!.*\n/, '')) }
    catch (error) { if (SyntaxError.prototype.isPrototypeOf(error) &&
                          new(RegExp)("from-new.js").test(error.stack.split('\n')[1])) {
      console.error("OOPS: The following syntax error does *not* exist where it is reported!")
      console.error("  \\   Due to a bug in V8, the error is being reported as existing in `from.js`")
      console.error("  /   but it in fact originates from the following file:") }
      console.error("  \\ < "+filename+" >")
      throw error }

    // TODO: Figure out a way to get this out of the `Script` instance itself… it must store it somewhere
    script.filename = filename; return script }

  executeScript = function(script, imports, injections){ var sources, from, sandbox = new(Object)()
    for (source in (sources = [global, { from:(from = new(From)({ filename:script.filename, imports:imports })),
                                            imports:from.imports, require:legacyRequire(from),
                                            __filename:script.filename, global:sandbox }, injections]))
      for (variable in sources[source]) if (sources[source].hasOwnProperty(variable))
        sandbox[variable] = sources[source][variable]
    return script.runInNewContext(sandbox) }

  constructCompiler = function(resolver){ return function(pathBit, _){
    resolver(pathBit, function(e, pathBit){ if(e)return _(e)
      fs.readFile(pathBit, 'utf8', function(e, source){ if(e)return _(e)
        _(u, compileScript(source.toString(), pathBit), pathBit) }) }) }}
  constructExecuter = function(compiler){ return function(pathBit, imports, injections, _){
    compiler(pathBit, function(e, script, pathBit){ if(e)return _(e)
      process.nextTick(function(){ _(u, executeScript(script, imports, injections)) }) }) }}

  ;(function(){ var super = Function
    ;((Acquisition = function(blueprint){ var that
      (that = function(){return acquisition.apply(that, arguments)})['__proto__'] = Acquisition.prototype

      if (blueprint) Object.keys(blueprint).forEach(function(key){
        that[key] = blueprint[key] }); return that })
    .prototype = (function(){ var C; (C = new(Function)()).prototype = super.prototype; return new(C)() })())
      .constructor = From })()

  ;(function(){ var super = Function
    ;((ResolutionMutator = function(body, blueprint){ var that
      (that = function(){return that.body.apply(that, arguments)})['__proto__'] = ResolutionMutator.prototype

      if (typeof(body) === "function") that.body = body
      else throw new(Error)("ResolutionMutators cannot be created without a body")

      if (blueprint) Object.keys(blueprint).forEach(function(key){
        that[key] = blueprint[key] }); return that })
    .prototype = (function(){ var C; (C = new(Function)()).prototype = super.prototype; return new(C)() })())
      .constructor = From })()

  // =======================
  // = Low-level porcelain =
  // =======================
                                                                                ;From.prototype.extensionMut =
  extensionMut = new(ResolutionMutator)(function(path, query){ /* … */ })        ;From.prototype.initializerMut =
  initializerMut = new(ResolutionMutator)(function(path, query){ /* … */ })              ;From.prototype.libMut =
  libMut = new(ResolutionMutator)(function(path, query){ /* … */ })                   ;From.prototype.subdirMut =
  subdirMut = new(ResolutionMutator)(function(path, query){ /* … */ })            ;From.prototype.repositoryMut =
  repositoryMut = new(ResolutionMutator)(function(path, query){ /* … */ })          ;From.prototype.relativeMut =
  relativeMut = new(ResolutionMutator)(function(path, query){ /* … */ })            ;From.prototype.absoluteMut =
  absoluteMut = new(ResolutionMutator)(function(path, query){ /* … */ })
                                                                                ;From.prototype.resolveAbsolute =
  absoluteResolver = function(pathBit, _){
    // TODO: Windows support? What about drive names (C:/) and such?
    if (pathBit[0] !== '/' && pathBit[0] !== '~') return _(new(Error)("Path is not absolute."))

    // TODO: Support `~elliottcable/foo` type paths. (I have no idea, remotely, how to do this.)
    if (pathBit[0] === '~') pathBit = process.env['HOME'] + pathBit.substring(1)

    // Probably the most simplistic function in this library, we don’t
    // really have to ‘resolve’ an absolute path. We simply have to check
    // if it exists, and is a file.
    fs.stat(pathBit, function(e, file){ if(e)return _(e)
      if (file.isFile) return _(u, pathBit)
                  else return _(new(Error)("Path does not refer to a file.")) }) }
                                                                                ;From.prototype.compileAbsolute =
  absoluteCompiler = constructCompiler(absoluteResolver)                        ;From.prototype.executeAbsolute =
  absoluteExecuter = constructExecuter(absoluteCompiler)

  // ========================
  // = High-level porcelain =
  // ========================

  // This is the most common interface to `from`: you call this method with the paths to files you want, and a
  // callback that expects to be handed the library objects from those files.
  //
  // If you like, you can also omit the callback, and receive an `Acquisition` object, that you can then call at
  // a later date with a callback.
  from = function(pathBit, pathBit, pathBit /* ... */, _){ var acquisition, paths
    if (typeof(_ = arguments[arguments.length - 1]) !== "function") _ = undefined

           acquisition = new(Acquisition)({ from:this, paths:Array.prototype.slice.call(arguments, 0, _? -1:u) })
    if (_) acquisition (_)
    return acquisition }

  // Since `from` hands you back an `Acquisition` if you don’t provide a callback, you can call *it* with a
  // callback after having modified the `Acquisition`. This is utilized via something like:
  //
  //     from('something', 'somewhere/somethingElse')(function(something, somethingElse){
  //
  //     })
  //
  // (Notice that the *return value* of `from()` is what is called with the parenthesis, via `from()()`!)
  acquisition = function(_){ var that = this, iterate
    ;(iterate = function(res, index){ if (typeof(that.paths[index]) === "undefined") return _.call(u,res)
      absoluteExecuter(that.paths[index], that.exports[index], undefined, function(e, result){ if(e)throw e
        if (that.imports[index]) Object.keys(that.imports[index]).forEach(function(key){ var n
          that.from.imports[key] = result[(n = that.imports[index][key]) ? n : key] })
        res[index] = result; return iterate(res, ++index) }) })(new(Array)(), 0)
    return that }

  // These two methods process `exports` and `imports`, respectively. The former takes objects containing
  // variable associations of the form `{"externalName": localVariable}` (notice that we pass localVariable
  // directly), while the latter takes associations of the form `{"localName", "externalName"}`.
  //
  // `export()`s are taken from the local namespace (i.e. whatever values you hand in in the association
  // objects) and placed into the `imports` object *of the file being acquired* (hence, “exporting” values to the
  // external file), while `import()`s are taken from the return value (presumably, then, the library-object) of
  // the file being acquired and placed into the `imports` object *of the file doing the acquiring* (i.e. where
  // `from()` was called from… hence, “importing” values from the external file).
                                                                                ;Acquisition.prototype.export =
  export = function(variable, variable, variable /* ... */){
    this.exports = Array.prototype.slice.call(arguments); return this }           ;Acquisition.prototype.import =
  import = function(variable, variable, variable /* ... */){
    this.imports = Array.prototype.slice.call(arguments); return this }

  root = new(From)({ filename:filename, root:true })
if (typeof(module) !== "undefined") (module.exports = root).library = "from"; return root })() })()
<|endoftext|>


<commit_before>

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by CodeZu.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

var Client = require('../../../client'), constants = Client.constants;

module.exports = Client.sub({
	getShipment: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/{shipmentId}?responseFields={responseFields}'
	}),
	getAvailableShipmentMethods: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/methods?draft={draft}'
	}),
	createPackageShipments: Client.method({
		method: constants.verbs.POST,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments'
	}),
	deleteShipment: Client.method({
		method: constants.verbs.DELETE,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/{shipmentId}'
	})
});
<commit_msg>add shipment price and adjustments endpoints<commit_after>

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by CodeZu.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

var Client = require('../../../client'), constants = Client.constants;

module.exports = Client.sub({
	getShipment: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/{shipmentId}?responseFields={responseFields}'
	}),
	getAvailableShipmentMethods: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/methods?draft={draft}'
	}),
	createPackageShipments: Client.method({
		method: constants.verbs.POST,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments'
	}),
	deleteShipment: Client.method({
		method: constants.verbs.DELETE,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/{shipmentId}'
	}),
	updateShipmentItem: Client.method({
		method: constants.verbs.POST,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/{shipmentNumber}/item/{itemId}/adjustments'
	}),
	updateShipmentAdjustments: Client.method({
		method: constants.verbs.POST,
		url: '{+tenantPod}api/commerce/orders/{orderId}/shipments/{shipmentNumber}/adjustments'
	}),
});
<|endoftext|>


<commit_before>module.exports = (function() {
  var crypto = require('crypto');
  var http = require('http');

  var Pusher = function(options) {
    this.options = options;
    return this;
  }

  Pusher.prototype.domain = 'api.pusherapp.com';

  Pusher.prototype.auth = function(socketId, channel) {
    return {
      auth: this.options.key + ':' + crypto.createHmac('sha256', this.options.secret).update(socketId + ':' + channel).digest('hex')
    };
  }

  Pusher.prototype.trigger = function(channel, event, message, socketId, callback) {
    var timestamp = parseInt(new Date().getTime() / 1000);
    var requestBody = JSON.stringify(message);
    var hash = crypto.createHash('md5').update(new Buffer(requestBody).toString('binary')).digest('hex');

    var params = [
      'auth_key=', this.options.key,
      '&auth_timestamp=', timestamp,
      '&auth_version=', '1.0',
      '&body_md5=', hash,
      '&name=', event
    ];
    if (socketId) {
      params.push('&socket_id=', socketId);
    }
    var queryString = params.join('');

    var path = '/apps/' + this.options.appId + '/channels/' + channel + '/events';
    var signData = ['POST', path, queryString].join('\n');
    var signature = crypto.createHmac('sha256', this.options.secret).update(signData).digest('hex');

    path = path + '?' + queryString + '&auth_signature=' + signature;

    var client = http.createClient(80, this.domain);
    var request = client.request('POST', path, {
      'host': this.domain,
      'content-type': 'application/json',
      'content-length': new Buffer(requestBody).toString('binary').length
    });

    if(callback) {
      client.addListener('error', function(error) {
        callback(error, request, null);
      });

      request.addListener('response', function(response) {
        callback(null, request, response);
      });
    }

    request.write(requestBody);
    request.end();

    return this;
  }

  return Pusher;
})();<commit_msg>Add channel data<commit_after>module.exports = (function() {
  var crypto = require('crypto');
  var http = require('http');

  var Pusher = function(options) {
    this.options = options;
    return this;
  }

  Pusher.prototype.domain = 'api.pusherapp.com';

  Pusher.prototype.auth = function(socketId, channel, channelData) {
    var returnHash = {}
    var channelDataStr = ''
    if (channelData) {
      channelData = JSON.stringify(channelData);
      channelDataStr = ':' + channelData;
      returnHash['channel_data'] = channelData;
    }
    var stringToSign = socketId + ':' + channel + channelDataStr;
    returnHash['auth'] = this.options.key + ':' + crypto.createHmac('sha256', this.options.secret).update(stringToSign).digest('hex');
    return(returnHash);
  }

  Pusher.prototype.trigger = function(channel, event, message, socketId, callback) {
    var timestamp = parseInt(new Date().getTime() / 1000);
    var requestBody = JSON.stringify(message);
    var hash = crypto.createHash('md5').update(new Buffer(requestBody).toString('binary')).digest('hex');

    var params = [
      'auth_key=', this.options.key,
      '&auth_timestamp=', timestamp,
      '&auth_version=', '1.0',
      '&body_md5=', hash,
      '&name=', event
    ];
    if (socketId) {
      params.push('&socket_id=', socketId);
    }
    var queryString = params.join('');

    var path = '/apps/' + this.options.appId + '/channels/' + channel + '/events';
    var signData = ['POST', path, queryString].join('\n');
    var signature = crypto.createHmac('sha256', this.options.secret).update(signData).digest('hex');

    path = path + '?' + queryString + '&auth_signature=' + signature;

    var client = http.createClient(80, this.domain);
    var request = client.request('POST', path, {
      'host': this.domain,
      'content-type': 'application/json',
      'content-length': new Buffer(requestBody).toString('binary').length
    });

    if(callback) {
      client.addListener('error', function(error) {
        callback(error, request, null);
      });

      request.addListener('response', function(response) {
        callback(null, request, response);
      });
    }

    request.write(requestBody);
    request.end();

    return this;
  }

  return Pusher;
})();<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .

var rendererOptions = {draggable: false};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
var zoom;
var bounds;
var distance = 0.1; // km
var boxpolys = [];
var markers = [];

function initialize() {

  var mapOptions = {
    center: new google.maps.LatLng(39.7386033, -104.935449)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directions-panel'));

//  ***************CRIME POINT MAP LAYER ************************
  //cartodb.createLayer(map, 'http://lmcnish14.cartodb.com/api/v2/viz/ba1f60ea-2fac-11e4-b64f-0e73339ffa50/viz.json')
    //.addTo(map);
//  ************************************************************

  var control = document.getElementById('control');
  control.style.display = 'block';
  map.controls.push(control);

  google.maps.event.trigger(map, 'resize');

  $("#control input[type=submit]").on('click', calcRoute);

}

function calcRoute(event) {
  event.preventDefault();
  var start = document.getElementById('start').value + "Denver, CO";
  var end = document.getElementById('end').value + "Denver, CO";
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.WALKING,
    provideRouteAlternatives: true

  };

  google.maps.event.clearListeners(directionsDisplay, 'routeindex_changed');

  findPath(request)
}

function findPath(request) {
  directionsService.route(request, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var directionsPanel = document.getElementById('directions-panel');
      directionsPanel.style.display = 'block';
      directionsPanel.style.background = '#f4f4f4';

      var path = response.routes[0].overview_path;
      var routeBoxer = new RouteBoxer();
      var boxes = routeBoxer.box(path, distance);
      bounds = response.routes[0][bounds];
      drawBoxes(boxes);
      google.maps.event.addListener(directionsDisplay, 'routeindex_changed', function () {
        var current_route_index = this.getRouteIndex();
        var path2 = response.routes[current_route_index].overview_path;
        var boxes2 = routeBoxer.box(path2, distance);
        drawBoxes(boxes2);
      });
    }
  })
}

function placeRequest(bounds) {
  var place_request = {
    bounds: bounds,
    types: ['fire_station'],
    keyword: 'fire station'
  };

  var place_request2 = {
    bounds: bounds,
    keyword: "health",
    types: ['hospital']
  };

  var place_request3 = {
    bounds: bounds,
    keyword: 'police',
    types: ['police']
  };

  var service = new google.maps.places.PlacesService(map);
  service.search(place_request, callback);
  var service2 = new google.maps.places.PlacesService(map);
  service2.search(place_request2, callback);
  var service3 = new google.maps.places.PlacesService(map);
  service3.search(place_request3, callback);
}

function drawBoxes(boxes) {
  var count = 0;
  var crime_count = 0;
  var promise = $.getJSON("http://lmcnish14.cartodb.com/api/v2/sql?q=SELECT geo_lon, geo_lat, severity FROM public.crime_updated");
  clearBoxes();
  deleteMarkers();

  promise.then(function (data) {
    for (var i = 0; i < boxes.length; i++) {
      var bounds = boxes[i];
      placeRequest(bounds);
      boxpolys[i] = new google.maps.Rectangle({
//       ************* BOX BORDERS ********************************************
        //bounds: boxes[i],
        //fillOpacity: 0,
        //strokeOpacity: 1.0,
        //strokeColor: '#000000',
        //strokeWeight: 1,
//        *********************************************************************
        map: map
      });
      var northeast = boxes[i].getNorthEast();
      var southwest = boxes[i].getSouthWest();
      $.each(data["rows"], function (i, crime_point) {
        var lat = crime_point.geo_lat;
        var lon = crime_point.geo_lon;
        if (lat > southwest["k"] && lat < northeast["k"] && lon > southwest["D"] && lon < northeast["D"]) {
          crime_count += 1;
          sev_count = parseInt(crime_point.severity);
          count += sev_count;

        }
      });
    }
    var avg_crime = parseInt(count / crime_count);
    $('#severity_score').replaceWith('

Number of Crimes: ' + crime_count + '

Avg Score: ' + avg_crime + '

Total Score: ' + count + '

');
  });
}

function clearBoxes() {
  for (var i = 0; i < boxpolys.length; i++) {
    boxpolys[i].setMap(null);
  }
  boxpolys = [];
}

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    var i = 0;

    while (i < results.length) {
      createMarker(results[i]);
      var request = { reference: results[i].reference };
      var service = new google.maps.places.PlacesService(map);
      service.getDetails(request, function (details, status2) {
      });
      i++;
    }
  }
}

function createMarker(place) {
  var str = place.name;
  if (str.indexOf("Green") === -1 && str.indexOf("Medicinals") === -1 && str.indexOf("Herban") === -1 && str.indexOf("Dispensary") === -1 && str.indexOf("Paternity") === -1 && str.indexOf("Mining") === -1 && str.indexOf("Plastic") === -1 && str.indexOf("Dentist") === -1 && str.indexOf("Dermatology") === -1 && str.indexOf("Marijuana") === -1 && str.indexOf("Chief") === -1) {
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location,
      clickable: true
    });
    marker.info = new google.maps.InfoWindow({
      content: '
' + place.name + '
' + '
' + place.vicinity + '
'
    });
    markers.push(marker);
    google.maps.event.addListener(marker, 'click', function () {
      marker.info.open(map, marker);
      setTimeout(function () {
        marker.info.close();
      }, 4000);
    });
  }
}

function deleteMarkers() {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];
}

$('#myTab a:last').click(function (e) {
  e.preventDefault();
  $(this).tab('show');
});

$(document).ready(function () {
  $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var center = map.getCenter();
    google.maps.event.trigger(map, "resize");
    map.setCenter(center);
    google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
      oldZoom = map.getZoom();
      map.setZoom(oldZoom + 8)
    });
    map.fitBounds(bounds);
  });
});

$(document).ready(function (){
  $('#demo').click(function(){
    var clickButton = function (){
      $('#direction-button').click()
    };
    var begin = document.getElementById('start');
    var end = document.getElementById('end');
    $(begin).val("100 e 1st ave");
    $(end).val("1000 broadway");
    window.setTimeout(clickButton, 2000);
    $('#demo').hide();
  });
});

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Lowered window timeout when using demo button<commit_after>//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .

var rendererOptions = {draggable: false};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
var zoom;
var bounds;
var distance = 0.1; // km
var boxpolys = [];
var markers = [];

function initialize() {

  var mapOptions = {
    center: new google.maps.LatLng(39.7386033, -104.935449)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directions-panel'));

//  ***************CRIME POINT MAP LAYER ************************
  //cartodb.createLayer(map, 'http://lmcnish14.cartodb.com/api/v2/viz/ba1f60ea-2fac-11e4-b64f-0e73339ffa50/viz.json')
    //.addTo(map);
//  ************************************************************

  var control = document.getElementById('control');
  control.style.display = 'block';
  map.controls.push(control);

  google.maps.event.trigger(map, 'resize');

  $("#control input[type=submit]").on('click', calcRoute);

}

function calcRoute(event) {
  event.preventDefault();
  var start = document.getElementById('start').value + "Denver, CO";
  var end = document.getElementById('end').value + "Denver, CO";
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.WALKING,
    provideRouteAlternatives: true

  };

  google.maps.event.clearListeners(directionsDisplay, 'routeindex_changed');

  findPath(request)
}

function findPath(request) {
  directionsService.route(request, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var directionsPanel = document.getElementById('directions-panel');
      directionsPanel.style.display = 'block';
      directionsPanel.style.background = '#f4f4f4';

      var path = response.routes[0].overview_path;
      var routeBoxer = new RouteBoxer();
      var boxes = routeBoxer.box(path, distance);
      bounds = response.routes[0][bounds];
      drawBoxes(boxes);
      google.maps.event.addListener(directionsDisplay, 'routeindex_changed', function () {
        var current_route_index = this.getRouteIndex();
        var path2 = response.routes[current_route_index].overview_path;
        var boxes2 = routeBoxer.box(path2, distance);
        drawBoxes(boxes2);
      });
    }
  })
}

function placeRequest(bounds) {
  var place_request = {
    bounds: bounds,
    types: ['fire_station'],
    keyword: 'fire station'
  };

  var place_request2 = {
    bounds: bounds,
    keyword: "health",
    types: ['hospital']
  };

  var place_request3 = {
    bounds: bounds,
    keyword: 'police',
    types: ['police']
  };

  var service = new google.maps.places.PlacesService(map);
  service.search(place_request, callback);
  var service2 = new google.maps.places.PlacesService(map);
  service2.search(place_request2, callback);
  var service3 = new google.maps.places.PlacesService(map);
  service3.search(place_request3, callback);
}

function drawBoxes(boxes) {
  var count = 0;
  var crime_count = 0;
  var promise = $.getJSON("http://lmcnish14.cartodb.com/api/v2/sql?q=SELECT geo_lon, geo_lat, severity FROM public.crime_updated");
  clearBoxes();
  deleteMarkers();

  promise.then(function (data) {
    for (var i = 0; i < boxes.length; i++) {
      var bounds = boxes[i];
      placeRequest(bounds);
      boxpolys[i] = new google.maps.Rectangle({
//       ************* BOX BORDERS ********************************************
        //bounds: boxes[i],
        //fillOpacity: 0,
        //strokeOpacity: 1.0,
        //strokeColor: '#000000',
        //strokeWeight: 1,
//        *********************************************************************
        map: map
      });
      var northeast = boxes[i].getNorthEast();
      var southwest = boxes[i].getSouthWest();
      $.each(data["rows"], function (i, crime_point) {
        var lat = crime_point.geo_lat;
        var lon = crime_point.geo_lon;
        if (lat > southwest["k"] && lat < northeast["k"] && lon > southwest["D"] && lon < northeast["D"]) {
          crime_count += 1;
          sev_count = parseInt(crime_point.severity);
          count += sev_count;

        }
      });
    }
    var avg_crime = parseInt(count / crime_count);
    $('#severity_score').replaceWith('

Number of Crimes: ' + crime_count + '

Avg Score: ' + avg_crime + '

Total Score: ' + count + '

');
  });
}

function clearBoxes() {
  for (var i = 0; i < boxpolys.length; i++) {
    boxpolys[i].setMap(null);
  }
  boxpolys = [];
}

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    var i = 0;

    while (i < results.length) {
      createMarker(results[i]);
      var request = { reference: results[i].reference };
      var service = new google.maps.places.PlacesService(map);
      service.getDetails(request, function (details, status2) {
      });
      i++;
    }
  }
}

function createMarker(place) {
  var str = place.name;
  if (str.indexOf("Green") === -1 && str.indexOf("Medicinals") === -1 && str.indexOf("Herban") === -1 && str.indexOf("Dispensary") === -1 && str.indexOf("Paternity") === -1 && str.indexOf("Mining") === -1 && str.indexOf("Plastic") === -1 && str.indexOf("Dentist") === -1 && str.indexOf("Dermatology") === -1 && str.indexOf("Marijuana") === -1 && str.indexOf("Chief") === -1) {
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location,
      clickable: true
    });
    marker.info = new google.maps.InfoWindow({
      content: '
' + place.name + '
' + '
' + place.vicinity + '
'
    });
    markers.push(marker);
    google.maps.event.addListener(marker, 'click', function () {
      marker.info.open(map, marker);
      setTimeout(function () {
        marker.info.close();
      }, 4000);
    });
  }
}

function deleteMarkers() {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];
}

$('#myTab a:last').click(function (e) {
  e.preventDefault();
  $(this).tab('show');
});

$(document).ready(function () {
  $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var center = map.getCenter();
    google.maps.event.trigger(map, "resize");
    map.setCenter(center);
    google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
      oldZoom = map.getZoom();
      map.setZoom(oldZoom + 8)
    });
    map.fitBounds(bounds);
  });
});

$(document).ready(function (){
  $('#demo').click(function(){
    var clickButton = function (){
      $('#direction-button').click()
    };
    var begin = document.getElementById('start');
    var end = document.getElementById('end');
    $(begin).val("100 e 1st ave");
    $(end).val("1000 broadway");
    window.setTimeout(clickButton, 1000);
    $('#demo').hide();
  });
});

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>/*
 * Author:
 * CreateAt: 2017-10-23
 * LastModify:
 * Goal: 公司常用功能封装
 * 1. eventHelper, 事件辅助方法
 * 2. ajaxHelper, Ajax辅助方法
 * 3. dateHelper, 时间辅助方法
 * 4. ligerHelper, ligerUI辅助方法
 */

var eventHelper = (function () {
    // 对指定的元素绑定回车事件触发另一指定元素的click事件
    // 通常对页面绑定回车触发搜索按钮
    var pageBindEnter = function (dom, bindElement) {
        $(dom).keydown(function () {
            if (event.keyCode == "13") {//keyCode=13是回车键
                $(bindElement).click();
            }
        });
    };

    return {
        pageBindEnter: pageBindEnter
   }
})();

var ajaxHelper = (function () {
    // 根据传入的url和key使用Ajax获取单个值并返回
    var getSingleValue = function (url, key, info) {
        var result = '';
        $.ajax({
            type: "post",
            url: url,
            async: false, //是否异步
            data: info === undefined ? null : info,
            success: function (data) {
                var resultObj = $.parseJSON(data);
                result = resultObj.Rows[0][key];
            }
        });
        return result;
    };

    // 根据传入的url和key使用Ajax获取值并填充到知道id
    var ajaxInsertSingleValue = function (url, key, tag, info, callback) {
        $.ajax({
            type: "post",
            url: url,
            data: info === undefined ? null : info,
            success: function (data) {
                var resultObj = $.parseJSON(data);
                $("#" + tag).text(resultObj.Rows[0][key]);
                if (callback) {
                    callback(resultObj.Rows[0][key]);
                }
            }
        });
    };

    return {
        getSingleValue: getSingleValue,
        ajaxInsertSingleValue: ajaxInsertSingleValue
    };
})();

var dateHelper = (function () {
    // 根据传入的dateTime String(例如: 2017/08/31 11:59:59)返回date(例如: 2017-08-31)
    var getDateObj = function (dateStr) {
        if (null == dateStr || undefined == dateStr) {
            return null;
        }

        // dateStr format, see more: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date
        // Todo: add support like '/Date(1328423451489)/, see one way of implement: line 7296 of ligerui.all.js

        return new Date(dateStr);
    };

    var getDateFromString = function (dateStr) {
        var date = getDateObj(dateStr);
        return date ? null: date.getFullYear() + '-' + (date.getMonth() + 1)
                                    + '-' + date.getDate();
    };

    // 根据传入的dateTime String(例如: 2017/08/31 11:59:59)返回date(例如: 2017-08-31 11:59:59)
    var getDateTime = function (dateStr) {
        var date = getDateObj(dateStr);

        return date ? null: date.getFullYear() + '-'
                                    + (date.getMonth() + 1) + '-'
                                    + date.getDate() + ' '
                                    + date.getHours() + ':'
                                    + date.getMinutes() + ':'
                                    + date.getSeconds();

    };

    return {
        getDateFromString: getDateFromString,
        getDateTime: getDateTime
    };
})();

// 与ligerUI相关的辅助方法
var ligerHelper = (function () {
    // 返回ligerUI的单个条件限制
    var getSingleFilter = function (key, value, op) {
        return {
            op: 'AND',
            rules: [
                { field: key, value: value, op: op }
            ]
        };
    };

    return {
        getSingleFilter: getSingleFilter
    };
})();

// 与财务相关的辅助方法
var financialHelper = (function () {
    var convertCurrency;

    convertCurrency = function (money) {
        var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'), //汉字的数字
            cnIntRadice = new Array('', '拾', '佰', '仟'),        //基本单位
            cnIntUnits = new Array('', '万', '亿', '兆'),         //对应整数部分扩展单位
            cnDecUnits = new Array('角', '分', '毫', '厘'),       //对应小数部分单位
            cnInteger = '整',            //整数金额时后面跟的字符
            cnIntLast = '元',           //整型完以后的单位
            maxNum = 999999999999999.9999,      //最大处理的数字
            integerNum,         //金额整数部分
            decimalNum,         //金额小数部分
            chineseStr = '',    //输出的中文金额字符串
            parts;              //分离金额后用的数组，预定义

        if (money == '') { return ''; }
        money = parseFloat(money);
        if (money >= maxNum) {
            //超出最大处理数字
            return '';
        }
        if (money == 0) {
            chineseStr = cnNums[0] + cnIntLast + cnInteger;
            return chineseStr;
        }
        //转换为字符串
        money = money.toString();
        if (money.indexOf('.') == -1) {
            integerNum = money;
            decimalNum = '';
        } else {
            parts = money.split('.');
            integerNum = parts[0];
            decimalNum = parts[1].substr(0, 4);
        }
        //获取整型部分转换
        if (parseInt(integerNum, 10) > 0) {
            var zeroCount = 0;
            var IntLen = integerNum.length;
            for (var i = 0; i < IntLen; i++) {
                var n = integerNum.substr(i, 1);
                var p = IntLen - i - 1;
                var q = p / 4;
                var m = p % 4;
                if (n == '0') {
                    zeroCount++;
                } else {
                    if (zeroCount > 0) {
                        chineseStr += cnNums[0];
                    }
                    //归零
                    zeroCount = 0;
                    chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
                }
                if (m == 0 && zeroCount < 4) {
                    chineseStr += cnIntUnits[q];
                }
            }
            chineseStr += cnIntLast;
        }
        //小数部分
        if (decimalNum != '') {
            var decLen = decimalNum.length;
            for (var i = 0; i < decLen; i++) {
                var n = decimalNum.substr(i, 1);
                if (n != '0') {
                    chineseStr += cnNums[Number(n)] + cnDecUnits[i];
                }
            }
        }
        if (chineseStr == '') {
            chineseStr += cnNums[0] + cnIntLast + cnInteger;
        } else if (decimalNum == '') {
            chineseStr += cnInteger;
        }
        return chineseStr;
    }

    return {
        convertCurrency: convertCurrency
    }
})();

// 验证相关的方法
var strategies = {
    isNumber: function (value) {
       return /^[0-9\.]+$/.test(value);
    }
};

// assert
var testHelper = {
    assert: function (value, msg) {
        if (!value) {
            throw(msg || (value + " does not equal true"));
        }
    },
    assertEqual: function (val1, val2, msg) {
        if (val1 !== val2) {
            throw(msg || (val1 + " does not equal " + val2));
        }
    }
};

var mathHelper = {
    guid : function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        }).toUpperCase();
    }
};

// 处理涉及IO的操作
var ioHelper = (function() {
    var excelExport;
     // 导出Excel
     excelExport = function(rule, url, spName) {
         var form = $("<form>"); //定义一个form表单
         form.attr("style", "display:none");
         form.attr("id", "form1");
         form.attr("target", "");
         form.attr("method", "post");
         form.attr("action", url);

         var input1 = $("<input>");
         input1.attr("type", "hidden");
         input1.attr("name", "view");
         input1.attr("value", spName);

         var input2 = $("<input>");
         input2.attr("type", "hidden");
         input2.attr("name", "where");
         input2.attr("value", JSON2.stringify(rule));

         $("body").append(form); //将表单放置在web中
         form.append(input1);
         form.append(input2);

         form.submit(); //表单提交
     }

     return {
        excelExport: excelExport
     };
}) ();<commit_msg>add getCurrentDate<commit_after>/*
 * Author:
 * CreateAt: 2017-10-23
 * LastModify:
 * Goal: 公司常用功能封装
 * 1. eventHelper, 事件辅助方法
 * 2. ajaxHelper, Ajax辅助方法
 * 3. dateHelper, 时间辅助方法
 * 4. ligerHelper, ligerUI辅助方法
 */

var eventHelper = (function () {
    // 对指定的元素绑定回车事件触发另一指定元素的click事件
    // 通常对页面绑定回车触发搜索按钮
    var pageBindEnter = function (dom, bindElement) {
        $(dom).keydown(function () {
            if (event.keyCode == "13") {//keyCode=13是回车键
                $(bindElement).click();
            }
        });
    };

    return {
        pageBindEnter: pageBindEnter
   }
})();

var ajaxHelper = (function () {
    // 根据传入的url和key使用Ajax获取单个值并返回
    var getSingleValue = function (url, key, info) {
        var result = '';
        $.ajax({
            type: "post",
            url: url,
            async: false, //是否异步
            data: info === undefined ? null : info,
            success: function (data) {
                var resultObj = $.parseJSON(data);
                result = resultObj.Rows[0][key];
            }
        });
        return result;
    };

    // 根据传入的url和key使用Ajax获取值并填充到知道id
    var ajaxInsertSingleValue = function (url, key, tag, info, callback) {
        $.ajax({
            type: "post",
            url: url,
            data: info === undefined ? null : info,
            success: function (data) {
                var resultObj = $.parseJSON(data);
                $("#" + tag).text(resultObj.Rows[0][key]);
                if (callback) {
                    callback(resultObj.Rows[0][key]);
                }
            }
        });
    };

    return {
        getSingleValue: getSingleValue,
        ajaxInsertSingleValue: ajaxInsertSingleValue
    };
})();

var dateHelper = (function () {
    var getDateObj, getDateFromString, getDateTime, getCurrentDate;
    // 根据传入的dateTime String(例如: 2017/08/31 11:59:59)返回date(例如: 2017-08-31)
    getDateObj = function (dateStr) {
        if (null == dateStr || undefined == dateStr) {
            return null;
        }

        // dateStr format, see more: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date
        // Todo: add support like '/Date(1328423451489)/, see one way of implement: line 7296 of ligerui.all.js

        return new Date(dateStr);
    };

    getDateFromString = function (dateStr) {
        var date = getDateObj(dateStr);
        return date ? null: date.getFullYear() + '-' + (date.getMonth() + 1)
                                    + '-' + date.getDate();
    };

    // 根据传入的dateTime String(例如: 2017/08/31 11:59:59)返回date(例如: 2017-08-31 11:59:59)
    getDateTime = function (dateStr) {
        var date = getDateObj(dateStr);

        return date ? null: date.getFullYear() + '-'
                                    + (date.getMonth() + 1) + '-'
                                    + date.getDate() + ' '
                                    + date.getHours() + ':'
                                    + date.getMinutes() + ':'
                                    + date.getSeconds();

    };

     // 返回当前时间
     getCurrentDate = function () {
        var date1 = new Date();
        return date1.getFullYear() + '-' + date1.getMonth() + '-' + date1.getDay() + ' '
                    + date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds();
     };

    return {
        getDateFromString: getDateFromString,
        getDateTime: getDateTime,
        getCurrentDate: getCurrentDate
    };
})();

// 与ligerUI相关的辅助方法
var ligerHelper = (function () {
    // 返回ligerUI的单个条件限制
    var getSingleFilter = function (key, value, op) {
        return {
            op: 'AND',
            rules: [
                { field: key, value: value, op: op }
            ]
        };
    };

    return {
        getSingleFilter: getSingleFilter
    };
})();

// 与财务相关的辅助方法
var financialHelper = (function () {
    var convertCurrency;

    convertCurrency = function (money) {
        var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'), //汉字的数字
            cnIntRadice = new Array('', '拾', '佰', '仟'),        //基本单位
            cnIntUnits = new Array('', '万', '亿', '兆'),         //对应整数部分扩展单位
            cnDecUnits = new Array('角', '分', '毫', '厘'),       //对应小数部分单位
            cnInteger = '整',            //整数金额时后面跟的字符
            cnIntLast = '元',           //整型完以后的单位
            maxNum = 999999999999999.9999,      //最大处理的数字
            integerNum,         //金额整数部分
            decimalNum,         //金额小数部分
            chineseStr = '',    //输出的中文金额字符串
            parts;              //分离金额后用的数组，预定义

        if (money == '') { return ''; }
        money = parseFloat(money);
        if (money >= maxNum) {
            //超出最大处理数字
            return '';
        }
        if (money == 0) {
            chineseStr = cnNums[0] + cnIntLast + cnInteger;
            return chineseStr;
        }
        //转换为字符串
        money = money.toString();
        if (money.indexOf('.') == -1) {
            integerNum = money;
            decimalNum = '';
        } else {
            parts = money.split('.');
            integerNum = parts[0];
            decimalNum = parts[1].substr(0, 4);
        }
        //获取整型部分转换
        if (parseInt(integerNum, 10) > 0) {
            var zeroCount = 0;
            var IntLen = integerNum.length;
            for (var i = 0; i < IntLen; i++) {
                var n = integerNum.substr(i, 1);
                var p = IntLen - i - 1;
                var q = p / 4;
                var m = p % 4;
                if (n == '0') {
                    zeroCount++;
                } else {
                    if (zeroCount > 0) {
                        chineseStr += cnNums[0];
                    }
                    //归零
                    zeroCount = 0;
                    chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
                }
                if (m == 0 && zeroCount < 4) {
                    chineseStr += cnIntUnits[q];
                }
            }
            chineseStr += cnIntLast;
        }
        //小数部分
        if (decimalNum != '') {
            var decLen = decimalNum.length;
            for (var i = 0; i < decLen; i++) {
                var n = decimalNum.substr(i, 1);
                if (n != '0') {
                    chineseStr += cnNums[Number(n)] + cnDecUnits[i];
                }
            }
        }
        if (chineseStr == '') {
            chineseStr += cnNums[0] + cnIntLast + cnInteger;
        } else if (decimalNum == '') {
            chineseStr += cnInteger;
        }
        return chineseStr;
    }

    return {
        convertCurrency: convertCurrency
    }
})();

// 验证相关的方法
var strategies = {
    isNumber: function (value) {
       return /^[0-9\.]+$/.test(value);
    }
};

// assert
var testHelper = {
    assert: function (value, msg) {
        if (!value) {
            throw(msg || (value + " does not equal true"));
        }
    },
    assertEqual: function (val1, val2, msg) {
        if (val1 !== val2) {
            throw(msg || (val1 + " does not equal " + val2));
        }
    }
};

var mathHelper = {
    guid : function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        }).toUpperCase();
    }
};

// 处理涉及IO的操作
var ioHelper = (function() {
    var excelExport;
     // 导出Excel
     excelExport = function(rule, url, spName) {
         var form = $("<form>"); //定义一个form表单
         form.attr("style", "display:none");
         form.attr("id", "form1");
         form.attr("target", "");
         form.attr("method", "post");
         form.attr("action", url);

         var input1 = $("<input>");
         input1.attr("type", "hidden");
         input1.attr("name", "view");
         input1.attr("value", spName);

         var input2 = $("<input>");
         input2.attr("type", "hidden");
         input2.attr("name", "where");
         input2.attr("value", JSON2.stringify(rule));

         $("body").append(form); //将表单放置在web中
         form.append(input1);
         form.append(input2);

         form.submit(); //表单提交
     }

     return {
        excelExport: excelExport
     };
}) ();<|endoftext|>


<commit_before>export const ACTION_LOGIN_START = 0
export const ACTION_LOGIN_STOP = 1
export const ACTION_LOGIN_SET_USER = 2
export const ACTION_LOGIN_SET_ERROR_MSG = 3<commit_msg>Revert "Revert "remove Constants file (to change filename to lowercase)""<commit_after><|endoftext|>


<commit_before>// Copyright 2005 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview A class that can be used to listen to font size changes.
 */

goog.provide('goog.dom.FontSizeMonitor');
goog.provide('goog.dom.FontSizeMonitor.EventType');

goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.userAgent');

// TODO(user): Move this to goog.events instead.

/**
 * This class can be used to monitor changes in font size.  Instances will
 * dispatch a {@code goog.dom.FontSizeMonitor.EventType.CHANGE} event.
 * Example usage:
 *

 * var fms = new goog.dom.FontSizeMonitor();
 * goog.events.listen(fms, goog.dom.FontSizeMonitor.EventType.CHANGE,
 *     function(e) {
 *       alert('Font size was changed');
 *     });
 *

 * @param {goog.dom.DomHelper=} opt_domHelper DOM helper object that is used to
 *     determine where to insert the DOM nodes used to determine when the font
 *     size changes.
 * @constructor
 * @extends {goog.events.EventTarget}
 */
goog.dom.FontSizeMonitor = function(opt_domHelper) {
  goog.events.EventTarget.call(this);

  var dom = opt_domHelper || goog.dom.getDomHelper();

  /**
   * Offscreen iframe which we use to detect resize events.
   * @type {Element}
   * @private
   */
  this.sizeElement_ = dom.createDom(
      // The size of the iframe is expressed in em, which are font size relative
      // which will cause the iframe to be resized when the font size changes.
      // The actual values are not relevant as long as we can ensure that the
      // iframe has a non zero size and is completely off screen.
      goog.userAgent.IE ? 'div' : 'iframe',
      {'style': 'position:absolute;width:9em;height:9em;top:-99em;z-index:-9'});
  var p = dom.getDocument().body;
  p.insertBefore(this.sizeElement_, p.firstChild);

  /**
   * The object that we listen to resize events on.
   * @type {Element|Window}
   * @private
   */
  var resizeTarget = this.resizeTarget_ =
      goog.userAgent.IE ? this.sizeElement_ :
          goog.dom.getFrameContentWindow(
              /** @type {HTMLIFrameElement} */ (this.sizeElement_));

  // We need to open and close the document to get Firefox 2 to work.  We must
  // not do this for IE in case we are using HTTPS since accessing the document
  // on an about:blank iframe in IE using HTTPS raises a Permission Denied
  // error. Additionally, firefox shows this frame in tab order by default,
  // suppress it by using a tabindex of -1.
  if (goog.userAgent.GECKO) {
    this.sizeElement_.tabIndex = -1;
    var doc = resizeTarget.document;
    doc.open();
    doc.close();
  }

  // Listen to resize event on the window inside the iframe.
  goog.events.listen(resizeTarget, goog.events.EventType.RESIZE,
                     this.handleResize_, false, this);

  /**
   * Last measured width of the iframe element.
   * @type {number}
   * @private
   */
  this.lastWidth_ = this.sizeElement_.offsetWidth;
};
goog.inherits(goog.dom.FontSizeMonitor, goog.events.EventTarget);

/**
 * The event types that the FontSizeMonitor fires.
 * @enum {string}
 */
goog.dom.FontSizeMonitor.EventType = {
  // TODO(user): Change value to 'change' after updating the callers.
  CHANGE: 'fontsizechange'
};

/**
 * Constant for the change event.
 * @type {string}
 * @deprecated Use {@code goog.dom.FontSizeMonitor.EventType.CHANGE} instead.
 */
goog.dom.FontSizeMonitor.CHANGE_EVENT =
    goog.dom.FontSizeMonitor.EventType.CHANGE;

/**
 * Disposes of the font size monitor.
 */
goog.dom.FontSizeMonitor.prototype.disposeInternal = function() {
  goog.dom.FontSizeMonitor.superClass_.disposeInternal.call(this);

  goog.events.unlisten(this.resizeTarget_, goog.events.EventType.RESIZE,
                       this.handleResize_, false, this);
  this.resizeTarget_ = null;

  // Firefox 2 crashes if the iframe is removed during the unload phase.
  if (!goog.userAgent.GECKO || goog.userAgent.isVersion('1.9')) {
    goog.dom.removeNode(this.sizeElement_);
  }
  delete this.sizeElement_;
};

/**
 * Handles the onresize event of the iframe and dispatches a change event in
 * case its size really changed.
 * @param {goog.events.BrowserEvent} e The event object.
 * @private
 */
goog.dom.FontSizeMonitor.prototype.handleResize_ = function(e) {
  // Only dispatch the event if the size really changed.  Some newer browsers do
  // not really change the font-size,  instead they zoom the whole page.  This
  // does trigger window resize events on the iframe but the logical pixel size
  // remains the same (the device pixel size changes but that is irrelevant).
  var currentWidth = this.sizeElement_.offsetWidth;
  if (this.lastWidth_ != currentWidth) {
    this.lastWidth_ = currentWidth;
    this.dispatchEvent(goog.dom.FontSizeMonitor.EventType.CHANGE);
  }
};
<commit_msg><commit_after>// Copyright 2005 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview A class that can be used to listen to font size changes.
 */

goog.provide('goog.dom.FontSizeMonitor');
goog.provide('goog.dom.FontSizeMonitor.EventType');

goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.userAgent');

// TODO(user): Move this to goog.events instead.

/**
 * This class can be used to monitor changes in font size.  Instances will
 * dispatch a {@code goog.dom.FontSizeMonitor.EventType.CHANGE} event.
 * Example usage:
 *

 * var fms = new goog.dom.FontSizeMonitor();
 * goog.events.listen(fms, goog.dom.FontSizeMonitor.EventType.CHANGE,
 *     function(e) {
 *       alert('Font size was changed');
 *     });
 *

 * @param {goog.dom.DomHelper=} opt_domHelper DOM helper object that is used to
 *     determine where to insert the DOM nodes used to determine when the font
 *     size changes.
 * @constructor
 * @extends {goog.events.EventTarget}
 */
goog.dom.FontSizeMonitor = function(opt_domHelper) {
  goog.events.EventTarget.call(this);

  var dom = opt_domHelper || goog.dom.getDomHelper();

  /**
   * Offscreen iframe which we use to detect resize events.
   * @type {Element}
   * @private
   */
  this.sizeElement_ = dom.createDom(
      // The size of the iframe is expressed in em, which are font size relative
      // which will cause the iframe to be resized when the font size changes.
      // The actual values are not relevant as long as we can ensure that the
      // iframe has a non zero size and is completely off screen.
      goog.userAgent.IE ? 'div' : 'iframe',
      {'style': 'position:absolute;width:9em;height:9em;top:-99em'});
  var p = dom.getDocument().body;
  p.insertBefore(this.sizeElement_, p.firstChild);

  /**
   * The object that we listen to resize events on.
   * @type {Element|Window}
   * @private
   */
  var resizeTarget = this.resizeTarget_ =
      goog.userAgent.IE ? this.sizeElement_ :
          goog.dom.getFrameContentWindow(
              /** @type {HTMLIFrameElement} */ (this.sizeElement_));

  // We need to open and close the document to get Firefox 2 to work.  We must
  // not do this for IE in case we are using HTTPS since accessing the document
  // on an about:blank iframe in IE using HTTPS raises a Permission Denied
  // error. Additionally, firefox shows this frame in tab order by default,
  // suppress it by using a tabindex of -1.
  if (goog.userAgent.GECKO) {
    this.sizeElement_.tabIndex = -1;
    var doc = resizeTarget.document;
    doc.open();
    doc.close();
  }

  // Listen to resize event on the window inside the iframe.
  goog.events.listen(resizeTarget, goog.events.EventType.RESIZE,
                     this.handleResize_, false, this);

  /**
   * Last measured width of the iframe element.
   * @type {number}
   * @private
   */
  this.lastWidth_ = this.sizeElement_.offsetWidth;
};
goog.inherits(goog.dom.FontSizeMonitor, goog.events.EventTarget);

/**
 * The event types that the FontSizeMonitor fires.
 * @enum {string}
 */
goog.dom.FontSizeMonitor.EventType = {
  // TODO(user): Change value to 'change' after updating the callers.
  CHANGE: 'fontsizechange'
};

/**
 * Constant for the change event.
 * @type {string}
 * @deprecated Use {@code goog.dom.FontSizeMonitor.EventType.CHANGE} instead.
 */
goog.dom.FontSizeMonitor.CHANGE_EVENT =
    goog.dom.FontSizeMonitor.EventType.CHANGE;

/**
 * Disposes of the font size monitor.
 */
goog.dom.FontSizeMonitor.prototype.disposeInternal = function() {
  goog.dom.FontSizeMonitor.superClass_.disposeInternal.call(this);

  goog.events.unlisten(this.resizeTarget_, goog.events.EventType.RESIZE,
                       this.handleResize_, false, this);
  this.resizeTarget_ = null;

  // Firefox 2 crashes if the iframe is removed during the unload phase.
  if (!goog.userAgent.GECKO || goog.userAgent.isVersion('1.9')) {
    goog.dom.removeNode(this.sizeElement_);
  }
  delete this.sizeElement_;
};

/**
 * Handles the onresize event of the iframe and dispatches a change event in
 * case its size really changed.
 * @param {goog.events.BrowserEvent} e The event object.
 * @private
 */
goog.dom.FontSizeMonitor.prototype.handleResize_ = function(e) {
  // Only dispatch the event if the size really changed.  Some newer browsers do
  // not really change the font-size,  instead they zoom the whole page.  This
  // does trigger window resize events on the iframe but the logical pixel size
  // remains the same (the device pixel size changes but that is irrelevant).
  var currentWidth = this.sizeElement_.offsetWidth;
  if (this.lastWidth_ != currentWidth) {
    this.lastWidth_ = currentWidth;
    this.dispatchEvent(goog.dom.FontSizeMonitor.EventType.CHANGE);
  }
};
<|endoftext|>


<commit_before>import { select, event } from 'd3-selection';
import { scaleIdentity } from 'd3-scale';
import { seriesSvgMulti, seriesCanvasMulti } from '@d3fc/d3fc-series';
import { axisBottom, axisRight, axisLeft, axisTop } from '@d3fc/d3fc-axis';
import { dataJoin } from '@d3fc/d3fc-data-join';
import { rebindAll, exclude, prefix } from '@d3fc/d3fc-rebind';
import store from './store';
import './css';

const functor = (v) =>
    typeof v === 'function' ? v : () => v;

export default (...args) => {
    const { xScale, yScale, xAxis, yAxis } = getArguments(...args);

    let xLabel = functor('');
    let yLabel = functor('');
    let xAxisHeight = functor(null);
    let yAxisWidth = functor(null);
    let yOrient = functor('right');
    let xOrient = functor('bottom');
    let canvasPlotArea = seriesCanvasMulti();
    let svgPlotArea = seriesSvgMulti();
    let xAxisStore = store('tickFormat', 'ticks', 'tickArguments', 'tickSize', 'tickSizeInner', 'tickSizeOuter', 'tickValues', 'tickPadding', 'tickCenterLabel');
    let xDecorate = () => { };
    let yAxisStore = store('tickFormat', 'ticks', 'tickArguments', 'tickSize', 'tickSizeInner', 'tickSizeOuter', 'tickValues', 'tickPadding', 'tickCenterLabel');
    let yDecorate = () => { };
    let decorate = () => { };

    const containerDataJoin = dataJoin('d3fc-group', 'cartesian-chart');
    const xAxisDataJoin = dataJoin('d3fc-svg', 'x-axis')
        .key(d => d);
    const yAxisDataJoin = dataJoin('d3fc-svg', 'y-axis')
        .key(d => d);
    const xLabelDataJoin = dataJoin('div', 'x-label')
        .key(d => d);
    const yLabelDataJoin = dataJoin('div', 'y-label')
        .key(d => d);

    const propagateTransition = maybeTransition => selection =>
        maybeTransition.selection ? selection.transition(maybeTransition) : selection;

    const cartesian = (selection) => {

        const transitionPropagator = propagateTransition(selection);

        selection.each((data, index, group) => {
            const container = containerDataJoin(select(group[index]), [data]);

            container.enter()
                .attr('auto-resize', '')
                .html(
                    '<d3fc-svg class="plot-area"></d3fc-svg>' +
                    '<d3fc-canvas class="plot-area"></d3fc-canvas>'
                );

            xLabelDataJoin(container, [xOrient(data)])
                .attr('class', d => `x-label ${d}-label`)
                .text(xLabel(data));

            yLabelDataJoin(container, [yOrient(data)])
                .attr('class', d => `y-label ${d}-label`)
                .text(yLabel(data));

            xAxisDataJoin(container, [xOrient(data)])
                .attr('class', d => `x-axis ${d}-axis`)
                .style('height', xAxisHeight(data))
                .on('measure', (d, i, nodes) => {
                    const { width, height } = event.detail;
                    if (d === 'top') {
                        select(nodes[i])
                            .select('svg')
                            .attr('viewBox', `0 ${-height} ${width} ${height}`);
                    }
                    xScale.range([0, width]);
                })
                .on('draw', (d, i, nodes) => {
                    const xAxisComponent = d === 'top' ? xAxis.top(xScale) : xAxis.bottom(xScale);
                    xAxisComponent.decorate(xDecorate);
                    transitionPropagator(select(nodes[i]))
                        .select('svg')
                        .call(xAxisStore(xAxisComponent));
                });

            yAxisDataJoin(container, [yOrient(data)])
                .attr('class', d => `y-axis ${d}-axis`)
                .style('width', yAxisWidth(data))
                .on('measure', (d, i, nodes) => {
                    const { width, height } = event.detail;
                    if (d === 'left') {
                        select(nodes[i])
                            .select('svg')
                            .attr('viewBox', `${-width} 0 ${width} ${height}`);
                    }
                    yScale.range([height, 0]);
                })
                .on('draw', (d, i, nodes) => {
                    const yAxisComponent = d === 'left' ? yAxis.left(yScale) : yAxis.right(yScale);
                    yAxisComponent.decorate(yDecorate);
                    transitionPropagator(select(nodes[i]))
                        .select('svg')
                        .call(yAxisStore(yAxisComponent));
                });

            container.select('d3fc-canvas.plot-area')
                .on('draw', (d, i, nodes) => {
                    const canvas = select(nodes[i])
                        .select('canvas')
                        .node();
                    canvasPlotArea.context(canvas.getContext('2d'))
                        .xScale(xScale)
                        .yScale(yScale);
                    canvasPlotArea(d);
                });

            container.select('d3fc-svg.plot-area')
                .on('draw', (d, i, nodes) => {
                    svgPlotArea.xScale(xScale)
                        .yScale(yScale);
                    transitionPropagator(select(nodes[i]))
                        .select('svg')
                        .call(svgPlotArea);
                });

            container.each((d, i, nodes) => nodes[i].requestRedraw());

            decorate(container, data, index);
        });
    };

    const scaleExclusions = exclude(
        /range\w*/,   // the scale range is set via the component layout
        /tickFormat/  // use axis.tickFormat instead (only present on linear scales)
    );
    rebindAll(cartesian, xScale, scaleExclusions, prefix('x'));
    rebindAll(cartesian, yScale, scaleExclusions, prefix('y'));
    rebindAll(cartesian, xAxisStore, prefix('x'));
    rebindAll(cartesian, yAxisStore, prefix('y'));

    cartesian.xOrient = (...args) => {
        if (!args.length) {
            return xOrient;
        }
        xOrient = functor(args[0]);
        return cartesian;
    };
    cartesian.yOrient = (...args) => {
        if (!args.length) {
            return yOrient;
        }
        yOrient = functor(args[0]);
        return cartesian;
    };
    cartesian.xDecorate = (...args) => {
        if (!args.length) {
            return xDecorate;
        }
        xDecorate = args[0];
        return cartesian;
    };
    cartesian.yDecorate = (...args) => {
        if (!args.length) {
            return yDecorate;
        }
        yDecorate = args[0];
        return cartesian;
    };
    cartesian.xLabel = (...args) => {
        if (!args.length) {
            return xLabel;
        }
        xLabel = functor(args[0]);
        return cartesian;
    };
    cartesian.yLabel = (...args) => {
        if (!args.length) {
            return yLabel;
        }
        yLabel = functor(args[0]);
        return cartesian;
    };
    cartesian.xAxisHeight = (...args) => {
        if (!args.length) {
            return xAxisHeight;
        }
        xAxisHeight = functor(args[0]);
        return cartesian;
    };
    cartesian.yAxisWidth = (...args) => {
        if (!args.length) {
            return yAxisWidth;
        }
        yAxisWidth = functor(args[0]);
        return cartesian;
    };
    cartesian.canvasPlotArea = (...args) => {
        if (!args.length) {
            return canvasPlotArea;
        }
        canvasPlotArea = args[0];
        return cartesian;
    };
    cartesian.svgPlotArea = (...args) => {
        if (!args.length) {
            return svgPlotArea;
        }
        svgPlotArea = args[0];
        return cartesian;
    };
    cartesian.decorate = (...args) => {
        if (!args.length) {
            return decorate;
        }
        decorate = args[0];
        return cartesian;
    };

    return cartesian;

};

const getArguments = (...args) => {
    const defaultSettings = {
        xScale: scaleIdentity(),
        yScale: scaleIdentity(),
        xAxis: { bottom: axisBottom, top: axisTop },
        yAxis: { right: axisRight, left: axisLeft }
    };

    if (args.length === 1 && !args[0].domain && !args[0].range) {
        // Settings object
        return Object.assign(defaultSettings, args[0]);
    }

    // xScale/yScale parameters
    return Object.assign(defaultSettings, {
        xScale: args[0] || defaultSettings.xScale,
        yScale: args[1] || defaultSettings.yScale
    });
};
<commit_msg>feat: default null plot area to hide unused<commit_after>import { select, event } from 'd3-selection';
import { scaleIdentity } from 'd3-scale';
import { seriesSvgMulti, seriesCanvasMulti } from '@d3fc/d3fc-series';
import { axisBottom, axisRight, axisLeft, axisTop } from '@d3fc/d3fc-axis';
import { dataJoin } from '@d3fc/d3fc-data-join';
import { rebindAll, exclude, prefix } from '@d3fc/d3fc-rebind';
import store from './store';
import './css';

const functor = (v) =>
    typeof v === 'function' ? v : () => v;

export default (...args) => {
    const { xScale, yScale, xAxis, yAxis } = getArguments(...args);

    let xLabel = functor('');
    let yLabel = functor('');
    let xAxisHeight = functor(null);
    let yAxisWidth = functor(null);
    let yOrient = functor('right');
    let xOrient = functor('bottom');
    let canvasPlotArea = null;
    let svgPlotArea = null;
    let xAxisStore = store('tickFormat', 'ticks', 'tickArguments', 'tickSize', 'tickSizeInner', 'tickSizeOuter', 'tickValues', 'tickPadding', 'tickCenterLabel');
    let xDecorate = () => { };
    let yAxisStore = store('tickFormat', 'ticks', 'tickArguments', 'tickSize', 'tickSizeInner', 'tickSizeOuter', 'tickValues', 'tickPadding', 'tickCenterLabel');
    let yDecorate = () => { };
    let decorate = () => { };

    const containerDataJoin = dataJoin('d3fc-group', 'cartesian-chart');
    const canvasDataJoin = dataJoin('d3fc-canvas', 'plot-area');
    const svgDataJoin = dataJoin('d3fc-svg', 'plot-area');
    const xAxisDataJoin = dataJoin('d3fc-svg', 'x-axis')
        .key(d => d);
    const yAxisDataJoin = dataJoin('d3fc-svg', 'y-axis')
        .key(d => d);
    const xLabelDataJoin = dataJoin('div', 'x-label')
        .key(d => d);
    const yLabelDataJoin = dataJoin('div', 'y-label')
        .key(d => d);

    const propagateTransition = maybeTransition => selection =>
        maybeTransition.selection ? selection.transition(maybeTransition) : selection;

    const cartesian = (selection) => {

        const transitionPropagator = propagateTransition(selection);

        selection.each((data, index, group) => {
            const container = containerDataJoin(select(group[index]), [data]);

            container.enter()
                .attr('auto-resize', '');

            xLabelDataJoin(container, [xOrient(data)])
                .attr('class', d => `x-label ${d}-label`)
                .text(xLabel(data));

            yLabelDataJoin(container, [yOrient(data)])
                .attr('class', d => `y-label ${d}-label`)
                .text(yLabel(data));

            xAxisDataJoin(container, [xOrient(data)])
                .attr('class', d => `x-axis ${d}-axis`)
                .style('height', xAxisHeight(data))
                .on('measure', (d, i, nodes) => {
                    const { width, height } = event.detail;
                    if (d === 'top') {
                        select(nodes[i])
                            .select('svg')
                            .attr('viewBox', `0 ${-height} ${width} ${height}`);
                    }
                    xScale.range([0, width]);
                })
                .on('draw', (d, i, nodes) => {
                    const xAxisComponent = d === 'top' ? xAxis.top(xScale) : xAxis.bottom(xScale);
                    xAxisComponent.decorate(xDecorate);
                    transitionPropagator(select(nodes[i]))
                        .select('svg')
                        .call(xAxisStore(xAxisComponent));
                });

            yAxisDataJoin(container, [yOrient(data)])
                .attr('class', d => `y-axis ${d}-axis`)
                .style('width', yAxisWidth(data))
                .on('measure', (d, i, nodes) => {
                    const { width, height } = event.detail;
                    if (d === 'left') {
                        select(nodes[i])
                            .select('svg')
                            .attr('viewBox', `${-width} 0 ${width} ${height}`);
                    }
                    yScale.range([height, 0]);
                })
                .on('draw', (d, i, nodes) => {
                    const yAxisComponent = d === 'left' ? yAxis.left(yScale) : yAxis.right(yScale);
                    yAxisComponent.decorate(yDecorate);
                    transitionPropagator(select(nodes[i]))
                        .select('svg')
                        .call(yAxisStore(yAxisComponent));
                });

            svgDataJoin(container, svgPlotArea ? [data] : [])
                .on('draw', (d, i, nodes) => {
                    svgPlotArea.xScale(xScale)
                        .yScale(yScale);
                    transitionPropagator(select(nodes[i]))
                        .select('svg')
                        .call(svgPlotArea);
                });

            canvasDataJoin(container, canvasPlotArea ? [data] : [])
                .on('draw', (d, i, nodes) => {
                    const canvas = select(nodes[i])
                        .select('canvas')
                        .node();
                    canvasPlotArea.context(canvas.getContext('2d'))
                        .xScale(xScale)
                        .yScale(yScale);
                    canvasPlotArea(d);
                });

            container.each((d, i, nodes) => nodes[i].requestRedraw());

            decorate(container, data, index);
        });
    };

    const scaleExclusions = exclude(
        /range\w*/,   // the scale range is set via the component layout
        /tickFormat/  // use axis.tickFormat instead (only present on linear scales)
    );
    rebindAll(cartesian, xScale, scaleExclusions, prefix('x'));
    rebindAll(cartesian, yScale, scaleExclusions, prefix('y'));
    rebindAll(cartesian, xAxisStore, prefix('x'));
    rebindAll(cartesian, yAxisStore, prefix('y'));

    cartesian.xOrient = (...args) => {
        if (!args.length) {
            return xOrient;
        }
        xOrient = functor(args[0]);
        return cartesian;
    };
    cartesian.yOrient = (...args) => {
        if (!args.length) {
            return yOrient;
        }
        yOrient = functor(args[0]);
        return cartesian;
    };
    cartesian.xDecorate = (...args) => {
        if (!args.length) {
            return xDecorate;
        }
        xDecorate = args[0];
        return cartesian;
    };
    cartesian.yDecorate = (...args) => {
        if (!args.length) {
            return yDecorate;
        }
        yDecorate = args[0];
        return cartesian;
    };
    cartesian.xLabel = (...args) => {
        if (!args.length) {
            return xLabel;
        }
        xLabel = functor(args[0]);
        return cartesian;
    };
    cartesian.yLabel = (...args) => {
        if (!args.length) {
            return yLabel;
        }
        yLabel = functor(args[0]);
        return cartesian;
    };
    cartesian.xAxisHeight = (...args) => {
        if (!args.length) {
            return xAxisHeight;
        }
        xAxisHeight = functor(args[0]);
        return cartesian;
    };
    cartesian.yAxisWidth = (...args) => {
        if (!args.length) {
            return yAxisWidth;
        }
        yAxisWidth = functor(args[0]);
        return cartesian;
    };
    cartesian.canvasPlotArea = (...args) => {
        if (!args.length) {
            return canvasPlotArea;
        }
        canvasPlotArea = args[0];
        return cartesian;
    };
    cartesian.svgPlotArea = (...args) => {
        if (!args.length) {
            return svgPlotArea;
        }
        svgPlotArea = args[0];
        return cartesian;
    };
    cartesian.decorate = (...args) => {
        if (!args.length) {
            return decorate;
        }
        decorate = args[0];
        return cartesian;
    };

    return cartesian;

};

const getArguments = (...args) => {
    const defaultSettings = {
        xScale: scaleIdentity(),
        yScale: scaleIdentity(),
        xAxis: { bottom: axisBottom, top: axisTop },
        yAxis: { right: axisRight, left: axisLeft }
    };

    if (args.length === 1 && !args[0].domain && !args[0].range) {
        // Settings object
        return Object.assign(defaultSettings, args[0]);
    }

    // xScale/yScale parameters
    return Object.assign(defaultSettings, {
        xScale: args[0] || defaultSettings.xScale,
        yScale: args[1] || defaultSettings.yScale
    });
};
<|endoftext|>