<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { PermissionsPropType, getPermissions, DEFAULT_PERMISSIONS } from '../../permissions/PermissionsStorage';
import { getEdmObject } from '../../edm/EdmStorage';
import LoadingSpinner from '../../../components/asynccontent/LoadingSpinner';
import DocumentTitle from 'react-document-title';
import * as psActionFactory from '../PermissionsSummaryActionFactory';
import * as actionFactories from '../../entitysetdetail/EntitySetDetailActionFactories';
import * as edmActionFactories from '../../edm/EdmActionFactories';
import * as PermissionsActionFactory from '../../permissions/PermissionsActionFactory';
import UserPermissionsTable from './UserPermissionsTable';
import RolePermissionsTable from './RolePermissionsTable';
import Page from '../../../components/page/Page';
import styles from '../styles.module.css';

const U_HEADERS = ['Users', 'Roles', 'Permissions'];
const R_HEADERS = ['Roles', 'Permissions'];

class AllPermissions extends React.Component {
  static propTypes = {
    params: PropTypes.object.isRequired,
    entitySet: PropTypes.object,
    entityUserPermissions: PropTypes.array.isRequired,
    entityRolePermissions: PropTypes.object.isRequired,
    propertyPermissions: PropTypes.object.isRequired,
    loadEntitySet: PropTypes.func.isRequired,
    getAllUsersAndRolesRequest: PropTypes.func.isRequired,
    isGettingUsersRoles: PropTypes.bool.isRequired,
    isGettingAcls: PropTypes.bool.isRequired,
    isGettingPermissions: PropTypes.bool.isRequired
  }

  componentDidMount() {
    const id = this.props.params.id;
    this.props.loadEntitySet(id);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.entitySet === undefined && nextProps.entitySet !== undefined) {
      this.props.getAllUsersAndRolesRequest(nextProps.entitySet);
    }
  }

  renderEntityTables() {
    return (

Entity Permissions

        <RolePermissionsTable
            rolePermissions={this.props.entityRolePermissions}
            headers={R_HEADERS} />
        <UserPermissionsTable
            userPermissions={this.props.entityUserPermissions}
            rolePermissions={this.props.entityRolePermissions}
            headers={U_HEADERS} />

    );
  }

  renderPropertyTables() {
    const { propertyPermissions } = this.props;
    const tables = [];

    Object.keys(propertyPermissions).forEach((property) => {
      const rolePermissions = propertyPermissions[property].rolePermissions || [];
      const userPermissions = propertyPermissions[property].userPermissions || [];
      const header = <h3 key={`header-${property}`}>{property} Permissions
;
      const roleTable = (<RolePermissionsTable
          rolePermissions={rolePermissions}
          headers={R_HEADERS}
          key={`role-${property}`} />);
      const userTable = (<UserPermissionsTable
          property={property}
          userPermissions={userPermissions}
          rolePermissions={rolePermissions}
          headers={U_HEADERS}
          key={`user-${property}`} />);

      tables.push(header, roleTable, userTable);
    });
    return tables;
  }

  renderTables() {
    return (

        {this.renderEntityTables()}
        {this.renderPropertyTables()}

    );
  }

  renderContent() {
    return (this.props.isGettingUsersRoles || this.props.isGettingAcls || this.props.isGettingPermissions)
    ? <LoadingSpinner />
    : this.renderTables();
  }

  getEntitySetTitle() {
    return this.props.entitySet ? this.props.entitySet.title : null;
  }

  render() {
    return (
      <DocumentTitle title="All Permissions">
        <Page>
          <Page.Header>
            <Page.Title>Permissions Summary</Page.Title>

{this.getEntitySetTitle()}

          </Page.Header>
          <Page.Body>
            {this.renderContent()}
          </Page.Body>
        </Page>
      </DocumentTitle>
    );
  }
}

// TODO: Move EntitySet calculations to helper functions/epics & reuse in EntitySetDetailComponent
function mapStateToProps(state) {
  const entitySetDetail = state.get('entitySetDetail');
  const normalizedData = state.get('normalizedData');
  const permissionsSummary = state.get('permissionsSummary');
  let entitySet;
  const reference = entitySetDetail.get('entitySetReference');
  if (reference) {
    entitySet = getEdmObject(normalizedData.toJS(), reference.toJS());
  }

  return {
    entitySet,
    entityUserPermissions: permissionsSummary.get('entityUserPermissions').toJS(),
    entityRolePermissions: permissionsSummary.get('entityRolePermissions').toJS(),
    propertyPermissions: permissionsSummary.get('propertyPermissions').toJS(),
    isGettingUsersRoles: permissionsSummary.get('isGettingUsersRoles'),
    isGettingAcls: permissionsSummary.get('isGettingAcls'),
    isGettingPermissions: permissionsSummary.get('isGettingPermissions')
  };
}

