<commit_before>import React from 'react';
import Helmet from 'react-helmet';
import Immutable from 'immutable';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import * as Utils from '../../utils';
import { DataManager, BulkActionManager } from '../../redux';
import SearchParameters from '../../domain/SearchParameters';
import NotificationLevelEnum from '../../enums/NotificationLevelEnum';

const UIKEY = 'bulk-actions';
const manager = new BulkActionManager();

/**
 * Registered bulk actions.
 *
 * @author Radek Tomiška
 * @since 10.6.0
 */
class BulkActions extends Advanced.AbstractTableContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      filterOpened: true
    };
  }

  getContentKey() {
    return `content.system.${UIKEY}`;
  }

  getNavigationKey() {
    return UIKEY;
  }

  getManager() {
    return manager;
  }

  componentDidMount() {
    super.componentDidMount();
    //
    this.reload();
    this.context.store.dispatch(manager.fetchRegisteredBulkActions());
  }

  reload() {
    const {_searchParameters} = this.props;
    //
    this.fetchBulkActions(_searchParameters);
  }

  useFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchBulkActions(
      SearchParameters.getSearchParameters(
        SearchParameters.getFilterData(this.refs.filterForm),
        this.props._searchParameters
      )
    );
  }

  cancelFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchBulkActions(null);
    this.refs.filterForm.setData({});
  }

  fetchBulkActions(searchParameters) {
    this.context.store.dispatch(this.getManager().fetchEntities(searchParameters, UIKEY));
  }

  onEnable(entity, enable, event) {
    if (event) {
      event.preventDefault();
    }
    this.refs[`confirm-${enable ? '' : 'de'}activate`].show(
      this.i18n(`action.${enable ? '' : 'de'}activate.message`, { count: 1, record: entity.name }),
      this.i18n(`action.${enable ? '' : 'de'}activate.header`, { count: 1 })
    ).then(() => {
      this.context.store.dispatch(this.getManager().setEnabled(entity.id, enable, (patchedEntity, error) => {
        if (!error) {
          this.addMessage({ message: this.i18n(`action.${enable ? '' : 'de'}activate.success`, { count: 1, record: entity.name }) });
          // refresh table with processors
          this.reload();
        } else {
          this.addError(error);
        }
      }));
    }, () => {
      // rejected
    });
  }

  render() {
    const { bulkActions, showLoading, registeredBulkActions, _searchParameters } = this.props;
    const { filterOpened } = this.state;
    let _bulkActions = new Immutable.OrderedMap();
    let _entityClasses = new Immutable.OrderedSet();
    let _registeredEntityClasses = new Immutable.OrderedSet();
    if (bulkActions) {
      bulkActions.forEach(bulkAction => {
        if (!_bulkActions.has(bulkAction.entityClass)) {
          _bulkActions = _bulkActions.set(bulkAction.entityClass, []);
        }
        const actions = _bulkActions.get(bulkAction.entityClass);
        actions.push(bulkAction);
        _bulkActions = _bulkActions.set(bulkAction.entityClass, actions);
        _entityClasses = _entityClasses.add(bulkAction.entityClass);
      });
    }
    if (registeredBulkActions) {
      registeredBulkActions.forEach(bulkAction => {
        _registeredEntityClasses = _registeredEntityClasses.add(bulkAction.entityClass);
      });
      // sort _entityTypes
      _registeredEntityClasses = _registeredEntityClasses.sort((one, two) => one > two);
    }
    return (
      <Basic.Div>
        <Helmet title={ this.i18n('title') }/>
        <Basic.Confirm ref="confirm-deactivate" level="warning"/>
        <Basic.Confirm ref="confirm-activate" level="success"/>

        <Basic.Toolbar className="collapse-top">
          <Basic.Collapse in={ filterOpened }>
            <Basic.Div>
              <Advanced.Filter onSubmit={ this.useFilter.bind(this) }>
                <Basic.AbstractForm ref="filterForm">
                  <Basic.Row>
                    <Basic.Col lg={ 8 }>
                      <Advanced.Filter.TextField
                        ref="text"
                        placeholder={ this.i18n('filter.text.placeholder') }/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 } className="text-right">
                      <Advanced.Filter.FilterButtons cancelFilter={ this.cancelFilter.bind(this) }/>
                    </Basic.Col>
                  </Basic.Row>
                  <Basic.Row className="last">
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.TextField
                        ref="module"
                        placeholder={this.i18n('filter.module.placeholder')}/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.EnumSelectBox
                        ref="entityClass"
                        placeholder={ this.i18n('filter.entityClass.placeholder') }
                        options={ _registeredEntityClasses.toArray().map(value => ({ value, niceLabel: Utils.Ui.getSimpleJavaType(value) })) }
                        searchable/>
                    </Basic.Col>
                  </Basic.Row>
                </Basic.AbstractForm>
              </Advanced.Filter>
            </Basic.Div>
          </Basic.Collapse>
          <Basic.Div>
            <Basic.Div className="pull-right">
              <Advanced.Filter.ToogleButton
                filterOpen={ (open) => this.setState({filterOpened: open}) }
                filterOpened={ filterOpened }
                style={{ marginLeft: 3 }}
                searchParameters={ _searchParameters }/>
              <Advanced.RefreshButton
                onClick={ this.fetchBulkActions.bind(this, _searchParameters) }
                title={ this.i18n('button.refresh') }
                showLoading={ showLoading }/>
            </Basic.Div>
            <Basic.Div className="clearfix"/>
          </Basic.Div>

        </Basic.Toolbar>
        <Basic.Loading isStatic show={ showLoading }/>
        <Basic.Alert
          level="info"
          text={ this.i18n('component.basic.Table.noData') }
          style={{ margin: 15 }}
          rendered={ !showLoading && _bulkActions.size === 0 } />
        {
          showLoading || _bulkActions.size === 0
          ||
          <Basic.Div>
            {
              [..._entityClasses.map((entityClass) => (
                <Basic.Div className="tab-pane-table-body" style={{ marginBottom: 15 }}>
                  <Basic.ContentHeader>
                    {
                      entityClass
                      ?
                      Utils.Ui.getSimpleJavaType(entityClass)
                      :
                      this.i18n('emptyEntityClass.header', { escape: false })
                    }
                  </Basic.ContentHeader>
                  <Basic.Table
                    data={ _bulkActions.get(entityClass) }
                    showLoading={ showLoading }
                    noData={ this.i18n('component.basic.Table.noData') }
                    rowClass={ ({rowIndex, data}) => Utils.Ui.getRowClass(data[rowIndex]) }>
                    <Basic.Column
                      property="module"
                      header={ this.i18n('entity.BulkAction.module.label') }
                      width={ 100 }/>
                    <Basic.Column
                      property="name"
                      width="20%"
                      header={
                        <span title={ this.i18n('entity.BulkAction.name.title') }>
                          { this.i18n('entity.BulkAction.name.label') }
                        </span>
                      }/>
                    <Basic.Column
                      property="description"
                      header={ this.i18n('entity.BulkAction.description.label') }/>
                    <Basic.Column
                      property="level"
                      header={ this.i18n('entity.BulkAction.level.label') }
                      width={ 100 }
                      cell={ <Basic.EnumCell className="column-face-enum" enumClass={ NotificationLevelEnum }/> }/>
                    <Basic.Column
                      property="icon"
                      header={
                        <Basic.Cell title={ this.i18n('entity.BulkAction.icon.title') }>
                          { this.i18n('entity.BulkAction.icon.label') }
                        </Basic.Cell>
                      }
                      className="center"
                      width={ 100 }
                      cell={
                        ({rowIndex, data, property}) => {
                          const action = data[rowIndex];
                          const icon = (
                            <Basic.Icon
                              icon={ action[property] }
                              level={ action.level !== 'SUCCESS' ? action.level.toLowerCase() : 'default' }/>
                          );
                          if (!icon) {
                            return null;
                          }
                          if (action.quickButton) {
                            return (
                              <Basic.Button
                                buttonSize="xs"
                                className="bulk-action-button"
                                style={{ marginRight: 0 }}
                                title={ this.i18n('entity.BulkAction.quickButton.help') }>
                                { icon }
                              </Basic.Button>
                            );
                          }
                          //
                          return icon;
                        }
                      }/>
                    <Basic.Column
                      property="quickButton"
                      header={
                        <Basic.Cell
                          className="column-face-bool"
                          title={ this.i18n('entity.BulkAction.quickButton.title') }>
                          { this.i18n('entity.BulkAction.quickButton.label') }
                        </Basic.Cell>
                      }
                      cell={ <Basic.BooleanCell className="column-face-bool"/> }
                      width={ 100 }/>
                    <Basic.Column
                      property="deleteAction"
                      header={
                        <Basic.Cell
                          className="column-face-bool"
                          title={ this.i18n('entity.BulkAction.deleteAction.title') }>
                          { this.i18n('entity.BulkAction.deleteAction.label') }
                        </Basic.Cell>
                      }
                      cell={ <Basic.BooleanCell className="column-face-bool"/> }
                      width={ 100 }/>
                    <Basic.Column
                      property="order"
                      header={ this.i18n('entity.BulkAction.order.label') }
                      width={ 100 }/>
                    <Basic.Column
                      property="disabled"
                      header={ <Basic.Cell className="column-face-bool">{ this.i18n('entity.BulkAction.disabled.label') }</Basic.Cell> }
                      cell={ <Basic.BooleanCell className="column-face-bool"/> }
                      width={ 100 }/>
                    <Basic.Column
                      header={ this.i18n('entity.id.label') }
                      property="id"
                      rendered={ this.isDevelopment() }
                      className="text-center"
                      width={ 100 }
                      cell={
                        ({rowIndex, data, property}) => (
                          <Advanced.UuidInfo value={ data[rowIndex][property] }/>
                        )
                      }/>
                    <Basic.Column
                      header={this.i18n('label.action')}
                      className="action"
                      cell={
                        ({ rowIndex, data }) => {
                          if (!data[rowIndex].disabled) {
                            return (
                              <Basic.Button
                                level="warning"
                                onClick={ this.onEnable.bind(this, data[rowIndex], false) }
                                className="btn-xs"
                                title={ this.i18n('button.deactivate') }
                                titlePlacement="bottom"
                                rendered={ data[rowIndex].disableable }>
                                { this.i18n('button.deactivate') }
                              </Basic.Button>
                            );
                          }
                          return (
                            <Basic.Button
                              level="success"
                              onClick={ this.onEnable.bind(this, data[rowIndex], true) }
                              className="btn-xs"
                              title={ this.i18n('button.activate') }
                              titlePlacement="bottom">
                              { this.i18n('button.activate') }
                            </Basic.Button>
                          );
                        }
                      }/>
                  </Basic.Table>
                </Basic.Div>
              )).values()]
            }
            <Basic.Pagination total={ bulkActions.length } />
          </Basic.Div>
        }
      </Basic.Div>
    );
  }
}

