<commit_before>angular.module(PKG.name + '.commons')
  .controller('MyPlumbController', function MyPlumbController(jsPlumb, $scope, $timeout, MyPlumbService, myHelpers, MyPlumbFactory, $window) {
    this.plugins = $scope.config || [];
    this.isDisabled = $scope.isDisabled;
    this.reloadDAG = $scope.reloaddag;
    MyPlumbService.setIsDisabled(this.isDisabled);

    this.instance = null;

    this.addPlugin = function addPlugin(config, type) {
      this.plugins.push(angular.extend({
        icon: MyPlumbFactory.getIcon(config.name)
      }, config));
      $timeout(drawNode.bind(this, config.id, type));
      $timeout(this.instance.repaintEverything);
    };

    this.removePlugin = function(index, nodeId) {
      this.instance.detachAllConnections(nodeId);
      this.instance.remove(nodeId);
      this.plugins.splice(index, 1);
      MyPlumbService.removeNode(nodeId);
      MyPlumbService.setConnections(this.instance.getConnections());
    };

    // Need to move this to the controller that is using this directive.
    this.onPluginClick = function(plugin) {
      if (plugin.error) {
        delete plugin.error;
      }
      MyPlumbService.editPluginProperties($scope, plugin.id, plugin.type);
    };

    function errorNotification(errObj) {
      this.canvasError = [];
      if (errObj.canvas) {
        this.canvasError = errObj.canvas;
      }

      angular.forEach(this.plugins, function (plugin) {
        if (errObj[plugin.id]) {
          plugin.error = errObj[plugin.id];
        } else if (plugin.error) {
          delete plugin.error;
        }
      });
    }

    MyPlumbService.errorCallback(errorNotification.bind(this));

    this.closeCanvasError = function () {
      this.canvasError = [];
    };

    this.drawGraph = function() {
      var graph = MyPlumbFactory.getGraph(this.plugins);
      var nodes = graph.nodes()
        .map(function(node) {
          return graph.node(node);
        });

      if (this.isDisabled) {
        var margins = $scope.getGraphMargins(this.plugins);
        var marginLeft = margins.left;
      }

      this.plugins.forEach(function(plugin) {
        plugin.icon = MyPlumbFactory.getIcon(plugin.name);
        plugin.style = plugin.style ||
        ( this.isDisabled? MyPlumbFactory.generateStyles(plugin.id, nodes, 0, marginLeft): '');
        drawNode.call(this, plugin.id, plugin.type);
      }.bind(this));

      drawConnections.call(this);

      MyPlumbService.setConnections(this.instance.getConnections());

      mapSchemas.call(this);

      $timeout(this.instance.repaintEverything);
    };

    function drawNode(id, type) {
      var sourceSettings = MyPlumbFactory.getSettings().source,
          sinkSettings = MyPlumbFactory.getSettings().sink;

      switch(type) {
        case 'source':
          this.instance.addEndpoint(id, sourceSettings, {uuid: id});
          break;
        case 'sink':
          this.instance.addEndpoint(id, sinkSettings, {uuid: id});
          break;
        case 'transform':
          // Need to id each end point so that it can be used later to make connections.
          this.instance.addEndpoint(id, sourceSettings, {uuid: 'Left' + id});
          this.instance.addEndpoint(id, sinkSettings, {uuid: 'Right' + id});
          break;
      }
      if (!this.isDisabled) {
        this.instance.draggable(id, {
          drag: function (evt) { return dragnode.call(this, evt); }.bind(this)
        });
      }
      // Super hacky way of restricting user to not scroll beyond certain top and left.
      function dragnode(e) {
        var returnResult = true;
        if (e.pos[1] < 0) {
          e.e.preventDefault();
          e.el.style.top = "10px";
          returnResult = false;
        }
        if (e.pos[0] < 0) {
          e.e.preventDefault();
          e.el.style.left = "10px";
          returnResult = false;
        }
        MyPlumbService.nodes[e.el.id].style = {top: e.el.style.top, left: e.el.style.left};
        return returnResult;
      }
    }

    function drawConnections() {
      var i;
      var prev, curr, next;

      var connections = MyPlumbService.connections;
      for(i=0; i<connections.length; i++) {
        if (connections[i].source.indexOf('transform') !== -1) {
          curr = 'Left' + connections[i].source;
        } else {
          curr = connections[i].source;
        }
        if (connections[i].target.indexOf('transform') !== -1) {
          next = 'Right' + connections[i].target;
        } else {
          next = connections[i].target;
        }

        if (this.isDisabled) {
          this.instance.connect({
            uuids: [curr, next],
            detachable: false
          });
        } else {
          this.instance.connect({
            uuids: [curr, next],
            editable: true
          });
        }
      }
    }

    function mapSchemas() {
      var connections = MyPlumbService.connections;
      var nodes = MyPlumbService.nodes;
      connections.forEach(function(connection) {
        var sourceNode = nodes[connection.source];
        var targetNode = nodes[connection.target];
        var sourceOutputSchema = myHelpers.objectQuery(sourceNode, 'properties', 'schema');
        var targetOuputSchema = myHelpers.objectQuery(targetNode, 'properties', 'schema');
        if (sourceOutputSchema) {
          sourceNode.outputSchema = sourceOutputSchema;
        }
        if (targetOuputSchema) {
          targetNode.outputSchema = targetOuputSchema;
        } else {
          targetNode.outputSchema = sourceNode.outputSchema;
        }
      });
    }

    MyPlumbService.registerCallBack(this.addPlugin.bind(this));

    $scope.$on('$destroy', function() {
      this.instance.reset();
      MyPlumbService.resetToDefaults();
    }.bind(this));

    jsPlumb.ready(function() {
      jsPlumb.setContainer('plumb-container');
      this.instance = jsPlumb.getInstance();

      angular.element($window).on('resize', function() {
        this.instance.repaintEverything();
      }.bind(this));

      this.instance.importDefaults(MyPlumbFactory.getSettings().default);

      // Need to move this to the controller that is using this directive.
      this.instance.bind('connection', function () {
        // Whenever there is a change in the connection just copy the entire array
        // We never know if a connection was altered or removed. We don't want to 'Sync'
        // between jsPlumb's internal connection array and ours (pointless)
        MyPlumbService.setConnections(this.instance.getConnections());
      }.bind(this));

      if (this.plugins.length > 0) {
        $timeout(this.drawGraph.bind(this));
      }
    }.bind(this));

    $scope.$watch('reloaddag', function (value) {
      if (value) {
        this.instance.reset();
        this.instance = jsPlumb.getInstance();
        this.instance.importDefaults(MyPlumbFactory.getSettings().default);
        this.plugins = $scope.config;
        $timeout(this.drawGraph.bind(this));
        $scope.reloaddag = false;
      }
    }.bind(this));

  });