function mapDispatchToProps(dispatch) {
  return {
    loadEntitySet: (id) => {
      dispatch(actionFactories.entitySetDetailRequest(id));
      dispatch(PermissionsActionFactory.getEntitySetsAuthorizations([id]));
      dispatch(edmActionFactories.filteredEdmRequest(
        [{
          type: 'EntitySet',
          id,
          include: ['EntitySet', 'EntityType', 'PropertyTypeInEntitySet']
        }]
      ));
    },
    getAllUsersAndRolesRequest: (id) => {
      dispatch(psActionFactory.getAllUsersAndRolesRequest(id));
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(AllPermissions);
<commit_msg>Use bindActionCreators<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { PermissionsPropType, getPermissions, DEFAULT_PERMISSIONS } from '../../permissions/PermissionsStorage';
import { getEdmObject } from '../../edm/EdmStorage';
import LoadingSpinner from '../../../components/asynccontent/LoadingSpinner';
import DocumentTitle from 'react-document-title';
import * as psActionFactory from '../PermissionsSummaryActionFactory';
import * as actionFactories from '../../entitysetdetail/EntitySetDetailActionFactories';
import * as edmActionFactories from '../../edm/EdmActionFactories';
import * as PermissionsActionFactory from '../../permissions/PermissionsActionFactory';
import UserPermissionsTable from './UserPermissionsTable';
import RolePermissionsTable from './RolePermissionsTable';
import Page from '../../../components/page/Page';
import styles from '../styles.module.css';

const U_HEADERS = ['Users', 'Roles', 'Permissions'];
const R_HEADERS = ['Roles', 'Permissions'];

class AllPermissions extends React.Component {
  static propTypes = {
    actions: React.PropTypes.shape({
      getAllUsersAndRolesRequest: React.PropTypes.func.isRequired
    }).isRequired,
    params: PropTypes.object.isRequired,
    entitySet: PropTypes.object,
    entityUserPermissions: PropTypes.array.isRequired,
    entityRolePermissions: PropTypes.object.isRequired,
    propertyPermissions: PropTypes.object.isRequired,
    loadEntitySet: PropTypes.func.isRequired,
    isGettingUsersRoles: PropTypes.bool.isRequired,
    isGettingAcls: PropTypes.bool.isRequired,
    isGettingPermissions: PropTypes.bool.isRequired
  }

  componentDidMount() {
    const id = this.props.params.id;
    this.props.loadEntitySet(id);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.entitySet === undefined && nextProps.entitySet !== undefined) {
      this.props.actions.getAllUsersAndRolesRequest(nextProps.entitySet);
    }
  }

  renderEntityTables() {
    return (

Entity Permissions

        <RolePermissionsTable
            rolePermissions={this.props.entityRolePermissions}
            headers={R_HEADERS} />
        <UserPermissionsTable
            userPermissions={this.props.entityUserPermissions}
            rolePermissions={this.props.entityRolePermissions}
            headers={U_HEADERS} />

    );
  }

  renderPropertyTables() {
    const { propertyPermissions } = this.props;
    const tables = [];

    Object.keys(propertyPermissions).forEach((property) => {
      const rolePermissions = propertyPermissions[property].rolePermissions || [];
      const userPermissions = propertyPermissions[property].userPermissions || [];
      const header = <h3 key={`header-${property}`}>{property} Permissions
;
      const roleTable = (<RolePermissionsTable
          rolePermissions={rolePermissions}
          headers={R_HEADERS}
          key={`role-${property}`} />);
      const userTable = (<UserPermissionsTable
          property={property}
          userPermissions={userPermissions}
          rolePermissions={rolePermissions}
          headers={U_HEADERS}
          key={`user-${property}`} />);

      tables.push(header, roleTable, userTable);
    });
    return tables;
  }

  renderTables() {
    return (

        {this.renderEntityTables()}
        {this.renderPropertyTables()}

    );
  }

  renderContent() {
    return (this.props.isGettingUsersRoles || this.props.isGettingAcls || this.props.isGettingPermissions)
    ? <LoadingSpinner />
    : this.renderTables();
  }

  getEntitySetTitle() {
    return this.props.entitySet ? this.props.entitySet.title : null;
  }

  render() {
    return (
      <DocumentTitle title="All Permissions">
        <Page>
          <Page.Header>
            <Page.Title>Permissions Summary</Page.Title>

{this.getEntitySetTitle()}

          </Page.Header>
          <Page.Body>
            {this.renderContent()}
          </Page.Body>
        </Page>
      </DocumentTitle>
    );
  }
}

// TODO: Move EntitySet calculations to helper functions/epics & reuse in EntitySetDetailComponent
function mapStateToProps(state) {
  const entitySetDetail = state.get('entitySetDetail');
  const normalizedData = state.get('normalizedData');
  const permissionsSummary = state.get('permissionsSummary');
  let entitySet;
  const reference = entitySetDetail.get('entitySetReference');
  if (reference) {
    entitySet = getEdmObject(normalizedData.toJS(), reference.toJS());
  }

  return {
    entitySet,
    entityUserPermissions: permissionsSummary.get('entityUserPermissions').toJS(),
    entityRolePermissions: permissionsSummary.get('entityRolePermissions').toJS(),
    propertyPermissions: permissionsSummary.get('propertyPermissions').toJS(),
    isGettingUsersRoles: permissionsSummary.get('isGettingUsersRoles'),
    isGettingAcls: permissionsSummary.get('isGettingAcls'),
    isGettingPermissions: permissionsSummary.get('isGettingPermissions')
  };
}

function mapDispatchToProps(dispatch) {
  const actions = {
    getAllUsersAndRolesRequest: psActionFactory.getAllUsersAndRolesRequest
  };

  return {
    loadEntitySet: (id) => {
      dispatch(actionFactories.entitySetDetailRequest(id));
      dispatch(PermissionsActionFactory.getEntitySetsAuthorizations([id]));
      dispatch(edmActionFactories.filteredEdmRequest(
        [{
          type: 'EntitySet',
          id,
          include: ['EntitySet', 'EntityType', 'PropertyTypeInEntitySet']
        }]
      ));
    },
    actions: bindActionCreators(actions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(AllPermissions);
<|endoftext|>


<commit_before>define('app/views/backend_add', ['app/views/panel'],
    //
    //  Backend Add View
    //
    //  @returns Class
    //
    function (PanelView) {

        'use strict';

        return PanelView.extend({

            selectedRegion: null,

            //
            //
            //  Computed Properties
            //
            //

            providerFields: function () {
                return getProviderFields(Mist.backendAddController.provider);
            }.property('Mist.backendAddController.provider'),

            providerRegions: function () {
                if (Mist.backendAddController.provider)
                    return Mist.backendAddController.provider.regions.map(function (region) {
                        return {
                            title: region.split('_').map(function (word) {
                                    if (word == 'ec2' ||
                                        word == 'ap')
                                            return word.toUpperCase();
                                    return word.capitalize()
                                }).join(' '),
                            id: region,
                        };
                    });
            }.property('Mist.backendAddController.provider'),

            isReady: function () {
                var isReady = true
                this.get('providerFields').some(function (field) {
                    if (field.optional) return;
                    if (field.value === undefined ||
                        field.value === null ||
                        field.value === '')
                            return isReady = false;
                });
                return isReady;
            }.property('providerFields.@each.value'),

            //
            //
            //  Methods
            //
            //

            clear: function () {
                Ember.run.next(this, function () {
                    $(this.panelId).trigger('create');
                });
            },

            //
            //
            //  Actions
            //
            //

            actions: {

                selectProvider: function(provider) {
                    this.clear();
                    clearProviderFields(provider);
                    Mist.backendAddController.set('provider', provider);
                    $('#new-backend-provider').collapsible('collapse');
                },

                selectRegion: function (region, field) {
                    field.set('value', region.id);
                    this.set('selectedRegion', region.title);
                    $('#region').collapsible('collapse');
                },

                uploadFile: function (field) {
                    Mist.fileUploadController.open('Upload ' + field.label, field.label,
                        function (uploadedFile) {
                            uploadedFile = uploadedFile.trim();
                            field.set('value', uploadedFile);
                            $('#' + field.name)
                                .removeClass('ui-icon-plus')
                                .removeClass('ui-icon-check')
                                .addClass(uploadedFile ? 'ui-icon-check' : 'ui-icon-plus');
                        },
                        field.value
                    );
                },

                selectKey: function (key, field) {
                    $('#' + field.name).collapsible('collapse');
                    field.set('value', key.id);
                },

                createKeyClicked: function (field) {
                    Mist.keyAddController.open( function (success, key) {
                        if (success) {
                            $('#' + field.name).collapsible('collapse');
                            $('#' + field.name + ' .ui-listview').listview('refresh');
                            field.set('value', key.id);
                        }
                    });
                },

                backClicked: function() {
                    Mist.backendAddController.close();
                },

                addClicked: function() {
                    Mist.backendAddController.add();
                },

                advancedToggled: function () {
                    var advanced = $('#non-hp-cloud');
                    if (advanced.css('display') == 'none') {
                        advanced.slideDown();
                    } else {
                        advanced.slideUp();
                    }
                }
            },
        });
    }
);

<commit_msg>Don't capitalize "ap"<commit_after>define('app/views/backend_add', ['app/views/panel'],
    //
    //  Backend Add View
    //
    //  @returns Class
    //
    function (PanelView) {

        'use strict';

        return PanelView.extend({

            selectedRegion: null,

            //
            //
            //  Computed Properties
            //
            //

            providerFields: function () {
                return getProviderFields(Mist.backendAddController.provider);
            }.property('Mist.backendAddController.provider'),

            providerRegions: function () {
                if (Mist.backendAddController.provider)
                    return Mist.backendAddController.provider.regions.map(function (region) {
                        return {
                            title: region.split('_').map(function (word) {
                                    if (word == 'ec2')
                                            return word.toUpperCase();
                                    return word.capitalize()
                                }).join(' '),
                            id: region,
                        };
                    });
            }.property('Mist.backendAddController.provider'),

            isReady: function () {
                var isReady = true
                this.get('providerFields').some(function (field) {
                    if (field.optional) return;
                    if (field.value === undefined ||
                        field.value === null ||
                        field.value === '')
                            return isReady = false;
                });
                return isReady;
            }.property('providerFields.@each.value'),

            //
            //
            //  Methods
            //
            //

            clear: function () {
                Ember.run.next(this, function () {
                    $(this.panelId).trigger('create');
                });
            },

            //
            //
            //  Actions
            //
            //

            actions: {

                selectProvider: function(provider) {
                    this.clear();
                    clearProviderFields(provider);
                    Mist.backendAddController.set('provider', provider);
                    $('#new-backend-provider').collapsible('collapse');
                },

                selectRegion: function (region, field) {
                    field.set('value', region.id);
                    this.set('selectedRegion', region.title);
                    $('#region').collapsible('collapse');
                },

                uploadFile: function (field) {
                    Mist.fileUploadController.open('Upload ' + field.label, field.label,
                        function (uploadedFile) {
                            uploadedFile = uploadedFile.trim();
                            field.set('value', uploadedFile);
                            $('#' + field.name)
                                .removeClass('ui-icon-plus')
                                .removeClass('ui-icon-check')
                                .addClass(uploadedFile ? 'ui-icon-check' : 'ui-icon-plus');
                        },
                        field.value
                    );
                },

                selectKey: function (key, field) {
                    $('#' + field.name).collapsible('collapse');
                    field.set('value', key.id);
                },

                createKeyClicked: function (field) {
                    Mist.keyAddController.open( function (success, key) {
                        if (success) {
                            $('#' + field.name).collapsible('collapse');
                            $('#' + field.name + ' .ui-listview').listview('refresh');
                            field.set('value', key.id);
                        }
                    });
                },

                backClicked: function() {
                    Mist.backendAddController.close();
                },

                addClicked: function() {
                    Mist.backendAddController.add();
                },

                advancedToggled: function () {
                    var advanced = $('#non-hp-cloud');
                    if (advanced.css('display') == 'none') {
                        advanced.slideDown();
                    } else {
                        advanced.slideUp();
                    }
                }
            },
        });
    }
);

<|endoftext|>


<commit_before>/**
 * --------------------------------------------------------------------------
 * Bootstrap (v5.1.3): carousel.js
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 * --------------------------------------------------------------------------
 */

import {
  defineJQueryPlugin,
  getElementFromSelector,
  getNextActiveElement,
  isRTL,
  isVisible,
  reflow,
  triggerTransitionEnd
} from './util/index'
import EventHandler from './dom/event-handler'
import Manipulator from './dom/manipulator'
import SelectorEngine from './dom/selector-engine'
import Swipe from './util/swipe'
import BaseComponent from './base-component'

/**
 * Constants
 */

const NAME = 'carousel'
const DATA_KEY = 'bs.carousel'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'

const ARROW_LEFT_KEY = 'ArrowLeft'
const ARROW_RIGHT_KEY = 'ArrowRight'
const TOUCHEVENT_COMPAT_WAIT = 500 // Time for mouse compat events to fire after touch

const ORDER_NEXT = 'next'
const ORDER_PREV = 'prev'
const DIRECTION_LEFT = 'left'
const DIRECTION_RIGHT = 'right'

const EVENT_SLIDE = `slide${EVENT_KEY}`
const EVENT_SLID = `slid${EVENT_KEY}`
const EVENT_KEYDOWN = `keydown${EVENT_KEY}`
const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY}`
const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY}`
const EVENT_DRAG_START = `dragstart${EVENT_KEY}`
const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`

const CLASS_NAME_CAROUSEL = 'carousel'
const CLASS_NAME_ACTIVE = 'active'
const CLASS_NAME_SLIDE = 'slide'
const CLASS_NAME_END = 'carousel-item-end'
const CLASS_NAME_START = 'carousel-item-start'
const CLASS_NAME_NEXT = 'carousel-item-next'
const CLASS_NAME_PREV = 'carousel-item-prev'

const SELECTOR_ACTIVE = '.active'
const SELECTOR_ACTIVE_ITEM = '.active.carousel-item'
const SELECTOR_ITEM = '.carousel-item'
const SELECTOR_ITEM_IMG = '.carousel-item img'
const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'
const SELECTOR_INDICATORS = '.carousel-indicators'
const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'
const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'

const KEY_TO_DIRECTION = {
  [ARROW_LEFT_KEY]: DIRECTION_RIGHT,
  [ARROW_RIGHT_KEY]: DIRECTION_LEFT
}

const Default = {
  interval: 5000,
  keyboard: true,
  slide: false,
  pause: 'hover',
  wrap: true,
  touch: true
}

const DefaultType = {
  interval: '(number|boolean)',
  keyboard: 'boolean',
  slide: '(boolean|string)',
  pause: '(string|boolean)',
  wrap: 'boolean',
  touch: 'boolean'
}

/**
 * Class definition
 */

class Carousel extends BaseComponent {
  constructor(element, config) {
    super(element, config)

    this._items = null
    this._interval = null
    this._activeElement = null
    this._isPaused = false
    this._isSliding = false
    this.touchTimeout = null
    this._swipeHelper = null

    this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element)
    this._addEventListeners()
  }

  // Getters
  static get Default() {
    return Default
  }

  static get DefaultType() {
    return DefaultType
  }

  static get NAME() {
    return NAME
  }

  // Public
  next() {
    this._slide(ORDER_NEXT)
  }

  nextWhenVisible() {
    // FIXME TODO use `document.visibilityState`
    // Don't call next when the page isn't visible
    // or the carousel or its parent isn't visible
    if (!document.hidden && isVisible(this._element)) {
      this.next()
    }
  }

  prev() {
    this._slide(ORDER_PREV)
  }

  pause(event) {
    if (!event) {
      this._isPaused = true
    }

    if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) {
      triggerTransitionEnd(this._element)
      this.cycle(true)
    }

    this._clearInterval()
  }

  cycle(event) {
    if (!event) {
      this._isPaused = false
    }

    this._clearInterval()
    if (this._config.interval && !this._isPaused) {
      this._updateInterval()

      this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval)
    }
  }

  to(index) {
    this._activeElement = this._getActive()
    const activeIndex = this._getItemIndex(this._activeElement)

    if (index > this._items.length - 1 || index < 0) {
      return
    }

    if (this._isSliding) {
      EventHandler.one(this._element, EVENT_SLID, () => this.to(index))
      return
    }

    if (activeIndex === index) {
      this.pause()
      this.cycle()
      return
    }

    const order = index > activeIndex ?
      ORDER_NEXT :
      ORDER_PREV

    this._slide(order, this._items[index])
  }

  dispose() {
    if (this._swipeHelper) {
      this._swipeHelper.dispose()
    }

    super.dispose()
  }

  // Private
  _configAfterMerge(config) {
    config.defaultInterval = config.interval
    return config
  }

  _addEventListeners() {
    if (this._config.keyboard) {
      EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event))
    }

    if (this._config.pause === 'hover') {
      EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event))
      EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event))
    }

    if (this._config.touch && Swipe.isSupported()) {
      this._addTouchEventListeners()
    }
  }

  _addTouchEventListeners() {
    for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) {
      EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault())
    }

    const endCallBack = () => {
      if (this._config.pause !== 'hover') {
        return
      }

      // If it's a touch-enabled device, mouseenter/leave are fired as
      // part of the mouse compatibility events on first tap - the carousel
      // would stop cycling until user tapped out of it;
      // here, we listen for touchend, explicitly pause the carousel
      // (as if it's the second time we tap on it, mouseenter compat event
      // is NOT fired) and after a timeout (to allow for mouse compatibility
      // events to fire) we explicitly restart cycling

      this.pause()
      if (this.touchTimeout) {
        clearTimeout(this.touchTimeout)
      }

      this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval)
    }

    const swipeConfig = {
      leftCallback: () => this._slide(DIRECTION_LEFT),
      rightCallback: () => this._slide(DIRECTION_RIGHT),
      endCallback: endCallBack
    }

    this._swipeHelper = new Swipe(this._element, swipeConfig)
  }

  _keydown(event) {
    if (/input|textarea/i.test(event.target.tagName)) {
      return
    }

    const direction = KEY_TO_DIRECTION[event.key]
    if (direction) {
      event.preventDefault()
      this._slide(direction)
    }
  }

  _getItemIndex(element) {
    this._items = SelectorEngine.find(SELECTOR_ITEM, this._element)

    return this._items.indexOf(element)
  }

  _getItemByOrder(order, activeElement) {
    const isNext = order === ORDER_NEXT
    return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap)
  }

  _triggerSlideEvent(relatedTarget, fromIndex, eventDirectionName) {
    const targetIndex = this._getItemIndex(relatedTarget)

    return EventHandler.trigger(this._element, EVENT_SLIDE, {
      relatedTarget,
      direction: eventDirectionName,
      from: fromIndex,
      to: targetIndex
    })
  }

  _setActiveIndicatorElement(index) {
    if (!this._indicatorsElement) {
      return
    }

    const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement)

    activeIndicator.classList.remove(CLASS_NAME_ACTIVE)
    activeIndicator.removeAttribute('aria-current')

    const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to="${index}"]`, this._indicatorsElement)

    if (newActiveIndicator) {
      newActiveIndicator.classList.add(CLASS_NAME_ACTIVE)
      newActiveIndicator.setAttribute('aria-current', 'true')
    }
  }

  _updateInterval() {
    const element = this._activeElement || this._getActive()

    if (!element) {
      return
    }

    const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10)

    this._config.interval = elementInterval || this._config.defaultInterval
  }

  _slide(directionOrOrder, element) {
    const order = this._directionToOrder(directionOrOrder)
    const activeElement = this._getActive()
    const activeElementIndex = this._getItemIndex(activeElement)
    const nextElement = element || this._getItemByOrder(order, activeElement)

    const nextElementIndex = this._getItemIndex(nextElement)
    const isCycling = Boolean(this._interval)

    const isNext = order === ORDER_NEXT
    const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END
    const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV
    const eventDirectionName = this._orderToDirection(order)

    if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE)) {
      this._isSliding = false
      return
    }

    if (this._isSliding) {
      return
    }

    const slideEvent = this._triggerSlideEvent(nextElement, activeElementIndex, eventDirectionName)
    if (slideEvent.defaultPrevented) {
      return
    }

    if (!activeElement || !nextElement) {
      // Some weirdness is happening, so we bail
      return
    }

    this._isSliding = true

    if (isCycling) {
      this.pause()
    }

    this._setActiveIndicatorElement(nextElementIndex)
    this._activeElement = nextElement

    nextElement.classList.add(orderClassName)

    reflow(nextElement)

    activeElement.classList.add(directionalClassName)
    nextElement.classList.add(directionalClassName)

    const completeCallBack = () => {
      nextElement.classList.remove(directionalClassName, orderClassName)
      nextElement.classList.add(CLASS_NAME_ACTIVE)

      activeElement.classList.remove(CLASS_NAME_ACTIVE, orderClassName, directionalClassName)

      this._isSliding = false

      EventHandler.trigger(this._element, EVENT_SLID, {
        relatedTarget: nextElement,
        direction: eventDirectionName,
        from: activeElementIndex,
        to: nextElementIndex
      })
    }

    this._queueCallback(completeCallBack, activeElement, this._isAnimated())

    if (isCycling) {
      this.cycle()
    }
  }

  _isAnimated() {
    return this._element.classList.contains(CLASS_NAME_SLIDE)
  }

  _getActive() {
    return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)
  }

  _clearInterval() {
    if (this._interval) {
      clearInterval(this._interval)
      this._interval = null
    }
  }

  _directionToOrder(direction) {
    if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {
      return direction
    }

    if (isRTL()) {
      return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT
    }

    return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV
  }

  _orderToDirection(order) {
    if (![ORDER_NEXT, ORDER_PREV].includes(order)) {
      return order
    }

    if (isRTL()) {
      return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT
    }

    return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT
  }

  // Static
  static jQueryInterface(config) {
    return this.each(function () {
      const data = Carousel.getOrCreateInstance(this, config)

      let { _config } = data
      if (typeof config === 'object') {
        _config = {
          ..._config,
          ...config
        }
      }

      const action = typeof config === 'string' ? config : _config.slide

      if (typeof config === 'number') {
        data.to(config)
      } else if (typeof action === 'string') {
        if (typeof data[action] === 'undefined') {
          throw new TypeError(`No method named "${action}"`)
        }

        data[action]()
      } else if (_config.interval && _config.ride) {
        data.pause()
        data.cycle()
      }
    })
  }
}