BulkActions.propTypes = {
  userContext: PropTypes.object,
  registeredBulkActions: PropTypes.object, // immutable
  bulkActions: PropTypes.arrayOf(PropTypes.object),
  showLoading: PropTypes.bool
};

BulkActions.defaultProps = {
  userContext: null,
  showLoading: true
};

function select(state) {
  return {
    registeredBulkActions: DataManager.getData(state, BulkActionManager.UI_KEY_BULK_ACTIONS),
    bulkActions: manager.getEntities(state, UIKEY),
    showLoading: Utils.Ui.isShowLoading(state, UIKEY)
            || Utils.Ui.isShowLoading(state, BulkActionManager.UI_KEY_BULK_ACTIONS),
    _searchParameters: Utils.Ui.getSearchParameters(state, UIKEY)
  };
}

export default connect(select)(BulkActions);
<commit_msg>FE: fix: bukl action agenda - check action level is missing<commit_after>import React from 'react';
import Helmet from 'react-helmet';
import Immutable from 'immutable';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import * as Utils from '../../utils';
import { DataManager, BulkActionManager } from '../../redux';
import SearchParameters from '../../domain/SearchParameters';
import NotificationLevelEnum from '../../enums/NotificationLevelEnum';

const UIKEY = 'bulk-actions';
const manager = new BulkActionManager();

/**
 * Registered bulk actions.
 *
 * @author Radek Tomiška
 * @since 10.6.0
 */
class BulkActions extends Advanced.AbstractTableContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      filterOpened: true
    };
  }

  getContentKey() {
    return `content.system.${UIKEY}`;
  }

  getNavigationKey() {
    return UIKEY;
  }

  getManager() {
    return manager;
  }

  componentDidMount() {
    super.componentDidMount();
    //
    this.reload();
    this.context.store.dispatch(manager.fetchRegisteredBulkActions());
  }

  reload() {
    const {_searchParameters} = this.props;
    //
    this.fetchBulkActions(_searchParameters);
  }

  useFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchBulkActions(
      SearchParameters.getSearchParameters(
        SearchParameters.getFilterData(this.refs.filterForm),
        this.props._searchParameters
      )
    );
  }

  cancelFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchBulkActions(null);
    this.refs.filterForm.setData({});
  }

  fetchBulkActions(searchParameters) {
    this.context.store.dispatch(this.getManager().fetchEntities(searchParameters, UIKEY));
  }

  onEnable(entity, enable, event) {
    if (event) {
      event.preventDefault();
    }
    this.refs[`confirm-${enable ? '' : 'de'}activate`].show(
      this.i18n(`action.${enable ? '' : 'de'}activate.message`, { count: 1, record: entity.name }),
      this.i18n(`action.${enable ? '' : 'de'}activate.header`, { count: 1 })
    ).then(() => {
      this.context.store.dispatch(this.getManager().setEnabled(entity.id, enable, (patchedEntity, error) => {
        if (!error) {
          this.addMessage({ message: this.i18n(`action.${enable ? '' : 'de'}activate.success`, { count: 1, record: entity.name }) });
          // refresh table with processors
          this.reload();
        } else {
          this.addError(error);
        }
      }));
    }, () => {
      // rejected
    });
  }

  render() {
    const { bulkActions, showLoading, registeredBulkActions, _searchParameters } = this.props;
    const { filterOpened } = this.state;
    let _bulkActions = new Immutable.OrderedMap();
    let _entityClasses = new Immutable.OrderedSet();
    let _registeredEntityClasses = new Immutable.OrderedSet();
    if (bulkActions) {
      bulkActions.forEach(bulkAction => {
        if (!_bulkActions.has(bulkAction.entityClass)) {
          _bulkActions = _bulkActions.set(bulkAction.entityClass, []);
        }
        const actions = _bulkActions.get(bulkAction.entityClass);
        actions.push(bulkAction);
        _bulkActions = _bulkActions.set(bulkAction.entityClass, actions);
        _entityClasses = _entityClasses.add(bulkAction.entityClass);
      });
    }
    if (registeredBulkActions) {
      registeredBulkActions.forEach(bulkAction => {
        _registeredEntityClasses = _registeredEntityClasses.add(bulkAction.entityClass);
      });
      // sort _entityTypes
      _registeredEntityClasses = _registeredEntityClasses.sort((one, two) => one > two);
    }
    return (
      <Basic.Div>
        <Helmet title={ this.i18n('title') }/>
        <Basic.Confirm ref="confirm-deactivate" level="warning"/>
        <Basic.Confirm ref="confirm-activate" level="success"/>

        <Basic.Toolbar className="collapse-top">
          <Basic.Collapse in={ filterOpened }>
            <Basic.Div>
              <Advanced.Filter onSubmit={ this.useFilter.bind(this) }>
                <Basic.AbstractForm ref="filterForm">
                  <Basic.Row>
                    <Basic.Col lg={ 8 }>
                      <Advanced.Filter.TextField
                        ref="text"
                        placeholder={ this.i18n('filter.text.placeholder') }/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 } className="text-right">
                      <Advanced.Filter.FilterButtons cancelFilter={ this.cancelFilter.bind(this) }/>
                    </Basic.Col>
                  </Basic.Row>
                  <Basic.Row className="last">
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.TextField
                        ref="module"
                        placeholder={this.i18n('filter.module.placeholder')}/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.EnumSelectBox
                        ref="entityClass"
                        placeholder={ this.i18n('filter.entityClass.placeholder') }
                        options={ _registeredEntityClasses.toArray().map(value => ({ value, niceLabel: Utils.Ui.getSimpleJavaType(value) })) }
                        searchable/>
                    </Basic.Col>
                  </Basic.Row>
                </Basic.AbstractForm>
              </Advanced.Filter>
            </Basic.Div>
          </Basic.Collapse>
          <Basic.Div>
            <Basic.Div className="pull-right">
              <Advanced.Filter.ToogleButton
                filterOpen={ (open) => this.setState({filterOpened: open}) }
                filterOpened={ filterOpened }
                style={{ marginLeft: 3 }}
                searchParameters={ _searchParameters }/>
              <Advanced.RefreshButton
                onClick={ this.fetchBulkActions.bind(this, _searchParameters) }
                title={ this.i18n('button.refresh') }
                showLoading={ showLoading }/>
            </Basic.Div>
            <Basic.Div className="clearfix"/>
          </Basic.Div>

        </Basic.Toolbar>
        <Basic.Loading isStatic show={ showLoading }/>
        <Basic.Alert
          level="info"
          text={ this.i18n('component.basic.Table.noData') }
          style={{ margin: 15 }}
          rendered={ !showLoading && _bulkActions.size === 0 } />
        {
          showLoading || _bulkActions.size === 0
          ||
          <Basic.Div>
            {
              [..._entityClasses.map((entityClass) => (
                <Basic.Div className="tab-pane-table-body" style={{ marginBottom: 15 }}>
                  <Basic.ContentHeader>
                    {
                      entityClass
                      ?
                      Utils.Ui.getSimpleJavaType(entityClass)
                      :
                      this.i18n('emptyEntityClass.header', { escape: false })
                    }
                  </Basic.ContentHeader>
                  <Basic.Table
                    data={ _bulkActions.get(entityClass) }
                    showLoading={ showLoading }
                    noData={ this.i18n('component.basic.Table.noData') }
                    rowClass={ ({rowIndex, data}) => Utils.Ui.getRowClass(data[rowIndex]) }>
                    <Basic.Column
                      property="module"
                      header={ this.i18n('entity.BulkAction.module.label') }
                      width={ 100 }/>
                    <Basic.Column
                      property="name"
                      width="20%"
                      header={
                        <span title={ this.i18n('entity.BulkAction.name.title') }>
                          { this.i18n('entity.BulkAction.name.label') }
                        </span>
                      }/>
                    <Basic.Column
                      property="description"
                      header={ this.i18n('entity.BulkAction.description.label') }/>
                    <Basic.Column
                      property="level"
                      header={ this.i18n('entity.BulkAction.level.label') }
                      width={ 100 }
                      cell={ <Basic.EnumCell className="column-face-enum" enumClass={ NotificationLevelEnum }/> }/>
                    <Basic.Column
                      property="icon"
                      header={
                        <Basic.Cell title={ this.i18n('entity.BulkAction.icon.title') }>
                          { this.i18n('entity.BulkAction.icon.label') }
                        </Basic.Cell>
                      }
                      className="center"
                      width={ 100 }
                      cell={
                        ({rowIndex, data, property}) => {
                          const action = data[rowIndex];
                          const icon = (
                            <Basic.Icon
                              icon={ action[property] }
                              level={ action.level && action.level !== 'SUCCESS' ? action.level.toLowerCase() : 'default' }/>
                          );
                          if (!icon) {
                            return null;
                          }
                          if (action.quickButton) {
                            return (
                              <Basic.Button
                                buttonSize="xs"
                                className="bulk-action-button"
                                style={{ marginRight: 0 }}
                                title={ this.i18n('entity.BulkAction.quickButton.help') }>
                                { icon }
                              </Basic.Button>
                            );
                          }
                          //
                          return icon;
                        }
                      }/>
                    <Basic.Column
                      property="quickButton"
                      header={
                        <Basic.Cell
                          className="column-face-bool"
                          title={ this.i18n('entity.BulkAction.quickButton.title') }>
                          { this.i18n('entity.BulkAction.quickButton.label') }
                        </Basic.Cell>
                      }
                      cell={ <Basic.BooleanCell className="column-face-bool"/> }
                      width={ 100 }/>
                    <Basic.Column
                      property="deleteAction"
                      header={
                        <Basic.Cell
                          className="column-face-bool"
                          title={ this.i18n('entity.BulkAction.deleteAction.title') }>
                          { this.i18n('entity.BulkAction.deleteAction.label') }
                        </Basic.Cell>
                      }
                      cell={ <Basic.BooleanCell className="column-face-bool"/> }
                      width={ 100 }/>
                    <Basic.Column
                      property="order"
                      header={ this.i18n('entity.BulkAction.order.label') }
                      width={ 100 }/>
                    <Basic.Column
                      property="disabled"
                      header={ <Basic.Cell className="column-face-bool">{ this.i18n('entity.BulkAction.disabled.label') }</Basic.Cell> }
                      cell={ <Basic.BooleanCell className="column-face-bool"/> }
                      width={ 100 }/>
                    <Basic.Column
                      header={ this.i18n('entity.id.label') }
                      property="id"
                      rendered={ this.isDevelopment() }
                      className="text-center"
                      width={ 100 }
                      cell={
                        ({rowIndex, data, property}) => (
                          <Advanced.UuidInfo value={ data[rowIndex][property] }/>
                        )
                      }/>
                    <Basic.Column
                      header={this.i18n('label.action')}
                      className="action"
                      cell={
                        ({ rowIndex, data }) => {
                          if (!data[rowIndex].disabled) {
                            return (
                              <Basic.Button
                                level="warning"
                                onClick={ this.onEnable.bind(this, data[rowIndex], false) }
                                className="btn-xs"
                                title={ this.i18n('button.deactivate') }
                                titlePlacement="bottom"
                                rendered={ data[rowIndex].disableable }>
                                { this.i18n('button.deactivate') }
                              </Basic.Button>
                            );
                          }
                          return (
                            <Basic.Button
                              level="success"
                              onClick={ this.onEnable.bind(this, data[rowIndex], true) }
                              className="btn-xs"
                              title={ this.i18n('button.activate') }
                              titlePlacement="bottom">
                              { this.i18n('button.activate') }
                            </Basic.Button>
                          );
                        }
                      }/>
                  </Basic.Table>
                </Basic.Div>
              )).values()]
            }
            <Basic.Pagination total={ bulkActions.length } />
          </Basic.Div>
        }
      </Basic.Div>
    );
  }
}

