<commit_before>/*!
 * medium-editor-insert-plugin v0.1.1 - jQuery insert plugin for MediumEditor
 *
 * Images Addon
 *
 * https://github.com/orthes/medium-editor-images-plugin
 *
 * Copyright (c) 2013 Pavel Linkesch (http://linkesch.sk)
 * Released under the MIT license
 */

(function ($) {

  $.fn.mediumInsert.images = {

    /**
    * Images initial function
    * @return {void}
    */

    init: function () {
      this.$el = $.fn.mediumInsert.insert.$el;
      this.options = $.extend(this.default,
        $.fn.mediumInsert.settings.imagesPlugin);

      this.setImageEvents();
      this.setDragAndDropEvents();
    },

    default: {
      formatData: function (file) {
        var formData = new FormData();
        formData.append('file', file);
        return formData;
      }
    },

    /**
    * Add image to placeholder
    * @param {element} $placeholder Placeholder to add image to
    * @return {element} $selectFile <input type="file"> element
    */

    add: function ($placeholder) {
      var that = this,
          $selectFile, files;

      $selectFile = $('<input type="file">').click();
      $selectFile.change(function () {
        files = this.files;
        that.uploadFiles($placeholder, files);
      });

      $.fn.mediumInsert.insert.deselect();

      return $selectFile;
    },

    /**
    * Update progressbar while upload
    * @param {event} e XMLHttpRequest.upload.onprogress event
    * @return {void}
    */

    updateProgressBar: function (e) {
      var $progress = $('.progress:first', this.$el),
          complete;

      if (e.lengthComputable) {
        complete = (e.loaded / e.total * 100 | 0);
        $progress.attr('value', complete);
        $progress.html(complete);
      }
    },

    /**
    * Show uploaded image after upload completed
    * @param {event} e XMLHttpRequest.onload event
    * @return {void}
    */

    uploadCompleted: function (jqxhr) {
      var $progress = $('.progress:first', this.$el),
          $img;

      $progress.attr('value', 100);
      $progress.html(100);

      $progress.before('');
      $img = $progress.siblings('img');
      $progress.remove();

      $img.load(function () {
        $img.parent().mouseleave().mouseenter();
      });
    },

    /**
    * Upload files, display progress bar and finally uploaded file
    * @param {element} placeholder Placeholder to add image to
    * @param {FileList} files Files to upload
    * @return {void}
    */

    uploadFiles: function ($placeholder, files) {
      var acceptedTypes = {
        'image/png': true,
        'image/jpeg': true,
        'image/gif': true
      },
      that = this,
      xhr = function () {
        var xhr = new XMLHttpRequest();
        xhr.upload.onprogress = that.updateProgressBar;
        return xhr;
      };

      for (var i = 0; i < files.length; i++) {
        var file = files[i];

        if (acceptedTypes[file.type] === true) {
          $placeholder.append('<progress class="progress" min="0" max="100" value="0">0</progress>');

          $.ajax({
            type: "post",
            url: $.fn.mediumInsert.settings.imagesUploadScript,
            xhr: xhr,
            cache: false,
            contentType: false,
            complete: this.uploadCompleted,
            processData: false,
            data: this.options.formatData(file)
          });
        }
      }
    },

    /**
    * Set image events displaying remove and resize buttons
    * @return {void}
    */

    setImageEvents: function () {
      this.$el.on('mouseenter', '.mediumInsert-images', function () {
        var $img = $('img', this),
            positionTop,
            positionLeft;

        if ($img.length > 0) {
          $(this).append('');

          if ($(this).parent().parent().hasClass('small')) {
            $(this).append('');
          } else {
            $(this).append('');
          }

          positionTop = $img.position().top + parseInt($img.css('margin-top'), 10);
          positionLeft = $img.position().left + $img.width() -30;
          $('.mediumInsert-imageRemove', this).css({
            'right': 'auto',
            'top': positionTop,
            'left': positionLeft
          });
          $('.mediumInsert-imageResizeBigger, .mediumInsert-imageResizeSmaller', this).css({
            'right': 'auto',
            'top': positionTop,
            'left': positionLeft-31
          });
        }
      });

      this.$el.on('mouseleave', '.mediumInsert-images', function () {
        $('.mediumInsert-imageRemove, .mediumInsert-imageResizeSmaller, .mediumInsert-imageResizeBigger', this).remove();
      });

      this.$el.on('click', '.mediumInsert-imageResizeSmaller', function () {
        $(this).parent().parent().parent().addClass('small');
        $(this).parent().mouseleave().mouseleave();

        $.fn.mediumInsert.insert.deselect();
      });

      this.$el.on('click', '.mediumInsert-imageResizeBigger', function () {
        $(this).parent().parent().parent().removeClass('small');
        $(this).parent().mouseleave().mouseleave();

        $.fn.mediumInsert.insert.deselect();
      });

      this.$el.on('click', '.mediumInsert-imageRemove', function () {
        if ($(this).parent().siblings().length === 0) {
          $(this).parent().parent().parent().removeClass('small');
        }
        $(this).parent().remove();

        $.fn.mediumInsert.insert.deselect();
      });
    },

    /**
    * Set drag and drop evnets
    * @return {void}
    */

    setDragAndDropEvents: function () {
      var that = this,
          dropSuccessful = false,
          dropSort = false,
          dropSortIndex, dropSortParent;

      $(document).on('dragover', 'body', function () {
        $(this).addClass('hover');
      });

      $(document).on('dragend', 'body', function () {
        $(this).removeClass('hover');
      });

      this.$el.on('dragover', '.mediumInsert', function () {
        $(this).addClass('hover');
        $(this).attr('contenteditable', true);
      });

      this.$el.on('dragleave', '.mediumInsert', function () {
        $(this).removeClass('hover');
        $(this).attr('contenteditable', false);
      });

      this.$el.on('dragstart', '.mediumInsert .mediumInsert-images img', function (e) {
        dropSortIndex = $(this).parent().index();
        dropSortParent = $(this).parent().parent().parent().attr('id');
      });

      this.$el.on('dragend', '.mediumInsert .mediumInsert-images img', function (e) {
        if (dropSuccessful === true) {
          if ($(e.originalEvent.target.parentNode).siblings().length === 0) {
            $(e.originalEvent.target.parentNode).parent().parent().removeClass('small');
          }
          $(e.originalEvent.target.parentNode).mouseleave();
          $(e.originalEvent.target.parentNode).remove();
          dropSuccessful = false;
          dropSort = false;
        }
      });

      this.$el.on('dragover', '.mediumInsert .mediumInsert-images img', function (e) {
        e.preventDefault();
      });

      this.$el.on('drop', '.mediumInsert .mediumInsert-images img', function (e) {
        var index, $dragged, finalIndex;

        if (dropSortParent !== $(this).parent().parent().parent().attr('id')) {
          dropSort = false;
          dropSortIndex = dropSortParent = null;
          return;
        }

        index = parseInt(dropSortIndex, 10);

        // Sort
        $dragged = $(this).parent().parent().find('.mediumInsert-images:nth-child('+ (index+1) +')');
        finalIndex = $(this).parent().index();
        if(index < finalIndex) {
          $dragged.insertAfter($(this).parent());
        } else if(index > finalIndex) {
          $dragged.insertBefore($(this).parent());
        }

        $dragged.mouseleave();

        dropSort = true;
        dropSortIndex = null;
      });

      this.$el.on('drop', '.mediumInsert', function (e) {
        var files;

        e.preventDefault();
        $(this).removeClass('hover');
        $('body').removeClass('hover');
        $(this).attr('contenteditable', false);

        files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
          // File upload
          that.uploadFiles($('.mediumInsert-placeholder', this), files);
        } else if (dropSort === true) {
          dropSort = false;
        } else {
          // Image move from block to block
          $('.mediumInsert-placeholder', this).append(''+ e.originalEvent.dataTransfer.getData('text/html') +'');
          $('meta', this).remove();
          dropSuccessful = true;
        }
      });
    }
  };
}(jQuery));
<commit_msg>Fixed dist files for clean grunt task out of the box.<commit_after>/*!
 * medium-editor-insert-plugin v0.1.1 - jQuery insert plugin for MediumEditor
 *
 * Images Addon
 *
 * https://github.com/orthes/medium-editor-images-plugin
 *
 * Copyright (c) 2013 Pavel Linkesch (http://linkesch.sk)
 * Released under the MIT license
 */