<commit_msg>refactor code<commit_after>angular.module(PKG.name + '.commons')
  .controller('MyPlumbController', function MyPlumbController(jsPlumb, $scope, $timeout, MyPlumbService, myHelpers, MyPlumbFactory, $window) {
    this.plugins = $scope.config || [];
    this.isDisabled = $scope.isDisabled;
    this.reloadDAG = $scope.reloaddag;
    MyPlumbService.setIsDisabled(this.isDisabled);

    this.instance = null;

    this.addPlugin = function addPlugin(config, type) {
      this.plugins.push(angular.extend({
        icon: MyPlumbFactory.getIcon(config.name)
      }, config));
      $timeout(drawNode.bind(this, config.id, type));
      $timeout(this.instance.repaintEverything);
    };

    this.removePlugin = function(index, nodeId) {
      this.instance.detachAllConnections(nodeId);
      this.instance.remove(nodeId);
      this.plugins.splice(index, 1);
      MyPlumbService.removeNode(nodeId);
      MyPlumbService.setConnections(this.instance.getConnections());
    };

    // Need to move this to the controller that is using this directive.
    this.onPluginClick = function(plugin) {
      if (plugin.error) {
        delete plugin.error;
      }
      MyPlumbService.editPluginProperties($scope, plugin.id, plugin.type);
    };

    function errorNotification(errObj) {
      this.canvasError = [];
      if (errObj.canvas) {
        this.canvasError = errObj.canvas;
      }

      angular.forEach(this.plugins, function (plugin) {
        if (errObj[plugin.id]) {
          plugin.error = errObj[plugin.id];
        } else if (plugin.error) {
          delete plugin.error;
        }
      });
    }

    MyPlumbService.errorCallback(errorNotification.bind(this));

    this.closeCanvasError = function () {
      this.canvasError = [];
    };

    this.drawGraph = function() {
      var graph = MyPlumbFactory.getGraph(this.plugins);
      var nodes = graph.nodes()
        .map(function(node) {
          return graph.node(node);
        });

      if (this.isDisabled) {
        var margins = $scope.getGraphMargins(this.plugins);
        var marginLeft = margins.left;
      }

      this.plugins.forEach(function(plugin) {
        plugin.icon = MyPlumbFactory.getIcon(plugin.name);
        plugin.style = plugin.style ||
        ( this.isDisabled? MyPlumbFactory.generateStyles(plugin.id, nodes, 0, marginLeft): '');
        drawNode.call(this, plugin.id, plugin.type);
      }.bind(this));

      drawConnections.call(this);

      MyPlumbService.setConnections(this.instance.getConnections());

      mapSchemas.call(this);

      $timeout(this.instance.repaintEverything);
    };

    function drawNode(id, type) {
      var sourceSettings = MyPlumbFactory.getSettings().source,
          sinkSettings = MyPlumbFactory.getSettings().sink;

      switch(type) {
        case 'source':
          this.instance.addEndpoint(id, sourceSettings, {uuid: id});
          break;
        case 'sink':
          this.instance.addEndpoint(id, sinkSettings, {uuid: id});
          break;
        case 'transform':
          // Need to id each end point so that it can be used later to make connections.
          this.instance.addEndpoint(id, sourceSettings, {uuid: 'Left' + id});
          this.instance.addEndpoint(id, sinkSettings, {uuid: 'Right' + id});
          break;
      }
      if (!this.isDisabled) {
        this.instance.draggable(id, {
          drag: function (evt) { return dragnode.call(this, evt); }.bind(this)
        });
      }
      // Super hacky way of restricting user to not scroll beyond certain top and left.
      function dragnode(e) {
        var returnResult = true;
        if (e.pos[1] < 0) {
          e.e.preventDefault();
          e.el.style.top = "10px";
          returnResult = false;
        }
        if (e.pos[0] < 0) {
          e.e.preventDefault();
          e.el.style.left = "10px";
          returnResult = false;
        }
        MyPlumbService.nodes[e.el.id].style = {top: e.el.style.top, left: e.el.style.left};
        return returnResult;
      }
    }

    function drawConnections() {
      var i;
      var prev, curr, next;

      var connections = MyPlumbService.connections;
      for(i=0; i<connections.length; i++) {
        if (connections[i].source.indexOf('transform') !== -1) {
          curr = 'Left' + connections[i].source;
        } else {
          curr = connections[i].source;
        }
        if (connections[i].target.indexOf('transform') !== -1) {
          next = 'Right' + connections[i].target;
        } else {
          next = connections[i].target;
        }

        var connObj = {
          uuids: [curr, next]
        };

        if (this.isDisabled) {
          connObj.detachable = false;
        }

        this.instance.connect(connObj);
      }
    }

    function mapSchemas() {
      var connections = MyPlumbService.connections;
      var nodes = MyPlumbService.nodes;
      connections.forEach(function(connection) {
        var sourceNode = nodes[connection.source];
        var targetNode = nodes[connection.target];
        var sourceOutputSchema = myHelpers.objectQuery(sourceNode, 'properties', 'schema');
        var targetOuputSchema = myHelpers.objectQuery(targetNode, 'properties', 'schema');
        if (sourceOutputSchema) {
          sourceNode.outputSchema = sourceOutputSchema;
        }
        if (targetOuputSchema) {
          targetNode.outputSchema = targetOuputSchema;
        } else {
          targetNode.outputSchema = sourceNode.outputSchema;
        }
      });
    }

    MyPlumbService.registerCallBack(this.addPlugin.bind(this));

    $scope.$on('$destroy', function() {
      this.instance.reset();
      MyPlumbService.resetToDefaults();
    }.bind(this));

    jsPlumb.ready(function() {
      jsPlumb.setContainer('plumb-container');
      this.instance = jsPlumb.getInstance();

      angular.element($window).on('resize', function() {
        this.instance.repaintEverything();
      }.bind(this));

      this.instance.importDefaults(MyPlumbFactory.getSettings().default);

      // Need to move this to the controller that is using this directive.
      this.instance.bind('connection', function () {
        // Whenever there is a change in the connection just copy the entire array
        // We never know if a connection was altered or removed. We don't want to 'Sync'
        // between jsPlumb's internal connection array and ours (pointless)
        MyPlumbService.setConnections(this.instance.getConnections());
      }.bind(this));

      if (this.plugins.length > 0) {
        $timeout(this.drawGraph.bind(this));
      }
    }.bind(this));

    $scope.$watch('reloaddag', function (value) {
      if (value) {
        this.instance.reset();
        this.instance = jsPlumb.getInstance();
        this.instance.importDefaults(MyPlumbFactory.getSettings().default);
        this.plugins = $scope.config;
        $timeout(this.drawGraph.bind(this));
        $scope.reloaddag = false;
      }
    }.bind(this));

  });
<|endoftext|>


<commit_before>/* eslint-disable react/prop-types */
import { Button } from 'react-bootstrap'
import { connect } from 'react-redux'
import { FormattedMessage } from 'react-intl'
import coreUtils from '@opentripplanner/core-utils'
import React from 'react'
import styled, { css } from 'styled-components'

import * as uiActions from '../../actions/ui'
import {
  getActiveItineraries,
  getActiveSearch,
  getResponsesWithErrors
} from '../../util/state'
import Icon from '../util/icon'
import Map from '../map/map'
import NarrativeItineraries from '../narrative/narrative-itineraries'

import MobileContainer from './container'
import ResultsError from './results-error'
import ResultsHeader from './results-header'

const StyledMobileContainer = styled(MobileContainer)`
  .options > .header {
    margin: 10px;
  }

  &.otp.mobile .mobile-narrative-container {
    bottom: 0;
    left: 0;
    overflow-y: auto;
    padding: 0;
    position: fixed;
    right: 0;
  }
`

const ExpandMapButton = styled(Button)`
  bottom: 10px;
  left: 10px;
  position: absolute;
  z-index: 999999;
`

const NARRATIVE_SPLIT_TOP_PERCENT = 45

// Styles for the results map also include prop-independent styles copied from mobile.css.
const ResultsMap = styled.div`
  bottom: ${(props) =>
    props.expanded ? '0' : `${100 - NARRATIVE_SPLIT_TOP_PERCENT}%`};
  display: ${(props) => (props.visible ? 'inherit' : 'none')};
  left: 0;
  position: fixed;
  right: 0;
  top: 100px;
`

const narrativeCss = css`
  top: ${(props) =>
    props.visible
      ? props.expanded
        ? '100px'
        : `${NARRATIVE_SPLIT_TOP_PERCENT}%`
      : '100%'};
  transition: top 300ms;
`

const StyledResultsError = styled(ResultsError)`
  display: ${(props) => (props.visible ? 'inherit' : 'none')};
  ${narrativeCss}
`

const NarrativeContainer = styled.div`
  ${narrativeCss}
`

const { ItineraryView } = uiActions

/**
 * This component renders the mobile view of itinerary results from batch routing,
 * and features a split view between the map and itinerary results or narratives.
 */
const BatchMobileResultsScreen = ({
  errors,
  itineraries,
  itineraryView,
  toggleBatchResultsMap
}) => {
  const hasErrorsAndNoResult = itineraries.length === 0 && errors.length > 0
  const mapExpanded =
    itineraryView === ItineraryView.LEG_HIDDEN ||
    itineraryView === ItineraryView.LIST_HIDDEN
  const itineraryExpanded = itineraryView === ItineraryView.FULL

  return (
    <StyledMobileContainer>
      <ResultsHeader />
      <ResultsMap expanded={mapExpanded} visible={!itineraryExpanded}>
        <Map />
        <ExpandMapButton bsSize="small" onClick={toggleBatchResultsMap}>
          <Icon name={mapExpanded ? 'list-ul' : 'arrows-alt'} withSpace />
          {mapExpanded ? (
            <FormattedMessage id="components.BatchResultsScreen.showResults" />
          ) : (
            <FormattedMessage id="components.BatchResultsScreen.expandMap" />
          )}
        </ExpandMapButton>
      </ResultsMap>
      {hasErrorsAndNoResult ? (
        <StyledResultsError
          error={errors[0]}
          expanded={itineraryExpanded}
          visible={!mapExpanded}
        />
      ) : (
        <NarrativeContainer
          className="mobile-narrative-container"
          expanded={itineraryExpanded}
          visible={!mapExpanded}
        >
          <NarrativeItineraries />
        </NarrativeContainer>
      )}
    </StyledMobileContainer>
  )
}

// connect to the redux store

const mapStateToProps = (state, ownProps) => {
  const activeSearch = getActiveSearch(state)
  const urlParams = coreUtils.query.getUrlParams()
  return {
    activeLeg: activeSearch ? activeSearch.activeLeg : null,
    errors: getResponsesWithErrors(state),
    itineraries: getActiveItineraries(state),
    itineraryView: urlParams.ui_itineraryView || ItineraryView.LIST
  }
}

const mapDispatchToProps = {
  toggleBatchResultsMap: uiActions.toggleBatchResultsMap
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BatchMobileResultsScreen)
<commit_msg>refactor(batch-results-screen): remove fa icon<commit_after>/* eslint-disable react/prop-types */
import { Button } from 'react-bootstrap'
import { connect } from 'react-redux'
import { FormattedMessage } from 'react-intl'
import coreUtils from '@opentripplanner/core-utils'
import React from 'react'
import styled, { css } from 'styled-components'

import * as uiActions from '../../actions/ui'
import { ArrowsAlt, ListUl } from '@styled-icons/fa-solid'
import {
  getActiveItineraries,
  getActiveSearch,
  getResponsesWithErrors
} from '../../util/state'
import Icon from '../util/icon'
import Map from '../map/map'
import NarrativeItineraries from '../narrative/narrative-itineraries'

import MobileContainer from './container'
import ResultsError from './results-error'
import ResultsHeader from './results-header'
import StyledIconWrapper from '../util/styledIcon'

const StyledMobileContainer = styled(MobileContainer)`
  .options > .header {
    margin: 10px;
  }

  &.otp.mobile .mobile-narrative-container {
    bottom: 0;
    left: 0;
    overflow-y: auto;
    padding: 0;
    position: fixed;
    right: 0;
  }
`

const ExpandMapButton = styled(Button)`
  bottom: 10px;
  left: 10px;
  position: absolute;
  z-index: 999999;
`