BulkActions.propTypes = {
  userContext: PropTypes.object,
  registeredBulkActions: PropTypes.object, // immutable
  bulkActions: PropTypes.arrayOf(PropTypes.object),
  showLoading: PropTypes.bool
};

BulkActions.defaultProps = {
  userContext: null,
  showLoading: true
};

function select(state) {
  return {
    registeredBulkActions: DataManager.getData(state, BulkActionManager.UI_KEY_BULK_ACTIONS),
    bulkActions: manager.getEntities(state, UIKEY),
    showLoading: Utils.Ui.isShowLoading(state, UIKEY)
            || Utils.Ui.isShowLoading(state, BulkActionManager.UI_KEY_BULK_ACTIONS),
    _searchParameters: Utils.Ui.getSearchParameters(state, UIKEY)
  };
}

export default connect(select)(BulkActions);
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// A generic onclick callback function.
function genericOnClick(info, tab) {
  //    alert("item " + info.menuItemId + " was clicked");
  //    alert("info: " + JSON.stringify(info));
  //    alert("tab: " + JSON.stringify(tab));
}

// Create one test item for each context type.
var contexts = ["editable"];
for (var i = 0; i < contexts.length; i++) {
    var context = contexts[i];
    var sql = chrome.contextMenus.create({"title": "SQL injection","contexts":[context]});
    var sqlchild = chrome.contextMenus.create(
  {"title": "Test for vulnerability", "parentId": sql, "onclick": genericOnClick,"contexts":[context]});
    var sqlchild2 = chrome.contextMenus.create(
  {"title": "Login Fields", "parentId": sql, "onclick": genericOnClick,"contexts":[context]});

    var xss = chrome.contextMenus.create({"title": "Cross-site Scripting","contexts":[context]});
    var xsschild = chrome.contextMenus.create(
  {"title": "Test for vulnerability", "parentId": xss, "onclick": genericOnClick,"contexts":[context]});
    var xsschild2 = chrome.contextMenus.create(
  {"title": "Insert Image", "parentId": xss, "onclick": genericOnClick,"contexts":[context]});
    var xsschild3 = chrome.contextMenus.create(
  {"title": "Insert Script", "parentId": xss, "onclick": genericOnClick,"contexts":[context]});
    var xsschild4 = chrome.contextMenus.create(
  {"title": "Insert Redirection", "parentId": xss, "onclick": genericOnClick,"contexts":[context]});

    var xsrf = chrome.contextMenus.create({"title": "Cross-site Request Forgery","contexts":[context]});
    var xsrfchild = chrome.contextMenus.create(
  {"title": "Test for vulnerability", "parentId": xsrf, "onclick": genericOnClick,"contexts":[context]});

}

/*
// Create a parent item and two children.
var parent = chrome.contextMenus.create({"title": "Test parent item"});
var child1 = chrome.contextMenus.create(
  {"title": "Child 1", "parentId": parent, "onclick": genericOnClick});
var child2 = chrome.contextMenus.create(
  {"title": "Child 2", "parentId": parent, "onclick": genericOnClick});
console.log("parent:" + parent + " child1:" + child1 + " child2:" + child2);

// Create some radio items.
function radioOnClick(info, tab) {
  console.log("radio item " + info.menuItemId +
              " was clicked (previous checked state was "  +
              info.wasChecked + ")");
}
var radio1 = chrome.contextMenus.create({"title": "Radio 1", "type": "radio",
                                         "onclick":radioOnClick});
var radio2 = chrome.contextMenus.create({"title": "Radio 2", "type": "radio",
                                         "onclick":radioOnClick});
console.log("radio1:" + radio1 + " radio2:" + radio2);

// Create some checkbox items.
function checkboxOnClick(info, tab) {
  console.log(JSON.stringify(info));
  console.log("checkbox item " + info.menuItemId +
              " was clicked, state is now: " + info.checked +
              "(previous state was " + info.wasChecked + ")");

}
var checkbox1 = chrome.contextMenus.create(
  {"title": "Checkbox1", "type": "checkbox", "onclick":checkboxOnClick});
var checkbox2 = chrome.contextMenus.create(
  {"title": "Checkbox2", "type": "checkbox", "onclick":checkboxOnClick});
console.log("checkbox1:" + checkbox1 + " checkbox2:" + checkbox2);

// Intentionally create an invalid item, to show off error checking in the
// create callback.
console.log("About to try creating an invalid item - an error about " +
            "item 999 should show up");
chrome.contextMenus.create({"title": "Oops", "parentId":999}, function() {
  if (chrome.extension.lastError) {
    console.log("Got expected error: " + chrome.extension.lastError.message);
  }
});*/<commit_msg>made context menu child creation easier and neater<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// A generic onclick callback function.
function genericOnClick(info, tab) {
  //    alert("item " + info.menuItemId + " was clicked");
  //    alert("info: " + JSON.stringify(info));
  //    alert("tab: " + JSON.stringify(tab));
}

function sqlOnClick(info,tab){
    alert("item " + info.menuItemId + " was clicked");
    alert("info: " + JSON.stringify(info));
    alert("tab: " + JSON.stringify(tab));
}

// Create one test item for each context type.
var sql = chrome.contextMenus.create({"title": "SQL injection","contexts":["editable"]});
var xss = chrome.contextMenus.create({"title": "Cross-site Scripting","contexts":["editable"]});
var xsrf = chrome.contextMenus.create({"title": "Cross-site Request Forgery","contexts":["editable"]});