(function ($) {

  $.fn.mediumInsert.images = {

    /**
    * Images initial function
    * @return {void}
    */

    init: function () {
      this.$el = $.fn.mediumInsert.insert.$el;
      this.options = $.extend(this.default,
        $.fn.mediumInsert.settings.imagesPlugin);

      this.setImageEvents();
      this.setDragAndDropEvents();
    },

    /**
    * Images default options
    */

    default: {
      formatData: function (file) {
        var formData = new FormData();
        formData.append('file', file);
        return formData;
      }
    },

    /**
    * Add image to placeholder
    * @param {element} $placeholder Placeholder to add image to
    * @return {element} $selectFile <input type="file"> element
    */

    add: function ($placeholder) {
      var that = this,
          $selectFile, files;

      $selectFile = $('<input type="file">').click();
      $selectFile.change(function () {
        files = this.files;
        that.uploadFiles($placeholder, files);
      });

      $.fn.mediumInsert.insert.deselect();

      return $selectFile;
    },

    /**
    * Update progressbar while upload
    * @param {event} e XMLHttpRequest.upload.onprogress event
    * @return {void}
    */

    updateProgressBar: function (e) {
      var $progress = $('.progress:first', this.$el),
          complete;

      if (e.lengthComputable) {
        complete = (e.loaded / e.total * 100 | 0);
        $progress.attr('value', complete);
        $progress.html(complete);
      }
    },

    /**
    * Show uploaded image after upload completed
    * @param {jqXHR} jqxhr jqXHR object
    * @return {void}
    */

    uploadCompleted: function (jqxhr) {
      var $progress = $('.progress:first', this.$el),
          $img;

      $progress.attr('value', 100);
      $progress.html(100);

      $progress.before('');
      $img = $progress.siblings('img');
      $progress.remove();

      $img.load(function () {
        $img.parent().mouseleave().mouseenter();
      });
    },

    /**
    * Upload files, display progress bar and finally uploaded file
    * @param {element} placeholder Placeholder to add image to
    * @param {FileList} files Files to upload
    * @return {void}
    */

    uploadFiles: function ($placeholder, files) {
      var acceptedTypes = {
        'image/png': true,
        'image/jpeg': true,
        'image/gif': true
      },
      that = this,
      xhr = function () {
        var xhr = new XMLHttpRequest();
        xhr.upload.onprogress = that.updateProgressBar;
        return xhr;
      };

      for (var i = 0; i < files.length; i++) {
        var file = files[i];

        if (acceptedTypes[file.type] === true) {
          $placeholder.append('<progress class="progress" min="0" max="100" value="0">0</progress>');

          $.ajax({
            type: "post",
            url: $.fn.mediumInsert.settings.imagesUploadScript,
            xhr: xhr,
            cache: false,
            contentType: false,
            complete: this.uploadCompleted,
            processData: false,
            data: this.options.formatData(file)
          });
        }
      }
    },

    /**
    * Set image events displaying remove and resize buttons
    * @return {void}
    */

    setImageEvents: function () {
      this.$el.on('mouseenter', '.mediumInsert-images', function () {
        var $img = $('img', this),
            positionTop,
            positionLeft;

        if ($img.length > 0) {
          $(this).append('');

          if ($(this).parent().parent().hasClass('small')) {
            $(this).append('');
          } else {
            $(this).append('');
          }

          positionTop = $img.position().top + parseInt($img.css('margin-top'), 10);
          positionLeft = $img.position().left + $img.width() -30;
          $('.mediumInsert-imageRemove', this).css({
            'right': 'auto',
            'top': positionTop,
            'left': positionLeft
          });
          $('.mediumInsert-imageResizeBigger, .mediumInsert-imageResizeSmaller', this).css({
            'right': 'auto',
            'top': positionTop,
            'left': positionLeft-31
          });
        }
      });

      this.$el.on('mouseleave', '.mediumInsert-images', function () {
        $('.mediumInsert-imageRemove, .mediumInsert-imageResizeSmaller, .mediumInsert-imageResizeBigger', this).remove();
      });

      this.$el.on('click', '.mediumInsert-imageResizeSmaller', function () {
        $(this).parent().parent().parent().addClass('small');
        $(this).parent().mouseleave().mouseleave();

        $.fn.mediumInsert.insert.deselect();
      });

      this.$el.on('click', '.mediumInsert-imageResizeBigger', function () {
        $(this).parent().parent().parent().removeClass('small');
        $(this).parent().mouseleave().mouseleave();

        $.fn.mediumInsert.insert.deselect();
      });

      this.$el.on('click', '.mediumInsert-imageRemove', function () {
        if ($(this).parent().siblings().length === 0) {
          $(this).parent().parent().parent().removeClass('small');
        }
        $(this).parent().remove();

        $.fn.mediumInsert.insert.deselect();
      });
    },

    /**
    * Set drag and drop evnets
    * @return {void}
    */

    setDragAndDropEvents: function () {
      var that = this,
          dropSuccessful = false,
          dropSort = false,
          dropSortIndex, dropSortParent;

      $(document).on('dragover', 'body', function () {
        $(this).addClass('hover');
      });

      $(document).on('dragend', 'body', function () {
        $(this).removeClass('hover');
      });

      this.$el.on('dragover', '.mediumInsert', function () {
        $(this).addClass('hover');
        $(this).attr('contenteditable', true);
      });

      this.$el.on('dragleave', '.mediumInsert', function () {
        $(this).removeClass('hover');
        $(this).attr('contenteditable', false);
      });

      this.$el.on('dragstart', '.mediumInsert .mediumInsert-images img', function (e) {
        dropSortIndex = $(this).parent().index();
        dropSortParent = $(this).parent().parent().parent().attr('id');
      });

      this.$el.on('dragend', '.mediumInsert .mediumInsert-images img', function (e) {
        if (dropSuccessful === true) {
          if ($(e.originalEvent.target.parentNode).siblings().length === 0) {
            $(e.originalEvent.target.parentNode).parent().parent().removeClass('small');
          }
          $(e.originalEvent.target.parentNode).mouseleave();
          $(e.originalEvent.target.parentNode).remove();
          dropSuccessful = false;
          dropSort = false;
        }
      });

      this.$el.on('dragover', '.mediumInsert .mediumInsert-images img', function (e) {
        e.preventDefault();
      });

      this.$el.on('drop', '.mediumInsert .mediumInsert-images img', function (e) {
        var index, $dragged, finalIndex;

        if (dropSortParent !== $(this).parent().parent().parent().attr('id')) {
          dropSort = false;
          dropSortIndex = dropSortParent = null;
          return;
        }

        index = parseInt(dropSortIndex, 10);

        // Sort
        $dragged = $(this).parent().parent().find('.mediumInsert-images:nth-child('+ (index+1) +')');
        finalIndex = $(this).parent().index();
        if(index < finalIndex) {
          $dragged.insertAfter($(this).parent());
        } else if(index > finalIndex) {
          $dragged.insertBefore($(this).parent());
        }

        $dragged.mouseleave();

        dropSort = true;
        dropSortIndex = null;
      });

      this.$el.on('drop', '.mediumInsert', function (e) {
        var files;

        e.preventDefault();
        $(this).removeClass('hover');
        $('body').removeClass('hover');
        $(this).attr('contenteditable', false);

        files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
          // File upload
          that.uploadFiles($('.mediumInsert-placeholder', this), files);
        } else if (dropSort === true) {
          dropSort = false;
        } else {
          // Image move from block to block
          $('.mediumInsert-placeholder', this).append(''+ e.originalEvent.dataTransfer.getData('text/html') +'');
          $('meta', this).remove();
          dropSuccessful = true;
        }
      });
    }
  };
}(jQuery));
<|endoftext|>


<commit_before>/**
 * @class Oskari.mapframework.bundle.parcel.view.MainView
 *
 * Handles events related to the tool selections.
 * Also, starts the saving flow for the feature data when 'Parcel.SaveDrawingEvent' is received.
 * If saving flow is started, this view shows the save form before continuing to the WFST operation.
 */
