<commit_before>import React, { PropTypes } from "react";

import Label from "./components/Label";

export default class Checkbox extends React.Component {

  static propTypes = {
    defaultValue: PropTypes.oneOfType([
      PropTypes.bool,
      PropTypes.string,
    ]),
    status: PropTypes.string,
    disabled: PropTypes.any, // eslint-disable-line
    validation: PropTypes.func,
    errorText: PropTypes.string,
    theme: PropTypes.string,
    type: PropTypes.string,
    error: PropTypes.any, // eslint-disable-line
    classes: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.array,
    ]),
    children: PropTypes.any, // eslint-disable-line
    id: PropTypes.string,
    label: PropTypes.string,
    name: PropTypes.string,
    inputClasses: PropTypes.array, // eslint-disable-line
    clicked: PropTypes.func,
    hideLabel: PropTypes.bool,
  }

  state = {
    status: false,
    error: false,
  }

  setStatus = (message) => {
    this.props.status = message;
    return undefined;
  }

  disabled = () => {
    if (this.props.disabled) {
      return disabled; // eslint-disable-line
    }
    return undefined;
  }

  validate = (event) => {
    const value = event.target.value;

    if (!value) {
      this.setState({
        active: false,
        error: false,
      });
    }

    if (this.props.validation && typeof (this.props.validation) === "function") {
      this.setState({
        error: !this.props.validation(value),
      });
    }
  }

  renderHelpText() {
    if ((this.state.error && this.props.errorText) || this.state.status) {
      return (

          {this.props.errorText || this.state.status}

      );
    }
    return undefined;
  }

  render() {
    let inputclasses = [
      "input",
    ];

    // theme overwrite
    if (this.props.theme) { inputclasses = this.props.theme; }
    // state mangaged classes
    if (this.state.status) { inputclasses.push("push-double-bottom"); }

    if (this.props.type) {
      inputclasses.push(this.props.type);
    } else {
      inputclasses.push("checkbox");
    }

    if (this.props.error) { inputclasses.push("input--alert"); }
    // custom added classes
    if (this.props.classes) { inputclasses = inputclasses.concat(this.props.classes); }

    return (

            {this.props.children}

        <input
          id={this.props.id || this.props.label || this.props.name}
          type={this.props.type || "checkbox"}
          name={this.props.name || this.props.label}
          className={this.props.inputClasses}
          disabled={this.disabled()}
          defaultChecked={this.props.defaultValue ? "checked" : ""}
          onClick={this.props.clicked}
          style={{ width: 0 }}
        />

        {!this.props.hideLabel && (

        )}

        {this.renderHelpText()}

    );
  }
}
<commit_msg>fixed disabled undefined<commit_after>import React, { PropTypes } from "react";

import Label from "./components/Label";

export default class Checkbox extends React.Component {

  static propTypes = {
    defaultValue: PropTypes.oneOfType([
      PropTypes.bool,
      PropTypes.string,
    ]),
    status: PropTypes.string,
    disabled: PropTypes.any, // eslint-disable-line
    validation: PropTypes.func,
    errorText: PropTypes.string,
    theme: PropTypes.string,
    type: PropTypes.string,
    error: PropTypes.any, // eslint-disable-line
    classes: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.array,
    ]),
    children: PropTypes.any, // eslint-disable-line
    id: PropTypes.string,
    label: PropTypes.string,
    name: PropTypes.string,
    inputClasses: PropTypes.array, // eslint-disable-line
    clicked: PropTypes.func,
    hideLabel: PropTypes.bool,
  }

  state = {
    status: false,
    error: false,
  }

  setStatus = (message) => {
    this.props.status = message;
    return undefined;
  }

  disabled = () => {
    if (this.props.disabled) {
      return this.props.disabled; // eslint-disable-line
    }
    return undefined;
  }

  validate = (event) => {
    const value = event.target.value;

    if (!value) {
      this.setState({
        active: false,
        error: false,
      });
    }

    if (this.props.validation && typeof (this.props.validation) === "function") {
      this.setState({
        error: !this.props.validation(value),
      });
    }
  }

  renderHelpText() {
    if ((this.state.error && this.props.errorText) || this.state.status) {
      return (

          {this.props.errorText || this.state.status}

      );
    }
    return undefined;
  }

  render() {
    let inputclasses = [
      "input",
    ];

    // theme overwrite
    if (this.props.theme) { inputclasses = this.props.theme; }
    // state mangaged classes
    if (this.state.status) { inputclasses.push("push-double-bottom"); }

    if (this.props.type) {
      inputclasses.push(this.props.type);
    } else {
      inputclasses.push("checkbox");
    }

    if (this.props.error) { inputclasses.push("input--alert"); }
    // custom added classes
    if (this.props.classes) { inputclasses = inputclasses.concat(this.props.classes); }

    return (

            {this.props.children}

        <input
          id={this.props.id || this.props.label || this.props.name}
          type={this.props.type || "checkbox"}
          name={this.props.name || this.props.label}
          className={this.props.inputClasses}
          disabled={this.disabled()}
          defaultChecked={this.props.defaultValue ? "checked" : ""}
          onClick={this.props.clicked}
          style={{ width: 0 }}
          data-spec="input"
        />

        {!this.props.hideLabel && (

        )}

        {this.renderHelpText()}

    );
  }
}
<|endoftext|>


<commit_before>//Import dependencies
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var utily = require('../index.js');

//Test common methods
describe('utily -> commons', function()
{
  //Each method
  describe('-> each method', function()
  {
    it('should iterate over all the elements in an array', function(done)
    {
      var list = [0, 1, 2, 3, 4];
      var counter = 0;
      utily.each(list, function(index, value)
      {
        assert.equal(counter, index);
        assert.equal(list[index], value);
        counter = counter + 1;
      });
      done();
    });

    it('should iterate over all the elements in an object', function(done)
    {
      var obj = { 'key1': 'value1', 'key2': 'value2' };
      var keys = Object.keys(obj);
      var counter = 0;
      utily.each(obj, function(key, value)
      {
        assert.equal(keys[counter], key);
        assert.equal(obj[key], value);
        counter = counter + 1;
      });
      done();
    });
  });

  //Each Async method
  describe('-> each async method', function()
  {
    it('should iterate over all the elements in an array', function(done)
    {
      var list = [0, 1, 2, 3, 4];
      var counter = 0;
      utily.eachAsync(list, function(index, value, next)
      {
        setTimeout(function()
        {
          assert.equal(counter, index);
          assert.equal(list[index], value);
          counter = counter + 1;
          next();
        }, 100);
      }, function(){ return done(); });
    });

    it('should iterate over all the elements in an object', function(done)
    {
      var obj = { 'key1': 'value1', 'key2': 'value2' };
      var keys = Object.keys(obj);
      var counter = 0;
      utily.eachAsync(obj, function(key, value, next)
      {
        setTimeout(function()
        {
          assert.equal(keys[counter], key);
          assert.equal(obj[key], value);
          counter = counter + 1;
          next();
        }, 100);
      }, function(){ return done(); });
    });
  });
});

//Test array methods
describe('utily -> array', function()
{
  //Test has method
  describe('-> has method', function()
  {
    it('should return true if item exists in the array', function(done)
    {
      assert.equal(utily.array.has([1, 2, 3], 3), true);
      done();
    });
    it('should return false if item does not exists in the array', function(done)
    {
      assert.equal(utily.array.has([1, 2, 3], 0), false);
      done();
    });
  });

  //Test max method
  describe('-> max method', function()
  {
    it('should return the maximum value of an array', function(done)
    {
      assert.equal(utily.array.max([5,4,7,3,9,-10]), 9);
      done();
    });
  });

  //Test min method
  describe('-> min method', function()
  {
    it('should return the minimum value of an array', function(done)
    {
      assert.equal(utily.array.min([5,4,7,3,9,-10]), -10);
      done();
    });
  });

  //Test remove method
  describe('-> range method', function()
  {
    it('should remove an element of the array', function(done)
    {
      var array = utily.array.remove([0, 1, 2, 3, 4, 5], 3);
      assert.equal(array.length, 5);
      assert.equal(array[2], 2);
      assert.equal(array[3], 4);
      assert.equal(array.indexOf(3), -1);
      done();
    });
  });
});