//makes into array for easier editing in future.
var sqlchild = [
    {"title": "Test for vulnerability", "parentId": sql, "onclick": sqlOnClick,"contexts":["editable"]},
    {"title": "Login Field", "parentId": sql, "onclick": sqlOnClick,"contexts":["editable"]}
];
var xsschild = [
    {"title": "Test for vulnerability", "parentId": xss, "onclick": genericOnClick,"contexts":["editable"]},
    {"title": "Insert Image", "parentId": xss, "onclick": genericOnClick,"contexts":["editable"]},
    {"title": "Insert Script", "parentId": xss, "onclick": genericOnClick,"contexts":["editable"]},
    {"title": "Insert Redirection", "parentId": xss, "onclick": genericOnClick,"contexts":["editable"]}
];
var xsrfchild = [
  {"title": "Test for vulnerability", "parentId": xsrf, "onclick": genericOnClick,"contexts":["editable"]}
];

var sqlchilds = [];
    sqlchild.forEach(function(entry){
        sqlchilds.push(chrome.contextMenus.create(entry));
    });

var xsschilds = [];
    xsschild.forEach(function(entry){
        xsschilds.push(chrome.contextMenus.create(entry));
    });

var xsrfchilds = [];
    xsrfchild.forEach(function(entry){
        xsrfchilds.push(chrome.contextMenus.create(entry));
    });

/*
// Create a parent item and two children.
var parent = chrome.contextMenus.create({"title": "Test parent item"});
var child1 = chrome.contextMenus.create(
  {"title": "Child 1", "parentId": parent, "onclick": genericOnClick});
var child2 = chrome.contextMenus.create(
  {"title": "Child 2", "parentId": parent, "onclick": genericOnClick});
console.log("parent:" + parent + " child1:" + child1 + " child2:" + child2);

// Create some radio items.
function radioOnClick(info, tab) {
  console.log("radio item " + info.menuItemId +
              " was clicked (previous checked state was "  +
              info.wasChecked + ")");
}
var radio1 = chrome.contextMenus.create({"title": "Radio 1", "type": "radio",
                                         "onclick":radioOnClick});
var radio2 = chrome.contextMenus.create({"title": "Radio 2", "type": "radio",
                                         "onclick":radioOnClick});
console.log("radio1:" + radio1 + " radio2:" + radio2);

// Create some checkbox items.
function checkboxOnClick(info, tab) {
  console.log(JSON.stringify(info));
  console.log("checkbox item " + info.menuItemId +
              " was clicked, state is now: " + info.checked +
              "(previous state was " + info.wasChecked + ")");

}
var checkbox1 = chrome.contextMenus.create(
  {"title": "Checkbox1", "type": "checkbox", "onclick":checkboxOnClick});
var checkbox2 = chrome.contextMenus.create(
  {"title": "Checkbox2", "type": "checkbox", "onclick":checkboxOnClick});
console.log("checkbox1:" + checkbox1 + " checkbox2:" + checkbox2);

// Intentionally create an invalid item, to show off error checking in the
// create callback.
console.log("About to try creating an invalid item - an error about " +
            "item 999 should show up");
chrome.contextMenus.create({"title": "Oops", "parentId":999}, function() {
  if (chrome.extension.lastError) {
    console.log("Got expected error: " + chrome.extension.lastError.message);
  }
});*/<|endoftext|>


<commit_before>Ext.namespace('Kwc.Abstract.Image');
Kwc.Abstract.Image.DimensionWindow = Ext.extend(Ext.Window, {

    dimensions: null,
    value: null, //contains width, height, cropdata

    title: trlKwf('Configure'),
    closeAction: 'close',
    modal: true,
    minWidth: 418,
    minHeight: 250,
    width: 418,
    height: 250,
    layout: 'fit',
    resizable: false,

    initComponent: function() {
        var radios = [];
        for (var i in this.dimensions) {
            radios.push({
                inputValue: i,
                boxLabel: Kwc.Abstract.Image.DimensionField.getDimensionString(this.dimensions, {dimension: i}),
                name: 'dimension',
                listeners: {
                    check: this._enableDisableFields,
                    scope: this
                }
            });
        }
        this._dimensionField = new Kwf.Form.RadioGroup({
            columns: 1,
            hideLabel: true,
            vertical: false,
            items: radios
        });
        this._widthField = new Ext.form.NumberField({
            width: 45,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });
        this._heightField = new Ext.form.NumberField({
            width: 45,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });
        this._xField = new Ext.BoxComponent({
            autoEl: {
                html: 'x',
                style: 'line-height:20px;text-align:center;padding-left:2px;padding-right:2px;'
            }
        });
        this._pxField = new Ext.BoxComponent({
            autoEl: {
                html: 'px',
                style: 'line-height:20px;text-align:center;padding-left:2px;'
            }
        });
        this._userSelection = new Ext.Panel({
            xtype: 'panel',
            layout: 'column',
            hideBorders: true,
            autoHeight: true,
            items: [
                this._widthField,
                this._xField,
                this._heightField,
                this._pxField
            ]
        });

        this._widthField.on('blur', this._validateSizes, this);
        this._widthField.on('keyup', this._validateSizes, this);
        this._widthField.on('keyup', this._updateOutSize, this);
        this._heightField.on('blur', this._validateSizes, this);
        this._heightField.on('keyup', this._validateSizes, this);
        this._heightField.on('keyup', this._updateOutSize, this);
        this._dimensionField.on('change', this._validateSizes, this);
        this._dimensionField.on('change', this._resetCropRegion, this);

        // Has to be initialized before cropRegion because cropRegion needs dimensionValue
        if (this.value && this.value.dimension) {
            this._dimensionField.setValue(this.value.dimension);
            this._widthField.setValue(this.value.width);
            this._heightField.setValue(this.value.height);
        } else {
            for (var i in this.dimensions) {
                break;
            }
            this._dimensionField.setValue(i);
        }
        this._enableDisableFields();

        this._configPanel = new Ext.Panel({
            region: 'west',
            bodyStyle: 'padding: 10px',
            width: 200,
            autoScroll: true,
            title: trlKwf('Select dimension'),
            hideBorders: true,
            items: [
                this._dimensionField,
                this._userSelection
            ]
        });

        this._initCropRegion();

        var cropPanelItems = new Array();
        if (this._cropImage.isCropDisabled()) {
            // show information for not able to crop
            var cropDisabledInfo = new Ext.BoxComponent({
                autoEl: {
                    tag: 'div',
                    cls: 'information',
                    html: trlKwf('There is no crop enabled because image is too small!')
                }
            });
            cropPanelItems.add(cropDisabledInfo);
        }
        cropPanelItems.add(this._cropImage);

        this._cropPanel = new Ext.Panel({
            cls: 'kwc-abstract-image-dimension-window-crop-panel',
            region: 'center',
            title: trlKwf('Select image region'),
            width: 600,
            height: 200,
            items: cropPanelItems
        });

        this.items = new Ext.FormPanel({
            border: false,
            bodyStyle: 'padding: 10px',
            layout: 'border',
            items: [
                this._configPanel,
                this._cropPanel
            ]
        });
        this.buttons = [
            {
                text: trlKwf('OK'),
                handler: function() {
                    if (this._validateSizes()) {
                        this.value = {
                            dimension: this._dimensionField.getValue(),
                            width: this._widthField.getValue(),
                            height: this._heightField.getValue(),
                            cropData: this._cropImage.getValue()
                        };
                        this.fireEvent('save', this.value);
                        this.close();
                    } else {
                        Ext.Msg.alert(trlKwf('Error'), trlKwf('Please fill the marked fields correctly.'));
                    }
                },
                scope: this
            },{
                text: trlKwf('Cancel'),
                handler: function() {
                    this.close();
                },
                scope: this
            }
        ];

        Kwc.Abstract.Image.DimensionWindow.superclass.initComponent.call(this);
        this._validateSizes();
    },

    _initCropRegion: function ()
    {
        var cropData = null;
        if (this._dimensionField.getValue() == this.value.dimension) {
            // load saved crop-values if not 0
            if (this.value.cropData && this.value.cropData.width > 0 && this.value.cropData.height > 0) {
                cropData = this.value.cropData;
            }
        }

        var outWidth = this._getUserSelectedDimensionWidth();
        var outHeight = this._getUserSelectedDimensionHeight();

        var imageWidth = Math.round(this.imageData.imageWidth / this.imageData.imageHandyScaleFactor);
        var imageHeight = Math.round(this.imageData.imageHeight / this.imageData.imageHandyScaleFactor);
        this._cropImage = new Kwc.Abstract.Image.CropImage({
            // call controller to create image with nice size to work with
            src: '/kwf/media/upload/download-handy?uploadId='+this.imageData.uploadId+'&hashKey='+this.imageData.hashKey,
            preserveRatio: this._getPreserveRatio(),
            cls: 'kwc-abstract-image-dimension-window-crop-image',
            outWidth: outWidth,
            outHeight: outHeight,
            cropData: cropData,
            width: imageWidth,
            height: imageHeight,
            style: 'margin-left:'+imageWidth/-2+'px;margin-top:'+imageHeight/-2+'px'
        });

        // Check if smaller than usefull so keep min-width
        var width = this.width;
        if (imageWidth +this._configPanel.width +18 > this.minWidth) {// and border
            width = this._configPanel.width +18 + imageWidth;
        }
        var height = this.height;
        if (imageHeight +98 > this.minHeight) { //titles height
            height = imageHeight +98;
        }
        this.setSize(width, height);
    },

    _getPreserveRatio: function()
    {
        var preserveRatio = false;
        var outWidth = this._getUserSelectedDimensionWidth();
        var outHeight = this._getUserSelectedDimensionHeight();
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.cover == true && !(outWidth <= 0 || outHeight <= 0)) {
            preserveRatio = true;
        }
        return preserveRatio;
    },

    _getUserSelectedDimensionHeight: function ()
    {
        var outHeight = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.height == 'user' && this._heightField.getValue() != '') {
            outHeight = this._heightField.getValue();
        } else if (dimension.height >= 0) {
            outHeight = dimension.height;
        } else if (typeof dimension.height === 'undefined') {
            outHeight = 0;
        }
        return outHeight;
    },

    _getUserSelectedDimensionWidth: function ()
    {
        var outWidth = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.width == 'user' && this._widthField.getValue() != '') {
            outWidth = this._widthField.getValue();
        } else if (dimension.width == 'contentWidth') {
            outWidth = 0;
        } else if (dimension.width >= 0) {
            outWidth = dimension.width;
        } else if (typeof dimension.width === 'undefined') {
            outWidth = 0;
        }
        return outWidth;
    },

    _resetCropRegion: function (element, value)
    {
        var cropData = this._cropImage.getValue();
        if (value.inputValue == this.value.dimension) {
            cropData = this.value.cropData;
        }
        this.value = {
            dimension: this._dimensionField.getValue(),
            width: this._widthField.getValue(),
            height: this._heightField.getValue(),
            cropData: cropData
        };
        this._cropImage.outWidth = this._getUserSelectedDimensionWidth();
        this._cropImage.outHeight = this._getUserSelectedDimensionHeight();
        this._cropImage.setCropData(cropData, this._getPreserveRatio());
    },

    _validateSizes: function()
    {
        var dim = this._dimensionField.getValue();
        if (this._widthField.getValue() < 1 && this.dimensions[dim].width == 'user'
            && this._heightField.getValue() < 1 && this.dimensions[dim].height == 'user'
        ) {
            if (this._widthField.getValue() < 1) {
                this._widthField.markInvalid(trlKwf('Width or height must be higher than 0.'));
            }
            if (this._heightField.getValue() < 1) {
                this._heightField.markInvalid(trlKwf('Width or height must be higher than 0.'));
            }
            return false;
        }

        this._widthField.clearInvalid();
        this._heightField.clearInvalid();

        return true;
    },

    _updateOutSize: function()
    {
        var outWidth = this._widthField.getValue();
        var outHeight = this._heightField.getValue();
        var cropData = this._cropImage.getValue();
        var preserveRatio = false;
        this._cropImage.outWidth = outWidth;
        this._cropImage.outHeight = outHeight;
        if (outWidth > 0 && outHeight > 0) {
            preserveRatio = true;
        }
        this._cropImage.setCropData(cropData, preserveRatio);
    },

    _enableDisableFields: function()
    {
        var userSelection = false;
        for (var i in this.dimensions) {
            var dim = this.dimensions[i];
            if (dim.width == 'user' || dim.height == 'user') {
                userSelection = true;
            }
        }
        if (userSelection) {
            this._userSelection.show();
            var dim = this.dimensions[this._dimensionField.getValue()];
            this._widthField.setDisabled(!(dim && dim.width == 'user'));
            this._heightField.setDisabled(!(dim && dim.height == 'user'));
            this._xField.setDisabled(!(dim && dim.width == 'user')
                    || !(dim && dim.height == 'user'));
            this._pxField.setDisabled(!(dim && dim.width == 'user')
                    || !(dim && dim.height == 'user'));
        } else {
            this._userSelection.hide();
        }
    }
});