Oskari.clazz.define("Oskari.mapframework.bundle.parcel.view.MainView",

/**
 * @method create called automatically on construction
 * @static
 */
function(instance) {
    this.instance = instance;
    this.popupId = 'parcelForm';
    this.form = undefined;
}, {
    /**
     * @method getName
     * @return {String} the name for the component
     */
    getName : function() {
        return 'ParcelMainView';
    },
    /**
     * @method getSandbox
     * @return {Oskari.mapframework.sandbox.Sandbox}
     */
    getSandbox : function() {
        return this.instance.sandbox;
    },
    /**
     * @method init
     * implements Module protocol init method
     */
    init : function() {
    },
    /**
     * @method start
     * implements Module protocol start methdod
     */
    start : function() {
        var me = this;

        var sandbox = this.instance.sandbox;
        sandbox.register(me);
        for (p in me.eventHandlers) {
            sandbox.registerForEventByName(me, p);
        }

        var mapModule = sandbox.findRegisteredModuleInstance('MainMapModule');

        // register plugin for map (drawing for parcels)
        var drawPlugin = Oskari.clazz.create('Oskari.mapframework.bundle.parcel.plugin.DrawPlugin', this.instance);
        mapModule.registerPlugin(drawPlugin);
        mapModule.startPlugin(drawPlugin);
        this.drawPlugin = drawPlugin;
    },
    /**
     * @method update
     * implements Module protocol update method
     */
    stop : function() {
        var sandbox = this.instance.sandbox;
        for (p in this.eventHandlers) {
            sandbox.unregisterFromEventByName(this, p);
        }
        sandbox.unregister(this);
    },
    /**
     * @method onEvent
     * @param {Oskari.mapframework.event.Event} event a Oskari event object
     * Event is handled forwarded to correct #eventHandlers if found or discarded if not.
     */
    onEvent : function(event) {
        var handler = this.eventHandlers[event.getName()];
        if (!handler) {
            return;
        }
        return handler.apply(this, [event]);
    },
    /**
     * @property {Object} eventHandlers
     * @static
     */
    eventHandlers : {
        /**
         * @method Toolbar.ToolSelectedEvent
         * User changed tool -> cancel parcel actions
         * @param {Oskari.mapframework.bundle.toolbar.event.ToolSelectedEvent} event
         */
        'Toolbar.ToolSelectedEvent' : function(event) {
            // changed tool
            this._cleanupPopup();
        },
        /**
         * @method Parcel.SaveDrawingEvent
         * Shows the save form.
         * @param {Oskari.mapframework.bundle.parcel.event.SaveDrawingEvent} event
         */
        'Parcel.SaveDrawingEvent' : function(event) {
            this._handleFinishedDrawingEvent(event);
        }
    },
    /**
     * @method _handleFinishedDrawingEvent
     * @private
     * Shows the saving form.
     * @param {Oskari.mapframework.bundle.parcel.event.FinishedDrawingEvent} event
     */
    _handleFinishedDrawingEvent : function(event) {
        var center = event.getDrawing().geometry.getCentroid();
        var lonlat = {
            lon : center.x,
            lat : center.y
        };
        this.showPlaceForm(lonlat);
    },
    /**
     * @method showPlaceForm
     * Displays a form popup on given location. Prepopulates the form if place is given
     * @param {OpenLayers.LonLat} location location to point with the popup
     */
    showPlaceForm : function(location) {
        var me = this;
        var sandbox = this.instance.sandbox;
        sandbox.postRequestByName('DisableMapKeyboardMovementRequest');
        var loc = this.instance.getLocalization();
        this.form = Oskari.clazz.create('Oskari.mapframework.bundle.parcel.view.PlaceForm', this.instance);

        // Get default value from the feature.
        var defaultValues = {
            place : {}
        };
        var feature = this.drawPlugin.getDrawing();
        var oldpreparcel = this.drawPlugin.getOldPreParcel();
        if (feature) {
            defaultValues.place.area = this.drawPlugin.getParcelGeometry().getArea().toFixed(0);
            if (feature.attributes) {
                defaultValues.place.name = feature.attributes.name+'-M';
                defaultValues.place.parent_property_id = feature.attributes.name;
                defaultValues.place.parent_property_quality = feature.attributes.quality;
            }
            // Override if old values available
            if (oldpreparcel)
            {
                defaultValues.place.id = oldpreparcel.id;
                defaultValues.place.name = oldpreparcel.preparcel_id;
                defaultValues.place.title = oldpreparcel.title;
                defaultValues.place.subtitle = oldpreparcel.subtitle;
                defaultValues.place.desc = oldpreparcel.description;
                defaultValues.place.parent_property_id = oldpreparcel.parent_property_id;
                defaultValues.place.parent_property_quality = oldpreparcel.parent_property_quality;
                defaultValues.place.reporter= oldpreparcel.reporter;
                defaultValues.place.area_unit = oldpreparcel.area_unit;
            }
        }
        // Set the default values for the form.
        this.form.setValues(defaultValues);

        var content = [{
            html : me.form.getForm(),
            useButtons : true,
            primaryButton : loc.buttons.save,
            actions : {}
        }];
        // cancel button
        content[0].actions[loc.buttons.cancel] = function() {
            me._cleanupPopup();
            // ask toolbar to select default tool
            var toolbarRequest = me.instance.sandbox.getRequestBuilder('Toolbar.SelectToolButtonRequest')();
            me.instance.sandbox.request(me, toolbarRequest);
        };
        // print button
        content[0].actions[loc.buttons.print] = function() {
            me._printForm();
        };
        // save button
        content[0].actions[loc.buttons.save] = function() {
            me._saveForm();
        };

        var request = sandbox.getRequestBuilder('InfoBox.ShowInfoBoxRequest')(this.popupId, loc.placeform.title, content, location, true);
        sandbox.request(me.getName(), request);
    },
    /**
     * @method _validateForm
     * Validates form data, returns an object array if any errors.
     * Error objects have field and error properties ({field : 'name', error: 'Name missing'}).
     * @private
     * @param {Object} values form values as returned by Oskari.mapframework.bundle.parcel.view.PlaceForm.getValues()
     * @return {Object[]}
     */
    _validateForm : function(values) {
        var errors = [];
        var loc = this.instance.getLocalization('validation');
        if (!values.place.name) {
            errors.push({
                name : 'name',
                error : loc.placeName
            });
        }
        return errors;
    },
    /**
     * @method __showValidationErrorMessage
     * @private
     * @param {Object[]} errors Error objects have field and error properties ({field : 'name', error: 'Name missing'}).
     */
    _showValidationErrorMessage : function(errors) {
        var loc = this.instance.getLocalization();
        var dialog = Oskari.clazz.create('Oskari.userinterface.component.Popup');
        var okBtn = dialog.createCloseButton(loc.buttons.ok);
        var content = jQuery('

');
        for (var i = 0; i < errors.length; ++i) {
            var row = jQuery('

');
            row.append(errors[i]['error'])
            content.append(row);
        }
        dialog.show(loc.validation.title, content, [okBtn]);
    },
    /**
     * @method _saveForm
     * @private
     * Handles save button on parcels form.
     */
    _saveForm : function() {
        // form not open, nothing to do
        if (!this.form) {
            return;
        }
        var me = this;
        var formValues = this.form.getValues();
        // validation
        var errors = this._validateForm(formValues);
        if (errors.length != 0) {
            this._showValidationErrorMessage(errors);
            return;
        }
        // validation passed -> go save stuff
        this.__savePlace(formValues.place);
    },
    /**
     * @method _printForm
     * @private
     * Handles print button on parcels form.
     */
    _printForm : function() {
    // form not open, nothing to do
    if (!this.form) {
        return;
    }
    var me = this;
    var formValues = this.form.getValues();
    // validation
    var errors = this._validateForm(formValues);
    if (errors.length != 0) {
        this._showValidationErrorMessage(errors);
        return;
    }
    // validation passed -> go save stuff
    this.__printPlace(formValues.place);
},
    /**
     * @method __printPlace
     * Handles print place.
     * @private
     * @param {Object} values place properties
     */
    __printPlace : function(values) {
        var me = this;
        // form not open, nothing to do
        if (!values) {
            // should not happen
            var loc = me.instance.getLocalization('notification')['error'];
            me.instance.showMessage(loc.title, loc.savePlace);
            return;
        }

        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess) {
            if (blnSuccess) {
                me._cleanupPopup();
            }
        }
        var name = values ? values.name : undefined;
        var description = values ? values.desc : undefined;
        this.instance.getService().printPlace(this.drawPlugin.getDrawing(), this.drawPlugin.getFeatureType(), name, description, serviceCallback);
    },
    /**
     * @method __savePlace
     * Handles save place.
     * @private
     * @param {Object} values place properties
     */
    __savePlace : function(values) {
        var me = this;
        // form not open, nothing to do
        if (!values) {
            // should not happen
            var loc = me.instance.getLocalization('notification')['error'];
            me.instance.showMessage(loc.title, loc.savePlace);
            return;
        }
        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess, model, blnNew) {
            if (blnSuccess) {
                me.instance.showMessage('Tallennus onnistui');
                me._cleanupPopup();
            } else {
                // blnNew should always be true since we are adding a preparcel
                if (blnNew) {
                    me.instance.showMessage('Error in inserting preparcel');
                } else {
                    me.instance.showMessage('Error in modifying preparcel');
                }
            }
        }
        this.instance.getService().savePlace(me.drawPlugin, values, serviceCallback);
    },

    /**
     * @method _loadPreParcel
     * Handles preparcel loading.
     * @private
     */
    _loadPreParcel : function() {
        var me = this;
        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess, model) {
            if (blnSuccess) {
                me._cleanupPopup();
            } else {
                me.instance.showMessage('Error in loading preparcel');
            }
        };
        this.instance.getService().loadPreParcel(me.drawPlugin, serviceCallback);
    },

    /**
     * @method _loadPreParcelData
     * Handles geometry data of place loading.
     * @param {String} parcel_id parcel identification
     * @private
     */
    _loadPreParcelData : function(parcel_id) {
        var me = this;
        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess, model) {
            if (blnSuccess) {
                me._cleanupPopup();
            } else {
                me.instance.showMessage('Error in loading preparcel');
            }
        };
        this.instance.getService().loadPreParcelData(parcel_id, me.drawPlugin, serviceCallback);
    },

    /**
     * @method _cleanupPopup
     * Cancels operations:
     * - close popup
     * - destroy form
     * @private
     */
    _cleanupPopup : function() {
        // form not open, nothing to do
        if (!this.form) {
            return;
        }
        var sandbox = this.instance.sandbox;
        var request = sandbox.getRequestBuilder('InfoBox.HideInfoBoxRequest')(this.popupId);
        sandbox.request(this, request);
        this.form.destroy();
        this.form = undefined;
        sandbox.postRequestByName('EnableMapKeyboardMovementRequest');
    }
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
    protocol : ['Oskari.mapframework.module.Module']
});
<commit_msg>[AH-613] preparcel edit<commit_after>/**
 * @class Oskari.mapframework.bundle.parcel.view.MainView
 *
 * Handles events related to the tool selections.
 * Also, starts the saving flow for the feature data when 'Parcel.SaveDrawingEvent' is received.
 * If saving flow is started, this view shows the save form before continuing to the WFST operation.
 */