/**
 * Data API implementation
 */

EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_SLIDE, function (event) {
  const target = getElementFromSelector(this)

  if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {
    return
  }

  event.preventDefault()

  const carousel = Carousel.getOrCreateInstance(target)
  const slideIndex = this.getAttribute('data-bs-slide-to')

  if (slideIndex) {
    carousel.to(slideIndex)
    return
  }

  if (Manipulator.getDataAttribute(this, 'slide') === 'next') {
    carousel.next()
    return
  }

  carousel.prev()
})

EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
  const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE)

  for (const carousel of carousels) {
    Carousel.getOrCreateInstance(carousel)
  }
})

/**
 * jQuery
 */

defineJQueryPlugin(Carousel)

export default Carousel
<commit_msg>Carousel: cleanup jQueryInterface<commit_after>/**
 * --------------------------------------------------------------------------
 * Bootstrap (v5.1.3): carousel.js
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 * --------------------------------------------------------------------------
 */

import {
  defineJQueryPlugin,
  getElementFromSelector,
  getNextActiveElement,
  isRTL,
  isVisible,
  reflow,
  triggerTransitionEnd
} from './util/index'
import EventHandler from './dom/event-handler'
import Manipulator from './dom/manipulator'
import SelectorEngine from './dom/selector-engine'
import Swipe from './util/swipe'
import BaseComponent from './base-component'

/**
 * Constants
 */

const NAME = 'carousel'
const DATA_KEY = 'bs.carousel'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'

const ARROW_LEFT_KEY = 'ArrowLeft'
const ARROW_RIGHT_KEY = 'ArrowRight'
const TOUCHEVENT_COMPAT_WAIT = 500 // Time for mouse compat events to fire after touch

const ORDER_NEXT = 'next'
const ORDER_PREV = 'prev'
const DIRECTION_LEFT = 'left'
const DIRECTION_RIGHT = 'right'