Ext.reg('kwc.image.dimensionwindow', Kwc.Abstract.Image.DimensionWindow);
<commit_msg>Add comment to remember how to change back to "reset on change"<commit_after>Ext.namespace('Kwc.Abstract.Image');
Kwc.Abstract.Image.DimensionWindow = Ext.extend(Ext.Window, {

    dimensions: null,
    value: null, //contains width, height, cropdata

    title: trlKwf('Configure'),
    closeAction: 'close',
    modal: true,
    minWidth: 418,
    minHeight: 250,
    width: 418,
    height: 250,
    layout: 'fit',
    resizable: false,

    initComponent: function() {
        var radios = [];
        for (var i in this.dimensions) {
            radios.push({
                inputValue: i,
                boxLabel: Kwc.Abstract.Image.DimensionField.getDimensionString(this.dimensions, {dimension: i}),
                name: 'dimension',
                listeners: {
                    check: this._enableDisableFields,
                    scope: this
                }
            });
        }
        this._dimensionField = new Kwf.Form.RadioGroup({
            columns: 1,
            hideLabel: true,
            vertical: false,
            items: radios
        });
        this._widthField = new Ext.form.NumberField({
            width: 45,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });
        this._heightField = new Ext.form.NumberField({
            width: 45,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });
        this._xField = new Ext.BoxComponent({
            autoEl: {
                html: 'x',
                style: 'line-height:20px;text-align:center;padding-left:2px;padding-right:2px;'
            }
        });
        this._pxField = new Ext.BoxComponent({
            autoEl: {
                html: 'px',
                style: 'line-height:20px;text-align:center;padding-left:2px;'
            }
        });
        this._userSelection = new Ext.Panel({
            xtype: 'panel',
            layout: 'column',
            hideBorders: true,
            autoHeight: true,
            items: [
                this._widthField,
                this._xField,
                this._heightField,
                this._pxField
            ]
        });

        this._widthField.on('blur', this._validateSizes, this);
        this._widthField.on('keyup', this._validateSizes, this);
        this._widthField.on('keyup', this._updateOutSize, this);
        this._heightField.on('blur', this._validateSizes, this);
        this._heightField.on('keyup', this._validateSizes, this);
        this._heightField.on('keyup', this._updateOutSize, this);
        this._dimensionField.on('change', this._validateSizes, this);
        this._dimensionField.on('change', this._resetCropRegion, this);

        // Has to be initialized before cropRegion because cropRegion needs dimensionValue
        if (this.value && this.value.dimension) {
            this._dimensionField.setValue(this.value.dimension);
            this._widthField.setValue(this.value.width);
            this._heightField.setValue(this.value.height);
        } else {
            for (var i in this.dimensions) {
                break;
            }
            this._dimensionField.setValue(i);
        }
        this._enableDisableFields();

        this._configPanel = new Ext.Panel({
            region: 'west',
            bodyStyle: 'padding: 10px',
            width: 200,
            autoScroll: true,
            title: trlKwf('Select dimension'),
            hideBorders: true,
            items: [
                this._dimensionField,
                this._userSelection
            ]
        });

        this._initCropRegion();

        var cropPanelItems = new Array();
        if (this._cropImage.isCropDisabled()) {
            // show information for not able to crop
            var cropDisabledInfo = new Ext.BoxComponent({
                autoEl: {
                    tag: 'div',
                    cls: 'information',
                    html: trlKwf('There is no crop enabled because image is too small!')
                }
            });
            cropPanelItems.add(cropDisabledInfo);
        }
        cropPanelItems.add(this._cropImage);

        this._cropPanel = new Ext.Panel({
            cls: 'kwc-abstract-image-dimension-window-crop-panel',
            region: 'center',
            title: trlKwf('Select image region'),
            width: 600,
            height: 200,
            items: cropPanelItems
        });

        this.items = new Ext.FormPanel({
            border: false,
            bodyStyle: 'padding: 10px',
            layout: 'border',
            items: [
                this._configPanel,
                this._cropPanel
            ]
        });
        this.buttons = [
            {
                text: trlKwf('OK'),
                handler: function() {
                    if (this._validateSizes()) {
                        this.value = {
                            dimension: this._dimensionField.getValue(),
                            width: this._widthField.getValue(),
                            height: this._heightField.getValue(),
                            cropData: this._cropImage.getValue()
                        };
                        this.fireEvent('save', this.value);
                        this.close();
                    } else {
                        Ext.Msg.alert(trlKwf('Error'), trlKwf('Please fill the marked fields correctly.'));
                    }
                },
                scope: this
            },{
                text: trlKwf('Cancel'),
                handler: function() {
                    this.close();
                },
                scope: this
            }
        ];

        Kwc.Abstract.Image.DimensionWindow.superclass.initComponent.call(this);
        this._validateSizes();
    },

    _initCropRegion: function ()
    {
        var cropData = null;
        if (this._dimensionField.getValue() == this.value.dimension) {
            // load saved crop-values if not 0
            if (this.value.cropData && this.value.cropData.width > 0 && this.value.cropData.height > 0) {
                cropData = this.value.cropData;
            }
        }

        var outWidth = this._getUserSelectedDimensionWidth();
        var outHeight = this._getUserSelectedDimensionHeight();

        var imageWidth = Math.round(this.imageData.imageWidth / this.imageData.imageHandyScaleFactor);
        var imageHeight = Math.round(this.imageData.imageHeight / this.imageData.imageHandyScaleFactor);
        this._cropImage = new Kwc.Abstract.Image.CropImage({
            // call controller to create image with nice size to work with
            src: '/kwf/media/upload/download-handy?uploadId='+this.imageData.uploadId+'&hashKey='+this.imageData.hashKey,
            preserveRatio: this._getPreserveRatio(),
            cls: 'kwc-abstract-image-dimension-window-crop-image',
            outWidth: outWidth,
            outHeight: outHeight,
            cropData: cropData,
            width: imageWidth,
            height: imageHeight,
            style: 'margin-left:'+imageWidth/-2+'px;margin-top:'+imageHeight/-2+'px'
        });

        // Check if smaller than usefull so keep min-width
        var width = this.width;
        if (imageWidth +this._configPanel.width +18 > this.minWidth) {// and border
            width = this._configPanel.width +18 + imageWidth;
        }
        var height = this.height;
        if (imageHeight +98 > this.minHeight) { //titles height
            height = imageHeight +98;
        }
        this.setSize(width, height);
    },

    _getPreserveRatio: function()
    {
        var preserveRatio = false;
        var outWidth = this._getUserSelectedDimensionWidth();
        var outHeight = this._getUserSelectedDimensionHeight();
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.cover == true && !(outWidth <= 0 || outHeight <= 0)) {
            preserveRatio = true;
        }
        return preserveRatio;
    },

    _getUserSelectedDimensionHeight: function ()
    {
        var outHeight = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.height == 'user' && this._heightField.getValue() != '') {
            outHeight = this._heightField.getValue();
        } else if (dimension.height >= 0) {
            outHeight = dimension.height;
        } else if (typeof dimension.height === 'undefined') {
            outHeight = 0;
        }
        return outHeight;
    },

    _getUserSelectedDimensionWidth: function ()
    {
        var outWidth = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.width == 'user' && this._widthField.getValue() != '') {
            outWidth = this._widthField.getValue();
        } else if (dimension.width == 'contentWidth') {
            outWidth = 0;
        } else if (dimension.width >= 0) {
            outWidth = dimension.width;
        } else if (typeof dimension.width === 'undefined') {
            outWidth = 0;
        }
        return outWidth;
    },

    _resetCropRegion: function (element, value)
    {
        //Change to cropData = null to reset selection on change
        var cropData = this._cropImage.getValue();
        if (value.inputValue == this.value.dimension) {
            cropData = this.value.cropData;
        }
        this.value = {
            dimension: this._dimensionField.getValue(),
            width: this._widthField.getValue(),
            height: this._heightField.getValue(),
            cropData: cropData
        };
        this._cropImage.outWidth = this._getUserSelectedDimensionWidth();
        this._cropImage.outHeight = this._getUserSelectedDimensionHeight();
        this._cropImage.setCropData(cropData, this._getPreserveRatio());
    },

    _validateSizes: function()
    {
        var dim = this._dimensionField.getValue();
        if (this._widthField.getValue() < 1 && this.dimensions[dim].width == 'user'
            && this._heightField.getValue() < 1 && this.dimensions[dim].height == 'user'
        ) {
            if (this._widthField.getValue() < 1) {
                this._widthField.markInvalid(trlKwf('Width or height must be higher than 0.'));
            }
            if (this._heightField.getValue() < 1) {
                this._heightField.markInvalid(trlKwf('Width or height must be higher than 0.'));
            }
            return false;
        }

        this._widthField.clearInvalid();
        this._heightField.clearInvalid();

        return true;
    },

    _updateOutSize: function()
    {
        var outWidth = this._widthField.getValue();
        var outHeight = this._heightField.getValue();
        var cropData = this._cropImage.getValue();
        var preserveRatio = false;
        this._cropImage.outWidth = outWidth;
        this._cropImage.outHeight = outHeight;
        if (outWidth > 0 && outHeight > 0) {
            preserveRatio = true;
        }
        this._cropImage.setCropData(cropData, preserveRatio);
    },

    _enableDisableFields: function()
    {
        var userSelection = false;
        for (var i in this.dimensions) {
            var dim = this.dimensions[i];
            if (dim.width == 'user' || dim.height == 'user') {
                userSelection = true;
            }
        }
        if (userSelection) {
            this._userSelection.show();
            var dim = this.dimensions[this._dimensionField.getValue()];
            this._widthField.setDisabled(!(dim && dim.width == 'user'));
            this._heightField.setDisabled(!(dim && dim.height == 'user'));
            this._xField.setDisabled(!(dim && dim.width == 'user')
                    || !(dim && dim.height == 'user'));
            this._pxField.setDisabled(!(dim && dim.width == 'user')
                    || !(dim && dim.height == 'user'));
        } else {
            this._userSelection.hide();
        }
    }
});