const NARRATIVE_SPLIT_TOP_PERCENT = 45

// Styles for the results map also include prop-independent styles copied from mobile.css.
const ResultsMap = styled.div`
  bottom: ${(props) =>
    props.expanded ? '0' : `${100 - NARRATIVE_SPLIT_TOP_PERCENT}%`};
  display: ${(props) => (props.visible ? 'inherit' : 'none')};
  left: 0;
  position: fixed;
  right: 0;
  top: 100px;
`

const narrativeCss = css`
  top: ${(props) =>
    props.visible
      ? props.expanded
        ? '100px'
        : `${NARRATIVE_SPLIT_TOP_PERCENT}%`
      : '100%'};
  transition: top 300ms;
`

const StyledResultsError = styled(ResultsError)`
  display: ${(props) => (props.visible ? 'inherit' : 'none')};
  ${narrativeCss}
`

const NarrativeContainer = styled.div`
  ${narrativeCss}
`

const { ItineraryView } = uiActions

/**
 * This component renders the mobile view of itinerary results from batch routing,
 * and features a split view between the map and itinerary results or narratives.
 */
const BatchMobileResultsScreen = ({
  errors,
  itineraries,
  itineraryView,
  toggleBatchResultsMap
}) => {
  const hasErrorsAndNoResult = itineraries.length === 0 && errors.length > 0
  const mapExpanded =
    itineraryView === ItineraryView.LEG_HIDDEN ||
    itineraryView === ItineraryView.LIST_HIDDEN
  const itineraryExpanded = itineraryView === ItineraryView.FULL

  return (
    <StyledMobileContainer>
      <ResultsHeader />
      <ResultsMap expanded={mapExpanded} visible={!itineraryExpanded}>
        <Map />
        <ExpandMapButton bsSize="small" onClick={toggleBatchResultsMap}>
          <StyledIconWrapper spaceRight>
            {mapExpanded ? <ListUl /> : <ArrowsAlt />}
          </StyledIconWrapper>
          {mapExpanded ? (
            <FormattedMessage id="components.BatchResultsScreen.showResults" />
          ) : (
            <FormattedMessage id="components.BatchResultsScreen.expandMap" />
          )}
        </ExpandMapButton>
      </ResultsMap>
      {hasErrorsAndNoResult ? (
        <StyledResultsError
          error={errors[0]}
          expanded={itineraryExpanded}
          visible={!mapExpanded}
        />
      ) : (
        <NarrativeContainer
          className="mobile-narrative-container"
          expanded={itineraryExpanded}
          visible={!mapExpanded}
        >
          <NarrativeItineraries />
        </NarrativeContainer>
      )}
    </StyledMobileContainer>
  )
}

// connect to the redux store

const mapStateToProps = (state, ownProps) => {
  const activeSearch = getActiveSearch(state)
  const urlParams = coreUtils.query.getUrlParams()
  return {
    activeLeg: activeSearch ? activeSearch.activeLeg : null,
    errors: getResponsesWithErrors(state),
    itineraries: getActiveItineraries(state),
    itineraryView: urlParams.ui_itineraryView || ItineraryView.LIST
  }
}

const mapDispatchToProps = {
  toggleBatchResultsMap: uiActions.toggleBatchResultsMap
}

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


<commit_before>
// Copyright 2011 Splunk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

exports.setup = function(http) {
    var splunkjs    = require('../index');

    splunkjs.Logger.setLevel("ALL");
    return {

        "HTTP GET Tests": {
            setUp: function(done) {
                this.http = http;
                done();
            },

            "Callback#abort simple": function(test) {
                var req = this.http.get("https://httpbin.org/get", {}, {}, 0, function(err, res) {
                    test.ok(err);
                    test.strictEqual(err.error, "abort");
                    test.done();
                });

                req.abort();
            },

            "Callback#abort delay": function(test) {
                var req = this.http.get("https://www.httpbin.org/delay/20", {}, {}, 0, function(err, res) {
                    test.ok(err);
                    test.strictEqual(err.error, "abort");
                    test.done();
                });

                splunkjs.Async.sleep(1000, function() {
                    req.abort();
                });
            },

            "Callback#no args": function(test) {
                this.http.get("http://www.httpbin.org/get", [], {}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://www.httpbin.org/get");
                    test.done();
                });
            },

            "Callback#success success+error": function(test) {
                this.http.get("http://www.httpbin.org/get", [], {}, 0, function(err, res) {
                    test.ok(!err);
                    test.strictEqual(res.data.url, "http://www.httpbin.org/get");
                    test.done();
                });
            },

            "Callback#error all": function(test) {
                this.http.get("http://www.httpbin.org/status/404", [], {}, 0, function(err, res) {
                    test.strictEqual(err.status, 404);
                    test.done();
                });
            },

            "Callback#args": function(test) {
                this.http.get("http://www.httpbin.org/get", [], { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var args = res.data.args;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.strictEqual(args.c, "1");
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://www.httpbin.org/get?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            },

            "Callback#args with objects": function(test) {
                this.http.get(
                    "http://www.httpbin.org/get", [],
                    {a: 1, b: {c: "ab", d: 12}}, 0,
                    function(err, res) {
                        var args = res.data.args;
                        test.strictEqual(args.a, "1");
                        test.strictEqual(args.b, "ab");
                        test.strictEqual(
                            res.data.url,
                            "http://www.httpbin.org/get?a=1&b=ab&b=12"
                        );
                        test.done();
                    }
                );
            },

            "Callback#headers": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.get("http://www.httpbin.org/get", {"X-Test1": 1, "X-Test2": "a/b/c"}, {}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }

                    test.strictEqual(res.data.url, "http://www.httpbin.org/get");
                    test.done();
                });
            },

            "Callback#all": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.get("http://www.httpbin.org/get", { "X-Test1": 1, "X-Test2": "a/b/c" }, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }

                    var args = res.data.args;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.strictEqual(args.c, "1");
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://www.httpbin.org/get?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            }
        },

        "HTTP POST Tests": {
            setUp: function(done) {
                this.http = http;
                done();
            },

            "Callback#no args": function(test) {
                this.http.post("http://www.httpbin.org/post", {}, {}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://www.httpbin.org/post");
                    test.done();
                });
            },

            "Callback#success success+error": function(test) {
                this.http.post("http://www.httpbin.org/post", {}, {}, 0, function(err, res) {
                    test.ok(!err);
                    test.strictEqual(res.data.url, "http://www.httpbin.org/post");
                    test.done();
                });
            },

            "Callback#error all": function(test) {
                this.http.post("http://www.httpbin.org/status/405", {}, {}, 0, function(err, res) {
                    test.strictEqual(err.status, 405);
                    test.done();
                });
            },

            "Callback#args": function(test) {
                this.http.post("http://www.httpbin.org/post", {}, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var args = res.data.form;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.deepEqual(args.c, ["1", "2", "3"]);
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://www.httpbin.org/post");
                    test.done();
                });
            },

            "Callback#headers": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.post("http://www.httpbin.org/post", { "X-Test1": 1, "X-Test2": "a/b/c" }, {}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }
                    test.strictEqual(res.data.url, "http://www.httpbin.org/post");
                    test.done();
                });
            },

            "Callback#all": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.post("http://www.httpbin.org/post", { "X-Test1": 1, "X-Test2": "a/b/c" }, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }

                    var args = res.data.form;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.deepEqual(args.c, ["1", "2", "3"]);
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://www.httpbin.org/post");
                    test.done();
                });
            }
        },

        "HTTP DELETE Tests": {
            setUp: function(done) {
                this.http = http;
                done();
            },

            "Callback#no args": function(test) {
                this.http.del("http://www.httpbin.org/delete", [], {}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://www.httpbin.org/delete");
                    test.done();
                });
            },

            "Callback#success success+error": function(test) {
                this.http.del("http://www.httpbin.org/delete", [], {}, 0, function(err, res) {
                    test.ok(!err);
                    test.strictEqual(res.data.url, "http://www.httpbin.org/delete");
                    test.done();
                });
            },

            "Callback#error all": function(test) {
                this.http.del("http://www.httpbin.org/status/405", [], {}, 0, function(err, res) {
                    test.strictEqual(err.status, 405);
                    test.done();
                });
            },

            "Callback#args": function(test) {
                this.http.del("http://www.httpbin.org/delete", [], { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://www.httpbin.org/delete?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            },

            "Callback#headers": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.del("http://www.httpbin.org/delete", { "X-Test1": 1, "X-Test2": "a/b/c" }, {}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }
                    test.strictEqual(res.data.url, "http://www.httpbin.org/delete");
                    test.done();
                });
            },

            "Callback#all": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.del("http://www.httpbin.org/delete", { "X-Test1": 1, "X-Test2": "a/b/c" }, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }
                    test.strictEqual(res.data.url, "http://www.httpbin.org/delete?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            },

            "Default arguments to Http work": function(test) {
                var NodeHttp = splunkjs.NodeHttp;
                var h = new NodeHttp();
                test.ok(h);
                test.done();
            },

            "Methods of Http base class that must be overrided": function(test) {
                var h = new splunkjs.Http();
                test.throws(function() { h.makeRequest("asdf", null, null); });
                test.throws(function() { h.parseJson("{}"); });
                test.done();
            }
        }
    };
};

if (module === require.main) {
    var splunkjs    = require('../index');
    var NodeHttp    = splunkjs.NodeHttp;
    var test        = require('../contrib/nodeunit/test_reporter');

    var http = new NodeHttp();

    var suite = exports.setup(http);
    test.run([{"Tests": suite}]);
}
<commit_msg>Continued fix for httpbin.org URLs<commit_after>
// Copyright 2011 Splunk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

