<commit_before>/*global define*/
define([
	'jQuery-2.1.4.min',
	'underscore_1.3.3',
	'backbone_0.9.2',
  'text!../../../js/app/templates/imageLibrary.html',
  'logs'
], function ($, _, Backbone, ImageLibraryTemplate, Logs) {
	'use strict';

	var ImageLibraryView = Backbone.View.extend({

		tagName:  'div',

    el: '#imageLibraryView',

		template: _.template(ImageLibraryTemplate),

		// The DOM events specific to an item.
		events: {
      'hidden.bs.modal #successWaitingModal': 'refreshView'
		},

		initialize: function () {
			//debugger;

		},

    render: function () {

      //Render the template for this view in the browser.
      this.$el.html(this.template);

      //Populate the View with images from the gallery.
      this.openGallery();

			return this;
		},

    //This function called by render() to generate the image gallery.
    openGallery: function() {
      //debugger;

      try {
          //debugger

          //Load the image data from the server if it hasn't been loaded yet.
          if( global.imageUploadCollection.length == 0) {
            log.push('Fetching JSON data for image library.');

            //Call server to retrieve JSON Gallery data.
            global.imageUploadCollection.fetch();

          } else {
            log.push('Image library data fetched. Populating images into ImageLibraryView');

            var defaultImgRow = this.$el.find('.imgrow').first();   //Save the default imgrow to an object as this will get copied and manipulated.
            var imgRows = [];                           //Array to contain the image rows.
            var currentImage = [];                      //Array used to work with the current image.

            var originalIndex = []; //Tracks the location in the original imgDataRaw array.

            //Remove all .imgrow entires except the first, empty one.
            //If a category was previously selected, this section will be filled in with images.
            //The program needs to remove them first before populating with new images.
            $('.imgrow:not(:first)').remove();

            //Calculate the number of image rows needed.
            //var numRows = Math.ceil(global.imageUploadCollection.models.length/3);
            var numRows = Math.ceil(global.parentImageCollection.models.length/3);

            //This block builds up the HTML for the image rows.
            var k = 0; //Used to track the current image in imgDataRaw
            //Loop through each row of images (3 images per row)
            for( var i = 0; i < numRows; i++) {

                //Add a new blank row of images
                imgRows.push(defaultImgRow.clone());

                //Get the array of 3 images in the current row
                currentImage = imgRows[i].find('img');

                //Loop through each image in the row.
                for( var j = 0; j < 3; j++) {

                    try {
                        var image = global.parentImageCollection.models[k].attributes;
                        //$(currentImage[j]).attr('src', 'http://'+global.serverIp+':'+global.serverPort+image.path.slice(6)+'/'+image.filename);
                        $(currentImage[j]).attr('src', image.url);
                        $(currentImage[j]).attr('onclick', 'global.imageLibraryView.editImage('+k+')');

                        if(image.width > 300)
                          $(currentImage[j]).attr('width', "300px");

                        if(image.height > 300)
                          $(currentImage[j]).attr('height', "300px");

                        k++;
                    } catch(err) {
                        //This loop intentially creates an error when it's time to exit the loop.
                        //To-Do: this could be coded better. Improper to exit by creating an error.
                        console.log('Breaking out of openGallery(). k = '+k);
                        break;
                    }
                }

            }

            //Add the populated imgRows to the DOM.
            defaultImgRow.parent().append(imgRows);
          }

      //
      } catch(err) {
          console.error('Catastrophic error in function openGallery().');
          console.error('Error Message: '+err.message);

          log.push('Catastrophic error in function openGallery().')
          log.push('Error Message: '+err.message);
          sendLog();
      }
    },

    //This function is called whenever an image in the gallery is clicked.
    //It's purpose is to load the image and image information into the 'Update Image' section.
    editImage: function(imageId) {
      //debugger;

      //Retrieve the image data from the collection.
      var selectedImageData = global.parentImageCollection.models[imageId];
      var selectedImage = selectedImageData.get('image');

      //Fill out the form fields.
      this.$el.find('#inputTitle').val(selectedImageData.get('imageName'));
      this.$el.find('#inputAltTitle').val(selectedImageData.get('alt1'));
      var URL = 'http://'+global.serverIp+':'+global.serverPort+selectedImage.path.slice(6)+'/'+selectedImage.filename;
      this.$el.find('#inputUrl').val(URL);
      this.$el.find('#selected-image').attr('src', URL); //Display the origional image by default.

      //Remove any li's in the ul. Create a blank slate in case previous images were viewed.
      this.$el.find('#thumbList').find('li').remove();

      this.$el.find('#thumbList').append(
        '
'+selectedImageData.attributes.imageName+' (original)
'
      );

      //Generate URLs for thumbnails and original
      //debugger;
      var childrenGUIDs = selectedImageData.get('children').split(',');
      if( childrenGUIDs[0] != "" ) {
        for( var i = 0; i < childrenGUIDs.length; i++ ) {

          //Retrieve the thumbnail images from the imageUploadCollection.
          selectedImageData = global.imageUploadCollection.get(childrenGUIDs[i]);
          selectedImage = selectedImageData.get('image');

          URL = 'http://'+global.serverIp+':'+global.serverPort+selectedImage.path.slice(6)+'/'+selectedImage.filename;

          //Add the thumbnail links to the ul list.
          this.$el.find('#thumbList').append(
            '
'+selectedImageData.attributes.imageName+'
'
          );

          //Save the URL to the 300px thumbnail. This is the image that should be displayed.
          if( i == 0 ) {
            var URL300px = URL;

            //Replace the original image with a 300px image if it's available.
            this.$el.find('#selected-image').attr('src', URL300px);
          }
        }
      }

      //Add the onclick function to the Update & Delete buttons.
      this.$el.find('#update-button').attr('onclick', 'global.imageLibraryView.updateImage('+imageId+')');
      this.$el.find('#delete-button').attr('onclick', 'global.imageLibraryView.deleteImage('+imageId+')');

      $('#edit-image').show();

      //Scroll to the top of the page.
      $('body').scrollTop(0);
    },

    //This function is called when the 'Update' button is clicked in the 'Update Image' section.
    //The purpose is to update the image data in the collection and then sync the collection with the server.
    updateImage: function(imageId) {
      //debugger;

      var selectedGUID = global.parentImageCollection.models[imageId].get('_id');
      var selectedModel = global.imageUploadCollection.get(selectedGUID);

      //Update the model in the collection.
      selectedModel.set('alt1', this.$el.find('#inputAltTitle').val());
      selectedModel.set('imageName', this.$el.find('#inputTitle').val());

      //Data is automatically synced with server upon change.

    },

    //This function is called when the 'Delete' button is clicked in the 'Update Image' section.
    //The purose is to delete the parent and thumbnail images from the database.
    //Unfortunately, the imags themselves get orphined in the /public/uploads/images directory. At some
    //point I need to write a server-side function that will handle the deletion on the server.
    deleteImage: function(imageId) {
      //debugger;

      var selectedGUID = global.parentImageCollection.models[imageId].get('_id');

      //Generate an array that contains the IDs of this images childen.
      var childrenGUIDs = global.imageUploadCollection.get(selectedGUID).get('children');
      childrenGUIDs = childrenGUIDs.split(',');

      var r = confirm("Are you sure you want to delete this image?");
      if (r == true) {

        //Show the waiting/success modal.
        this.$el.find('#successWaitingModal').modal('show');

        //Delete all children first
        for( var i=0; i < childrenGUIDs.length; i++ ) {
          $.getJSON('http://'+global.serverIp+':'+global.serverPort+'/api/imageupload/'+childrenGUIDs[i]+'/remove', function(data) {
            if( data.success ) {
              log.push('Child image id='+childrenGUIDs[i]+' successfully deleted from database.');
            } else {
              alert('The selected image was NOT deleted. There may be a problem communicating with the server.');
              console.error('Child image id='+childrenGUIDs[i]+' not deleted from datase!');
              log.push('Child image id='+childrenGUIDs[i]+' not deleted from datase!');
              sendLog();
              return;
            }
          });
        }

        //Delete the parent last
        $.getJSON('http://'+global.serverIp+':'+global.serverPort+'/api/imageupload/'+selectedGUID+'/remove', function(data) {
          //debugger;
          if( data.success ) {
            console.log('Image successfully deleted from database.');
            log.push('Image successfully deleted from database.');

            //global.leftMenuView.showImageLibrary2();
            //alert('Image successfully deleted.');

            //debugger;
            global.imageLibraryView.$el.find('#successWaitingModal').find('h2').css('color', 'green');
            global.imageLibraryView.$el.find('#successWaitingModal').find('h2').text('Success!');
            global.imageLibraryView.$el.find('#successWaitingModal').find('#waitingGif').hide();
            global.imageLibraryView.$el.find('#successWaitingModal').find('#successMsg').show();

            //Refesh the collection, which will also refresh the view after it's updated.
            global.imageUploadCollection.fetch();

          } else {
            alert('The selected image was NOT deleted. There may be a problem communicating with the server.')
            console.error('Image not deleted from datase!');
            log.push('Selected image was NOT deleted.');
          }
        });
      } else {
        //debugger;

      }

    },

    //This function is called after the imageUploadCollection has fetched its data from the server.
    //The purpose it to create an additional collection of 'parent' images -e.g. images with thumbnail children.
    getParentImageCollection: function() {
      //debugger;

      log.push('Retrieving parent images from imageUploadCollection and storing in parentImageCollection.')

      var ParentImageCollection = Backbone.Collection.extend({ //Collection Class
          model: global.imageUploadCollection.models[0],
      });
      global.parentImageCollection = new ParentImageCollection();

      //Cycle through all the models in imageUploadCollection and add those without a parent GUID into the ParentImageCollection.
      global.imageUploadCollection.forEach( function(model) {
        //debugger;
        if( (model.attributes.parent == "" ) || (model.attributes.parent == undefined) ) {
          global.parentImageCollection.add(model);
        }

      });
    },

    //This function gets called when the modal is closed.
    refreshView: function() {
      //debugger;

      //Hide the edit image area.
      $('#edit-image').hide();

      //Scroll to the top of the page.
      $('body').scrollTop(0);
    }

	});

  //debugger;
	return ImageLibraryView;
});
<commit_msg>updating image library view and add new view to deal with new file upload quirks of KeystoneJS v4<commit_after>/*global define*/
define([
	'jQuery-2.1.4.min',
	'underscore_1.3.3',
	'backbone_0.9.2',
  'text!../../../js/app/templates/imageLibrary.html',
  'logs'
], function ($, _, Backbone, ImageLibraryTemplate, Logs) {
	'use strict';

	var ImageLibraryView = Backbone.View.extend({

		tagName:  'div',

    el: '#imageLibraryView',

		template: _.template(ImageLibraryTemplate),

		// The DOM events specific to an item.
		events: {
      'hidden.bs.modal #successWaitingModal': 'refreshView'
		},

		initialize: function () {
			//debugger;

		},

    render: function () {

      //Render the template for this view in the browser.
      this.$el.html(this.template);

      //Populate the View with images from the gallery.
      this.openGallery();

			return this;
		},

    //This function called by render() to generate the image gallery.
    openGallery: function() {
      //debugger;

      try {
          //debugger

          //Load the image data from the server if it hasn't been loaded yet.
          if( global.imageUploadCollection.length == 0) {
            log.push('Fetching JSON data for image library.');

            //Call server to retrieve JSON Gallery data.
            global.imageUploadCollection.fetch();

          } else {
            log.push('Image library data fetched. Populating images into ImageLibraryView');

            var defaultImgRow = this.$el.find('.imgrow').first();   //Save the default imgrow to an object as this will get copied and manipulated.
            var imgRows = [];                           //Array to contain the image rows.
            var currentImage = [];                      //Array used to work with the current image.

            var originalIndex = []; //Tracks the location in the original imgDataRaw array.

            //Remove all .imgrow entires except the first, empty one.
            //If a category was previously selected, this section will be filled in with images.
            //The program needs to remove them first before populating with new images.
            $('.imgrow:not(:first)').remove();

            //Calculate the number of image rows needed.
            //var numRows = Math.ceil(global.imageUploadCollection.models.length/3);
            var numRows = Math.ceil(global.parentImageCollection.models.length/3);

            //This block builds up the HTML for the image rows.
            var k = 0; //Used to track the current image in imgDataRaw
            //Loop through each row of images (3 images per row)
            for( var i = 0; i < numRows; i++) {

                //Add a new blank row of images
                imgRows.push(defaultImgRow.clone());

                //Get the array of 3 images in the current row
                currentImage = imgRows[i].find('img');

                //Loop through each image in the row.
                for( var j = 0; j < 3; j++) {

                    try {
                        var image = global.parentImageCollection.models[k].attributes;
                        //$(currentImage[j]).attr('src', 'http://'+global.serverIp+':'+global.serverPort+image.path.slice(6)+'/'+image.filename);
                        $(currentImage[j]).attr('src', image.url);
                        $(currentImage[j]).attr('onclick', 'global.imageLibraryView.editImage('+k+')');

                        if(image.width > 300)
                          $(currentImage[j]).attr('width', "300");

                        if(image.height > 300)
                          $(currentImage[j]).attr('height', "300");

                        k++;
                    } catch(err) {
                        //This loop intentially creates an error when it's time to exit the loop.
                        //To-Do: this could be coded better. Improper to exit by creating an error.
                        console.log('Breaking out of openGallery(). k = '+k);
                        break;
                    }
                }

            }

            //Add the populated imgRows to the DOM.
            defaultImgRow.parent().append(imgRows);
          }

      //
      } catch(err) {
          console.error('Catastrophic error in function openGallery().');
          console.error('Error Message: '+err.message);

          log.push('Catastrophic error in function openGallery().')
          log.push('Error Message: '+err.message);
          sendLog();
      }
    },

    //This function is called whenever an image in the gallery is clicked.
    //It's purpose is to load the image and image information into the 'Update Image' section.
    editImage: function(imageId) {
      //debugger;

      //Retrieve the image data from the collection.
      var selectedImageData = global.parentImageCollection.models[imageId];
      var selectedImage = selectedImageData.get('image');

      //Fill out the form fields.
      this.$el.find('#inputTitle').val(selectedImageData.get('imageName'));
      this.$el.find('#inputAltTitle').val(selectedImageData.get('alt1'));
      var URL = 'http://'+global.serverIp+':'+global.serverPort+selectedImage.path.slice(6)+'/'+selectedImage.filename;
      this.$el.find('#inputUrl').val(URL);
      this.$el.find('#selected-image').attr('src', URL); //Display the origional image by default.

      //Remove any li's in the ul. Create a blank slate in case previous images were viewed.
      this.$el.find('#thumbList').find('li').remove();

      this.$el.find('#thumbList').append(
        '
'+selectedImageData.attributes.imageName+' (original)
'
      );

      //Generate URLs for thumbnails and original
      //debugger;
      var childrenGUIDs = selectedImageData.get('children').split(',');
      if( childrenGUIDs[0] != "" ) {
        for( var i = 0; i < childrenGUIDs.length; i++ ) {

          //Retrieve the thumbnail images from the imageUploadCollection.
          selectedImageData = global.imageUploadCollection.get(childrenGUIDs[i]);
          selectedImage = selectedImageData.get('image');

          URL = 'http://'+global.serverIp+':'+global.serverPort+selectedImage.path.slice(6)+'/'+selectedImage.filename;

          //Add the thumbnail links to the ul list.
          this.$el.find('#thumbList').append(
            '
'+selectedImageData.attributes.imageName+'
'
          );

          //Save the URL to the 300px thumbnail. This is the image that should be displayed.
          if( i == 0 ) {
            var URL300px = URL;

            //Replace the original image with a 300px image if it's available.
            this.$el.find('#selected-image').attr('src', URL300px);
          }
        }
      }

      //Add the onclick function to the Update & Delete buttons.
      this.$el.find('#update-button').attr('onclick', 'global.imageLibraryView.updateImage('+imageId+')');
      this.$el.find('#delete-button').attr('onclick', 'global.imageLibraryView.deleteImage('+imageId+')');

      $('#edit-image').show();

      //Scroll to the top of the page.
      $('body').scrollTop(0);
    },

    //This function is called when the 'Update' button is clicked in the 'Update Image' section.
    //The purpose is to update the image data in the collection and then sync the collection with the server.
    updateImage: function(imageId) {
      //debugger;

      var selectedGUID = global.parentImageCollection.models[imageId].get('_id');
      var selectedModel = global.imageUploadCollection.get(selectedGUID);

      //Update the model in the collection.
      selectedModel.set('alt1', this.$el.find('#inputAltTitle').val());
      selectedModel.set('imageName', this.$el.find('#inputTitle').val());

      //Data is automatically synced with server upon change.

    },

    //This function is called when the 'Delete' button is clicked in the 'Update Image' section.
    //The purose is to delete the parent and thumbnail images from the database.
    //Unfortunately, the imags themselves get orphined in the /public/uploads/images directory. At some
    //point I need to write a server-side function that will handle the deletion on the server.
    deleteImage: function(imageId) {
      //debugger;

      var selectedGUID = global.parentImageCollection.models[imageId].get('_id');

      //Generate an array that contains the IDs of this images childen.
      var childrenGUIDs = global.imageUploadCollection.get(selectedGUID).get('children');
      childrenGUIDs = childrenGUIDs.split(',');

      var r = confirm("Are you sure you want to delete this image?");
      if (r == true) {

        //Show the waiting/success modal.
        this.$el.find('#successWaitingModal').modal('show');

        //Delete all children first
        for( var i=0; i < childrenGUIDs.length; i++ ) {
          $.getJSON('http://'+global.serverIp+':'+global.serverPort+'/api/imageupload/'+childrenGUIDs[i]+'/remove', function(data) {
            if( data.success ) {
              log.push('Child image id='+childrenGUIDs[i]+' successfully deleted from database.');
            } else {
              alert('The selected image was NOT deleted. There may be a problem communicating with the server.');
              console.error('Child image id='+childrenGUIDs[i]+' not deleted from datase!');
              log.push('Child image id='+childrenGUIDs[i]+' not deleted from datase!');
              sendLog();
              return;
            }
          });
        }

        //Delete the parent last
        $.getJSON('http://'+global.serverIp+':'+global.serverPort+'/api/imageupload/'+selectedGUID+'/remove', function(data) {
          //debugger;
          if( data.success ) {
            console.log('Image successfully deleted from database.');
            log.push('Image successfully deleted from database.');

            //global.leftMenuView.showImageLibrary2();
            //alert('Image successfully deleted.');

            //debugger;
            global.imageLibraryView.$el.find('#successWaitingModal').find('h2').css('color', 'green');
            global.imageLibraryView.$el.find('#successWaitingModal').find('h2').text('Success!');
            global.imageLibraryView.$el.find('#successWaitingModal').find('#waitingGif').hide();
            global.imageLibraryView.$el.find('#successWaitingModal').find('#successMsg').show();

            //Refesh the collection, which will also refresh the view after it's updated.
            global.imageUploadCollection.fetch();

          } else {
            alert('The selected image was NOT deleted. There may be a problem communicating with the server.')
            console.error('Image not deleted from datase!');
            log.push('Selected image was NOT deleted.');
          }
        });
      } else {
        //debugger;

      }

    },

    //This function is called after the imageUploadCollection has fetched its data from the server.
    //The purpose it to create an additional collection of 'parent' images -e.g. images with thumbnail children.
    getParentImageCollection: function() {
      //debugger;

      log.push('Retrieving parent images from imageUploadCollection and storing in parentImageCollection.')

      var ParentImageCollection = Backbone.Collection.extend({ //Collection Class
          model: global.imageUploadCollection.models[0],
      });
      global.parentImageCollection = new ParentImageCollection();

      //Cycle through all the models in imageUploadCollection and add those without a parent GUID into the ParentImageCollection.
      global.imageUploadCollection.forEach( function(model) {
        //debugger;
        if( (model.attributes.parent == "" ) || (model.attributes.parent == undefined) ) {
          global.parentImageCollection.add(model);
        }

      });
    },

    //This function gets called when the modal is closed.
    refreshView: function() {
      //debugger;

      //Hide the edit image area.
      $('#edit-image').hide();

      //Scroll to the top of the page.
      $('body').scrollTop(0);
    }

	});

  //debugger;
	return ImageLibraryView;
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'

import Icon from '../Icon'
import IconTocco from '../IconTocco'
import StyledButton from './StyledButton'
import {design} from '../utilStyles'

/**
 * Use <Button> to trigger any actions. Choose look and ink according Material Design.
 */
const Button = props => (

)

Button.defaultProps = {
  iconPosition: design.position.PREPEND,
  look: design.look.FLAT,
  type: 'button'
}

Button.propTypes = {
  /**
   * A flat object of ARIA keys and values.
   */
  'aria': PropTypes.object,
  /**
   * May be passed from <ButtonGroup> to use as default for ink. Do not set manually.
   */
  'buttonGroupInk': design.inkPropTypes,
  /**
   * May be passed from <ButtonGroup> to morph buttons into a split button. Do not set manually.
   */
  'buttonGroupMelt': PropTypes.bool,
  /**
   * Instead of using label prop it is possible to pass a child
   * (e.g. <Button><FormattedMessage id="client.message"/></Button>). This is not useful for
   * styled tags since buttons design is controlled by props ink and look and immutable.
   */
  'children': PropTypes.node,
  /**
   * If true, button occupies less space. It should only used for crowded areas like tables and only if necessary.
   */
  'dense': PropTypes.bool,
  /**
   * If true, the button can not be triggered. Disable a button rather than hide it temporarily.
   */
  'disabled': PropTypes.bool,
  /**
   * Display an icon alongside button label. It is possible to omit label text if a icon is chosen.
   * See Icon component for more information.
   */
  'icon': PropTypes.string,
  /**
   * Prepend icon or append icon to label. Default value is 'prepend'.
   * Possible values: append|prepend
   */
  'iconPosition': PropTypes.oneOf([design.position.APPEND, design.position.PREPEND]),
  /**
   * Specify color palette. Default value is 'base'.
   */
  'ink': design.inkPropTypes,
  /**
   * Describe button action concise. Default is ''.
   */
  'label': PropTypes.node,
  /**
   * Look of button. Default value is 'flat'.
   */
  'look': PropTypes.oneOf([
    design.look.BALL,
    design.look.FLAT,
    design.look.RAISED
  ]),
  /**
   * Function that will be triggered on click event.
   */
  'onClick': PropTypes.func,
  /**
  * If true, an animated spinner icon is prepended.
  */
  'pending': PropTypes.bool,
  /**
   * Describe button action in detail to instruct users. It is shown as popover on mouse over.
   */
  'title': PropTypes.string,
  /**
   * HTML Button type. Default is 'button'.
   */
  'type': PropTypes.oneOf(['button', 'submit', 'reset']),
  /**
   * Tabindex indicates if the button can be focused and if/where it participates
   * in sequential keyboard navigation.
   */
  'tabIndex': PropTypes.number,
  /**
   * cypress selector string
   */
  'data-cy': PropTypes.string
}

export default Button
<commit_msg>style(tocco-ui): typo<commit_after>import PropTypes from 'prop-types'
import React from 'react'

import Icon from '../Icon'
import IconTocco from '../IconTocco'
import StyledButton from './StyledButton'
import {design} from '../utilStyles'

/**
 * Use <Button> to trigger any actions. Choose look and ink according Material Design.
 */
const Button = props => (

)

Button.defaultProps = {
  iconPosition: design.position.PREPEND,
  look: design.look.FLAT,
  type: 'button'
}

Button.propTypes = {
  /**
   * A flat object of ARIA keys and values.
   */
  'aria': PropTypes.object,
  /**
   * May be passed from <ButtonGroup> to use as default for ink. Do not set manually.
   */
  'buttonGroupInk': design.inkPropTypes,
  /**
   * May be passed from <ButtonGroup> to morph buttons into a split button. Do not set manually.
   */
  'buttonGroupMelt': PropTypes.bool,
  /**
   * Instead of using label prop it is possible to pass a child
   * (e.g. <Button><FormattedMessage id="client.message"/></Button>). This is not useful for
   * styled tags since buttons design is controlled by props ink and look and immutable.
   */
  'children': PropTypes.node,
  /**
   * If true, button occupies less space. It should only used for crowded areas like tables and only if necessary.
   */
  'dense': PropTypes.bool,
  /**
   * If true, the button can not be triggered. Disable a button rather than hide it temporarily.
   */
  'disabled': PropTypes.bool,
  /**
   * Display an icon alongside button label. It is possible to omit label text if an icon is chosen.
   * See Icon component for more information.
   */
  'icon': PropTypes.string,
  /**
   * Prepend icon or append icon to label. Default value is 'prepend'.
   * Possible values: append|prepend
   */
  'iconPosition': PropTypes.oneOf([design.position.APPEND, design.position.PREPEND]),
  /**
   * Specify color palette. Default value is 'base'.
   */
  'ink': design.inkPropTypes,
  /**
   * Describe button action concise. Default is ''.
   */
  'label': PropTypes.node,
  /**
   * Look of button. Default value is 'flat'.
   */
  'look': PropTypes.oneOf([
    design.look.BALL,
    design.look.FLAT,
    design.look.RAISED
  ]),
  /**
   * Function that will be triggered on click event.
   */
  'onClick': PropTypes.func,
  /**
  * If true, an animated spinner icon is prepended.
  */
  'pending': PropTypes.bool,
  /**
   * Describe button action in detail to instruct users. It is shown as popover on mouse over.
   */
  'title': PropTypes.string,
  /**
   * HTML Button type. Default is 'button'.
   */
  'type': PropTypes.oneOf(['button', 'submit', 'reset']),
  /**
   * Tabindex indicates if the button can be focused and if/where it participates
   * in sequential keyboard navigation.
   */
  'tabIndex': PropTypes.number,
  /**
   * cypress selector string
   */
  'data-cy': PropTypes.string
}

export default Button
<|endoftext|>


<commit_before><commit_msg>remove the local reference, sandbox<commit_after><|endoftext|>


<commit_before>const glob = require('glob');
const path = require('path');
const test = require('tape');
const load = require('load-json-file');
const {lineString, polygon} = require('@turf/helpers');
const booleanParallel = require('./');

test('turf-boolean-parallel', t => {
    // True Fixtures
    glob.sync(path.join(__dirname, 'test', 'true', '**', '*.geojson')).forEach(filepath => {
        const {name} = path.parse(filepath);
        const geojson = load.sync(filepath);
        const [line1, line2] = geojson.features;
        const result = booleanParallel(line1, line2);

        if (process.env.SHAPELY) shapely.contains(line1, line2).then(result => t.true(result, '[true] shapely - ' + name));
        t.true(result, '[true] ' + name);
    });
    // False Fixtures
    glob.sync(path.join(__dirname, 'test', 'false', '**', '*.geojson')).forEach(filepath => {
        const {name} = path.parse(filepath);
        const geojson = load.sync(filepath);
        const [line1, line2] = geojson.features;
        const result = booleanParallel(line1, line2);

        if (process.env.SHAPELY) shapely.contains(line1, line2).then(result => t.false(result, '[false] shapely - ' + name));
        t.false(result, '[false] ' + name);
    });
    t.end();
});

test('turf-boolean-parallel -- throws', t => {
    const line = lineString([[0, 0], [0, 1]]);
    const poly = polygon([[[0, 0], [0, 1], [1, 1], [0, 0]]]);

    t.throws(() => booleanParallel(null, line), /line1 is required/, 'missing line1');
    t.throws(() => booleanParallel(line, null), /line2 is required/, 'missing line2');
    t.throws(() => booleanParallel(poly, line), /line1 must be a LineString/, 'different types');
    t.throws(() => booleanParallel(line, poly), /line2 must be a LineString/, 'different types');
    t.throws(() => booleanParallel({}, line), /Invalid GeoJSON object for line1/, 'invalid types');
    t.throws(() => booleanParallel(line, {}), /Invalid GeoJSON object for line2/, 'invalid types');

    t.end();
});
<commit_msg>Remove shapely from tests<commit_after>const glob = require('glob');
const path = require('path');
const test = require('tape');
const load = require('load-json-file');
const {lineString, polygon} = require('@turf/helpers');
const booleanParallel = require('./');

test('turf-boolean-parallel', t => {
    // True Fixtures
    glob.sync(path.join(__dirname, 'test', 'true', '**', '*.geojson')).forEach(filepath => {
        const {name} = path.parse(filepath);
        const geojson = load.sync(filepath);
        const [line1, line2] = geojson.features;
        const result = booleanParallel(line1, line2);

        t.true(result, '[true] ' + name);
    });
    // False Fixtures
    glob.sync(path.join(__dirname, 'test', 'false', '**', '*.geojson')).forEach(filepath => {
        const {name} = path.parse(filepath);
        const geojson = load.sync(filepath);
        const [line1, line2] = geojson.features;
        const result = booleanParallel(line1, line2);

        t.false(result, '[false] ' + name);
    });
    t.end();
});

test('turf-boolean-parallel -- throws', t => {
    const line = lineString([[0, 0], [0, 1]]);
    const poly = polygon([[[0, 0], [0, 1], [1, 1], [0, 0]]]);

    t.throws(() => booleanParallel(null, line), /line1 is required/, 'missing line1');
    t.throws(() => booleanParallel(line, null), /line2 is required/, 'missing line2');
    t.throws(() => booleanParallel(poly, line), /line1 must be a LineString/, 'different types');
    t.throws(() => booleanParallel(line, poly), /line2 must be a LineString/, 'different types');
    t.throws(() => booleanParallel({}, line), /Invalid GeoJSON object for line1/, 'invalid types');
    t.throws(() => booleanParallel(line, {}), /Invalid GeoJSON object for line2/, 'invalid types');

    t.end();
});
<|endoftext|>


<commit_before>(function(root, factory){
    if (typeof define === 'function' && define.amd){
        define(['array-events', 'object-events', 'jquery', 'Handlebars', 'extended-emitter', 'dom-tool', 'hashmap'], factory);
    }else if(typeof exports === 'object'){
        var jsdom = require('jsdom');
        var JQ;
        var onready = [];
        jsdom.env(
            '',
            ["http://code.jquery.com/jquery.js"],
            function(errors, window){
                JQ = window.$;
                if(onready.length) onready.forEach(function(cb){
                    cb(JQ);
                })
            }
        );
        module.exports = factory(require('array-events'), require('object-events'), {ready:function(cb){
            if(!JQ) onready.push(cb);
            else JQ.ready(cb);
        }}, require('Handlebars'), require('extended-emitter'), require('dom-tool'), require('hashmap'));
    }else{
        root.LiveTemplates = factory(
            root.EventedArray, root.EventedObject, root.$, root.Handlebars,
            root.ExtendedEmitter, root.DOMTool, root.HashMap
        );
    }
}(this, function(EventedArray, EventedObject, $, Handlebars, Emitter, dTool, HashMap){
    var mode = 'evented';
    var corpse = false;
    $.ready(function(JQ){
        dTool.dom = JQ.parseHTML;
        dTool.fragment = JQ;
        dTool.attach = modelAttach;
    });
    console.log(Object.keys(dTool), Object.keys($));
    var engine;

    var root = {}; //models
    var listOptions = {}; //the options used in rendering a list, stored by list id

    //Modes, currently hardcoded, will eventually move to their own, loadable modules

    function getModelValue(model, field){
        switch(mode){
            case 'backbone' :

            case 'deep-backbone' :
            case 'evented' :
            case 'backbone-hybrid' :
            case 'deep-hybrid' :
                return model.get(field);
                break;
        }
    }

    function modelAttach(model, field, update){
        switch(mode){
            case 'backbone' :
            case 'deep-backbone' :
            case 'backbone-hybrid' :
            case 'deep-hybrid' :
                model.on('change:'+field, function(value){
                    update(value);
                });
                break;
            case 'evented' :
                model.on('change', field, function(value){
                    update(value);
                });
                break;
        }
    }

    function escapeRegExp(str){
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }

    function listAttach(list, id, root){
        var sentinel = Templates.opener+':ITEM:'+Templates.closer;
        var add = function(item){
            var position = list.indexOf(item);
            var newHTML = engine.block(item, engine.context(listOptions[id].data || {}), listOptions[id]);
            var dom = dTool.live({
                sentinel : new RegExp(escapeRegExp(Templates.opener)+'(.*)'+escapeRegExp(Templates.closer), 'g')
            }, root, function(updaters){
                Object.keys(updaters).forEach(function(id){
                    var updater = updaters[id];
                    var selector = updater.marker;
                    var parts = selector.split(':');
                    var model = Template.model(parts.shift());
                    var field = parts.shift();
                    modelAttach(model, field, updater.set);
                })
            });

        };

        var remove = function(item, previousPosition){
            tool.removeBlockAt(sentinel, root);
        };

        switch(mode){
            case 'backbone' :
            case 'deep-backbone' :
                list.on('add', add);
                list.on('remove', remove);
                break;
            case 'evented' :
            case 'backbone-hybrid' :
            case 'deep-hybrid' :
                list.on('add', add);
                list.on('remove', remove);
                //list.on('move', function(item, previousPosition){ });
                break;
        }
    }
    var map = new HashMap();
    var listOptions = {};
    var Templates = {};
    Templates.domSelector = $;
    //var modelStack = [];
    var listStack = [];
    var listNameStack = [];
    /*function currentModelContext(){
        return (modelStack[modelStack.length -1] && modelStack[modelStack.length -1]['__modelName']);
    }
    function currentListContext(){
        return (listStack[listStack.length -1] && listStack[listStack.length -1]['__modelName']);
    }*/
    function currentListName(){
        return (listNameStack[listNameStack.length -1]);
    }
    var liveReferences = {};
    //todo: view association for GC
    Templates.engine = function(eng){
        if(!eng) return engine;
        engine = eng;
        engine.macro('model', function(options){
            if(options.args && options.args[0] && !options.path) options.path = options.args[0];
            if(options.args && options.args[1] && !options.storeInto) options.storeInto = options.args[1];
            var id = dTool.uniqueID();
            var parts = options.path.split(':');
            var modelPath = parts[0];
            var fieldPath = parts[1];
            var model = modelPath?Templates.model(modelPath):this;
            if(!modelPath){
                var listName = currentListName();
                var list = Templates.model(listName);
                modelPath = listName+'.'+list.indexOf(model);
            }
            liveReferences[id] = {
                type : 'item',
                modelName : modelPath,
                fieldName : fieldPath,
                model : model
            };

            if(corpse){
                return engine.literal(getModelValue(model, fieldPath));
            }else{
                console.log('!!', modelPath, fieldPath);
                return engine.literal('');
            }
        });

        engine.macro({
            name : 'models',
            type : 'block'
        }, function(options){
            var id = dTool.uniqueID();
            listOptions[id] = options;
            if(options.args && options.args[0] && !options.selector) options.selector = options.args[0];
            var list = Templates.model(options.selector);
            if(!Array.isArray(list)) return '';
            var output = '';
            function makeItem(item, index, options){
                var data = {};
                if(options.data){
                    data = engine.context(options.data || {});
                    data.index = i;
                    data.item = item;
                }
                if(!corpse) output += '';
                return engine.block(list[i], data, options);
            }
            if(!corpse) output += '';
            listNameStack.push(options.selector);
            listStack.push(list);
            for(var i=0; i<list.length; i++){
                //modelStack.push(list[i]);
                output += makeItem(list[i], i, options);
                //modelStack.pop();
            }
            listStack.pop();
            listNameStack.pop();
            if(!corpse) output += '';
            liveReferences[id] = {
                type : 'list',
                list : list,
                listName : list,
                name : options.selector,
                makeNew : function(item){
                    return makeItem(item, list.length, options);
                },
                id : id
            };
            /*var root = function(){
                //todo: index blocks on create, so they don't have to be in the DOM
                return this.root || (this.root = findComment(document, Templates.opener+id+Templates.closer).parentNode);
            };
            list.on('add', function(item, index){
                item.namekey = options.selector+'.'+(list.length-1);
                var newHTML = engine.block(item, engine.context(options.data || {}), options);
                var dom = Templates.domSelector.parseHTML(newHTML);
                convertMarkersToLiveHTML(dom);
                var replaceableAttrs = scanAttributesFor('');
            }
        });

        engine.macro({
            name : 'models',
            type : 'block'
        }, function(options){
            var id = dTool.uniqueID();
            listOptions[id] = options;
            if(options.args && options.args[0] && !options.selector) options.selector = options.args[0];
            var list = Templates.model(options.selector);
            if(!Array.isArray(list)) return '';
            var output = '';
            function makeItem(item, index, options){
                var data = {};
                if(options.data){
                    data = engine.context(options.data || {});
                    data.index = i;
                    data.item = item;
                }
                if(!corpse) output += '';
                return engine.block(list[i], data, options);
            }
            if(!corpse) output += '';
            listNameStack.push(options.selector);
            listStack.push(list);
            for(var i=0; i<list.length; i++){
                //modelStack.push(list[i]);
                output += makeItem(list[i], i, options);
                //modelStack.pop();
            }
            listStack.pop();
            listNameStack.pop();
            if(!corpse) output += '';
            liveReferences[id] = {
                type : 'list',
                list : list,
                listName : list,
                name : options.selector,
                makeNew : function(item){
                    return makeItem(item, list.length, options);
                },
                id : id
            };
            /*var root = function(){
                //todo: index blocks on create, so they don't have to be in the DOM
                return this.root || (this.root = findComment(document, Templates.opener+id+Templates.closer).parentNode);
            };
            list.on('add', function(item, index){
                item.namekey = options.selector+'.'+(list.length-1);
                var newHTML = engine.block(item, engine.context(options.data || {}), options);
                var dom = Templates.domSelector.parseHTML(newHTML);
                convertMarkersToLiveHTML(dom);
                var replaceableAttrs = scanAttributesFor('


<commit_before>import React from 'react';
import { Link } from 'react-router';
import Button from 'react-toolbox/button';
import Logo from '../../logo';
import Navigation from '../../navigation';
import style from './style';

const GithubIcon = () => (
  <svg viewBox="0 0 284 277">
    <g><path d="M141.888675,0.0234927555 C63.5359948,0.0234927555 0,63.5477395 0,141.912168 C0,204.6023 40.6554239,257.788232 97.0321356,276.549924 C104.12328,277.86336 106.726656,273.471926 106.726656,269.724287 C106.726656,266.340838 106.595077,255.16371 106.533987,243.307542 C67.0604204,251.890693 58.7310279,226.56652 58.7310279,226.56652 C52.2766299,210.166193 42.9768456,205.805304 42.9768456,205.805304 C30.1032937,196.998939 43.9472374,197.17986 43.9472374,197.17986 C58.1953153,198.180797 65.6976425,211.801527 65.6976425,211.801527 C78.35268,233.493192 98.8906827,227.222064 106.987463,223.596605 C108.260955,214.426049 111.938106,208.166669 115.995895,204.623447 C84.4804813,201.035582 51.3508808,188.869264 51.3508808,134.501475 C51.3508808,119.01045 56.8936274,106.353063 65.9701981,96.4165325 C64.4969882,92.842765 59.6403297,78.411417 67.3447241,58.8673023 C67.3447241,58.8673023 79.2596322,55.0538738 106.374213,73.4114319 C117.692318,70.2676443 129.83044,68.6910512 141.888675,68.63701 C153.94691,68.6910512 166.09443,70.2676443 177.433682,73.4114319 C204.515368,55.0538738 216.413829,58.8673023 216.413829,58.8673023 C224.13702,78.411417 219.278012,92.842765 217.804802,96.4165325 C226.902519,106.353063 232.407672,119.01045 232.407672,134.501475 C232.407672,188.998493 199.214632,200.997988 167.619331,204.510665 C172.708602,208.913848 177.243363,217.54869 177.243363,230.786433 C177.243363,249.771339 177.078889,265.050898 177.078889,269.724287 C177.078889,273.500121 179.632923,277.92445 186.825101,276.531127 C243.171268,257.748288 283.775,204.581154 283.775,141.912168 C283.775,63.5477395 220.248404,0.0234927555 141.888675,0.0234927555" /></g>
  </svg>
);

const TwitterIcon = () => (
  <svg viewBox="0 0 274 223">
    <g><path d="M273.39,26.301 C263.331,30.762 252.521,33.777 241.175,35.133 C252.756,28.191 261.649,17.199 265.837,4.102 C255,10.529 242.996,15.197 230.22,17.713 C219.988,6.812 205.411,0 189.279,0 C158.302,0 133.188,25.113 133.188,56.088 C133.188,60.484 133.685,64.765 134.641,68.87 C88.025,66.531 46.696,44.201 19.032,10.267 C14.204,18.551 11.438,28.186 11.438,38.465 C11.438,57.924 21.341,75.092 36.391,85.15 C27.196,84.859 18.548,82.336 10.985,78.135 C10.981,78.369 10.981,78.604 10.981,78.84 C10.981,106.016 30.315,128.686 55.974,133.838 C51.267,135.12 46.312,135.805 41.196,135.805 C37.582,135.805 34.068,135.454 30.644,134.799 C37.781,157.083 58.495,173.299 83.039,173.752 C63.843,188.795 39.658,197.762 13.38,197.762 C8.853,197.762 4.388,197.497 0,196.979 C24.822,212.893 54.305,222.178 85.98,222.178 C189.148,222.178 245.564,136.711 245.564,62.592 C245.564,60.16 245.51,57.741 245.402,55.336 C256.36,47.428 265.87,37.549 273.39,26.301" /></g>
  </svg>
);

const Home = () => (

      <Logo className={style.logo} />

React Toolbox

Bootstrap your application with beautiful Material Design Components

      <Navigation className={style.navigation} />

        React Toolbox is a set of React components that implements Google Material Design specification.
        It's built on top of some the trendiest proposals like CSS Modules (written in SASS), Webpack and ES6.
        The library harmoniously integrates with your Webpack workflow and it's easily customizable and very flexible.

        Check our awesome documentation (which is built using React Toolbox) and try all the components with
        live examples. We've created a playground so you don't need to install anything to fall in love with
        our components, so fun!

      <Link to='/components'>
        <Button label='Try it now!' raised accent />
      </Link>

React Toolbox © 2016

      Crafted with ღ between Spain and Thailand

);

export default Home;
<commit_msg>personalized docs more<commit_after>import React from 'react';
import { Link } from 'react-router';
import Button from 'react-toolbox/button';
import Logo from '../../logo';
import Navigation from '../../navigation';
import style from './style';

const GithubIcon = () => (
  <svg viewBox="0 0 284 277">
    <g><path d="M141.888675,0.0234927555 C63.5359948,0.0234927555 0,63.5477395 0,141.912168 C0,204.6023 40.6554239,257.788232 97.0321356,276.549924 C104.12328,277.86336 106.726656,273.471926 106.726656,269.724287 C106.726656,266.340838 106.595077,255.16371 106.533987,243.307542 C67.0604204,251.890693 58.7310279,226.56652 58.7310279,226.56652 C52.2766299,210.166193 42.9768456,205.805304 42.9768456,205.805304 C30.1032937,196.998939 43.9472374,197.17986 43.9472374,197.17986 C58.1953153,198.180797 65.6976425,211.801527 65.6976425,211.801527 C78.35268,233.493192 98.8906827,227.222064 106.987463,223.596605 C108.260955,214.426049 111.938106,208.166669 115.995895,204.623447 C84.4804813,201.035582 51.3508808,188.869264 51.3508808,134.501475 C51.3508808,119.01045 56.8936274,106.353063 65.9701981,96.4165325 C64.4969882,92.842765 59.6403297,78.411417 67.3447241,58.8673023 C67.3447241,58.8673023 79.2596322,55.0538738 106.374213,73.4114319 C117.692318,70.2676443 129.83044,68.6910512 141.888675,68.63701 C153.94691,68.6910512 166.09443,70.2676443 177.433682,73.4114319 C204.515368,55.0538738 216.413829,58.8673023 216.413829,58.8673023 C224.13702,78.411417 219.278012,92.842765 217.804802,96.4165325 C226.902519,106.353063 232.407672,119.01045 232.407672,134.501475 C232.407672,188.998493 199.214632,200.997988 167.619331,204.510665 C172.708602,208.913848 177.243363,217.54869 177.243363,230.786433 C177.243363,249.771339 177.078889,265.050898 177.078889,269.724287 C177.078889,273.500121 179.632923,277.92445 186.825101,276.531127 C243.171268,257.748288 283.775,204.581154 283.775,141.912168 C283.775,63.5477395 220.248404,0.0234927555 141.888675,0.0234927555" /></g>
  </svg>
);

const TwitterIcon = () => (
  <svg viewBox="0 0 274 223">
    <g><path d="M273.39,26.301 C263.331,30.762 252.521,33.777 241.175,35.133 C252.756,28.191 261.649,17.199 265.837,4.102 C255,10.529 242.996,15.197 230.22,17.713 C219.988,6.812 205.411,0 189.279,0 C158.302,0 133.188,25.113 133.188,56.088 C133.188,60.484 133.685,64.765 134.641,68.87 C88.025,66.531 46.696,44.201 19.032,10.267 C14.204,18.551 11.438,28.186 11.438,38.465 C11.438,57.924 21.341,75.092 36.391,85.15 C27.196,84.859 18.548,82.336 10.985,78.135 C10.981,78.369 10.981,78.604 10.981,78.84 C10.981,106.016 30.315,128.686 55.974,133.838 C51.267,135.12 46.312,135.805 41.196,135.805 C37.582,135.805 34.068,135.454 30.644,134.799 C37.781,157.083 58.495,173.299 83.039,173.752 C63.843,188.795 39.658,197.762 13.38,197.762 C8.853,197.762 4.388,197.497 0,196.979 C24.822,212.893 54.305,222.178 85.98,222.178 C189.148,222.178 245.564,136.711 245.564,62.592 C245.564,60.16 245.51,57.741 245.402,55.336 C256.36,47.428 265.87,37.549 273.39,26.301" /></g>
  </svg>
);

const Home = () => (

      <Logo className={style.logo} />

V. Alexander's

React Components

Bootstrap your application with beautiful Material Design Components based on React Toolbox.

      <Navigation className={style.navigation} />

        React Toolbox is a set of React components that implements Google Material Design specification.
        It's built on top of some the trendiest proposals like CSS Modules (written in SASS), Webpack and ES6.
        The library harmoniously integrates with your Webpack workflow and it's easily customizable and very flexible.

        Check our awesome documentation (which is built using React Toolbox) and try all the components with
        live examples. We've created a playground so you don't need to install anything to fall in love with
        our components, so fun!

      <Link to='/components'>
        <Button label='Try it now!' raised accent />
      </Link>

React Toolbox © 2016

      Crafted with ღ between Spain and Thailand

);

export default Home;
<|endoftext|>


<commit_before>angular
  .module('mwl.calendar.docs') //you will need to declare your module with the dependencies ['mwl.calendar', 'ui.bootstrap', 'ngAnimate']
  .controller('KitchenSinkCtrl', function(moment, alert) {

    var vm = this;

    //These variables MUST be set as a minimum for the calendar to work
    vm.calendarView = 'month';
    vm.viewDate = new Date();
    vm.events = [];

    //ADD EVENTS HERE
    $(document).ready(function(){
      $.get("http://swumusic.com/json.html", function(data, status){
        var arr = JSON.parse(data);

        arr.map(function (X) {
          date = new Date (X["Store Date"])
          vm.events.push({title: 'WHATDDUP BITCHES', type: 'important', startsAt: date, endsAt: date, draggable: true, resizable: true});
        });
      });
    });

    //vm.events.push({title: 'WHATDDUP BITCHES', type: 'important', startsAt: moment().startOf('week').subtract(2, 'days').add(8, 'hours').toDate(), endsAt: moment().startOf('week').add(1, 'week').add(9, 'hours').toDate(), draggable: true, resizable: true});

    vm.isCellOpen = false;

    vm.eventClicked = function(event) {
      alert.show('Clicked', event);
    };

    vm.eventEdited = function(event) {
      alert.show('Edited', event);
    };

    vm.eventDeleted = function(event) {
      alert.show('Deleted', event);
    };

    vm.eventTimesChanged = function(event) {
      alert.show('Dropped or resized', event);
    };

    vm.toggle = function($event, field, event) {
      $event.preventDefault();
      $event.stopPropagation();
      event[field] = !event[field];
    };

  });
<commit_msg>just starts at<commit_after>angular
  .module('mwl.calendar.docs') //you will need to declare your module with the dependencies ['mwl.calendar', 'ui.bootstrap', 'ngAnimate']
  .controller('KitchenSinkCtrl', function(moment, alert) {

    var vm = this;

    //These variables MUST be set as a minimum for the calendar to work
    vm.calendarView = 'month';
    vm.viewDate = new Date();
    vm.events = [];

    //ADD EVENTS HERE
    $(document).ready(function(){
      $.get("http://swumusic.com/json.html", function(data, status){
        var arr = JSON.parse(data);

        arr.map(function (X) {
          date = new Date (X["Store Date"])
          vm.events.push({
            title: X["Content Title"],
            type: 'important',
            startsAt: date,
            draggable: true,
            resizable: true});
        });
      });
    });

    vm.isCellOpen = false;

    vm.eventClicked = function(event) {
      alert.show('Clicked', event);
    };

    vm.eventEdited = function(event) {
      alert.show('Edited', event);
    };

    vm.eventDeleted = function(event) {
      alert.show('Deleted', event);
    };

    vm.eventTimesChanged = function(event) {
      alert.show('Dropped or resized', event);
    };

    vm.toggle = function($event, field, event) {
      $event.preventDefault();
      $event.stopPropagation();
      event[field] = !event[field];
    };

  });
<|endoftext|>


<commit_before>if (!dp) var dp = {};

dp.helper = {
    prefixize: function(path, prefix) {
        prefix = prefix || dp.vars.prefix;

        if (prefix) {
            if (dp.helper.string.endsWith(prefix, '/')) {
                prefix = prefix.substr(0, prefix.length -1);
            }
        }
        else {
            prefix = '';
        }

        if (dp.helper.string.startsWith(path, prefix)) {
            path = path.substr(prefix.length) || '/';
        }

        return path;
    },
    req_busy: {},
    req: function(obj, obj_add) {
        if (obj instanceof dp_jqlib) {
            var _obj = obj;
            obj = {
                'url': _obj.attr('action'),
                'type': _obj.attr('method'),
                'dataType': obj.attr('dp-req-res-type') || 'json',
                'prefixize': obj.attr('dp-req-prefixize') != 'no' && obj.attr('dp-req-prefixize') != 'false',
                'fields': []
            };

            var objSucc = _obj.attr('dp-req-success');
            var objError = _obj.attr('dp-req-error');

            if (objSucc) {
                obj.success = eval(objSucc);
            }

            if (objError) {
                obj.error = eval(objError);
            }

            if (_obj.find('*[dp-req-type="button"]').length > 0) {
                var _btn = dp_jqlib(_obj.find('*[dp-req-type="button"]').get(0));

                obj.button = _btn;
                obj.fade = _btn.attr('dp-req-fade') != 'no' && _btn.attr('dp-req-fade') != 'false';
                obj.multiple = _btn.attr('dp-req-multiple') != 'no' && _btn.attr('dp-req-multiple') != 'false';

                if (!_btn.attr('dp-req-identifier')) {
                    _btn.attr('dp-req-identifier', 'req-' + dp.helper.string.uniqid());
                }

                if (_btn.attr('dp-req-identifier')) {
                    obj.identifier = _btn.attr('dp-req-identifier');
                }
            }

            _obj.find('*[dp-req-type]').each(function(i, e) {
                var _this = dp_jqlib(this);
                var payload = {
                    name: _this.attr('name') || _this.attr('id'),
                    obj: _this,
                    required: _this.attr('dp-req-required') == 'yes' || _this.attr('dp-req-required') == 'true',
                    focus: _this.attr('dp-req-required') == 'yes' || _this.attr('dp-req-required') == 'true',
                    validate: _this.attr('dp-req-type'),
                    length: _this.attr('dp-req-length') ? dp_jqlib.map(_this.attr('dp-req-length').split(','), function(v, i) { return parseInt(v, 10); }) : undefined,
                    message: {
                        missing: _this.attr('dp-req-missing'),
                        invalid: _this.attr('dp-req-invalid'),
                        confirm: _this.attr('dp-req-confirm'),
                        confirmYes: _this.attr('dp-req-confirm-yes'),
                        confirmNo: _this.attr('dp-req-confirm-no')
                    }
                };

                if (_this.attr('dp-req-type') == 'checkbox') {
                    payload.val = _this.prop('checked') ? _this.val() : '';
                }

                obj.fields.push(payload);
            });
        }

        if (obj_add) {
            dp_jqlib.extend(obj, obj_add);
        }

        var btn = obj.button || undefined;
        var multiple = obj.multiple || false;
        var fields = obj.fields || [];
        var url = obj.url || undefined;
        var headers = obj.headers || undefined;
        var type = obj.type || 'POST';
        var data = obj.data || {};
        var dataType = obj.dataType || 'json';
        var fade = obj.fade != undefined ? obj.fade : true;
        var prefixize = obj.prefixize != undefined ? obj.prefixize : true;
        var prefix = obj.prefix != undefined ? obj.prefix : dp.vars.prefix;
        var identifier = obj.identifier || undefined;
        var opacity_origin = btn ? btn.css('opacity') : 1.0;

        if (btn && !btn.attr('id')) {
            btn.attr('id', 'temp-' + dp.helper.string.uniqid());
        }

        if (!identifier) {
            identifier = btn ? btn.attr('id') : dp.helper.string.uniqid();
        }

        if (!multiple && dp.helper.req_busy[identifier]) return false;
        dp.helper.req_busy[identifier] = true;

        var no_finalize = false;
        var fn_finalize = function() {
            if (no_finalize) {
                no_finalize = false;
                return;
            }

            dp.helper.req_busy[identifier] = false;
            if (btn) {
                btn.fadeTo(100, opacity_origin);
            }
        };

        if (obj.before) {
            if (obj.before() == false) {
                fn_finalize();
                return false;
            }
        }

        var fields_checked = true;
        var output = false;

        dp_jqlib(fields).each(function(i, e) {
            var val = e.val;

            if (val === undefined) {
                val = e.obj.val();
            }

            var skip = false;

            // Required
            if (fields_checked && e.required && !val) {
                if (e.message && e.message.missing) {
                    output = dp.alert(e.message.missing);
                }

                fields_checked = false;
            }

            // Button - SKIP
            if (fields_checked && e.validate == 'button') {
                skip = true;
            }
            // E-Mail validation
            else if (fields_checked && e.validate == 'email' && !dp.helper.validator.email(val)) {
                if (e.message && e.message.invalid) {
                    output = dp.alert(e.message.invalid);
                }

                fields_checked = false;
            }
            // URL validation
            else if (fields_checked && e.validate == 'url' && !dp.helper.validator.url(val)) {
                if (e.message && e.message.invalid) {
                    output = dp.alert(e.message.invalid);
                }

                fields_checked = false;
            }

            if (fields_checked && e.length) {
                if ((e.length.length >= 1 && val.length < e.length[0]) || (e.length.length >= 2 && val.length > e.length[1])) {
                    if (e.message && e.message.invalid) {
                        output = dp.alert(e.message.invalid);
                    }

                    fields_checked = false;
                }
            }

            // Confirm (alert)
            if (fields_checked && e.message && e.message.confirm && !e.message.confirming) {
                e.message.confirming = true;

                var confirmYes = e.message.confirmYes || 'OK';
                var confirmNo = e.message.confirmNo || 'Cancel';

                output = dp.alert(
                    e.message.confirm,
                    function() {
                        fn_finalize();
                        dp.req(obj);
                    }, confirmYes,
                    function() {
                        fn_finalize();
                    }, confirmNo
                );

                no_finalize = true;
                fields_checked = false;
            }

            if (!fields_checked) {
                dp.ui.util.alert_focus = e.obj;
                return false;
            }

            if (!skip && e.name) {
                data[e.name] = val;
            }
        });

        if (!fields_checked) {
            fn_finalize();
            return output;
        }

        var finalize = function(data) {
            if (data && typeof(data) == 'object') {
                var finalizePage = function() {
                    if (data.redirect) {
                        document.location.href = data.redirect;
                    }
                    else if (data.reload) {
                        document.location.reload();
                    }
                };

                if (data.message) {
                    dp.alert(data.message, function() {
                        finalizePage();
                    });
                }
                else {
                    finalizePage();
                }
            }
        };

        var success = function(res) {
            if (dataType && dataType.toLowerCase() == 'json') {
                if (res.result != undefined && !res.result) {
                    error(undefined, undefined, undefined, res);
                    return;
                }
            }

            fn_finalize();

            if (obj.success) {
                obj.success(res, data);
            }

            finalize(res);
        };

        var error = function(a, b, c, res) {
            fn_finalize();

            if (obj.error) {
                obj.error(res, a, b, c);
            }

            finalize(res);
        };

        var ajax_req = function() {
            var payload = {
                url: prefixize ? dp.helper.prefixize(url, prefix) : url,
                headers: headers,
                type: type,
                data: data,
                dataType: dataType,
                success: success,
                error: error
            };

            dp_jqlib.ajax(payload);
        };

        if (btn && fade) {
            btn.stop().clearQueue().fadeTo(100, 0.3, function() {
                ajax_req();
            });
        }
        else {
            ajax_req();
        }

        return true;
    },
    validator: {
        email: function(e) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(e);
        },
        url: function(e, i) {
            if (!i && e.indexOf('http')) {
                return false;
            }

            var re = new RegExp('^(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:22[0-3]|2[01]\\d|[1-9]\\d?|1\\d\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1?\\d{1,2})){2}(?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d?))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:/\\S*)?$', 'i');
			return re.test(e);
        }
    },
    string: {
        _uniqid_seed: 0,
        uniqid: function(prefix, more_entropy, more_entropy_separator) {
            /* This code has extracted from php.js */

            if (!prefix) {
                prefix = "";
            }

            if (!more_entropy_separator) {
                more_entropy_separator = '';
            }

            var retId;
            var formatSeed = (function(seed, reqWidth){
                seed = parseInt(seed, 10).toString(16);

                if (reqWidth < seed.length)
                {
                    return seed.slice(seed.length - reqWidth);
                }

                if (reqWidth > seed.length)
                {
                    var arr = new Array(1 + (reqWidth - seed.length));
                    return arr.join('0') + seed;
                }

                return seed;
            });

            if (!dp.helper.string._uniqid_seed)
            {
                dp.helper.string._uniqid_seed = Math.floor(Math.random() * 0x75bcd15);
            }

            dp.helper.string._uniqid_seed++;

            retId = prefix; // start with prefix, add current milliseconds hex string
            retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
            retId += formatSeed(dp.helper.string._uniqid_seed, 5); // add seed hex string

            // for more entropy we add a float lower to 10
            if (more_entropy)
            {
                retId += (Math.random() * 10).toFixed(8).toString();
            }

            return dp.helper.string.replaceAll(retId, '.', more_entropy_separator);
        },
        replaceAll: function(text, find, replace) {
            return text.split(find).join(replace);
        },
        startsWith: function(str, prefix) {
            return str ? str.indexOf(prefix, 0) !== -1 : false;
        },
        endsWith: function(str, suffix) {
            return str ? str.indexOf(suffix, str.length - suffix.length) !== -1 : false;
        },
        extractNumbers: function(val) {
            var replace = /[^0-9]/gi;
            return (val.substring(0, 1) == '-' ? '-' : '') + val.replace(replace, '');
        },
        numberFormat: function(val) {
            return val.toFixed(0).replace(/(\d)(?=(\d{3})+$)/g, "$1,");
        }
    }
};
<commit_msg>fields list to object.<commit_after>if (!dp) var dp = {};

dp.helper = {
    prefixize: function(path, prefix) {
        prefix = prefix || dp.vars.prefix;

        if (prefix) {
            if (dp.helper.string.endsWith(prefix, '/')) {
                prefix = prefix.substr(0, prefix.length -1);
            }
        }
        else {
            prefix = '';
        }

        if (dp.helper.string.startsWith(path, prefix)) {
            path = path.substr(prefix.length) || '/';
        }

        return path;
    },
    req_busy: {},
    req: function(obj, obj_add) {
        if (obj instanceof dp_jqlib) {
            var _obj = obj;
            obj = {
                'url': _obj.attr('action'),
                'type': _obj.attr('method'),
                'dataType': obj.attr('dp-req-res-type') || 'json',
                'prefixize': obj.attr('dp-req-prefixize') != 'no' && obj.attr('dp-req-prefixize') != 'false',
                'fields': {}
            };

            var objSucc = _obj.attr('dp-req-success');
            var objError = _obj.attr('dp-req-error');

            if (objSucc) {
                obj.success = eval(objSucc);
            }

            if (objError) {
                obj.error = eval(objError);
            }

            if (_obj.find('*[dp-req-type="button"]').length > 0) {
                var _btn = dp_jqlib(_obj.find('*[dp-req-type="button"]').get(0));

                obj.button = _btn;
                obj.fade = _btn.attr('dp-req-fade') != 'no' && _btn.attr('dp-req-fade') != 'false';
                obj.multiple = _btn.attr('dp-req-multiple') != 'no' && _btn.attr('dp-req-multiple') != 'false';

                if (!_btn.attr('dp-req-identifier')) {
                    _btn.attr('dp-req-identifier', 'req-' + dp.helper.string.uniqid());
                }

                if (_btn.attr('dp-req-identifier')) {
                    obj.identifier = _btn.attr('dp-req-identifier');
                }
            }

            _obj.find('*[dp-req-type]').each(function(i, e) {
                var _this = dp_jqlib(this);
                var key = _this.attr('name') || _this.attr('id');
                var payload = {
                    obj: _this,
                    required: _this.attr('dp-req-required') == 'yes' || _this.attr('dp-req-required') == 'true',
                    focus: _this.attr('dp-req-required') == 'yes' || _this.attr('dp-req-required') == 'true',
                    validate: _this.attr('dp-req-type'),
                    length: _this.attr('dp-req-length') ? dp_jqlib.map(_this.attr('dp-req-length').split(','), function(v, i) { return parseInt(v, 10); }) : undefined,
                    message: {
                        missing: _this.attr('dp-req-missing'),
                        invalid: _this.attr('dp-req-invalid'),
                        confirm: _this.attr('dp-req-confirm'),
                        confirmYes: _this.attr('dp-req-confirm-yes'),
                        confirmNo: _this.attr('dp-req-confirm-no')
                    }
                };

                if (_this.attr('dp-req-type') == 'checkbox') {
                    payload.val = _this.prop('checked') ? _this.val() : '';
                }

                obj.fields[key] = payload;
            });
        }

        if (obj_add) {
            dp_jqlib.extend(obj, obj_add);
        }

        var btn = obj.button || undefined;
        var multiple = obj.multiple || false;
        var fields = obj.fields || [];
        var url = obj.url || undefined;
        var headers = obj.headers || undefined;
        var type = obj.type || 'POST';
        var data = obj.data || {};
        var dataType = obj.dataType || 'json';
        var fade = obj.fade != undefined ? obj.fade : true;
        var prefixize = obj.prefixize != undefined ? obj.prefixize : true;
        var prefix = obj.prefix != undefined ? obj.prefix : dp.vars.prefix;
        var identifier = obj.identifier || undefined;
        var opacity_origin = btn ? btn.css('opacity') : 1.0;

        if (btn && !btn.attr('id')) {
            btn.attr('id', 'temp-' + dp.helper.string.uniqid());
        }

        if (!identifier) {
            identifier = btn ? btn.attr('id') : dp.helper.string.uniqid();
        }

        if (!multiple && dp.helper.req_busy[identifier]) return false;
        dp.helper.req_busy[identifier] = true;

        var no_finalize = false;
        var fn_finalize = function() {
            if (no_finalize) {
                no_finalize = false;
                return;
            }

            dp.helper.req_busy[identifier] = false;
            if (btn) {
                btn.fadeTo(100, opacity_origin);
            }
        };

        if (obj.before) {
            if (obj.before() == false) {
                fn_finalize();
                return false;
            }
        }

        var fields_checked = true;
        var output = false;

        dp_jqlib.each(fields, function(key, e) {
            var val = e.val;

            if (val === undefined && e.obj) {
                val = e.obj.val();
            }

            var skip = false;

            // Required
            if (fields_checked && e.required && !val) {
                if (e.message && e.message.missing) {
                    output = dp.alert(e.message.missing);
                }

                fields_checked = false;
            }

            // Button - SKIP
            if (fields_checked && e.validate == 'button') {
                skip = true;
            }
            // E-Mail validation
            else if (fields_checked && e.validate == 'email' && !dp.helper.validator.email(val)) {
                if (e.message && e.message.invalid) {
                    output = dp.alert(e.message.invalid);
                }

                fields_checked = false;
            }
            // URL validation
            else if (fields_checked && e.validate == 'url' && !dp.helper.validator.url(val)) {
                if (e.message && e.message.invalid) {
                    output = dp.alert(e.message.invalid);
                }

                fields_checked = false;
            }

            if (fields_checked && e.length) {
                if ((e.length.length >= 1 && val.length < e.length[0]) || (e.length.length >= 2 && val.length > e.length[1])) {
                    if (e.message && e.message.invalid) {
                        output = dp.alert(e.message.invalid);
                    }

                    fields_checked = false;
                }
            }

            // Confirm (alert)
            if (fields_checked && e.message && e.message.confirm && !e.message.confirming) {
                e.message.confirming = true;

                var confirmYes = e.message.confirmYes || 'OK';
                var confirmNo = e.message.confirmNo || 'Cancel';

                output = dp.alert(
                    e.message.confirm,
                    function() {
                        fn_finalize();
                        dp.req(obj);
                    }, confirmYes,
                    function() {
                        fn_finalize();
                    }, confirmNo
                );

                no_finalize = true;
                fields_checked = false;
            }

            if (!fields_checked) {
                dp.ui.util.alert_focus = e.obj;
                return false;
            }

            if (!skip && key) {
                data[key] = val;
            }
        });

        if (!fields_checked) {
            fn_finalize();
            return output;
        }

        var finalize = function(data) {
            if (data && typeof(data) == 'object') {
                var finalizePage = function() {
                    if (data.redirect) {
                        document.location.href = data.redirect;
                    }
                    else if (data.reload) {
                        document.location.reload();
                    }
                };

                if (data.message) {
                    dp.alert(data.message, function() {
                        finalizePage();
                    });
                }
                else {
                    finalizePage();
                }
            }
        };

        var success = function(res) {
            if (dataType && dataType.toLowerCase() == 'json') {
                if (res.result != undefined && !res.result) {
                    error(undefined, undefined, undefined, res);
                    return;
                }
            }

            fn_finalize();

            if (obj.success) {
                obj.success(res, data);
            }

            finalize(res);
        };

        var error = function(a, b, c, res) {
            fn_finalize();

            if (obj.error) {
                obj.error(res, a, b, c);
            }

            finalize(res);
        };

        var ajax_req = function() {
            var payload = {
                url: prefixize ? dp.helper.prefixize(url, prefix) : url,
                headers: headers,
                type: type,
                data: data,
                dataType: dataType,
                success: success,
                error: error
            };

            dp_jqlib.ajax(payload);
        };

        if (btn && fade) {
            btn.stop().clearQueue().fadeTo(100, 0.3, function() {
                ajax_req();
            });
        }
        else {
            ajax_req();
        }

        return true;
    },
    validator: {
        email: function(e) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(e);
        },
        url: function(e, i) {
            if (!i && e.indexOf('http')) {
                return false;
            }

            var re = new RegExp('^(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:22[0-3]|2[01]\\d|[1-9]\\d?|1\\d\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1?\\d{1,2})){2}(?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d?))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:/\\S*)?$', 'i');
			return re.test(e);
        }
    },
    string: {
        _uniqid_seed: 0,
        uniqid: function(prefix, more_entropy, more_entropy_separator) {
            /* This code has extracted from php.js */

            if (!prefix) {
                prefix = "";
            }

            if (!more_entropy_separator) {
                more_entropy_separator = '';
            }

            var retId;
            var formatSeed = (function(seed, reqWidth){
                seed = parseInt(seed, 10).toString(16);

                if (reqWidth < seed.length)
                {
                    return seed.slice(seed.length - reqWidth);
                }

                if (reqWidth > seed.length)
                {
                    var arr = new Array(1 + (reqWidth - seed.length));
                    return arr.join('0') + seed;
                }

                return seed;
            });

            if (!dp.helper.string._uniqid_seed)
            {
                dp.helper.string._uniqid_seed = Math.floor(Math.random() * 0x75bcd15);
            }

            dp.helper.string._uniqid_seed++;

            retId = prefix; // start with prefix, add current milliseconds hex string
            retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
            retId += formatSeed(dp.helper.string._uniqid_seed, 5); // add seed hex string

            // for more entropy we add a float lower to 10
            if (more_entropy)
            {
                retId += (Math.random() * 10).toFixed(8).toString();
            }

            return dp.helper.string.replaceAll(retId, '.', more_entropy_separator);
        },
        replaceAll: function(text, find, replace) {
            return text.split(find).join(replace);
        },
        startsWith: function(str, prefix) {
            return str ? str.indexOf(prefix, 0) !== -1 : false;
        },
        endsWith: function(str, suffix) {
            return str ? str.indexOf(suffix, str.length - suffix.length) !== -1 : false;
        },
        extractNumbers: function(val) {
            var replace = /[^0-9]/gi;
            return (val.substring(0, 1) == '-' ? '-' : '') + val.replace(replace, '');
        },
        numberFormat: function(val) {
            return val.toFixed(0).replace(/(\d)(?=(\d{3})+$)/g, "$1,");
        }
    }
};
<|endoftext|>


<commit_before>describe("When using the constructor invocation pattern", function(){
  var ThisConstructor = function(){
    this.foo = 'bar';
  }

  var ThisConstructorThrowsThings = function(){
    if(!(this instanceof arguments.callee)){
      throw new Error("Constructor called without the new keyword");
    }
  }

  it("should return a new object", function(){
      expect(new ThisConstructor()).not.toBe(null);
      var fooType = typeof foo
      expect(fooType).toBe("undefined");
  });

  it("Should polute the global namespace if called without the new keyword", function(){
    ThisConstructor();

    expect(foo).toBe('bar');
  })

  it ("Should throw an exception when called without the new keyword", function(){
    expect( function() { ThisConstructorThrowsThings(); }).toThrow(new Error("Constructor called without the new keyword"));
  });
});

describe("When using the method invocation pattern", function(){
  this.fooTwo = "Not What We Want";
  var ThisConstructor = function(){
    this.fooTwo = "What We want";
    this.foo = function(){
      return this.fooTwo;
    };
  }
  var target = new ThisConstructor();
  it("should scope this to the defined object", function() {
    expect(target.foo()).toBe("What We want");
  });
});<commit_msg>Updated the test to be right<commit_after>describe("When using the constructor invocation pattern", function(){
  var ThisConstructor = function(){
    this.foo = 'bar';
  }

  var ThisConstructorThrowsThings = function(){
    if(!(this instanceof arguments.callee)){
      throw new Error("Constructor called without the new keyword");
    }
  }

  it("should return a new object", function(){
      expect(new ThisConstructor()).not.toBe(null);
      var fooType = typeof foo
      expect(fooType).toBe("undefined");
  });

  it("Should polute the global namespace if called without the new keyword", function(){
    ThisConstructor();

    expect(foo).toBe('bar');
  })

  it ("Should throw an exception when called without the new keyword", function(){
    expect( function() { ThisConstructorThrowsThings(); }).toThrow(new Error("Constructor called without the new keyword"));
  });
});

describe("When using the method invocation pattern", function(){

  var ThisConstructor = function(){
    this.fooTwo = "What We want";
    this.foo = function(){
      return this.fooTwo;
    };
  }
  this.fooTwo = "Not What We Want";
  var target = new ThisConstructor();
  it("should scope this to the defined object", function() {
    expect(target.foo()).toBe("What We want");
  });
});<|endoftext|>


<commit_before>/*
 * ext-server_opensave.js
 *
 * Licensed under the Apache License, Version 2
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {

		var save_svg_action = 'extensions/filesave.php';
		var save_png_action = 'extensions/filesave.php';

		// Create upload target (hidden iframe)
		var target = $('<iframe name="output_frame" src="#"/>').hide().appendTo('body');

		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version='1.0'?>\n" + data;

				var title = svgCanvas.getDocumentTitle();
				var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			pngsave: function(win, data) {
				var issues = data.issues;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				var c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg);
				var datauri = c.toDataURL('image/png');

				var uiStrings = svgEditor.uiStrings;
				var note = '';

				// Check if there's issues
				if(issues.length) {
					var pre = "\n \u2022 ";
					note += ("\n\n" + pre + issues.join(pre));
				}

				if(note.length) {
					alert(note);
				}

				var title = svgCanvas.getDocumentTitle();
				var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_png_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_png" value="' + datauri + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) return;

		var cancelled = false;

		// Change these to appropriate script file
		var open_svg_action = 'extensions/fileopen.php?type=load_svg';
		var import_svg_action = 'extensions/fileopen.php?type=import_svg';
		var import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if(type != 'import_img') {
				var xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch ( type ) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		}

		// Create upload form
		var open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		var import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		var import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<commit_msg>Added timeout to PNG export for server_opensave extension<commit_after>/*
 * ext-server_opensave.js
 *
 * Licensed under the Apache License, Version 2
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {

		var save_svg_action = 'extensions/filesave.php';
		var save_png_action = 'extensions/filesave.php';

		// Create upload target (hidden iframe)
		var target = $('<iframe name="output_frame" src="#"/>').hide().appendTo('body');

		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version='1.0'?>\n" + data;

				var title = svgCanvas.getDocumentTitle();
				var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			pngsave: function(win, data) {
				var issues = data.issues;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				var c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg);

				// Timeout to allow canvg to run a bit
				setTimeout(function() {
					var datauri = c.toDataURL('image/png');

					var uiStrings = svgEditor.uiStrings;
					var note = '';

					// Check if there's issues
					if(issues.length) {
						var pre = "\n \u2022 ";
						note += ("\n\n" + pre + issues.join(pre));
					}

					if(note.length) {
						alert(note);
					}

					var title = svgCanvas.getDocumentTitle();
					var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

					var form = $('<form>').attr({
						method: 'post',
						action: save_png_action,
						target: 'output_frame'
					})	.append('<input type="hidden" name="output_png" value="' + datauri + '">')
						.append('<input type="hidden" name="filename" value="' + filename + '">')
						.appendTo('body')
						.submit().remove();
				}, 1000);

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) return;

		var cancelled = false;

		// Change these to appropriate script file
		var open_svg_action = 'extensions/fileopen.php?type=load_svg';
		var import_svg_action = 'extensions/fileopen.php?type=import_svg';
		var import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if(type != 'import_img') {
				var xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch ( type ) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		}

		// Create upload form
		var open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		var import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		var import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<|endoftext|>