const EVENT_SLIDE = `slide${EVENT_KEY}`
const EVENT_SLID = `slid${EVENT_KEY}`
const EVENT_KEYDOWN = `keydown${EVENT_KEY}`
const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY}`
const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY}`
const EVENT_DRAG_START = `dragstart${EVENT_KEY}`
const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`

const CLASS_NAME_CAROUSEL = 'carousel'
const CLASS_NAME_ACTIVE = 'active'
const CLASS_NAME_SLIDE = 'slide'
const CLASS_NAME_END = 'carousel-item-end'
const CLASS_NAME_START = 'carousel-item-start'
const CLASS_NAME_NEXT = 'carousel-item-next'
const CLASS_NAME_PREV = 'carousel-item-prev'

const SELECTOR_ACTIVE = '.active'
const SELECTOR_ACTIVE_ITEM = '.active.carousel-item'
const SELECTOR_ITEM = '.carousel-item'
const SELECTOR_ITEM_IMG = '.carousel-item img'
const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'
const SELECTOR_INDICATORS = '.carousel-indicators'
const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'
const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'

const KEY_TO_DIRECTION = {
  [ARROW_LEFT_KEY]: DIRECTION_RIGHT,
  [ARROW_RIGHT_KEY]: DIRECTION_LEFT
}

const Default = {
  interval: 5000,
  keyboard: true,
  slide: false,
  pause: 'hover',
  wrap: true,
  touch: true
}

const DefaultType = {
  interval: '(number|boolean)',
  keyboard: 'boolean',
  slide: '(boolean|string)',
  pause: '(string|boolean)',
  wrap: 'boolean',
  touch: 'boolean'
}

/**
 * Class definition
 */

class Carousel extends BaseComponent {
  constructor(element, config) {
    super(element, config)

    this._items = null
    this._interval = null
    this._activeElement = null
    this._isPaused = false
    this._isSliding = false
    this.touchTimeout = null
    this._swipeHelper = null

    this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element)
    this._addEventListeners()
  }

  // Getters
  static get Default() {
    return Default
  }

  static get DefaultType() {
    return DefaultType
  }

  static get NAME() {
    return NAME
  }

  // Public
  next() {
    this._slide(ORDER_NEXT)
  }

  nextWhenVisible() {
    // FIXME TODO use `document.visibilityState`
    // Don't call next when the page isn't visible
    // or the carousel or its parent isn't visible
    if (!document.hidden && isVisible(this._element)) {
      this.next()
    }
  }

  prev() {
    this._slide(ORDER_PREV)
  }

  pause(event) {
    if (!event) {
      this._isPaused = true
    }

    if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) {
      triggerTransitionEnd(this._element)
      this.cycle(true)
    }

    this._clearInterval()
  }

  cycle(event) {
    if (!event) {
      this._isPaused = false
    }

    this._clearInterval()
    if (this._config.interval && !this._isPaused) {
      this._updateInterval()

      this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval)
    }
  }

  to(index) {
    this._activeElement = this._getActive()
    const activeIndex = this._getItemIndex(this._activeElement)

    if (index > this._items.length - 1 || index < 0) {
      return
    }

    if (this._isSliding) {
      EventHandler.one(this._element, EVENT_SLID, () => this.to(index))
      return
    }

    if (activeIndex === index) {
      this.pause()
      this.cycle()
      return
    }

    const order = index > activeIndex ?
      ORDER_NEXT :
      ORDER_PREV

    this._slide(order, this._items[index])
  }

  dispose() {
    if (this._swipeHelper) {
      this._swipeHelper.dispose()
    }

    super.dispose()
  }

  // Private
  _configAfterMerge(config) {
    config.defaultInterval = config.interval
    return config
  }

  _addEventListeners() {
    if (this._config.keyboard) {
      EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event))
    }

    if (this._config.pause === 'hover') {
      EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event))
      EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event))
    }

    if (this._config.touch && Swipe.isSupported()) {
      this._addTouchEventListeners()
    }
  }

  _addTouchEventListeners() {
    for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) {
      EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault())
    }

    const endCallBack = () => {
      if (this._config.pause !== 'hover') {
        return
      }

      // If it's a touch-enabled device, mouseenter/leave are fired as
      // part of the mouse compatibility events on first tap - the carousel
      // would stop cycling until user tapped out of it;
      // here, we listen for touchend, explicitly pause the carousel
      // (as if it's the second time we tap on it, mouseenter compat event
      // is NOT fired) and after a timeout (to allow for mouse compatibility
      // events to fire) we explicitly restart cycling

      this.pause()
      if (this.touchTimeout) {
        clearTimeout(this.touchTimeout)
      }

      this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval)
    }

    const swipeConfig = {
      leftCallback: () => this._slide(DIRECTION_LEFT),
      rightCallback: () => this._slide(DIRECTION_RIGHT),
      endCallback: endCallBack
    }

    this._swipeHelper = new Swipe(this._element, swipeConfig)
  }

  _keydown(event) {
    if (/input|textarea/i.test(event.target.tagName)) {
      return
    }

    const direction = KEY_TO_DIRECTION[event.key]
    if (direction) {
      event.preventDefault()
      this._slide(direction)
    }
  }

  _getItemIndex(element) {
    this._items = SelectorEngine.find(SELECTOR_ITEM, this._element)

    return this._items.indexOf(element)
  }

  _getItemByOrder(order, activeElement) {
    const isNext = order === ORDER_NEXT
    return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap)
  }

  _triggerSlideEvent(relatedTarget, fromIndex, eventDirectionName) {
    const targetIndex = this._getItemIndex(relatedTarget)

    return EventHandler.trigger(this._element, EVENT_SLIDE, {
      relatedTarget,
      direction: eventDirectionName,
      from: fromIndex,
      to: targetIndex
    })
  }

  _setActiveIndicatorElement(index) {
    if (!this._indicatorsElement) {
      return
    }

    const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement)

    activeIndicator.classList.remove(CLASS_NAME_ACTIVE)
    activeIndicator.removeAttribute('aria-current')

    const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to="${index}"]`, this._indicatorsElement)

    if (newActiveIndicator) {
      newActiveIndicator.classList.add(CLASS_NAME_ACTIVE)
      newActiveIndicator.setAttribute('aria-current', 'true')
    }
  }

  _updateInterval() {
    const element = this._activeElement || this._getActive()

    if (!element) {
      return
    }

    const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10)

    this._config.interval = elementInterval || this._config.defaultInterval
  }

  _slide(directionOrOrder, element) {
    const order = this._directionToOrder(directionOrOrder)
    const activeElement = this._getActive()
    const activeElementIndex = this._getItemIndex(activeElement)
    const nextElement = element || this._getItemByOrder(order, activeElement)

    const nextElementIndex = this._getItemIndex(nextElement)
    const isCycling = Boolean(this._interval)

    const isNext = order === ORDER_NEXT
    const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END
    const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV
    const eventDirectionName = this._orderToDirection(order)

    if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE)) {
      this._isSliding = false
      return
    }

    if (this._isSliding) {
      return
    }

    const slideEvent = this._triggerSlideEvent(nextElement, activeElementIndex, eventDirectionName)
    if (slideEvent.defaultPrevented) {
      return
    }

    if (!activeElement || !nextElement) {
      // Some weirdness is happening, so we bail
      return
    }

    this._isSliding = true

    if (isCycling) {
      this.pause()
    }

    this._setActiveIndicatorElement(nextElementIndex)
    this._activeElement = nextElement

    nextElement.classList.add(orderClassName)

    reflow(nextElement)

    activeElement.classList.add(directionalClassName)
    nextElement.classList.add(directionalClassName)

    const completeCallBack = () => {
      nextElement.classList.remove(directionalClassName, orderClassName)
      nextElement.classList.add(CLASS_NAME_ACTIVE)

      activeElement.classList.remove(CLASS_NAME_ACTIVE, orderClassName, directionalClassName)

      this._isSliding = false

      EventHandler.trigger(this._element, EVENT_SLID, {
        relatedTarget: nextElement,
        direction: eventDirectionName,
        from: activeElementIndex,
        to: nextElementIndex
      })
    }

    this._queueCallback(completeCallBack, activeElement, this._isAnimated())

    if (isCycling) {
      this.cycle()
    }
  }

  _isAnimated() {
    return this._element.classList.contains(CLASS_NAME_SLIDE)
  }

  _getActive() {
    return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)
  }

  _clearInterval() {
    if (this._interval) {
      clearInterval(this._interval)
      this._interval = null
    }
  }

  _directionToOrder(direction) {
    if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {
      return direction
    }

    if (isRTL()) {
      return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT
    }

    return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV
  }

  _orderToDirection(order) {
    if (![ORDER_NEXT, ORDER_PREV].includes(order)) {
      return order
    }

    if (isRTL()) {
      return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT
    }

    return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT
  }

  // Static
  static jQueryInterface(config) {
    return this.each(function () {
      const data = Carousel.getOrCreateInstance(this, config)

      let { _config } = data
      if (typeof config === 'object') {
        _config = {
          ..._config,
          ...config
        }
      }

      if (typeof config === 'number') {
        data.to(config)
        return
      }

      if (typeof config === 'string') {
        if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {
          throw new TypeError(`No method named "${config}"`)
        }

        data[config]()
        return
      }

      if (_config.interval && _config.ride) {
        data.pause()
        data.cycle()
      }
    })
  }
}

/**
 * Data API implementation
 */

EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_SLIDE, function (event) {
  const target = getElementFromSelector(this)

  if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {
    return
  }

  event.preventDefault()

  const carousel = Carousel.getOrCreateInstance(target)
  const slideIndex = this.getAttribute('data-bs-slide-to')

  if (slideIndex) {
    carousel.to(slideIndex)
    return
  }

  if (Manipulator.getDataAttribute(this, 'slide') === 'next') {
    carousel.next()
    return
  }

  carousel.prev()
})

EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
  const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE)

  for (const carousel of carousels) {
    Carousel.getOrCreateInstance(carousel)
  }
})

/**
 * jQuery
 */

defineJQueryPlugin(Carousel)

export default Carousel
<|endoftext|>


<commit_before>/*jshint node: true */
// Karma configuration
// Generated on Thu Mar 12 2015 16:54:00 GMT-0500 (Central Daylight Time)

// use test configuration
process.env.NODE_ENV = 'test';