exports.setup = function(http) {
    var splunkjs    = require('../index');

    splunkjs.Logger.setLevel("ALL");
    return {

        "HTTP GET Tests": {
            setUp: function(done) {
                this.http = http;
                done();
            },

            "Callback#abort simple": function(test) {
                var req = this.http.get("https://httpbin.org/get", {}, {}, 0, function(err, res) {
                    test.ok(err);
                    test.strictEqual(err.error, "abort");
                    test.done();
                });

                req.abort();
            },

            "Callback#abort delay": function(test) {
                var req = this.http.get("https://httpbin.org/delay/20", {}, {}, 0, function(err, res) {
                    test.ok(err);
                    test.strictEqual(err.error, "abort");
                    test.done();
                });

                splunkjs.Async.sleep(1000, function() {
                    req.abort();
                });
            },

            "Callback#no args": function(test) {
                this.http.get("http://httpbin.org/get", [], {}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://httpbin.org/get");
                    test.done();
                });
            },

            "Callback#success success+error": function(test) {
                this.http.get("http://httpbin.org/get", [], {}, 0, function(err, res) {
                    test.ok(!err);
                    test.strictEqual(res.data.url, "http://httpbin.org/get");
                    test.done();
                });
            },

            "Callback#error all": function(test) {
                this.http.get("http://httpbin.org/status/404", [], {}, 0, function(err, res) {
                    test.strictEqual(err.status, 404);
                    test.done();
                });
            },

            "Callback#args": function(test) {
                this.http.get("http://httpbin.org/get", [], { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var args = res.data.args;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.strictEqual(args.c, "1");
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://httpbin.org/get?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            },

            "Callback#args with objects": function(test) {
                this.http.get(
                    "http://httpbin.org/get", [],
                    {a: 1, b: {c: "ab", d: 12}}, 0,
                    function(err, res) {
                        var args = res.data.args;
                        test.strictEqual(args.a, "1");
                        test.strictEqual(args.b, "ab");
                        test.strictEqual(
                            res.data.url,
                            "http://httpbin.org/get?a=1&b=ab&b=12"
                        );
                        test.done();
                    }
                );
            },

            "Callback#headers": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.get("http://httpbin.org/get", {"X-Test1": 1, "X-Test2": "a/b/c"}, {}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }

                    test.strictEqual(res.data.url, "http://httpbin.org/get");
                    test.done();
                });
            },

            "Callback#all": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.get("http://httpbin.org/get", { "X-Test1": 1, "X-Test2": "a/b/c" }, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }

                    var args = res.data.args;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.strictEqual(args.c, "1");
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://httpbin.org/get?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            }
        },

        "HTTP POST Tests": {
            setUp: function(done) {
                this.http = http;
                done();
            },

            "Callback#no args": function(test) {
                this.http.post("http://httpbin.org/post", {}, {}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://httpbin.org/post");
                    test.done();
                });
            },

            "Callback#success success+error": function(test) {
                this.http.post("http://httpbin.org/post", {}, {}, 0, function(err, res) {
                    test.ok(!err);
                    test.strictEqual(res.data.url, "http://httpbin.org/post");
                    test.done();
                });
            },

            "Callback#error all": function(test) {
                this.http.post("http://httpbin.org/status/405", {}, {}, 0, function(err, res) {
                    test.strictEqual(err.status, 405);
                    test.done();
                });
            },

            "Callback#args": function(test) {
                this.http.post("http://httpbin.org/post", {}, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var args = res.data.form;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.deepEqual(args.c, ["1", "2", "3"]);
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://httpbin.org/post");
                    test.done();
                });
            },

            "Callback#headers": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.post("http://httpbin.org/post", { "X-Test1": 1, "X-Test2": "a/b/c" }, {}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }
                    test.strictEqual(res.data.url, "http://httpbin.org/post");
                    test.done();
                });
            },

            "Callback#all": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.post("http://httpbin.org/post", { "X-Test1": 1, "X-Test2": "a/b/c" }, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }

                    var args = res.data.form;
                    test.strictEqual(args.a, "1");
                    test.strictEqual(args.b, "2");
                    test.deepEqual(args.c, ["1", "2", "3"]);
                    test.strictEqual(args.d, "a/b");
                    test.strictEqual(res.data.url, "http://httpbin.org/post");
                    test.done();
                });
            }
        },

        "HTTP DELETE Tests": {
            setUp: function(done) {
                this.http = http;
                done();
            },

            "Callback#no args": function(test) {
                this.http.del("http://httpbin.org/delete", [], {}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://httpbin.org/delete");
                    test.done();
                });
            },

            "Callback#success success+error": function(test) {
                this.http.del("http://httpbin.org/delete", [], {}, 0, function(err, res) {
                    test.ok(!err);
                    test.strictEqual(res.data.url, "http://httpbin.org/delete");
                    test.done();
                });
            },

            "Callback#error all": function(test) {
                this.http.del("http://httpbin.org/status/405", [], {}, 0, function(err, res) {
                    test.strictEqual(err.status, 405);
                    test.done();
                });
            },

            "Callback#args": function(test) {
                this.http.del("http://httpbin.org/delete", [], { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    test.strictEqual(res.data.url, "http://httpbin.org/delete?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            },

            "Callback#headers": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.del("http://httpbin.org/delete", { "X-Test1": 1, "X-Test2": "a/b/c" }, {}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }
                    test.strictEqual(res.data.url, "http://httpbin.org/delete");
                    test.done();
                });
            },

            "Callback#all": function(test) {
                var headers = { "X-Test1": 1, "X-Test2": "a/b/c" };

                this.http.del("http://httpbin.org/delete", { "X-Test1": 1, "X-Test2": "a/b/c" }, { a: 1, b: 2, c: [1,2,3], d: "a/b"}, 0, function(err, res) {
                    var returnedHeaders = res.data.headers;
                    for(var headerName in headers) {
                        if (headers.hasOwnProperty(headerName)) {
                            // We have to make the header values into strings
                            test.strictEqual(headers[headerName] + "", returnedHeaders[headerName]);
                        }
                    }
                    test.strictEqual(res.data.url, "http://httpbin.org/delete?a=1&b=2&c=1&c=2&c=3&d=a%2Fb");
                    test.done();
                });
            },

            "Default arguments to Http work": function(test) {
                var NodeHttp = splunkjs.NodeHttp;
                var h = new NodeHttp();
                test.ok(h);
                test.done();
            },

            "Methods of Http base class that must be overrided": function(test) {
                var h = new splunkjs.Http();
                test.throws(function() { h.makeRequest("asdf", null, null); });
                test.throws(function() { h.parseJson("{}"); });
                test.done();
            }
        }
    };
};

if (module === require.main) {
    var splunkjs    = require('../index');
    var NodeHttp    = splunkjs.NodeHttp;
    var test        = require('../contrib/nodeunit/test_reporter');

    var http = new NodeHttp();

    var suite = exports.setup(http);
    test.run([{"Tests": suite}]);
}
<|endoftext|>


<commit_before>(function($) {

    jQuery.extend($.icescrum, {
                addToWidgetBar:function(id, callback) {
                    if ($.inArray(id,  $.icescrum.getWidgetsList()) == -1) {
                        jQuery.ajax({
                                type:'GET',
                                global:false,
                                url:this.o.urlOpenWidget + '/' + id,
                                success:function(data, textStatus) {
                                    if ($.inArray(id, $.icescrum.getWidgetsList()) == -1 && data) {
                                        $(data).appendTo($.icescrum.o.widgetContainer);
                                        $.icescrum.addToWidgetsList(id);
                                        if (callback) {
                                            callback();
                                        }
                                    }
                                },
                                error:function() {
                                    $.icescrum.removeFromWidgetsList(id);
                                }
                            });
                    }
                    return false;
                },

                widgetToWindow:function(obj, event) {
                    var opts = obj.data('opts');
                    $.icescrum.openWindow(obj.data('id'));
                    this.stopEvent(event);
                },

                closeWidget:function(obj, event) {
                    var opts = obj.data('opts');
                    obj.effect('blind', null, 'fast', function() { obj.remove(); });
                    this.removeFromWidgetsList(obj.data('id'));
                    if (opts && opts.onClose)
                        opts.onClose();
                    if (event)
                        this.stopEvent(event);
                },

                saveWidgetsList:function(widgetsList){
                    if ($.icescrum.product.id){
                        $.cookie('widgets-' + $.icescrum.product.id, widgetsList);
                    }else{
                        $.cookie('widgets-noproduct', widgetsList);
                    }
                },

                getWidgetsList:function(){
                    var list = $.icescrum.product.id ? $.cookie('widgets-' + $.icescrum.product.id) : $.cookie('widgets-noproduct');
                    return list ? list.split(',') : [];
                },

                removeFromWidgetsList:function(id){
                    var list = $.grep(this.getWidgetsList(), function(value) {
                        return value != id;
                    });
                    this.saveWidgetsList(list);
                },

                addToWidgetsList:function(id){
                    var list = this.getWidgetsList();
                    list.push(id);
                    this.saveWidgetsList(list);
                }
            });

    $.fn.isWidget = function(options) {
        var opts = $.extend({}, $.fn.isWidget.defaults, options);
        var obj = $(this);
        var widgetid = $(this).attr('id');
        var id = widgetid.substring(widgetid.lastIndexOf("-") + 1, widgetid.length);
        var iconWindow;

        obj.data('opts', opts);
        obj.data('widgetid', widgetid);
        obj.data('id', id);

        if (opts.windowable) {
            iconWindow = $("#" + widgetid + ' .widget-maxicon');
            iconWindow.parent().bind('click', function(event) {
                $.icescrum.widgetToWindow(obj, event)
            });
            iconWindow.parents('.resizable:first').bind('dblclick', function(event) {
                $.icescrum.widgetToWindow(obj, event)
            });
            obj.addClass('draggable-to-desktop');
        }

        if (opts.closeable) {
            $("#" + widgetid + ' .widget-close').bind('click', function(event) {
                $.icescrum.closeWidget(obj, event)
            });
        }

        if (opts.resizable) {

            var content = $("#widget-content-" + id, obj);
            var dif = obj.height() - content.height();
            var savedHeight = $.icescrum.product.id ? parseInt($.cookie('widget-'+id+$.icescrum.product.id)) : null;

            if ($('.box-blank', content).is(':visible')){
                content.height(opts.resizable.minHeight);
            }else{
                if (savedHeight && $(content.children()[0]).height() > savedHeight){
                    content.height(savedHeight);
                }else if (!savedHeight && $(content.children()[0]).height() > opts.resizable.defaultHeight){
                    content.height(opts.resizable.defaultHeight);
                }
            }
            opts.resizable.minHeight += dif;
            opts.resizable.zIndex = 990;
            opts.resizable.minWidth = obj.width();
            opts.resizable.maxWidth = obj.width();
            opts.resizable.start = function(event, ui){
                var height = $(content.children()[0]).height();
                obj.resizable('option','maxHeight',height >= opts.resizable.minHeight ? height + dif : opts.resizable.minHeight);
            };
            opts.resizable.resize = function(event, ui){
                content.height(ui.size.height - dif);
            };
            opts.resizable.stop = function(event, ui){
                $.cookie('widget-'+id+$.icescrum.product.id,ui.size.height - dif);
            };

            obj.resizable(opts.resizable);
        }
    };

})(jQuery);