Oskari.clazz.define("Oskari.mapframework.bundle.parcel.view.MainView",

/**
 * @method create called automatically on construction
 * @static
 */
function(instance) {
    this.instance = instance;
    this.popupId = 'parcelForm';
    this.form = undefined;
}, {
    /**
     * @method getName
     * @return {String} the name for the component
     */
    getName : function() {
        return 'ParcelMainView';
    },
    /**
     * @method getSandbox
     * @return {Oskari.mapframework.sandbox.Sandbox}
     */
    getSandbox : function() {
        return this.instance.sandbox;
    },
    /**
     * @method init
     * implements Module protocol init method
     */
    init : function() {
    },
    /**
     * @method start
     * implements Module protocol start methdod
     */
    start : function() {
        var me = this;

        var sandbox = this.instance.sandbox;
        sandbox.register(me);
        for (p in me.eventHandlers) {
            sandbox.registerForEventByName(me, p);
        }

        var mapModule = sandbox.findRegisteredModuleInstance('MainMapModule');

        // register plugin for map (drawing for parcels)
        var drawPlugin = Oskari.clazz.create('Oskari.mapframework.bundle.parcel.plugin.DrawPlugin', this.instance);
        mapModule.registerPlugin(drawPlugin);
        mapModule.startPlugin(drawPlugin);
        this.drawPlugin = drawPlugin;
    },
    /**
     * @method update
     * implements Module protocol update method
     */
    stop : function() {
        var sandbox = this.instance.sandbox;
        for (p in this.eventHandlers) {
            sandbox.unregisterFromEventByName(this, p);
        }
        sandbox.unregister(this);
    },
    /**
     * @method onEvent
     * @param {Oskari.mapframework.event.Event} event a Oskari event object
     * Event is handled forwarded to correct #eventHandlers if found or discarded if not.
     */
    onEvent : function(event) {
        var handler = this.eventHandlers[event.getName()];
        if (!handler) {
            return;
        }
        return handler.apply(this, [event]);
    },
    /**
     * @property {Object} eventHandlers
     * @static
     */
    eventHandlers : {
        /**
         * @method Toolbar.ToolSelectedEvent
         * User changed tool -> cancel parcel actions
         * @param {Oskari.mapframework.bundle.toolbar.event.ToolSelectedEvent} event
         */
        'Toolbar.ToolSelectedEvent' : function(event) {
            // changed tool
            this._cleanupPopup();
        },
        /**
         * @method Parcel.SaveDrawingEvent
         * Shows the save form.
         * @param {Oskari.mapframework.bundle.parcel.event.SaveDrawingEvent} event
         */
        'Parcel.SaveDrawingEvent' : function(event) {
            this._handleFinishedDrawingEvent(event);
        }
    },
    /**
     * @method _handleFinishedDrawingEvent
     * @private
     * Shows the saving form.
     * @param {Oskari.mapframework.bundle.parcel.event.FinishedDrawingEvent} event
     */
    _handleFinishedDrawingEvent : function(event) {
        var center = event.getDrawing().geometry.getCentroid();
        var lonlat = {
            lon : center.x,
            lat : center.y
        };
        this.showPlaceForm(lonlat);
    },
    /**
     * @method showPlaceForm
     * Displays a form popup on given location. Prepopulates the form if place is given
     * @param {OpenLayers.LonLat} location location to point with the popup
     */
    showPlaceForm : function(location) {
        var me = this;
        var sandbox = this.instance.sandbox;
        sandbox.postRequestByName('DisableMapKeyboardMovementRequest');
        var loc = this.instance.getLocalization();
        this.form = Oskari.clazz.create('Oskari.mapframework.bundle.parcel.view.PlaceForm', this.instance);

        // Get default value from the feature.
        var defaultValues = {
            place : {}
        };
        var feature = this.drawPlugin.getDrawing();
        var oldpreparcel = this.drawPlugin.getOldPreParcel();
        if (feature) {
            defaultValues.place.area = this.drawPlugin.getParcelGeometry().getArea().toFixed(0);
            if (feature.attributes) {
                defaultValues.place.name = feature.attributes.name+'-K';
                defaultValues.place.parent_property_id = feature.attributes.name;
                defaultValues.place.parent_property_quality = feature.attributes.quality;
            }
            // Override if old values available
            if (oldpreparcel)
            {
                defaultValues.place.id = oldpreparcel.id;
                defaultValues.place.name = oldpreparcel.preparcel_id;
                defaultValues.place.title = oldpreparcel.title;
                defaultValues.place.subtitle = oldpreparcel.subtitle;
                defaultValues.place.desc = oldpreparcel.description;
                defaultValues.place.parent_property_id = oldpreparcel.parent_property_id;
                defaultValues.place.parent_property_quality = oldpreparcel.parent_property_quality;
                defaultValues.place.reporter= oldpreparcel.reporter;
                defaultValues.place.area_unit = oldpreparcel.area_unit;
            }
        }
        // Set the default values for the form.
        this.form.setValues(defaultValues);

        var content = [{
            html : me.form.getForm(),
            useButtons : true,
            primaryButton : loc.buttons.save,
            actions : {}
        }];
        // cancel button
        content[0].actions[loc.buttons.cancel] = function() {
            me._cleanupPopup();
            // ask toolbar to select default tool
            var toolbarRequest = me.instance.sandbox.getRequestBuilder('Toolbar.SelectToolButtonRequest')();
            me.instance.sandbox.request(me, toolbarRequest);
        };
        // print button
        content[0].actions[loc.buttons.print] = function() {
            me._printForm();
        };
        // save button
        content[0].actions[loc.buttons.save] = function() {
            me._saveForm();
        };

        var request = sandbox.getRequestBuilder('InfoBox.ShowInfoBoxRequest')(this.popupId, loc.placeform.title, content, location, true);
        sandbox.request(me.getName(), request);
    },
    /**
     * @method _validateForm
     * Validates form data, returns an object array if any errors.
     * Error objects have field and error properties ({field : 'name', error: 'Name missing'}).
     * @private
     * @param {Object} values form values as returned by Oskari.mapframework.bundle.parcel.view.PlaceForm.getValues()
     * @return {Object[]}
     */
    _validateForm : function(values) {
        var errors = [];
        var loc = this.instance.getLocalization('validation');
        if (!values.place.name) {
            errors.push({
                name : 'name',
                error : loc.placeName
            });
        }
        return errors;
    },
    /**
     * @method __showValidationErrorMessage
     * @private
     * @param {Object[]} errors Error objects have field and error properties ({field : 'name', error: 'Name missing'}).
     */
    _showValidationErrorMessage : function(errors) {
        var loc = this.instance.getLocalization();
        var dialog = Oskari.clazz.create('Oskari.userinterface.component.Popup');
        var okBtn = dialog.createCloseButton(loc.buttons.ok);
        var content = jQuery('

');
        for (var i = 0; i < errors.length; ++i) {
            var row = jQuery('

');
            row.append(errors[i]['error'])
            content.append(row);
        }
        dialog.show(loc.validation.title, content, [okBtn]);
    },
    /**
     * @method _saveForm
     * @private
     * Handles save button on parcels form.
     */
    _saveForm : function() {
        // form not open, nothing to do
        if (!this.form) {
            return;
        }
        var me = this;
        var formValues = this.form.getValues();
        // validation
        var errors = this._validateForm(formValues);
        if (errors.length != 0) {
            this._showValidationErrorMessage(errors);
            return;
        }
        // validation passed -> go save stuff
        this.__savePlace(formValues.place);
    },
    /**
     * @method _printForm
     * @private
     * Handles print button on parcels form.
     */
    _printForm : function() {
    // form not open, nothing to do
    if (!this.form) {
        return;
    }
    var me = this;
    var formValues = this.form.getValues();
    // validation
    var errors = this._validateForm(formValues);
    if (errors.length != 0) {
        this._showValidationErrorMessage(errors);
        return;
    }
    // validation passed -> go save stuff
    this.__printPlace(formValues.place);
},
    /**
     * @method __printPlace
     * Handles print place.
     * @private
     * @param {Object} values place properties
     */
    __printPlace : function(values) {
        var me = this;
        // form not open, nothing to do
        if (!values) {
            // should not happen
            var loc = me.instance.getLocalization('notification')['error'];
            me.instance.showMessage(loc.title, loc.savePlace);
            return;
        }

        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess) {
            if (blnSuccess) {
                me._cleanupPopup();
            }
        }
        var name = values ? values.name : undefined;
        var description = values ? values.desc : undefined;
        this.instance.getService().printPlace(this.drawPlugin.getDrawing(), this.drawPlugin.getFeatureType(), name, description, serviceCallback);
    },
    /**
     * @method __savePlace
     * Handles save place.
     * @private
     * @param {Object} values place properties
     */
    __savePlace : function(values) {
        var me = this;
        // form not open, nothing to do
        if (!values) {
            // should not happen
            var loc = me.instance.getLocalization('notification')['error'];
            me.instance.showMessage(loc.title, loc.savePlace);
            return;
        }
        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess, model, blnNew) {
            if (blnSuccess) {
                me.instance.showMessage('Tallennus onnistui');
                me._cleanupPopup();
            } else {
                // blnNew should always be true since we are adding a preparcel
                if (blnNew) {
                    me.instance.showMessage('Error in inserting preparcel');
                } else {
                    me.instance.showMessage('Error in modifying preparcel');
                }
            }
        }
        this.instance.getService().savePlace(me.drawPlugin, values, serviceCallback);
    },

    /**
     * @method _loadPreParcel
     * Handles preparcel loading.
     * @private
     */
    _loadPreParcel : function() {
        var me = this;
        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess, model) {
            if (blnSuccess) {
                me._cleanupPopup();
            } else {
                me.instance.showMessage('Error in loading preparcel');
            }
        };
        this.instance.getService().loadPreParcel(me.drawPlugin, serviceCallback);
    },

    /**
     * @method _loadPreParcelData
     * Handles geometry data of place loading.
     * @param {String} parcel_id parcel identification
     * @private
     */
    _loadPreParcelData : function(parcel_id) {
        var me = this;
        // Callback handles the end of the asynchronous operation.
        var serviceCallback = function(blnSuccess, model) {
            if (blnSuccess) {
                me._cleanupPopup();
            } else {
                me.instance.showMessage('Error in loading preparcel');
            }
        };
        this.instance.getService().loadPreParcelData(parcel_id, me.drawPlugin, serviceCallback);
    },

    /**
     * @method _cleanupPopup
     * Cancels operations:
     * - close popup
     * - destroy form
     * @private
     */
    _cleanupPopup : function() {
        // form not open, nothing to do
        if (!this.form) {
            return;
        }
        var sandbox = this.instance.sandbox;
        var request = sandbox.getRequestBuilder('InfoBox.HideInfoBoxRequest')(this.popupId);
        sandbox.request(this, request);
        this.form.destroy();
        this.form = undefined;
        sandbox.postRequestByName('EnableMapKeyboardMovementRequest');
    }
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
    protocol : ['Oskari.mapframework.module.Module']
});
<|endoftext|>


<commit_before>import {Emitter} from 'event-kit';

import {nullFile} from './file';
import Patch, {COLLAPSED} from './patch';
import {toGitPathSep} from '../../helpers';

export default class FilePatch {
  static createNull() {
    return new this(nullFile, nullFile, Patch.createNull());
  }

  static createHiddenFilePatch(oldFile, newFile, marker, renderStatus, showFn) {
    return new this(oldFile, newFile, Patch.createHiddenPatch(marker, renderStatus, showFn));
  }

  constructor(oldFile, newFile, patch) {
    this.oldFile = oldFile;
    this.newFile = newFile;
    this.patch = patch;

    this.emitter = new Emitter();
  }

  isPresent() {
    return this.oldFile.isPresent() || this.newFile.isPresent() || this.patch.isPresent();
  }

  getRenderStatus() {
    return this.patch.getRenderStatus();
  }

  getOldFile() {
    return this.oldFile;
  }

  getNewFile() {
    return this.newFile;
  }

  getPatch() {
    return this.patch;
  }

  getMarker() {
    return this.getPatch().getMarker();
  }

  getStartRange() {
    return this.getPatch().getStartRange();
  }

  getOldPath() {
    return this.getOldFile().getPath();
  }

  getNewPath() {
    return this.getNewFile().getPath();
  }

  getOldMode() {
    return this.getOldFile().getMode();
  }

  getNewMode() {
    return this.getNewFile().getMode();
  }

  getOldSymlink() {
    return this.getOldFile().getSymlink();
  }

  getNewSymlink() {
    return this.getNewFile().getSymlink();
  }

  getFirstChangeRange() {
    return this.getPatch().getFirstChangeRange();
  }

  getMaxLineNumberWidth() {
    return this.getPatch().getMaxLineNumberWidth();
  }

  containsRow(row) {
    return this.getPatch().containsRow(row);
  }

  didChangeExecutableMode() {
    if (!this.oldFile.isPresent() || !this.newFile.isPresent()) {
      return false;
    }

    return this.oldFile.isExecutable() && !this.newFile.isExecutable() ||
      !this.oldFile.isExecutable() && this.newFile.isExecutable();
  }

  hasSymlink() {
    return Boolean(this.getOldFile().getSymlink() || this.getNewFile().getSymlink());
  }

  hasTypechange() {
    if (!this.oldFile.isPresent() || !this.newFile.isPresent()) {
      return false;
    }

    return this.oldFile.isSymlink() && !this.newFile.isSymlink() ||
      !this.oldFile.isSymlink() && this.newFile.isSymlink();
  }

  getPath() {
    return this.getOldPath() || this.getNewPath();
  }

  getStatus() {
    return this.getPatch().getStatus();
  }

  getHunks() {
    return this.getPatch().getHunks();
  }

  updateMarkers(map) {
    return this.patch.updateMarkers(map);
  }

  triggerCollapseIn(patchBuffer) {
    if (!this.patch.getRenderStatus().isVisible()) {
      return false;
    }

    const oldPatch = this.patch;
    const position = oldPatch.getRange().start.copy();
    const {patchBuffer: subPatchBuffer, markerMap} = patchBuffer.extractPatchBuffer(oldPatch.getRange());
    oldPatch.destroyMarkers();
    oldPatch.updateMarkers(markerMap);

    // Delete the separating newline after the collapsing patch, if any.
    patchBuffer.getBuffer().delete([position, [position.row + 1, 0]]);

    const patchMarker = patchBuffer.markPosition(Patch.layerName, position, {invalidate: 'never', exclude: true});
    this.patch = Patch.createHiddenPatch(patchMarker, COLLAPSED, () => {
      return {patch: oldPatch, patchBuffer: subPatchBuffer};
    });

    this.didChangeRenderStatus();
    return true;
  }

  triggerExpandIn(patchBuffer, {before, after}) {
    if (this.patch.getRenderStatus().isVisible()) {
      return false;
    }

    const {patch: nextPatch, patchBuffer: subPatchBuffer} = this.patch.show();
    const atEnd = this.patch.getInsertionPoint().isEqual(patchBuffer.getBuffer().getEndPosition());

    // Insert a newline *before* the expanding patch if we're inserting at the end, because newlines separate patches
    // and the buffer doesn't end with one. Insert a newline *after* the expanding patch if we're inserting internally,
    // because the insertion point is after the existing newline between the surrounding patches.

    patchBuffer
      .createInserterAt(this.patch.getInsertionPoint())
      .keepBefore(before)
      .keepAfter(after)
      .insert(atEnd ? '\n' : '')
      .insertPatchBuffer(subPatchBuffer, {callback: map => nextPatch.updateMarkers(map)})
      .insert(atEnd ? '' : '\n')
      .apply();

    this.patch.destroyMarkers();
    this.patch = nextPatch;
    this.didChangeRenderStatus();
    return true;
  }