Ext.reg('kwc.image.dimensionwindow', Kwc.Abstract.Image.DimensionWindow);
<|endoftext|>


<commit_before>/* global describe, it*/
/* jslint node: true, esnext: true */

"use strict";

const fs = require('fs');
const path = require('path');
const request = require('request');

const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();

const endpointImpl = require('../lib/endpointImplementation');

describe('http endpoint', function () {
  const url = "http://localhost:12345/";

  const endpoint = endpointImpl.createEndpoint('e1', {
    target: url,
    direction: 'in'
  }, endpointImpl.implementations.http);

  const flowStream = fs.createReadStream(path.join(__dirname,'fixtures','sample.flow'),{ encoding: 'utf8' });

  setTimeout(function() {
    request.post({
        url: url,
        formData: {
          content: flowStream,
        }
      },
      function optionalCallback(err, httpResponse, body) {
      //console.log(`http post done: ${body}`);
      });
    },10);

  it("should produce a request", function (done) {

    let in1 = endpoint.initialize(function *() {
      const r = yield;
//      console.log(`request: ${JSON.stringify(r.info)}`);
      assert(r.info.host === 'localhost:12345');
      done();
      });
/*
    let gen = in1.next();
    let request = gen.value;
    assert(request.info.name === 'stdin');
    assert(request.stream !== undefined);
    */
  });
});
<commit_msg>testing hack: increas timeout aftern initialiing http endpoint<commit_after>/* global describe, it*/
/* jslint node: true, esnext: true */

"use strict";

const fs = require('fs');
const path = require('path');
const request = require('request');

const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();

const endpointImpl = require('../lib/endpointImplementation');

describe('http endpoint', function () {
  const url = "http://localhost:12346/";

  const endpoint = endpointImpl.createEndpoint('e1', {
    target: url,
    direction: 'in'
  }, endpointImpl.implementations.http);

  const flowStream = fs.createReadStream(path.join(__dirname,'fixtures','sample.flow'),{ encoding: 'utf8' });

  setTimeout(function() {
    request.post({
        url: url,
        formData: {
          content: flowStream,
        }
      },
      function optionalCallback(err, httpResponse, body) {
        console.log(`http post done: ${body}`);
      });
    },300);

  it("should produce a request", function (done) {
    let in1 = endpoint.initialize(function *() {
      const r = yield;
      console.log(`request: ${JSON.stringify(r.info)}`);
      assert(r.info.host === 'localhost:12346');
      done();
      });
  });
});
<|endoftext|>


<commit_before>/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};

(function ($) {
	'use strict';

	// The Application
	// ---------------

	// Our overall **AppView** is the top-level piece of UI.
	app.AppView = Backbone.View.extend({

		// Instead of generating a new element, bind to the existing skeleton of
		// the App already present in the HTML.
		el: '#todoapp',

		// Our template for the line of statistics at the bottom of the app.
		statsTemplate: _.template($('#stats-template').html()),

		// Delegated events for creating new items, and clearing completed ones.
		events: {
			'keypress #new-todo': 'createOnEnter',
			'click #clear-completed': 'clearCompleted',
			'click #toggle-all': 'toggleAllComplete'
		},

		// At initialization we bind to the relevant events on the `Todos`
		// collection, when items are added or changed. Kick things off by
		// loading any preexisting todos that might be saved in *localStorage*.
		initialize: function () {
			this.allCheckbox = this.$('#toggle-all')[0];
			this.$input = this.$('#new-todo');
			this.$footer = this.$('#footer');
			this.$main = this.$('#main');
			this.$list = $('#todo-list');

			this.listenTo(app.todos, 'add', this.addOne);
			this.listenTo(app.todos, 'reset', this.addAll);
			this.listenTo(app.todos, 'change:completed', this.filterOne);
			this.listenTo(app.todos, 'filter', this.filterAll);
			this.listenTo(app.todos, 'all', this.render);

			// Suppresses 'add' events with {reset: true} and prevents the app view
			// from being re-rendered for every model. Only renders when the 'reset'
			// event is triggered at the end of the fetch.
			app.todos.fetch({reset: true});
		},

		// Re-rendering the App just means refreshing the statistics -- the rest
		// of the app doesn't change.
		render: function () {
			var completed = app.todos.completed().length;
			var remaining = app.todos.remaining().length;

			if (app.todos.length) {
				this.$main.show();
				this.$footer.show();

				this.$footer.html(this.statsTemplate({
					completed: completed,
					remaining: remaining
				}));

				this.$('#filters li a')
					.removeClass('selected')
					.filter('[href="#/' + (app.TodoFilter || '') + '"]')
					.addClass('selected');
			} else {
				this.$main.hide();
				this.$footer.hide();
			}

			this.allCheckbox.checked = !remaining;
		},

		// Add a single todo item to the list by creating a view for it, and
		// appending its element to the `<ul>`.
		addOne: function (todo) {
			var view = new app.TodoView({ model: todo });
			this.$list.append(view.render().el);
		},

		// Add all items in the **Todos** collection at once.
		addAll: function () {
			this.$list.html('');
			app.todos.each(this.addOne, this);
		},

		filterOne: function (todo) {
			todo.trigger('visible');
		},

		filterAll: function () {
			app.todos.each(this.filterOne, this);
		},

		// Generate the attributes for a new Todo item.
		newAttributes: function () {
			return {
				title: this.$input.val().trim(),
				order: app.todos.nextOrder(),
				completed: false
			};
		},

		// If you hit return in the main input field, create new **Todo** model,
		// persisting it to *localStorage*.
		createOnEnter: function (e) {
			if (e.which === ENTER_KEY && this.$input.val().trim()) {
				app.todos.create(this.newAttributes());
				this.$input.val('');
			}
		},

		// Clear all completed todo items, destroying their models.
		clearCompleted: function () {
			_.invoke(app.todos.completed(), 'destroy');
			return false;
		},

		toggleAllComplete: function () {
			var completed = this.allCheckbox.checked;

			app.todos.each(function (todo) {
				todo.save({
					completed: completed
				});
			});
		}
	});
})(jQuery);
<commit_msg>Debounce the rendering of the application view<commit_after>/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};

