<commit_before>// node modules
import readline from 'readline';
// npm modules
import moment from 'moment';
import Table from 'cli-table2';
import chalk from 'chalk';
// our modules
import env from './assignConfig';
import {api, config} from '../../utils';

// TODO: Default is tables with headers
// TODO: Silent only shows tables.
// TODO: Decouple helptext from everything else.
// TODO: Structure infotext.
// TODO: Add daily revenue option.
// TODO: Add notifications option.

// Create a new table for projects that the user is queued up for
const projectDetailsTable = new Table({
  head: [
    {hAlign: 'center', content: 'pos'},
    {hAlign: 'center', content: 'id'},
    {hAlign: 'left', content: 'project name'},
    {hAlign: 'center', content: 'lang'}],
  colWidths: [5, 7, 40, 7],
});

// Shows assigned projects in a table
const assignedDetailsTable = new Table({
  head: [
    {hAlign: 'center', content: 'key'},
    {hAlign: 'left', content: 'project name'},
    {hAlign: 'center', content: 'expires'},
    {hAlign: 'center', content: 'price'}],
  colWidths: [5, 40, 15, 8],
});

const createProjectDetailsTable = () => {
  let output = '';
  if (!env.positions.length) {
    console.log(env.positions);
    output += chalk.yellow('Waiting for queue information...\n');
  } else if (env.assigned.length === 2) {
    output += chalk.yellow(`    You have ${chalk.white(env.assigned.length)} (max) submissions assigned.\n`);
  } else {
    projectDetailsTable.length = 0;
    env.positions
      .sort((p1, p2) => p1.position - p2.position)
      .forEach((project) => {
        projectDetailsTable.push([
          {hAlign: 'center', content: project.position},
          {hAlign: 'center', content: project.project_id},
          {hAlign: 'left', content: config.certs[project.project_id].name},
          {hAlign: 'center', content: project.language},
        ]);
      });
    if (env.flags.helptext && !env.flags.silent) {
      output += 'You are in the following queues:\n';
    }
    output += `${projectDetailsTable.toString()}\n\n`;
  }
  return output;
};

const createAssignedDetailsTable = () => {
  let output = '';
  if (!env.assigned.length) {
    if (env.flags.helptext && !env.flags.silent) {
      output += chalk.yellow('No submissions are currently assigned.\n');
    }
  } else {
    assignedDetailsTable.length = 0;
    env.assigned
      .forEach((submission, idx) => {
        const assignedAt = moment.utc(submission.assigned_at);
        const completeTime = assignedAt.add(12, 'hours');
        assignedDetailsTable.push([
          {hAlign: 'center', content: idx + 1},
          {hAlign: 'left', content: submission.project.name},
          {hAlign: 'center', content: completeTime.fromNow()},
          {hAlign: 'center', content: submission.price},
        ]);
      });
    output += `Currently assigned:\n${assignedDetailsTable.toString()}`;
  }
  output += '\n';
  return output;
};

const createWarning = () => {
  let output = '';
  if (env.error) {
    output += chalk.red('The API is responding with the following error message:\n');
    output += chalk.red(env.error.message);
    env.error = '';
  }
  const tokenExpiryWarning = moment(config.tokenAge).diff(moment(), 'days') < 5;
  if (tokenExpiryWarning) {
    output += chalk.red(`Token expires ${moment(config.tokenAge).fromNow()}\n\n`);
  }
  return output;
};

const createSessionInfo = () => {
  let output = '';
  output += chalk.green(`Uptime: ${chalk.white(env.startTime.fromNow(true))}\nTotal assigned: ${
    chalk.white(env.assignedTotal)} since ${env.startTime.format('dddd, MMMM Do YYYY, HH:mm')}\n`);
  output += '\n';
  if (env.updateInfo) {
    if (env.flags.feedbacks) {
      output += chalk.blue('Checked for new feedbacks a few seconds ago...\n');
    }
    output += chalk.blue('Updated the queue a few seconds ago...\n');
  } else {
    const remainingSeconds = (env.updateInfoInterval - env.tick) < 0 ?
                             env.updateInfoInterval - (env.tick % env.updateInfoInterval) :
                             env.updateInfoInterval - env.tick;
    const infoIsCheckedAt = moment().add(remainingSeconds, 'seconds');
    const humanReadableMessage = moment().to(infoIsCheckedAt);
    if (env.flags.feedbacks) {
      output += chalk.blue(`Checking for new feedbacks ${humanReadableMessage}\n`);
    }
    output += chalk.blue(`Updating queue information ${humanReadableMessage}\n`);
  }
  output += '\n';
  return output;
};

const createHelptext = () => {
  const ON = chalk.green('ON');
  const OFF = chalk.red('OFF');
  const output = `
KEYBOARD SHORTCUTS:

${chalk.green(`  Press ${chalk.white('0')} to open the review dashboard.
  Press ${chalk.white('1')} or ${chalk.white('2')} to open your assigned submissions.

  Press ${chalk.white('h')} to toggle this helptext. ${env.flags.helptext ? ON : OFF}
  Press ${chalk.white('i')} to toggle extra infotext. ${env.flags.infotext ? ON : OFF}
  Press ${chalk.white('s')} to toggle all extra information off. ${env.flags.silent ? ON : OFF}
  Press ${chalk.white('f')} to receive notifications of new feedbacks. ${env.flags.feedbacks ? ON : OFF}
  Press ${chalk.white('v')} to receive debugging output. ${env.flags.verbose ? ON : OFF}

  Press ${chalk.white('r')} to refresh the output.

  Press ${chalk.white('CTRL-C')} to exit the queue cleanly by deleting the submission_request.
  Press ${chalk.white('ESC')} to suspend the script without deleting the submission_request.`)}
`;
  return output;
};

const createVerboseOutput = async () => {
  const submissionRequest = await api({task: 'get'});
  let output = '';
  output += 'Debug INFO:\n';
  output += `${chalk.blue(`List of request IDs (${env.requestIds.length}):`)} ${env.requestIds}\n`;
  output += `${
    chalk.blue('Submission Request returned from the server:')} ${
      JSON.stringify(submissionRequest.body[0], null, 2)}\n`;
  output += `${
    chalk.blue('Stored Submission Request object:')} ${JSON.stringify(env.submission_request, null, 2)}\n`;
  return output;
};

async function setPrompt() {
  let output = '';
  // Creating the output
  output += createWarning();
  output += createProjectDetailsTable();
  output += createAssignedDetailsTable();
  if (!env.flags.silent) {
    if (env.flags.infotext) {
      output += createSessionInfo();
    }
    if (env.flags.helptext) {
      output += createHelptext();
    }
  }
  if (env.flags.verbose) {
    output += await createVerboseOutput();
  }
  // Clearing the screen.
  readline.cursorTo(process.stdout, 0, 0);
  readline.clearScreenDown(process.stdout);
  console.log(output);
}

export default setPrompt;
<commit_msg>Spacing<commit_after>// node modules
import readline from 'readline';
// npm modules
import moment from 'moment';
import Table from 'cli-table2';
import chalk from 'chalk';
// our modules
import env from './assignConfig';
import {api, config} from '../../utils';

// TODO: Default is tables with headers
// TODO: Silent only shows tables.
// TODO: Decouple helptext from everything else.
// TODO: Structure infotext.
// TODO: Add daily revenue option.
// TODO: Add notifications option.

// Create a new table for projects that the user is queued up for
const projectDetailsTable = new Table({
  head: [
    {hAlign: 'center', content: 'pos'},
    {hAlign: 'center', content: 'id'},
    {hAlign: 'left', content: 'project name'},
    {hAlign: 'center', content: 'lang'}],
  colWidths: [5, 7, 40, 7],
});

// Shows assigned projects in a table
const assignedDetailsTable = new Table({
  head: [
    {hAlign: 'center', content: 'key'},
    {hAlign: 'left', content: 'project name'},
    {hAlign: 'center', content: 'expires'},
    {hAlign: 'center', content: 'price'}],
  colWidths: [5, 40, 15, 8],
});

const createProjectDetailsTable = () => {
  let output = '';
  if (!env.positions.length) {
    console.log(env.positions);
    output += chalk.yellow('Waiting for queue information...\n\n');
  } else if (env.assigned.length === 2) {
    output += chalk.yellow(`You have ${chalk.white(env.assigned.length)} (max) submissions assigned.\n\n`);
  } else {
    projectDetailsTable.length = 0;
    env.positions
      .sort((p1, p2) => p1.position - p2.position)
      .forEach((project) => {
        projectDetailsTable.push([
          {hAlign: 'center', content: project.position},
          {hAlign: 'center', content: project.project_id},
          {hAlign: 'left', content: config.certs[project.project_id].name},
          {hAlign: 'center', content: project.language},
        ]);
      });
    if (env.flags.helptext && !env.flags.silent) {
      output += 'You are in the following queues:\n';
    }
    output += `${projectDetailsTable.toString()}\n\n`;
  }
  return output;
};