  didChangeRenderStatus() {
    return this.emitter.emit('change-render-status', this);
  }

  onDidChangeRenderStatus(callback) {
    return this.emitter.on('change-render-status', callback);
  }

  clone(opts = {}) {
    return new this.constructor(
      opts.oldFile !== undefined ? opts.oldFile : this.oldFile,
      opts.newFile !== undefined ? opts.newFile : this.newFile,
      opts.patch !== undefined ? opts.patch : this.patch,
    );
  }

  getStartingMarkers() {
    return this.patch.getStartingMarkers();
  }

  getEndingMarkers() {
    return this.patch.getEndingMarkers();
  }

  buildStagePatchForLines(originalBuffer, nextLayeredBuffer, selectedLineSet) {
    let newFile = this.getNewFile();
    if (this.getStatus() === 'deleted') {
      if (
        this.patch.getChangedLineCount() === selectedLineSet.size &&
        Array.from(selectedLineSet, row => this.patch.containsRow(row)).every(Boolean)
      ) {
        // Whole file deletion staged.
        newFile = nullFile;
      } else {
        // Partial file deletion, which becomes a modification.
        newFile = this.getOldFile();
      }
    }

    const patch = this.patch.buildStagePatchForLines(
      originalBuffer,
      nextLayeredBuffer,
      selectedLineSet,
    );
    return this.clone({newFile, patch});
  }

  buildUnstagePatchForLines(originalBuffer, nextLayeredBuffer, selectedLineSet) {
    const nonNullFile = this.getNewFile().isPresent() ? this.getNewFile() : this.getOldFile();
    let oldFile = this.getNewFile();
    let newFile = nonNullFile;

    if (this.getStatus() === 'added') {
      if (
        selectedLineSet.size === this.patch.getChangedLineCount() &&
        Array.from(selectedLineSet, row => this.patch.containsRow(row)).every(Boolean)
      ) {
        // Ensure that newFile is null if the patch is an addition because we're deleting the entire file from the
        // index. If a symlink was deleted and replaced by a non-symlink file, we don't want the symlink entry to muck
        // up the patch.
        oldFile = nonNullFile;
        newFile = nullFile;
      }
    } else if (this.getStatus() === 'deleted') {
      if (
        selectedLineSet.size === this.patch.getChangedLineCount() &&
        Array.from(selectedLineSet, row => this.patch.containsRow(row)).every(Boolean)
      ) {
        oldFile = nullFile;
        newFile = nonNullFile;
      }
    }

    const patch = this.patch.buildUnstagePatchForLines(
      originalBuffer,
      nextLayeredBuffer,
      selectedLineSet,
    );
    return this.clone({oldFile, newFile, patch});
  }

  toStringIn(buffer) {
    if (!this.isPresent()) {
      return '';
    }

    if (this.hasTypechange()) {
      const left = this.clone({
        newFile: nullFile,
        patch: this.getOldSymlink() ? this.getPatch().clone({status: 'deleted'}) : this.getPatch(),
      });

      const right = this.clone({
        oldFile: nullFile,
        patch: this.getNewSymlink() ? this.getPatch().clone({status: 'added'}) : this.getPatch(),
      });

      return left.toStringIn(buffer) + right.toStringIn(buffer);
    } else if (this.getStatus() === 'added' && this.getNewFile().isSymlink()) {
      const symlinkPath = this.getNewSymlink();
      return this.getHeaderString() + `@@ -0,0 +1 @@\n+${symlinkPath}\n\\ No newline at end of file\n`;
    } else if (this.getStatus() === 'deleted' && this.getOldFile().isSymlink()) {
      const symlinkPath = this.getOldSymlink();
      return this.getHeaderString() + `@@ -1 +0,0 @@\n-${symlinkPath}\n\\ No newline at end of file\n`;
    } else {
      return this.getHeaderString() + this.getPatch().toStringIn(buffer);
    }
  }

  /*
   * Construct a String containing diagnostic information about the internal state of this FilePatch.
   */
  inspect(opts = {}) {
    const options = {
      indent: 0,
      ...opts,
    };

    let indentation = '';
    for (let i = 0; i < options.indent; i++) {
      indentation += ' ';
    }

    let inspectString = `${indentation}(FilePatch `;
    if (this.getOldPath() !== this.getNewPath()) {
      inspectString += `oldPath=${this.getOldPath()} newPath=${this.getNewPath()}`;
    } else {
      inspectString += `path=${this.getPath()}`;
    }
    inspectString += '\n';

    inspectString += this.patch.inspect({indent: options.indent + 2});

    inspectString += `${indentation})\n`;
    return inspectString;
  }

  getHeaderString() {
    const fromPath = this.getOldPath() || this.getNewPath();
    const toPath = this.getNewPath() || this.getOldPath();
    let header = `diff --git a/${toGitPathSep(fromPath)} b/${toGitPathSep(toPath)}`;
    header += '\n';
    if (this.getStatus() === 'added') {
      header += `new file mode ${this.getNewMode()}`;
      header += '\n';
    } else if (this.getStatus() === 'deleted') {
      header += `deleted file mode ${this.getOldMode()}`;
      header += '\n';
    }
    header += this.getOldPath() ? `--- a/${toGitPathSep(this.getOldPath())}` : '--- /dev/null';
    header += '\n';
    header += this.getNewPath() ? `+++ b/${toGitPathSep(this.getNewPath())}` : '+++ /dev/null';
    header += '\n';
    return header;
  }
}
<commit_msg>"exclude" :point_right: "exclusive"<commit_after>import {Emitter} from 'event-kit';

import {nullFile} from './file';
import Patch, {COLLAPSED} from './patch';
import {toGitPathSep} from '../../helpers';

export default class FilePatch {
  static createNull() {
    return new this(nullFile, nullFile, Patch.createNull());
  }

  static createHiddenFilePatch(oldFile, newFile, marker, renderStatus, showFn) {
    return new this(oldFile, newFile, Patch.createHiddenPatch(marker, renderStatus, showFn));
  }

  constructor(oldFile, newFile, patch) {
    this.oldFile = oldFile;
    this.newFile = newFile;
    this.patch = patch;

    this.emitter = new Emitter();
  }

  isPresent() {
    return this.oldFile.isPresent() || this.newFile.isPresent() || this.patch.isPresent();
  }

  getRenderStatus() {
    return this.patch.getRenderStatus();
  }

  getOldFile() {
    return this.oldFile;
  }

  getNewFile() {
    return this.newFile;
  }

  getPatch() {
    return this.patch;
  }

  getMarker() {
    return this.getPatch().getMarker();
  }

  getStartRange() {
    return this.getPatch().getStartRange();
  }

  getOldPath() {
    return this.getOldFile().getPath();
  }

  getNewPath() {
    return this.getNewFile().getPath();
  }

  getOldMode() {
    return this.getOldFile().getMode();
  }

  getNewMode() {
    return this.getNewFile().getMode();
  }

  getOldSymlink() {
    return this.getOldFile().getSymlink();
  }

  getNewSymlink() {
    return this.getNewFile().getSymlink();
  }

  getFirstChangeRange() {
    return this.getPatch().getFirstChangeRange();
  }

  getMaxLineNumberWidth() {
    return this.getPatch().getMaxLineNumberWidth();
  }

  containsRow(row) {
    return this.getPatch().containsRow(row);
  }

  didChangeExecutableMode() {
    if (!this.oldFile.isPresent() || !this.newFile.isPresent()) {
      return false;
    }

    return this.oldFile.isExecutable() && !this.newFile.isExecutable() ||
      !this.oldFile.isExecutable() && this.newFile.isExecutable();
  }

  hasSymlink() {
    return Boolean(this.getOldFile().getSymlink() || this.getNewFile().getSymlink());
  }

  hasTypechange() {
    if (!this.oldFile.isPresent() || !this.newFile.isPresent()) {
      return false;
    }

    return this.oldFile.isSymlink() && !this.newFile.isSymlink() ||
      !this.oldFile.isSymlink() && this.newFile.isSymlink();
  }

  getPath() {
    return this.getOldPath() || this.getNewPath();
  }

  getStatus() {
    return this.getPatch().getStatus();
  }

  getHunks() {
    return this.getPatch().getHunks();
  }

  updateMarkers(map) {
    return this.patch.updateMarkers(map);
  }

  triggerCollapseIn(patchBuffer) {
    if (!this.patch.getRenderStatus().isVisible()) {
      return false;
    }

    const oldPatch = this.patch;
    const position = oldPatch.getRange().start.copy();
    const {patchBuffer: subPatchBuffer, markerMap} = patchBuffer.extractPatchBuffer(oldPatch.getRange());
    oldPatch.destroyMarkers();
    oldPatch.updateMarkers(markerMap);

    // Delete the separating newline after the collapsing patch, if any.
    patchBuffer.getBuffer().delete([position, [position.row + 1, 0]]);

    const patchMarker = patchBuffer.markPosition(Patch.layerName, position, {invalidate: 'never', exclusive: true});
    this.patch = Patch.createHiddenPatch(patchMarker, COLLAPSED, () => {
      return {patch: oldPatch, patchBuffer: subPatchBuffer};
    });

    this.didChangeRenderStatus();
    return true;
  }

  triggerExpandIn(patchBuffer, {before, after}) {
    if (this.patch.getRenderStatus().isVisible()) {
      return false;
    }

    const {patch: nextPatch, patchBuffer: subPatchBuffer} = this.patch.show();
    const atEnd = this.patch.getInsertionPoint().isEqual(patchBuffer.getBuffer().getEndPosition());

    // Insert a newline *before* the expanding patch if we're inserting at the end, because newlines separate patches
    // and the buffer doesn't end with one. Insert a newline *after* the expanding patch if we're inserting internally,
    // because the insertion point is after the existing newline between the surrounding patches.

    patchBuffer
      .createInserterAt(this.patch.getInsertionPoint())
      .keepBefore(before)
      .keepAfter(after)
      .insert(atEnd ? '\n' : '')
      .insertPatchBuffer(subPatchBuffer, {callback: map => nextPatch.updateMarkers(map)})
      .insert(atEnd ? '' : '\n')
      .apply();

    this.patch.destroyMarkers();
    this.patch = nextPatch;
    this.didChangeRenderStatus();
    return true;
  }

  didChangeRenderStatus() {
    return this.emitter.emit('change-render-status', this);
  }

  onDidChangeRenderStatus(callback) {
    return this.emitter.on('change-render-status', callback);
  }

  clone(opts = {}) {
    return new this.constructor(
      opts.oldFile !== undefined ? opts.oldFile : this.oldFile,
      opts.newFile !== undefined ? opts.newFile : this.newFile,
      opts.patch !== undefined ? opts.patch : this.patch,
    );
  }

  getStartingMarkers() {
    return this.patch.getStartingMarkers();
  }

  getEndingMarkers() {
    return this.patch.getEndingMarkers();
  }