//Test the fs methods
describe('utily -> fs', function()
{
  //Test checksum method
  describe('-> checksum method', function()
  {
    var file = path.join(__dirname, './fs-checksum-test.txt');
    fs.writeFileSync(file, 'Hello\nThis is the content\n', 'utf8');
    it('should generate the correct checksum of the file', function(done)
    {
      return utily.fs.checksum(file, 'md5', function(error, sum)
      {
        assert.equal(null, error);
        assert.equal('2c1b03ff58b808e5bd56196131cc8505', sum);
        done();
      });
    });
  });

  //Test copy method
  describe('-> copy method', function()
  {
    //Copy files
    it('shgould copy a file that exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      fs.writeFileSync(file_source, 'This is the content of the file 1', 'utf8');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.equal(null, error);
        var content1 = fs.readFileSync(file_source, 'utf8');
        var content2 = fs.readFileSync(file_destination, 'utf8');
        assert.equal(content1, content2);
        done();
      });
    });

    //Display an error
    it('should return an error if source file does not exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source-unexistent.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.notEqual(null, error);
        done();
      });
    });
  });

  //Test exists method
  describe('-> exists method', function()
  {
    //Folder that does not exists
    it('should return false if path does not exists', function(done)
    {
      return utily.fs.exists(path.join(__dirname, './inexistent'), function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });
    //Folder that exists
    it('should return true if path exists', function(done)
    {
      return utily.fs.exists(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });
  });

  //Test isDir method
  describe('-> isDir method', function()
  {
    //Folder that exists
    it('should return that the folder path is a directory', function(done)
    {
      return utily.fs.isDir(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });

    //Path is a file
    it('should return that the file path is not a directory', function(done)
    {
      var file = path.join(__dirname, 'test.js');
      return utily.fs.isDir(file, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });

    //Path does not exists
    it('should return that the fake path is not a directory', function(done)
    {
      var fake = path.join(__dirname, './fake/path');
      return utily.fs.isDir(fake, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    })
  });

  //Test isFile method
  describe('-> isFile method', function()
  {
    //Path is a file that exists
    it('should return that the file path is a file', function(done)
    {
      var file = path.join(__dirname, 'test.js');
      return utily.fs.isFile(file, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });

    //Path is a folder
    it('should return that the folder path is not a file', function(done)
    {
      return utily.fs.isFile(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });

    //Path does not exists
    it('should return that the fake path is not a file', function(done)
    {
      var fake = path.join(__dirname, './fake/path.txt');
      return utily.fs.isFile(fake, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    })
  });

  //Test mkdir method
  describe('-> mkdir method', function()
  {
    //Create a folder
    it('should create the folders', function(done)
    {
      var folders = path.join(__dirname, './new/folders/yeah');
      return utily.fs.mkdir(folders, function(error)
      {
        assert.equal(null, error);
        assert.equal(true, fs.existsSync(folders));
        done();
      });
    });
  });

  //Test size method
  describe('-> size method', function()
  {
    //Check the file size
    it('should get the real file size', function(done)
    {
      var file = path.join(__dirname, './fs-size-test.txt');
      fs.writeFileSync(file, 'This is the content of the \nfile\n', 'utf8');
      return utily.fs.size(file, function(error, size)
      {
        assert.equal(null, error);
        assert.equal(33, size);
        done();
      });
    });
  });

  //Test unlink method
  describe('-> unlink method', function()
  {
    //Delete a list of file
    it('should delete a list of files', function(done)
    {
      var file1 = path.join(__dirname, './fs-unlink-test1.txt');
      var file2 = path.join(__dirname, './fs-unlink-test2.txt');
      fs.writeFileSync(file1, 'Test 1', 'utf8');
      fs.writeFileSync(file2, 'Test 2', 'utf8');
      return utily.fs.unlink([ file1, file2 ], function(error)
      {
        assert.equal(null, error);
        assert.equal(false, fs.existsSync(file1));
        assert.equal(false, fs.existsSync(file2));
        done();
      });
    });
  });
});

//Test object methods
describe('utily -> object', function()
{
  //Test each method
  describe('-> each method', function()
  {
    it('should iterate over all the elements in an object', function(done)
    {
      var obj = { key1: 'value1', key2: 'value2', key3: 'value3' };
      utily.object.each(obj, function(key, value)
      {
        assert.equal(value, obj[key]);
      });
      done();
    });
  });
});

//Test queue methods
describe('utily -> queue', function()
{
  //Test
  it('should run functions in order', function(done)
  {
    var counter = 0;
    utily.queue.add('test1', function(next)
    {
      assert.equal(counter, 0);
      counter = counter + 1;
      setTimeout(function(){ return next(); }, 500);
    });
    utily.queue.add('test1', function(next)
    {
      assert.equal(counter, 1);
      counter = counter + 1;
      setTimeout(function(){ return next(); }, 500);
    });
    utily.queue.add('test1', function(next)
    {
      assert.equal(counter, 2);
      return done();
    });
  });
});

<commit_msg>test/test.js: added queue pause/resume tests<commit_after>//Import dependencies
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var utily = require('../index.js');

//Test common methods
describe('utily -> commons', function()
{
  //Each method
  describe('-> each method', function()
  {
    it('should iterate over all the elements in an array', function(done)
    {
      var list = [0, 1, 2, 3, 4];
      var counter = 0;
      utily.each(list, function(index, value)
      {
        assert.equal(counter, index);
        assert.equal(list[index], value);
        counter = counter + 1;
      });
      done();
    });

    it('should iterate over all the elements in an object', function(done)
    {
      var obj = { 'key1': 'value1', 'key2': 'value2' };
      var keys = Object.keys(obj);
      var counter = 0;
      utily.each(obj, function(key, value)
      {
        assert.equal(keys[counter], key);
        assert.equal(obj[key], value);
        counter = counter + 1;
      });
      done();
    });
  });

  //Each Async method
  describe('-> each async method', function()
  {
    it('should iterate over all the elements in an array', function(done)
    {
      var list = [0, 1, 2, 3, 4];
      var counter = 0;
      utily.eachAsync(list, function(index, value, next)
      {
        setTimeout(function()
        {
          assert.equal(counter, index);
          assert.equal(list[index], value);
          counter = counter + 1;
          next();
        }, 100);
      }, function(){ return done(); });
    });

    it('should iterate over all the elements in an object', function(done)
    {
      var obj = { 'key1': 'value1', 'key2': 'value2' };
      var keys = Object.keys(obj);
      var counter = 0;
      utily.eachAsync(obj, function(key, value, next)
      {
        setTimeout(function()
        {
          assert.equal(keys[counter], key);
          assert.equal(obj[key], value);
          counter = counter + 1;
          next();
        }, 100);
      }, function(){ return done(); });
    });
  });
});

//Test array methods
describe('utily -> array', function()
{
  //Test has method
  describe('-> has method', function()
  {
    it('should return true if item exists in the array', function(done)
    {
      assert.equal(utily.array.has([1, 2, 3], 3), true);
      done();
    });
    it('should return false if item does not exists in the array', function(done)
    {
      assert.equal(utily.array.has([1, 2, 3], 0), false);
      done();
    });
  });

  //Test max method
  describe('-> max method', function()
  {
    it('should return the maximum value of an array', function(done)
    {
      assert.equal(utily.array.max([5,4,7,3,9,-10]), 9);
      done();
    });
  });

  //Test min method
  describe('-> min method', function()
  {
    it('should return the minimum value of an array', function(done)
    {
      assert.equal(utily.array.min([5,4,7,3,9,-10]), -10);
      done();
    });
  });

  //Test remove method
  describe('-> range method', function()
  {
    it('should remove an element of the array', function(done)
    {
      var array = utily.array.remove([0, 1, 2, 3, 4, 5], 3);
      assert.equal(array.length, 5);
      assert.equal(array[2], 2);
      assert.equal(array[3], 4);
      assert.equal(array.indexOf(3), -1);
      done();
    });
  });
});

//Test the fs methods
describe('utily -> fs', function()
{
  //Test checksum method
  describe('-> checksum method', function()
  {
    var file = path.join(__dirname, './fs-checksum-test.txt');
    fs.writeFileSync(file, 'Hello\nThis is the content\n', 'utf8');
    it('should generate the correct checksum of the file', function(done)
    {
      return utily.fs.checksum(file, 'md5', function(error, sum)
      {
        assert.equal(null, error);
        assert.equal('2c1b03ff58b808e5bd56196131cc8505', sum);
        done();
      });
    });
  });

  //Test copy method
  describe('-> copy method', function()
  {
    //Copy files
    it('shgould copy a file that exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      fs.writeFileSync(file_source, 'This is the content of the file 1', 'utf8');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.equal(null, error);
        var content1 = fs.readFileSync(file_source, 'utf8');
        var content2 = fs.readFileSync(file_destination, 'utf8');
        assert.equal(content1, content2);
        done();
      });
    });

    //Display an error
    it('should return an error if source file does not exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source-unexistent.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.notEqual(null, error);
        done();
      });
    });
  });

  //Test exists method
  describe('-> exists method', function()
  {
    //Folder that does not exists
    it('should return false if path does not exists', function(done)
    {
      return utily.fs.exists(path.join(__dirname, './inexistent'), function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });
    //Folder that exists
    it('should return true if path exists', function(done)
    {
      return utily.fs.exists(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });
  });

  //Test isDir method
  describe('-> isDir method', function()
  {
    //Folder that exists
    it('should return that the folder path is a directory', function(done)
    {
      return utily.fs.isDir(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });

    //Path is a file
    it('should return that the file path is not a directory', function(done)
    {
      var file = path.join(__dirname, 'test.js');
      return utily.fs.isDir(file, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });

    //Path does not exists
    it('should return that the fake path is not a directory', function(done)
    {
      var fake = path.join(__dirname, './fake/path');
      return utily.fs.isDir(fake, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    })
  });

  //Test isFile method
  describe('-> isFile method', function()
  {
    //Path is a file that exists
    it('should return that the file path is a file', function(done)
    {
      var file = path.join(__dirname, 'test.js');
      return utily.fs.isFile(file, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });

    //Path is a folder
    it('should return that the folder path is not a file', function(done)
    {
      return utily.fs.isFile(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });

    //Path does not exists
    it('should return that the fake path is not a file', function(done)
    {
      var fake = path.join(__dirname, './fake/path.txt');
      return utily.fs.isFile(fake, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    })
  });

  //Test mkdir method
  describe('-> mkdir method', function()
  {
    //Create a folder
    it('should create the folders', function(done)
    {
      var folders = path.join(__dirname, './new/folders/yeah');
      return utily.fs.mkdir(folders, function(error)
      {
        assert.equal(null, error);
        assert.equal(true, fs.existsSync(folders));
        done();
      });
    });
  });

  //Test size method
  describe('-> size method', function()
  {
    //Check the file size
    it('should get the real file size', function(done)
    {
      var file = path.join(__dirname, './fs-size-test.txt');
      fs.writeFileSync(file, 'This is the content of the \nfile\n', 'utf8');
      return utily.fs.size(file, function(error, size)
      {
        assert.equal(null, error);
        assert.equal(33, size);
        done();
      });
    });
  });

  //Test unlink method
  describe('-> unlink method', function()
  {
    //Delete a list of file
    it('should delete a list of files', function(done)
    {
      var file1 = path.join(__dirname, './fs-unlink-test1.txt');
      var file2 = path.join(__dirname, './fs-unlink-test2.txt');
      fs.writeFileSync(file1, 'Test 1', 'utf8');
      fs.writeFileSync(file2, 'Test 2', 'utf8');
      return utily.fs.unlink([ file1, file2 ], function(error)
      {
        assert.equal(null, error);
        assert.equal(false, fs.existsSync(file1));
        assert.equal(false, fs.existsSync(file2));
        done();
      });
    });
  });
});

//Test object methods
describe('utily -> object', function()
{
  //Test each method
  describe('-> each method', function()
  {
    it('should iterate over all the elements in an object', function(done)
    {
      var obj = { key1: 'value1', key2: 'value2', key3: 'value3' };
      utily.object.each(obj, function(key, value)
      {
        assert.equal(value, obj[key]);
      });
      done();
    });
  });
});

//Test queue methods
describe('utily -> queue', function()
{
  it('should run tasks in order', function(done)
  {
    var counter = 0;
    utily.queue.add('test1', function(next)
    {
      assert.equal(counter, 0);
      counter = counter + 1;
      setTimeout(function(){ return next(); }, 500);
    });
    utily.queue.add('test1', function(next)
    {
      assert.equal(counter, 1);
      counter = counter + 1;
      setTimeout(function(){ return next(); }, 500);
    });
    utily.queue.add('test1', function(next)
    {
      assert.equal(counter, 2);
      next();
      return done();
    });
  });

  it('should pause and resume tasks', function(done)
  {
    var ready = false;
    utily.queue.add('test2', function(next)
    {
      //Pause the queue
      utily.queue.pause('test2');
      next();
      setTimeout(function(){ ready = true; utily.queue.resume('test2'); }, 1000);
    });
    utily.queue.add('test2', function(next)
    {
      assert.equal(ready, true);
      next();
      return done();
    });
  });
});

<|endoftext|>


<commit_before>
var assert = require('assert');
var should = require('should');
var inter = require("../scheme").interpreter;

describe('interpreter', function () {
    it('plus', function () {
        inter("(+ 1 45)").should.equal(46);
        inter("(+ 1 (+ 1 44))").should.equal(46)
    })

    it('sub1 & add1', function () {
        inter("(sub1 47)").should.equal(46);
        inter("(add1 45)").should.equal(46);
    })

    it('lambda', function () {
        inter("(lambda (x) x)")(46).should.equal(46)
        inter("((lambda (x) (+ x 2)) 44)").should.equal(46)
    })

    it('let', function () {
        inter("(let ((x 1)) (+ x 45))").should.equal(46)
    })

    it('if', function () {
        inter("(if (zero? 0) 46 0)").should.equal(46)
        inter("(if (eq? 46 46) 46 0)").should.equal(46)
    })

    it('fact', function () {
        inter("\
                (letrec ((fact \ (lambda (n) \
                                    (if (zero? n) \
                                        1 \
                                        (* n  (fact (sub1 n))))))) \
                    (+ (fact  4) 22))").should.equal(46);
    })

    // http://www.ece.uc.edu/~franco/C511/html/Scheme/ycomb.html

    it('Y combinator', function () {
        inter("(((lambda (X) \
              ((lambda (procedure) \
                 (X (lambda (arg) ((procedure procedure) arg)))) \
               (lambda (procedure) \
                 (X (lambda (arg) ((procedure procedure) arg)))))) \
            (lambda (func-arg) \
              (lambda (n) \
                (if (zero? n) \
                    1 \
                    (* n (func-arg (sub1 n))))))) \
           5)").should.equal(120);
    })

    it('support two arg lambda', function(){
        inter("(lambda (x y) x)")(46, 1).should.equal(46)
        inter("(lambda (x y) (+ x y))")(45, 1).should.equal(46)
        inter("((lambda (x y) (+ x y)) 45 1)").should.equal(46)
    })

    it('begin', function(){
        inter("(begin (+ 1 2) 46)").should.equal(46)
    })

    it('set!', function(){
        inter("(let ((x 45))(begin (set! x 46) x))").should.equal(46)
    })

    it('let multi body',function(){
        inter("(let ((x 45))(set! x 46) x)").should.equal(46)
    })

    it('call-by-value', function(){
        inter("\
            ((lambda (a) \
                      ((lambda (p) \
                     (begin \
                      (p a) \
                      a)) (lambda (x) (set! x 3)))) 46)").should.equal(46)
    })

    it('let set! check', function(){
        inter("\
            (let ((x 46)) \
                (let ((x 45)) \
                    (set! x 44)) \
            x)").should.equal(46)
    })

    // use globalEnv? buildInEnv
    it('define', function(){

    })

    //
    it('cond', function(){

    })

    //
    it('quote', function(){

    })

    it('quasiquote', function(){

    })

    // this is difficult
    it('match', function(){

    })

    it('tostring', function(){

    })

})

<commit_msg>use es6 multiline `<commit_after>
var assert = require('assert');
var should = require('should');
var inter = require("../scheme").interpreter;

describe('interpreter', function () {
    it('plus', function () {
        inter("(+ 1 45)").should.equal(46);
        inter("(+ 1 (+ 1 44))").should.equal(46)
    })

    it('sub1 & add1', function () {
        inter("(sub1 47)").should.equal(46);
        inter("(add1 45)").should.equal(46);
    })

    it('lambda', function () {
        inter("(lambda (x) x)")(46).should.equal(46)
        inter("((lambda (x) (+ x 2)) 44)").should.equal(46)
    })

    it('let', function () {
        inter("(let ((x 1)) (+ x 45))").should.equal(46)
    })

    it('if', function () {
        inter("(if (zero? 0) 46 0)").should.equal(46)
        inter("(if (eq? 46 46) 46 0)").should.equal(46)
    })

    it('fact', function () {
        inter(`
                (letrec ((fact  (lambda (n)
                                    (if (zero? n)
                                        1
                                        (* n  (fact (sub1 n)))))))
                    (+ (fact  4) 22))`).should.equal(46);
    })

    // http://www.ece.uc.edu/~franco/C511/html/Scheme/ycomb.html

    it('Y combinator', function () {
        inter(`(((lambda (X)
              ((lambda (procedure)
                 (X (lambda (arg) ((procedure procedure) arg))))
               (lambda (procedure)
                 (X (lambda (arg) ((procedure procedure) arg))))))
            (lambda (func-arg)
              (lambda (n)
                (if (zero? n)
                    1
                    (* n (func-arg (sub1 n)))))))
           5)`).should.equal(120);
    })

    it('support two arg lambda', function(){
        inter("(lambda (x y) x)")(46, 1).should.equal(46)
        inter("(lambda (x y) (+ x y))")(45, 1).should.equal(46)
        inter("((lambda (x y) (+ x y)) 45 1)").should.equal(46)
    })

    it('begin', function(){
        inter("(begin (+ 1 2) 46)").should.equal(46)
    })

    it('set!', function(){
        inter("(let ((x 45))(begin (set! x 46) x))").should.equal(46)
    })

    it('let multi body',function(){
        inter("(let ((x 45))(set! x 46) x)").should.equal(46)
    })

    it('call-by-value', function(){
        inter(`
            ((lambda (a)
                  ((lambda (p)
                     (begin
                      (p a)
                      a)) (lambda (x) (set! x 3)))) 46)`).should.equal(46)
    })

    it('let set! check', function(){
        inter(`
            (let ((x 46))
                (let ((x 45))
                    (set! x 44))
            x)`).should.equal(46)
    })

    // use globalEnv? buildInEnv
    it('define', function(){

    })

    //
    it('cond', function(){

    })

    //
    it('quote', function(){

    })

    it('quasiquote', function(){

    })

    // this is difficult
    it('match', function(){

    })

    it('tostring', function(){

    })

})

<|endoftext|>


<commit_before>var request = require("supertest"),
    assert = require("assert"),
    app = require("../app");

describe("Root routes", function() {
    describe("GET /", function() {
        it("should respond with the index page", function(done) {
            request(app)
                .get("/")
                .expect(200)
                .expect("Content-Type", /html/)
                .end(done);
        });
    });

    describe("GET known 404", function() {
        it("should respond with 404", function(done) {
            request(app)
                .get("/nopagehere")
                .expect(404)
                //.expect("404") // hi-fi
                .end(done);
        });
    });

    describe("POST /shorten", function() {
        it("should return an id on success", function(done) {
            request(app)
                .post("/shorten")
                .send({"link": "https://www.google.fi/"})
                .expect(200)
                .expect("Content-Type", /text\/plain/)
                .expect(/^.{5}$/)
                .end(done);
        });
        it("should return 400 on lacking parameters", function(done) {
            request(app)
                .post("/shorten")
                .send({"link_bad": "https://www.google.fi/"})
                .expect(400)
                .end(done);
        });
    });

    describe("GET /:id", function() {
        it("should respond with 301 on success", function(done) {
            var url = "https://www.google.fi/";
            request(app)
                .post("/shorten")
                .send({"link": url})
                .end(function(err, res) {
                    if (err) return done(err);
                    var id = res.text;
                    request(app)
                        .get("/" + id)
                        .expect(301)
                        .expect("Location", url)
                        .end(done);
                });
        });
        it("should respond with 404 if the entry is not there", function(done) {
            request(app)
                .get("/XXXXX")
                .expect(404)
                .end(done);
        });
    });
});

describe("URLS resource (/urls)", function() {
    describe("POST /urls", function() {
        it("should return the created resource with given details as json", function(done) {
            var id = "google";
            var link = "https://www.google.com";
            request(app)
                .post("/urls")
                .send({"id": id, "link": link})
                .expect(200)
                .expect("Content-Type", /application\/json/)
                .expect(function (res) {
                    var url = JSON.parse(res.text);
                    assert.equal(url.id, id, "ID");
                    assert.equal(url.link, link, "LINK");
                })
                .end(done);
        });
        it("should return 400 if the id is in use", function(done) {
            var id = "doubleid";
            var link = "https://www.google.com";
            request(app)
                .post("/urls")
                .send({"id": id, "link": link})
                .end(function(err, res) {
                    if (err) return done(err);
                    request(app)
                        .post("/urls")
                        .send({"id": id, "link": link})
                        .expect(400)
                        .expect("Content-Type", /application\/json/)
                        .end(done);
                });
        });
        it("should return 400 on missing parameters", function(done) {
            request(app)
                .post("/urls")
                .send({"id_bad": "bad_params1", "link": "bad_params1"})
                .expect(400)
                .expect("Content-Type", /application\/json/)
                .end(function(err, res) {
                    if (err) return done(err);
                    request(app)
                        .post("/urls")
                        .send({"id": "bad_params2"})
                        .expect(400)
                        .end(done);
                });
        });
    });

    describe.skip("GET /urls", function() {
        it("should return the collection resource as json", function(done) {
        });
    });

    describe.skip("GET /urls/:id", function() {
        it("should return an existing resource as json", function(done) {
        });
        it("should return 404 if the resource is not found", function(done) {
        });
    });
});
<commit_msg>Ever so slight clarification to test description.<commit_after>var request = require("supertest"),
    assert = require("assert"),
    app = require("../app");

describe("Root routes (/)", function() {
    describe("GET /", function() {
        it("should respond with the index page", function(done) {
            request(app)
                .get("/")
                .expect(200)
                .expect("Content-Type", /html/)
                .end(done);
        });
    });

    describe("GET known 404", function() {
        it("should respond with 404", function(done) {
            request(app)
                .get("/nopagehere")
                .expect(404)
                //.expect("404") // hi-fi
                .end(done);
        });
    });

    describe("POST /shorten", function() {
        it("should return an id on success", function(done) {
            request(app)
                .post("/shorten")
                .send({"link": "https://www.google.fi/"})
                .expect(200)
                .expect("Content-Type", /text\/plain/)
                .expect(/^.{5}$/)
                .end(done);
        });
        it("should return 400 on lacking parameters", function(done) {
            request(app)
                .post("/shorten")
                .send({"link_bad": "https://www.google.fi/"})
                .expect(400)
                .end(done);
        });
    });

    describe("GET /:id", function() {
        it("should respond with 301 on success", function(done) {
            var url = "https://www.google.fi/";
            request(app)
                .post("/shorten")
                .send({"link": url})
                .end(function(err, res) {
                    if (err) return done(err);
                    var id = res.text;
                    request(app)
                        .get("/" + id)
                        .expect(301)
                        .expect("Location", url)
                        .end(done);
                });
        });
        it("should respond with 404 if the entry is not there", function(done) {
            request(app)
                .get("/XXXXX")
                .expect(404)
                .end(done);
        });
    });
});

describe("URLS resource (/urls)", function() {
    describe("POST /urls", function() {
        it("should return the created resource with given details as json", function(done) {
            var id = "google";
            var link = "https://www.google.com";
            request(app)
                .post("/urls")
                .send({"id": id, "link": link})
                .expect(200)
                .expect("Content-Type", /application\/json/)
                .expect(function (res) {
                    var url = JSON.parse(res.text);
                    assert.equal(url.id, id, "ID");
                    assert.equal(url.link, link, "LINK");
                })
                .end(done);
        });
        it("should return 400 if the id is in use", function(done) {
            var id = "doubleid";
            var link = "https://www.google.com";
            request(app)
                .post("/urls")
                .send({"id": id, "link": link})
                .end(function(err, res) {
                    if (err) return done(err);
                    request(app)
                        .post("/urls")
                        .send({"id": id, "link": link})
                        .expect(400)
                        .expect("Content-Type", /application\/json/)
                        .end(done);
                });
        });
        it("should return 400 on missing parameters", function(done) {
            request(app)
                .post("/urls")
                .send({"id_bad": "bad_params1", "link": "bad_params1"})
                .expect(400)
                .expect("Content-Type", /application\/json/)
                .end(function(err, res) {
                    if (err) return done(err);
                    request(app)
                        .post("/urls")
                        .send({"id": "bad_params2"})
                        .expect(400)
                        .end(done);
                });
        });
    });

    describe.skip("GET /urls", function() {
        it("should return the collection resource as json", function(done) {
        });
    });

    describe.skip("GET /urls/:id", function() {
        it("should return an existing resource as json", function(done) {
        });
        it("should return 404 if the resource is not found", function(done) {
        });
    });
});
<|endoftext|>


<commit_before>const assert = require('assert');
const Converter = require('../js/convert.js');
const fs = require('fs');

describe('ppt-png', function() {
    describe('normal', function() {
        this.timeout(10000);
        it('Test if the ppt file can convert to a jpg.', function(done) {
            new Converter({
                files:          ['test/OPW 733 Tienduizend redenen.ppt'],
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  true,
                outputType:     'jpg',
                logLevel:       3,
                fileNameFormat: '_vers_%d',
                callback:       function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done(data.failed[0].error);
                    } else {
                        done();
                    }
                }
            }).run();
        });
    });

    describe('promise', function() {
        this.timeout(10000);
        it('Test with the promise.', function(done) {
            new Converter({
                files:  ['test/OPW 733 Tienduizend redenen.ppt'],
                output: 'output/test/'
            })
                .wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done(data.failed[0].error);
                    } else {
                        done();
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('failed', function() {
        this.timeout(10000);
        it('Test if the fail function works on not existing files.', function(done) {
            new Converter({
                files:          ['x.ppt'],
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       2,
                fileNameFormat: '_vers_%d'
            })
                .wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done();
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('add files', function() {
        this.timeout(10000);
        it('Test the addFiles function.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       2,
                fileNameFormat: '_vers_%d'
            });

            convertTest.addFiles(['test/OPW 733 Tienduizend redenen.ppt']);

            convertTest
                .wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done(data.failed[0].error);
                    } else {
                        done();
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('reset failed', function() {
        this.timeout(10000);
        it('Test the resetFailed function.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       2,
                fileNameFormat: '_vers_%d'
            });

            convertTest.failed = [{
                file: 'test/OPW 733 Tienduizend redenen.ppt'
            }];
            convertTest.resetFailed();

            convertTest
                .wait()
                .then(function(data) {
                    if(data.success.length > 0) {
                        done();
                    } else if(data.failed.length > 0) {
                        done(data.failed[0].error);
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('fail', function() {
        this.timeout(10000);
        it('Test if the fail function works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            convertTest.addFiles(['test/OPW 733 Tienduizend redenen.ppt']);

            convertTest
                .wait()
                .then(function(data) {
                    convertTest.fail('test');
                    if(data.failed.length > 0) {
                        done();
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('convert to png', function() {
        this.timeout(10000);
        it('Check if the convert to png works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            convertTest.addFiles(['test/OPW 733 Tienduizend redenen.ppt']);

            convertTest
                .wait()
                .then(function(data) {
                    file = convertTest.convertedToPdf(1, [733], false, 'test');

                    fs.readFile(file, function(error, data) {
                        if (error) {
                            done(error);
                        } else {
                            done();
                        }
                    });
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('process page', function() {
        this.timeout(10000);
        it('Check if the process page to png works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            convertTest.processPage('test/OPW 733 Tienduizend redenen.ppt', true, null);

            convertTest.wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done();
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('convert', function() {
        this.timeout(10000);
        it('Check if the convert fail works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  true,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            if(convertTest.convert()) {
                done('error');
            } else {
                done();
            }
        });
    });
});
<commit_msg>Test file fixes<commit_after>const assert = require('assert');
const Converter = require('../js/convert.js');
const fs = require('fs');

describe('ppt-png', function() {
    describe('normal', function() {
        this.timeout(10000);
        it('Test if the ppt file can convert to a png.', function(done) {
            new Converter({
                files:          ['test/OPW 733 Tienduizend redenen.ppt'],
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  true,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d',
                callback:       function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done(data.failed[0].error);
                    } else {
                        done();
                    }
                }
            }).run();
        });
    });

    describe('promise', function() {
        this.timeout(10000);
        it('Test with the promise.', function(done) {
            new Converter({
                files:  ['test/OPW 733 Tienduizend redenen.ppt'],
                output: 'output/test/'
            })
                .wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done(data.failed[0].error);
                    } else {
                        done();
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('failed', function() {
        this.timeout(10000);
        it('Test if the fail function works on not existing files.', function(done) {
            new Converter({
                files:          ['x.ppt'],
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       2,
                fileNameFormat: '_vers_%d'
            })
                .wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done();
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('add files', function() {
        this.timeout(10000);
        it('Test the addFiles function.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       2,
                fileNameFormat: '_vers_%d'
            });

            convertTest.addFiles(['test/OPW 733 Tienduizend redenen.ppt']);

            convertTest
                .wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done(data.failed[0].error);
                    } else {
                        done();
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('reset failed', function() {
        this.timeout(10000);
        it('Test the resetFailed function.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       2,
                fileNameFormat: '_vers_%d'
            });

            convertTest.failed = [{
                file: 'test/OPW 733 Tienduizend redenen.ppt'
            }];
            convertTest.resetFailed();

            convertTest
                .wait()
                .then(function(data) {
                    if(data.success.length > 0) {
                        done();
                    } else if(data.failed.length > 0) {
                        done(data.failed[0].error);
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('fail', function() {
        this.timeout(10000);
        it('Test if the fail function works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            convertTest.addFiles(['test/OPW 733 Tienduizend redenen.ppt']);

            convertTest
                .wait()
                .then(function(data) {
                    convertTest.fail('test');
                    if(data.failed.length > 0) {
                        done();
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('convert to png', function() {
        this.timeout(10000);
        it('Check if the convert to png works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            convertTest.addFiles(['test/OPW 733 Tienduizend redenen.ppt']);

            convertTest
                .wait()
                .then(function(data) {
                    file = convertTest.convertedToPdf(1, [733], false, 'test');

                    fs.readFile(file, function(error, data) {
                        if (error) {
                            done(error);
                        } else {
                            done();
                        }
                    });
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('process page', function() {
        this.timeout(10000);
        it('Check if the process page to png works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  false,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            convertTest.processPage('test/OPW 733 Tienduizend redenen.ppt', true, null);

            convertTest.wait()
                .then(function(data) {
                    if(data.failed.length > 0 || data.success.length < 1) {
                        done();
                    } else {
                        done('error');
                    }
                })
                .catch(function(error) {
                    done(error);
                });
        });
    });

    describe('convert', function() {
        this.timeout(10000);
        it('Check if the convert fail works.', function(done) {
            var convertTest = new Converter({
                output:         'output/test/',
                invert:         true,
                greyscale:      true,
                deletePdfFile:  true,
                outputType:     'png',
                logLevel:       3,
                fileNameFormat: '_vers_%d'
            });

            if(convertTest.convert()) {
                done('error');
            } else {
                done();
            }
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var advpng = require('../');
var isPng = require('is-png');
var path = require('path');
var read = require('vinyl-file').read;
var test = require('ava');

test('optimize a PNG', function (t) {
	t.plan(3);

	read(path.join(__dirname, 'fixtures/test.png'), function (err, file) {
		t.assert(!err);

		var stream = advpng();
		var size = file.contents.length;

		stream.on('data', function (data) {
			t.assert(data.contents.length < size);
			t.assert(isPng(data.contents));
		});

		stream.end(file);
	});
});

test('optimize a PNG using ctor', function (t) {
	t.plan(3);

	var Advpng = advpng.ctor();

	read(path.join(__dirname, 'fixtures/test.png'), function (err, file) {
		t.assert(!err);

		var stream = new Advpng();
		var size = file.contents.length;

		stream.on('data', function (data) {
			t.assert(data.contents.length < size);
			t.assert(isPng(data.contents));
		});

		stream.end(file);
	});
});
<commit_msg>Show errors in tests<commit_after>'use strict';

var advpng = require('../');
var isPng = require('is-png');
var path = require('path');
var read = require('vinyl-file').read;
var test = require('ava');

test('optimize a PNG', function (t) {
	t.plan(3);

	read(path.join(__dirname, 'fixtures/test.png'), function (err, file) {
		t.assert(!err, err);

		var stream = advpng();
		var size = file.contents.length;

		stream.on('data', function (data) {
			t.assert(data.contents.length < size);
			t.assert(isPng(data.contents));
		});

		stream.end(file);
	});
});

test('optimize a PNG using ctor', function (t) {
	t.plan(3);

	var Advpng = advpng.ctor();

	read(path.join(__dirname, 'fixtures/test.png'), function (err, file) {
		t.assert(!err, err);

		var stream = new Advpng();
		var size = file.contents.length;

		stream.on('data', function (data) {
			t.assert(data.contents.length < size);
			t.assert(isPng(data.contents));
		});

		stream.end(file);
	});
});
<|endoftext|>


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

describe('pickle version 0', function() {
    it('should decode integers', function() {
        assert.strictEqual(jpickle.loads('I1\n.'), 1);
        assert.strictEqual(jpickle.loads('I12\n.'), 12);
    });

    it('should decode booleans', function() {
        assert.strictEqual(jpickle.loads('I00\n.'), false);
        assert.strictEqual(jpickle.loads('I01\n.'), true);
    });

    it('should decode floats', function() {
        assert.strictEqual(jpickle.loads('F3.14159\n.'), 3.14159);
    });

    it('should decode strings', function() {
        assert.strictEqual(jpickle.loads("S'foo'\np0\n."), 'foo');
        assert.strictEqual(jpickle.loads("S\"foo\"\np0\n."), 'foo');
    });

    it('should decode unicode', function() {
        assert.strictEqual(jpickle.loads('VTest\xe9\np0\n.'), 'Testé');
    });

    it('should decode tuples', function() {
        assert.deepEqual(jpickle.loads("(t."), []);
        assert.deepEqual(jpickle.loads("(S'foo'\np0\ntp1\n."), ['foo']);
        assert.deepEqual(jpickle.loads("(S'foo'\np0\nS'bar'\np1\ntp2\n."), ['foo', 'bar']);
        assert.deepEqual(jpickle.loads("(S'foo'\np0\nS'bar'\np1\nS'wiz'\np2\ntp3\n."), ['foo', 'bar', 'wiz']);
    });

    it('should decode lists', function() {
        assert.deepEqual(jpickle.loads('(lp0\n.'), []);
        assert.deepEqual(jpickle.loads('(lp0\nI1\na.'), [1]);
        assert.deepEqual(jpickle.loads('(lp1\nI1\naI2\naI3\na.'), [1, 2, 3]);
    });

    it('should decode dicts', function() {
        assert.deepEqual(jpickle.loads('(dp0\n.'), {});
        assert.deepEqual(jpickle.loads("(dp0\nS'foo'\np1\nS'bar'\np2\ns."), {foo: 'bar'});
    });
});

describe('pickle version 1', function() {
    it('should decode BININT1', function() {
        assert.strictEqual(jpickle.loads('K\x01.'), 1);
    });

    it('should decode BININT2', function() {
        assert.strictEqual(jpickle.loads('M\x00\x01.'), 256);
    });

    it('should decode BININT', function() {
        assert.strictEqual(jpickle.loads('J\xff\xff\xff\xff.'), -1);
        assert.strictEqual(jpickle.loads('J\x00\x00\x01\x00.'), 65536);
    });

    it('should decode BINFLOAT', function() {
        assert.strictEqual(jpickle.loads('G@\t!\xf9\xf0\x1b\x86n.'), 3.14159);
    });

    it('should decode BINSTRING', function() {
        assert.strictEqual(jpickle.loads('T\x00\x01\x00\x00xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxq\x00.'), 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
    });

    it('should decode SHORT_BINSTRING', function() {
        assert.strictEqual(jpickle.loads('U\x03fooq\x00.'), 'foo');
    });

    it('should decode BINUNICODE', function() {
        assert.strictEqual(jpickle.loads('X\x06\x00\x00\x00Test\xc3\xa9q\x00.'), 'Testé');
    });

    it('should decode tuples', function() {
        assert.deepEqual(jpickle.loads(').'), []);
        assert.deepEqual(jpickle.loads('(U\x03fooq\x00tq\x01.'), ['foo']);
        assert.deepEqual(jpickle.loads('(U\x03fooq\x00U\x03barq\x01tq\x02.'), ['foo', 'bar']);
        assert.deepEqual(jpickle.loads('(U\x03fooq\x00U\x03barq\x01U\x03wizq\x02tq\x03.'), ['foo', 'bar', 'wiz']);
    });

    it('should decode EMPTY_LIST', function() {
        assert.deepEqual(jpickle.loads(']q\x00.'), []);
    });

    it('should decode EMPTY_LIST, BINPUT .. APPEND', function() {
        assert.deepEqual(jpickle.loads(']q\x00K\x01a.'), [1]);
    });

    it('should decode EMPTY_LIST, BINPUT, MARK .. APPENDS', function() {
        assert.deepEqual(jpickle.loads(']q\x00(K\x01K\x02K\x03e.'), [1, 2, 3]);
    });

    it('should decode EMPTY_DICT', function() {
        assert.deepEqual(jpickle.loads('}q\x00.'), {});
    });

    it('should decode EMPTY_DICT, BINPUT, MARK .. SETITEM', function() {
        assert.deepEqual(jpickle.loads('}q\x00U\x03fooq\x01U\x03barq\x02s.'), {foo: 'bar'});
    });
});

describe('pickle version 2', function() {
    it('should decode tuples', function() {
        assert.deepEqual(jpickle.loads('\x80\x02).'), []);
        assert.deepEqual(jpickle.loads('\x80\x02U\x03fooq\x00\x85q\x01.'), ['foo']);
        assert.deepEqual(jpickle.loads('\x80\x02U\x03fooq\x00U\x03barq\x01\x86q\x02.'), ['foo', 'bar']);
        assert.deepEqual(jpickle.loads('\x80\x02U\x03fooq\x00U\x03barq\x01U\x03wizq\x02\x87q\x03.'), ['foo', 'bar', 'wiz']);
        assert.deepEqual(jpickle.loads('\x80\x02(U\x03fooq\x00U\x03barq\x01U\x03wizq\x02U\x04bangq\x03tq\x04.'), ['foo', 'bar', 'wiz', 'bang']);
    });
});
<commit_msg>improve test coverage of dicts<commit_after>var assert = require('assert')
  , jpickle = require('../lib/jpickle');

describe('pickle version 0', function() {
    it('should decode integers', function() {
        assert.strictEqual(jpickle.loads('I1\n.'), 1);
        assert.strictEqual(jpickle.loads('I12\n.'), 12);
    });

    it('should decode booleans', function() {
        assert.strictEqual(jpickle.loads('I00\n.'), false);
        assert.strictEqual(jpickle.loads('I01\n.'), true);
    });

    it('should decode floats', function() {
        assert.strictEqual(jpickle.loads('F3.14159\n.'), 3.14159);
    });

    it('should decode strings', function() {
        assert.strictEqual(jpickle.loads("S'foo'\np0\n."), 'foo');
        assert.strictEqual(jpickle.loads("S\"foo\"\np0\n."), 'foo');
    });

    it('should decode unicode', function() {
        assert.strictEqual(jpickle.loads('VTest\xe9\np0\n.'), 'Testé');
    });

    it('should decode tuples', function() {
        assert.deepEqual(jpickle.loads("(t."), []);
        assert.deepEqual(jpickle.loads("(S'foo'\np0\ntp1\n."), ['foo']);
        assert.deepEqual(jpickle.loads("(S'foo'\np0\nS'bar'\np1\ntp2\n."), ['foo', 'bar']);
        assert.deepEqual(jpickle.loads("(S'foo'\np0\nS'bar'\np1\nS'wiz'\np2\ntp3\n."), ['foo', 'bar', 'wiz']);
    });

    it('should decode lists', function() {
        assert.deepEqual(jpickle.loads('(lp0\n.'), []);
        assert.deepEqual(jpickle.loads('(lp0\nI1\na.'), [1]);
        assert.deepEqual(jpickle.loads('(lp1\nI1\naI2\naI3\na.'), [1, 2, 3]);
    });

    it('should decode dicts', function() {
        assert.deepEqual(jpickle.loads('(dp0\n.'), {});
        assert.deepEqual(jpickle.loads("(dp0\nS'foo'\np1\nS'bar'\np2\ns."), {foo: 'bar'});
        assert.deepEqual(jpickle.loads("(dp0\nS'foo'\np1\nS'bar'\np2\nsS'wiz'\np3\nS'bang'\np4\ns."), {foo: 'bar', wiz: 'bang'});
    });
});

describe('pickle version 1', function() {
    it('should decode BININT1', function() {
        assert.strictEqual(jpickle.loads('K\x01.'), 1);
    });

    it('should decode BININT2', function() {
        assert.strictEqual(jpickle.loads('M\x00\x01.'), 256);
    });

    it('should decode BININT', function() {
        assert.strictEqual(jpickle.loads('J\xff\xff\xff\xff.'), -1);
        assert.strictEqual(jpickle.loads('J\x00\x00\x01\x00.'), 65536);
    });

    it('should decode BINFLOAT', function() {
        assert.strictEqual(jpickle.loads('G@\t!\xf9\xf0\x1b\x86n.'), 3.14159);
    });

    it('should decode BINSTRING', function() {
        assert.strictEqual(jpickle.loads('T\x00\x01\x00\x00xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxq\x00.'), 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
    });

    it('should decode SHORT_BINSTRING', function() {
        assert.strictEqual(jpickle.loads('U\x03fooq\x00.'), 'foo');
    });

    it('should decode BINUNICODE', function() {
        assert.strictEqual(jpickle.loads('X\x06\x00\x00\x00Test\xc3\xa9q\x00.'), 'Testé');
    });

    it('should decode tuples', function() {
        assert.deepEqual(jpickle.loads(').'), []);
        assert.deepEqual(jpickle.loads('(U\x03fooq\x00tq\x01.'), ['foo']);
        assert.deepEqual(jpickle.loads('(U\x03fooq\x00U\x03barq\x01tq\x02.'), ['foo', 'bar']);
        assert.deepEqual(jpickle.loads('(U\x03fooq\x00U\x03barq\x01U\x03wizq\x02tq\x03.'), ['foo', 'bar', 'wiz']);
    });

    it('should decode EMPTY_LIST', function() {
        assert.deepEqual(jpickle.loads(']q\x00.'), []);
    });

    it('should decode EMPTY_LIST, BINPUT .. APPEND', function() {
        assert.deepEqual(jpickle.loads(']q\x00K\x01a.'), [1]);
    });

    it('should decode EMPTY_LIST, BINPUT, MARK .. APPENDS', function() {
        assert.deepEqual(jpickle.loads(']q\x00(K\x01K\x02K\x03e.'), [1, 2, 3]);
    });

    it('should decode dicts', function() {
        assert.deepEqual(jpickle.loads('}q\x00.'), {});
        assert.deepEqual(jpickle.loads('}q\x00U\x03fooq\x01U\x03barq\x02s.'), {foo: 'bar'});
        assert.deepEqual(jpickle.loads('}q\x00(U\x03fooq\x01U\x03barq\x02U\x03wizq\x03U\x04bangq\x04u.'), {foo: 'bar', wiz: 'bang'});
    });
});

describe('pickle version 2', function() {
    it('should decode tuples', function() {
        assert.deepEqual(jpickle.loads('\x80\x02).'), []);
        assert.deepEqual(jpickle.loads('\x80\x02U\x03fooq\x00\x85q\x01.'), ['foo']);
        assert.deepEqual(jpickle.loads('\x80\x02U\x03fooq\x00U\x03barq\x01\x86q\x02.'), ['foo', 'bar']);
        assert.deepEqual(jpickle.loads('\x80\x02U\x03fooq\x00U\x03barq\x01U\x03wizq\x02\x87q\x03.'), ['foo', 'bar', 'wiz']);
        assert.deepEqual(jpickle.loads('\x80\x02(U\x03fooq\x00U\x03barq\x01U\x03wizq\x02U\x04bangq\x03tq\x04.'), ['foo', 'bar', 'wiz', 'bang']);
    });
});
<|endoftext|>


<commit_before>/**
 * @module src/UploadTokens
 *
 * Component that display SourceDocument
 * Accepts the following properties:
 *  - language: Ethnologue code of the language
 *  - content: Content of all the source documents stored
 *  - Access ID & Key: Returned as a response after authentication
*/

import React, { Component } from 'react';
import './App.css';
import Header from './Header';
import Footer from './Footer';
import { FormControl } from 'react-bootstrap';
import Language from './SourceLanguages';
import TargetLanguages from './TargetLanguages';
import $ from 'jquery';
import GlobalURL from './GlobalURL';

class UploadTokens extends Component {
  constructor(props) {
    super(props);
    this.state = {
      language:'tam',
      version: '',
      revision: '',
      targetlang: 'tam',
      tokenwords: {},
      uploaded:'Uploading',
      message: ''
    }

      // Upload file specific callback handlers
      this.uploadTokens = this.uploadTokens.bind(this);
      this.onSelect = this.onSelect.bind(this);
      this.file_xls = this.file_xls.bind(this);
  }

  onSelect(e) {
    this.setState({
      [e.target.name]: e.target.value });
  }

  file_xls(e, files){
    var _this = this;
    var file = files[0];
    var allRows = [];
    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function (evt) {
         allRows = evt.target.result.split(/\r?\n|\r/);

      }
      reader.onerror = function (evt) {
          allRows = []
      }
    }
    return allRows;
  }

  uploadTokens(e){
    var _this = this;
    let file = document.getElementById('file-input').files[0];
    var allRows = [];
    var tokenwords = {};
    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function (evt) {
        allRows = evt.target.result.split(/\r?\n|\r/);
        for(var singleRow = 0; singleRow < allRows.length; singleRow++) {
          let token = allRows[singleRow].split(",");
            tokenwords[token[0]] = token[1];
        }
        var data = {
            "language": _this.state.language, "version": _this.state.version, "revision": _this.state.revision, "targetlang": _this.state.targetlang, "tokenwords": tokenwords
          }

        let accessToken = JSON.parse(window.localStorage.getItem('access_token'))

        $.ajax({
          url: GlobalURL["hostURL"]+"/v1/uploadtokentranslation",
          contentType: "application/json; charset=utf-8",
          data : JSON.stringify(data),
          method : "POST",
          headers: {
                    "Authorization": "bearer " + JSON.stringify(accessToken['access_token']).slice(1,-1)},
          beforeSend: function () {
            $(".modal").show();
          },
          complete: function () {
            $(".modal").hide();
          },
          success: function (result) {
             result = JSON.parse(result)
            _this.setState({uploaded: result.success ? 'success' : ''})
            _this.setState({message: result.message})

          },
          error: function (error) {
           _this.setState({message: error.message, uploaded: 'failure'})
          }
        });
      }
      reader.onerror = function (evt) {
          allRows = []
      }
    }
    e.preventDefault();

  }

  render() {
    return(

          <form className="col-md-8 uploader" encType="multipart/form-data">

Upload Tokens

                {this.state.message}

                {this.state.message}

                <lable className="control-label">  Source Language  </lable>
                    <FormControl value={this.state.language} onChange={this.onSelect} name="language" componentClass="select" placeholder="select">
                      {Language.map((language, i) => <option  key={i} value={language.code}>{language.value}</option>)}
                    </FormControl>

                <lable className="control-lable">  Version  </lable>
                    <input value={this.state.version} onChange={this.onSelect} name="version" type="text"  placeholder="version" className="form-control" />

                <lable className="control-lable">  Revision  </lable>
                    <input value={this.state.revision} onChange={this.onSelect} name="revision" type="text" placeholder="revision" className="form-control"/>

                <lable className="control-label">  Target Language  </lable>
                    <FormControl value={this.state.targetlang} onChange={this.onSelect} name="targetlang" componentClass="select" placeholder="select">
                      {TargetLanguages.map((targetlang, i) => <option  key={i} value={targetlang.code}>{targetlang.value}</option>)}
                    </FormControl>

                  <input id="file-input" type="file" className="fileInput" multiple />

                  <button id="btnGet" type="button" className="btn btn-success sourcefooter" onClick={this.uploadTokens}>  Upload Tokens</button>

          </form>

      );
    }
}

export default UploadTokens;<commit_msg>Bookname added instead of Bookcode<commit_after>/**
 * @module src/UploadTokens
 *
 * Component that display SourceDocument
 * Accepts the following properties:
 *  - language: Ethnologue code of the language
 *  - content: Content of all the source documents stored
 *  - Access ID & Key: Returned as a response after authentication
*/

import React, { Component } from 'react';
import './App.css';
import Header from './Header';
import Footer from './Footer';
import { FormControl } from 'react-bootstrap';
import Language from './SourceLanguages';
import TargetLanguages from './TargetLanguages';
import $ from 'jquery';
import GlobalURL from './GlobalURL';

class UploadTokens extends Component {
  constructor(props) {
    super(props);
    this.state = {
      language:'Tamil',
      version: '',
      revision: '',
      targetlang: 'Malayalam',
      tokenwords: {},
      uploaded:'Uploading',
      message: ''
    }

      // Upload file specific callback handlers
      this.uploadTokens = this.uploadTokens.bind(this);
      this.onSelect = this.onSelect.bind(this);
      this.file_xls = this.file_xls.bind(this);
  }

  onSelect(e) {
    this.setState({
      [e.target.name]: e.target.value });
  }

  file_xls(e, files){
    var _this = this;
    var file = files[0];
    var allRows = [];
    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function (evt) {
         allRows = evt.target.result.split(/\r?\n|\r/);

      }
      reader.onerror = function (evt) {
          allRows = []
      }
    }
    return allRows;
  }

  uploadTokens(e){
    var _this = this;
    let file = document.getElementById('file-input').files[0];
    var allRows = [];
    var tokenwords = {};
    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function (evt) {
        allRows = evt.target.result.split(/\r?\n|\r/);
        for(var singleRow = 0; singleRow < allRows.length; singleRow++) {
          let token = allRows[singleRow].split(",");
            tokenwords[token[0]] = token[1];
        }
        var data = {
            "language": _this.state.language, "version": _this.state.version, "revision": _this.state.revision, "targetlang": _this.state.targetlang, "tokenwords": tokenwords
          }

        let accessToken = JSON.parse(window.localStorage.getItem('access_token'))

        $.ajax({
          url: GlobalURL["hostURL"]+"/v1/uploadtokentranslation",
          contentType: "application/json; charset=utf-8",
          data : JSON.stringify(data),
          method : "POST",
          headers: {
                    "Authorization": "bearer " + JSON.stringify(accessToken['access_token']).slice(1,-1)},
          beforeSend: function () {
            $(".modal").show();
          },
          complete: function () {
            $(".modal").hide();
          },
          success: function (result) {
             result = JSON.parse(result)
            _this.setState({uploaded: result.success ? 'success' : ''})
            _this.setState({message: result.message})

          },
          error: function (error) {
           _this.setState({message: error.message, uploaded: 'failure'})
          }
        });
      }
      reader.onerror = function (evt) {
          allRows = []
      }
    }
    e.preventDefault();

  }

  render() {
    return(

          <form className="col-md-8 uploader" encType="multipart/form-data">

Upload Tokens

                {this.state.message}

                {this.state.message}

                <lable className="control-label">  Source Language  </lable>
                    <FormControl value={this.state.language} onChange={this.onSelect} name="language" componentClass="select" placeholder="select">
                      {Language.map((language, i) => <option  key={i} value={language.value}>{language.value}</option>)}
                    </FormControl>

                <lable className="control-lable">  Version  </lable>
                    <input value={this.state.version} onChange={this.onSelect} name="version" type="text"  placeholder="version" className="form-control" />

                <lable className="control-lable">  Revision  </lable>
                    <input value={this.state.revision} onChange={this.onSelect} name="revision" type="text" placeholder="revision" className="form-control"/>

                <lable className="control-label">  Target Language  </lable>
                    <FormControl value={this.state.targetlang} onChange={this.onSelect} name="targetlang" componentClass="select" placeholder="select">
                      {TargetLanguages.map((targetlang, i) => <option  key={i} value={targetlang.value}>{targetlang.value}</option>)}
                    </FormControl>

                  <input id="file-input" type="file" className="fileInput" multiple />

                  <button id="btnGet" type="button" className="btn btn-success sourcefooter" onClick={this.uploadTokens}>  Upload Tokens</button>

          </form>

      );
    }
}

export default UploadTokens;<|endoftext|>


<commit_before>import h from 'hyperscript';
import c from '../utils/prefixClass';

import Controls from '../Controls';
import Page from '../Page';

import errorView from './error';
import orderPagesBooklet from './orderPagesBooklet';
import padPages from './padPages';
import { gridLayout, printLayout, flipLayout } from '../Layouts';

const MODE_FLIP = 'interactive';
const MODE_PREVIEW = 'grid';
const MODE_SHEET = 'print';
const MODE_OUTLINE = 'outline';

const ARRANGE_ONE = 'arrange_one';
const ARRANGE_SPREAD = 'arrange_two';
const ARRANGE_BOOKLET = 'arrange_booklet';
// const ARRANGE_SIGNATURE = 'arrange_signature';

const setOrientationCSS = (newValue) => {
  let sheet;
  const existing = document.querySelector('#binderyPrintSetup');
  if (existing) {
    sheet = existing;
  } else {
    sheet = document.createElement('style');
    sheet.id = 'binderyPrintSetup';
  }
  sheet.innerHTML = `@page { size: ${newValue}; }`;
  document.head.appendChild(sheet);
};

class Viewer {
  constructor({ bindery }) {
    this.book = null;

    this.zoomBox = h(c('.zoom-wrap'));
    this.element = h(c('.root'), this.zoomBox);

    this.doubleSided = true;
    this.printArrange = ARRANGE_SPREAD;
    this.isShowingCropMarks = true;
    this.isShowingBleedMarks = false;
    this.setOrientation('landscape');

    this.mode = MODE_PREVIEW;
    this.currentLeaf = 0;

    this.listenForPrint();
    this.listenForResize();

    this.setGrid = this.setGrid.bind(this);
    this.setOutline = this.setOutline.bind(this);
    this.setPrint = this.setPrint.bind(this);
    this.setFlip = this.setFlip.bind(this);

    this.controls = new Controls({ binder: bindery, viewer: this });

    this.element.appendChild(this.controls.element);
    document.body.appendChild(this.element);
  }

  // Automatically switch into print mode
  listenForPrint() {
    if (window.matchMedia) {
      const mediaQueryList = window.matchMedia('print');
      mediaQueryList.addListener((mql) => {
        if (mql.matches) {
          this.setPrint();
        } else {
          // after print
        }
      });
    }
  }

  listenForResize() {
    window.addEventListener('resize', () => {
      if (!this.throttleResize) {
        this.updateZoom();
        this.throttleResize = setTimeout(() => {
          this.throttleResize = null;
        }, 20);
      }
    });
  }

  get isShowingCropMarks() {
    return this.element.classList.contains(c('show-crop'));
  }

  set isShowingCropMarks(newVal) {
    if (newVal) {
      this.element.classList.add(c('show-crop'));
    } else {
      this.element.classList.remove(c('show-crop'));
    }
  }
  get isShowingBleedMarks() {
    return this.element.classList.contains(c('show-bleed-marks'));
  }

  set isShowingBleedMarks(newVal) {
    if (newVal) {
      this.element.classList.add(c('show-bleed-marks'));
    } else {
      this.element.classList.remove(c('show-bleed-marks'));
    }
  }

  setOrientation(newVal) {
    if (newVal === this.orientation) return;
    this.orientation = newVal;
    setOrientationCSS(newVal);
    if (this.mode === MODE_SHEET) {
      this.render();
    } else {
      this.setPrint();
    }
  }

  setPrintArrange(newVal) {
    if (newVal === this.printArrange) return;
    this.printArrange = newVal;
    if (this.mode === MODE_SHEET) {
      this.render();
    } else {
      this.setPrint();
    }
  }

  displayError(title, text) {
    if (!this.element.parentNode) {
      document.body.appendChild(this.element);
    }
    if (!this.error) {
      this.zoomBox.innerHTML = '';
      this.error = errorView(title, text);
      this.zoomBox.appendChild(this.error);
    }
  }
  clear() {
    this.book = null;
    this.zoomBox.innerHTML = '';
  }
  cancel() {
    // TODO this doesn't work if the target is an existing node
    if (this.element.parentNode) {
      this.element.parentNode.removeChild(this.element);
    }
  }
  toggleGuides() {
    this.element.classList.toggle(c('show-guides'));
  }
  toggleBleed() {
    this.element.classList.add(c('show-bleed'));
  }
  toggleDouble() {
    this.doubleSided = !this.doubleSided;
    this.render();
  }
  setMode(newMode) {
    switch (newMode) {
    case 'grid':
    case 'default':
      this.mode = MODE_PREVIEW;
      break;
    case 'interactive':
    case 'flip':
      this.mode = MODE_FLIP;
      break;
    case 'print':
    case 'sheet':
      this.mode = MODE_SHEET;
      break;
    case 'outline':
    case 'outlines':
      this.mode = MODE_OUTLINE;
      break;
    default:
      console.error(`Bindery: Unknown view mode "${newMode}"`);
      break;
    }
  }
  setGrid() {
    if (this.mode === MODE_PREVIEW) return;
    if (this.mode === MODE_OUTLINE) {
      this.mode = MODE_PREVIEW;
      this.updateGuides();
    } else {
      this.mode = MODE_PREVIEW;
      this.render();
    }
  }
  setOutline() {
    if (this.mode === MODE_OUTLINE) return;
    if (this.mode === MODE_PREVIEW) {
      this.mode = MODE_OUTLINE;
      this.updateGuides();
    } else {
      this.mode = MODE_OUTLINE;
      this.render();
    }
  }
  setPrint() {
    if (this.mode === MODE_SHEET) return;
    this.mode = MODE_SHEET;
    this.render();
  }
  setFlip() {
    this.mode = MODE_FLIP;
    this.render();
  }
  render() {
    if (!this.book) return;
    if (!this.element.parentNode) {
      document.body.appendChild(this.element);
    }

    this.flaps = [];
    document.body.classList.add(c('viewing'));
    this.element.setAttribute('bindery-view-mode', this.mode);

    const scrollPct = document.body.scrollTop / document.body.scrollHeight;

    if (this.mode === MODE_PREVIEW) {
      this.renderGrid();
    } else if (this.mode === MODE_OUTLINE) {
      this.renderGrid();
    } else if (this.mode === MODE_FLIP) {
      this.renderInteractive();
    } else if (this.mode === MODE_SHEET) {
      this.renderPrint();
    } else {
      this.renderGrid();
    }

    document.body.scrollTop = document.body.scrollHeight * scrollPct;
    this.updateZoom();
  }

  renderProgress() {
    const twoPageSpread = function (...arg) {
      return h(c('.spread-wrapper') + c('.spread-size'), ...arg);
    };

    this.book.pages.forEach((page, i) => {
      if (!this.zoomBox.contains(page.element)) {
        if (this.lastSpread && this.lastSpread.children.length < 2) {
          this.lastSpread.appendChild(page.element);
        } else {
          if (i === 0) {
            const spacer = new Page();
            spacer.element.style.visibility = 'hidden';
            this.lastSpread = twoPageSpread(spacer.element, page.element);
          } else {
            this.lastSpread = twoPageSpread(page.element);
          }

          this.zoomBox.appendChild(this.lastSpread);
        }
      }
    });
  }

  updateZoom() {
    if (this.zoomBox.firstElementChild) {
      const scrollPct = document.body.scrollTop / document.body.scrollHeight;
      const exportW = this.zoomBox.getBoundingClientRect().width;
      const contentW = this.zoomBox.firstElementChild.getBoundingClientRect().width;

      const scale = Math.min(1, exportW / (contentW + 20));

      this.zoomBox.style.transform = `scale(${scale})`;
      document.body.scrollTop = document.body.scrollHeight * scrollPct;
    }
  }

  updateGuides() {
    this.element.setAttribute('bindery-view-mode', this.mode);
    if (this.mode === MODE_OUTLINE) {
      this.element.classList.add(c('show-bleed'));
      this.element.classList.add(c('show-guides'));
    } else {
      this.element.classList.remove(c('show-bleed'));
      this.element.classList.remove(c('show-guides'));
    }
  }

  renderPrint() {
    this.element.classList.add(c('show-bleed'));
    this.element.classList.remove(c('show-guides'));

    this.zoomBox.innerHTML = '';

    const isTwoUp = this.printArrange !== ARRANGE_ONE;
    const isBooklet = this.printArrange === ARRANGE_BOOKLET;
    const orient = this.orientation;

    let pages = this.book.pages.slice();
    if (this.printArrange === ARRANGE_SPREAD) {
      pages = padPages(pages);
    } else if (this.printArrange === ARRANGE_BOOKLET) {
      pages = orderPagesBooklet(pages);
    }

    const fragment = printLayout(pages, isTwoUp, orient, isBooklet);
    this.zoomBox.appendChild(fragment);
  }

  renderGrid() {
    this.updateGuides();
    this.zoomBox.innerHTML = '';

    let pages = this.book.pages.slice();

    if (this.doubleSided) pages = padPages(pages);

    const fragment = gridLayout(pages, this.doubleSided);
    this.zoomBox.appendChild(fragment);
  }

  renderInteractive() {
    this.zoomBox.innerHTML = '';
    this.flaps = [];

    this.element.classList.remove(c('show-bleed'));
    this.element.classList.remove(c('show-guides'));
    this.zoomBox.classList.add(c('stage3d'));

    const pages = padPages(this.book.pages.slice());

    const fragment = flipLayout(pages, this.doubleSided);
    this.zoomBox.appendChild(fragment);
  }

}

export default Viewer;
<commit_msg>Fix restored scroll position<commit_after>import h from 'hyperscript';
import c from '../utils/prefixClass';

import Controls from '../Controls';
import Page from '../Page';

import errorView from './error';
import orderPagesBooklet from './orderPagesBooklet';
import padPages from './padPages';
import { gridLayout, printLayout, flipLayout } from '../Layouts';

const MODE_FLIP = 'interactive';
const MODE_PREVIEW = 'grid';
const MODE_SHEET = 'print';
const MODE_OUTLINE = 'outline';

const ARRANGE_ONE = 'arrange_one';
const ARRANGE_SPREAD = 'arrange_two';
const ARRANGE_BOOKLET = 'arrange_booklet';
// const ARRANGE_SIGNATURE = 'arrange_signature';

const setOrientationCSS = (newValue) => {
  let sheet;
  const existing = document.querySelector('#binderyPrintSetup');
  if (existing) {
    sheet = existing;
  } else {
    sheet = document.createElement('style');
    sheet.id = 'binderyPrintSetup';
  }
  sheet.innerHTML = `@page { size: ${newValue}; }`;
  document.head.appendChild(sheet);
};

class Viewer {
  constructor({ bindery }) {
    this.book = null;

    this.zoomBox = h(c('.zoom-wrap'));
    this.element = h(c('.root'), this.zoomBox);

    this.doubleSided = true;
    this.printArrange = ARRANGE_SPREAD;
    this.isShowingCropMarks = true;
    this.isShowingBleedMarks = false;
    this.setOrientation('landscape');

    this.mode = MODE_PREVIEW;
    this.currentLeaf = 0;

    this.listenForPrint();
    this.listenForResize();

    this.setGrid = this.setGrid.bind(this);
    this.setOutline = this.setOutline.bind(this);
    this.setPrint = this.setPrint.bind(this);
    this.setFlip = this.setFlip.bind(this);

    this.controls = new Controls({ binder: bindery, viewer: this });

    this.element.classList.add(c('in-progress'));

    this.element.appendChild(this.controls.element);
    document.body.appendChild(this.element);
  }

  // Automatically switch into print mode
  listenForPrint() {
    if (window.matchMedia) {
      const mediaQueryList = window.matchMedia('print');
      mediaQueryList.addListener((mql) => {
        if (mql.matches) {
          this.setPrint();
        } else {
          // after print
        }
      });
    }
  }

  listenForResize() {
    window.addEventListener('resize', () => {
      if (!this.throttleResize) {
        this.updateZoom();
        this.throttleResize = setTimeout(() => {
          this.throttleResize = null;
        }, 20);
      }
    });
  }

  get isShowingCropMarks() {
    return this.element.classList.contains(c('show-crop'));
  }

  set isShowingCropMarks(newVal) {
    if (newVal) {
      this.element.classList.add(c('show-crop'));
    } else {
      this.element.classList.remove(c('show-crop'));
    }
  }
  get isShowingBleedMarks() {
    return this.element.classList.contains(c('show-bleed-marks'));
  }

  set isShowingBleedMarks(newVal) {
    if (newVal) {
      this.element.classList.add(c('show-bleed-marks'));
    } else {
      this.element.classList.remove(c('show-bleed-marks'));
    }
  }

  setOrientation(newVal) {
    if (newVal === this.orientation) return;
    this.orientation = newVal;
    setOrientationCSS(newVal);
    if (this.mode === MODE_SHEET) {
      this.render();
    } else {
      this.setPrint();
    }
  }

  setPrintArrange(newVal) {
    if (newVal === this.printArrange) return;
    this.printArrange = newVal;
    if (this.mode === MODE_SHEET) {
      this.render();
    } else {
      this.setPrint();
    }
  }

  displayError(title, text) {
    if (!this.element.parentNode) {
      document.body.appendChild(this.element);
    }
    if (!this.error) {
      this.zoomBox.innerHTML = '';
      this.error = errorView(title, text);
      this.zoomBox.appendChild(this.error);
    }
  }
  clear() {
    this.book = null;
    this.zoomBox.innerHTML = '';
  }
  cancel() {
    // TODO this doesn't work if the target is an existing node
    if (this.element.parentNode) {
      this.element.parentNode.removeChild(this.element);
    }
  }
  toggleGuides() {
    this.element.classList.toggle(c('show-guides'));
  }
  toggleBleed() {
    this.element.classList.add(c('show-bleed'));
  }
  toggleDouble() {
    this.doubleSided = !this.doubleSided;
    this.render();
  }
  setMode(newMode) {
    switch (newMode) {
    case 'grid':
    case 'default':
      this.mode = MODE_PREVIEW;
      break;
    case 'interactive':
    case 'flip':
      this.mode = MODE_FLIP;
      break;
    case 'print':
    case 'sheet':
      this.mode = MODE_SHEET;
      break;
    case 'outline':
    case 'outlines':
      this.mode = MODE_OUTLINE;
      break;
    default:
      console.error(`Bindery: Unknown view mode "${newMode}"`);
      break;
    }
  }
  setGrid() {
    if (this.mode === MODE_PREVIEW) return;
    if (this.mode === MODE_OUTLINE) {
      this.mode = MODE_PREVIEW;
      this.updateGuides();
    } else {
      this.mode = MODE_PREVIEW;
      this.render();
    }
  }
  setOutline() {
    if (this.mode === MODE_OUTLINE) return;
    if (this.mode === MODE_PREVIEW) {
      this.mode = MODE_OUTLINE;
      this.updateGuides();
    } else {
      this.mode = MODE_OUTLINE;
      this.render();
    }
  }
  setPrint() {
    if (this.mode === MODE_SHEET) return;
    this.mode = MODE_SHEET;
    this.render();
  }
  setFlip() {
    this.mode = MODE_FLIP;
    this.render();
  }
  render() {
    if (!this.book) return;
    const { body } = document;

    if (!this.element.parentNode) {
      body.appendChild(this.element);
    }

    this.flaps = [];
    body.classList.add(c('viewing'));
    this.element.setAttribute('bindery-view-mode', this.mode);

    const scrollMax = body.scrollHeight - body.offsetHeight;
    const scrollPct = body.scrollTop / scrollMax;

    if (this.mode === MODE_PREVIEW) {
      this.renderGrid();
    } else if (this.mode === MODE_OUTLINE) {
      this.renderGrid();
    } else if (this.mode === MODE_FLIP) {
      this.renderInteractive();
    } else if (this.mode === MODE_SHEET) {
      this.renderPrint();
    } else {
      this.renderGrid();
    }

    body.scrollTop = scrollMax * scrollPct;
    this.updateZoom();
  }

  renderProgress() {
    const twoPageSpread = function (...arg) {
      return h(c('.spread-wrapper') + c('.spread-size'), ...arg);
    };

    this.book.pages.forEach((page, i) => {
      if (!this.zoomBox.contains(page.element)) {
        if (this.lastSpread && this.lastSpread.children.length < 2) {
          this.lastSpread.appendChild(page.element);
        } else {
          if (i === 0) {
            const spacer = new Page();
            spacer.element.style.visibility = 'hidden';
            this.lastSpread = twoPageSpread(spacer.element, page.element);
          } else {
            this.lastSpread = twoPageSpread(page.element);
          }

          this.zoomBox.appendChild(this.lastSpread);
        }
      }
    });
  }

  updateZoom() {
    if (this.zoomBox.firstElementChild) {
      const scrollPct = document.body.scrollTop / document.body.scrollHeight;
      const exportW = this.zoomBox.getBoundingClientRect().width;
      const contentW = this.zoomBox.firstElementChild.getBoundingClientRect().width;

      const scale = Math.min(1, exportW / (contentW + 20));

      this.zoomBox.style.transform = `scale(${scale})`;
      document.body.scrollTop = document.body.scrollHeight * scrollPct;
    }
  }

  updateGuides() {
    this.element.setAttribute('bindery-view-mode', this.mode);
    if (this.mode === MODE_OUTLINE) {
      this.element.classList.add(c('show-bleed'));
      this.element.classList.add(c('show-guides'));
    } else {
      this.element.classList.remove(c('show-bleed'));
      this.element.classList.remove(c('show-guides'));
    }
  }

  renderPrint() {
    this.element.classList.add(c('show-bleed'));
    this.element.classList.remove(c('show-guides'));

    this.zoomBox.innerHTML = '';

    const isTwoUp = this.printArrange !== ARRANGE_ONE;
    const isBooklet = this.printArrange === ARRANGE_BOOKLET;
    const orient = this.orientation;

    let pages = this.book.pages.slice();
    if (this.printArrange === ARRANGE_SPREAD) {
      pages = padPages(pages);
    } else if (this.printArrange === ARRANGE_BOOKLET) {
      pages = orderPagesBooklet(pages);
    }

    const fragment = printLayout(pages, isTwoUp, orient, isBooklet);
    this.zoomBox.appendChild(fragment);
  }

  renderGrid() {
    this.updateGuides();
    this.zoomBox.innerHTML = '';

    let pages = this.book.pages.slice();

    if (this.doubleSided) pages = padPages(pages);

    const fragment = gridLayout(pages, this.doubleSided);
    this.zoomBox.appendChild(fragment);
  }

  renderInteractive() {
    this.zoomBox.innerHTML = '';
    this.flaps = [];

    this.element.classList.remove(c('show-bleed'));
    this.element.classList.remove(c('show-guides'));
    this.zoomBox.classList.add(c('stage3d'));

    const pages = padPages(this.book.pages.slice());

    const fragment = flipLayout(pages, this.doubleSided);
    this.zoomBox.appendChild(fragment);
  }

}

export default Viewer;
<|endoftext|>