const createAssignedDetailsTable = () => {
  let output = '';
  if (!env.assigned.length) {
    if (env.flags.helptext && !env.flags.silent) {
      output += chalk.yellow('No submissions are currently assigned.\n');
    }
  } else {
    assignedDetailsTable.length = 0;
    env.assigned
      .forEach((submission, idx) => {
        const assignedAt = moment.utc(submission.assigned_at);
        const completeTime = assignedAt.add(12, 'hours');
        assignedDetailsTable.push([
          {hAlign: 'center', content: idx + 1},
          {hAlign: 'left', content: submission.project.name},
          {hAlign: 'center', content: completeTime.fromNow()},
          {hAlign: 'center', content: submission.price},
        ]);
      });
    output += `Currently assigned:\n${assignedDetailsTable.toString()}`;
  }
  output += '\n';
  return output;
};

const createWarning = () => {
  let output = '';
  if (env.error) {
    output += chalk.red('The API is responding with the following error message:\n');
    output += chalk.red(env.error.message);
    env.error = '';
  }
  const tokenExpiryWarning = moment(config.tokenAge).diff(moment(), 'days') < 5;
  if (tokenExpiryWarning) {
    output += chalk.red(`Token expires ${moment(config.tokenAge).fromNow()}\n\n`);
  }
  return output;
};

const createSessionInfo = () => {
  let output = '';
  output += chalk.green(`Uptime: ${chalk.white(env.startTime.fromNow(true))}\nTotal assigned: ${
    chalk.white(env.assignedTotal)} since ${env.startTime.format('dddd, MMMM Do YYYY, HH:mm')}\n`);
  output += '\n';
  if (env.updateInfo) {
    if (env.flags.feedbacks) {
      output += chalk.blue('Checked for new feedbacks a few seconds ago...\n');
    }
    output += chalk.blue('Updated the queue a few seconds ago...\n');
  } else {
    const remainingSeconds = (env.updateInfoInterval - env.tick) < 0 ?
                             env.updateInfoInterval - (env.tick % env.updateInfoInterval) :
                             env.updateInfoInterval - env.tick;
    const infoIsCheckedAt = moment().add(remainingSeconds, 'seconds');
    const humanReadableMessage = moment().to(infoIsCheckedAt);
    if (env.flags.feedbacks) {
      output += chalk.blue(`Checking for new feedbacks ${humanReadableMessage}\n`);
    }
    output += chalk.blue(`Updating queue information ${humanReadableMessage}\n`);
  }
  output += '\n';
  return output;
};

const createHelptext = () => {
  const ON = chalk.green('ON');
  const OFF = chalk.red('OFF');
  const output = `
KEYBOARD SHORTCUTS:

${chalk.green(`  Press ${chalk.white('0')} to open the review dashboard.
  Press ${chalk.white('1')} or ${chalk.white('2')} to open your assigned submissions.

  Press ${chalk.white('h')} to toggle this helptext. ${env.flags.helptext ? ON : OFF}
  Press ${chalk.white('i')} to toggle extra infotext. ${env.flags.infotext ? ON : OFF}
  Press ${chalk.white('s')} to toggle all extra information off. ${env.flags.silent ? ON : OFF}
  Press ${chalk.white('f')} to receive notifications of new feedbacks. ${env.flags.feedbacks ? ON : OFF}
  Press ${chalk.white('v')} to receive debugging output. ${env.flags.verbose ? ON : OFF}

  Press ${chalk.white('r')} to refresh the output.

  Press ${chalk.white('CTRL-C')} to exit the queue cleanly by deleting the submission_request.
  Press ${chalk.white('ESC')} to suspend the script without deleting the submission_request.`)}
`;
  return output;
};

const createVerboseOutput = async () => {
  const submissionRequest = await api({task: 'get'});
  let output = '';
  output += 'Debug INFO:\n';
  output += `${chalk.blue(`List of request IDs (${env.requestIds.length}):`)} ${env.requestIds}\n`;
  output += `${
    chalk.blue('Submission Request returned from the server:')} ${
      JSON.stringify(submissionRequest.body[0], null, 2)}\n`;
  output += `${
    chalk.blue('Stored Submission Request object:')} ${JSON.stringify(env.submission_request, null, 2)}\n`;
  return output;
};

async function setPrompt() {
  let output = '';
  // Creating the output
  output += createWarning();
  output += createProjectDetailsTable();
  output += createAssignedDetailsTable();
  if (!env.flags.silent) {
    if (env.flags.infotext) {
      output += createSessionInfo();
    }
    if (env.flags.helptext) {
      output += createHelptext();
    }
  }
  if (env.flags.verbose) {
    output += await createVerboseOutput();
  }
  // Clearing the screen.
  readline.cursorTo(process.stdout, 0, 0);
  readline.clearScreenDown(process.stdout);
  console.log(output);
}

export default setPrompt;
<|endoftext|>


<commit_before>var JSC          = require("jscheck");
var assert       = require("chai").assert;
var _            = require("lodash");
var getTestUtils = require("../TestUtils.js");

module.exports = function(config) {
  var Immutable = config.implementation;
  var TestUtils = getTestUtils(Immutable);
  var check     = TestUtils.check;

  describe("#asObject", function() {
    it("works on arrays of various lengths", function() {
      check(100, [TestUtils.ComplexObjectSpecifier()], function(obj) {
        var keys   = _.keys(obj);
        var values = _.values(obj);
        var array  = Immutable(_.map(obj, function(value, key) {
          return [key, value];
        }));

        var result = array.asObject(function(value, index) {
          // Check that the index argument we receive works as expected.
          assert.deepEqual(value, array[index], "Expected array[" + index + "] to be " + value);

          return [keys[index], values[index]]
        });

        assert.deepEqual(result, obj);
      });
    });

    it("works without an iterator on arrays that are already organized properly", function() {
      check(100, [TestUtils.ComplexObjectSpecifier()], function(obj) {
        var keys  = _.keys(obj);
        var array = Immutable(_.map(obj, function(value, key) {
          return [key, value];
        }));

        var result = array.asObject();

        assert.deepEqual(result, obj);
      });
    });

    // Sanity check to make sure our QuickCheck logic isn't off the rails.
    it("passes a basic sanity check on canned input", function() {
      var expected = Immutable({all: "your base", are: {belong: "to us"}});
      var actual   = Immutable([{key: "all", value: "your base"}, {key: "are", value: {belong: "to us"}}]).asObject(function(elem) {
        return [elem.key, elem.value];
      });

      assert.deepEqual(actual, expected);
    });
  });
};
<commit_msg>Clean up unnecessary call to _.keys<commit_after>var JSC          = require("jscheck");
var assert       = require("chai").assert;
var _            = require("lodash");
var getTestUtils = require("../TestUtils.js");

module.exports = function(config) {
  var Immutable = config.implementation;
  var TestUtils = getTestUtils(Immutable);
  var check     = TestUtils.check;

  describe("#asObject", function() {
    it("works on arrays of various lengths", function() {
      check(100, [TestUtils.ComplexObjectSpecifier()], function(obj) {
        var keys   = _.keys(obj);
        var values = _.values(obj);
        var array  = Immutable(_.map(obj, function(value, key) {
          return [key, value];
        }));

        var result = array.asObject(function(value, index) {
          // Check that the index argument we receive works as expected.
          assert.deepEqual(value, array[index], "Expected array[" + index + "] to be " + value);

          return [keys[index], values[index]]
        });

        assert.deepEqual(result, obj);
      });
    });

    it("works without an iterator on arrays that are already organized properly", function() {
      check(100, [TestUtils.ComplexObjectSpecifier()], function(obj) {
        var array = Immutable(_.map(obj, function(value, key) {
          return [key, value];
        }));

        var result = array.asObject();

        assert.deepEqual(result, obj);
      });
    });

    // Sanity check to make sure our QuickCheck logic isn't off the rails.
    it("passes a basic sanity check on canned input", function() {
      var expected = Immutable({all: "your base", are: {belong: "to us"}});
      var actual   = Immutable([{key: "all", value: "your base"}, {key: "are", value: {belong: "to us"}}]).asObject(function(elem) {
        return [elem.key, elem.value];
      });

      assert.deepEqual(actual, expected);
    });
  });
};
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('./lib/event_emitter');
var stat = require('./lib/stat');
var inherits = require('util').inherits;

var errors = require('./errors');
var States = require('./reqres_states');

function TChannelOutResponse(id, options) {
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.spanEvent = self.defineEvent('span');
    self.finishEvent = self.defineEvent('finish');

    self.channel = options.channel;
    self.inreq = options.inreq;
    self.logger = options.logger;
    self.random = options.random;
    self.timers = options.timers;

    self.start = 0;
    self.end = 0;
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0;
    self.span = options.span || null;
    self.streamed = false;
    self._argstream = null;
    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.codeString = null;
    self.message = null;
}