  buildStagePatchForLines(originalBuffer, nextLayeredBuffer, selectedLineSet) {
    let newFile = this.getNewFile();
    if (this.getStatus() === 'deleted') {
      if (
        this.patch.getChangedLineCount() === selectedLineSet.size &&
        Array.from(selectedLineSet, row => this.patch.containsRow(row)).every(Boolean)
      ) {
        // Whole file deletion staged.
        newFile = nullFile;
      } else {
        // Partial file deletion, which becomes a modification.
        newFile = this.getOldFile();
      }
    }

    const patch = this.patch.buildStagePatchForLines(
      originalBuffer,
      nextLayeredBuffer,
      selectedLineSet,
    );
    return this.clone({newFile, patch});
  }

  buildUnstagePatchForLines(originalBuffer, nextLayeredBuffer, selectedLineSet) {
    const nonNullFile = this.getNewFile().isPresent() ? this.getNewFile() : this.getOldFile();
    let oldFile = this.getNewFile();
    let newFile = nonNullFile;

    if (this.getStatus() === 'added') {
      if (
        selectedLineSet.size === this.patch.getChangedLineCount() &&
        Array.from(selectedLineSet, row => this.patch.containsRow(row)).every(Boolean)
      ) {
        // Ensure that newFile is null if the patch is an addition because we're deleting the entire file from the
        // index. If a symlink was deleted and replaced by a non-symlink file, we don't want the symlink entry to muck
        // up the patch.
        oldFile = nonNullFile;
        newFile = nullFile;
      }
    } else if (this.getStatus() === 'deleted') {
      if (
        selectedLineSet.size === this.patch.getChangedLineCount() &&
        Array.from(selectedLineSet, row => this.patch.containsRow(row)).every(Boolean)
      ) {
        oldFile = nullFile;
        newFile = nonNullFile;
      }
    }

    const patch = this.patch.buildUnstagePatchForLines(
      originalBuffer,
      nextLayeredBuffer,
      selectedLineSet,
    );
    return this.clone({oldFile, newFile, patch});
  }

  toStringIn(buffer) {
    if (!this.isPresent()) {
      return '';
    }

    if (this.hasTypechange()) {
      const left = this.clone({
        newFile: nullFile,
        patch: this.getOldSymlink() ? this.getPatch().clone({status: 'deleted'}) : this.getPatch(),
      });

      const right = this.clone({
        oldFile: nullFile,
        patch: this.getNewSymlink() ? this.getPatch().clone({status: 'added'}) : this.getPatch(),
      });

      return left.toStringIn(buffer) + right.toStringIn(buffer);
    } else if (this.getStatus() === 'added' && this.getNewFile().isSymlink()) {
      const symlinkPath = this.getNewSymlink();
      return this.getHeaderString() + `@@ -0,0 +1 @@\n+${symlinkPath}\n\\ No newline at end of file\n`;
    } else if (this.getStatus() === 'deleted' && this.getOldFile().isSymlink()) {
      const symlinkPath = this.getOldSymlink();
      return this.getHeaderString() + `@@ -1 +0,0 @@\n-${symlinkPath}\n\\ No newline at end of file\n`;
    } else {
      return this.getHeaderString() + this.getPatch().toStringIn(buffer);
    }
  }

  /*
   * Construct a String containing diagnostic information about the internal state of this FilePatch.
   */
  inspect(opts = {}) {
    const options = {
      indent: 0,
      ...opts,
    };

    let indentation = '';
    for (let i = 0; i < options.indent; i++) {
      indentation += ' ';
    }

    let inspectString = `${indentation}(FilePatch `;
    if (this.getOldPath() !== this.getNewPath()) {
      inspectString += `oldPath=${this.getOldPath()} newPath=${this.getNewPath()}`;
    } else {
      inspectString += `path=${this.getPath()}`;
    }
    inspectString += '\n';

    inspectString += this.patch.inspect({indent: options.indent + 2});

    inspectString += `${indentation})\n`;
    return inspectString;
  }

  getHeaderString() {
    const fromPath = this.getOldPath() || this.getNewPath();
    const toPath = this.getNewPath() || this.getOldPath();
    let header = `diff --git a/${toGitPathSep(fromPath)} b/${toGitPathSep(toPath)}`;
    header += '\n';
    if (this.getStatus() === 'added') {
      header += `new file mode ${this.getNewMode()}`;
      header += '\n';
    } else if (this.getStatus() === 'deleted') {
      header += `deleted file mode ${this.getOldMode()}`;
      header += '\n';
    }
    header += this.getOldPath() ? `--- a/${toGitPathSep(this.getOldPath())}` : '--- /dev/null';
    header += '\n';
    header += this.getNewPath() ? `+++ b/${toGitPathSep(this.getNewPath())}` : '+++ /dev/null';
    header += '\n';
    return header;
  }
}
<|endoftext|>


<commit_before>const deezerDef = require('../music_services/deezerDef');
const eliteDef = deezerDef.init(true);

module.exports = eliteDef;
<commit_msg>Delete eliteDef.js<commit_after><|endoftext|>


<commit_before>'use strict';

var Form = function(controller) {
  this._hstsPreload = new HSTSPreload();
  this._controller = new controller(this._hstsPreload);

  this._urlParam = new URLParam();
  this._view = new PreloadView(this._controller, this.submitDomain.bind(this), this._urlParam);

  var domainParam = this._urlParam.get();
  if (domainParam) {
    var domain = extractDomain(domainParam);

    if (domain != domainParam) {
      this._view.setDomain(domain);
      this._view.clickCheck();
    } else {
      console.log('From URL parameter:', domain);
      $('#domain').value = domain;
      this.checkDomain(domain);
    }
  }
};

Form.prototype = {
  checkDomain: function(domain) {
    this._view.clearDomainSpecificElements();
    this._view.showWaiting(domain);

    if (!domain) {
      console.log('checkDomain called with empty domain');
      $('#result-waiting').classList.add('hidden');
      return;
    }

    this._currentResultsDomain = '';

    Promise
        .all([
          this._hstsPreload.status(domain),
          this._controller.eligible(domain)
        ])
        .then(
            function(values) {
              this.handleResults(domain, values[0], values[1]);
            }.bind(this),
            function() {
              // TODO: handle failure better.
              $('#result').classList.remove('hidden');
              $('#result-waiting').classList.add('hidden');
            });
  },

  submitDomain: function() {
    var domain = this.domainToSubmit;

    this._controller.submit(domain).then(function(issues) {
      if (issues.errors.length == 0) {
        $('#submit-success').show();
          if ($('#ssl-labs-link')) {
            $('#ssl-labs-link')
                .href = 'https://www.ssllabs.com/ssltest/analyze.html?d=' + domain;
          }
      } else {
        this._view.setTheme('theme-red');
        $('#submit-failure').show();
        console.log(issues);
      }
    }.bind(this));
  },

  handleResults: function(domain, status, issues) {
    if (domain !== this._view.currentDomain()) {
      return;
    }
    if (this._currentResultsDomain === domain) {
      return;
    }
    this._currentResultsDomain = domain;

    if (domain !== this._view.currentDomain()) {
      console.log('Outdated result.');
      return;
    }

    this._view.clearStatus();
    this._view.clearSummary();
    var showForm = this._controller.showResults(this._view, domain, issues, status);
    this._view.hideWaiting();

    if (showForm) {
      this.domainToSubmit = domain;
      this._view.showSubmission(domain);
    }
  }
};

function statusString(status, issues, domain) {
  switch (status.status) {
    case 'unknown':
      return 'Status: ' + domain + ' is not preloaded.';
    case 'pending':
      return 'Status: ' + domain + ' is pending submission to the preload list.';
    case 'preloaded':
      if (status.bulk) {
        switch (worstIssues(issues)) {
          case 'warnings':
            return 'Status: ' + domain + ' is currently preloaded, but has the following issues:';
          case 'errors':
            return 'Status: ' + domain + ' is currently preloaded, but no longer meets the requirements. It may be at risk of removal.';
          default:
            return 'Status: ' + domain + ' is currently preloaded.';
        }
      } else {
        return 'Status: ' + domain + ' is currently preloaded.';
      }
      break;

    case 'rejected':
      if (status.message) {
        return 'Status: ' + domain +
          ' was previously rejected from the preload list for the following reason: ' +
          status.message;
      } else {
        return 'Status: ' + domain +
          ' was previously rejected from the preload list.'
      }
    case 'pending-removal':
      return 'Status: ' + domain +
          ' was previously submitted to the preload list, but is now pending removal.';
    case 'removed':
      return 'Status: ' + domain +
          ' was previously submitted to the preload list, but has been removed.';
    default:
      return 'Cannot determine preload status.';
  }
};

function worstIssues(issues) {
  if (issues.errors.length == 0) {
    if (issues.warnings.length == 0) {
      return 'none';
    } else {
      return 'warnings';
    }
  } else {
    return 'errors';
  }
}

var PreloadController = function(hstsPreload) {
  this._hstsPreload = hstsPreload;
}

PreloadController.prototype = {
  formHasCheckboxes: function() {
    return true;
  },

  eligible: function(domain) {
    return this._hstsPreload.preloadable(domain);
  },

  submit: function(domain) {
    return this._hstsPreload.submit(domain);
  },

  submitButtonString: function(domain) {
    return 'Submit ' + domain + ' to the HSTS preload list';
  },

  showPending: function(view, domain, issues) {
    switch (worstIssues(issues)) {
      case 'none':
        view.setStatus(
            'Status: ' + domain +
            ' is pending submission to the preload list.');
        view.setTheme('theme-green');
        break;
      case 'warnings':
        view.setStatus(
            'Status: ' + domain +
            ' is pending submission to the preload list.');
        view.setSummary(
            'However, it still has the following issues, which we recommend fixing:');
        view.setTheme('theme-yellow');
        view.showIssues(issues);
        break;
      case 'errors':
        view.setStatus(
            'Status: ' + domain +
            ' was recently submitted to the preload list.');
        view.setSummary(
            'However, ' + domain +
            ' has changed its behaviour since it was submitted, and will not be added to the official preload list unless the errors below are resolved:');
        view.setTheme('theme-red');
        view.showIssues(issues);
        break;
    }
  },

  showPreloadElibigility: function(view, domain, issues) {
    switch (worstIssues(issues)) {
      case 'none':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for the HSTS preload list.');
        view.setTheme('theme-green');
        return true;
        break;
      case 'warnings':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for preloading, although we recommend fixing the following warnings:');
        view.setTheme('theme-yellow');
        return true;
        break;
      case 'errors':
        view.setSummary(
            'Eligibility: In order for ' + domain +
            ' to be eligible for preloading, the errors below must be resolved:');
        view.setTheme('theme-red');
        return false;
        break;
    }
  },

  showResults: function(view, domain, issues, status) {

    view.setStatus(statusString(status, issues, domain));

    var showForm = false;

    console.log("showResults", status)

    switch (status.status) {
      case 'unknown':
      case 'rejected':
      case 'removed':
      case 'pending-removal':
        showForm = this.showPreloadElibigility(view, domain, issues);
        view.showIssues(issues);
        break;
      case 'pending':
        this.showPending(view, domain, issues);
        break;
      case 'preloaded':
        view.setTheme('theme-green');
        if (status.bulk) {
          view.showIssues(issues);
          if (worstIssues(issues) !== 'none') {
            view.clearTheme();
          }
        }
        break;
      default:
        throw "Unknown status";
    }

    view.showResults();
    return showForm;
  }
}

