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

function PaymentSuccess({
  reservation,
  resource,
}) {
  return (

      {reservation.id}
      {resource.id}

  );
}

PaymentSuccess.propTypes = {
  reservation: PropTypes.object,
  resource: PropTypes.object,
};

export default PaymentSuccess;
<commit_msg>Show ReservationConfirmation on payment success<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
import flow from 'lodash/flow';
import get from 'lodash/get';

import { currentUserSelector } from '../../state/selectors/authSelectors';
import ReservationConfirmation from './reservation-confirmation/ReservationConfirmation';

const translateEntity = (entity, locale) => (
  Object
    .entries(entity)
    .reduce((acc, [key, value]) => {
      acc[key] = get(value, locale, value);
      return acc;
    }, {})
);

function PaymentSuccess({
  reservation,
  resource,
  user,
  intl: { locale },
}) {
  const translatedReservation = translateEntity(reservation, locale);
  const translatedResource = translateEntity(resource, locale);
  return (

      <ReservationConfirmation
        reservation={translatedReservation}
        resource={translatedResource}
        user={user}
      />

  );
}

PaymentSuccess.propTypes = {
  reservation: PropTypes.object,
  resource: PropTypes.object,
  user: PropTypes.object,
  intl: PropTypes.object,
};

export default flow(
  connect(
    state => ({
      user: currentUserSelector(state)
    })
  ),
  injectIntl,
)(PaymentSuccess);
<|endoftext|>


<commit_before>/**
 * @module ol/control/Rotate
 */

import Control from '../control/Control.js';
import {CLASS_CONTROL, CLASS_HIDDEN, CLASS_UNSELECTABLE} from '../css.js';
import {easeOut} from '../easing.js';
import {listen} from '../events.js';
import EventType from '../events/EventType.js';
import {inherits} from '../index.js';

/**
 * @classdesc
 * A button control to reset rotation to 0.
 * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css
 * selector is added to the button when the rotation is 0.
 *
 * @constructor
 * @extends {ol.control.Control}
 * @param {olx.control.RotateOptions=} opt_options Rotate options.
 * @api
 */
const Rotate = function(opt_options) {

  const options = opt_options ? opt_options : {};

  const className = options.className !== undefined ? options.className : 'ol-rotate';

  const label = options.label !== undefined ? options.label : '\u21E7';

  /**
   * @type {Element}
   * @private
   */
  this.label_ = null;

  if (typeof label === 'string') {
    this.label_ = document.createElement('span');
    this.label_.className = 'ol-compass';
    this.label_.textContent = label;
  } else {
    this.label_ = label;
    this.label_.classList.add('ol-compass');
  }

  const tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation';

  const button = document.createElement('button');
  button.className = className + '-reset';
  button.setAttribute('type', 'button');
  button.title = tipLabel;
  button.appendChild(this.label_);

  listen(button, EventType.CLICK,
    Rotate.prototype.handleClick_, this);

  const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
  const element = document.createElement('div');
  element.className = cssClasses;
  element.appendChild(button);

  const render = options.render ? options.render : Rotate.render;

  this.callResetNorth_ = options.resetNorth ? options.resetNorth : undefined;

  Control.call(this, {
    element: element,
    render: render,
    target: options.target
  });

  /**
   * @type {number}
   * @private
   */
  this.duration_ = options.duration !== undefined ? options.duration : 250;

  /**
   * @type {boolean}
   * @private
   */
  this.autoHide_ = options.autoHide !== undefined ? options.autoHide : true;

  /**
   * @private
   * @type {number|undefined}
   */
  this.rotation_ = undefined;

  if (this.autoHide_) {
    this.element.classList.add(CLASS_HIDDEN);
  }

};

inherits(Rotate, Control);

/**
 * @param {Event} event The event to handle
 * @private
 */
Rotate.prototype.handleClick_ = function(event) {
  event.preventDefault();
  if (this.callResetNorth_ !== undefined) {
    this.callResetNorth_();
  } else {
    this.resetNorth_();
  }
};

/**
 * @private
 */
Rotate.prototype.resetNorth_ = function() {
  const map = this.getMap();
  const view = map.getView();
  if (!view) {
    // the map does not have a view, so we can't act
    // upon it
    return;
  }
  if (view.getRotation() !== undefined) {
    if (this.duration_ > 0) {
      view.animate({
        rotation: 0,
        duration: this.duration_,
        easing: easeOut
      });
    } else {
      view.setRotation(0);
    }
  }
};

/**
 * Update the rotate control element.
 * @param {ol.MapEvent} mapEvent Map event.
 * @this {ol.control.Rotate}
 * @api
 */
Rotate.render = function(mapEvent) {
  const frameState = mapEvent.frameState;
  if (!frameState) {
    return;
  }
  const rotation = frameState.viewState.rotation;
  if (rotation != this.rotation_) {
    const transform = 'rotate(' + rotation + 'rad)';
    if (this.autoHide_) {
      const contains = this.element.classList.contains(CLASS_HIDDEN);
      if (!contains && rotation === 0) {
        this.element.classList.add(CLASS_HIDDEN);
      } else if (contains && rotation !== 0) {
        this.element.classList.remove(CLASS_HIDDEN);
      }
    }
    this.label_.style.msTransform = transform;
    this.label_.style.webkitTransform = transform;
    this.label_.style.transform = transform;
  }
  this.rotation_ = rotation;
};
export default Rotate;
<commit_msg>Export render from ol/control/Rotate<commit_after>/**
 * @module ol/control/Rotate
 */

import Control from '../control/Control.js';
import {CLASS_CONTROL, CLASS_HIDDEN, CLASS_UNSELECTABLE} from '../css.js';
import {easeOut} from '../easing.js';
import {listen} from '../events.js';
import EventType from '../events/EventType.js';
import {inherits} from '../index.js';

/**
 * @classdesc
 * A button control to reset rotation to 0.
 * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css
 * selector is added to the button when the rotation is 0.
 *
 * @constructor
 * @extends {ol.control.Control}
 * @param {olx.control.RotateOptions=} opt_options Rotate options.
 * @api
 */
const Rotate = function(opt_options) {

  const options = opt_options ? opt_options : {};

  const className = options.className !== undefined ? options.className : 'ol-rotate';

  const label = options.label !== undefined ? options.label : '\u21E7';

  /**
   * @type {Element}
   * @private
   */
  this.label_ = null;

  if (typeof label === 'string') {
    this.label_ = document.createElement('span');
    this.label_.className = 'ol-compass';
    this.label_.textContent = label;
  } else {
    this.label_ = label;
    this.label_.classList.add('ol-compass');
  }

  const tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation';

  const button = document.createElement('button');
  button.className = className + '-reset';
  button.setAttribute('type', 'button');
  button.title = tipLabel;
  button.appendChild(this.label_);

  listen(button, EventType.CLICK,
    Rotate.prototype.handleClick_, this);

  const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
  const element = document.createElement('div');
  element.className = cssClasses;
  element.appendChild(button);

  this.callResetNorth_ = options.resetNorth ? options.resetNorth : undefined;

  Control.call(this, {
    element: element,
    render: options.render || render,
    target: options.target
  });

  /**
   * @type {number}
   * @private
   */
  this.duration_ = options.duration !== undefined ? options.duration : 250;

  /**
   * @type {boolean}
   * @private
   */
  this.autoHide_ = options.autoHide !== undefined ? options.autoHide : true;

  /**
   * @private
   * @type {number|undefined}
   */
  this.rotation_ = undefined;

  if (this.autoHide_) {
    this.element.classList.add(CLASS_HIDDEN);
  }

};

inherits(Rotate, Control);

/**
 * @param {Event} event The event to handle
 * @private
 */
Rotate.prototype.handleClick_ = function(event) {
  event.preventDefault();
  if (this.callResetNorth_ !== undefined) {
    this.callResetNorth_();
  } else {
    this.resetNorth_();
  }
};

/**
 * @private
 */
Rotate.prototype.resetNorth_ = function() {
  const map = this.getMap();
  const view = map.getView();
  if (!view) {
    // the map does not have a view, so we can't act
    // upon it
    return;
  }
  if (view.getRotation() !== undefined) {
    if (this.duration_ > 0) {
      view.animate({
        rotation: 0,
        duration: this.duration_,
        easing: easeOut
      });
    } else {
      view.setRotation(0);
    }
  }
};

/**
 * Update the rotate control element.
 * @param {ol.MapEvent} mapEvent Map event.
 * @this {ol.control.Rotate}
 * @api
 */
export function render(mapEvent) {
  const frameState = mapEvent.frameState;
  if (!frameState) {
    return;
  }
  const rotation = frameState.viewState.rotation;
  if (rotation != this.rotation_) {
    const transform = 'rotate(' + rotation + 'rad)';
    if (this.autoHide_) {
      const contains = this.element.classList.contains(CLASS_HIDDEN);
      if (!contains && rotation === 0) {
        this.element.classList.add(CLASS_HIDDEN);
      } else if (contains && rotation !== 0) {
        this.element.classList.remove(CLASS_HIDDEN);
      }
    }
    this.label_.style.msTransform = transform;
    this.label_.style.webkitTransform = transform;
    this.label_.style.transform = transform;
  }
  this.rotation_ = rotation;
}