inherits(TChannelOutResponse, EventEmitter);

TChannelOutResponse.prototype.type = 'tchannel.outgoing-response';

TChannelOutResponse.prototype._sendCallResponse = function _sendCallResponse(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponse'
    });
};

TChannelOutResponse.prototype._sendCallResponseCont = function _sendCallResponseCont(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponseCont'
    });
};

TChannelOutResponse.prototype._sendError = function _sendError(codeString, message) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendError'
    });
};

TChannelOutResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'arg parts',
                state: 'Done'
            }));
            break;
        case States.Error:
            // TODO: log warn
            break;
        default:
            self.channel.logger.error('TChannelOutResponse is in a wrong state', {
                state: self.state
            });
            break;
    }
};

TChannelOutResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.start = self.timers.now();
            self._sendCallResponse(args, isLast);
            if (self.span) {
                self.span.annotate('ss');
            }
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response',
                state: 'Streaming'
            }));
            break;
        case States.Done:
        case States.Error:
            var arg2 = args[1] || '';
            var arg3 = args[2] || '';

            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response',
                state: self.state,
                method: 'sendCallResponseFrame',
                bufArg2: arg2.slice(0, 50),
                arg2: String(arg2).slice(0, 50),
                bufArg3: arg3.slice(0, 50),
                arg3: String(arg3).slice(0, 50)
            }));
    }
};

TChannelOutResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response continuation',
                state: 'Initial'
            }));
            break;
        case States.Streaming:
            self._sendCallResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response continuation',
                state: self.state,
                method: 'sendCallResponseContFrame'
            }));
    }
};

TChannelOutResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        self.errorEvent.emit(self, errors.ResponseAlreadyDone({
            attempted: 'send error frame: ' + codeString + ': ' + message,
            currentState: self.state,
            method: 'sendError',
            codeString: codeString,
            errMessage: message
        }));
    } else {
        if (self.span) {
            self.span.annotate('ss');
        }
        self.state = States.Error;

        self.codeString = codeString;
        self.message = message;
        self.channel.inboundCallsSystemErrorsStat.increment(1, {
            'calling-service': self.inreq.headers.cn,
            'service': self.inreq.serviceName,
            'endpoint': String(self.inreq.arg1),
            'type': self.codeString
        });
        self._sendError(codeString, message);
        self.emitFinish();
    }
};

TChannelOutResponse.prototype.emitFinish = function emitFinish() {
    var self = this;
    var now = self.timers.now();

    if (self.end) {
        self.logger.warn('out response double emitFinish', {
            end: self.end,
            now: now,
            serviceName: self.inreq.serviceName,
            cn: self.inreq.headers.cn,
            endpoint: String(self.inreq.arg1),
            codeString: self.codeString,
            errorMessage: self.message,
            remoteAddr: self.inreq.connection.socketRemoteAddr,
            state: self.state,

            isOk: self.ok
        });
        return;
    }

    self.end = now;

    var latency = self.end - self.inreq.start;

    self.channel.emitFastStat(self.channel.buildStat(
        'tchannel.inbound.calls.latency',
        'timing',
        latency,
        new stat.InboundCallsLatencyTags(
            self.inreq.headers.cn,
            self.inreq.serviceName,
            self.inreq.endpoint
        )
    ));

    if (self.span) {
        self.spanEvent.emit(self, self.span);
    }

    self.finishEvent.emit(self);
};

TChannelOutResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        self.errorEvent.emit(self, errors.ResponseAlreadyStarted({
            state: self.state,
            method: 'setOk',
            ok: ok
        }));
        return;
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
};

TChannelOutResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    self.send(res1, res2);
};

TChannelOutResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    if (self.state === States.Error) {
        self.logger.error('cannot send application error, already sent error frame', {
            res1: res1,
            res2: res2
        });
    } else {
        self.setOk(false);
        self.send(res1, res2);
    }
};

TChannelOutResponse.prototype.send = function send(res1, res2) {
    var self = this;

    /* send calls after finish() should be swallowed */
    if (self.end) {
        return;
    }

    self.arg2 = res1;
    self.arg3 = res2;

    if (self.ok) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.success',
            'counter',
            1,
            new stat.InboundCallsSuccessTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint
            )
        ));
    } else {
        // TODO: add outResponse.setErrorType()
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.app-errors',
            'counter',
            1,
            new stat.InboundCallsAppErrorsTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint,
                'unknown'
            )
        ));
    }

    self.sendCallResponseFrame([self.arg1, res1, res2], true);
    self.emitFinish();

    return self;
};

module.exports = TChannelOutResponse;
<commit_msg>out_response: Add a loud warning for send() after end<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('./lib/event_emitter');
var stat = require('./lib/stat');
var inherits = require('util').inherits;

var errors = require('./errors');
var States = require('./reqres_states');

function TChannelOutResponse(id, options) {
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.spanEvent = self.defineEvent('span');
    self.finishEvent = self.defineEvent('finish');

    self.channel = options.channel;
    self.inreq = options.inreq;
    self.logger = options.logger;
    self.random = options.random;
    self.timers = options.timers;

    self.start = 0;
    self.end = 0;
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0;
    self.span = options.span || null;
    self.streamed = false;
    self._argstream = null;
    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.codeString = null;
    self.message = null;
}

inherits(TChannelOutResponse, EventEmitter);

TChannelOutResponse.prototype.type = 'tchannel.outgoing-response';

TChannelOutResponse.prototype._sendCallResponse = function _sendCallResponse(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponse'
    });
};

TChannelOutResponse.prototype._sendCallResponseCont = function _sendCallResponseCont(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallResponseCont'
    });
};

TChannelOutResponse.prototype._sendError = function _sendError(codeString, message) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendError'
    });
};

TChannelOutResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'arg parts',
                state: 'Done'
            }));
            break;
        case States.Error:
            // TODO: log warn
            break;
        default:
            self.channel.logger.error('TChannelOutResponse is in a wrong state', {
                state: self.state
            });
            break;
    }
};

TChannelOutResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.start = self.timers.now();
            self._sendCallResponse(args, isLast);
            if (self.span) {
                self.span.annotate('ss');
            }
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response',
                state: 'Streaming'
            }));
            break;
        case States.Done:
        case States.Error:
            var arg2 = args[1] || '';
            var arg3 = args[2] || '';

            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response',
                state: self.state,
                method: 'sendCallResponseFrame',
                bufArg2: arg2.slice(0, 50),
                arg2: String(arg2).slice(0, 50),
                bufArg3: arg3.slice(0, 50),
                arg3: String(arg3).slice(0, 50)
            }));
    }
};

TChannelOutResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.errorEvent.emit(self, errors.ResponseFrameState({
                attempted: 'call response continuation',
                state: 'Initial'
            }));
            break;
        case States.Streaming:
            self._sendCallResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            self.errorEvent.emit(self, errors.ResponseAlreadyDone({
                attempted: 'call response continuation',
                state: self.state,
                method: 'sendCallResponseContFrame'
            }));
    }
};

TChannelOutResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        self.errorEvent.emit(self, errors.ResponseAlreadyDone({
            attempted: 'send error frame: ' + codeString + ': ' + message,
            currentState: self.state,
            method: 'sendError',
            codeString: codeString,
            errMessage: message
        }));
    } else {
        if (self.span) {
            self.span.annotate('ss');
        }
        self.state = States.Error;

        self.codeString = codeString;
        self.message = message;
        self.channel.inboundCallsSystemErrorsStat.increment(1, {
            'calling-service': self.inreq.headers.cn,
            'service': self.inreq.serviceName,
            'endpoint': String(self.inreq.arg1),
            'type': self.codeString
        });
        self._sendError(codeString, message);
        self.emitFinish();
    }
};

TChannelOutResponse.prototype.emitFinish = function emitFinish() {
    var self = this;
    var now = self.timers.now();

    if (self.end) {
        self.logger.warn('out response double emitFinish', {
            end: self.end,
            now: now,
            serviceName: self.inreq.serviceName,
            cn: self.inreq.headers.cn,
            endpoint: String(self.inreq.arg1),
            codeString: self.codeString,
            errorMessage: self.message,
            remoteAddr: self.inreq.connection.socketRemoteAddr,
            state: self.state,

            isOk: self.ok
        });
        return;
    }

    self.end = now;

    var latency = self.end - self.inreq.start;

    self.channel.emitFastStat(self.channel.buildStat(
        'tchannel.inbound.calls.latency',
        'timing',
        latency,
        new stat.InboundCallsLatencyTags(
            self.inreq.headers.cn,
            self.inreq.serviceName,
            self.inreq.endpoint
        )
    ));

    if (self.span) {
        self.spanEvent.emit(self, self.span);
    }

    self.finishEvent.emit(self);
};

TChannelOutResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        self.errorEvent.emit(self, errors.ResponseAlreadyStarted({
            state: self.state,
            method: 'setOk',
            ok: ok
        }));
        return;
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
};

TChannelOutResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    self.send(res1, res2);
};

TChannelOutResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    if (self.state === States.Error) {
        self.logger.error('cannot send application error, already sent error frame', {
            res1: res1,
            res2: res2
        });
    } else {
        self.setOk(false);
        self.send(res1, res2);
    }
};

TChannelOutResponse.prototype.send = function send(res1, res2) {
    var self = this;

    /* send calls after finish() should be swallowed */
    if (self.end) {
        self.logger.warn('OutResponse called send() after end', {
            serviceName: self.inreq.serviceName,
            cn: self.inreq.headers.cn,
            endpoint: self.inreq.endpoint,
            remoteAddr: self.inreq.remoteAddr,

            end: self.end,
            codeString: self.codeString,
            errorMessage: self.message,
            isOk: self.ok,
            hasResponse: !!self.arg3,
            state: self.state
        });
        return;
    }

    self.arg2 = res1;
    self.arg3 = res2;

    if (self.ok) {
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.success',
            'counter',
            1,
            new stat.InboundCallsSuccessTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint
            )
        ));
    } else {
        // TODO: add outResponse.setErrorType()
        self.channel.emitFastStat(self.channel.buildStat(
            'tchannel.inbound.calls.app-errors',
            'counter',
            1,
            new stat.InboundCallsAppErrorsTags(
                self.inreq.headers.cn,
                self.inreq.serviceName,
                self.inreq.endpoint,
                'unknown'
            )
        ));
    }

    self.sendCallResponseFrame([self.arg1, res1, res2], true);
    self.emitFinish();

    return self;
};

module.exports = TChannelOutResponse;
<|endoftext|>


<commit_before>import _ from 'lodash';

export function mergeResults(previous, current) {
  if (previous === undefined || previous.results === undefined) {
    return current;
  }
  const expectedOffset = (previous.limit + previous.offset);
  if (current.offset === expectedOffset) {
    return { ...current, results: [...previous.results, ...current.results] };
  }
  return previous;
}

export function objectLoadComplete(state, id, data = {}) {
  /* eslint-disable no-param-reassign */
  data.isLoading = false;
  data.isError = false;
  data.shouldLoad = false;
  /* eslint-enable no-param-reassign */
  return { ...state, [id]: data };
}

export function updateResults(state, { query, result }) {
  const key = query.toKey();
  const res = { ...result, results: result.results.map(r => r.id) };
  return objectLoadComplete(state, key, mergeResults(state[key], res));
}

export function invalidateResults() {
  return {};
}

export function objectLoadStart(state, id) {
  const object = { isLoading: true, shouldLoad: false };
  return { ...state, [id]: _.assign({}, state[id], object) };
}

export function resultLoadStart(state, query) {
  const key = query ? query.toKey() : undefined;
  return objectLoadStart(state, key);
}

export function objectLoadError(state, id, error) {
  const object = {
    isLoading: false,
    isError: true,
    shouldLoad: false,
    error,
  };
  return { ...state, [id]: _.assign({}, state[id], object) };
}

export function resultLoadError(state, query, error) {
  const key = query ? query.toKey() : undefined;
  return objectLoadError(state, key, error);
}

export function objectDelete(state, id) {
  _.unset(state, id);
  return state;
}

export function resultObjects(state, result, onComplete = objectLoadComplete) {
  if (result.results !== undefined) {
    return result.results
      .reduce((finalState, object) => onComplete(finalState, object.id, object), state);
  }
  return state;
}
<commit_msg>return current result if offset is not defined<commit_after>import _ from 'lodash';

export function mergeResults(previous, current) {
  if (previous === undefined || previous.results === undefined) {
    return current;
  }
  const expectedOffset = (previous.limit + previous.offset);
  if (current.offset === expectedOffset) {
    return { ...current, results: [...previous.results, ...current.results] };
  }
  if (Number.isNaN(expectedOffset)) return current;
  return previous;
}

export function objectLoadComplete(state, id, data = {}) {
  /* eslint-disable no-param-reassign */
  data.isLoading = false;
  data.isError = false;
  data.shouldLoad = false;
  /* eslint-enable no-param-reassign */
  return { ...state, [id]: data };
}

export function updateResults(state, { query, result }) {
  const key = query.toKey();
  const res = { ...result, results: result.results.map(r => r.id) };
  return objectLoadComplete(state, key, mergeResults(state[key], res));
}

export function invalidateResults() {
  return {};
}

export function objectLoadStart(state, id) {
  const object = { isLoading: true, shouldLoad: false };
  return { ...state, [id]: _.assign({}, state[id], object) };
}

export function resultLoadStart(state, query) {
  const key = query ? query.toKey() : undefined;
  return objectLoadStart(state, key);
}

export function objectLoadError(state, id, error) {
  const object = {
    isLoading: false,
    isError: true,
    shouldLoad: false,
    error,
  };
  return { ...state, [id]: _.assign({}, state[id], object) };
}

export function resultLoadError(state, query, error) {
  const key = query ? query.toKey() : undefined;
  return objectLoadError(state, key, error);
}

export function objectDelete(state, id) {
  _.unset(state, id);
  return state;
}

export function resultObjects(state, result, onComplete = objectLoadComplete) {
  if (result.results !== undefined) {
    return result.results
      .reduce((finalState, object) => onComplete(finalState, object.id, object), state);
  }
  return state;
}
<|endoftext|>


<commit_before><commit_msg>mock facebookService.getFriends<commit_after><|endoftext|>


<commit_before>// package-test.js: check to make sure that all dependcies are sufficiently up
// to date. If dependencies are too outdated, exit with an error, failing `npm
// run update:packages` and thus eventually the entire build.

const parsedPackage = require('./package.json');
const packageJson = require('package-json');
const SAFE_TIME = 1000 * 1 * 60 * 60 * 24 * 7; //7days
// webpack has a major update
// copy-webpack-plugin major update
// holding off on husky changes as the cli still has some weird necessary changes to run commitlint
const EXCEPTIONS = [
  'multicoin-address-validator',
  'postcss-import',
  'postcss-url',
  'webpack',
  'copy-webpack-plugin',
  'sass',
  'sass-loader',
  'husky',
  '@aave/protocol-js',
  'sass',
  'web3',
  'web3-core-helpers',
  'web3-core-method',
  'web3-core-requestmanager',
  'web3-utils',
  'remark-cli',
  'node-fetch',
  'vuetify',
  'vue-i18n',
  'stylelint',
  'stylelint-config-standard',
  'vue',
  'vue-router',
  'vuex',
  'eslint',
  'eslint-plugin-vue',
  'imagemin-mozjpeg', // issue with importing it to vue config will look into it more if we need it
  // versions for vue3
  '@vue/eslint-config-prettier', // creates more warnings
  '@vue/test-utils',
  '@vue/babel-preset-app',
  '@vue/cli-plugin-babel',
  '@vue/cli-plugin-eslint',
  '@vue/cli-plugin-pwa',
  '@vue/cli-plugin-unit-jest',
  '@vue/cli-service',
  'vue-i18n',
  'vue',
  '@vue/cli-plugin-e2e-nightwatch',
  // breaking
  '@shapeshiftoss/hdwallet-core',
  '@shapeshiftoss/hdwallet-keepkey-webusb',
  'package-json',
  'codecov',
  'node-polyfill-webpack-plugin',
  '@lokalise/node-api',
  '@unstoppabledomains/resolution',
  '@walletconnect/client',
  '@walletconnect/qrcode-modal',
  'chromedriver',
  '@ethereumjs/common',
  '@ethereumjs/tx',
  'graphql',
  'vue-lazyload',
  '@ensdomains/ensjs',
  'vue-template-compiler',
  '@aave/contract-helpers',
  '@aave/math-utils',
  'node-sass',
  '@ledgerhq/hw-transport-web-ble',
  '@ledgerhq/hw-transport-webusb',
  'uuid',
  'web3-eth-contract',
  '@myetherwallet/mewconnect-web-client',
  'is-ipfs',
  'protobufjs'
];
const CUSTOM_DIST = {
  ['babel-core']: 'bridge'
};
const ALL_PACKAGES = Object.assign(
  parsedPackage.dependencies,
  parsedPackage.devDependencies
);
const names = Object.keys(ALL_PACKAGES);
let updatesFound = false;
const looper = () => {
  if (!names.length) {
    if (updatesFound) {
      console.error(
        '\nREFUSING TO CONTINUE because above packages are TOO FAR OUT OF DATE!'
      );
      console.error(
        'In order to build MyEtherWallet, you must edit package.json.'
      );
      console.error(
        'Update the versions for the packages above to their current versions.'
      );
      console.error('Then run `npm update`.');
      console.error();
      process.exit(1);
    } else {
      process.exit(0);
    }
  }
  const _name = names.shift();
  if (EXCEPTIONS.includes(_name)) return looper();
  if (ALL_PACKAGES[_name].includes('^') || ALL_PACKAGES[_name].includes('~')) {
    console.error(
      'Invalid character ~ or ^ found in package.json version string, only fixed versions are allowed.'
    );
    process.exit(1);
  }
  packageJson(_name, {
    fullMetadata: true,
    allVersions: true
  })
    .then(info => {
      const latestVersion = info['dist-tags'][CUSTOM_DIST[_name] || 'latest'];
      const latestVersionTime = info['time'][latestVersion];
      if (ALL_PACKAGES[_name] !== latestVersion) {
        const isBehind =
          new Date(latestVersionTime).getTime() <
          new Date().getTime() - SAFE_TIME;
        const isMewComponentBeta =
          _name === '@myetherwallet/mew-components' &&
          latestVersion.includes('-beta');
        if (isBehind) {
          if (!isMewComponentBeta) {
            console.error(
              'ERROR: Update ' +
                _name +
                ' from ' +
                ALL_PACKAGES[_name] +
                ' to ' +
                latestVersion +
                '. Released:',
              latestVersionTime
            );
            updatesFound = true;
          }
        }
      }
    })
    .then(looper);
};
looper();
<commit_msg>chore: 👷 exclude packages<commit_after>// package-test.js: check to make sure that all dependcies are sufficiently up
// to date. If dependencies are too outdated, exit with an error, failing `npm
// run update:packages` and thus eventually the entire build.