var RemovalController = function(hstsPreload) {
  this._hstsPreload = hstsPreload;
}

RemovalController.prototype = {
  formHasCheckboxes: function() {
    return false;
  },

  eligible: function(domain) {
    return this._hstsPreload.removable(domain);
  },

  submit: function(domain) {
    return this._hstsPreload.remove(domain);
  },

  submittableStatus: function(status) {
    return ['preloaded', 'pending'].indexOf(status) != -1;
  },

  submitButtonString: function(domain) {
    return 'Remove ' + domain + ' from the HSTS preload list';
  },

  showRemovalElibigility: function(view, domain, issues) {
    switch (worstIssues(issues)) {
      case 'none':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for removal from the HSTS preload list.');
        view.setTheme('theme-green');
        return true;
        break;
      case 'warnings':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for removal, although we recommend fixing the following warnings:');
        view.setTheme('theme-yellow');
        return true;
        break;
      case 'errors':
        view.setSummary(
            'Eligibility: In order for ' + domain +
            ' to be eligible for removal from the preload list, the errors below must be resolved:');
        view.setTheme('theme-red');
        return false;
        break;
    }
  },

  showResults: function(view, domain, issues, status) {

    view.setStatus(statusString(status, issues, domain));

    var showForm = false;

    console.log("showResults", status)

    switch (status.status) {
      case 'unknown':
      case 'rejected':
      case 'removed':
      case 'pending-removal':
        view.setTheme('theme-red');
        break;
      case 'pending':
      case 'preloaded':
        showForm = this.showRemovalElibigility(view, domain, issues);
        view.showIssues(issues);
        break;
      default:
        throw "Unknown status";
    }

    view.showResults();
    return showForm;
  }
}<commit_msg>Fix typo.<commit_after>'use strict';

var Form = function(controller) {
  this._hstsPreload = new HSTSPreload();
  this._controller = new controller(this._hstsPreload);

  this._urlParam = new URLParam();
  this._view = new PreloadView(this._controller, this.submitDomain.bind(this), this._urlParam);

  var domainParam = this._urlParam.get();
  if (domainParam) {
    var domain = extractDomain(domainParam);

    if (domain != domainParam) {
      this._view.setDomain(domain);
      this._view.clickCheck();
    } else {
      console.log('From URL parameter:', domain);
      $('#domain').value = domain;
      this.checkDomain(domain);
    }
  }
};

Form.prototype = {
  checkDomain: function(domain) {
    this._view.clearDomainSpecificElements();
    this._view.showWaiting(domain);

    if (!domain) {
      console.log('checkDomain called with empty domain');
      $('#result-waiting').classList.add('hidden');
      return;
    }

    this._currentResultsDomain = '';

    Promise
        .all([
          this._hstsPreload.status(domain),
          this._controller.eligible(domain)
        ])
        .then(
            function(values) {
              this.handleResults(domain, values[0], values[1]);
            }.bind(this),
            function() {
              // TODO: handle failure better.
              $('#result').classList.remove('hidden');
              $('#result-waiting').classList.add('hidden');
            });
  },

  submitDomain: function() {
    var domain = this.domainToSubmit;

    this._controller.submit(domain).then(function(issues) {
      if (issues.errors.length == 0) {
        $('#submit-success').show();
          if ($('#ssl-labs-link')) {
            $('#ssl-labs-link')
                .href = 'https://www.ssllabs.com/ssltest/analyze.html?d=' + domain;
          }
      } else {
        this._view.setTheme('theme-red');
        $('#submit-failure').show();
        console.log(issues);
      }
    }.bind(this));
  },

  handleResults: function(domain, status, issues) {
    if (domain !== this._view.currentDomain()) {
      return;
    }
    if (this._currentResultsDomain === domain) {
      return;
    }
    this._currentResultsDomain = domain;

    if (domain !== this._view.currentDomain()) {
      console.log('Outdated result.');
      return;
    }

    this._view.clearStatus();
    this._view.clearSummary();
    var showForm = this._controller.showResults(this._view, domain, issues, status);
    this._view.hideWaiting();

    if (showForm) {
      this.domainToSubmit = domain;
      this._view.showSubmission(domain);
    }
  }
};

function statusString(status, issues, domain) {
  switch (status.status) {
    case 'unknown':
      return 'Status: ' + domain + ' is not preloaded.';
    case 'pending':
      return 'Status: ' + domain + ' is pending submission to the preload list.';
    case 'preloaded':
      if (status.bulk) {
        switch (worstIssues(issues)) {
          case 'warnings':
            return 'Status: ' + domain + ' is currently preloaded, but has the following issues:';
          case 'errors':
            return 'Status: ' + domain + ' is currently preloaded, but no longer meets the requirements. It may be at risk of removal.';
          default:
            return 'Status: ' + domain + ' is currently preloaded.';
        }
      } else {
        return 'Status: ' + domain + ' is currently preloaded.';
      }
      break;

    case 'rejected':
      if (status.message) {
        return 'Status: ' + domain +
          ' was previously rejected from the preload list for the following reason: ' +
          status.message;
      } else {
        return 'Status: ' + domain +
          ' was previously rejected from the preload list.'
      }
    case 'pending-removal':
      return 'Status: ' + domain +
          ' was previously submitted to the preload list, but is now pending removal.';
    case 'removed':
      return 'Status: ' + domain +
          ' was previously submitted to the preload list, but has been removed.';
    default:
      return 'Cannot determine preload status.';
  }
};

function worstIssues(issues) {
  if (issues.errors.length == 0) {
    if (issues.warnings.length == 0) {
      return 'none';
    } else {
      return 'warnings';
    }
  } else {
    return 'errors';
  }
}

var PreloadController = function(hstsPreload) {
  this._hstsPreload = hstsPreload;
}

PreloadController.prototype = {
  formHasCheckboxes: function() {
    return true;
  },

  eligible: function(domain) {
    return this._hstsPreload.preloadable(domain);
  },

  submit: function(domain) {
    return this._hstsPreload.submit(domain);
  },

  submitButtonString: function(domain) {
    return 'Submit ' + domain + ' to the HSTS preload list';
  },

  showPending: function(view, domain, issues) {
    switch (worstIssues(issues)) {
      case 'none':
        view.setStatus(
            'Status: ' + domain +
            ' is pending submission to the preload list.');
        view.setTheme('theme-green');
        break;
      case 'warnings':
        view.setStatus(
            'Status: ' + domain +
            ' is pending submission to the preload list.');
        view.setSummary(
            'However, it still has the following issues, which we recommend fixing:');
        view.setTheme('theme-yellow');
        view.showIssues(issues);
        break;
      case 'errors':
        view.setStatus(
            'Status: ' + domain +
            ' was recently submitted to the preload list.');
        view.setSummary(
            'However, ' + domain +
            ' has changed its behaviour since it was submitted, and will not be added to the official preload list unless the errors below are resolved:');
        view.setTheme('theme-red');
        view.showIssues(issues);
        break;
    }
  },

  showPreloadEligibility: function(view, domain, issues) {
    switch (worstIssues(issues)) {
      case 'none':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for the HSTS preload list.');
        view.setTheme('theme-green');
        return true;
        break;
      case 'warnings':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for preloading, although we recommend fixing the following warnings:');
        view.setTheme('theme-yellow');
        return true;
        break;
      case 'errors':
        view.setSummary(
            'Eligibility: In order for ' + domain +
            ' to be eligible for preloading, the errors below must be resolved:');
        view.setTheme('theme-red');
        return false;
        break;
    }
  },

  showResults: function(view, domain, issues, status) {

    view.setStatus(statusString(status, issues, domain));

    var showForm = false;

    console.log("showResults", status)

    switch (status.status) {
      case 'unknown':
      case 'rejected':
      case 'removed':
      case 'pending-removal':
        showForm = this.showPreloadEligibility(view, domain, issues);
        view.showIssues(issues);
        break;
      case 'pending':
        this.showPending(view, domain, issues);
        break;
      case 'preloaded':
        view.setTheme('theme-green');
        if (status.bulk) {
          view.showIssues(issues);
          if (worstIssues(issues) !== 'none') {
            view.clearTheme();
          }
        }
        break;
      default:
        throw "Unknown status";
    }

    view.showResults();
    return showForm;
  }
}

var RemovalController = function(hstsPreload) {
  this._hstsPreload = hstsPreload;
}

RemovalController.prototype = {
  formHasCheckboxes: function() {
    return false;
  },

  eligible: function(domain) {
    return this._hstsPreload.removable(domain);
  },

  submit: function(domain) {
    return this._hstsPreload.remove(domain);
  },

  submittableStatus: function(status) {
    return ['preloaded', 'pending'].indexOf(status) != -1;
  },

  submitButtonString: function(domain) {
    return 'Remove ' + domain + ' from the HSTS preload list';
  },

  showRemovalEligibility: function(view, domain, issues) {
    switch (worstIssues(issues)) {
      case 'none':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for removal from the HSTS preload list.');
        view.setTheme('theme-green');
        return true;
        break;
      case 'warnings':
        view.setSummary(
            'Eligibility: ' + domain +
            ' is eligible for removal, although we recommend fixing the following warnings:');
        view.setTheme('theme-yellow');
        return true;
        break;
      case 'errors':
        view.setSummary(
            'Eligibility: In order for ' + domain +
            ' to be eligible for removal from the preload list, the errors below must be resolved:');
        view.setTheme('theme-red');
        return false;
        break;
    }
  },

  showResults: function(view, domain, issues, status) {

    view.setStatus(statusString(status, issues, domain));

    var showForm = false;

    console.log("showResults", status)

    switch (status.status) {
      case 'unknown':
      case 'rejected':
      case 'removed':
      case 'pending-removal':
        view.setTheme('theme-red');
        break;
      case 'pending':
      case 'preloaded':
        showForm = this.showRemovalEligibility(view, domain, issues);
        view.showIssues(issues);
        break;
      default:
        throw "Unknown status";
    }

    view.showResults();
    return showForm;
  }
}<|endoftext|>


<commit_before>'use strict';

var Node = require('../node');
var dot = require('dot');
dot.templateSettings.strip = false;

var TYPE = 'link-by-line';