(function ($) {
	'use strict';

	// The Application
	// ---------------

	// Our overall **AppView** is the top-level piece of UI.
	app.AppView = Backbone.View.extend({

		// Instead of generating a new element, bind to the existing skeleton of
		// the App already present in the HTML.
		el: '#todoapp',

		// Our template for the line of statistics at the bottom of the app.
		statsTemplate: _.template($('#stats-template').html()),

		// Delegated events for creating new items, and clearing completed ones.
		events: {
			'keypress #new-todo': 'createOnEnter',
			'click #clear-completed': 'clearCompleted',
			'click #toggle-all': 'toggleAllComplete'
		},

		// At initialization we bind to the relevant events on the `Todos`
		// collection, when items are added or changed. Kick things off by
		// loading any preexisting todos that might be saved in *localStorage*.
		initialize: function () {
			this.allCheckbox = this.$('#toggle-all')[0];
			this.$input = this.$('#new-todo');
			this.$footer = this.$('#footer');
			this.$main = this.$('#main');
			this.$list = $('#todo-list');

			this.listenTo(app.todos, 'add', this.addOne);
			this.listenTo(app.todos, 'reset', this.addAll);
			this.listenTo(app.todos, 'change:completed', this.filterOne);
			this.listenTo(app.todos, 'filter', this.filterAll);
			this.listenTo(app.todos, 'all', _.debounce(this.render, 0));

			// Suppresses 'add' events with {reset: true} and prevents the app view
			// from being re-rendered for every model. Only renders when the 'reset'
			// event is triggered at the end of the fetch.
			app.todos.fetch({reset: true});
		},

		// Re-rendering the App just means refreshing the statistics -- the rest
		// of the app doesn't change.
		render: function () {
			var completed = app.todos.completed().length;
			var remaining = app.todos.remaining().length;

			if (app.todos.length) {
				this.$main.show();
				this.$footer.show();

				this.$footer.html(this.statsTemplate({
					completed: completed,
					remaining: remaining
				}));

				this.$('#filters li a')
					.removeClass('selected')
					.filter('[href="#/' + (app.TodoFilter || '') + '"]')
					.addClass('selected');
			} else {
				this.$main.hide();
				this.$footer.hide();
			}

			this.allCheckbox.checked = !remaining;
		},

		// Add a single todo item to the list by creating a view for it, and
		// appending its element to the `<ul>`.
		addOne: function (todo) {
			var view = new app.TodoView({ model: todo });
			this.$list.append(view.render().el);
		},

		// Add all items in the **Todos** collection at once.
		addAll: function () {
			this.$list.html('');
			app.todos.each(this.addOne, this);
		},

		filterOne: function (todo) {
			todo.trigger('visible');
		},

		filterAll: function () {
			app.todos.each(this.filterOne, this);
		},

		// Generate the attributes for a new Todo item.
		newAttributes: function () {
			return {
				title: this.$input.val().trim(),
				order: app.todos.nextOrder(),
				completed: false
			};
		},

		// If you hit return in the main input field, create new **Todo** model,
		// persisting it to *localStorage*.
		createOnEnter: function (e) {
			if (e.which === ENTER_KEY && this.$input.val().trim()) {
				app.todos.create(this.newAttributes());
				this.$input.val('');
			}
		},

		// Clear all completed todo items, destroying their models.
		clearCompleted: function () {
			_.invoke(app.todos.completed(), 'destroy');
			return false;
		},

		toggleAllComplete: function () {
			var completed = this.allCheckbox.checked;

			app.todos.each(function (todo) {
				todo.save({
					completed: completed
				});
			});
		}
	});
})(jQuery);
<|endoftext|>


<commit_before>var tempQuizBuilder = require('../quiz');

function buildQuizFromQuizDescriptor(descriptor, id, s) {
	var tmpQuiz = new tempQuizBuilder.Quiz(descriptor, { seed : s });

    var showQuestions = 1;
    var showKey = 1;
    var showJson = 1;

    var quiz = {};

    quiz.title = descriptor.title;
    quiz.qd = id;
    quiz.seed = s;
    quiz.questions = [];

	for (var i = 0; i < tmpQuiz.questions.length; i++) {
    	var q = {
    		question : tmpQuiz.questions[i].question,
    		answer : tmpQuiz.questions[i].answer,
            format : tmpQuiz.questions[i].format
    	};
    	quiz.questions.push(q);

	}

	return quiz;

}

module.exports.build = buildQuizFromQuizDescriptor;

<commit_msg>QuizBuilder expects the seed to be an 8 digit hex string.<commit_after>var tempQuizBuilder = require('../quiz');

function buildQuizFromQuizDescriptor(descriptor, id, hexStringSeed) {
    var s = parseInt(hexStringSeed, 16);
	var tmpQuiz = new tempQuizBuilder.Quiz(descriptor, { seed : s });

    var showQuestions = 1;
    var showKey = 1;
    var showJson = 1;

    var quiz = {};

    quiz.title = descriptor.title;
    quiz.qd = id;
    quiz.seed = s;
    quiz.questions = [];

	for (var i = 0; i < tmpQuiz.questions.length; i++) {
    	var q = {
    		question : tmpQuiz.questions[i].question,
    		answer : tmpQuiz.questions[i].answer,
            format : tmpQuiz.questions[i].format
    	};
    	quiz.questions.push(q);

	}

	return quiz;

}

module.exports.build = buildQuizFromQuizDescriptor;

<|endoftext|>


<commit_before>console.log("basic test");

var url, request, NODE, uri, should, assert;

//check if we are in browser or webview
if (typeof window == "undefined") {
  console.log("we are not in the browser");
  url = require('url');

  request = require('superagent');

  NODE = true;
  uri = 'http://localhost:5000';
  if (typeof window !== 'undefined') {
    NODE = false;
    uri = '//' + window.location.host;
  }
  else {
    process.env.ZUUL_PORT = 5000;
    require('./support/server.js');
    uri = 'http://localhost:5000';
  }

}

//desktop
if (typeof cordova == "undefined" && typeof window == "undefined") {
    console.log("we are in the desktop");
    should = require('should');
    assert = require('assert');
}