const parsedPackage = require('./package.json');
const packageJson = require('package-json');
const SAFE_TIME = 1000 * 1 * 60 * 60 * 24 * 7; //7days
// webpack has a major update
// copy-webpack-plugin major update
// holding off on husky changes as the cli still has some weird necessary changes to run commitlint
const EXCEPTIONS = [
  'multicoin-address-validator',
  'postcss-import',
  'postcss-url',
  'webpack',
  'copy-webpack-plugin',
  'sass',
  'sass-loader',
  'husky',
  '@aave/protocol-js',
  'sass',
  'web3',
  'web3-core-helpers',
  'web3-core-method',
  'web3-core-requestmanager',
  'web3-utils',
  'remark-cli',
  'node-fetch',
  'vuetify',
  'vue-i18n',
  'stylelint',
  'stylelint-config-standard',
  'vue',
  'vue-router',
  'vuex',
  'eslint',
  'eslint-plugin-vue',
  'imagemin-mozjpeg', // issue with importing it to vue config will look into it more if we need it
  // versions for vue3
  '@vue/eslint-config-prettier', // creates more warnings
  '@vue/test-utils',
  '@vue/babel-preset-app',
  '@vue/cli-plugin-babel',
  '@vue/cli-plugin-eslint',
  '@vue/cli-plugin-pwa',
  '@vue/cli-plugin-unit-jest',
  '@vue/cli-service',
  'vue-i18n',
  'vue',
  '@vue/cli-plugin-e2e-nightwatch',
  // breaking
  '@shapeshiftoss/hdwallet-core',
  '@shapeshiftoss/hdwallet-keepkey-webusb',
  'package-json',
  'codecov',
  'node-polyfill-webpack-plugin',
  '@lokalise/node-api',
  '@unstoppabledomains/resolution',
  '@walletconnect/client',
  '@walletconnect/qrcode-modal',
  'chromedriver',
  '@ethereumjs/common',
  '@ethereumjs/tx',
  'graphql',
  'vue-lazyload',
  '@ensdomains/ensjs',
  'vue-template-compiler',
  '@aave/contract-helpers',
  '@aave/math-utils',
  'node-sass',
  '@ledgerhq/hw-transport-web-ble',
  '@ledgerhq/hw-transport-webusb',
  'uuid',
  'web3-eth-contract',
  '@myetherwallet/mewconnect-web-client',
  'is-ipfs',
  'protobufjs',
  '@myetherwallet/mew-components'
];
const CUSTOM_DIST = {
  ['babel-core']: 'bridge'
};
const ALL_PACKAGES = Object.assign(
  parsedPackage.dependencies,
  parsedPackage.devDependencies
);
const names = Object.keys(ALL_PACKAGES);
let updatesFound = false;
const looper = () => {
  if (!names.length) {
    if (updatesFound) {
      console.error(
        '\nREFUSING TO CONTINUE because above packages are TOO FAR OUT OF DATE!'
      );
      console.error(
        'In order to build MyEtherWallet, you must edit package.json.'
      );
      console.error(
        'Update the versions for the packages above to their current versions.'
      );
      console.error('Then run `npm update`.');
      console.error();
      process.exit(1);
    } else {
      process.exit(0);
    }
  }
  const _name = names.shift();
  if (EXCEPTIONS.includes(_name)) return looper();
  if (ALL_PACKAGES[_name].includes('^') || ALL_PACKAGES[_name].includes('~')) {
    console.error(
      'Invalid character ~ or ^ found in package.json version string, only fixed versions are allowed.'
    );
    process.exit(1);
  }
  packageJson(_name, {
    fullMetadata: true,
    allVersions: true
  })
    .then(info => {
      const latestVersion = info['dist-tags'][CUSTOM_DIST[_name] || 'latest'];
      const latestVersionTime = info['time'][latestVersion];
      if (ALL_PACKAGES[_name] !== latestVersion) {
        const isBehind =
          new Date(latestVersionTime).getTime() <
          new Date().getTime() - SAFE_TIME;
        const isMewComponentBeta =
          _name === '@myetherwallet/mew-components' &&
          latestVersion.includes('-beta');
        if (isBehind) {
          if (!isMewComponentBeta) {
            console.error(
              'ERROR: Update ' +
                _name +
                ' from ' +
                ALL_PACKAGES[_name] +
                ' to ' +
                latestVersion +
                '. Released:',
              latestVersionTime
            );
            updatesFound = true;
          }
        }
      }
    })
    .then(looper);
};
looper();
<|endoftext|>


<commit_before>import { createElement as h, render } from '../../src/index';
import { setupScratch, teardown } from '../_util/helpers';

/** @jsx h */

// hacky normalization of attribute order across browsers.
function sortAttributes(html) {
	return html.replace(/<([a-z0-9-]+)((?:\s[a-z0-9:_.-]+=".*?")+)((?:\s*\/)?>)/gi, (s, pre, attrs, after) => {
		let list = attrs.match(/\s[a-z0-9:_.-]+=".*?"/gi).sort( (a, b) => a>b ? 1 : -1 );
		if (~after.indexOf('/')) after = '></'+pre+'>';
		return '<' + pre + list.join('') + after;
	});
}