var PARAMS = {
    source_points      : Node.PARAM.NODE(Node.GEOMETRY.POINT),
    dest_points        : Node.PARAM.NODE(Node.GEOMETRY.POINT),
    id_column_source   : Node.PARAM.STRING(),
    id_column_dest     : Node.PARAM.STRING(),
    use_great_circle   : Node.PARAM.BOOLEAN()
};

var LinkByLine = Node.create(TYPE, PARAMS, {cache: true});

module.exports = LinkByLine;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;

var linkByLineTemplate = dot.template([
    'with source as(',
    '  select * from ({{=it.sourceQuery}}) a ' ,
    '),',
    'dest as (',
    '  select * from ({{=it.destQuery}}) b ',
    ')',
    'select {{=it.lineFunc}}(source.the_geom, dest.the_geom) as the_geom, {{=it.sourceColumns}}, {{=it.targetColumns}}',
    'from source, dest',
    'where source.{{=it.source_id}} = dest.{{=it.dest_id}}',
].join('\n'));

var featureColumns = function(columns,prefix){
    return columns.filter(function(col){
        return ['the_geom','the_geom_webmercator','cartodb_id'].indexOf(col) === -1;
    }).map(function(col){
        return prefix+'.'+col + ' as '+prefix+'_'+col;
    }).join(',');
};

LinkByLine.prototype.sql = function(){
    var lineFunc      = this.use_great_circle ? 'CDB_GreatCircle' : 'ST_MakeLine';
    return linkByLineTemplate({
        sourceQuery : this.source_points.getQuery(),
        destQuery : this.dest_points.getQuery(),
        source_id: this.id_column_source,
        dest_id  : this.id_column_dest,
        sourceColumns: featureColumns(this.source_points.getColumns(), 'source'),
        targetColumns: featureColumns(this.dest_points.getColumns(), 'dest'),
        lineFunc: lineFunc
    });
};
<commit_msg>fix indent<commit_after>'use strict';

var Node = require('../node');
var dot = require('dot');
dot.templateSettings.strip = false;

var TYPE = 'link-by-line';

var PARAMS = {
    source_points: Node.PARAM.NODE(Node.GEOMETRY.POINT),
    destination_points: Node.PARAM.NODE(Node.GEOMETRY.POINT),
    source_column: Node.PARAM.STRING(),
    destination_column: Node.PARAM.STRING(),
    use_great_circle: Node.PARAM.BOOLEAN()
};

var LinkByLine = Node.create(TYPE, PARAMS, {cache: true});

module.exports = LinkByLine;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;

var linkByLineTemplate = dot.template([
    'with source as(',
    '  select * from ({{=it.sourceQuery}}) a ' ,
    '),',
    'dest as (',
    '  select * from ({{=it.destQuery}}) b ',
    ')',
    'select {{=it.lineFunc}}(source.the_geom, dest.the_geom) as the_geom, {{=it.sourceColumns}}, {{=it.targetColumns}}',
    'from source, dest',
    'where source.{{=it.source_id}} = dest.{{=it.dest_id}}',
].join('\n'));

var featureColumns = function(columns,prefix){
    return columns.filter(function(col){
        return ['the_geom','the_geom_webmercator','cartodb_id'].indexOf(col) === -1;
    }).map(function(col){
        return prefix+'.'+col + ' as '+prefix+'_'+col;
    }).join(',');
};

LinkByLine.prototype.sql = function(){
    var lineFunc = this.use_great_circle ? 'CDB_GreatCircle' : 'ST_MakeLine';
    return linkByLineTemplate({
        sourceQuery : this.source_points.getQuery(),
        destQuery : this.dest_points.getQuery(),
        source_id: this.id_column_source,
        dest_id  : this.id_column_dest,
        sourceColumns: featureColumns(this.source_points.getColumns(), 'source'),
        targetColumns: featureColumns(this.dest_points.getColumns(), 'dest'),
        lineFunc: lineFunc
    });
};
<|endoftext|>


<commit_before>var fs = require('fs');

// Import and parse Taillard instances from directory
function Taillard() {
}

// Filter Taillard instances by jobs and machines
Taillard.prototype.filter = function(jobs, machines) {
    var data = parseFiles('taillard/'), filteredData = [];
    for(var i = 0; i < data.length; i++) {
        if(data[i].numberOfJobs === jobs && data[i].numberOfMachines === machines) {
            filteredData.push(data[i]);
        }
    }
    return filteredData.reverse();
};
exports.filter = Taillard.prototype.filter;

// Get Taillard instance by name
Taillard.prototype.get = function(name) {
    var data = parseFiles('taillard/');
    for(var i = 0; i < data.length; i++) {
        if(name !== 'custom' && data[i].name === name) {
            return data[i];
        }
    }
    return [];
};
exports.get = Taillard.prototype.get;

function parseLine(line) {
    var finalValues = [], rawValues = line.split(/[a-zA-Z:, ]+/);
    for(var i = 0; i < rawValues.length; i++) {
        var eachValue = +(rawValues[i]);
        if(eachValue > 0) {
            finalValues.push(eachValue);
        }
    }
    return finalValues;
}

function parseFile(file) {
    var finalValues = [], rawValues = file.split(String.fromCharCode(13) + String.fromCharCode(10));
    for(var i = 0; i < rawValues.length; i++) {
        var eachLine = parseLine(rawValues[i]);
        if(eachLine.length > 0) {
            finalValues.push(eachLine);
        }
    }
    return finalValues;
}

function parseFiles(path) {
    var finalData = [], fileList = fs.readdirSync(path);
    for(var i = 0; i < fileList.length; i++) {
        var tempData = {
            data: []
        };
        var counter = counterByFileName(fileList[i]);
        var nextHeaderData = 0;
        var rawData = parseFile( fs.readFileSync(path + fileList[i]).toString() );
        var j = 0;
        for(var k = 0; k < rawData.length; k++) {
            if(k === nextHeaderData) {
                var name = 'ta';
                if(counter > 0) {
                    name = name + fillWithZeros('' + counter, 3);
                } else {
                    name = 'custom';
                }
                tempData = {
                    name: name,
                    data: [],
                    numberOfJobs: rawData[k][0],
                    numberOfMachines: rawData[k][1],
                    initialSeed: rawData[k][2],
                    upperBound: rawData[k][3],
                    lowerBound: rawData[k][4]
                };
                nextHeaderData = nextHeaderData + tempData.numberOfMachines + 1;
                if(counter > 0) {
                    counter++;
                }
            } else if(k === nextHeaderData - 1) {
                finalData.push(tempData);
                j = 0;
            } else {
                for(var l = 0; l < rawData[k].length; l++) {
                    if(!tempData.data[l]) {
                        tempData.data[l] = [];
                    }
                    tempData.data[l][j] = rawData[k][l];
                }
                j = j + 1;
            }
        }
    }
    return finalData.reverse();
}

function fillWithZeros(input, length) {
    while(input.length < length) {
        input = '0' + input;
    }
    return input;
}

function counterByFileName(fileName) {
    var map = {
        'tai20_5.txt': 1,
        'tai20_10.txt': 11,
        'tai20_20.txt': 21,
        'tai50_5.txt': 31,
        'tai50_10.txt': 41,
        'tai50_20.txt': 51,
        'tai100_5.txt': 61,
        'tai100_10.txt': 71,
        'tai100_20.txt': 81,
        'tai200_10.txt': 91,
        'tai200_20.txt': 101,
        'tai500_20.txt': 111
    };
    return map[fileName] || 0;
}
<commit_msg>Minor change<commit_after>var fs = require('fs');

// Import and parse Taillard instances from directory
function Taillard() {
}

// Filter Taillard instances by jobs and machines
Taillard.prototype.filter = function(jobs, machines) {
    var data = parseFiles('taillard/'), filteredData = [];
    for(var i = 0; i < data.length; i++) {
        if(data[i].numberOfJobs === jobs && data[i].numberOfMachines === machines) {
            filteredData.push(data[i]);
        }
    }
    return filteredData.reverse();
};
exports.filter = Taillard.prototype.filter;

// Get Taillard instance by name
Taillard.prototype.get = function(name) {
    var data = parseFiles('taillard/');
    for(var i = 0; i < data.length; i++) {
        if(name !== 'custom' && data[i].name === name) {
            return data[i];
        }
    }
    return [];
};
exports.get = Taillard.prototype.get;

function parseLine(line) {
    var finalValues = [], rawValues = line.split(/[a-zA-Z:, ]+/);
    for(var i = 0; i < rawValues.length; i++) {
        var eachValue = +(rawValues[i]);
        if(eachValue > 0) {
            finalValues.push(eachValue);
        }
    }
    return finalValues;
}

function parseFile(file) {
    var finalValues = [], rawValues = file.split(String.fromCharCode(13) + String.fromCharCode(10));
    for(var i = 0; i < rawValues.length; i++) {
        var eachLine = parseLine(rawValues[i]);
        if(eachLine.length > 0) {
            finalValues.push(eachLine);
        }
    }
    return finalValues;
}

function parseFiles(path) {
    var finalData = [], fileList = fs.readdirSync(path);
    for(var i = 0; i < fileList.length; i++) {
        var tempData = {
            data: []
        };
        var counter = counterByFileName(fileList[i]);
        var nextHeaderData = 0;
        var rawData = parseFile( fs.readFileSync(path + fileList[i]).toString() );
        var j = 0;
        for(var k = 0; k < rawData.length; k++) {
            if(k === nextHeaderData) {
                var name = 'ta';
                if(counter > 0) {
                    name = name + fillWithZeros('' + counter, 3);
                } else {
                    name = 'custom';
                }
                tempData = {
                    name: name,
                    data: [],
                    numberOfJobs: rawData[k][0],
                    numberOfMachines: rawData[k][1],
                    initialSeed: rawData[k][2],
                    upperBound: rawData[k][3],
                    lowerBound: rawData[k][4]
                };
                nextHeaderData = nextHeaderData + tempData.numberOfMachines + 1;
                if(counter > 0) {
                    counter++;
                }
            } else {
                for(var l = 0; l < rawData[k].length; l++) {
                    if(!tempData.data[l]) {
                        tempData.data[l] = [];
                    }
                    tempData.data[l][j] = rawData[k][l];
                }
                j = j + 1;
                if(k === nextHeaderData - 1) {
                    finalData.push(tempData);
                    j = 0;
                }
            }
        }
    }
    return finalData.reverse();
}

function fillWithZeros(input, length) {
    while(input.length < length) {
        input = '0' + input;
    }
    return input;
}

function counterByFileName(fileName) {
    var map = {
        'tai20_5.txt': 1,
        'tai20_10.txt': 11,
        'tai20_20.txt': 21,
        'tai50_5.txt': 31,
        'tai50_10.txt': 41,
        'tai50_20.txt': 51,
        'tai100_5.txt': 61,
        'tai100_10.txt': 71,
        'tai100_20.txt': 81,
        'tai200_10.txt': 91,
        'tai200_20.txt': 101,
        'tai500_20.txt': 111
    };
    return map[fileName] || 0;
}
<|endoftext|>