export default Rotate;
<|endoftext|>


<commit_before>/*
 * Copyright https://github.com/divio/django-cms
 */

// #############################################################################
// NAMESPACES
/**
 * @module CMS
 */
var CMS = window.CMS || {};

// #############################################################################
// Toolbar
(function ($) {
    'use strict';

    // shorthand for jQuery(document).ready();
    $(function () {
        /**
         * Responsible for creating usable navigation for narrow screens.
         *
         * @class Navigation
         * @namespace CMS
         * @uses CMS.API.Helpers
         */
        CMS.Navigation = new CMS.Class({

            implement: [CMS.API.Helpers],

            initialize: function initialize() {
                this._setupUI();
                this.getWidths();

                /** The zero based index of the right-most visible menu item of the left toolbar part. */
                this.rightMostItemIndex = this.items.left.length - 1;

                /** The zero based index of the left-most visible item of the right toolbar part. */
                this.leftMostItemIndex = 0;

                this._events();
            },

            /**
             * Cache UI jquery objects
             * @method _setupUI
             * @private
             */
            _setupUI: function _setupUI() {
                var trigger = $('.cms-toolbar-more');
                this.ui = {
                    window: $(window),
                    toolbarLeftPart: $('.cms-toolbar-left'),
                    toolbarRightPart: $('.cms-toolbar-right'),
                    trigger: trigger,
                    dropdown: trigger.find('> ul'),
                    toolbarTrigger: $('.cms-toolbar-trigger'),
                    logo: $('.cms-toolbar-item-logo')
                };
            },

            /**
             * Setup resize handler to construct the dropdown
             * @method _events
             * @private
             */
            _events: function _events() {
                this.ui.window.on('resize.cms load.cms', CMS.API.Helpers.throttle(
                    this._handleResize.bind(this), 50
                ));
            },

            /**
             * Calculates all the movable menu items widths
             * @method _getWidths
             */
            getWidths: function getWidths() {
                var that = this;
                that.items = {
                    left: [],
                    leftTotalWidth: 0,
                    right: [],
                    rightTotalWidth: 0,
                    moreButtonWidth: 0
                };
                var leftItems = that.ui.toolbarLeftPart
                    .find('.cms-toolbar-item-navigation > li:not(.cms-toolbar-more)');
                var rightItems = that.ui.toolbarRightPart.find('> .cms-toolbar-item');

                var getSize = function getSize(el, store) {
                    var element = $(el);
                    var width = $(el).outerWidth(true);

                    store.push({
                        element: element,
                        width: width
                    });
                };
                var sumWidths = function sumWidths(sum, item) {
                    return sum + item.width;
                };

                leftItems.each(function () {
                    getSize(this, that.items.left);
                });

                rightItems.each(function () {
                    getSize(this, that.items.right);
                });

                that.items.leftTotalWidth = that.items.left.reduce(sumWidths, 0);
                that.items.rightTotalWidth = that.items.right.reduce(sumWidths, 0);
                that.items.moreButtonWidth = that.ui.trigger.outerWidth();
            },

            /**
             * Calculates available width based on the state of the page
             * @method calculateAvailableWidth
             */
            calculateAvailableWidth: function calculateAvailableWidth() {
                var fullWidth = this.ui.window.width();
                var reduce = this.ui.toolbarTrigger.width() + this.ui.logo.offset().left +
                    this.ui.logo.outerWidth(true);

                return fullWidth - reduce;
            },

            /**
             * Shows the dropdown
             *
             * @method showDropdown
             */
            showDropdown: function showDropdown() {
                this.ui.trigger.show();
            },

            /**
             * Hides the dropdown
             *
             * @method hideDropdown
             */
            hideDropdown: function hideDropdown() {
                this.ui.trigger.hide();
            },

            /**
             * Figures out if we need to show/hide/modify the dropdown
             *
             * @method _handleResize
             * @private
             */
            _handleResize: function _handleResize() {
                var remainingWidth;
                var availableWidth = this.calculateAvailableWidth();

                if (availableWidth > this.items.leftTotalWidth + this.items.rightTotalWidth) {
                    this.showAll();
                } else {
                    // first handle the left part
                    remainingWidth = availableWidth - this.items.moreButtonWidth - this.items.rightTotalWidth;
                    console.log('remainingWidth', remainingWidth);

                    // Figure out how many nav menu items fit into the available space.
                    var newRightMostItemIndex = -1;
                    while (remainingWidth - this.items.left[newRightMostItemIndex + 1].width >= 0) {
                        remainingWidth -= this.items.left[newRightMostItemIndex + 1].width;
                        newRightMostItemIndex++;
                    }

                    if (newRightMostItemIndex < this.rightMostItemIndex) {
                        this.moveToDropdown(this.rightMostItemIndex - newRightMostItemIndex);
                    } else if (this.rightMostItemIndex < newRightMostItemIndex) {
                        this.moveOutOfDropdown(newRightMostItemIndex - this.rightMostItemIndex);
                    }

                    this.showDropdown();

                    if (remainingWidth <= 0) {
                        console.log('do the right part');
                        remainingWidth += this.items.rightTotalWidth;

                        var newLeftMostItemIndex = this.items.right.length;
                        while (remainingWidth - this.items.right[newLeftMostItemIndex - 1].width > 0) {
                            remainingWidth -= this.items.right[newLeftMostItemIndex - 1].width;
                            newLeftMostItemIndex--;
                        }

                        if (newLeftMostItemIndex > this.leftMostItemIndex) {
                            this.moveToDropdown(newLeftMostItemIndex - this.leftMostItemIndex, 'right');
                        } else if (newLeftMostItemIndex < this.leftMostItemIndex) {
                            this.moveOutOfDropdown(this.leftMostItemIndex - newLeftMostItemIndex, 'right');
                        }
                    } else {
                        this.showAllRight();
                    }
                }
            },

            /**
             * Hides and empties dropdown
             *
             * @method showAll
             */
            showAll: function showAll() {
                this.showAllLeft();
                this.showAllRight();
                this.hideDropdown();
            },

            /**
             * Show all items in the left part of the toolbar
             *
             * @method showAllLeft
             */
            showAllLeft: function showAllLeft() {
                this.moveOutOfDropdown((this.items.left.length - 1) - this.rightMostItemIndex);
            },

            /**
             * Show all items in the right part of the toolbar
             *
             * @method showAllRight
             */
            showAllRight: function showAllRight() {
                this.moveOutOfDropdown(this.leftMostItemIndex, 'right');
            },

            /**
             * Moves items into the dropdown, reducing menu right-to-left in case it's a left part of toolbar
             * and left-to-right if it's right one
             *
             * @param numberOfItems {Number} how many items to move to dropdown
             * @param part {String} from which part to move to dropdown (defaults to left)
             */
            moveToDropdown: function moveToDropdown(numberOfItems, part) {
                if (numberOfItems <= 0) {
                    return;
                }

                var item;
                var leftMostIndexToMove;
                var rightMostIndexToMove;
                var i;

                if (part === 'right') {
                    console.log('moving from right part to dropdown');
                    // Move items (working left-to-right) from the toolbar left part to the more menu.
                    leftMostIndexToMove = this.leftMostItemIndex;
                    rightMostIndexToMove = this.leftMostItemIndex + numberOfItems - 1;
                    for (i = leftMostIndexToMove; i <= rightMostIndexToMove; i++) {
                        item = this.items.right[i].element;

                        this.ui.dropdown.append(item.wrap('

').parent());
                    }

                    this.leftMostItemIndex += numberOfItems;
                } else {
                    // Move items (working right-to-left) from the toolbar left part to the more menu.
                    rightMostIndexToMove = this.rightMostItemIndex;
                    leftMostIndexToMove = this.rightMostItemIndex - numberOfItems + 1;
                    for (i = rightMostIndexToMove; i >= leftMostIndexToMove; i--) {
                        item = this.items.left[i].element;

                        this.ui.dropdown.prepend(item);
                        if (item.find('> ul').children().length) {
                            item.addClass('cms-toolbar-item-navigation-children');
                        }
                    }

                    this.rightMostItemIndex -= numberOfItems;
                }
            },

            /**
             * Moves items out of the dropdown
             *
             * @param numberOfItems Number how many items to move out of the dropdown
             * @param part {String} to which part to move out of dropdown (defaults to left)
             */
            moveOutOfDropdown: function moveOutOfDropdown(numberOfItems, part) {
                if (numberOfItems <= 0) {
                    return;
                }

                var i;
                var item;
                var leftMostIndexToMove;
                var rightMostIndexToMove;

                if (part === 'right') {
                    console.log('moving out of right part');
                    // Move items (working bottom-to-top) from the more menu into the toolbar right part.
                    rightMostIndexToMove = this.leftMostItemIndex - 1;
                    leftMostIndexToMove = this.leftMostItemIndex - numberOfItems;

                    for (i = rightMostIndexToMove; i >= leftMostIndexToMove; i--) {
                        item = this.items.right[i].element;
                        item.unwrap('

');

                        item.prependTo(this.ui.toolbarRightPart);
                    }

                    this.leftMostItemIndex -= numberOfItems;
                } else {
                    // Move items (working top-to-bottom) from the more menu into the toolbar left part.
                    leftMostIndexToMove = this.rightMostItemIndex + 1;
                    rightMostIndexToMove = this.rightMostItemIndex + numberOfItems;

                    for (i = leftMostIndexToMove; i <= rightMostIndexToMove; i++) {
                        item = this.items.left[i].element;

                        item.insertBefore(this.ui.trigger);
                        item.removeClass('cms-toolbar-item-navigation-children');
                        item.find('> ul').removeAttr('style');
                    }

                    this.rightMostItemIndex += numberOfItems;
                }
            }

        });

    });
})(CMS.$);
<commit_msg>use cheaper hide/show<commit_after>/*
 * Copyright https://github.com/divio/django-cms
 */

// #############################################################################
// NAMESPACES
/**
 * @module CMS
 */
var CMS = window.CMS || {};

// #############################################################################
// Toolbar
(function ($) {
    'use strict';

    // shorthand for jQuery(document).ready();
    $(function () {
        /**
         * Responsible for creating usable navigation for narrow screens.
         *
         * @class Navigation
         * @namespace CMS
         * @uses CMS.API.Helpers
         */
        CMS.Navigation = new CMS.Class({

            implement: [CMS.API.Helpers],

            initialize: function initialize() {
                this._setupUI();
                this.getWidths();

                /** The zero based index of the right-most visible menu item of the left toolbar part. */
                this.rightMostItemIndex = this.items.left.length - 1;

                /** The zero based index of the left-most visible item of the right toolbar part. */
                this.leftMostItemIndex = 0;

                this._events();
            },

            /**
             * Cache UI jquery objects
             * @method _setupUI
             * @private
             */
            _setupUI: function _setupUI() {
                var trigger = $('.cms-toolbar-more');
                this.ui = {
                    window: $(window),
                    toolbarLeftPart: $('.cms-toolbar-left'),
                    toolbarRightPart: $('.cms-toolbar-right'),
                    trigger: trigger,
                    dropdown: trigger.find('> ul'),
                    toolbarTrigger: $('.cms-toolbar-trigger'),
                    logo: $('.cms-toolbar-item-logo')
                };
            },

            /**
             * Setup resize handler to construct the dropdown
             * @method _events
             * @private
             */
            _events: function _events() {
                this.ui.window.on('resize.cms load.cms', CMS.API.Helpers.throttle(
                    this._handleResize.bind(this), 50
                ));
            },

            /**
             * Calculates all the movable menu items widths
             * @method _getWidths
             */
            getWidths: function getWidths() {
                var that = this;
                that.items = {
                    left: [],
                    leftTotalWidth: 0,
                    right: [],
                    rightTotalWidth: 0,
                    moreButtonWidth: 0
                };
                var leftItems = that.ui.toolbarLeftPart
                    .find('.cms-toolbar-item-navigation > li:not(.cms-toolbar-more)');
                var rightItems = that.ui.toolbarRightPart.find('> .cms-toolbar-item');

                var getSize = function getSize(el, store) {
                    var element = $(el);
                    var width = $(el).outerWidth(true);

                    store.push({
                        element: element,
                        width: width
                    });
                };
                var sumWidths = function sumWidths(sum, item) {
                    return sum + item.width;
                };

                leftItems.each(function () {
                    getSize(this, that.items.left);
                });

                rightItems.each(function () {
                    getSize(this, that.items.right);
                });

                that.items.leftTotalWidth = that.items.left.reduce(sumWidths, 0);
                that.items.rightTotalWidth = that.items.right.reduce(sumWidths, 0);
                that.items.moreButtonWidth = that.ui.trigger.outerWidth();
            },

            /**
             * Calculates available width based on the state of the page
             * @method calculateAvailableWidth
             */
            calculateAvailableWidth: function calculateAvailableWidth() {
                var fullWidth = this.ui.window.width();
                var reduce = this.ui.toolbarTrigger.width() + this.ui.logo.offset().left +
                    this.ui.logo.outerWidth(true);

                return fullWidth - reduce;
            },

            /**
             * Shows the dropdown
             *
             * @method showDropdown
             */
            showDropdown: function showDropdown() {
                this.ui.trigger.css('display', 'list-item');
            },

            /**
             * Hides the dropdown
             *
             * @method hideDropdown
             */
            hideDropdown: function hideDropdown() {
                this.ui.trigger.css('display', 'none');
            },

            /**
             * Figures out if we need to show/hide/modify the dropdown
             *
             * @method _handleResize
             * @private
             */
            _handleResize: function _handleResize() {
                var remainingWidth;
                var availableWidth = this.calculateAvailableWidth();

                if (availableWidth > this.items.leftTotalWidth + this.items.rightTotalWidth) {
                    this.showAll();
                } else {
                    // first handle the left part
                    remainingWidth = availableWidth - this.items.moreButtonWidth - this.items.rightTotalWidth;
                    console.log('remainingWidth', remainingWidth);

                    // Figure out how many nav menu items fit into the available space.
                    var newRightMostItemIndex = -1;
                    while (remainingWidth - this.items.left[newRightMostItemIndex + 1].width >= 0) {
                        remainingWidth -= this.items.left[newRightMostItemIndex + 1].width;
                        newRightMostItemIndex++;
                    }

                    if (newRightMostItemIndex < this.rightMostItemIndex) {
                        this.moveToDropdown(this.rightMostItemIndex - newRightMostItemIndex);
                    } else if (this.rightMostItemIndex < newRightMostItemIndex) {
                        this.moveOutOfDropdown(newRightMostItemIndex - this.rightMostItemIndex);
                    }

                    this.showDropdown();

                    if (remainingWidth <= 0) {
                        console.log('do the right part');
                        remainingWidth += this.items.rightTotalWidth;

                        var newLeftMostItemIndex = this.items.right.length;
                        while (remainingWidth - this.items.right[newLeftMostItemIndex - 1].width > 0) {
                            remainingWidth -= this.items.right[newLeftMostItemIndex - 1].width;
                            newLeftMostItemIndex--;
                        }

                        if (newLeftMostItemIndex > this.leftMostItemIndex) {
                            this.moveToDropdown(newLeftMostItemIndex - this.leftMostItemIndex, 'right');
                        } else if (newLeftMostItemIndex < this.leftMostItemIndex) {
                            this.moveOutOfDropdown(this.leftMostItemIndex - newLeftMostItemIndex, 'right');
                        }
                    } else {
                        this.showAllRight();
                    }
                }
            },

            /**
             * Hides and empties dropdown
             *
             * @method showAll
             */
            showAll: function showAll() {
                this.showAllLeft();
                this.showAllRight();
                this.hideDropdown();
            },

            /**
             * Show all items in the left part of the toolbar
             *
             * @method showAllLeft
             */
            showAllLeft: function showAllLeft() {
                this.moveOutOfDropdown((this.items.left.length - 1) - this.rightMostItemIndex);
            },

            /**
             * Show all items in the right part of the toolbar
             *
             * @method showAllRight
             */
            showAllRight: function showAllRight() {
                this.moveOutOfDropdown(this.leftMostItemIndex, 'right');
            },

            /**
             * Moves items into the dropdown, reducing menu right-to-left in case it's a left part of toolbar
             * and left-to-right if it's right one
             *
             * @param numberOfItems {Number} how many items to move to dropdown
             * @param part {String} from which part to move to dropdown (defaults to left)
             */
            moveToDropdown: function moveToDropdown(numberOfItems, part) {
                if (numberOfItems <= 0) {
                    return;
                }

                var item;
                var leftMostIndexToMove;
                var rightMostIndexToMove;
                var i;

                if (part === 'right') {
                    console.log('moving from right part to dropdown');
                    // Move items (working left-to-right) from the toolbar left part to the more menu.
                    leftMostIndexToMove = this.leftMostItemIndex;
                    rightMostIndexToMove = this.leftMostItemIndex + numberOfItems - 1;
                    for (i = leftMostIndexToMove; i <= rightMostIndexToMove; i++) {
                        item = this.items.right[i].element;

                        this.ui.dropdown.append(item.wrap('

').parent());
                    }

                    this.leftMostItemIndex += numberOfItems;
                } else {
                    // Move items (working right-to-left) from the toolbar left part to the more menu.
                    rightMostIndexToMove = this.rightMostItemIndex;
                    leftMostIndexToMove = this.rightMostItemIndex - numberOfItems + 1;
                    for (i = rightMostIndexToMove; i >= leftMostIndexToMove; i--) {
                        item = this.items.left[i].element;

                        this.ui.dropdown.prepend(item);
                        if (item.find('> ul').children().length) {
                            item.addClass('cms-toolbar-item-navigation-children');
                        }
                    }

                    this.rightMostItemIndex -= numberOfItems;
                }
            },

            /**
             * Moves items out of the dropdown
             *
             * @param numberOfItems Number how many items to move out of the dropdown
             * @param part {String} to which part to move out of dropdown (defaults to left)
             */
            moveOutOfDropdown: function moveOutOfDropdown(numberOfItems, part) {
                if (numberOfItems <= 0) {
                    return;
                }

                var i;
                var item;
                var leftMostIndexToMove;
                var rightMostIndexToMove;

                if (part === 'right') {
                    console.log('moving out of right part');
                    // Move items (working bottom-to-top) from the more menu into the toolbar right part.
                    rightMostIndexToMove = this.leftMostItemIndex - 1;
                    leftMostIndexToMove = this.leftMostItemIndex - numberOfItems;

                    for (i = rightMostIndexToMove; i >= leftMostIndexToMove; i--) {
                        item = this.items.right[i].element;
                        item.unwrap('

');

                        item.prependTo(this.ui.toolbarRightPart);
                    }

                    this.leftMostItemIndex -= numberOfItems;
                } else {
                    // Move items (working top-to-bottom) from the more menu into the toolbar left part.
                    leftMostIndexToMove = this.rightMostItemIndex + 1;
                    rightMostIndexToMove = this.rightMostItemIndex + numberOfItems;

                    for (i = leftMostIndexToMove; i <= rightMostIndexToMove; i++) {
                        item = this.items.left[i].element;

                        item.insertBefore(this.ui.trigger);
                        item.removeClass('cms-toolbar-item-navigation-children');
                        item.find('> ul').removeAttr('style');
                    }

                    this.rightMostItemIndex += numberOfItems;
                }
            }

        });

    });
})(CMS.$);
<|endoftext|>


<commit_before>//= require ../../main

"use strict";

var
    esPhinx;

(function ($) {

    $.extend({

        Object: {

            type: function (object) {
                // /[^ ]+(?=\])/g
                return /[A-Z_]+[^\]]+/g.exec(Object.prototype.toString
                    .call(object))[0].replace(/ /g, "");
            },

            areEquivalents: function (object, comparator) {
                var
                    primitiveTypes =
                        /(number|string|boolean|null|undefined|symbol)/,
                    count = 0,
                    attributesCount,
                    objectAttrs,
                    comparatorAttrs,
                    objectMethods,
                    comparatorMethods,
                    objectAttrValue,
                    comparatorAttrValue;

                if (object == comparator) {
                    return true;
                } else if (Object.getPrototypeOf(object)
                    === Object.getPrototypeOf(comparator)) {
                    if (object instanceof Object
                        && !(object instanceof Function)) {
                        if (object instanceof Node) {
                            if (object.isEqualNode(comparator)) {
                                return true;
                            }
                        } else {
                            objectAttrs = $.Object.attributes(object);
                            comparatorAttrs = $.Object.attributes(comparator);
                            objectMethods = $.Object.methods(object);
                            comparatorMethods = $.Object.methods(comparator);

                            // if doesn't have attributes
                            if (!objectAttrs.length) {
                                if (objectMethods.length) {
                                    if (objectMethods.length
                                        == comparatorMethods.length
                                        && $.Object
                                            .areEquivalents(objectMethods,
                                            comparatorMethods)) {
                                        return true;
                                    }
                                } else if (objectMethods.length
                                    == comparatorMethods.length) {
                                    return true;
                                }
                            }

                            if (objectAttrs.length
                                == comparatorAttrs.length) {

                                for (let i of objectAttrs) {
                                    objectAttrValue = object[i];
                                    comparatorAttrValue = comparator[i];

                                    if (typeof objectAttrValue == "boolean"
                                        && typeof comparatorAttrValue
                                        == "boolean") {
                                        objectAttrValue = objectAttrValue
                                            .toString();
                                        comparatorAttrValue
                                            = comparatorAttrValue.toString();
                                    }

                                    if (objectAttrValue
                                        && comparatorAttrValue) {
                                        if (Object
                                            .getPrototypeOf(objectAttrValue)
                                            == Object.getPrototypeOf(
                                                comparatorAttrValue)) {
                                            if (objectAttrValue
                                                instanceof Object) {
                                                if ($.Object.areEquivalents(
                                                    objectAttrValue,
                                                    comparatorAttrValue)) {
                                                    count += 1;
                                                }
                                            } else if (objectAttrValue
                                                == comparatorAttrValue) {
                                                count += 1;
                                            }
                                        }

                                    } else if (objectAttrValue
                                        == comparatorAttrValue) {
                                        return true;
                                    }

                                }

                                attributesCount = objectAttrs.length;

                                if (count && count == attributesCount) {
                                    return true;
                                }
                            }
                        }

                    } else {
                        if (primitiveTypes.test(typeof object)) {
                            if (object == comparator) {
                                return true;
                            }
                        }
                    }
                }

                return false;
            },

            count: function (object, value) {
                var
                    length = Object.keys(object).length;

                if (value) {
                    Object.defineProperties(object, {
                        length: {
                            get: function () {
                                return length;
                            },
                            set: function (value) {
                                if (value == length) {
                                    length = value;
                                }
                            }
                        }
                    });
                }

                return length;
            },

            merge: function () {
                var
                    mainReference = arguments[0],
                    args = Array.from(arguments),
                    merged = {},
                    i;

                Iterator.each(mainReference, function (v, i) {
                    merged[i] = v;
                });

                for(i = 1; i < args.length; i++) {
                    if (Object.getPrototypeOf(args[i])
                        == Object.getPrototypeOf(Object)) {
                        Iterator.each(args[i], function (v, i) {
                            merged[i] = v;
                        });
                    }
                }

                return merged;
            },

            attributes: function (object) {
                var
                    attributes = [];

                Object.keys(object).forEach(function (property) {
                    if (typeof object[property] !== "function") {
                        attributes.push(property);
                    }
                });

                return attributes;
            },

            methods: function (object) {
                var
                    methods = [];

                Object.keys(object).forEach(function (property) {
                    if (typeof object[property] == "function") {
                        methods.push(property);
                    }
                });

                return methods;
            },

            asObject: function (object) {
                object = Iterator.asIterable(object);

                var newObject = {};

                Array.from(object).forEach(function (v, i) {
                    newObject[i] = v;
                });

                Iterator.toIterable(newObject);

                return newObject;
            },

            delete: function (object, index) {
                delete object[index];
                if (object.length) {
                    object.length -= 1;
                }
                return object;
            },

            indexOf: function (object, value) {
                for (let key of Object.getOwnPropertyNames(object)) {
                    if (object[key] == value) {
                        return key;
                    }
                }

                return undefined;
            },

            // firstOfSlice: function (object, slice, startingIndex = 0) {
            firstOfSlice: function (object, slice, startingIndex) {
                startingIndex = startingIndex || 0;

                for (let key of $.Object.attributes(object)) {
                    if (key >= startingIndex) {
                        if (object[key].search(slice) !== -1) {
                            return key;
                        }
                    }
                }

                return undefined;
            }

        }

    });

}(esPhinx));
<commit_msg>refactor and improves object<commit_after>//= require ../../main
//= require ../array

"use strict";

var
    esPhinx;

(function ($) {

    $.extend({

        Object: {

            type: function (object) {
                // /[^ ]+(?=\])/g
                return /[A-Z_]+[^\]]+/g.exec(Object.prototype.toString
                    .call(object))[0].replace(/ /g, "");
            },

            areEquivalents: function (object, comparator) {
                var
                    primitiveTypes =
                        /(number|string|boolean|null|undefined|symbol)/,
                    count = 0,
                    attributesCount,
                    objectAttrs,
                    comparatorAttrs,
                    objectMethods,
                    comparatorMethods,
                    objectAttrValue,
                    comparatorAttrValue;

                if (object == comparator) {
                    return true;
                } else if (Object.getPrototypeOf(object)
                    === Object.getPrototypeOf(comparator)) {
                    if (object instanceof Object
                        && !(object instanceof Function)) {
                        if (object instanceof Node) {
                            if (object.isEqualNode(comparator)) {
                                return true;
                            }
                        } else {
                            objectAttrs = this.attributes(object);
                            comparatorAttrs = this.attributes(comparator);
                            objectMethods = this.methods(object);
                            comparatorMethods = this.methods(comparator);

                            // if doesn't have attributes
                            if (!objectAttrs.length) {
                                if (objectMethods.length) {
                                    if (objectMethods.length
                                        == comparatorMethods.length
                                        && this
                                            .areEquivalents(objectMethods,
                                            comparatorMethods)) {
                                        return true;
                                    }
                                } else if (objectMethods.length
                                    == comparatorMethods.length) {
                                    return true;
                                }
                            }

                            if (objectAttrs.length
                                == comparatorAttrs.length) {

                                for (let i of objectAttrs) {
                                    objectAttrValue = object[i];
                                    comparatorAttrValue = comparator[i];

                                    if (typeof objectAttrValue == "boolean"
                                        && typeof comparatorAttrValue
                                        == "boolean") {
                                        objectAttrValue = objectAttrValue
                                            .toString();
                                        comparatorAttrValue
                                            = comparatorAttrValue.toString();
                                    }

                                    if (objectAttrValue
                                        && comparatorAttrValue) {
                                        if (Object
                                            .getPrototypeOf(objectAttrValue)
                                            == Object.getPrototypeOf(
                                                comparatorAttrValue)) {
                                            if (objectAttrValue
                                                instanceof Object) {
                                                if (this.areEquivalents(
                                                    objectAttrValue,
                                                    comparatorAttrValue)) {
                                                    count += 1;
                                                }
                                            } else if (objectAttrValue
                                                == comparatorAttrValue) {
                                                count += 1;
                                            }
                                        }

                                    } else if (objectAttrValue
                                        == comparatorAttrValue) {
                                        return true;
                                    }

                                }

                                attributesCount = objectAttrs.length;

                                if (count && count == attributesCount) {
                                    return true;
                                }
                            }
                        }

                    } else {
                        if (primitiveTypes.test(typeof object)) {
                            if (object == comparator) {
                                return true;
                            }
                        }
                    }
                }

                return false;
            },

            count: function (object, value) {
                var
                    length = Object.keys(object).length;

                if (value) {
                    Object.defineProperties(object, {
                        length: {
                            get: function () {
                                return length;
                            },
                            set: function (value) {
                                if (value == length) {
                                    length = value;
                                }
                            }
                        }
                    });
                }

                return length;
            },

            merge: function () {
                var
                    mainReference = arguments[0],
                    args = Array.from(arguments),
                    merged = {},
                    i;

                Iterator.each(mainReference, function (v, i) {
                    merged[i] = v;
                });

                for(i = 1; i < args.length; i++) {
                    if (Object.getPrototypeOf(args[i])
                        == Object.getPrototypeOf(Object)) {
                        Iterator.each(args[i], function (v, i) {
                            merged[i] = v;
                        });
                    }
                }

                return merged;
            },

            // attributes: function (object) {
            attributes: function (getNotEnumerable, object) {
                if (getNotEnumerable instanceof Object) {
                    object = getNotEnumerable;
                } else if (typeof getNotEnumerable !== "boolean") {
                    getNotEnumerable = false;
                }

                var
                    attributes = [],
                    properties = Object.keys(object);

                if (getNotEnumerable) {
                    properties = Object.getOwnPropertyNames(object);
                }

                properties.forEach(function (property) {
                    if (typeof object[property] !== "function") {
                        attributes.push(property);
                    }
                });

                return attributes;
            },

            methods: function (object) {
                var
                    methods = [],
                    properties = Object.getOwnPropertyNames(object);

                return properties.difference(this.attributes(true, object));
            },

            asObject: function (object) {
                object = Iterator.asIterable(object);

                var newObject = {};

                Array.from(object).forEach(function (v, i) {
                    newObject[i] = v;
                });

                Iterator.toIterable(newObject);

                return newObject;
            },

            delete: function (object, index) {
                delete object[index];
                if (object.length) {
                    object.length -= 1;
                }
                return object;
            },

            indexOf: function (object, value) {
                for (let key of Object.getOwnPropertyNames(object)) {
                    if (object[key] == value) {
                        return key;
                    }
                }

                return undefined;
            },

            // firstOfSlice: function (object, slice, startingIndex = 0) {
            firstOfSlice: function (object, slice, startingIndex) {
                startingIndex = startingIndex || 0;

                for (let key of this.attributes(object)) {
                    if (key >= startingIndex) {
                        if (object[key].search(slice) !== -1) {
                            return key;
                        }
                    }
                }

                return undefined;
            }

        }

    });

}(esPhinx));
<|endoftext|>


<commit_before>describe("cdb.admin.LayerPanelView", function() {

  var view;
  var map, table, sqlView, user, layer, vis;
  beforeEach(function() {
    map = new cdb.admin.Map();

    user = new cdb.admin.User({
      username: 'testusername',
      api_key: 'rabos'
    });

    vis = new cdb.admin.Visualization({
      map_id:  96,
      name:    "test_table",
      privacy: "PUBLIC",
      type:    "table"
    });

    var globalError = new cdb.admin.GlobalError({
      el: $('<div>')
    });

    layer = new cdb.admin.CartoDBLayer({
      table_name: 'test',
      id: 10,
      visible: 'true'
    });

    table = layer.table;
    map.layers.add(layer);

    view = new cdb.admin.LayerPanelView({
      model: layer,
      vis: vis,
      map: map,
      user: user,
      globalError: globalError
    });
  });

  it("should add map_key in layer", function() {
    expect(layer.get('extra_params').map_key).toEqual('rabos');
  });

  it("should hide/show the layer", function() {
    view.hide();
    expect(view.$('.sidebar').css('display')).toEqual('none');
    expect(view.$('.views').css('display')).toEqual('none');

    view.show();
    expect(view.$('.sidebar').css('display')).toEqual('block');
    expect(view.$('.views').css('display')).toEqual('block');
  });

  describe("layer initialization", function() {

    beforeEach(function() {
      //view.vis.set('type', 'derived');
    });

    it("should have 6 modules + 4 action buttons", function() {
      expect(view.buttons.length).toBe(10);
    });
  });

  describe("buttons behavior", function() {

    it("should show all the buttons when no sql is applied", function() {
      view.setActiveWorkView('table');
      var e = _(view.enabledButtonsForSection('table')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(5);

      view.setActiveWorkView('map');
      var e = _(view.enabledButtonsForSection('map')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(7);
    });

    it("should show readonly buttons when sql is applied", function() {
      table.useSQLView(view.sqlView);
      view.setActiveWorkView('table');
      var e = _(view.enabledButtonsForSection('table')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(2);

      view.setActiveWorkView('map');
      var e = _(view.enabledButtonsForSection('map')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(6);
    });

    it("should change to readonly buttons when sql is applied", function() {
      table.useSQLView(view.sqlView);
      view.setActiveWorkView('table');
      view.sqlView.modify_rows = false;
      view.sqlView.trigger('reset');
      var e = _(view.enabledButtonsForSection('table')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });

      expect(e.length).toEqual(2);
    });
  });

  describe("layer info", function() {

    it("should set layer name, order and options", function() {
      expect(view.$('.layer_info a.info .name').text()).toBe('test');
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
      expect(view.$('.layer_info div.right').css("display")).toBe('none');
    });

    it("should show layer option buttons if the visualization is the type derived", function() {
      view.vis.set('type', 'derived');
      expect(view.$('.layer_info div.right').css("display")).toBe('block');
    });

    it("should change the layer name if it changes", function() {
      view.dataLayer.set('table_name', 'jam');
      expect(view.$('.layer_info a.info .name').text()).toBe('jam');
    });

    it("shouldn't change the layer order if it changes, due to the visualization is the type table", function() {
      view.dataLayer.set('order', '4');
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
    });

    it("should change the layer order if it changes", function() {
      var ll= new cdb.admin.CartoDBLayer({
        table_name: 'test',
        id: 11,
        visible: 'true'
      });
      map.layers.add(ll, {at : 0});
      view.vis.set('type', 'derived');
      view.setLayerOrder(view.dataLayer);
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
    });

  });

  describe("layer actions", function() {

    beforeEach(function() {
      view.vis.set('type', 'derived');
    });

    it("should remove the layer", function() {
      view.$('a.remove').trigger('click');
      var removed = false;
      view.bind('delete', function() {
        removed = true;
      })
      view.trigger('delete', this);
      expect(removed).toBeTruthy();
    });

    it("should toggle the layer", function() {
      view.$('a.visibility').trigger('click');
      expect(view.model.get('visible')).toBeFalsy();
    });

    it("should hide infowindow if hides the layer", function() {
      view.model.infowindow.set('visibility', true);
      view.$('a.visibility').trigger('click');
      expect(view.model.infowindow.get('visibility')).toBeFalsy();
    });

    it("should active the layer", function() {
      var called = false;
      view.bind('switchTo', function() {
        called = true;
      })
      view.$('a.info').trigger('click');
      expect(called).toBeTruthy();
    });

    it("shouldn't remove a layer if visualization is a table type", function() {
      view.vis.set('type', 'table');
      view.$('a.remove').trigger('click');
      expect(view.remove_dlg).toBe(undefined);
    });

    it("shouldn't change layer visibility if visualization is a table type", function() {
      view.vis.set('type', 'table');
      view.$('a.visibility').trigger('click');
      expect(view.model.get('visible')).toBeTruthy();
    });

    it("should open a dropdown to choose a geometry", function() {
      view.$('.add_feature').click();
      expect(view.newGeomDropdown).toBeDefined();
      spyOn(view, '_addGeometry');
      view.newGeomDropdown.$('li:eq(0) a').click();
      expect(view._addGeometry).toHaveBeenCalled();
      view.newGeomDropdown.clean();
    });
  });
});
<commit_msg>new layer panel view specs added<commit_after>describe("cdb.admin.LayerPanelView", function() {

  var view;
  var map, table, sqlView, user, layer, vis;
  beforeEach(function() {
    map = new cdb.admin.Map();

    user = new cdb.admin.User({
      username: 'testusername',
      api_key: 'rabos'
    });

    vis = new cdb.admin.Visualization({
      map_id:  96,
      name:    "test_table",
      privacy: "PUBLIC",
      type:    "table"
    });

    var globalError = new cdb.admin.GlobalError({
      el: $('<div>')
    });

    layer = new cdb.admin.CartoDBLayer({
      table_name: 'test',
      id: 10,
      visible: 'true'
    });

    table = layer.table;
    map.layers.add(layer);

    view = new cdb.admin.LayerPanelView({
      model: layer,
      vis: vis,
      map: map,
      user: user,
      globalError: globalError
    });
  });

  it("should add map_key in layer", function() {
    expect(layer.get('extra_params').map_key).toEqual('rabos');
  });

  it("should hide/show the layer", function() {
    view.hide();
    expect(view.$('.sidebar').css('display')).toEqual('none');
    expect(view.$('.views').css('display')).toEqual('none');

    view.show();
    expect(view.$('.sidebar').css('display')).toEqual('block');
    expect(view.$('.views').css('display')).toEqual('block');
  });

  describe("layer initialization", function() {

    beforeEach(function() {
      //view.vis.set('type', 'derived');
    });

    it("should have 6 modules + 4 action buttons", function() {
      expect(view.buttons.length).toBe(10);
    });
  });

  describe("buttons behavior", function() {

    it("should show all the buttons when no sql is applied", function() {
      view.setActiveWorkView('table');
      var e = _(view.enabledButtonsForSection('table')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(5);

      view.setActiveWorkView('map');
      var e = _(view.enabledButtonsForSection('map')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(7);
    });

    it("should show readonly buttons when sql is applied", function() {
      table.useSQLView(view.sqlView);
      view.setActiveWorkView('table');
      var e = _(view.enabledButtonsForSection('table')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(2);

      view.setActiveWorkView('map');
      var e = _(view.enabledButtonsForSection('map')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });
      expect(e.length).toEqual(6);
    });

    it("should change to readonly buttons when sql is applied", function() {
      table.useSQLView(view.sqlView);
      view.setActiveWorkView('table');
      view.sqlView.modify_rows = false;
      view.sqlView.trigger('reset');
      var e = _(view.enabledButtonsForSection('table')).filter(function(b) {
        return b.$el.css('display') != 'none'
      });

      expect(e.length).toEqual(2);
    });
  });

  describe("layer info", function() {

    it("should set layer name, order and options", function() {
      expect(view.$('.layer_info a.info .name').text()).toBe('test');
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
      expect(view.$('.layer_info div.right').css("display")).toBe('none');
    });

    it("should show layer option buttons if the visualization is the type derived", function() {
      view.vis.set('type', 'derived');
      expect(view.$('.layer_info div.right').css("display")).toBe('block');
    });

    it("should change the layer name if it changes", function() {
      view.dataLayer.set('table_name', 'jam');
      expect(view.$('.layer_info a.info .name').text()).toBe('jam');
    });

    it("shouldn't change the layer order if it changes, due to the visualization is the type table", function() {
      view.dataLayer.set('order', '4');
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
    });

    it("should change the layer order if it changes", function() {
      var ll= new cdb.admin.CartoDBLayer({
        table_name: 'test',
        id: 11,
        visible: 'true'
      });
      map.layers.add(ll, {at : 0});
      view.vis.set('type', 'derived');
      view.setLayerOrder(view.dataLayer);
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
    });

    it("should add alias if the layer is in a visualization", function() {
      view.vis.set('type', 'derived');
      view.setLayerName(view.dataLayer);
      expect(view.$('.layer_info a.info .name').text()).toBe('test');
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
      expect(view.$('.layer_info a.info .name_info').text()).toBe('view of test');
    });

    it("should add alias if the layer is in a visualization", function() {
      view.vis.set('type', 'derived');
      view.model.set('table_name', 'test_jamon');
      view.setLayerName(view.dataLayer);

      expect(view.$('.layer_info a.info .name').text()).toBe('test jamon');
      expect(view.$('.layer_info a.info .order').text()).toBe('1');
      expect(view.$('.layer_info a.info .name_info').text()).toBe('view of test_jamon');
    });

    it("should be able to change alias if layer is in a visualization", function() {
      view.vis.set('type', 'derived');
      view.$('.layer_info a.info .name').dblclick();
      expect(view.$('.layer_info input.alias').css('display')).not.toBe('none');
    });

    it("shouldn't be able to change alias if layer is NOT in a visualization", function() {
      view.$('.layer_info a.info .name').dblclick();
      expect(view.$('.layer_info input.alias').is(':visible')).toBe(false);
    });

  });

  describe("layer actions", function() {

    beforeEach(function() {
      view.vis.set('type', 'derived');
    });

    it("should remove the layer", function() {
      view.$('a.remove').trigger('click');
      var removed = false;
      view.bind('delete', function() {
        removed = true;
      })
      view.trigger('delete', this);
      expect(removed).toBeTruthy();
    });

    it("should toggle the layer", function() {
      view.$('a.visibility').trigger('click');
      expect(view.model.get('visible')).toBeFalsy();
    });

    it("should hide infowindow if hides the layer", function() {
      view.model.infowindow.set('visibility', true);
      view.$('a.visibility').trigger('click');
      expect(view.model.infowindow.get('visibility')).toBeFalsy();
    });

    it("should active the layer", function() {
      var called = false;
      view.bind('switchTo', function() {
        called = true;
      })
      view.$('a.info').trigger('click');
      expect(called).toBeTruthy();
    });

    it("shouldn't remove a layer if visualization is a table type", function() {
      view.vis.set('type', 'table');
      view.$('a.remove').trigger('click');
      expect(view.remove_dlg).toBe(undefined);
    });

    it("shouldn't change layer visibility if visualization is a table type", function() {
      view.vis.set('type', 'table');
      view.$('a.visibility').trigger('click');
      expect(view.model.get('visible')).toBeTruthy();
    });

    it("should open a dropdown to choose a geometry", function() {
      view.$('.add_feature').click();
      expect(view.newGeomDropdown).toBeDefined();
      spyOn(view, '_addGeometry');
      view.newGeomDropdown.$('li:eq(0) a').click();
      expect(view._addGeometry).toHaveBeenCalled();
      view.newGeomDropdown.clean();
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var subprogramTemplate = function(){
  console.log("In subprogramTEmplate 1");
  console.log(this);
  console.log("In subprogramTemplate");
  return "project-pages/imagemanipulation-project/" + this.require + ".html";
};

angular
  .module('projectPage')
  .component('resizeSubprogram', {
    templateUrl: subprogramTemplate,
    controller: ['$resource', '$window',
      function subprogramController($resource) {
        var self = this;

        var cgiURL = 'https://ideallyconnected.me/cgi-bin/cs50/pset4/resize.sh?multiplier=:multiplier&subbtn=Submit';
        var request = $resource(cgiURL, null, {
            newimage: {
              method: 'GET',
              headers: {
                'Content-type': 'text/html'
              },
              transformResponse: function (data) {
                self.httpResponseData = data;
              },
              cache: false
            }
          }
        );

        // Called during form submission
        this.submit = function (multiplier) {
          self.requestResult = request.newimage({multiplier: multiplier});
        };

      }]
  });
<commit_msg>removed print / console.log statements<commit_after>'use strict';

var subprogramTemplate = function(){
  return "project-pages/imagemanipulation-project/" + this.require + ".html";
};

angular
  .module('projectPage')
  .component('resizeSubprogram', {
    templateUrl: subprogramTemplate,
    controller: ['$resource', '$window',
      function subprogramController($resource) {
        var self = this;

        var cgiURL = 'https://ideallyconnected.me/cgi-bin/cs50/pset4/resize.sh?multiplier=:multiplier&subbtn=Submit';
        var request = $resource(cgiURL, null, {
            newimage: {
              method: 'GET',
              headers: {
                'Content-type': 'text/html'
              },
              transformResponse: function (data) {
                self.httpResponseData = data;
              },
              cache: false
            }
          }
        );

        this.submit = function (multiplier) {
          self.requestResult = request.newimage({multiplier: multiplier});
        };

      }]
  });
<|endoftext|>


<commit_before>/** @format */
import statemachine from "@/statemachine"

let html = String.raw
export const simpleSearchComponent = {
    template: html`

            <global-filters lang="lang"></global-filters>

                <form class="simple_form">
                    <autoc
                        id="simple_text"
                        input="$ctrl.input"
                        is-raw-input="$ctrl.isRawInput"
                        type="lemgram"
                        disable-lemgram-autocomplete="$ctrl.disableLemgramAutocomplete"
                        on-change="$ctrl.onChange(output, isRawOutput)"
                    ></autoc>
                    <search-submit
                        on-search="$ctrl.updateSearch()"
                        on-search-save="$ctrl.onSearchSave(name)"
                    ></search-submit>

                        <input id="inOrderChk" type="checkbox" ng-model="$ctrl.inOrder" />
                         {{'in_order_chk' | loc:$root.lang}}
                         {{'and' | loc:$root.lang}}
                         {{'and_include' | loc:$root.lang}}
                        <input id="prefixChk" type="checkbox" ng-model="$ctrl.prefix" />
                         {{'prefix_chk' | loc:$root.lang}}
                        <input id="midChk" type="checkbox" ng-model="$ctrl.mid_comp" />
                         {{'compound_middle' | loc:$root.lang}}
                        <input id="suffixChk" type="checkbox" ng-model="$ctrl.suffix" />
                         {{'suffix_chk' | loc:$root.lang}}
                         {{'and' | loc:$root.lang}}
                        <input id="caseChk" type="checkbox" ng-model="$ctrl.isCaseInsensitive" />
                         {{'case_insensitive' | loc:$root.lang}}

                </form>

                    <button
                        class="btn btn-sm btn-default"
                        ng-click="$ctrl.showAllRelated()"
                        ng-if="$ctrl.relatedObj.length != 0"
                    >
                        {{ 'similar_header' | loc:$root.lang }} (SWE-FN)

                            {{$ctrl.stringifyRelated(wd)}},

                            {{$ctrl.stringifyRelated(wd)}},  $ctrl.relatedDefault || $ctrl.relatedObj.length > 1"
                        >
                            ...
                    </button>

                        {{ 'similar_header' | loc:$root.lang }} (SWE-FN)
{{'no_related_words' | loc:$root.lang}}

    `,
    bindings: {
        wordPic: "<",
    },
    controller: [
        "$location",
        "backend",
        "$rootScope",
        "searches",
        "compareSearches",
        "$uibModal",
        "$timeout",
        function ($location, backend, $rootScope, searches, compareSearches, $uibModal, $timeout) {
            const ctrl = this

            ctrl.disableLemgramAutocomplete = !settings.autocomplete

            statemachine.listen("lemgram_search", (event) => {
                ctrl.input = event.value
                ctrl.isRawInput = false
                ctrl.onChange(event.value, false)
            })

            ctrl.inOrder = $location.search().in_order == null
            ctrl.prefix = $location.search().prefix != null
            ctrl.mid_comp = $location.search().mid_comp != null
            ctrl.suffix = $location.search().suffix != null
            if (settings.inputCaseInsensitiveDefault) {
                ctrl.isCaseInsensitive = true
                $location.search("isCaseInsensitive", "")
            } else {
                ctrl.isCaseInsensitive = $location.search().isCaseInsensitive != null
            }

            // triggers watch on searches.activeSearch
            ctrl.updateSearch = function () {
                $location.search("in_order", !ctrl.inOrder ? false : null)
                $location.search("prefix", ctrl.prefix ? true : null)
                $location.search("mid_comp", ctrl.mid_comp ? true : null)
                $location.search("suffix", ctrl.suffix ? true : null)
                $location.search("isCaseInsensitive", ctrl.isCaseInsensitive ? true : null)

                $location.search("within", null)
                locationSearch("search", null)
                $rootScope.simpleCQP = CQP.expandOperators(ctrl.getCQP())
                $timeout(function () {
                    if (ctrl.currentText) {
                        util.searchHash("word", ctrl.currentText)
                    } else if (ctrl.lemgram) {
                        util.searchHash("lemgram", ctrl.lemgram)
                    }
                }, 0)
            }

            ctrl.getCQP = function () {
                let suffix, val
                const currentText = (ctrl.currentText || "").trim()

                if (currentText) {
                    suffix = ctrl.isCaseInsensitive ? " %c" : ""
                    const wordArray = currentText.split(" ")
                    const tokenArray = _.map(wordArray, (token) => {
                        const orParts = []
                        if (ctrl.prefix) {
                            orParts.push(token + ".*")
                        }
                        if (ctrl.mid_comp) {
                            orParts.push(`.*${token}.*`)
                        }
                        if (ctrl.suffix) {
                            orParts.push(`.*${token}`)
                        }
                        if (!(ctrl.prefix || ctrl.suffix)) {
                            orParts.push(regescape(token))
                        }
                        const res = _.map(orParts, (orPart) => `word = "${orPart}"${suffix}`)
                        return `[${res.join(" | ")}]`
                    })
                    val = tokenArray.join(" ")
                } else if (ctrl.lemgram) {
                    const lemgram = ctrl.lemgram
                    val = `[lex contains \"${lemgram}\"`
                    if (ctrl.prefix) {
                        val += ` | complemgram contains \"${lemgram}\\+.*\"`
                    }
                    if (ctrl.mid_comp) {
                        val += ` | complemgram contains \".*\\+${lemgram}\\+.*\"`
                    }
                    if (ctrl.suffix) {
                        val += ` | complemgram contains \".*\\+${lemgram}:.*\"`
                    }
                    val += "]"
                }

                if ($rootScope.globalFilter) {
                    val = CQP.stringify(CQP.mergeCqpExprs(CQP.parse(val || "[]"), $rootScope.globalFilter))
                }

                return val
            }

            ctrl.onSearchSave = (name) => {
                compareSearches.saveSearch(name, ctrl.getCQP())
            }

            ctrl.stringifyRelated = (wd) => util.saldoToString(wd)

            ctrl.relatedDefault = 3

            ctrl.showAllRelated = () => {
                const scope = $rootScope.$new()
                scope.stringifyRelatedHeader = (wd) => wd.replace(/_/g, " ")
                scope.clickX = () => modalInstance.dismiss()
                scope.stringifyRelated = ctrl.stringifyRelated
                scope.relatedObj = ctrl.relatedObj
                scope.clickRelated = function (wd, attribute) {
                    let cqp
                    if (modalInstance != null) {
                        modalInstance.close()
                    }
                    $rootScope.searchtabs()[1].tab.select()
                    if (attribute === "saldo") {
                        cqp = `[saldo contains \"${regescape(wd)}\"]`
                    } else {
                        cqp = `[sense rank_contains \"${regescape(wd)}\"]`
                    }
                    statemachine.send("SEARCH_CQP", { cqp })
                }
                const modalInstance = $uibModal.open({
                    template: `\

{{'similar_header' | loc:$root.lang}} (SWE-FN)

                            ×

{{stringifyRelatedHeader(obj.label)}}

 {{stringifyRelated(wd) + " "}}

\
                        `,
                    scope,
                    size: "lg",
                    windowClass: "related",
                })
            }

            $rootScope.searches = searches
            $rootScope.$watch("searches.activeSearch", function (search) {
                if (!search) {
                    return
                }
                if (search.type === "word" || search.type === "lemgram") {
                    if (search.type === "word") {
                        ctrl.input = search.val
                        ctrl.isRawInput = true
                        ctrl.currentText = search.val
                    } else {
                        ctrl.input = unregescape(search.val)
                        ctrl.isRawInput = false
                        ctrl.lemgram = search.val
                    }
                    ctrl.doSearch()
                } else {
                    if ("lemgramResults" in window) {
                        lemgramResults.resetView()
                    }
                }
            })

            ctrl.onChange = (output, isRawOutput) => {
                if (isRawOutput) {
                    ctrl.currentText = output
                    ctrl.lemgram = null
                } else {
                    ctrl.lemgram = regescape(output)
                    ctrl.currentText = null
                }
            }

            ctrl.doSearch = function () {
                const search = searches.activeSearch
                ctrl.relatedObj = null
                const cqp = ctrl.getCQP()
                searches.kwicSearch(cqp, search && search.pageOnly)

                if (!(search && search.pageOnly)) {
                    if (search.type === "lemgram") {
                        let sense = false
                        let saldo = false
                        for (let corpus of settings.corpusListing.selected) {
                            if ("sense" in corpus.attributes) {
                                sense = true
                            }
                            if ("saldo" in corpus.attributes) {
                                saldo = true
                            }
                        }

                        if (sense || saldo) {
                            backend.relatedWordSearch(unregescape(search.val)).then(function (data) {
                                ctrl.relatedObj = data
                                if (data.length > 2 && data[0].label == "Excreting") {
                                    let [first, second, ...rest] = data
                                    ctrl.relatedObj.data = [second, first, ...rest]
                                }
                                ctrl.relatedObj.attribute = sense ? "sense" : "saldo"
                            })
                        }
                    }

                    if (ctrl.wordPic && (search.type === "lemgram" || !search.val.includes(" "))) {
                        const value = search.type === "lemgram" ? unregescape(search.val) : search.val
                        return searches.lemgramSearch(value, search.type)
                    } else {
                        if ("lemgramResults" in window) {
                            lemgramResults.resetView()
                        }
                    }
                }
            }
        },
    ],
}
<commit_msg>set simpleCQP used in advanced tab in correct place<commit_after>/** @format */
import statemachine from "@/statemachine"

let html = String.raw
export const simpleSearchComponent = {
    template: html`

            <global-filters lang="lang"></global-filters>

                <form class="simple_form">
                    <autoc
                        id="simple_text"
                        input="$ctrl.input"
                        is-raw-input="$ctrl.isRawInput"
                        type="lemgram"
                        disable-lemgram-autocomplete="$ctrl.disableLemgramAutocomplete"
                        on-change="$ctrl.onChange(output, isRawOutput)"
                    ></autoc>
                    <search-submit
                        on-search="$ctrl.updateSearch()"
                        on-search-save="$ctrl.onSearchSave(name)"
                    ></search-submit>

                        <input id="inOrderChk" type="checkbox" ng-model="$ctrl.inOrder" />
                         {{'in_order_chk' | loc:$root.lang}}
                         {{'and' | loc:$root.lang}}
                         {{'and_include' | loc:$root.lang}}
                        <input id="prefixChk" type="checkbox" ng-model="$ctrl.prefix" />
                         {{'prefix_chk' | loc:$root.lang}}
                        <input id="midChk" type="checkbox" ng-model="$ctrl.mid_comp" />
                         {{'compound_middle' | loc:$root.lang}}
                        <input id="suffixChk" type="checkbox" ng-model="$ctrl.suffix" />
                         {{'suffix_chk' | loc:$root.lang}}
                         {{'and' | loc:$root.lang}}
                        <input id="caseChk" type="checkbox" ng-model="$ctrl.isCaseInsensitive" />
                         {{'case_insensitive' | loc:$root.lang}}

                </form>

                    <button
                        class="btn btn-sm btn-default"
                        ng-click="$ctrl.showAllRelated()"
                        ng-if="$ctrl.relatedObj.length != 0"
                    >
                        {{ 'similar_header' | loc:$root.lang }} (SWE-FN)

                            {{$ctrl.stringifyRelated(wd)}},

                            {{$ctrl.stringifyRelated(wd)}},  $ctrl.relatedDefault || $ctrl.relatedObj.length > 1"
                        >
                            ...
                    </button>

                        {{ 'similar_header' | loc:$root.lang }} (SWE-FN)
{{'no_related_words' | loc:$root.lang}}

    `,
    bindings: {
        wordPic: "<",
    },
    controller: [
        "$location",
        "backend",
        "$rootScope",
        "searches",
        "compareSearches",
        "$uibModal",
        "$timeout",
        function ($location, backend, $rootScope, searches, compareSearches, $uibModal, $timeout) {
            const ctrl = this

            ctrl.disableLemgramAutocomplete = !settings.autocomplete

            statemachine.listen("lemgram_search", (event) => {
                ctrl.input = event.value
                ctrl.isRawInput = false
                ctrl.onChange(event.value, false)
            })

            ctrl.inOrder = $location.search().in_order == null
            ctrl.prefix = $location.search().prefix != null
            ctrl.mid_comp = $location.search().mid_comp != null
            ctrl.suffix = $location.search().suffix != null
            if (settings.inputCaseInsensitiveDefault) {
                ctrl.isCaseInsensitive = true
                $location.search("isCaseInsensitive", "")
            } else {
                ctrl.isCaseInsensitive = $location.search().isCaseInsensitive != null
            }

            // triggers watch on searches.activeSearch
            ctrl.updateSearch = function () {
                $location.search("in_order", !ctrl.inOrder ? false : null)
                $location.search("prefix", ctrl.prefix ? true : null)
                $location.search("mid_comp", ctrl.mid_comp ? true : null)
                $location.search("suffix", ctrl.suffix ? true : null)
                $location.search("isCaseInsensitive", ctrl.isCaseInsensitive ? true : null)

                $location.search("within", null)
                locationSearch("search", null)
                $timeout(function () {
                    if (ctrl.currentText) {
                        util.searchHash("word", ctrl.currentText)
                    } else if (ctrl.lemgram) {
                        util.searchHash("lemgram", ctrl.lemgram)
                    }
                }, 0)
            }

            ctrl.getCQP = function () {
                let suffix, val
                const currentText = (ctrl.currentText || "").trim()

                if (currentText) {
                    suffix = ctrl.isCaseInsensitive ? " %c" : ""
                    const wordArray = currentText.split(" ")
                    const tokenArray = _.map(wordArray, (token) => {
                        const orParts = []
                        if (ctrl.prefix) {
                            orParts.push(token + ".*")
                        }
                        if (ctrl.mid_comp) {
                            orParts.push(`.*${token}.*`)
                        }
                        if (ctrl.suffix) {
                            orParts.push(`.*${token}`)
                        }
                        if (!(ctrl.prefix || ctrl.suffix)) {
                            orParts.push(regescape(token))
                        }
                        const res = _.map(orParts, (orPart) => `word = "${orPart}"${suffix}`)
                        return `[${res.join(" | ")}]`
                    })
                    val = tokenArray.join(" ")
                } else if (ctrl.lemgram) {
                    const lemgram = ctrl.lemgram
                    val = `[lex contains \"${lemgram}\"`
                    if (ctrl.prefix) {
                        val += ` | complemgram contains \"${lemgram}\\+.*\"`
                    }
                    if (ctrl.mid_comp) {
                        val += ` | complemgram contains \".*\\+${lemgram}\\+.*\"`
                    }
                    if (ctrl.suffix) {
                        val += ` | complemgram contains \".*\\+${lemgram}:.*\"`
                    }
                    val += "]"
                }

                if ($rootScope.globalFilter) {
                    val = CQP.stringify(CQP.mergeCqpExprs(CQP.parse(val || "[]"), $rootScope.globalFilter))
                }

                return val
            }

            ctrl.onSearchSave = (name) => {
                compareSearches.saveSearch(name, ctrl.getCQP())
            }

            ctrl.stringifyRelated = (wd) => util.saldoToString(wd)

            ctrl.relatedDefault = 3

            ctrl.showAllRelated = () => {
                const scope = $rootScope.$new()
                scope.stringifyRelatedHeader = (wd) => wd.replace(/_/g, " ")
                scope.clickX = () => modalInstance.dismiss()
                scope.stringifyRelated = ctrl.stringifyRelated
                scope.relatedObj = ctrl.relatedObj
                scope.clickRelated = function (wd, attribute) {
                    let cqp
                    if (modalInstance != null) {
                        modalInstance.close()
                    }
                    $rootScope.searchtabs()[1].tab.select()
                    if (attribute === "saldo") {
                        cqp = `[saldo contains \"${regescape(wd)}\"]`
                    } else {
                        cqp = `[sense rank_contains \"${regescape(wd)}\"]`
                    }
                    statemachine.send("SEARCH_CQP", { cqp })
                }
                const modalInstance = $uibModal.open({
                    template: `\

{{'similar_header' | loc:$root.lang}} (SWE-FN)

                            ×

{{stringifyRelatedHeader(obj.label)}}

 {{stringifyRelated(wd) + " "}}

\
                        `,
                    scope,
                    size: "lg",
                    windowClass: "related",
                })
            }

            $rootScope.searches = searches
            $rootScope.$watch("searches.activeSearch", function (search) {
                if (!search) {
                    return
                }
                if (search.type === "word" || search.type === "lemgram") {
                    if (search.type === "word") {
                        ctrl.input = search.val
                        ctrl.isRawInput = true
                        ctrl.currentText = search.val
                    } else {
                        ctrl.input = unregescape(search.val)
                        ctrl.isRawInput = false
                        ctrl.lemgram = search.val
                    }
                    $rootScope.simpleCQP = CQP.expandOperators(ctrl.getCQP())
                    ctrl.doSearch()
                } else {
                    if ("lemgramResults" in window) {
                        lemgramResults.resetView()
                    }
                }
            })

            ctrl.onChange = (output, isRawOutput) => {
                if (isRawOutput) {
                    ctrl.currentText = output
                    ctrl.lemgram = null
                } else {
                    ctrl.lemgram = regescape(output)
                    ctrl.currentText = null
                }
            }

            ctrl.doSearch = function () {
                const search = searches.activeSearch
                ctrl.relatedObj = null
                const cqp = ctrl.getCQP()
                searches.kwicSearch(cqp, search && search.pageOnly)

                if (!(search && search.pageOnly)) {
                    if (search.type === "lemgram") {
                        let sense = false
                        let saldo = false
                        for (let corpus of settings.corpusListing.selected) {
                            if ("sense" in corpus.attributes) {
                                sense = true
                            }
                            if ("saldo" in corpus.attributes) {
                                saldo = true
                            }
                        }

                        if (sense || saldo) {
                            backend.relatedWordSearch(unregescape(search.val)).then(function (data) {
                                ctrl.relatedObj = data
                                if (data.length > 2 && data[0].label == "Excreting") {
                                    let [first, second, ...rest] = data
                                    ctrl.relatedObj.data = [second, first, ...rest]
                                }
                                ctrl.relatedObj.attribute = sense ? "sense" : "saldo"
                            })
                        }
                    }

                    if (ctrl.wordPic && (search.type === "lemgram" || !search.val.includes(" "))) {
                        const value = search.type === "lemgram" ? unregescape(search.val) : search.val
                        return searches.lemgramSearch(value, search.type)
                    } else {
                        if ("lemgramResults" in window) {
                            lemgramResults.resetView()
                        }
                    }
                }
            }
        },
    ],
}
<|endoftext|>