$.fn.isWidget.defaults = {
    windowable:false,
    resizable:null,
    closeable:true,
    onClose:null
};<commit_msg>- avoide duplicate widgets - cookie by user / project<commit_after>(function($) {

    jQuery.extend($.icescrum, {
                addToWidgetBar:function(id, callback) {
                    if ($.inArray(id,  $.icescrum.getWidgetsList()) == -1) {
                        jQuery.ajax({
                                type:'GET',
                                global:false,
                                url:this.o.urlOpenWidget + '/' + id,
                                success:function(data, textStatus) {
                                    if ($.inArray(id, $.icescrum.getWidgetsList()) == -1 && data) {
                                        $(data).appendTo($.icescrum.o.widgetContainer);
                                        $.icescrum.addToWidgetsList(id);
                                        if (callback) {
                                            callback();
                                        }
                                    }
                                },
                                error:function() {
                                    $.icescrum.removeFromWidgetsList(id);
                                }
                            });
                    }
                    return false;
                },

                widgetToWindow:function(obj, event) {
                    var opts = obj.data('opts');
                    $.icescrum.openWindow(obj.data('id'));
                    this.stopEvent(event);
                },

                closeWidget:function(obj, event) {
                    var opts = obj.data('opts');
                    obj.effect('blind', null, 'fast', function() { obj.remove(); });
                    this.removeFromWidgetsList(obj.data('id'));
                    if (opts && opts.onClose)
                        opts.onClose();
                    if (event)
                        this.stopEvent(event);
                },

                saveWidgetsList:function(widgetsList){
                    widgetsList = $.makeArray($(widgetsList).filter(function(i,itm){
                        return i == $(widgetsList).index(itm);
                    }));
                    if ($.icescrum.product.id){
                        $.cookie('widgets-' + ($.icescrum.product.id ? $.icescrum.product.id : 'noproduct') + '-' +($.icescrum.user.id ? $.icescrum.user.id : 'anonymous') , widgetsList);
                    }
                },

                getWidgetsList:function(){
                    var list = $.icescrum.product.id ? $.cookie('widgets-' + $.icescrum.product.id) : $.cookie('widgets-noproduct');
                    return list ? list.split(',') : [];
                },

                removeFromWidgetsList:function(id){
                    var list = $.grep(this.getWidgetsList(), function(value) {
                        return value != id;
                    });
                    this.saveWidgetsList(list);
                },

                addToWidgetsList:function(id){
                    var list = this.getWidgetsList();
                    list.push(id);
                    this.saveWidgetsList(list);
                }
            });

    $.fn.isWidget = function(options) {
        var opts = $.extend({}, $.fn.isWidget.defaults, options);
        var obj = $(this);
        var widgetid = $(this).attr('id');
        var id = widgetid.substring(widgetid.lastIndexOf("-") + 1, widgetid.length);
        var iconWindow;

        obj.data('opts', opts);
        obj.data('widgetid', widgetid);
        obj.data('id', id);

        if (opts.windowable) {
            iconWindow = $("#" + widgetid + ' .widget-maxicon');
            iconWindow.parent().bind('click', function(event) {
                $.icescrum.widgetToWindow(obj, event)
            });
            iconWindow.parents('.resizable:first').bind('dblclick', function(event) {
                $.icescrum.widgetToWindow(obj, event)
            });
            obj.addClass('draggable-to-desktop');
        }

        if (opts.closeable) {
            $("#" + widgetid + ' .widget-close').bind('click', function(event) {
                $.icescrum.closeWidget(obj, event)
            });
        }

        if (opts.resizable) {

            var content = $("#widget-content-" + id, obj);
            var dif = obj.height() - content.height();
            var savedHeight = $.icescrum.product.id ? parseInt($.cookie('widget-'+id+$.icescrum.product.id)) : null;

            if ($('.box-blank', content).is(':visible')){
                content.height(opts.resizable.minHeight);
            }else{
                if (savedHeight && $(content.children()[0]).height() > savedHeight){
                    content.height(savedHeight);
                }else if (!savedHeight && $(content.children()[0]).height() > opts.resizable.defaultHeight){
                    content.height(opts.resizable.defaultHeight);
                }
            }
            opts.resizable.minHeight += dif;
            opts.resizable.zIndex = 990;
            opts.resizable.minWidth = obj.width();
            opts.resizable.maxWidth = obj.width();
            opts.resizable.start = function(event, ui){
                var height = $(content.children()[0]).height();
                obj.resizable('option','maxHeight',height >= opts.resizable.minHeight ? height + dif : opts.resizable.minHeight);
            };
            opts.resizable.resize = function(event, ui){
                content.height(ui.size.height - dif);
            };
            opts.resizable.stop = function(event, ui){
                $.cookie('widget-'+id+$.icescrum.product.id,ui.size.height - dif);
            };

            obj.resizable(opts.resizable);
        }
    };

})(jQuery);

$.fn.isWidget.defaults = {
    windowable:false,
    resizable:null,
    closeable:true,
    onClose:null
};<|endoftext|>


<commit_before>'use strict'
const path = require('path')
const {spawnSync} = require('child_process')
const {
  env: {
    STANDARDJS_EXECUTABLE,
    STANDARDJS_ARGV,
    SKIP_CODE_STYLE_CHECKING
  }
} = require('process')

const wdir = path.resolve(__dirname, '..')

test('JavaScript Code Style: StandardJS', () => {
  if (SKIP_CODE_STYLE_CHECKING === 'true') return

  const argv = STANDARDJS_ARGV
    ? JSON.parse(STANDARDJS_ARGV)
    : []

  expect(argv).toBeInstanceOf(Array)

  const {
    stdout,
    stderr,
    error,
    status
  } = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir})

  if (stdout === null) console.warn('standard.stdout is null')
  if (stderr === null) console.warn('standard.stderr is null')
  if (error) throw error
  if (status) throw new Error(stderr + '\n' + stdout)
})
<commit_msg>Warn about signal<commit_after>'use strict'
const path = require('path')
const {spawnSync} = require('child_process')
const {
  env: {
    STANDARDJS_EXECUTABLE,
    STANDARDJS_ARGV,
    SKIP_CODE_STYLE_CHECKING
  }
} = require('process')

const wdir = path.resolve(__dirname, '..')

test('JavaScript Code Style: StandardJS', () => {
  if (SKIP_CODE_STYLE_CHECKING === 'true') return

  const argv = STANDARDJS_ARGV
    ? JSON.parse(STANDARDJS_ARGV)
    : []

  expect(argv).toBeInstanceOf(Array)

  const {
    stdout,
    stderr,
    signal,
    error,
    status
  } = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir})

  if (stdout === null) console.warn('standard.stdout is null')
  if (stderr === null) console.warn('standard.stderr is null')
  if (signal) console.warn(`standard.signal is ${JSON.stringify(signal)}`)
  if (error) throw error
  if (status) throw new Error(stderr + '\n' + stdout)
})
<|endoftext|>


<commit_before>// Load dependencies
var amanda = require('../../../src/amanda.js');

var schema = {
  type: 'object',
  properties: {
    user: {
      type: 'object',
      properties: {
        name: {
          required: true
        },
        surname: {
          required: true
        }
      }
    }
  }
};

/**
 * Test #1
 */
exports['Test #1'] = function(test) {

  var data = {
    user: {
      name: 'František',
      surname: 'Hába'
    }
  };

  amanda.validate(data, schema, function(error) {

    test.equal(error, undefined);

  });

  test.done();

};

exports['Test #2'] = function(test) {

  var data = {};

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};