describe('svg', () => {
	let scratch;

	beforeEach(() => {
		scratch = setupScratch();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('should render SVG to string', () => {
		render((
			<svg viewBox="0 0 360 360">
				<path stroke="white" fill="black" d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z" />
			</svg>
		), scratch);

		let html = sortAttributes(String(scratch.innerHTML).replace(' xmlns="http://www.w3.org/2000/svg"', ''));
		expect(html).to.equal(sortAttributes(`
			<svg viewBox="0 0 360 360">
				<path d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z" fill="black" stroke="white"></path>
			</svg>
		`.replace(/[\n\t]+/g,'')));
	});

	it('should render SVG to DOM', () => {
		const Demo = () => (
			<svg viewBox="0 0 360 360">
				<path d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z" fill="black" stroke="white" />
			</svg>
		);
		render(<Demo />, scratch);

		let html = sortAttributes(String(scratch.innerHTML).replace(' xmlns="http://www.w3.org/2000/svg"', ''));
		expect(html).to.equal(sortAttributes('<svg viewBox="0 0 360 360"><path stroke="white" fill="black" d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z"></path></svg>'));
	});

	it('should render with the correct namespace URI', () => {
		render(<svg />, scratch);

		let namespace = scratch.querySelector('svg').namespaceURI;

		expect(namespace).to.equal('http://www.w3.org/2000/svg');
	});

	it('should use attributes for className', () => {
		const Demo = ({ c }) => (
			<svg viewBox="0 0 360 360" {...(c ? { class: 'foo_'+c } : {})}>
				<path class={c && ('bar_'+c)} stroke="white" fill="black" d="M347.1 357.9L183.3 256.5 13 357.9V1.7h334.1v356.2zM58.5 47.2v231.4l124.8-74.1 118.3 72.8V47.2H58.5z" />
			</svg>
		);
		render(<Demo c="1" />, scratch);
		let root = scratch.firstChild;
		sinon.spy(root, 'removeAttribute');
		render(<Demo />, scratch);
		expect(root.removeAttribute)
			.to.have.been.calledOnce
			.and.calledWith('class');

		root.removeAttribute.restore();

		render(
, scratch);
		render(<Demo />, scratch);
		root = scratch.firstChild;
		sinon.spy(root, 'setAttribute');
		render(<Demo c="2" />, scratch);
		expect(root.setAttribute).to.have.been.calledOnce.and.calledWith('class', 'foo_2');

		root.setAttribute.restore();
	});

	it('should still support class attribute', () => {
		render((
			<svg viewBox="0 0 1 1" class="foo bar" />
		), scratch);

		expect(scratch.innerHTML).to.contain(` class="foo bar"`);
	});

	it('should still support className attribute', () => {
		render((
			<svg viewBox="0 0 1 1" className="foo bar" />
		), scratch);

		expect(scratch.innerHTML).to.contain(` class="foo bar"`);
	});

	it('should switch back to HTML for <foreignObject>', () => {
		render((
			<svg>
				<g>
					<foreignObject>
						test
					</foreignObject>
				</g>
			</svg>
		), scratch);

		expect(scratch.getElementsByTagName('a'))
			.to.have.property('0')
			.that.is.a('HTMLAnchorElement');
	});
});
<commit_msg>Add test for transitioning into SVG<commit_after>import { createElement as h, render } from '../../src/index';
import { setupScratch, teardown } from '../_util/helpers';

/** @jsx h */

// hacky normalization of attribute order across browsers.
function sortAttributes(html) {
	return html.replace(/<([a-z0-9-]+)((?:\s[a-z0-9:_.-]+=".*?")+)((?:\s*\/)?>)/gi, (s, pre, attrs, after) => {
		let list = attrs.match(/\s[a-z0-9:_.-]+=".*?"/gi).sort( (a, b) => a>b ? 1 : -1 );
		if (~after.indexOf('/')) after = '></'+pre+'>';
		return '<' + pre + list.join('') + after;
	});
}

describe('svg', () => {
	let scratch;

	beforeEach(() => {
		scratch = setupScratch();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('should render SVG to string', () => {
		render((
			<svg viewBox="0 0 360 360">
				<path stroke="white" fill="black" d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z" />
			</svg>
		), scratch);

		let html = sortAttributes(String(scratch.innerHTML).replace(' xmlns="http://www.w3.org/2000/svg"', ''));
		expect(html).to.equal(sortAttributes(`
			<svg viewBox="0 0 360 360">
				<path d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z" fill="black" stroke="white"></path>
			</svg>
		`.replace(/[\n\t]+/g,'')));
	});

	it('should render SVG to DOM', () => {
		const Demo = () => (
			<svg viewBox="0 0 360 360">
				<path d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z" fill="black" stroke="white" />
			</svg>
		);
		render(<Demo />, scratch);

		let html = sortAttributes(String(scratch.innerHTML).replace(' xmlns="http://www.w3.org/2000/svg"', ''));
		expect(html).to.equal(sortAttributes('<svg viewBox="0 0 360 360"><path stroke="white" fill="black" d="M 347.1 357.9 L 183.3 256.5 L 13 357.9 V 1.7 h 334.1 v 356.2 Z M 58.5 47.2 v 231.4 l 124.8 -74.1 l 118.3 72.8 V 47.2 H 58.5 Z"></path></svg>'));
	});

	it('should render with the correct namespace URI', () => {
		render(<svg />, scratch);

		let namespace = scratch.querySelector('svg').namespaceURI;

		expect(namespace).to.equal('http://www.w3.org/2000/svg');
	});

	it('should use attributes for className', () => {
		const Demo = ({ c }) => (
			<svg viewBox="0 0 360 360" {...(c ? { class: 'foo_'+c } : {})}>
				<path class={c && ('bar_'+c)} stroke="white" fill="black" d="M347.1 357.9L183.3 256.5 13 357.9V1.7h334.1v356.2zM58.5 47.2v231.4l124.8-74.1 118.3 72.8V47.2H58.5z" />
			</svg>
		);
		render(<Demo c="1" />, scratch);
		let root = scratch.firstChild;
		sinon.spy(root, 'removeAttribute');
		render(<Demo />, scratch);
		expect(root.removeAttribute)
			.to.have.been.calledOnce
			.and.calledWith('class');

		root.removeAttribute.restore();

		render(
, scratch);
		render(<Demo />, scratch);
		root = scratch.firstChild;
		sinon.spy(root, 'setAttribute');
		render(<Demo c="2" />, scratch);
		expect(root.setAttribute).to.have.been.calledOnce.and.calledWith('class', 'foo_2');

		root.setAttribute.restore();
	});

	it('should still support class attribute', () => {
		render((
			<svg viewBox="0 0 1 1" class="foo bar" />
		), scratch);

		expect(scratch.innerHTML).to.contain(` class="foo bar"`);
	});

	it('should still support className attribute', () => {
		render((
			<svg viewBox="0 0 1 1" className="foo bar" />
		), scratch);

		expect(scratch.innerHTML).to.contain(` class="foo bar"`);
	});

	it('should switch back to HTML for <foreignObject>', () => {
		render((
			<svg>
				<g>
					<foreignObject>
						test
					</foreignObject>
				</g>
			</svg>
		), scratch);

		expect(scratch.getElementsByTagName('a'))
			.to.have.property('0')
			.that.is.a('HTMLAnchorElement');
	});

	it('should transition from DOM to SVG and back', () => {
		render((

				<svg id="svg1923" width="700" xmlns="http://www.w3.org/2000/svg" height="700">
					<circle cy="333" cx="333" r="333" />
					<circle cy="333" cx="333" r="333" fill="#fede58" />
				</svg>

		), scratch);

		expect(scratch.firstChild).to.be.an('HTMLDivElement');
		expect(scratch.firstChild.firstChild).to.be.an('SVGSVGElement');
	});
});
<|endoftext|>


<commit_before><commit_msg>fix flow and eslint<commit_after><|endoftext|>


<commit_before>const assert = require('assert');

const { EventEmitter } = require('events');
const errors = require('@feathersjs/errors');
const Service = require('../lib/client');

describe('client', () => {
  let connection, testData, service;

  beforeEach(() => {
    connection = new EventEmitter();
    testData = { data: 'testing ' };
    service = new Service({
      events: [ 'created' ],
      name: 'todos',
      method: 'emit',
      timeout: 50,
      connection
    });
  });

  it('sets `events` property on service', () => {
    assert.ok(service.events);
  });

  it('throws an error when the emitter does not have the method', () => {
    const service = new Service({
      name: 'todos',
      method: 'emit',
      timeout: 50,
      connection: {}
    });

    try {
      service.eventNames();
      assert.ok(false, 'Should never get here');
    } catch (e) {
      assert.equal(e.message, 'Can not call \'eventNames\' on the client service connection');
    }

    try {
      service.on();
      assert.ok(false, 'Should never get here');
    } catch (e) {
      assert.equal(e.message, 'Can not call \'on\' on the client service connection');
    }
  });

  it('allows chaining event listeners', () => {
    assert.equal(service, service.on('thing', () => {}));
    assert.equal(service, service.once('other thing', () => {}));
  });

  it('initializes and emits namespaced events', done => {
    connection.once('todos test', data => {
      assert.deepEqual(data, testData);
      done();
    });
    service.emit('test', testData);
  });

  it('has other emitter methods', () => {
    assert.ok(service.eventNames());
  });

  it('can receive pathed events', done => {
    service.once('thing', data => {
      assert.deepEqual(data, testData);
      done();
    });

    connection.emit('todos thing', testData);
  });

  it('sends all service methods with acknowledgement', () => {
    const idCb = (path, id, params, callback) =>
      callback(null, { id });
    const idDataCb = (path, id, data, params, callback) =>
      callback(null, data);

    connection.once('create', (path, data, params, callback) => {
      data.created = true;
      callback(null, data);
    });

    return service.create(testData)
      .then(result => assert.ok(result.created))
      .then(() => {
        connection.once('get', idCb);

        return service.get(1)
          .then(res => assert.deepEqual(res, { id: 1 }));
      })
      .then(() => {
        connection.once('remove', idCb);

        return service.remove(12)
          .then(res => assert.deepEqual(res, { id: 12 }));
      })
      .then(() => {
        connection.once('update', idDataCb);

        return service.update(12, testData)
          .then(res => assert.deepEqual(res, testData));
      })
      .then(() => {
        connection.once('patch', idDataCb);

        return service.patch(12, testData)
          .then(res => assert.deepEqual(res, testData));
      })
      .then(() => {
        connection.once('find', (path, params, callback) =>
          callback(null, { params })
        );

        return service.find({ query: { test: true } }).then(res =>
          assert.deepEqual(res, {
            params: { test: true }
          })
        );
      });
  });

  it('times out on undefined methods', () => {
    return service.remove(10).then(() => {
      throw new Error('Should never get here');
    }).catch(error =>
      assert.equal(error.message, 'Timeout of 50ms exceeded calling remove on todos')
    );
  });

  it('throws a Timeout error when send times out waiting for a response', () => {
    return service.remove(10).then(() => {
      throw new Error('Should never get here');
    }).catch(error =>
      assert.equal(error.name, 'Timeout')
    );
  });

  it('converts to feathers-errors (#19)', () => {
    connection.once('create', (path, data, params, callback) =>
      callback(new errors.NotAuthenticated('Test', { hi: 'me' }).toJSON())
    );

    return service.create(testData).catch(error => {
      assert.ok(error instanceof errors.NotAuthenticated);
      assert.equal(error.name, 'NotAuthenticated');
      assert.equal(error.message, 'Test');
      assert.equal(error.code, 401);
      assert.deepEqual(error.data, { hi: 'me' });
    });
  });

  it('converts other errors (#19)', () => {
    connection.once('create', (path, data, params, callback) =>
      callback('Something went wrong') // eslint-disable-line
    );

    return service.create(testData).catch(error => {
      assert.ok(error instanceof Error);
      assert.equal(error.message, 'Something went wrong');
    });
  });

  it('has all EventEmitter methods', done => {
    const testData = { hello: 'world' };
    const callback = data => {
      assert.deepEqual(data, testData);
      assert.equal(service.listenerCount('test'), 1);
      service.removeListener('test', callback);
      assert.equal(service.listenerCount('test'), 0);
      done();
    };

    service.addListener('test', callback);

    connection.emit('todos test', testData);
  });

  it('properly handles on/off methods', done => {
    const testData = { hello: 'world' };

    const callback1 = data => {
      assert.deepEqual(data, testData);
      assert.equal(service.listenerCount('test'), 3);
      service.off('test', callback1);
      assert.equal(service.listenerCount('test'), 2);
      service.off('test');
      assert.equal(service.listenerCount('test'), 0);
      done();
    };
    const callback2 = () => {
      // noop
    };

    service.on('test', callback1);
    service.on('test', callback2);
    service.on('test', callback2);

    connection.emit('todos test', testData);
  });

  it('forwards namespaced call to .off', done => {
    // Use it's own connection and service so off method gets detected
    const connection = new EventEmitter();

    connection.off = name => {
      assert.equal(name, 'todos test');
      done();
    };

    const service = new Service({
      name: 'todos',
      method: 'emit',
      timeout: 50,
      connection
    });

    service.off('test');
  });
});
<commit_msg>Fix listener tests<commit_after>const assert = require('assert');

const { EventEmitter } = require('events');
const errors = require('@feathersjs/errors');
const Service = require('../lib/client');

describe('client', () => {
  let connection, testData, service;

  beforeEach(() => {
    connection = new EventEmitter();
    testData = { data: 'testing ' };
    service = new Service({
      events: [ 'created' ],
      name: 'todos',
      method: 'emit',
      timeout: 50,
      connection
    });
  });

  it('sets `events` property on service', () => {
    assert.ok(service.events);
  });

  it('throws an error when the emitter does not have the method', () => {
    const service = new Service({
      name: 'todos',
      method: 'emit',
      timeout: 50,
      connection: {}
    });

    try {
      service.eventNames();
      assert.ok(false, 'Should never get here');
    } catch (e) {
      assert.equal(e.message, 'Can not call \'eventNames\' on the client service connection');
    }

    try {
      service.on();
      assert.ok(false, 'Should never get here');
    } catch (e) {
      assert.equal(e.message, 'Can not call \'on\' on the client service connection');
    }
  });

  it('allows chaining event listeners', () => {
    assert.equal(service, service.on('thing', () => {}));
    assert.equal(service, service.once('other thing', () => {}));
  });

  it('initializes and emits namespaced events', done => {
    connection.once('todos test', data => {
      assert.deepEqual(data, testData);
      done();
    });
    service.emit('test', testData);
  });

  it('has other emitter methods', () => {
    assert.ok(service.eventNames());
  });

  it('can receive pathed events', done => {
    service.once('thing', data => {
      assert.deepEqual(data, testData);
      done();
    });

    connection.emit('todos thing', testData);
  });

  it('sends all service methods with acknowledgement', () => {
    const idCb = (path, id, params, callback) =>
      callback(null, { id });
    const idDataCb = (path, id, data, params, callback) =>
      callback(null, data);

    connection.once('create', (path, data, params, callback) => {
      data.created = true;
      callback(null, data);
    });

    return service.create(testData)
      .then(result => assert.ok(result.created))
      .then(() => {
        connection.once('get', idCb);

        return service.get(1)
          .then(res => assert.deepEqual(res, { id: 1 }));
      })
      .then(() => {
        connection.once('remove', idCb);

        return service.remove(12)
          .then(res => assert.deepEqual(res, { id: 12 }));
      })
      .then(() => {
        connection.once('update', idDataCb);

        return service.update(12, testData)
          .then(res => assert.deepEqual(res, testData));
      })
      .then(() => {
        connection.once('patch', idDataCb);

        return service.patch(12, testData)
          .then(res => assert.deepEqual(res, testData));
      })
      .then(() => {
        connection.once('find', (path, params, callback) =>
          callback(null, { params })
        );

        return service.find({ query: { test: true } }).then(res =>
          assert.deepEqual(res, {
            params: { test: true }
          })
        );
      });
  });

  it('times out on undefined methods', () => {
    return service.remove(10).then(() => {
      throw new Error('Should never get here');
    }).catch(error =>
      assert.equal(error.message, 'Timeout of 50ms exceeded calling remove on todos')
    );
  });

  it('throws a Timeout error when send times out waiting for a response', () => {
    return service.remove(10).then(() => {
      throw new Error('Should never get here');
    }).catch(error =>
      assert.equal(error.name, 'Timeout')
    );
  });

  it('converts to feathers-errors (#19)', () => {
    connection.once('create', (path, data, params, callback) =>
      callback(new errors.NotAuthenticated('Test', { hi: 'me' }).toJSON())
    );

    return service.create(testData).catch(error => {
      assert.ok(error instanceof errors.NotAuthenticated);
      assert.equal(error.name, 'NotAuthenticated');
      assert.equal(error.message, 'Test');
      assert.equal(error.code, 401);
      assert.deepEqual(error.data, { hi: 'me' });
    });
  });

  it('converts other errors (#19)', () => {
    connection.once('create', (path, data, params, callback) =>
      callback('Something went wrong') // eslint-disable-line
    );

    return service.create(testData).catch(error => {
      assert.ok(error instanceof Error);
      assert.equal(error.message, 'Something went wrong');
    });
  });

  it('has all EventEmitter methods', done => {
    const testData = { hello: 'world' };
    const callback = data => {
      assert.deepEqual(data, testData);
      assert.equal(service.listenerCount('test'), 1);
      service.removeListener('test', callback);
      assert.equal(service.listenerCount('test'), 0);
      done();
    };

    service.addListener('test', callback);

    connection.emit('todos test', testData);
  });

  it('properly handles on/off methods', done => {
    const testData = { hello: 'world' };

    const callback1 = data => {
      assert.deepEqual(data, testData);
      assert.equal(service.listenerCount('test'), 3);
      service.off('test', callback1);
      assert.equal(service.listenerCount('test'), 2);
      service.removeAllListeners('test');
      assert.equal(service.listenerCount('test'), 0);
      done();
    };
    const callback2 = () => {
      // noop
    };

    service.on('test', callback1);
    service.on('test', callback2);
    service.on('test', callback2);

    connection.emit('todos test', testData);
  });

  it('forwards namespaced call to .off', done => {
    // Use it's own connection and service so off method gets detected
    const connection = new EventEmitter();

    connection.off = name => {
      assert.equal(name, 'todos test');
      done();
    };

    const service = new Service({
      name: 'todos',
      method: 'emit',
      timeout: 50,
      connection
    });

    service.off('test');
  });
});
<|endoftext|>


<commit_before><commit_msg>Updated to use revised vectorize function<commit_after><|endoftext|>


<commit_before>var assert = require('assert')
  , fs = require('fs')
  , sinon = require('sinon');

var { pathTestConfig, rmFiles } = require('./helpers');

var logger = require('../lib/logger');

var config = require('../lib/config');

describe('Config', function() {

    const testPath = pathTestConfig('config_test1.json');
    const newTestPath = pathTestConfig('config_test2.json');

    before(function() {
        sinon.stub(logger, 'log');
        this.prevPath = config.getPath();
    });

    after(function() {
        logger.log.restore();
        rmFiles(testPath, newTestPath);
        config.setPath(this.prevPath);
    });

    it('should correctly set path', function() {
        config.setPath(testPath);
        assert.strictEqual(config.getPath(), testPath);
    });

    it('should save values to file', function() {
        config.set('username', 'test1');
        config.save(() => {
            let data = JSON.parse(fs.readFileSync(testPath));
            assert.strictEqual(data.username, 'test1');
        });
    });

    it('should set and get correct values', function() {
        config.set('username', 'test2');
        let value = config.get('username');
        assert.strictEqual(value, 'test2');
    });

    it('should load existing config files', function() {
        let data = Object.assign({}, config.get());
        data.username = 'test3';
        fs.writeFileSync(newTestPath, JSON.stringify(data));
        config.setPath(newTestPath);
        let value = config.get('username');
        assert.strictEqual(value, 'test3');
    });

});
<commit_msg>Added done argument for async test.<commit_after>var assert = require('assert')
  , fs = require('fs')
  , sinon = require('sinon');

var { pathTestConfig, rmFiles } = require('./helpers');

var logger = require('../lib/logger');

var config = require('../lib/config');

describe('Config', function() {

    const testPath = pathTestConfig('config_test1.json');
    const newTestPath = pathTestConfig('config_test2.json');

    before(function() {
        sinon.stub(logger, 'log');
        this.prevPath = config.getPath();
    });

    after(function() {
        logger.log.restore();
        rmFiles(testPath, newTestPath);
        config.setPath(this.prevPath);
    });

    it('should correctly set path', function() {
        config.setPath(testPath);
        assert.strictEqual(config.getPath(), testPath);
    });

    it('should save values to file', function(done) {
        config.set('username', 'test1');
        config.save(() => {
            let data = JSON.parse(fs.readFileSync(testPath));
            assert.strictEqual(data.username, 'test1');
            done();
        });
    });

    it('should set and get correct values', function() {
        config.set('username', 'test2');
        let value = config.get('username');
        assert.strictEqual(value, 'test2');
    });

    it('should load existing config files', function() {
        let data = Object.assign({}, config.get());
        data.username = 'test3';
        fs.writeFileSync(newTestPath, JSON.stringify(data));
        config.setPath(newTestPath);
        let value = config.get('username');
        assert.strictEqual(value, 'test3');
    });

});
<|endoftext|>


<commit_before>angular.module("wbt")
.factory("authInterceptor",function($q,$localStorage,$injector){
  var request=function(config){
    if(!config.headers.authorization){
      if($localStorage.token){config.headers.authorization="bearer "+$localStorage.token;}
    }
    return config;
  };
  var responseError=function(response){
    if(response.status===401&&response.data==="Unauthorized"){
      var identity=$injector.get("identity");
      var $http=$injector.get("$http");
      var deferred=$q.defer();
      var loginModal=identity.login();
      loginModal.result.then(deferred.resolve,deferred.reject);
      return deferred.promise.then(function(){
        return $http(response.config);
      });
    }
    return $q.reject(response);
  };
  return {
    request: request
  };
});<commit_msg>authintercepter fix<commit_after>angular.module("wbt")
.factory("authInterceptor",function($q,$window,$injector){
  var request=function(config){
    /*
    if(!config.headers.authorization){
      if($localStorage.token){config.headers.authorization="bearer "+$localStorage.token;}
    }
    */
    if(!config.headers.authorization){
    var token=$window.localStorage.getItem('authToken');
    if(token){
      config.headers.authorization="bearer "+token;
    }
    }
    return config;
  };
  var responseError=function(response){
    if(response.status===401&&response.data==="Unauthorized"){
      var identity=$injector.get("identity");
      var $http=$injector.get("$http");
      var deferred=$q.defer();
      var loginModal=identity.login();
      loginModal.result.then(deferred.resolve,deferred.reject);
      return deferred.promise.then(function(){
        return $http(response.config);
      });
    }
    return $q.reject(response);
  };
  return {
    request: request
  };
});<|endoftext|>


<commit_before><commit_msg>fix(test): use logger instead of engine.logger<commit_after><|endoftext|>


<commit_before>
/**
 * Minimal.View Limit
 * @since 0.1.9.1
 * @description Comes from Minimal View
 * @return {[type]} [description]
 */
UI.Container.implement({
	options: {
		toggleFx: {
			duration: 300,
		    transition: 'quart:out',
		    link: 'cancel'
		}
	},

	/**
	 * [_initToggle description]
	 * @return {[type]} [description]
	 */
	_initToggle: function() {
		 //_log('_initToggle', this.isOpen, this._modifier, this.element);

		var opts = this.options,
			self = this,
			modifier = 'width';

		var size = this.element[modifier];
		opts.toggleFx.property = modifier;
		this.toggleFx = this.toggleFx || new Fx.Tween(this.element, opts.toggleFx).addEvents({
			complete: function(ev) {
				//_log('toggle complete', ev);
				self.fireEvent('toggled');
			}
		});
	},

	/**
	 * Remove or Inject the Application Container in the DOM
	 * @return {[type]} [description]
	 */
	toggle: function() {
		//console.log('toggle', this.isOpen);

		var self = this,
			opts = this.options,
			modifier = 'width';

		var size = this[modifier] || 160;
		//_log('size', size || 100);
		//_log('--- isOpen', this.isOpen);
		if (this.isOpen === true) {
			//_log('--- close', this.isOpen);
			this.toggleClose();
		} else {
			//_log('--- open', this.isOpen);
			this.toggleOpen(size);
		}

		//return this.isOpen;
	},

	/**
	 * [toggleClose description]
	 * @return {[type]} [description]
	 */
	toggleClose: function() {
		//_log('toggleOpen');

		this.toggleFx.start(0);

		//console.log('close');
		this.element.removeClass('state-focus');

		/*(function() {
			self.container.setStyle('display', 'none');
		}).delay(250);*/

		minimal.settings.set('layout.' + this.main + '.hidden', true);
		minimal.settings.save();

		this.isOpen = false;

		//view.container.addClass('state-focus');
	},

	/**
	 * [toggleOpen description]
	 * @param  {[type]} size [description]
	 * @return {[type]}      [description]
	 */
	toggleOpen: function(size) {
		//_log('toggleOpen', size);

		this.toggleFx.start(size);

		this.element.setStyle('display', null);
		this.element.addClass('state-focus');

		minimal.settings.set('layout.' + this.main + '.hidden', false);
		minimal.settings.save();

		//view.container.removeClass('state-focus');
		this.isOpen = true;
	}

});
<commit_msg>Enhance User Experience<commit_after>
/**
 * Minimal.View Limit
 * @since 0.1.9.1
 * @description Comes from Minimal View
 * @return {[type]} [description]
 */
UI.Container.implement({
	options: {
		toggleFx: {
			duration: 260,
		    transition: 'sine:out',
		    link: 'cancel'
		}
	},

	/**
	 * [_initToggle description]
	 * @return {[type]} [description]
	 */
	_initToggle: function() {
		 _log('_initToggle', this.isOpen, this._modifier, this.element);

		var opts = this.options,
			self = this,
			modifier = 'width';

		var size = this.element[modifier];

		console.log('-----', size);

		opts.toggleFx.property = modifier;
		this.toggleFx = this.toggleFx || new Fx.Tween(this.element, opts.toggleFx).addEvents({
			complete: function(ev) {
				//_log('toggle complete', ev);
				self.fireEvent('toggled');
			}
		});
	},

	/**
	 * Remove or Inject the Application Container in the DOM
	 * @return {[type]} [description]
	 */
	toggle: function() {
		//console.log('toggle', this.isOpen);

		var self = this,
			opts = this.options,
			modifier = 'width';

		var size = this[modifier] || 160;
		_log('size', size || 100);
		_log('--- isOpen', this.isOpen);
		if (this.isOpen === true) {
			_log('--- close', this.isOpen);
			this.toggleClose();
		} else {
			_log('--- open', this.isOpen, size);
			this.toggleOpen(size);
		}

		//return this.isOpen;
	},

	/**
	 * [toggleClose description]
	 * @return {[type]} [description]
	 */
	toggleClose: function() {
		_log('toggleOpen');

		this.toggleFx.start(0);

		//console.log('close');
		this.element.removeClass('state-focus');

		/*(function() {
			self.container.setStyle('display', 'none');
		}).delay(250);*/
		this.isOpen = false;

		minimal.settings.set('layout.' + this.main + '.hidden', true);
		minimal.settings.save();

		//view.container.addClass('state-focus');
	},

	/**
	 * [toggleOpen description]
	 * @param  {[type]} size [description]
	 * @return {[type]}      [description]
	 */
	toggleOpen: function(size) {
		_log('toggleOpen', size);

		this.toggleFx.start(size);

		this.element.setStyle('display', null);
		this.element.addClass('state-focus');

		this.isOpen = true;

		minimal.settings.set('layout.' + this.main + '.hidden', false);
		minimal.settings.save();

		//view.container.removeClass('state-focus');

	}

});
<|endoftext|>