//test if we are using mocha
if(typeof describe != "undefined") {

    describe('request', function () {

        describe('with a callback', function () {
            it('should invoke .end()', function (done) {
                request
                    .get(uri + '/login', function (err, res) {
                        assert(res.status == 200);
                        done();
                    })
            })
        })

        describe('.end()', function () {
            it('should issue a request', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        assert(res.status == 200);
                        done();
                    });
            })
        })

        describe('res.error', function () {
            it('should should be an Error object', function (done) {
                request
                    .get(uri + '/error')
                    .end(function (err, res) {
                        if (NODE) {
                            res.error.message.should.equal('cannot GET /error (500)');
                        }
                        else {
                            res.error.message.should.equal('cannot GET ' + uri + '/error (500)');
                        }
                        assert(res.error.status === 500);
                        assert(err, 'should have an error for 500');
                        assert.equal(err.message, 'Internal Server Error');
                        done();
                    });
            })
        })

        describe('res.header', function () {
            it('should be an object', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        assert('Express' == res.header['x-powered-by']);
                        done();
                    });
            })
        })

        describe('res.charset', function () {
            it('should be set when present', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        res.charset.should.equal('utf-8');
                        done();
                    });
            })
        })

        describe('res.statusType', function () {
            it('should provide the first digit', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        assert(!err, 'should not have an error for success responses');
                        assert(200 == res.status);
                        assert(2 == res.statusType);
                        done();
                    });
            })
        })

        describe('res.type', function () {
            it('should provide the mime-type void of params', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        res.type.should.equal('text/html');
                        res.charset.should.equal('utf-8');
                        done();
                    });
            })
        })

        describe('req.set(field, val)', function () {
            it('should set the header field', function (done) {
                request
                    .post(uri + '/echo')
                    .set('X-Foo', 'bar')
                    .set('X-Bar', 'baz')
                    .end(function (err, res) {
                        assert('bar' == res.header['x-foo']);
                        assert('baz' == res.header['x-bar']);
                        done();
                    })
            })
        })

        describe('req.set(obj)', function () {
            it('should set the header fields', function (done) {
                request
                    .post(uri + '/echo')
                    .set({'X-Foo': 'bar', 'X-Bar': 'baz'})
                    .end(function (err, res) {
                        assert('bar' == res.header['x-foo']);
                        assert('baz' == res.header['x-bar']);
                        done();
                    })
            })
        })

        describe('req.type(str)', function () {
            it('should set the Content-Type', function (done) {
                request
                    .post(uri + '/echo')
                    .type('text/x-foo')
                    .end(function (err, res) {
                        res.header['content-type'].should.equal('text/x-foo');
                        done();
                    });
            })

            it('should map "json"', function (done) {
                request
                    .post(uri + '/echo')
                    .type('json')
                    .send('{"a": 1}')
                    .end(function (err, res) {
                        res.should.be.json;
                        done();
                    });
            })

            it('should map "html"', function (done) {
                request
                    .post(uri + '/echo')
                    .type('html')
                    .end(function (err, res) {
                        res.header['content-type'].should.equal('text/html');
                        done();
                    });
            })
        })

        describe('req.accept(str)', function () {
            it('should set Accept', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('text/x-foo')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('text/x-foo');
                        done();
                    });
            })

            it('should map "json"', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('json')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('application/json');
                        done();
                    });
            })

            it('should map "xml"', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('xml')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('application/xml');
                        done();
                    });
            })

            it('should map "html"', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('html')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('text/html');
                        done();
                    });
            })
        })

        describe('req.send(str)', function () {
            it('should write the string', function (done) {
                request
                    .post(uri + '/echo')
                    .type('json')
                    .send('{"name":"tobi"}')
                    .end(function (err, res) {
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    });
            })
        })

        describe('req.send(Object)', function () {
            it('should default to json', function (done) {
                request
                    .post(uri + '/echo')
                    .send({name: 'tobi'})
                    .end(function (err, res) {
                        res.should.be.json
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    });
            })

            describe('when called several times', function () {
                it('should merge the objects', function (done) {
                    request
                        .post(uri + '/echo')
                        .send({name: 'tobi'})
                        .send({age: 1})
                        .end(function (err, res) {
                            res.should.be.json
                            if (NODE) {
                                res.buffered.should.be.true;
                            }
                            res.text.should.equal('{"name":"tobi","age":1}');
                            done();
                        });
                })
            })
        })

        describe('.end(fn)', function () {
            it('should check arity', function (done) {
                request
                    .post(uri + '/echo')
                    .send({name: 'tobi'})
                    .end(function (err, res) {
                        assert(null == err);
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    });
            })

            it('should emit request', function (done) {
                var req = request.post(uri + '/echo');
                req.on('request', function (request) {
                    assert(req == request);
                    done();
                });
                req.end();
            })

            it('should emit response', function (done) {
                request
                    .post(uri + '/echo')
                    .send({name: 'tobi'})
                    .on('response', function (res) {
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    })
                    .end();
            })
        })

        describe('.abort()', function () {
            it('should abort the request', function (done) {
                var req = request
                    .get(uri + '/delay/3000')
                    .end(function (err, res) {
                        assert(false, 'should not complete the request');
                    });

                req.on('abort', done);

                setTimeout(function () {
                    req.abort();
                }, 1000);
            })
        })
    })

}<commit_msg>update superagent tests<commit_after>console.log("basic test");

var url, NODE, uri, should, assert;

//check if we are in browser or webview
if (typeof window == "undefined") {
  console.log("we are not in the browser");
  url = require('url');

  var request = require('superagent');

  NODE = true;
  uri = 'http://localhost:5000';
  if (typeof window !== 'undefined') {
    NODE = false;
    uri = '//' + window.location.host;
  }
  else {
    process.env.ZUUL_PORT = 5000;
    require('./support/server.js');
    uri = 'http://localhost:5000';
  }

}

//desktop
if (typeof cordova == "undefined" && typeof window == "undefined") {
    console.log("we are in the desktop");
    should = require('should');
    assert = require('assert');
}

//test if we are using mocha
if(typeof describe != "undefined") {
    console.log("run mocha tests!");

    console.log("typeof request:" + typeof request);

    describe('request', function () {

        describe('with a callback', function () {
            it('should invoke .end()', function (done) {
                request
                    .get(uri + '/login', function (err, res) {
                        assert(res.status == 200);
                        done();
                    })
            })
        })

        describe('.end()', function () {
            it('should issue a request', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        assert(res.status == 200);
                        done();
                    });
            })
        })

        describe('res.error', function () {
            it('should should be an Error object', function (done) {
                request
                    .get(uri + '/error')
                    .end(function (err, res) {
                        if (NODE) {
                            res.error.message.should.equal('cannot GET /error (500)');
                        }
                        else {
                            res.error.message.should.equal('cannot GET ' + uri + '/error (500)');
                        }
                        assert(res.error.status === 500);
                        assert(err, 'should have an error for 500');
                        assert.equal(err.message, 'Internal Server Error');
                        done();
                    });
            })
        })

        describe('res.header', function () {
            it('should be an object', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        assert('Express' == res.header['x-powered-by']);
                        done();
                    });
            })
        })

        describe('res.charset', function () {
            it('should be set when present', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        res.charset.should.equal('utf-8');
                        done();
                    });
            })
        })

        describe('res.statusType', function () {
            it('should provide the first digit', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        assert(!err, 'should not have an error for success responses');
                        assert(200 == res.status);
                        assert(2 == res.statusType);
                        done();
                    });
            })
        })

        describe('res.type', function () {
            it('should provide the mime-type void of params', function (done) {
                request
                    .get(uri + '/login')
                    .end(function (err, res) {
                        res.type.should.equal('text/html');
                        res.charset.should.equal('utf-8');
                        done();
                    });
            })
        })

        describe('req.set(field, val)', function () {
            it('should set the header field', function (done) {
                request
                    .post(uri + '/echo')
                    .set('X-Foo', 'bar')
                    .set('X-Bar', 'baz')
                    .end(function (err, res) {
                        assert('bar' == res.header['x-foo']);
                        assert('baz' == res.header['x-bar']);
                        done();
                    })
            })
        })

        describe('req.set(obj)', function () {
            it('should set the header fields', function (done) {
                request
                    .post(uri + '/echo')
                    .set({'X-Foo': 'bar', 'X-Bar': 'baz'})
                    .end(function (err, res) {
                        assert('bar' == res.header['x-foo']);
                        assert('baz' == res.header['x-bar']);
                        done();
                    })
            })
        })

        describe('req.type(str)', function () {
            it('should set the Content-Type', function (done) {
                request
                    .post(uri + '/echo')
                    .type('text/x-foo')
                    .end(function (err, res) {
                        res.header['content-type'].should.equal('text/x-foo');
                        done();
                    });
            })

            it('should map "json"', function (done) {
                request
                    .post(uri + '/echo')
                    .type('json')
                    .send('{"a": 1}')
                    .end(function (err, res) {
                        res.should.be.json;
                        done();
                    });
            })

            it('should map "html"', function (done) {
                request
                    .post(uri + '/echo')
                    .type('html')
                    .end(function (err, res) {
                        res.header['content-type'].should.equal('text/html');
                        done();
                    });
            })
        })

        describe('req.accept(str)', function () {
            it('should set Accept', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('text/x-foo')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('text/x-foo');
                        done();
                    });
            })

            it('should map "json"', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('json')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('application/json');
                        done();
                    });
            })

            it('should map "xml"', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('xml')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('application/xml');
                        done();
                    });
            })

            it('should map "html"', function (done) {
                request
                    .get(uri + '/echo')
                    .accept('html')
                    .end(function (err, res) {
                        res.header['accept'].should.equal('text/html');
                        done();
                    });
            })
        })

        describe('req.send(str)', function () {
            it('should write the string', function (done) {
                request
                    .post(uri + '/echo')
                    .type('json')
                    .send('{"name":"tobi"}')
                    .end(function (err, res) {
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    });
            })
        })

        describe('req.send(Object)', function () {
            it('should default to json', function (done) {
                request
                    .post(uri + '/echo')
                    .send({name: 'tobi'})
                    .end(function (err, res) {
                        res.should.be.json
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    });
            })

            describe('when called several times', function () {
                it('should merge the objects', function (done) {
                    request
                        .post(uri + '/echo')
                        .send({name: 'tobi'})
                        .send({age: 1})
                        .end(function (err, res) {
                            res.should.be.json
                            if (NODE) {
                                res.buffered.should.be.true;
                            }
                            res.text.should.equal('{"name":"tobi","age":1}');
                            done();
                        });
                })
            })
        })

        describe('.end(fn)', function () {
            it('should check arity', function (done) {
                request
                    .post(uri + '/echo')
                    .send({name: 'tobi'})
                    .end(function (err, res) {
                        assert(null == err);
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    });
            })

            it('should emit request', function (done) {
                var req = request.post(uri + '/echo');
                req.on('request', function (request) {
                    assert(req == request);
                    done();
                });
                req.end();
            })

            it('should emit response', function (done) {
                request
                    .post(uri + '/echo')
                    .send({name: 'tobi'})
                    .on('response', function (res) {
                        res.text.should.equal('{"name":"tobi"}');
                        done();
                    })
                    .end();
            })
        })

        describe('.abort()', function () {
            it('should abort the request', function (done) {
                var req = request
                    .get(uri + '/delay/3000')
                    .end(function (err, res) {
                        assert(false, 'should not complete the request');
                    });

                req.on('abort', done);

                setTimeout(function () {
                    req.abort();
                }, 1000);
            })
        })
    })

}<|endoftext|>