exports['Test #3'] = function(test) {

  var data = {
    user: 123
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;
    delete error[1].message;

    test.deepEqual(error[0], {
      property: 'user',
      propertyValue: 123,
      validator: 'type',
      validatorValue: 'object'
    });

    test.deepEqual(error[1], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 2);

  });

  test.done();

};

exports['Test #4'] = function(test) {

  var data = {
    user: {}
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};

exports['Test #5'] = function(test) {

  var data = {
    user: {
      name: 'František'
    }
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.surname',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};

exports['Test #6'] = function(test) {

  var data = {
    user: {
      surname: 'Hába'
    }
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};<commit_msg>Update the path to Amanda in the ‘objectsSingleError.js’ file<commit_after>// Load dependencies
var amanda = require('../../../dist/latest.js');

var schema = {
  type: 'object',
  properties: {
    user: {
      type: 'object',
      properties: {
        name: {
          required: true
        },
        surname: {
          required: true
        }
      }
    }
  }
};

/**
 * Test #1
 */
exports['Test #1'] = function(test) {

  var data = {
    user: {
      name: 'František',
      surname: 'Hába'
    }
  };

  amanda.validate(data, schema, function(error) {

    test.equal(error, undefined);

  });

  test.done();

};

exports['Test #2'] = function(test) {

  var data = {};

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};

exports['Test #3'] = function(test) {

  var data = {
    user: 123
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;
    delete error[1].message;

    test.deepEqual(error[0], {
      property: 'user',
      propertyValue: 123,
      validator: 'type',
      validatorValue: 'object'
    });

    test.deepEqual(error[1], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 2);

  });

  test.done();

};

exports['Test #4'] = function(test) {

  var data = {
    user: {}
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};

exports['Test #5'] = function(test) {

  var data = {
    user: {
      name: 'František'
    }
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.surname',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};

exports['Test #6'] = function(test) {

  var data = {
    user: {
      surname: 'Hába'
    }
  };

  amanda.validate(data, schema, function(error) {

    delete error[0].message;

    test.deepEqual(error[0], {
      property: 'user.name',
      propertyValue: undefined,
      validator: 'required',
      validatorValue: true
    });

    test.equal(error.length, 1);

  });

  test.done();

};<|endoftext|>


<commit_before>/*
 * EJS Embedded JavaScript templates
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

'use strict';

var fs = require('fs')
  , utils = require('./utils')
  , jsCache = {}
  , _VERSION_STRING = require('../package.json').version
  , _DEFAULT_DELIMITER = '%'
  , _DEFAULT_LOCALS_NAME = 'locals'
  , _REGEX_STRING = '(<%%|<%=|<%-|<%#|<%|%>|-%>)'
  , _OPTS = [ 'cache', 'filename', 'delimiter', 'scope', 'context'
            , 'debug', 'compileDebug', 'client', '_with'
            ]
  , _TRAILING_SEMCOL = /;\s*$/;

exports.localsName = _DEFAULT_LOCALS_NAME;

exports.resolveInclude = function(name, filename) {
  var path = require('path')
    , dirname = path.dirname
    , extname = path.extname
    , resolve = path.resolve
    , includePath = resolve(dirname(filename), name)
    , ext = extname(name);
  if (!ext) {
    includePath += '.ejs';
  }
  return includePath;
}

// Returns a possibly cached template function, set by options.cache.
// `template` is the string of EJS to compile.
// If template is undefined then the file specified in options.filename is
// read.
function handleCache(options, template) {
  var fn
    , path = options.filename
    , hasTemplate = template !== undefined;

  if (options.cache) {
    if (!path) {
      throw new Error('cache option requires a filename');
    }
    fn = jsCache[path];
    if (fn) {
      return fn;
    }
    if (!hasTemplate) {
      template = fs.readFileSync(path).toString();
    }
  }
  else if (!hasTemplate) {
    if (!path) {
      throw new Error('Internal EJS error: no file name or template '
                    + 'provided');
    }
    template = fs.readFileSync(path).toString();
  }
  fn = exports.compile(template.trim(), options);
  if (options.cache) {
    jsCache[path] = fn;
  }
  return fn;
}

function includeFile(path, options) {
  var opts = utils.shallowCopy({}, options);
  if (!opts.filename) {
    throw new Error('`include` requires the \'filename\' option.');
  }
  opts.filename = exports.resolveInclude(path, opts.filename);
  return handleCache(opts);
}

function includeSource(path, options) {
  var opts = utils.shallowCopy({}, options)
    , includePath
    , template;
  if (!opts.filename) {
    throw new Error('`include` requires the \'filename\' option.');
  }
  includePath = exports.resolveInclude(path, opts.filename);
  template = fs.readFileSync(includePath).toString().trim();

  opts.filename = includePath;
  var templ = new Template(template, opts);
  templ.generateSource();
  return templ.source;
}

function rethrow(err, str, filename, lineno){
  var lines = str.split('\n')
    , start = Math.max(lineno - 3, 0)
    , end = Math.min(lines.length, lineno + 3);

  // Error context
  var context = lines.slice(start, end).map(function (line, i){
    var curr = i + start + 1;
    return (curr == lineno ? ' >> ' : '    ')
      + curr
      + '| '
      + line;
  }).join('\n');

  // Alter exception message
  err.path = filename;
  err.message = (filename || 'ejs') + ':'
    + lineno + '\n'
    + context + '\n\n'
    + err.message;

  throw err;
}

function cpOptsInData(data, opts) {
  _OPTS.forEach(function (p) {
    if (typeof data[p] != 'undefined') {
      opts[p] = data[p];
    }
  });
}

function compile(template, opts) {
  var templ;

  // v1 compat
  // 'scope' is 'context'
  // FIXME: Remove this in a future version
  if (opts && opts.scope) {
    if (!opts.context) {
      opts.context = opts.scope;
    }
    delete opts.scope;
  }
  templ = new Template(template, opts);
  return templ.compile();
}
exports.compile = compile;

// template, [data], [opts]
// Have to include an empty data object if you want opts and no data
exports.render = function (template, data, opts) {
  data = data || {};
  opts = opts || {};
  var fn;

  // No options object -- if there are optiony names
  // in the data, copy them to options
  if (arguments.length == 2) {
    cpOptsInData(data, opts);
  }

  fn = handleCache(opts, template);
  return fn.call(opts.context, data);
};

// path, [data], [opts], cb
// Have to include an empty data object if you want opts and no data
exports.renderFile = function () {
  var args = Array.prototype.slice.call(arguments)
    , path = args.shift()
    , cb = args.pop()
    , data = args.shift() || {}
    , opts = args.pop() || {}
    , result
    , failed = false;

  // No options object -- if there are optiony names
  // in the data, copy them to options
  if (arguments.length == 3) {
    cpOptsInData(data, opts);
  }
  opts.filename = path;

  try {
    result = handleCache(opts)(data);
  }
  catch(err) {
    return process.nextTick(function () {
      cb(err);
    });
  }
  process.nextTick(function () {
    cb(null, result);
  });
};

exports.clearCache = function () {
  jsCache = {};
};

function Template(text, opts) {
  opts = opts || {};
  var options = {};
  this.templateText = text;
  this.mode = null;
  this.truncate = false;
  this.currentLine = 1;
  this.source = '';
  options.client = opts.client || false;
  options.escapeFunction = opts.escape || utils.escapeXML;
  options.compileDebug = opts.compileDebug !== false;
  options.debug = !!opts.debug;
  options.filename = opts.filename;
  options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
  options._with = typeof opts._with != 'undefined' ? opts._with : true;
  options.cache = opts.cache || false;
  this.opts = options;

  this.regex = this.createRegex();
}

Template.modes = {
    EVAL: 'eval'
  , ESCAPED: 'escaped'
  , RAW: 'raw'
  , COMMENT: 'comment'
  , LITERAL: 'literal'
};

Template.prototype = new function () {
  this.createRegex = function () {
    var str = _REGEX_STRING
      , delim = utils.escapeRegExpChars(this.opts.delimiter);
    str = str.replace(/%/g, delim);
    return new RegExp(str);
  };

  this.compile = function () {
    var src
      , fn
      , opts = this.opts
      , escape = opts.escapeFunction;

    if (!this.source) {
      this.generateSource();
      var prepended = '  var __output = [];' + '\n';
      if (opts._with !== false) {
        prepended +=  '  with (' + exports.localsName + ' || {}) {' + '\n';
      }
      this.source  = prepended + this.source;
      if (opts._with !== false) {
        this.source += '  }' + '\n';
      }
      this.source += '  return __output.join("").trim();' + '\n';
    }

    if (opts.compileDebug) {
      src = 'var __line = 1' + '\n'
          + '  , __lines = ' + JSON.stringify(this.templateText) + '\n'
          + '  , __filename = ' + (opts.filename ?
                JSON.stringify(opts.filename) : 'undefined') + ';' + '\n'
          + 'try {' + '\n'
          + this.source
          + '} catch (e) {' + '\n'
          + '  rethrow(e, __lines, __filename, __line);' + '\n'
          + '}' + '\n';
    }
    else {
      src = this.source;
    }

    if (opts.debug) {
      console.log(src);
    }

    if (opts.client) {
      if (escape !== utils.escapeXML) {
        src = 'escape = escape || ' + escape.toString() + ';' + '\n' + src;
      }
      else {
        src = utils.escapeFuncStr
            + 'escape = escape || ' + escape.toString() + ';' + '\n' + src;
      }
      if (opts.compileDebug) {
        src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
      }
    }

    try {
      fn = new Function(exports.localsName + ', escape, include, rethrow', src);
    }
    catch(e) {
      if (e instanceof SyntaxError) {
        if (opts.filename) {
          e.message += ' in ' + opts.filename;
        }
        e.message += ' while compiling ejs';
      }
      throw e;
    }

    if (opts.client) {
      return fn;
    }

    // Return a callable function which will execute the function
    // created by the source-code, with the passed data as locals
    return function (data) {
      var include = function (path, includeData) {
        var d = utils.shallowCopy({}, data);
        if (includeData) {
          d = utils.shallowCopy(d, includeData);
        }
        return includeFile(path, opts)(d);
      };
      return fn(data || {}, escape, include, rethrow);
    };

  };

  this.generateSource = function () {
    var self = this
      , matches = this.parseTemplateText()
      , d = this.opts.delimiter;

    if (matches && matches.length) {
      matches.forEach(function (line, index) {
        var closing
          , include
          , includeOpts
          , includeSrc;
        // If this is an opening tag, check for closing tags
        // FIXME: May end up with some false positives here
        // Better to store modes as k/v with '<' + delimiter as key
        // Then this can simply check against the map
        if ( line.indexOf('<' + d) === 0        // If it is a tag
          && line.indexOf('<' + d + d) !== 0) { // and is not escaped
          closing = matches[index + 2];
          if (!(closing == d + '>' || closing == '-' + d + '>')) {
            throw new Error('Could not find matching close tag for "' + line + '".');
          }
        }
        // HACK: backward-compat `include` preprocessor directives
        if ((include = line.match(/^\s*include\s+(\S+)/))) {
          includeOpts = utils.shallowCopy({}, self.opts);
          includeSrc = includeSource(include[1], includeOpts);
          includeSrc = '    ; (function(){' + '\n' + includeSrc + '    ; })()' + '\n';
          self.source += includeSrc;
        }
        else {
          self.scanLine(line);
        }
      });
    }

  };

  this.parseTemplateText = function () {
    var str = this.templateText
      , pat = this.regex
      , result = pat.exec(str)
      , arr = []
      , firstPos
      , lastPos;

    while (result) {
      firstPos = result.index;
      lastPos = pat.lastIndex;

      if (firstPos !== 0) {
        arr.push(str.substring(0, firstPos));
        str = str.slice(firstPos);
      }

      arr.push(result[0]);
      str = str.slice(result[0].length);
      result = pat.exec(str);
    }

    if (str) {
      arr.push(str);
    }

    return arr;
  };

  this.scanLine = function (line) {
    var self = this
      , d = this.opts.delimiter
      , newLineCount = 0;

    function _addOutput() {
      if (self.truncate) {
        line = line.replace('\n', '');
      }

      // Preserve literal slashes
      line = line.replace(/\\/g, '\\\\');

      // Convert linebreaks
      line = line.replace(/\n/g, '\\n');
      line = line.replace(/\r/g, '\\r');

      // Escape double-quotes
      // - this will be the delimiter during execution
      line = line.replace(/"/g, '\\"');
      self.source += '    ; __output.push("' + line + '")' + '\n';
    }

    newLineCount = (line.split('\n').length - 1);

    switch (line) {
      case '<' + d:
        this.mode = Template.modes.EVAL;
        break;
      case '<' + d + '=':
        this.mode = Template.modes.ESCAPED;
        break;
      case '<' + d + '-':
        this.mode = Template.modes.RAW;
        break;
      case '<' + d + '#':
        this.mode = Template.modes.COMMENT;
        break;
      case '<' + d + d:
        this.mode = Template.modes.LITERAL;
        this.source += '    ; __output.push("' + line.replace('<' + d + d, '<' + d) + '")' + '\n';
        break;
      case d + '>':
      case '-' + d + '>':
        if (this.mode == Template.modes.LITERAL) {
          _addOutput();
        }

        this.mode = null;
        this.truncate = line.indexOf('-') === 0;
        break;
      default:
        // In script mode, depends on type of tag
        if (this.mode) {
          // If '//' is found without a line break, add a line break.
          switch (this.mode) {
            case Template.modes.EVAL:
            case Template.modes.ESCAPED:
            case Template.modes.RAW:
              if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
                line += '\n';
              }
          }
          switch (this.mode) {
            // Just executing code
            case Template.modes.EVAL:
              this.source += '    ; ' + line + '\n';
              break;
            // Exec, esc, and output
            case Template.modes.ESCAPED:
              this.source += '    ; __output.push(escape(' +
                line.replace(_TRAILING_SEMCOL, '').trim() + '))' + '\n';
              break;
            // Exec and output
            case Template.modes.RAW:
              this.source += '    ; __output.push(' +
                line.replace(_TRAILING_SEMCOL, '').trim() + ')' + '\n';
              break;
            case Template.modes.COMMENT:
              // Do nothing
              break;
            // Literal <%% mode, append as raw output
            case Template.modes.LITERAL:
              _addOutput();
              break;
          }
        }
        // In string mode, just add the output
        else {
          _addOutput();
        }
    }

    if (self.opts.compileDebug && newLineCount) {
      this.currentLine += newLineCount;
      this.source += '    ; __line = ' + this.currentLine + '\n';
    }
  };
};

// Express support
exports.__express = exports.renderFile;

// Add require support
/* istanbul ignore else */
if (require.extensions) {
  require.extensions['.ejs'] = function (module, filename) {
    filename = filename || /* istanbul ignore next */ module.filename;
    var options = {
          filename: filename
        , client: true
        }
      , template = fs.readFileSync(filename).toString().trim()
      , fn = compile(template, options);
    module._compile('module.exports = ' + fn.toString() + ';', filename);
  };
}

exports.VERSION = _VERSION_STRING;

/* istanbul ignore if */
if (typeof window != 'undefined') {
  window.ejs = exports;
}
<commit_msg>Add some more istanbul annotations<commit_after>/*
 * EJS Embedded JavaScript templates
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

'use strict';

var fs = require('fs')
  , utils = require('./utils')
  , jsCache = {}
  , _VERSION_STRING = require('../package.json').version
  , _DEFAULT_DELIMITER = '%'
  , _DEFAULT_LOCALS_NAME = 'locals'
  , _REGEX_STRING = '(<%%|<%=|<%-|<%#|<%|%>|-%>)'
  , _OPTS = [ 'cache', 'filename', 'delimiter', 'scope', 'context'
            , 'debug', 'compileDebug', 'client', '_with'
            ]
  , _TRAILING_SEMCOL = /;\s*$/;

exports.localsName = _DEFAULT_LOCALS_NAME;

exports.resolveInclude = function(name, filename) {
  var path = require('path')
    , dirname = path.dirname
    , extname = path.extname
    , resolve = path.resolve
    , includePath = resolve(dirname(filename), name)
    , ext = extname(name);
  if (!ext) {
    includePath += '.ejs';
  }
  return includePath;
}

// Returns a possibly cached template function, set by options.cache.
// `template` is the string of EJS to compile.
// If template is undefined then the file specified in options.filename is
// read.
function handleCache(options, template) {
  var fn
    , path = options.filename
    , hasTemplate = template !== undefined;

  if (options.cache) {
    if (!path) {
      throw new Error('cache option requires a filename');
    }
    fn = jsCache[path];
    if (fn) {
      return fn;
    }
    if (!hasTemplate) {
      template = fs.readFileSync(path).toString();
    }
  }
  else if (!hasTemplate) {
    // istanbul ignore if: should not happen at all
    if (!path) {
      throw new Error('Internal EJS error: no file name or template '
                    + 'provided');
    }
    template = fs.readFileSync(path).toString();
  }
  fn = exports.compile(template.trim(), options);
  if (options.cache) {
    jsCache[path] = fn;
  }
  return fn;
}

function includeFile(path, options) {
  var opts = utils.shallowCopy({}, options);
  if (!opts.filename) {
    throw new Error('`include` requires the \'filename\' option.');
  }
  opts.filename = exports.resolveInclude(path, opts.filename);
  return handleCache(opts);
}

function includeSource(path, options) {
  var opts = utils.shallowCopy({}, options)
    , includePath
    , template;
  if (!opts.filename) {
    throw new Error('`include` requires the \'filename\' option.');
  }
  includePath = exports.resolveInclude(path, opts.filename);
  template = fs.readFileSync(includePath).toString().trim();

  opts.filename = includePath;
  var templ = new Template(template, opts);
  templ.generateSource();
  return templ.source;
}

function rethrow(err, str, filename, lineno){
  var lines = str.split('\n')
    , start = Math.max(lineno - 3, 0)
    , end = Math.min(lines.length, lineno + 3);

  // Error context
  var context = lines.slice(start, end).map(function (line, i){
    var curr = i + start + 1;
    return (curr == lineno ? ' >> ' : '    ')
      + curr
      + '| '
      + line;
  }).join('\n');

  // Alter exception message
  err.path = filename;
  err.message = (filename || 'ejs') + ':'
    + lineno + '\n'
    + context + '\n\n'
    + err.message;

  throw err;
}

function cpOptsInData(data, opts) {
  _OPTS.forEach(function (p) {
    if (typeof data[p] != 'undefined') {
      opts[p] = data[p];
    }
  });
}

function compile(template, opts) {
  var templ;

  // v1 compat
  // 'scope' is 'context'
  // FIXME: Remove this in a future version
  if (opts && opts.scope) {
    if (!opts.context) {
      opts.context = opts.scope;
    }
    delete opts.scope;
  }
  templ = new Template(template, opts);
  return templ.compile();
}
exports.compile = compile;

// template, [data], [opts]
// Have to include an empty data object if you want opts and no data
exports.render = function (template, data, opts) {
  data = data || {};
  opts = opts || {};
  var fn;

  // No options object -- if there are optiony names
  // in the data, copy them to options
  if (arguments.length == 2) {
    cpOptsInData(data, opts);
  }

  fn = handleCache(opts, template);
  return fn.call(opts.context, data);
};

// path, [data], [opts], cb
// Have to include an empty data object if you want opts and no data
exports.renderFile = function () {
  var args = Array.prototype.slice.call(arguments)
    , path = args.shift()
    , cb = args.pop()
    , data = args.shift() || {}
    , opts = args.pop() || {}
    , result
    , failed = false;

  // No options object -- if there are optiony names
  // in the data, copy them to options
  if (arguments.length == 3) {
    cpOptsInData(data, opts);
  }
  opts.filename = path;

  try {
    result = handleCache(opts)(data);
  }
  catch(err) {
    return process.nextTick(function () {
      cb(err);
    });
  }
  process.nextTick(function () {
    cb(null, result);
  });
};

exports.clearCache = function () {
  jsCache = {};
};

function Template(text, opts) {
  opts = opts || {};
  var options = {};
  this.templateText = text;
  this.mode = null;
  this.truncate = false;
  this.currentLine = 1;
  this.source = '';
  options.client = opts.client || false;
  options.escapeFunction = opts.escape || utils.escapeXML;
  options.compileDebug = opts.compileDebug !== false;
  options.debug = !!opts.debug;
  options.filename = opts.filename;
  options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
  options._with = typeof opts._with != 'undefined' ? opts._with : true;
  options.cache = opts.cache || false;
  this.opts = options;

  this.regex = this.createRegex();
}

Template.modes = {
    EVAL: 'eval'
  , ESCAPED: 'escaped'
  , RAW: 'raw'
  , COMMENT: 'comment'
  , LITERAL: 'literal'
};

Template.prototype = new function () {
  this.createRegex = function () {
    var str = _REGEX_STRING
      , delim = utils.escapeRegExpChars(this.opts.delimiter);
    str = str.replace(/%/g, delim);
    return new RegExp(str);
  };

  this.compile = function () {
    var src
      , fn
      , opts = this.opts
      , escape = opts.escapeFunction;

    if (!this.source) {
      this.generateSource();
      var prepended = '  var __output = [];' + '\n';
      if (opts._with !== false) {
        prepended +=  '  with (' + exports.localsName + ' || {}) {' + '\n';
      }
      this.source  = prepended + this.source;
      if (opts._with !== false) {
        this.source += '  }' + '\n';
      }
      this.source += '  return __output.join("").trim();' + '\n';
    }

    if (opts.compileDebug) {
      src = 'var __line = 1' + '\n'
          + '  , __lines = ' + JSON.stringify(this.templateText) + '\n'
          + '  , __filename = ' + (opts.filename ?
                JSON.stringify(opts.filename) : 'undefined') + ';' + '\n'
          + 'try {' + '\n'
          + this.source
          + '} catch (e) {' + '\n'
          + '  rethrow(e, __lines, __filename, __line);' + '\n'
          + '}' + '\n';
    }
    else {
      src = this.source;
    }

    if (opts.debug) {
      console.log(src);
    }

    if (opts.client) {
      if (escape !== utils.escapeXML) {
        src = 'escape = escape || ' + escape.toString() + ';' + '\n' + src;
      }
      else {
        src = utils.escapeFuncStr
            + 'escape = escape || ' + escape.toString() + ';' + '\n' + src;
      }
      if (opts.compileDebug) {
        src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
      }
    }

    try {
      fn = new Function(exports.localsName + ', escape, include, rethrow', src);
    }
    catch(e) {
      // istanbul ignore else
      if (e instanceof SyntaxError) {
        if (opts.filename) {
          e.message += ' in ' + opts.filename;
        }
        e.message += ' while compiling ejs';
      }
      throw e;
    }

    if (opts.client) {
      return fn;
    }

    // Return a callable function which will execute the function
    // created by the source-code, with the passed data as locals
    return function (data) {
      var include = function (path, includeData) {
        var d = utils.shallowCopy({}, data);
        if (includeData) {
          d = utils.shallowCopy(d, includeData);
        }
        return includeFile(path, opts)(d);
      };
      return fn(data || {}, escape, include, rethrow);
    };

  };

  this.generateSource = function () {
    var self = this
      , matches = this.parseTemplateText()
      , d = this.opts.delimiter;

    if (matches && matches.length) {
      matches.forEach(function (line, index) {
        var closing
          , include
          , includeOpts
          , includeSrc;
        // If this is an opening tag, check for closing tags
        // FIXME: May end up with some false positives here
        // Better to store modes as k/v with '<' + delimiter as key
        // Then this can simply check against the map
        if ( line.indexOf('<' + d) === 0        // If it is a tag
          && line.indexOf('<' + d + d) !== 0) { // and is not escaped
          closing = matches[index + 2];
          if (!(closing == d + '>' || closing == '-' + d + '>')) {
            throw new Error('Could not find matching close tag for "' + line + '".');
          }
        }
        // HACK: backward-compat `include` preprocessor directives
        if ((include = line.match(/^\s*include\s+(\S+)/))) {
          includeOpts = utils.shallowCopy({}, self.opts);
          includeSrc = includeSource(include[1], includeOpts);
          includeSrc = '    ; (function(){' + '\n' + includeSrc + '    ; })()' + '\n';
          self.source += includeSrc;
        }
        else {
          self.scanLine(line);
        }
      });
    }

  };

  this.parseTemplateText = function () {
    var str = this.templateText
      , pat = this.regex
      , result = pat.exec(str)
      , arr = []
      , firstPos
      , lastPos;

    while (result) {
      firstPos = result.index;
      lastPos = pat.lastIndex;

      if (firstPos !== 0) {
        arr.push(str.substring(0, firstPos));
        str = str.slice(firstPos);
      }

      arr.push(result[0]);
      str = str.slice(result[0].length);
      result = pat.exec(str);
    }

    if (str) {
      arr.push(str);
    }

    return arr;
  };

  this.scanLine = function (line) {
    var self = this
      , d = this.opts.delimiter
      , newLineCount = 0;

    function _addOutput() {
      if (self.truncate) {
        line = line.replace('\n', '');
      }

      // Preserve literal slashes
      line = line.replace(/\\/g, '\\\\');

      // Convert linebreaks
      line = line.replace(/\n/g, '\\n');
      line = line.replace(/\r/g, '\\r');

      // Escape double-quotes
      // - this will be the delimiter during execution
      line = line.replace(/"/g, '\\"');
      self.source += '    ; __output.push("' + line + '")' + '\n';
    }

    newLineCount = (line.split('\n').length - 1);

    switch (line) {
      case '<' + d:
        this.mode = Template.modes.EVAL;
        break;
      case '<' + d + '=':
        this.mode = Template.modes.ESCAPED;
        break;
      case '<' + d + '-':
        this.mode = Template.modes.RAW;
        break;
      case '<' + d + '#':
        this.mode = Template.modes.COMMENT;
        break;
      case '<' + d + d:
        this.mode = Template.modes.LITERAL;
        this.source += '    ; __output.push("' + line.replace('<' + d + d, '<' + d) + '")' + '\n';
        break;
      case d + '>':
      case '-' + d + '>':
        if (this.mode == Template.modes.LITERAL) {
          _addOutput();
        }

        this.mode = null;
        this.truncate = line.indexOf('-') === 0;
        break;
      default:
        // In script mode, depends on type of tag
        if (this.mode) {
          // If '//' is found without a line break, add a line break.
          switch (this.mode) {
            case Template.modes.EVAL:
            case Template.modes.ESCAPED:
            case Template.modes.RAW:
              if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
                line += '\n';
              }
          }
          switch (this.mode) {
            // Just executing code
            case Template.modes.EVAL:
              this.source += '    ; ' + line + '\n';
              break;
            // Exec, esc, and output
            case Template.modes.ESCAPED:
              this.source += '    ; __output.push(escape(' +
                line.replace(_TRAILING_SEMCOL, '').trim() + '))' + '\n';
              break;
            // Exec and output
            case Template.modes.RAW:
              this.source += '    ; __output.push(' +
                line.replace(_TRAILING_SEMCOL, '').trim() + ')' + '\n';
              break;
            case Template.modes.COMMENT:
              // Do nothing
              break;
            // Literal <%% mode, append as raw output
            case Template.modes.LITERAL:
              _addOutput();
              break;
          }
        }
        // In string mode, just add the output
        else {
          _addOutput();
        }
    }

    if (self.opts.compileDebug && newLineCount) {
      this.currentLine += newLineCount;
      this.source += '    ; __line = ' + this.currentLine + '\n';
    }
  };
};

// Express support
exports.__express = exports.renderFile;

// Add require support
/* istanbul ignore else */
if (require.extensions) {
  require.extensions['.ejs'] = function (module, filename) {
    filename = filename || /* istanbul ignore next */ module.filename;
    var options = {
          filename: filename
        , client: true
        }
      , template = fs.readFileSync(filename).toString().trim()
      , fn = compile(template, options);
    module._compile('module.exports = ' + fn.toString() + ';', filename);
  };
}

exports.VERSION = _VERSION_STRING;

/* istanbul ignore if */
if (typeof window != 'undefined') {
  window.ejs = exports;
}
<|endoftext|>