// load gme configuration
var testFixture = require('./test/_globals.js'),
    gmeConfig = testFixture.getGmeConfig(),
    webgme = testFixture.WebGME,
    Q = testFixture.Q,
    gmeAuth,
    storage,
    server,
    logger = testFixture.logger.fork('karma.conf'),
    PROJECTS_TO_IMPORT = [
        {name: 'ProjectAndBranchOperationsTest', path: './test-karma/client/js/client/basicProject.json'},
        {name: 'noBranchSeedProject', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'alreadyExists', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'createGenericBranch', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'removeGenericBranch', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'metaQueryAndManipulationTest', path: './test-karma/client/js/client/metaTestProject.json'},
        {name: 'ClientNodeInquiryTests', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'nodeManipulationProject', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'RESTLikeTests', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'undoRedoTests', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'territoryProject', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'projectSeedSingleMaster', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {
            name: 'projectSeedSingleNonMaster',
            path: './test-karma/client/js/client/clientNodeTestProject.json',
            branches: ['other']
        },
        {
            name: 'projectSeedMultiple',
            path: './test-karma/client/js/client/clientNodeTestProject.json',
            branches: ['master', 'other']
        },
        {name: 'pluginProject', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'branchWatcher', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'branchStatus', path: './test-karma/client/js/client/pluginProject.json'}
    ];

(function initializeServer() {
    'use strict';
    // Add a user to to GMEAuth
    var projectNames = PROJECTS_TO_IMPORT.map(function (projectData) {
        return projectData.name;
    });
    console.log(projectNames);
    testFixture.clearDBAndGetGMEAuth(gmeConfig, projectNames)
        .then(function (gmeAuth_) {
            // Open the database storage
            gmeAuth = gmeAuth_;
            storage = testFixture.getMongoStorage(logger, gmeConfig, gmeAuth);
            return storage.openDatabase();
        })
        .then(function () {
            // Import all the projects.
            function importProject(projectInfo) {
                var branchName = projectInfo.hasOwnProperty('branches') ?
                    projectInfo.branches[0] : 'master';

                return testFixture.importProject(storage, {
                    projectSeed: projectInfo.path,
                    projectName: projectInfo.name,
                    branchName: branchName,
                    gmeConfig: gmeConfig,
                    logger: logger
                })
                    .then(function (importResult) {
                        var i,
                            createBranches = [];
                        if (projectInfo.hasOwnProperty('branches') && projectInfo.branches.length > 1) {
                            // First one is already added thus i = 1.
                            for (i = 1; i < projectInfo.branches.length; i += 1) {
                                createBranches.push(storage.createBranch({
                                        projectId: testFixture.projectName2Id(projectInfo.name),
                                        branchName: projectInfo.branches[i],
                                        hash: importResult.commitHash
                                    })
                                );
                            }
                        }
                        return Q.allDone(createBranches);
                    });
            }

            return Q.allDone(PROJECTS_TO_IMPORT.map(importProject));
        })
        .then(function () {
            // Close the storage
            return storage.closeDatabase();
        })
        .then(function () {
            server = webgme.standaloneServer(gmeConfig);
            //setTimeout(function () {
            server.start(function () {
                console.log('webgme server started');
            });
            //}, 10000); // timeout to emulate long server start up see test-main.js
        })
        .catch(function (err) {
            console.error(err);
        });
}());

module.exports = function (config) {
    'use strict';

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'requirejs', 'chai'],

        // list of files / patterns to load in the browser
        files: [
            {pattern: 'src/**/*.js', included: false},
            {pattern: 'utils/build/empty/empty.js', included: false},
            {pattern: 'test/plugin/scenarios/plugins/**/*.js', included: false},
            {pattern: 'seeds/*.json', included: false}, //seeds
            {pattern: 'test-karma/**/*.spec.js', included: false},
            {pattern: 'test-karma/**/*.inc.js', included: false}, //test include scripts
            {pattern: 'test-karma/**/*.json', included: false}, //test assets
            'test-main.js'
        ],

        // list of files to exclude
        exclude: [
            'src/server/middleware/executor/worker/node_modules/**/*.js'
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/**/*.js': ['coverage']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['dots', 'coverage'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values:
        // config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome', 'Firefox'],

        // to avoid DISCONNECTED messages
        browserDisconnectTimeout: 10000, // default 2000
        browserDisconnectTolerance: 1, // default 0
        browserNoActivityTimeout: 60000, //default 10000

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // forward these requests to the webgme server. All other files are server by the karma web server
        proxies: {
            '/base/gmeConfig.json': 'http://localhost:' + gmeConfig.server.port + '/gmeConfig.json',
            '/rest': 'http://localhost:' + gmeConfig.server.port + '/rest',
            '/api': 'http://localhost:' + gmeConfig.server.port + '/api'
        }
    });
};
<commit_msg>Throttle the imports for karma tests (#696)<commit_after>/*jshint node: true */
// Karma configuration
// Generated on Thu Mar 12 2015 16:54:00 GMT-0500 (Central Daylight Time)

// use test configuration
process.env.NODE_ENV = 'test';

// load gme configuration
var testFixture = require('./test/_globals.js'),
    gmeConfig = testFixture.getGmeConfig(),
    webgme = testFixture.WebGME,
    Q = testFixture.Q,
    gmeAuth,
    storage,
    server,
    logger = testFixture.logger.fork('karma.conf'),
    PROJECTS_TO_IMPORT = [
        {name: 'ProjectAndBranchOperationsTest', path: './test-karma/client/js/client/basicProject.json'},
        {name: 'noBranchSeedProject', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'alreadyExists', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'createGenericBranch', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'removeGenericBranch', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'metaQueryAndManipulationTest', path: './test-karma/client/js/client/metaTestProject.json'},
        {name: 'ClientNodeInquiryTests', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'nodeManipulationProject', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'RESTLikeTests', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'undoRedoTests', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'territoryProject', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {name: 'projectSeedSingleMaster', path: './test-karma/client/js/client/clientNodeTestProject.json'},
        {
            name: 'projectSeedSingleNonMaster',
            path: './test-karma/client/js/client/clientNodeTestProject.json',
            branches: ['other']
        },
        {
            name: 'projectSeedMultiple',
            path: './test-karma/client/js/client/clientNodeTestProject.json',
            branches: ['master', 'other']
        },
        {name: 'pluginProject', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'branchWatcher', path: './test-karma/client/js/client/pluginProject.json'},
        {name: 'branchStatus', path: './test-karma/client/js/client/pluginProject.json'}
    ];

(function initializeServer() {
    'use strict';
    // Add a user to to GMEAuth
    var projectNames = PROJECTS_TO_IMPORT.map(function (projectData) {
        return projectData.name;
    });
    console.log(projectNames);
    testFixture.clearDBAndGetGMEAuth(gmeConfig, projectNames)
        .then(function (gmeAuth_) {
            // Open the database storage
            gmeAuth = gmeAuth_;
            storage = testFixture.getMongoStorage(logger, gmeConfig, gmeAuth);
            return storage.openDatabase();
        })
        .then(function () {
            // Import all the projects.

            function importProject(projectInfo) {
                var branchName = projectInfo.hasOwnProperty('branches') ?
                    projectInfo.branches[0] : 'master';

                return testFixture.importProject(storage, {
                    projectSeed: projectInfo.path,
                    projectName: projectInfo.name,
                    branchName: branchName,
                    gmeConfig: gmeConfig,
                    logger: logger
                })
                    .then(function (importResult) {
                        var i,
                            createBranches = [];
                        if (projectInfo.hasOwnProperty('branches') && projectInfo.branches.length > 1) {
                            // First one is already added thus i = 1.
                            for (i = 1; i < projectInfo.branches.length; i += 1) {
                                createBranches.push(storage.createBranch({
                                        projectId: testFixture.projectName2Id(projectInfo.name),
                                        branchName: projectInfo.branches[i],
                                        hash: importResult.commitHash
                                    })
                                );
                            }
                        }
                        return Q.allDone(createBranches);
                    })
                    .then(function () {
                        var nextProject = PROJECTS_TO_IMPORT.shift();
                        if (nextProject) {
                            return importProject(nextProject);
                        }
                    });
            }

            return importProject(PROJECTS_TO_IMPORT.shift());
        })
        .then(function () {
            // Close the storage
            return storage.closeDatabase();
        })
        .then(function () {
            server = webgme.standaloneServer(gmeConfig);
            //setTimeout(function () {
            server.start(function () {
                console.log('webgme server started');
            });
            //}, 10000); // timeout to emulate long server start up see test-main.js
        })
        .catch(function (err) {
            console.error(err);
        });
}());

module.exports = function (config) {
    'use strict';

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'requirejs', 'chai'],

        // list of files / patterns to load in the browser
        files: [
            {pattern: 'src/**/*.js', included: false},
            {pattern: 'utils/build/empty/empty.js', included: false},
            {pattern: 'test/plugin/scenarios/plugins/**/*.js', included: false},
            {pattern: 'seeds/*.json', included: false}, //seeds
            {pattern: 'test-karma/**/*.spec.js', included: false},
            {pattern: 'test-karma/**/*.inc.js', included: false}, //test include scripts
            {pattern: 'test-karma/**/*.json', included: false}, //test assets
            'test-main.js'
        ],

        // list of files to exclude
        exclude: [
            'src/server/middleware/executor/worker/node_modules/**/*.js'
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/**/*.js': ['coverage']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['dots', 'coverage'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values:
        // config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome', 'Firefox'],

        // to avoid DISCONNECTED messages
        browserDisconnectTimeout: 10000, // default 2000
        browserDisconnectTolerance: 1, // default 0
        browserNoActivityTimeout: 60000, //default 10000

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // forward these requests to the webgme server. All other files are server by the karma web server
        proxies: {
            '/base/gmeConfig.json': 'http://localhost:' + gmeConfig.server.port + '/gmeConfig.json',
            '/rest': 'http://localhost:' + gmeConfig.server.port + '/rest',
            '/api': 'http://localhost:' + gmeConfig.server.port + '/api'
        }
    });
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function() {

  var path = require('path'),
      fs = require('fs'),
      async = require('async'),
      forever = require('forever-monitor'),
      uuid = require('node-uuid'),
      stream = require('stream'),
      pidsPath = path.resolve(__dirname, '../../.pids'),
      _this = this,
      _isMain = false,
      _isFork = false,
      _ids = -1,
      _messagesCallbacks = {},
      _children = [{
        name: 'Allons-y',
        id: ++_ids,
        type: 'main',
        startDate: new Date()
      }],
      childrenStdout = new stream.Writable();

  childrenStdout._write = function(data, encoding, callback) {
    data = data.toString();

    _this.output(data);

    callback();
  };

  function _logDate(date) {
    if (!date) {
      return '';
    }

    var day = date.getDate(),
        month = date.getMonth() + 1,
        hours = date.getHours(),
        minutes = date.getMinutes();

    return (day < 10 ? '0' + day : day) + '/' + (month < 10 ? '0' + month : month) + ' ' +
        (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes);
  }

  function _cleanPids() {
    if (fs.existsSync(pidsPath)) {
      try {
        _this.log('allons-y', 'processes-clean-pids');

        fs.unlinkSync(pidsPath);
      }
      catch (err) {
        _this.logWarning('allons-y', 'processes-clean-pids-error', {
          error: err
        });
      }
    }
  }

  function _pids() {
    var pids = (fs.existsSync(pidsPath) ? fs.readFileSync(pidsPath, 'utf-8') : '').split('\n');

    for (var i = pids.length - 1; i >= 0; i--) {
      if (!pids[i]) {
        pids.splice(i, 1);
      }
      else {
        pids[i] = pids[i].split(':');
      }
    }

    return pids;
  }

  function _savePid(pid, processName) {
    if (!pid || !processName) {
      return false;
    }

    _this.log('allons-y', 'processes-pid-save:' + pid + ',' + processName);

    var pids = fs.existsSync(pidsPath) ? fs.readFileSync(pidsPath, 'utf-8') : '';
    pids += (pids ? '\n' : '') + pid + ':' + processName;

    fs.writeFileSync(pidsPath, pids);

    return true;
  }

  _this.liveCommand(['processes', 'p'], 'output the live processes list', function() {
    _this.outputInfo('► processes:\n');

    _children.forEach(function(child) {
      _this.output([
        '  ■ [' + _logDate(child.startDate) + ']',
        _this.textInfo(child.name),
        (child.processes ? '(' + child.processes.length + ')' : ''),
        '#' + _this.textWarning(child.id)
      ].join(' '), '\n');

      if (child.processes) {
        child.processes.forEach(function(p) {
          _this.output([
            '    ∙ [' + _logDate(p.restartDate) + ']',
            _this.textInfo(p.name),
            '(' + child.type + ')',
            '(' + p.forever.times + ' restarts)',
            '#' + _this.textWarning(p.id)
          ].join(' '), '\n');
        });
      }
    });
  });

  function _findProcesses($args, splice) {
    $args = $args || [];
    $args[0] = ($args[0] || '')
      .toString()
      .replace('#', '');

    if (!$args[0]) {
      return null;
    }

    var id = $args[0],
        found = false;

    if (id.indexOf('0') === 0) {
      return false;
    }

    for (var i = 0; i < _children.length; i++) {
      var child = _children[i];

      if (child.id.toString() === id) {
        found = {
          id: id,
          name: child.name,
          processes: child.processes
        };

        if (splice) {
          _children.splice(i, 1);
        }

        break;
      }

      if (child.processes) {
        for (var j = 0; j < child.processes.length; j++) {
          if (child.processes[j].id.toString() === id) {
            found = {
              id: id,
              name: child.processes[j].name,
              processes: [child.processes[j]]
            };

            if (splice) {
              child.processes.splice(j, 1);
            }

            if (!child.processes.length) {
              _children.splice(i, 1);
            }

            break;
          }
        }
      }
    }

    return found === false ? -1 : found;
  }

  this.childByName = function(name) {
    for (var i = 0; i < _children.length; i++) {
      if (_children[i].name == name) {
        return _children[i];
      }
    }

    return null;
  };

  this.sendMessage = function(message, callback) {
    message = message || {};
    message = typeof message == 'object' ? message : {
      event: message
    };

    if (callback) {
      message.messageId = uuid.v1();
      _messagesCallbacks[message.messageId] = callback;
    }

    if (_isMain) {
      _children.forEach(function(child) {
        if (!child.processes) {
          return;
        }

        child.processes.forEach(function(p) {
          p.forever.send(message);
        });
      });
    }
    else if (_isFork) {
      process.send(message);
    }
  };

  _this.liveCommand('restart [process]', 'restart a process', function($args) {
    _this.outputInfo('► restart:\n');

    var found = _findProcesses($args);

    if (found === null) {
      return _this.outputWarning('  Set a process id for the "restart" command: restart [process]');
    }
    else if (found === false) {
      return _this.outputWarning('  You cannot restart Allons-y from the Live Commands');
    }
    else if (found === -1 || !found.processes) {
      return _this.outputWarning('  There is no process for this id');
    }

    for (var i = 0; i < found.processes.length; i++) {
      var p = found.processes[i];

      if (p.forever) {
        _this.log('allons-y', 'processes-restart:' + p.id + ',' + p.name);

        p.forever.restart();
      }
    }

    _this.outputSuccess('\n► process "' + found.name + '" (#' + found.id + ') restarted');
  });

  _this.liveCommand('kill [process]', 'shutdown a process', function($args) {
    _this.outputInfo('► kill:\n');

    var found = _findProcesses($args, true);

    if (found === null) {
      return _this.outputWarning('  Set a process id for the "kill" command: kill [process]');
    }
    else if (found === false) {
      return _this.outputWarning('  Use the "exit" command to shutdown Allons-y');
    }
    else if (found === -1 || !found.processes) {
      return _this.outputWarning('  There is no process for this id');
    }

    found.processes.forEach(function(p) {
      if (p.forever) {
        _this.log('allons-y', 'processes-stop:' + p.id + ',' + p.name);

        p.forever.stop();
      }
      if (p.watcher) {
        p.watcher.stop();
      }
    });

    _this.outputSuccess('\n► process "' + found.name + '" (#' + found.id + ') terminated');
  });

  _this.liveCommand('exit', 'shutdown allons-y', function() {
    _this.outputInfo('► exit');

    for (var i = 0; i < _children.length; i++) {
      var child = _children[i];

      if (child.processes && child.processes.length) {
        for (var j = 0; j < child.processes.length; j++) {
          if (child.processes[j].forever) {
            _this.log('allons-y', 'processes-stop:' + child.processes[j].id + ',' + child.processes[j].name);

            child.processes[j].forever.stop();
          }
          if (child.processes[j].watcher) {
            child.processes[j].watcher.stop();
          }
        }
      }
    }

    _cleanPids();

    _this.log('allons-y', 'exit');

    _this.cleanPrompt();

    process.exit();
  });

  function _callModule(startModule, callback) {
    DependencyInjection.injector.controller.invoke(null, startModule.module, {
      controller: {
        $done: function() {
          return callback || function() {};
        }
      }
    });
  }

  function _messageReceived(message, child, p) {
    message = typeof message == 'object' ? message : {
      event: message
    };

    if (child) {
      message.child = child;
      message.p = p;
    }

    if (message.messageId && _messagesCallbacks[message.messageId]) {
      _messagesCallbacks[message.messageId](message);

      delete _messagesCallbacks[message.messageId];
    }

    _this.fire('message', message);
  }

  function _processEvents(p, child) {
    p.forever.on('restart', function() {
      p.restartDate = new Date();
    });

    p.forever.on('exit', function() {
      _findProcesses([p.id], true);
    });

    p.forever.on('watch:restart', function() {
      p.restartDate = new Date();
      _this.outputInfo('► [Watch] Restart "' + p.name + '" (#' + _this.outputWarning(p.id) + ')');
    });

    p.forever.on('message', function(message) {
      _messageReceived(message, child, p);
    });

    p.forever.child.stdout.pipe(childrenStdout);
    p.forever.child.stderr.pipe(childrenStdout);

    p.watcher.on('change', function() {
      _this.outputInfo('► [Watch] Restart "' + p.name + '" (#' + p.id + ')');
      p.forever.times--;
      p.forever.restart();
    });

    _savePid(p.forever.child.pid, p.name);
  }

  process.on('message', _messageReceived);

  this.start = function(dontStopBefore) {
    _isMain = true;

    if (!dontStopBefore) {
      return _this.stop(function() {
        _this.start(true);
      }, true);
    }

    _this.startLiveCommand();

    _this.outputBanner();

    _savePid(process.pid, 'Allons-y');

    if (!process.env.ALLONSY_LIVE_COMMANDS || process.env.ALLONSY_LIVE_COMMANDS == 'true') {
      _this.outputSuccess('  Live Commands is enabled. Use "help" to display the available commands.\n');
    }

    _this.bootstrap({
      owner: 'start'
    }, function() {
      var files = _this.findInFeaturesSync('*-allons-y-start.js');

      _this.log('allons-y', 'start', {
        files: files
      });

      async.mapSeries(files, function(file, nextFile) {
        var startModule = require(path.resolve(file));

        if (typeof startModule.enabled == 'boolean' && startModule.enabled === false) {
          return nextFile();
        }

        if (startModule.fork || startModule.spawn) {
          if (startModule.fork) {
            startModule.forkCount = startModule.forkCount || 1;
            startModule.forkMaxRestarts = startModule.forkMaxRestarts || 10;
          }
          else if (startModule.spawn) {
            startModule.spawnCount = startModule.spawnCount || 1;
            startModule.spawnArgs = startModule.spawnArgs || [];
            startModule.spawnMaxRestarts = startModule.spawnMaxRestarts || 10;
          }

          var count = startModule.fork ? startModule.forkCount : startModule.spawnCount,
              child = {
                name: startModule.name,
                id: ++_ids,
                ids: -1,
                type: startModule.fork ? 'fork' : 'spawn',
                startDate: new Date(),
                processes: []
              };

          _children.push(child);

          for (var i = 0; i < count; i++) {
            var pId = child.id + '.' + (++child.ids);

            _this.log('allons-y', 'processes-' + child.type + '-start:' + pId + ',' + child.name);

            _this.outputInfo('► Starting "' + child.name + '" (' + child.type + ')' + ' [' + (i + 1) + '/' + count + ']');

            var p = {
              name: child.name,
              id: pId,
              startDate: new Date(),
              restartDate: new Date(),
              watcher: _this.watcher(startModule.name, startModule.watch || null),
              forever: startModule.fork ?
                new (forever.Monitor)('./node_modules/allons-y/fork.js', {
                  fork: true,
                  silent: true,
                  max: startModule.forkMaxRestarts,
                  args: [file, i],
                  stdio: ['pipe', 'pipe', 'pipe', 'ipc']
                }).start() :
                forever.start(startModule.spawnCommands, {
                  max: startModule.spawnMaxRestarts,
                  silent: true,
                  stdio: ['pipe', 'pipe', 'pipe', 'ipc']
                })
            };

            _processEvents(p, child);

            child.processes.push(p);
          }

          return nextFile();
        }

        _callModule(startModule, nextFile);
      });
    });
  };

  this.stop = function(callback, fromStart) {
    _this.bootstrap({
      owner: 'stop'
    }, function() {
      _this.log('allons-y', 'stop');

      var pids = _pids();

      if (!fromStart) {
        _this.outputBanner();

        _this.outputInfo('► stop\n');
      }

      pids.forEach(function(pid) {
        if (!pid) {
          return;
        }

        if (!fromStart) {
          _this.outputSuccess('  kill "' + pid[1] + '" (#' + pid[0] + ')');
        }

        _this.log('allons-y', 'processes-stop:' + pid[0] + ',' + pid[1]);

        forever.kill(pid[0]);
      });

      _cleanPids();

      if (callback) {
        callback();
      }
    });
  };

  this.fork = function() {
    _isFork = true;

    _this.bootstrap({
      owner: 'fork'
    }, function() {
      if (process.argv.length < 4) {
        return;
      }

      var startModule = require(path.resolve(process.argv[2]));

      _this.log('allons-y', 'fork-exec:' + process.argv[3]);

      DependencyInjection.service('$processIndex', function() {
        return parseInt(process.argv[3], 10);
      });

      _callModule(startModule);
    });
  };

};
<commit_msg>feat(allons-y processes): add DI $processName in forks processes<commit_after>'use strict';

module.exports = function() {

  var path = require('path'),
      fs = require('fs'),
      async = require('async'),
      forever = require('forever-monitor'),
      uuid = require('node-uuid'),
      stream = require('stream'),
      pidsPath = path.resolve(__dirname, '../../.pids'),
      _this = this,
      _isMain = false,
      _isFork = false,
      _ids = -1,
      _messagesCallbacks = {},
      _children = [{
        name: 'Allons-y',
        id: ++_ids,
        type: 'main',
        startDate: new Date()
      }],
      childrenStdout = new stream.Writable();

  childrenStdout._write = function(data, encoding, callback) {
    data = data.toString();

    _this.output(data);

    callback();
  };

  function _logDate(date) {
    if (!date) {
      return '';
    }

    var day = date.getDate(),
        month = date.getMonth() + 1,
        hours = date.getHours(),
        minutes = date.getMinutes();

    return (day < 10 ? '0' + day : day) + '/' + (month < 10 ? '0' + month : month) + ' ' +
        (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes);
  }

  function _cleanPids() {
    if (fs.existsSync(pidsPath)) {
      try {
        _this.log('allons-y', 'processes-clean-pids');

        fs.unlinkSync(pidsPath);
      }
      catch (err) {
        _this.logWarning('allons-y', 'processes-clean-pids-error', {
          error: err
        });
      }
    }
  }

  function _pids() {
    var pids = (fs.existsSync(pidsPath) ? fs.readFileSync(pidsPath, 'utf-8') : '').split('\n');

    for (var i = pids.length - 1; i >= 0; i--) {
      if (!pids[i]) {
        pids.splice(i, 1);
      }
      else {
        pids[i] = pids[i].split(':');
      }
    }

    return pids;
  }

  function _savePid(pid, processName) {
    if (!pid || !processName) {
      return false;
    }

    _this.log('allons-y', 'processes-pid-save:' + pid + ',' + processName);

    var pids = fs.existsSync(pidsPath) ? fs.readFileSync(pidsPath, 'utf-8') : '';
    pids += (pids ? '\n' : '') + pid + ':' + processName;

    fs.writeFileSync(pidsPath, pids);

    return true;
  }

  _this.liveCommand(['processes', 'p'], 'output the live processes list', function() {
    _this.outputInfo('► processes:\n');

    _children.forEach(function(child) {
      _this.output([
        '  ■ [' + _logDate(child.startDate) + ']',
        _this.textInfo(child.name),
        (child.processes ? '(' + child.processes.length + ')' : ''),
        '#' + _this.textWarning(child.id)
      ].join(' '), '\n');

      if (child.processes) {
        child.processes.forEach(function(p) {
          _this.output([
            '    ∙ [' + _logDate(p.restartDate) + ']',
            _this.textInfo(p.name),
            '(' + child.type + ')',
            '(' + p.forever.times + ' restarts)',
            '#' + _this.textWarning(p.id)
          ].join(' '), '\n');
        });
      }
    });
  });

  function _findProcesses($args, splice) {
    $args = $args || [];
    $args[0] = ($args[0] || '')
      .toString()
      .replace('#', '');

    if (!$args[0]) {
      return null;
    }

    var id = $args[0],
        found = false;

    if (id.indexOf('0') === 0) {
      return false;
    }

    for (var i = 0; i < _children.length; i++) {
      var child = _children[i];

      if (child.id.toString() === id) {
        found = {
          id: id,
          name: child.name,
          processes: child.processes
        };

        if (splice) {
          _children.splice(i, 1);
        }

        break;
      }

      if (child.processes) {
        for (var j = 0; j < child.processes.length; j++) {
          if (child.processes[j].id.toString() === id) {
            found = {
              id: id,
              name: child.processes[j].name,
              processes: [child.processes[j]]
            };

            if (splice) {
              child.processes.splice(j, 1);
            }

            if (!child.processes.length) {
              _children.splice(i, 1);
            }

            break;
          }
        }
      }
    }

    return found === false ? -1 : found;
  }

  this.childByName = function(name) {
    for (var i = 0; i < _children.length; i++) {
      if (_children[i].name == name) {
        return _children[i];
      }
    }

    return null;
  };

  this.sendMessage = function(message, callback) {
    message = message || {};
    message = typeof message == 'object' ? message : {
      event: message
    };

    if (callback) {
      message.messageId = uuid.v1();
      _messagesCallbacks[message.messageId] = callback;
    }

    if (_isMain) {
      _children.forEach(function(child) {
        if (!child.processes) {
          return;
        }

        child.processes.forEach(function(p) {
          p.forever.send(message);
        });
      });
    }
    else if (_isFork) {
      process.send(message);
    }
  };

  _this.liveCommand('restart [process]', 'restart a process', function($args) {
    _this.outputInfo('► restart:\n');

    var found = _findProcesses($args);

    if (found === null) {
      return _this.outputWarning('  Set a process id for the "restart" command: restart [process]');
    }
    else if (found === false) {
      return _this.outputWarning('  You cannot restart Allons-y from the Live Commands');
    }
    else if (found === -1 || !found.processes) {
      return _this.outputWarning('  There is no process for this id');
    }

    for (var i = 0; i < found.processes.length; i++) {
      var p = found.processes[i];

      if (p.forever) {
        _this.log('allons-y', 'processes-restart:' + p.id + ',' + p.name);

        p.forever.restart();
      }
    }

    _this.outputSuccess('\n► process "' + found.name + '" (#' + found.id + ') restarted');
  });

  _this.liveCommand('kill [process]', 'shutdown a process', function($args) {
    _this.outputInfo('► kill:\n');

    var found = _findProcesses($args, true);

    if (found === null) {
      return _this.outputWarning('  Set a process id for the "kill" command: kill [process]');
    }
    else if (found === false) {
      return _this.outputWarning('  Use the "exit" command to shutdown Allons-y');
    }
    else if (found === -1 || !found.processes) {
      return _this.outputWarning('  There is no process for this id');
    }

    found.processes.forEach(function(p) {
      if (p.forever) {
        _this.log('allons-y', 'processes-stop:' + p.id + ',' + p.name);

        p.forever.stop();
      }
      if (p.watcher) {
        p.watcher.stop();
      }
    });

    _this.outputSuccess('\n► process "' + found.name + '" (#' + found.id + ') terminated');
  });

  _this.liveCommand('exit', 'shutdown allons-y', function() {
    _this.outputInfo('► exit');

    for (var i = 0; i < _children.length; i++) {
      var child = _children[i];

      if (child.processes && child.processes.length) {
        for (var j = 0; j < child.processes.length; j++) {
          if (child.processes[j].forever) {
            _this.log('allons-y', 'processes-stop:' + child.processes[j].id + ',' + child.processes[j].name);

            child.processes[j].forever.stop();
          }
          if (child.processes[j].watcher) {
            child.processes[j].watcher.stop();
          }
        }
      }
    }

    _cleanPids();

    _this.log('allons-y', 'exit');

    _this.cleanPrompt();

    process.exit();
  });

  function _callModule(startModule, callback) {
    DependencyInjection.injector.controller.invoke(null, startModule.module, {
      controller: {
        $done: function() {
          return callback || function() {};
        }
      }
    });
  }

  function _messageReceived(message, child, p) {
    message = typeof message == 'object' ? message : {
      event: message
    };

    if (child) {
      message.child = child;
      message.p = p;
    }

    if (message.messageId && _messagesCallbacks[message.messageId]) {
      _messagesCallbacks[message.messageId](message);

      delete _messagesCallbacks[message.messageId];
    }

    _this.fire('message', message);
  }

  function _processEvents(p, child) {
    p.forever.on('restart', function() {
      p.restartDate = new Date();
    });

    p.forever.on('exit', function() {
      _findProcesses([p.id], true);
    });

    p.forever.on('watch:restart', function() {
      p.restartDate = new Date();
      _this.outputInfo('► [Watch] Restart "' + p.name + '" (#' + _this.outputWarning(p.id) + ')');
    });

    p.forever.on('message', function(message) {
      _messageReceived(message, child, p);
    });

    p.forever.child.stdout.pipe(childrenStdout);
    p.forever.child.stderr.pipe(childrenStdout);

    p.watcher.on('change', function() {
      _this.outputInfo('► [Watch] Restart "' + p.name + '" (#' + p.id + ')');
      p.forever.times--;
      p.forever.restart();
    });

    _savePid(p.forever.child.pid, p.name);
  }

  process.on('message', _messageReceived);

  this.start = function(dontStopBefore) {
    _isMain = true;

    if (!dontStopBefore) {
      return _this.stop(function() {
        _this.start(true);
      }, true);
    }

    _this.startLiveCommand();

    _this.outputBanner();

    _savePid(process.pid, 'Allons-y');

    if (!process.env.ALLONSY_LIVE_COMMANDS || process.env.ALLONSY_LIVE_COMMANDS == 'true') {
      _this.outputSuccess('  Live Commands is enabled. Use "help" to display the available commands.\n');
    }

    _this.bootstrap({
      owner: 'start'
    }, function() {
      var files = _this.findInFeaturesSync('*-allons-y-start.js');

      _this.log('allons-y', 'start', {
        files: files
      });

      async.mapSeries(files, function(file, nextFile) {
        var startModule = require(path.resolve(file));

        if (typeof startModule.enabled == 'boolean' && startModule.enabled === false) {
          return nextFile();
        }

        if (startModule.fork || startModule.spawn) {
          if (startModule.fork) {
            startModule.forkCount = startModule.forkCount || 1;
            startModule.forkMaxRestarts = startModule.forkMaxRestarts || 10;
          }
          else if (startModule.spawn) {
            startModule.spawnCount = startModule.spawnCount || 1;
            startModule.spawnArgs = startModule.spawnArgs || [];
            startModule.spawnMaxRestarts = startModule.spawnMaxRestarts || 10;
          }

          var count = startModule.fork ? startModule.forkCount : startModule.spawnCount,
              child = {
                name: startModule.name,
                id: ++_ids,
                ids: -1,
                type: startModule.fork ? 'fork' : 'spawn',
                startDate: new Date(),
                processes: []
              };

          _children.push(child);

          for (var i = 0; i < count; i++) {
            var pId = child.id + '.' + (++child.ids);

            _this.log('allons-y', 'processes-' + child.type + '-start:' + pId + ',' + child.name);

            _this.outputInfo('► Starting "' + child.name + '" (' + child.type + ')' + ' [' + (i + 1) + '/' + count + ']');

            var p = {
              name: child.name,
              id: pId,
              startDate: new Date(),
              restartDate: new Date(),
              watcher: _this.watcher(startModule.name, startModule.watch || null),
              forever: startModule.fork ?
                new (forever.Monitor)('./node_modules/allons-y/fork.js', {
                  fork: true,
                  silent: true,
                  max: startModule.forkMaxRestarts,
                  args: [file, i, startModule.name],
                  stdio: ['pipe', 'pipe', 'pipe', 'ipc']
                }).start() :
                forever.start(startModule.spawnCommands, {
                  max: startModule.spawnMaxRestarts,
                  silent: true,
                  stdio: ['pipe', 'pipe', 'pipe', 'ipc']
                })
            };

            _processEvents(p, child);

            child.processes.push(p);
          }

          return nextFile();
        }

        _callModule(startModule, nextFile);
      });
    });
  };

  this.stop = function(callback, fromStart) {
    _this.bootstrap({
      owner: 'stop'
    }, function() {
      _this.log('allons-y', 'stop');

      var pids = _pids();

      if (!fromStart) {
        _this.outputBanner();

        _this.outputInfo('► stop\n');
      }

      pids.forEach(function(pid) {
        if (!pid) {
          return;
        }

        if (!fromStart) {
          _this.outputSuccess('  kill "' + pid[1] + '" (#' + pid[0] + ')');
        }

        _this.log('allons-y', 'processes-stop:' + pid[0] + ',' + pid[1]);

        forever.kill(pid[0]);
      });

      _cleanPids();

      if (callback) {
        callback();
      }
    });
  };

  this.fork = function() {
    _isFork = true;

    if (process.argv.length < 4) {
      return;
    }

    DependencyInjection.service('$processIndex', function() {
      return parseInt(process.argv[3], 10);
    });

    DependencyInjection.service('$processName', function() {
      return parseInt(process.argv[4], 10);
    });

    _this.bootstrap({
      owner: 'fork',
      processIndex: process.argv[3],
      processName: process.argv[4]
    }, function() {
      var startModule = require(path.resolve(process.argv[2]));

      _this.log('allons-y', 'fork-exec:' + process.argv[4] + ':' + process.argv[3]);

      _callModule(startModule);
    });
  };

};
<|endoftext|>


<commit_before>var ThemeGenerator = {
	config: {
		2: { tileColor: '#7aba7a', fontSizeFactor: 1 },
		4: { tileColor: '#46a646', fontSizeFactor: 1 },
		8: { tileColor: '#2a812a', fontSizeFactor: 1 },
		16: { tileColor: '#156515', fontSizeFactor: 1 },
		32: { tileColor: '#074007', fontSizeFactor: 1 },
		64: { tileColor: '#ffcc00', fontSizeFactor: 1 },
		128: { tileColor: '#ffa200', fontSizeFactor: 0.68 },
		256: { tileColor: '#ff8400', fontSizeFactor: 0.68 },
		512: { tileColor: '#ff5500', fontSizeFactor: 0.68 },
		1024: { tileColor: '#ff2b00', fontSizeFactor: 0.5 },
		2048: { tileColor: '#b76eb8', fontSizeFactor: 0.5 },
		4096: { tileColor: '#984399', fontSizeFactor: 0.5 },
		8192: { tileColor: '#641b66', fontSizeFactor: 0.5 },
		16384: { tileColor: '#3c093e', fontSizeFactor: 0.38 },
		32768: { tileColor: '#c0a172', fontSizeFactor: 0.38 },
		65536: { tileColor: '#836b46', fontSizeFactor: 0.38 },
		131072: { tileColor: '#614d2f', fontSizeFactor: 0.3 },
		262144: { tileColor: '#3e2f1b', fontSizeFactor: 0.3 },
		524288: { tileColor: '#ec799a', fontSizeFactor: 0.3 },
		1048576: { tileColor: '#c01c61', fontSizeFactor: 0.25 },
		2097152: { tileColor: '#a00b5b', fontSizeFactor: 0.25 },

		4194304: { tileColor: '#9f9f9f', fontSizeFactor: 0.25 },
		8388608: { tileColor: '#989898', fontSizeFactor: 0.25 },
		16777216: { tileColor: '#8f8f8f', fontSizeFactor: 0.20 },
		33554432: { tileColor: '#888888', fontSizeFactor: 0.20 },
		67108864: { tileColor: '#7f7f7f', fontSizeFactor: 0.20 },
		134217728: { tileColor: '#787878', fontSizeFactor: 0.18 },
		268435456: { tileColor: '#6f6f6f', fontSizeFactor: 0.18 },
		536870912: { tileColor: '#606060', fontSizeFactor: 0.18 },
		1073741824: { tileColor: '#525252', fontSizeFactor: 0.17 },
		2147483648: { tileColor: '#454545', fontSizeFactor: 0.17 },
		4294967296: { tileColor: '#3a3a3a', fontSizeFactor: 0.16 },
		8589934592: { tileColor: '#303030', fontSizeFactor: 0.16 },
		17179869184: { tileColor: '#212121', fontSizeFactor: 0.17 },
		34359738368: { tileColor: '#131313', fontSizeFactor: 0.16 },
		68719476736: { tileColor: '#050505', fontSizeFactor: 0.16 }
	},

	generateCellsStyles: function (cellSize) {
		var baseFontSize = cellSize / 1.3,
			availableNumbers = Object.keys(this.config),
			num, conf, styleObj;

		for (var i = 0; i < availableNumbers.length; i++) {
			num = availableNumbers[i];
			conf = this.config[num];
			styleObj = {};

			styleObj['CellBackground_' + num] = {
				styles: {
					backgroundColor: conf.tileColor,
					fontSize: baseFontSize * conf.fontSizeFactor
				}
			};

			Theme.set(styleObj);
		}
	}
};<commit_msg>Fix font size;<commit_after>var ThemeGenerator = {
	config: {
		2: { tileColor: '#7aba7a', fontSizeFactor: 1 },
		4: { tileColor: '#46a646', fontSizeFactor: 1 },
		8: { tileColor: '#2a812a', fontSizeFactor: 1 },
		16: { tileColor: '#156515', fontSizeFactor: 1 },
		32: { tileColor: '#074007', fontSizeFactor: 0.85 },
		64: { tileColor: '#ffcc00', fontSizeFactor: 0.85 },
		128: { tileColor: '#ffa200', fontSizeFactor: 0.68 },
		256: { tileColor: '#ff8400', fontSizeFactor: 0.58 },
		512: { tileColor: '#ff5500', fontSizeFactor: 0.68 },
		1024: { tileColor: '#ff2b00', fontSizeFactor: 0.5 },
		2048: { tileColor: '#b76eb8', fontSizeFactor: 0.5 },
		4096: { tileColor: '#984399', fontSizeFactor: 0.5 },
		8192: { tileColor: '#641b66', fontSizeFactor: 0.5 },
		16384: { tileColor: '#3c093e', fontSizeFactor: 0.38 },
		32768: { tileColor: '#c0a172', fontSizeFactor: 0.38 },
		65536: { tileColor: '#836b46', fontSizeFactor: 0.38 },
		131072: { tileColor: '#614d2f', fontSizeFactor: 0.3 },
		262144: { tileColor: '#3e2f1b', fontSizeFactor: 0.3 },
		524288: { tileColor: '#ec799a', fontSizeFactor: 0.3 },
		1048576: { tileColor: '#c01c61', fontSizeFactor: 0.25 },
		2097152: { tileColor: '#a00b5b', fontSizeFactor: 0.25 },

		4194304: { tileColor: '#9f9f9f', fontSizeFactor: 0.25 },
		8388608: { tileColor: '#989898', fontSizeFactor: 0.25 },
		16777216: { tileColor: '#8f8f8f', fontSizeFactor: 0.20 },
		33554432: { tileColor: '#888888', fontSizeFactor: 0.20 },
		67108864: { tileColor: '#7f7f7f', fontSizeFactor: 0.20 },
		134217728: { tileColor: '#787878', fontSizeFactor: 0.18 },
		268435456: { tileColor: '#6f6f6f', fontSizeFactor: 0.18 },
		536870912: { tileColor: '#606060', fontSizeFactor: 0.18 },
		1073741824: { tileColor: '#525252', fontSizeFactor: 0.17 },
		2147483648: { tileColor: '#454545', fontSizeFactor: 0.17 },
		4294967296: { tileColor: '#3a3a3a', fontSizeFactor: 0.16 },
		8589934592: { tileColor: '#303030', fontSizeFactor: 0.16 },
		17179869184: { tileColor: '#212121', fontSizeFactor: 0.17 },
		34359738368: { tileColor: '#131313', fontSizeFactor: 0.16 },
		68719476736: { tileColor: '#050505', fontSizeFactor: 0.16 }
	},

	generateCellsStyles: function (cellSize) {
		var baseFontSize = cellSize / 1.3,
			availableNumbers = Object.keys(this.config),
			num, conf, styleObj;

		for (var i = 0; i < availableNumbers.length; i++) {
			num = availableNumbers[i];
			conf = this.config[num];
			styleObj = {};

			styleObj['CellBackground_' + num] = {
				styles: {
					backgroundColor: conf.tileColor,
					fontSize: baseFontSize * conf.fontSizeFactor
				}
			};

			Theme.set(styleObj);
		}
	}
};<|endoftext|>


<commit_before><commit_msg>add missed view_item event<commit_after><|endoftext|>


<commit_before>import _ from 'lodash'
import React, { Component, PropTypes } from 'react'

import { Label, Table } from 'stardust'

/**
 * Displays a table of a Component's PropTypes.
 */
export default class ComponentProps extends Component {
  static propTypes = {
    /**
     * A single Component's prop info as generated by react-docgen.
     * @type {object} Props info object where keys are prop names and values are prop definitions.
     */
    props: PropTypes.object,
  }

  nameRenderer = (item) => {item.name}

  requiredRenderer = (item) => {
    if (item.required) {
      return required
    }
  }
  defaultValueRenderer = (item) => {
    let defaultValue = _.get(item, 'defaultValue.value')

    if (_.startsWith(defaultValue, 'function ')) {
      defaultValue = defaultValue.match(/^function(.*)\{/)[1].trim()
    }

    const defaultIsComputed = computed

    return (

        {defaultValue} {_.get(item, 'defaultValue.computed') && defaultIsComputed}

    )
  }

  render() {
    const propsDefinition = this.props.props
    const content = _.map(propsDefinition, (propConfig, propName) => {
      const name = propName
      const description = _.get(propConfig, 'docBlock.description')

      const value = _.get(propConfig, 'type.value')
      let type = _.get(propConfig, 'type.name')
      if (type === 'union') {
        type = _.map(value, (val) => val.name).join('|')
      }
      type = type && `{${type}}`

      const required = propConfig.required
      const defaultValue = propConfig.defaultValue

      return {
        name,
        type,
        value,
        required,
        defaultValue,
        description,
      }
    })

    return (

    )
  }
}
<commit_msg>feat(ComponentProps): sort doc props alphabetically (#489)<commit_after>import _ from 'lodash'
import React, { Component, PropTypes } from 'react'

import { Label, Table } from 'stardust'

/**
 * Displays a table of a Component's PropTypes.
 */
export default class ComponentProps extends Component {
  static propTypes = {
    /**
     * A single Component's prop info as generated by react-docgen.
     * @type {object} Props info object where keys are prop names and values are prop definitions.
     */
    props: PropTypes.object,
  }

  nameRenderer = (item) => {item.name}

  requiredRenderer = (item) => {
    if (item.required) {
      return required
    }
  }
  defaultValueRenderer = (item) => {
    let defaultValue = _.get(item, 'defaultValue.value')

    if (_.startsWith(defaultValue, 'function ')) {
      defaultValue = defaultValue.match(/^function(.*)\{/)[1].trim()
    }

    const defaultIsComputed = computed

    return (

        {defaultValue} {_.get(item, 'defaultValue.computed') && defaultIsComputed}

    )
  }

  render() {
    const propsDefinition = this.props.props
    const content = _.sortBy(_.map(propsDefinition, (config, name) => {
      const value = _.get(config, 'type.value')
      let type = _.get(config, 'type.name')
      if (type === 'union') {
        type = _.map(value, (val) => val.name).join('|')
      }
      type = type && `{${type}}`

      return {
        name,
        type,
        value,
        required: config.required,
        defaultValue: config.defaultValue,
        description: _.get(config, 'docBlock.description'),
      }
    }), 'name')
    return (

    )
  }
}
<|endoftext|>