<commit_before>/*
 * TimeCard View
 * Copyright ©2015 Thomas Nelson, Jacob Nichols, David Opp, Todd Brochu,
Andrew McGown, Sasha Fahrenkopf, Cameron B. White.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE text file in the root directory of this source tree.
 */
import React, { PropTypes } from "react"
import { Link } from "react-router"
import moment from "moment"
import _ from "lodash"
import FluxComponent from 'flummox/component';
import flux from "../../flux/flux"
import DayOverviewCalendar from '../DayOverviewCalendar/DayOverviewCalendar'
import Page from '../Page/Page'

export default class DayOverview extends React.Component {
  render() {
    return (
      <FluxComponent
        connectToStores={['kronos']}
        stateGetter={([kronos]) => {
          const { params } = this.props
          const date = moment(params.date, 'YYYY-MM-DD')
          const day = kronos.getDay(date)
          const inPunches = kronos.getInPunchesForDate(date)
          const outPunches = kronos.getOutPunchesForDate(date)
          const exceptions = kronos.getExceptionsForDate(date)
          return {
            day,
            inPunches,
            outPunches,
            exceptions,
          }
        }}
      >
        <Overview {...this.props} />
      </FluxComponent>
    )
  }
}

class Overview extends React.Component {
  render() {
    // XXX Hack! Need to pull from API in a better way
    let lastKronosTimeZone = ""

    const { params, day, inPunches, outPunches } = this.props

    const inPunchesChain = _.chain(inPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "InPunch",
          })
        })
    const outPunchesChain = _.chain(outPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "OutPunch",
          })
        })

    /*
    const shiftsChain = _.chain(Schedule)
      .get('ScheduleItems.ScheduleShift', [])
      .filter({StartDate: moment(params.date).format("M/DD/YYYY")})
      .pluck('ShiftSegments.ShiftSegment')
      .compact()
      .map(eachShift => {
        const { StartDate, EndDate, StartTime, EndTime} = eachShift
        return [
          {
            time: kronosMoment(StartDate, StartTime, lastKronosTimeZone),
            type: 'scheduledIn'
          },{
            time: kronosMoment(EndDate, EndTime, lastKronosTimeZone),
            type: 'scheduledOut'
          }
        ]
      })
      .flatten()
    */

    const punches = inPunchesChain
       .concat(outPunchesChain.value())
       //.concat(shiftsChain.value())
       .sortBy('time')
       .map(punch => <Entry {...punch} />)
       .value()

    const date = moment(params.date)
    const year = date.format("YYYY")
    const month = date.format("MM")

    const dayHeaders = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]

    return (
      <Page>
        <DayHeader date={date}/>

            { punches.length > 0 ? punches :

No punches today

}

              <DayOverviewCalendar year={year} month={month-1} headers={dayHeaders} />

              <FluxComponent connectToStores={{
                  kronos: store => ({
                    day: store.getDay(moment(this.props.params.date, 'YYYY-MM-DD'))
                  })
              }}>
                <DayStats />
              </FluxComponent>

      </Page>
    )
  }
}

class DayHeader extends React.Component {
  render() {
    const displayDate = this.props.date.format("MMMM DD")
    return (

          <Link to="day" params={{date: this.props.date.clone().subtract(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-left subtle-btn">

                «

          </Link>

{displayDate}

          <Link to="day" params={{date: this.props.date.clone().add(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-right subtle-btn">

                »

          </Link>

 {/*For space*/}

    )
  }
}

class DayStats extends React.Component {
  render() {
    const { day } = this.props
    const total = day ? day.total : ''
    return (

Total Hours Worked: {total}

    )
  }
}

class Entry extends React.Component {
  render() {
    const panelClassDefault = "panel time-entry day"
    const glyphClassDefault = "day-icon"

    const settings = {
      InPunch: {
        action: "Clocked in",
        panelClass: panelClassDefault + " " + "time-in",
        glyphClass: "icon-truck"
      },
      OutPunch: {
        action: "Clocked out",
        panelClass: panelClassDefault + " " + "time-out",
        glyphClass: "icon-truck"
      },
      scheduledIn: {
        action: "Shift started",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      },
      scheduledOut: {
        action: "Shift ended",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      }
    }

    const {action, panelClass, glyphClass} = settings[this.props.type]

    const time = moment(this.props.time).format('hh:mm a')
    return (

{action}

                    <ActionIcon action = {action}/>

{time}

    )
  }
}

class ActionIcon extends React.Component {
    render () {
       if (this.props.action == "Clocked in") {
         return (

         )
       }

        if (this.props.action == "Clocked out") {
         return (

         )
       }

        if (this.props.action == "Shift started" || "Shift ended") {
         return (

         )
       }

        else {
           return null
       }
    }
}
<commit_msg>TCV-181: Print "a.m." or "p.m." after the time of each punch, for context<commit_after>/*
 * TimeCard View
 * Copyright ©2015 Thomas Nelson, Jacob Nichols, David Opp, Todd Brochu,
Andrew McGown, Sasha Fahrenkopf, Cameron B. White.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE text file in the root directory of this source tree.
 */
import React, { PropTypes } from "react"
import { Link } from "react-router"
import moment from "moment"
import _ from "lodash"
import FluxComponent from 'flummox/component';
import flux from "../../flux/flux"
import DayOverviewCalendar from '../DayOverviewCalendar/DayOverviewCalendar'
import Page from '../Page/Page'

export default class DayOverview extends React.Component {
  render() {
    return (
      <FluxComponent
        connectToStores={['kronos']}
        stateGetter={([kronos]) => {
          const { params } = this.props
          const date = moment(params.date, 'YYYY-MM-DD')
          const day = kronos.getDay(date)
          const inPunches = kronos.getInPunchesForDate(date)
          const outPunches = kronos.getOutPunchesForDate(date)
          const exceptions = kronos.getExceptionsForDate(date)
          return {
            day,
            inPunches,
            outPunches,
            exceptions,
          }
        }}
      >
        <Overview {...this.props} />
      </FluxComponent>
    )
  }
}

class Overview extends React.Component {
  render() {
    // XXX Hack! Need to pull from API in a better way
    let lastKronosTimeZone = ""

    const { params, day, inPunches, outPunches } = this.props

    const inPunchesChain = _.chain(inPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "InPunch",
          })
        })
    const outPunchesChain = _.chain(outPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "OutPunch",
          })
        })

    /*
    const shiftsChain = _.chain(Schedule)
      .get('ScheduleItems.ScheduleShift', [])
      .filter({StartDate: moment(params.date).format("M/DD/YYYY")})
      .pluck('ShiftSegments.ShiftSegment')
      .compact()
      .map(eachShift => {
        const { StartDate, EndDate, StartTime, EndTime} = eachShift
        return [
          {
            time: kronosMoment(StartDate, StartTime, lastKronosTimeZone),
            type: 'scheduledIn'
          },{
            time: kronosMoment(EndDate, EndTime, lastKronosTimeZone),
            type: 'scheduledOut'
          }
        ]
      })
      .flatten()
    */

    const punches = inPunchesChain
       .concat(outPunchesChain.value())
       //.concat(shiftsChain.value())
       .sortBy('time')
       .map(punch => <Entry {...punch} />)
       .value()

    const date = moment(params.date)
    const year = date.format("YYYY")
    const month = date.format("MM")

    const dayHeaders = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]

    return (
      <Page>
        <DayHeader date={date}/>

            { punches.length > 0 ? punches :

No punches today

}

              <DayOverviewCalendar year={year} month={month-1} headers={dayHeaders} />

              <FluxComponent connectToStores={{
                  kronos: store => ({
                    day: store.getDay(moment(this.props.params.date, 'YYYY-MM-DD'))
                  })
              }}>
                <DayStats />
              </FluxComponent>

      </Page>
    )
  }
}

class DayHeader extends React.Component {
  render() {
    const displayDate = this.props.date.format("MMMM DD")
    return (

          <Link to="day" params={{date: this.props.date.clone().subtract(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-left subtle-btn">

                «

          </Link>

{displayDate}

          <Link to="day" params={{date: this.props.date.clone().add(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-right subtle-btn">

                »

          </Link>

 {/*For space*/}

    )
  }
}

class DayStats extends React.Component {
  render() {
    const { day } = this.props
    const total = day ? day.total : ''
    return (

Total Hours Worked: {total}

    )
  }
}

class Entry extends React.Component {
  render() {
    const panelClassDefault = "panel time-entry day"
    const glyphClassDefault = "day-icon"

    const settings = {
      InPunch: {
        action: "Clocked in",
        panelClass: panelClassDefault + " " + "time-in",
        glyphClass: "icon-truck"
      },
      OutPunch: {
        action: "Clocked out",
        panelClass: panelClassDefault + " " + "time-out",
        glyphClass: "icon-truck"
      },
      scheduledIn: {
        action: "Shift started",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      },
      scheduledOut: {
        action: "Shift ended",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      }
    }

    const {action, panelClass, glyphClass} = settings[this.props.type]

    const time = moment(this.props.time).format('h:mma')
    return (

{action}

                    <ActionIcon action = {action}/>

{time}

    )
  }
}

class ActionIcon extends React.Component {
    render () {
       if (this.props.action == "Clocked in") {
         return (

         )
       }

        if (this.props.action == "Clocked out") {
         return (

         )
       }

        if (this.props.action == "Shift started" || "Shift ended") {
         return (

         )
       }

        else {
           return null
       }
    }
}
<|endoftext|>


<commit_before>'use strict';

/*globals accounting*/

angular.module('main')
.controller('ComparisonInformationCtrl', function($scope, $http, $location, $state, $backend, QueriesService) {
    $scope.service = (new QueriesService($backend.API_URL + '/_queries/public/api'));
    $scope.selection = {};
    $scope.showtab = [];
    $scope.reports = [];
    $scope.filings = null;
    $scope.error = false;
    $scope.errormany = false;

    $scope.$on('filterChanged', function(event, selection) {
        $scope.selection = angular.copy(selection);
        if (!selection) { return; }

        $location.search($scope.selection);

        $scope.filings = null;
        $scope.error = false;
        $scope.errormany = false;

        $scope.service.listFilings({
            $method: 'POST',
            cik: selection.cik,
            tag: selection.tag,
            fiscalYear: selection.fiscalYear,
            fiscalPeriod: selection.fiscalPeriod,
            token: $scope.token
        }).then(function(data) {
            $scope.filings = [];
            data.Archives.forEach(function(a) { $scope.filings.push(a.AccessionNumber); });
            if ($scope.filings.length > 30 && !$scope.nomany) {
                $scope.reports = [];
                $scope.errormany = true;
            } else {
                $scope.getInfo();
            }
        },
        function(response) {
            $scope.$emit('error', response.status, response.data);
        });
    });

    $scope.getInfo = function() {

        $scope.reports = [];
        $scope.params = {
                _method: 'POST',
                aid: $scope.filings,
                report: 'FundamentalAccountingConcepts',
                'token' : $scope.token
            };
        var promiseResponse = $backend.getFactsForReport($scope.params);
        promiseResponse.then(
            $scope.prepareReportForUI,
            function (data, status) {
              if (status === 401) {
                $scope.error = true;
              } else {
                $scope.$emit('error', status, data);
              }
            }
          );
    };

    $scope.prepareReportForUI = function(data) {
      var reports = [];

      var prepareReport =
        function(cik, list, array, index, isNumeric, decimals) {
          var j = 0, item;
          for (var key in list) {
            if (list.hasOwnProperty(key)) {
              if (index === 0) {
                item = {};
                item.cik = cik;
                item.name = key;
                item.label = list[key].Label ? list[key].Label : '';
                item.value = [];
                item.type = [];
                array[j] = item;
              } else {
                item = array[j];
              }
              if (list[key].Facts && list[key].Facts.length > 0) {
                item.type[index] = list[key].Facts[0].Type;
                if (list[key].Facts[0].Type === 'NumericValue') {
                  var num = list[key].Facts[0].Value;
                  if (!num) { num = '0'; }
                    item.value[index] = accounting.formatNumber(num, decimals);
                  } else {
                    item.value[index] = list[key].Facts[0].Value;
                  }
                } else {
                  if (isNumeric)
                  {
                    item.value[index] = 0;
                    item.type[index] = 'NumericValue';
                  }
                  else {
                    item.value[index] = null;
                    item.type[index] = '';
                  }
                }
                j++;
              } // if
          } // for
        };

      for (var i = 0; i < data.length; i++)
      {
        var root =
          data[i].Trees['fac:FundamentalAccountingConceptsLineItems']
          .To['fac:FundamentalAccountingConceptsHierarchy'].To;
        var cik = root["fac:GeneralInformationHierarchy"]
                  .To["fac:EntityCentralIndexKey"]
                  .Facts[0].Value;
        var k = 0;
        for (var report in root) {
          if (root.hasOwnProperty(report)
            && report !== 'fac:KeyRatiosHierarchy') {
            if (i === 0) {
              var obj = {
                name: root[report].Label.toString().replace(' [Hierarchy]', ''),
                section: report,
                items: [],
                isNumeric : (
                    report === 'fac:BalanceSheetHierarchy'
                    || report === 'fac:CashFlowStatementHierarchy'
                    || report === 'fac:IncomeStatementHierarchy'
                    || report === 'fac:StatementComprehensiveIncomeHierarchy'
                    || report === 'fac:KeyRatiosHierarchy'
                    || report === 'fac:ValidationStatistics'),
                isBoolean : (report === 'fac:Validations')
              };
              if (report === 'fac:KeyRatiosHierarchy')
              {
                obj.decimals = 3;
              }
              reports[k] = obj;
            }
            prepareReport(
              cik,
              root[report].To,
              reports[k].items,
              i,
              reports[k].isNumeric,
              reports[k].decimals || 0);
            k++;
          }
        }//for
      }//for
      $scope.error = false;
      $scope.errormany = false;
      $scope.reports = reports;
      for (var i = 0; i < reports.length; i++)
      {
        $scope.showtab.push(true);
      }
    };

    $scope.forceShow = function() {
        $scope.nomany=true;
        $scope.getInfo();
    };

    $scope.drill = function(cik, year, period) {
        $state.go('root.entity.information', { cik: cik, year: year, period: period });
    };

    $scope.isBlock = function(string) {
        if (!string) {
            return false;
        }
        return string.length > 60;
    };

    $scope.showText = function(html) {
        $scope.$emit('alert', 'Text Details', html);
    };

    $scope.getUrl = function(format) {
        var str = $backend.API_URL + '/_queries/public/api/facttable-for-report.jq';
        var params = angular.copy($scope.params);
        if (format) {
            params.format = format;
        }
        var qs = $scope.wwwFormUrlencoded(params);
        if (qs) {
            str += '?' + qs;
        }
        return str;
    };

    $scope.$on('$stateChangeSuccess', function(event, toState) {
        $scope.subActive = toState.data && toState.data.subActive;
    });
});
<commit_msg>- some indentation fixes<commit_after>'use strict';

/*globals accounting*/

angular.module('main')
.controller('ComparisonInformationCtrl', function($scope, $http, $location, $state, $backend, QueriesService) {
    $scope.service = (new QueriesService($backend.API_URL + '/_queries/public/api'));
    $scope.selection = {};
    $scope.showtab = [];
    $scope.reports = [];
    $scope.filings = null;
    $scope.error = false;
    $scope.errormany = false;

    $scope.$on('filterChanged', function(event, selection) {
        $scope.selection = angular.copy(selection);
        if (!selection) { return; }

        $location.search($scope.selection);

        $scope.filings = null;
        $scope.error = false;
        $scope.errormany = false;

        $scope.service.listFilings({
            $method: 'POST',
            cik: selection.cik,
            tag: selection.tag,
            fiscalYear: selection.fiscalYear,
            fiscalPeriod: selection.fiscalPeriod,
            token: $scope.token
        }).then(function(data) {
            $scope.filings = [];
            data.Archives.forEach(function(a) { $scope.filings.push(a.AccessionNumber); });
            if ($scope.filings.length > 30 && !$scope.nomany) {
                $scope.reports = [];
                $scope.errormany = true;
            } else {
                $scope.getInfo();
            }
        },
        function(response) {
            $scope.$emit('error', response.status, response.data);
        });
    });

    $scope.getInfo = function() {

        $scope.reports = [];
        $scope.params = {
                _method: 'POST',
                aid: $scope.filings,
                report: 'FundamentalAccountingConcepts',
                'token' : $scope.token
            };
        var promiseResponse = $backend.getFactsForReport($scope.params);
        promiseResponse.then(
            $scope.prepareReportForUI,
            function (data, status) {
                if (status === 401) {
                  $scope.error = true;
                } else {
                  $scope.$emit('error', status, data);
                }
            }
        );
    };

    $scope.prepareReportForUI = function(data) {
        var reports = [];

        var prepareReport =
            function(cik, list, array, index, isNumeric, decimals) {
                var j = 0, item;
                for (var key in list) {
                    if (list.hasOwnProperty(key)) {
                        if (index === 0) {
                            item = {};
                            item.cik = cik;
                            item.name = key;
                            item.label = list[key].Label ? list[key].Label : '';
                            item.value = [];
                            item.type = [];
                            array[j] = item;
                        } else {
                            item = array[j];
                        }
                        if (list[key].Facts && list[key].Facts.length > 0) {
                            item.type[index] = list[key].Facts[0].Type;
                            if (list[key].Facts[0].Type === 'NumericValue') {
                                var num = list[key].Facts[0].Value;
                                if (!num) { num = '0'; }
                                item.value[index] = accounting.formatNumber(num, decimals);
                            } else {
                                item.value[index] = list[key].Facts[0].Value;
                            }
                        } else {
                            if (isNumeric)
                            {
                                item.value[index] = 0;
                                item.type[index] = 'NumericValue';
                            }
                            else {
                                item.value[index] = null;
                                item.type[index] = '';
                            }
                        }
                        j++;
                    } // if
                } // for
            };

        for (var i = 0; i < data.length; i++)
        {
            var root = data[i].Trees['fac:FundamentalAccountingConceptsLineItems'].To['fac:FundamentalAccountingConceptsHierarchy'].To;
            var cik = root["fac:GeneralInformationHierarchy"].To["fac:EntityCentralIndexKey"].Facts[0].Value;
            var k = 0;
            for (var report in root) {
                if (root.hasOwnProperty(report)
                    && report !== 'fac:KeyRatiosHierarchy') {
                    if (i === 0) {
                        var obj = {
                            name: root[report].Label.toString().replace(' [Hierarchy]', ''),
                            section: report,
                            items: [],
                            isNumeric : (
                                report === 'fac:BalanceSheetHierarchy'
                                || report === 'fac:CashFlowStatementHierarchy'
                                || report === 'fac:IncomeStatementHierarchy'
                                || report === 'fac:StatementComprehensiveIncomeHierarchy'
                                || report === 'fac:KeyRatiosHierarchy'
                                || report === 'fac:ValidationStatistics'),
                            isBoolean : (report === 'fac:Validations')
                        };
                        if (report === 'fac:KeyRatiosHierarchy')
                        {
                            obj.decimals = 3;
                        }
                        reports[k] = obj;
                    }
                    prepareReport(
                        cik,
                        root[report].To,
                        reports[k].items,
                        i,
                        reports[k].isNumeric,
                        reports[k].decimals || 0);
                    k++;
                }
            }//for
        }//for
        $scope.error = false;
        $scope.errormany = false;
        $scope.reports = reports;
        for (var i = 0; i < reports.length; i++)
        {
            $scope.showtab.push(true);
        }
    };

    $scope.forceShow = function() {
        $scope.nomany=true;
        $scope.getInfo();
    };

    $scope.drill = function(cik, year, period) {
        $state.go('root.entity.information', { cik: cik, year: year, period: period });
    };

    $scope.isBlock = function(string) {
        if (!string) {
            return false;
        }
        return string.length > 60;
    };

    $scope.showText = function(html) {
        $scope.$emit('alert', 'Text Details', html);
    };

    $scope.getUrl = function(format) {
        var str = $backend.API_URL + '/_queries/public/api/facttable-for-report.jq';
        var params = angular.copy($scope.params);
        if (format) {
            params.format = format;
        }
        var qs = $scope.wwwFormUrlencoded(params);
        if (qs) {
            str += '?' + qs;
        }
        return str;
    };

    $scope.$on('$stateChangeSuccess', function(event, toState) {
        $scope.subActive = toState.data && toState.data.subActive;
    });
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular.module('sslv2App')
        .controller('UserInviteCtrl', UserInviteCtrl);

    UserInviteCtrl.$inject = ['$state', 'UserService', '$timeout', 'RESOURCES'];

    function UserInviteCtrl($state, UserService, $timeout, RESOURCES) {

        var vm = this;
        vm.message = "";
        vm.user = {
            email: '',
            role: '',
            caseWorkerRestricted: true,
            redirect_url: RESOURCES.REDIRECT_URL
        }
        vm.submit = submit;

        function submit(user) {
            UserService.invite(user)
                .then(function(response) {

                    if (response.data.success === true) {
                        vm.message = response.data.message;
                        closeMessage();
                    }else{
                        vm.message = response.data.error;
                        $timeout(function() {
                            vm.message = "";
                        }, 2000);
                    }
                }, function(error) {

                })
        }

        function closeMessage() {
            $timeout(function() {
                vm.message = "";
                $state.go('dashboard.manage');
            }, 2000);
        }
    }

})();<commit_msg>remove double slash in invite 2<commit_after>(function() {
    'use strict';

    angular.module('sslv2App')
        .controller('UserInviteCtrl', UserInviteCtrl);

    UserInviteCtrl.$inject = ['$state', 'UserService', '$timeout', 'RESOURCES', '$location'];

    function UserInviteCtrl($state, UserService, $timeout, RESOURCES, $location) {

        var vm = this;
        var port = $location.port();
        port =  port > 0 ? ':'+port : '';
        var url = $location.host();
        vm.message = "";
        vm.user = {
            email: '',
            role: '',
            caseWorkerRestricted: true,
            redirect_url: url + port
        }
        vm.submit = submit;

        function submit(user) {
            UserService.invite(user)
                .then(function(response) {

                    if (response.data.success === true) {
                        vm.message = response.data.message;
                        closeMessage();
                    }else{
                        vm.message = response.data.error;
                        $timeout(function() {
                            vm.message = "";
                        }, 2000);
                    }
                }, function(error) {

                })
        }

        function closeMessage() {
            $timeout(function() {
                vm.message = "";
                $state.go('dashboard.manage');
            }, 2000);
        }
    }

})();<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name atacamaApp.controller:WidgetCtrl
 * @description
 * # WidgetCtrl
 * Controller of the atacamaApp
 */
angular.module('atacamaApp')
    .controller('OhlcWidgetCtrl', function(
      $scope, $uibModal, ngstomp, $resource, $log, Restangular,
      elasticsearchService, chartService, turbineService, utilService) {
        var vm = this;

        vm.isLoaded = false;
        vm.hasError = false;

        // var url = 'http://localhost:48002';
        var sod = moment(0, "HH").format("x");
        // var subscription;

        // TODO select market in UI
        var market = 'FTSE100';

        var topic = '';

        var esError = '';
        var stompError = '';

        // TODO centralise the rest call data more so widgets can share the results...

        // {"stocks":[{"market":"FTSE100","symbol":"ABC"},{"market":"FTSE100","symbol":"DEF"}]}
        // {"indicators":[{"overlay":true,"name":"BollingerBands"},{"overlay":false,"name":"SMA12"}]}
        // {"strategies":[{"name":"SMAStrategy"},{"name":"CCICorrectionStrategy"}]}

          turbineService.symbols(market).then(function(response) {
            // console.log(JSON.stringify(response.stocks));
            vm.symbols = _.pluck(response.stocks, 'symbol');
            // $scope.selectedSymbol = $scope.symbols[0];
            vm.selectedSymbol = "...";
          }, function (err) {
            esError = 'unable to load symbols: {0}'.format(err.message);
            console.trace(esError);
          });

        reset();

        // $scope.strategies = [
        //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
        //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
        //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
        //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
        //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
        //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
        //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
        //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
        //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
        //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'}
        // ];

        // set the size of the chart as the widget is resized...
        $scope.$on('gridster-item-resized', function(item) {
          $log.debug('gridster-item-resized');
          //vm.options.chart.height = firstHeight + ((item.targetScope.gridsterItem.sizeY - 1) * nextHeight);
          //vm.options.chart.width = firstWidth + ((item.targetScope.gridsterItem.sizeX - 1) * nextWidth);
          //console.log('offsetHeight:' + $scope.offsetParent.prop('offsetHeight'));
          //console.log('offsetWidth:' + $scope.offsetParent.prop('offsetWidth'));

          // TODO this is inconsistent... needs work!
          vm.options.chart.height = $scope.offsetParent.prop('offsetHeight');
          vm.options.chart.width = $scope.offsetParent.prop('offsetWidth')
          // TODO now causes an error... is this needed?
          // $scope.api.update();
        });

        function reset() {
          $log.debug('reset()');
          vm.isLoaded = false;
          vm.hasError = false;

          vm.options = {
              chart: {
                  // TODO error message appears in console...
              }
          };

          vm.config = {
              deepWatchData: true,
              // deepWatchDataDepth: 1,
              refreshDataOnly: false,
              disabled: true
          };

          vm.data = [{
              key: vm.selectedSymbol,
              values: [{}]
          }];
        }

        var addOHLC = function(item) {
            console.log("ohlcController.js::addOHLC");
            // $scope.item = item;
            item.name = vm.selectedSymbol;
            reset();
            vm.typeOHLC = true;
            utilService.unsubscribeTopic(topic);

            if ( vm.selectedSymbol === "..." ) {
              return;
            }

            vm.config = {
              deepWatchData: true,
              // deepWatchDataDepth: 1,
              refreshDataOnly: false,
              disabled: false
            };

            vm.options = {
                chart: {
                    type: 'candlestickBarChart',
                    // type: 'ohlcBarChart',
                    height: $scope.offsetParent.prop('offsetHeight'),
                    width: $scope.offsetParent.prop('offsetWidth'),
                    margin: {
                        top: 20,
                        right: 40,
                        bottom: 40,
                        left: 40
                    },
                    x: function(d) {
                        return d['date'];
                    },
                    y: function(d) {
                        return d['close'];
                    },
                    showValues: true,
                    transitionDuration: 500,
                    xAxis: {
                        // axisLabel: 'Dates',
                        tickFormat: function(d) {
                            return d3.time.format('%X')(new Date(d));
                        },
                    },
                    yAxis: {
                        // axisLabel: 'Stock Price',
                        tickFormat: function(d, i) {
                            return '$' + d3.format(',.1f')(d);
                        }
                    }
                }
            };

            // $scope.message = moment();

            // var ticks = Restangular.one('tick').one($scope.selectedSymbol).one(sod);

            // ticks.get().then(function(response) {
            //     vm.data[0].values = response.ticks;
            // });

            var promise = elasticsearchService.getTicksAfter(vm.selectedSymbol, sod);

            promise.then(function (response) {
              utilService.traceLog(item, "elasticsearch");
              vm.data[0].values = elasticsearchService.parseResults(response);
            }, function (err) {
              esError = 'unable to load data: {0}:{1}'.format(vm.selectedSymbol, err.message);
              console.trace(esError);
            });

            topic = '/topic/ticks.' + market + '.' + vm.selectedSymbol;
            //ngstomp.subscribe(topic, onMessage, {}, $scope);

            try {
              ngstomp
                .subscribeTo(topic)
                .callback(onMessage)
                .withBodyInJson()
                .bindTo($scope)
                .connect();
              // throw new Error("unable to subscribe to topic: " + topic);
            } catch (err) {
              stompError = 'unable to connect to: {0}:{1}'.format(topic, err.message);
              console.trace(stompError);
            }

            function onMessage(message) {
              utilService.traceLog(item, "rabbit");
              // vm.data[0].values.push(JSON.parse(message.body));
              vm.data[0].values.push(message.body);
              $scope.$apply();
            }

            vm.isLoaded = true;

            // TODO catch all errors and set the property and message as required
            if (esError !== '' || stompError !== '') {
              vm.hasError = true;
            }

        };

        vm.selectSymbol = function(selectedSymbol) {
          vm.selectedSymbol = selectedSymbol;
          $log.log('select symbol: ', vm.selectedSymbol);
          addOHLC($scope.item);
        };

        // for smart-table...
        // $scope.addStrategies = function(widget) {
        //    console.log("widget.js::addStrategies");
        //    reset();
        //    $scope.typeStrategies = true;
        //    unsubscribeTopic();
        //  };

        // I don't think this is necessary anymore...
        // $scope.$on('$destroy', function() {
        //   utilService.unsubscribeTopic(topic);
        // });

    });
<commit_msg>[Style Y024] Named vs Anonymous Functions<commit_after>'use strict';

/**
 * @ngdoc function
 * @name atacamaApp.controller:WidgetCtrl
 * @description
 * # WidgetCtrl
 * Controller of the atacamaApp
 */
angular.module('atacamaApp')
    .controller('OhlcWidgetCtrl', OhlcWidgetController);

function OhlcWidgetController(
  $scope, $uibModal, ngstomp, $resource, $log, Restangular,
  elasticsearchService, chartService, turbineService, utilService) {
    var vm = this;

    vm.isLoaded = false;
    vm.hasError = false;

    // var url = 'http://localhost:48002';
    var sod = moment(0, "HH").format("x");
    // var subscription;

    // TODO select market in UI
    var market = 'FTSE100';

    var topic = '';

    var esError = '';
    var stompError = '';

    // TODO centralise the rest call data more so widgets can share the results...

    // {"stocks":[{"market":"FTSE100","symbol":"ABC"},{"market":"FTSE100","symbol":"DEF"}]}
    // {"indicators":[{"overlay":true,"name":"BollingerBands"},{"overlay":false,"name":"SMA12"}]}
    // {"strategies":[{"name":"SMAStrategy"},{"name":"CCICorrectionStrategy"}]}

      turbineService.symbols(market).then(function(response) {
        // console.log(JSON.stringify(response.stocks));
        vm.symbols = _.pluck(response.stocks, 'symbol');
        // $scope.selectedSymbol = $scope.symbols[0];
        vm.selectedSymbol = "...";
      }, function (err) {
        esError = 'unable to load symbols: {0}'.format(err.message);
        console.trace(esError);
      });

    reset();

    // $scope.strategies = [
    //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
    //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
    //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
    //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
    //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
    //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
    //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
    //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'},
    //   { action: 'sell', symbol: 'ABC', market: 'FTSE100'},
    //   { action: 'buy', symbol: 'DEF', market: 'FTSE100'}
    // ];

    // set the size of the chart as the widget is resized...
    $scope.$on('gridster-item-resized', function(item) {
      $log.debug('gridster-item-resized');
      //vm.options.chart.height = firstHeight + ((item.targetScope.gridsterItem.sizeY - 1) * nextHeight);
      //vm.options.chart.width = firstWidth + ((item.targetScope.gridsterItem.sizeX - 1) * nextWidth);
      //console.log('offsetHeight:' + $scope.offsetParent.prop('offsetHeight'));
      //console.log('offsetWidth:' + $scope.offsetParent.prop('offsetWidth'));

      // TODO this is inconsistent... needs work!
      vm.options.chart.height = $scope.offsetParent.prop('offsetHeight');
      vm.options.chart.width = $scope.offsetParent.prop('offsetWidth')
      // TODO now causes an error... is this needed?
      // $scope.api.update();
    });

    function reset() {
      $log.debug('reset()');
      vm.isLoaded = false;
      vm.hasError = false;

      vm.options = {
          chart: {
              // TODO error message appears in console...
          }
      };

      vm.config = {
          deepWatchData: true,
          // deepWatchDataDepth: 1,
          refreshDataOnly: false,
          disabled: true
      };

      vm.data = [{
          key: vm.selectedSymbol,
          values: [{}]
      }];
    }

    var addOHLC = function(item) {
        console.log("ohlcController.js::addOHLC");
        // $scope.item = item;
        item.name = vm.selectedSymbol;
        reset();
        vm.typeOHLC = true;
        utilService.unsubscribeTopic(topic);

        if ( vm.selectedSymbol === "..." ) {
          return;
        }

        vm.config = {
          deepWatchData: true,
          // deepWatchDataDepth: 1,
          refreshDataOnly: false,
          disabled: false
        };

        vm.options = {
            chart: {
                type: 'candlestickBarChart',
                // type: 'ohlcBarChart',
                height: $scope.offsetParent.prop('offsetHeight'),
                width: $scope.offsetParent.prop('offsetWidth'),
                margin: {
                    top: 20,
                    right: 40,
                    bottom: 40,
                    left: 40
                },
                x: function(d) {
                    return d['date'];
                },
                y: function(d) {
                    return d['close'];
                },
                showValues: true,
                transitionDuration: 500,
                xAxis: {
                    // axisLabel: 'Dates',
                    tickFormat: function(d) {
                        return d3.time.format('%X')(new Date(d));
                    },
                },
                yAxis: {
                    // axisLabel: 'Stock Price',
                    tickFormat: function(d, i) {
                        return '$' + d3.format(',.1f')(d);
                    }
                }
            }
        };

        // $scope.message = moment();

        // var ticks = Restangular.one('tick').one($scope.selectedSymbol).one(sod);

        // ticks.get().then(function(response) {
        //     vm.data[0].values = response.ticks;
        // });

        var promise = elasticsearchService.getTicksAfter(vm.selectedSymbol, sod);

        promise.then(function (response) {
          utilService.traceLog(item, "elasticsearch");
          vm.data[0].values = elasticsearchService.parseResults(response);
        }, function (err) {
          esError = 'unable to load data: {0}:{1}'.format(vm.selectedSymbol, err.message);
          console.trace(esError);
        });

        topic = '/topic/ticks.' + market + '.' + vm.selectedSymbol;
        //ngstomp.subscribe(topic, onMessage, {}, $scope);

        try {
          ngstomp
            .subscribeTo(topic)
            .callback(onMessage)
            .withBodyInJson()
            .bindTo($scope)
            .connect();
          // throw new Error("unable to subscribe to topic: " + topic);
        } catch (err) {
          stompError = 'unable to connect to: {0}:{1}'.format(topic, err.message);
          console.trace(stompError);
        }

        function onMessage(message) {
          utilService.traceLog(item, "rabbit");
          // vm.data[0].values.push(JSON.parse(message.body));
          vm.data[0].values.push(message.body);
          $scope.$apply();
        }

        vm.isLoaded = true;

        // TODO catch all errors and set the property and message as required
        if (esError !== '' || stompError !== '') {
          vm.hasError = true;
        }

    };

    vm.selectSymbol = function(selectedSymbol) {
      vm.selectedSymbol = selectedSymbol;
      $log.log('select symbol: ', vm.selectedSymbol);
      addOHLC($scope.item);
    };

    // for smart-table...
    // $scope.addStrategies = function(widget) {
    //    console.log("widget.js::addStrategies");
    //    reset();
    //    $scope.typeStrategies = true;
    //    unsubscribeTopic();
    //  };

    // I don't think this is necessary anymore...
    // $scope.$on('$destroy', function() {
    //   utilService.unsubscribeTopic(topic);
    // });

}
<|endoftext|>


<commit_before><commit_msg>Finish porting old basic.js to the new version<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

// For example, to find the nodeStepHash of "The Life Exotic" nodes:

// brew install jq
// ./getBungieManifest.js
// ./manifestDig.js manifest/world_sql_content_c7ea5036ed3278fe06a7a8feae87bf94.content 'The Life Exotic' DestinyTalentGridDefinition | jq '.nodes[].steps[] | select(.nodeStepName == "The Life Exotic") | .["nodeStepHash"]' | sort | uniq

var fs = require('fs');
var sqlite3 = require('sqlite3').verbose();

var target = process.argv[3];

var tables = (process.argv[4] || '').split(',');
if (tables.length == 1 && !tables[0].length) {
  tables = [];
}

var db = new sqlite3.Database(process.argv[2], sqlite3.OPEN_READONLY);

function dig(object, target, table, result) {
  if (typeof object === 'object') {
    for (var key in object) {
      if (key === target) {
        console.log(result);
      } else {
        dig(object[key], target, table, result);
      }
    }
  } else if (Array.isArray(object)) {
    object.forEach(function(val) {
      dig(val, target, table, result);
    });
  } else if (object == target) {
    console.log(result);
  }
}

db.serialize(function () {
  db.each("select name from sqlite_master where type='table'", function (err, table) {
    if (!tables.length || tables.indexOf(table.name) >= 0) {
      db.all("select * from " + table.name, function (err, result) {
        (result || []).forEach(function(entry) {
          if (entry.id === target) {
            console.log(entry.json);
          } else {
            try {
              var doc = JSON.parse(entry.json);
              dig(doc, target, table.name, entry.json);
            } catch(e) {
              console.error(e, entry.json);
            }
          }
        });
      });
    }
  });
});
<commit_msg>Add table info to manifestDig<commit_after>#!/usr/bin/env node

// For example, to find the nodeStepHash of "The Life Exotic" nodes:

// brew install jq
// ./getBungieManifest.js
// ./manifestDig.js manifest/world_sql_content_c7ea5036ed3278fe06a7a8feae87bf94.content 'The Life Exotic' DestinyTalentGridDefinition | jq '.nodes[].steps[] | select(.nodeStepName == "The Life Exotic") | .["nodeStepHash"]' | sort | uniq

var fs = require('fs');
var sqlite3 = require('sqlite3').verbose();

var target = process.argv[3];

var tables = (process.argv[4] || '').split(',');
if (tables.length == 1 && !tables[0].length) {
  tables = [];
}

var db = new sqlite3.Database(process.argv[2], sqlite3.OPEN_READONLY);

function dig(object, target, table, result) {
  if (typeof object === 'object') {
    for (var key in object) {
      if (key === target) {
        console.log('{ "table": "' + table + '", "result": ' + result + ' }');
      } else {
        dig(object[key], target, table, result);
      }
    }
  } else if (Array.isArray(object)) {
    object.forEach(function(val) {
      dig(val, target, table, result);
    });
  } else if (object == target) {
    console.log('{ "table": "' + table + '", "result": ' + result + ' }');
  }
}

db.serialize(function () {
  db.each("select name from sqlite_master where type='table'", function (err, table) {
    if (!tables.length || tables.indexOf(table.name) >= 0) {
      db.all("select * from " + table.name, function (err, result) {
        (result || []).forEach(function(entry) {
          if (entry.id === target) {
            console.log('{ "table": "' + table.name + '", "result": ' + entry.json + ' }');
          } else {
            try {
              var doc = JSON.parse(entry.json);
              dig(doc, target, table.name, entry.json);
            } catch(e) {
              console.error(e, entry.json);
            }
          }
        });
      });
    }
  });
});
<|endoftext|>


<commit_before><commit_msg>remove console.log<commit_after><|endoftext|>


<commit_before><commit_msg>core/remote: Log path when resolving conflict<commit_after><|endoftext|>


<commit_before>var Parser=(cur)=>{/* Convert keyboard events into Actions */
    var ParserCommand=()=>({current:'',previous:''}),

        parse_arrow=(dec)=>{
            switch(dec.code){
            case'D':cur.down(1);break;
            case'U':cur.up(1);break;
            case'R':cur.right(1,true);break;
            case'L':cur.left(1,true);break;
            default:break;
            }
        },

        parse_insert=(dec,t)=>{
            switch(dec.type){
            case'print':
                cur.ins(dec.code);cur.rowcol();
                // auxiliary escape methods: quickly type 'fd' or use the chord 'C-['
                if(dec.code==='f'){cur.fd=-t;}
                if(dec.code==='d'&&cur.fd<0&&t+cur.fd<500){cur.esc_fd();}
                if(dec.code==='['&&dec.mods[1]){cur.del_backward();cur.mode='normal';cur.left(1);}
                break;
            case'edit':
                if(dec.code==='B'){cur.del_backward();}// backspace
                else if(dec.code==='D'){cur.del_forward();}// forward delete
                break;
            case'escape':cur.normal_mode();break;
            default:break;
            }
        },

        parse_single=(dec,repeats=1)=>{
            for(var i=0;i<repeats;++i){
                switch(dec.code){
                    // motions
                case'j':cur.down(1);break;
                case'k':cur.up(1);break;
                case'l':cur.right(1);break;
                case'h':cur.left(1);break;
                case'0':cur.to_bol();break;
                case'$':cur.to_eol();break;
                case'{':cur.backward_paragraph();break;
                case'}':cur.forward_paragraph();break;
                case'G':cur.to_eob();break;
                case'b':cur.backward_word();break;
                case'e':cur.forward_word();break;
                    // mode changers
                case'i':cur.insert_mode();break;
                case'a':cur.append_mode();break;
                    // editing actions
                case'x':cur.del_at_point();break;
                case'D':cur.del_to_eol();break;
                default:break;
                }
            }
            //case' ':console.log('SPC-');break;// TODO SPC-prefixed functions a-la Spacemacs!
        },

        /* command tokenizers */
        multiplier=/[1-9][0-9]*/g,
        modifier=/a|i/,
        operator=/[cdy]/,
        motion=/[beGhjklw$^]/,
        object=/[wWps(){}\[\]"'`]/,
        find_all=(r,s)=>{var m,res=[];while((m=r.exec(s))!==null){res.push(m)}r.lastIndex=0;return res;},
        tokenize=(cmd,is_motion)=>{/* tokenize a command ending with a motion */
            var t={times:[]};
            var m;
            t.times=find_all(multiplier,cmd).map(a=>parseInt(a,10));
            //while((m=multiplier.exec(cmd))!==null){t.times.push(parseInt(m,10));}multiplier.lastIndex=0;
            t.oper=cmd.search(operator);
            if(is_motion){t.move=cmd.search(motion);}
            else{
                t.modifier=cmd.search(modifier);
                t.object=cmd.search(object);
            }
            return t;
        };

    return ({
        cmd:ParserCommand(),/* current, previous command */
        reset(){this.cmd=ParserCommand();},
        parse(t,dec){/* parse : DecodedKey -> Action Cursor */
            /* motion: [repeat] (h|j|k|l|w|e|b|...)
               operator: [repeat] (c|d|y)
               text_obj: [repeat] modifier (w|W|p|s|(|)|{|}|"|'|`)
               rule: operator (motion|text_obj)
               e.g: 5d2w = (repeat-five-times (delete (repeat-two-times (word-forward))))
            */
            if(cur.mode==='insert'){parse_insert(dec,t);}
            else{
                // only append non-chords
                if(!(dec.mods[0]||dec.mods[1]||dec.mods[2])){this.cmd.current+=dec.code;}

                var mo=this.cmd.current.search(motion),
                    ob=this.cmd.current.search(object);
                if(mo>=0||ob>=0){
                    var tokens=tokenize(this.cmd.current,(mo>=0));
                    console.log(JSON.stringify(tokens));

                    // clean up
                    this.cmd.previous=this.cmd.current;
                    this.cmd.current='';
                }
                if(cur.mode==='normal'){parse_single(dec);}
                // if(cur.mode==='visual'){TODO}
            }
            if(dec.type==='arrow'){parse_arrow(dec);}// parse arrows regardless of Cursor mode
        }
    });
};
<commit_msg>motions can now be repeated :tada:<commit_after>/* motion: [repeat] (h|j|k|l|w|e|b|...)
   operator: [repeat] (c|d|y)
   text_obj: [repeat] modifier (w|W|p|s|(|)|{|}|"|'|`)
   rule: operator (motion|text_obj)
   e.g: 5d2w = (repeat-five-times (delete (repeat-two-times (word-forward))))
*/
var Parser=(cur)=>{/* Convert keyboard events into Actions */
    var ParserCommand=()=>({current:'',previous:''}),

        arrow=(dec)=>{
            switch(dec.code){
            case'D':cur.down(1);break;
            case'U':cur.up(1);break;
            case'R':cur.right(1,true);break;
            case'L':cur.left(1,true);break;
            default:break;
            }
        },

        insert=(dec,t)=>{
            switch(dec.type){
            case'print':
                cur.ins(dec.code);cur.rowcol();
                // auxiliary escape methods: quickly type 'fd' or use the chord 'C-['
                if(dec.code==='f'){cur.fd=-t;}
                if(dec.code==='d'&&cur.fd<0&&t+cur.fd<500){cur.esc_fd();}
                if(dec.code==='['&&dec.mods[1]){cur.del_backward();cur.mode='normal';cur.left(1);}
                break;
            case'edit':
                if(dec.code==='B'){cur.del_backward();}// backspace
                else if(dec.code==='D'){cur.del_forward();}// forward delete
                break;
            case'escape':cur.normal_mode();break;
            default:break;
            }
        },

        single_token=(dec,repeats=1)=>{
            for(var i=0;i<repeats;++i){
                switch(dec.code){
                    // motions
                case'j':cur.down(1);break;
                case'k':cur.up(1);break;
                case'l':cur.right(1);break;
                case'h':cur.left(1);break;
                case'0':cur.to_bol();break;
                case'$':cur.to_eol();break;
                case'{':cur.backward_paragraph();break;
                case'}':cur.forward_paragraph();break;
                case'G':cur.to_eob();break;
                case'b':cur.backward_word();break;
                case'e':cur.forward_word();break;
                    // mode changers
                case'i':cur.insert_mode();break;
                case'a':cur.append_mode();break;
                    // editing actions
                case'x':cur.del_at_point();break;
                case'D':cur.del_to_eol();break;
                default:break;
                }
            }
            //case' ':console.log('SPC-');break;// TODO SPC-prefixed functions a-la Spacemacs!
        },

        /* command tokenizers */
        multiplier=/[1-9][0-9]*/g,
        modifier=/a|i/,
        operator=/[cdy]/,
        motion=/[beGhjklw$0^]/,
        object=/[wWps(){}\[\]"'`]/,

        find_all=(regex,str)=>{
            var match,result=[];
            while((match=regex.exec(str))!==null){result.push(match)}
            regex.lastIndex=0;
            return result.map(a=>parseInt(a,10));
        },

        tokenize=(cmd,is_obj)=>{
            var t={};
            t.times=find_all(multiplier,cmd);
            t.oper=cmd.match(operator);
            if(is_obj){t.modifier=cmd.search(modifier);t.txt_obj=cmd.search(object);}
            return t;
        };

    return ({
        cmd:ParserCommand(),/* current, previous command */
        reset(){this.cmd=ParserCommand();},
        parse(t,dec){/* parse : DecodedKey -> Action Cursor */
            if(cur.mode==='insert'){insert(dec,t);}
            else{
                // only append non-chords
                if(!(dec.mods[0]||dec.mods[1]||dec.mods[2])){this.cmd.current+=dec.code;}

                var mo=this.cmd.current.search(motion),ob=this.cmd.current.search(object);
                if(mo>=0||ob>=0){
                    // tokenize
                    var tokens=tokenize(this.cmd.current,(ob>=0));
                    console.log(JSON.stringify(tokens));

                    // parse the command
                    if(tokens.times.length<2){single_token(dec,tokens.times.pop())}

                    // clean up
                    this.cmd.previous=this.cmd.current;
                    this.cmd.current='';
                }
            }
            if(dec.type==='arrow'){arrow(dec);}// parse arrows regardless of Cursor mode
        }
    });
};
<|endoftext|>


<commit_before>/**
 * Gravatar demo
 * Based on
 *     https://en.gravatar.com/site/implement/images/
 * and
 *     http://www.deluxeblogtips.com/2010/04/get-gravatar-using-only-javascript.html
 */
enyo.kind({
    name: "tld.Gravatar",
    kind: "enyo.Image",
    src: "http://www.gravatar.com/avatar/0?s=10&f=y", // defaults to Gravatar logo
    published: {
        email: "t@t.com",
        imageSize: 50, // 1 to 2048 pixels, square
        rating: 'pg' // g, pg, r, x
    },
    rendered: function() {
        this.inherited(arguments);
        this.setSrc(this.newSrc());
    },
    newSrc: function() {
        this.inherited(arguments);
        var MD5=function(s){function L(k,d){return(k<<d)|(k>>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H<F){Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=(aa[Z]|(G.charCodeAt(H)<<d));H++}Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=aa[Z]|(128<<d);aa[I-2]=F<<3;aa[I-1]=F>>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F<k.length;F++){var x=k.charCodeAt(F);if(x<128){d+=String.fromCharCode(x)}else{if((x>127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P<C.length;P+=16){h=Y;E=X;v=W;g=V;Y=u(Y,X,W,V,C[P+0],S,3614090360);V=u(V,Y,X,W,C[P+1],Q,3905402710);W=u(W,V,Y,X,C[P+2],N,606105819);X=u(X,W,V,Y,C[P+3],M,3250441966);Y=u(Y,X,W,V,C[P+4],S,4118548399);V=u(V,Y,X,W,C[P+5],Q,1200080426);W=u(W,V,Y,X,C[P+6],N,2821735955);X=u(X,W,V,Y,C[P+7],M,4249261313);Y=u(Y,X,W,V,C[P+8],S,1770035416);V=u(V,Y,X,W,C[P+9],Q,2336552879);W=u(W,V,Y,X,C[P+10],N,4294925233);X=u(X,W,V,Y,C[P+11],M,2304563134);Y=u(Y,X,W,V,C[P+12],S,1804603682);V=u(V,Y,X,W,C[P+13],Q,4254626195);W=u(W,V,Y,X,C[P+14],N,2792965006);X=u(X,W,V,Y,C[P+15],M,1236535329);Y=f(Y,X,W,V,C[P+1],A,4129170786);V=f(V,Y,X,W,C[P+6],z,3225465664);W=f(W,V,Y,X,C[P+11],y,643717713);X=f(X,W,V,Y,C[P+0],w,3921069994);Y=f(Y,X,W,V,C[P+5],A,3593408605);V=f(V,Y,X,W,C[P+10],z,38016083);W=f(W,V,Y,X,C[P+15],y,3634488961);X=f(X,W,V,Y,C[P+4],w,3889429448);Y=f(Y,X,W,V,C[P+9],A,568446438);V=f(V,Y,X,W,C[P+14],z,3275163606);W=f(W,V,Y,X,C[P+3],y,4107603335);X=f(X,W,V,Y,C[P+8],w,1163531501);Y=f(Y,X,W,V,C[P+13],A,2850285829);V=f(V,Y,X,W,C[P+2],z,4243563512);W=f(W,V,Y,X,C[P+7],y,1735328473);X=f(X,W,V,Y,C[P+12],w,2368359562);Y=D(Y,X,W,V,C[P+5],o,4294588738);V=D(V,Y,X,W,C[P+8],m,2272392833);W=D(W,V,Y,X,C[P+11],l,1839030562);X=D(X,W,V,Y,C[P+14],j,4259657740);Y=D(Y,X,W,V,C[P+1],o,2763975236);V=D(V,Y,X,W,C[P+4],m,1272893353);W=D(W,V,Y,X,C[P+7],l,4139469664);X=D(X,W,V,Y,C[P+10],j,3200236656);Y=D(Y,X,W,V,C[P+13],o,681279174);V=D(V,Y,X,W,C[P+0],m,3936430074);W=D(W,V,Y,X,C[P+3],l,3572445317);X=D(X,W,V,Y,C[P+6],j,76029189);Y=D(Y,X,W,V,C[P+9],o,3654602809);V=D(V,Y,X,W,C[P+12],m,3873151461);W=D(W,V,Y,X,C[P+15],l,530742520);X=D(X,W,V,Y,C[P+2],j,3299628645);Y=t(Y,X,W,V,C[P+0],U,4096336452);V=t(V,Y,X,W,C[P+7],T,1126891415);W=t(W,V,Y,X,C[P+14],R,2878612391);X=t(X,W,V,Y,C[P+5],O,4237533241);Y=t(Y,X,W,V,C[P+12],U,1700485571);V=t(V,Y,X,W,C[P+3],T,2399980690);W=t(W,V,Y,X,C[P+10],R,4293915773);X=t(X,W,V,Y,C[P+1],O,2240044497);Y=t(Y,X,W,V,C[P+8],U,1873313359);V=t(V,Y,X,W,C[P+15],T,4264355552);W=t(W,V,Y,X,C[P+6],R,2734768916);X=t(X,W,V,Y,C[P+13],O,1309151649);Y=t(Y,X,W,V,C[P+4],U,4149444226);V=t(V,Y,X,W,C[P+11],T,3174756917);W=t(W,V,Y,X,C[P+2],R,718787259);X=t(X,W,V,Y,C[P+9],O,3951481745);Y=K(Y,h);X=K(X,E);W=K(W,v);V=K(V,g)}var i=B(Y)+B(X)+B(W)+B(V);return i.toLowerCase()};
        return 'http://www.gravatar.com/avatar/' + MD5(this.email) + '.jpg?s=' + this.imageSize + '&r=' + this.rating;
    }
});
/** Example can be found at JSFiddle
http://jsfiddle.net/pcimino/VBNSM/

enyo.kind({
    name: "App",
    kind: "Control",
    components: [
        {kind: "tld.Gravatar", email: "pcimino@translunardesigns.com", imageSize: 50},
        {kind: "tld.Gravatar", imageSize: 75},
        {kind: "tld.Gravatar", email: "pcimino@translunardesigns.com", imageSize: 100},
        {kind: "tld.Gravatar", imageSize: 125},
        {kind: "tld.Gravatar", email: "pcimino@translunardesigns.com", imageSize: 150},
        {kind: "tld.Gravatar", imageSize: 175}
    ]
});

new App().renderInto(document.body);
*/<commit_msg>Removed unnecessary inherited call<commit_after>/**
 * Gravatar demo
 * Based on
 *     https://en.gravatar.com/site/implement/images/
 * and
 *     http://www.deluxeblogtips.com/2010/04/get-gravatar-using-only-javascript.html
 */
enyo.kind({
    name: "tld.Gravatar",
    kind: "enyo.Image",
    src: "http://www.gravatar.com/avatar/0?s=10&f=y", // defaults to Gravatar logo
    published: {
        email: "t@t.com",
        imageSize: 50, // 1 to 2048 pixels, square
        rating: 'pg' // g, pg, r, x
    },
    rendered: function() {
        this.inherited(arguments);
        this.setSrc(this.newSrc());
    },
    newSrc: function() {
        var MD5=function(s){function L(k,d){return(k<<d)|(k>>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H<F){Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=(aa[Z]|(G.charCodeAt(H)<<d));H++}Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=aa[Z]|(128<<d);aa[I-2]=F<<3;aa[I-1]=F>>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F<k.length;F++){var x=k.charCodeAt(F);if(x<128){d+=String.fromCharCode(x)}else{if((x>127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P<C.length;P+=16){h=Y;E=X;v=W;g=V;Y=u(Y,X,W,V,C[P+0],S,3614090360);V=u(V,Y,X,W,C[P+1],Q,3905402710);W=u(W,V,Y,X,C[P+2],N,606105819);X=u(X,W,V,Y,C[P+3],M,3250441966);Y=u(Y,X,W,V,C[P+4],S,4118548399);V=u(V,Y,X,W,C[P+5],Q,1200080426);W=u(W,V,Y,X,C[P+6],N,2821735955);X=u(X,W,V,Y,C[P+7],M,4249261313);Y=u(Y,X,W,V,C[P+8],S,1770035416);V=u(V,Y,X,W,C[P+9],Q,2336552879);W=u(W,V,Y,X,C[P+10],N,4294925233);X=u(X,W,V,Y,C[P+11],M,2304563134);Y=u(Y,X,W,V,C[P+12],S,1804603682);V=u(V,Y,X,W,C[P+13],Q,4254626195);W=u(W,V,Y,X,C[P+14],N,2792965006);X=u(X,W,V,Y,C[P+15],M,1236535329);Y=f(Y,X,W,V,C[P+1],A,4129170786);V=f(V,Y,X,W,C[P+6],z,3225465664);W=f(W,V,Y,X,C[P+11],y,643717713);X=f(X,W,V,Y,C[P+0],w,3921069994);Y=f(Y,X,W,V,C[P+5],A,3593408605);V=f(V,Y,X,W,C[P+10],z,38016083);W=f(W,V,Y,X,C[P+15],y,3634488961);X=f(X,W,V,Y,C[P+4],w,3889429448);Y=f(Y,X,W,V,C[P+9],A,568446438);V=f(V,Y,X,W,C[P+14],z,3275163606);W=f(W,V,Y,X,C[P+3],y,4107603335);X=f(X,W,V,Y,C[P+8],w,1163531501);Y=f(Y,X,W,V,C[P+13],A,2850285829);V=f(V,Y,X,W,C[P+2],z,4243563512);W=f(W,V,Y,X,C[P+7],y,1735328473);X=f(X,W,V,Y,C[P+12],w,2368359562);Y=D(Y,X,W,V,C[P+5],o,4294588738);V=D(V,Y,X,W,C[P+8],m,2272392833);W=D(W,V,Y,X,C[P+11],l,1839030562);X=D(X,W,V,Y,C[P+14],j,4259657740);Y=D(Y,X,W,V,C[P+1],o,2763975236);V=D(V,Y,X,W,C[P+4],m,1272893353);W=D(W,V,Y,X,C[P+7],l,4139469664);X=D(X,W,V,Y,C[P+10],j,3200236656);Y=D(Y,X,W,V,C[P+13],o,681279174);V=D(V,Y,X,W,C[P+0],m,3936430074);W=D(W,V,Y,X,C[P+3],l,3572445317);X=D(X,W,V,Y,C[P+6],j,76029189);Y=D(Y,X,W,V,C[P+9],o,3654602809);V=D(V,Y,X,W,C[P+12],m,3873151461);W=D(W,V,Y,X,C[P+15],l,530742520);X=D(X,W,V,Y,C[P+2],j,3299628645);Y=t(Y,X,W,V,C[P+0],U,4096336452);V=t(V,Y,X,W,C[P+7],T,1126891415);W=t(W,V,Y,X,C[P+14],R,2878612391);X=t(X,W,V,Y,C[P+5],O,4237533241);Y=t(Y,X,W,V,C[P+12],U,1700485571);V=t(V,Y,X,W,C[P+3],T,2399980690);W=t(W,V,Y,X,C[P+10],R,4293915773);X=t(X,W,V,Y,C[P+1],O,2240044497);Y=t(Y,X,W,V,C[P+8],U,1873313359);V=t(V,Y,X,W,C[P+15],T,4264355552);W=t(W,V,Y,X,C[P+6],R,2734768916);X=t(X,W,V,Y,C[P+13],O,1309151649);Y=t(Y,X,W,V,C[P+4],U,4149444226);V=t(V,Y,X,W,C[P+11],T,3174756917);W=t(W,V,Y,X,C[P+2],R,718787259);X=t(X,W,V,Y,C[P+9],O,3951481745);Y=K(Y,h);X=K(X,E);W=K(W,v);V=K(V,g)}var i=B(Y)+B(X)+B(W)+B(V);return i.toLowerCase()};
        return 'http://www.gravatar.com/avatar/' + MD5(this.email) + '.jpg?s=' + this.imageSize + '&r=' + this.rating;
    }
});
/** Example can be found at JSFiddle
http://jsfiddle.net/pcimino/VBNSM/

enyo.kind({
    name: "App",
    kind: "Control",
    components: [
        {kind: "tld.Gravatar", email: "pcimino@translunardesigns.com", imageSize: 50},
        {kind: "tld.Gravatar", imageSize: 75},
        {kind: "tld.Gravatar", email: "pcimino@translunardesigns.com", imageSize: 100},
        {kind: "tld.Gravatar", imageSize: 125},
        {kind: "tld.Gravatar", email: "pcimino@translunardesigns.com", imageSize: 150},
        {kind: "tld.Gravatar", imageSize: 175}
    ]
    , create: function() {
        this.inherited(arguments);
        // create one dynamically before rendering
        this.createComponent({kind: "tld.Gravatar", name: 'testDynamic', imageSize: 50});
        this.$.testDynamic.setEmail('pcimino@translunardesigns.com');
    }
    , rendered: function() {
        this.inherited(arguments);
        // create one dynamically after everything else has been built
        this.createComponent({kind: "tld.Gravatar", name: 'testDynamicPostRender', imageSize: 25});
        this.$.testDynamicPostRender.setEmail('pcimino@translunardesigns.com');
        this.$.testDynamicPostRender.render();
    }
});

new App().renderInto(document.body);
*/<|endoftext|>


<commit_before>var selectTime = 0;
var countTime = null;
var sound = true;
var counter = 0;

function startTimer(){
	document.getElementById("start").disabled = "disabled";
	var mySelect = document.Form.selector.selectedIndex;
	selectTime = document.Form.selector.options[mySelect].value - 0;
	countTime = setInterval ( setTimer, 1000 );

}

function setTimer(){
	selectTime = selectTime - 1;
	document.getElementById( "countdown" ).innerHTML = getRestTimeText() + "
Stopをおすととまります";
	if ( selectTime == 0 ){
		if( sound ){
			clearInterval( countTime );
			countTime = null;
			document.getElementById("start").disabled = "";
			audio = new Audio();
			audio.src = "ata_a19.wav";
			audio.play();
			document.getElementById( "countdown" ).innerHTML = getRestTimeText() + "
Goをおすとカウントダウンがはじまります";
		}else{
			clearInterval( countTime );
			alert( "終了ー" );
			countTime = null;
			document.getElementById("start").disabled = "";
			document.getElementById( "countdown" ).innerHTML = getRestTimeText() + "
Goをおすとカウントダウンがはじまります";
		}
	}
}

function stopTimer(){
	if(countTime != null){
		clearInterval(countTime);
		document.getElementById("start").disabled = "";
		countTime = null;
		document.getElementById( "countdown" ).innerHTML = getRestTimeText() + "
Goをおすとはじめからカウントダウンしなおします";
		selectTime = 0;

	}
}

function getRestTimeText() {
	var minutes = Math.floor(selectTime / 60);
	var seconds = selectTime % 60;
	return "残り時間：" + minutes + "分"+ seconds + "秒";
}

function soundOff(){
	if (counter % 2 == 0){
		sound = false;
		sound_off.value="音を鳴らす";
		document.getElementById( "sound" ).innerHTML = "ボタンをおすと音声を再生するか選べます（現在：音声再生OFF）";
		counter++;
	}else{
		sound = true;
		sound_off.value="音を鳴らさない"
		document.getElementById( "sound" ).innerHTML = "ボタンをおすと音声を再生するか選べます（現在：音声再生ON）";
		counter++;
	}

}<commit_msg>フォーマットそろえた<commit_after>var selectTime = 0;
var countTime = null;
var sound = true;
var counter = 0;

function startTimer() {
	document.getElementById("start").disabled = "disabled";
	var mySelect = document.Form.selector.selectedIndex;
	selectTime = document.Form.selector.options[mySelect].value - 0;
	countTime = setInterval(setTimer, 1000);

}

function setTimer() {
	selectTime = selectTime - 1;
	document.getElementById("countdown").innerHTML = getRestTimeText() + "
Stopをおすととまります";
	if (selectTime == 0) {
		if (sound) {
			clearInterval(countTime);
			countTime = null;
			document.getElementById("start").disabled = "";
			audio = new Audio();
			audio.src = "ata_a19.wav";
			audio.play();
			document.getElementById("countdown").innerHTML = getRestTimeText() + "
Goをおすとカウントダウンがはじまります";
		} else {
			clearInterval(countTime);
			alert("終了ー");
			countTime = null;
			document.getElementById("start").disabled = "";
			document.getElementById("countdown").innerHTML = getRestTimeText() + "
Goをおすとカウントダウンがはじまります";
		}
	}
}

function stopTimer() {
	if (countTime != null) {
		clearInterval(countTime);
		document.getElementById("start").disabled = "";
		countTime = null;
		document.getElementById("countdown").innerHTML = getRestTimeText() + "
Goをおすとはじめからカウントダウンしなおします";
		selectTime = 0;

	}
}

function getRestTimeText() {
	var minutes = Math.floor(selectTime / 60);
	var seconds = selectTime % 60;
	return "残り時間：" + minutes + "分" + seconds + "秒";
}

function soundOff() {
	if (counter % 2 == 0) {
		sound = false;
		sound_off.value = "音を鳴らす";
		document.getElementById("sound").innerHTML = "ボタンをおすと音声を再生するか選べます（現在：音声再生OFF）";
		counter++;
	} else {
		sound = true;
		sound_off.value = "音を鳴らさない"
		document.getElementById("sound").innerHTML = "ボタンをおすと音声を再生するか選べます（現在：音声再生ON）";
		counter++;
	}

}<|endoftext|>


<commit_before>// gesture feature
/**
 enyo.gesture is an event filter for enyo dispatcher.

 This filter monitors DOM events to provide special synthesized events.

 * "back" - sent for the back gesture on webOS devices with a gesture area or on the ESC key in browsers
 * "click" - normally, you get the one sent by the system, but you can get a synthetic "click" when a drag has been initiated
 * "dragstart", "dragfinish" - sent for mouse moves that exceed a certain threshhold
 * "drag", "drop" - sent to the original target of the mousemove to inform it about the item being moved over or released over another element
 * "dragover", "dragout" - sent in place of mouseover and mouseout when there is an active drag
 * "mousehold", "mouseholdpulse", and "mouserelease" - sent for mouse moves that stay within the drag threshhold.  Used to implement hold actions.

 There are no public methods defined here.
 */

//* @protected
enyo.dispatcher.features.push(
	function(e) {
		// NOTE: beware of properties in enyo.gesture inadvertantly mapped to event types
		if (enyo.gesture.drag[e.type]) {
			return enyo.gesture.drag[e.type](e);
		}
	}
);

//* @public
enyo.gesture.drag = {
	//* @protected
	hysteresis: 4,
	down: function(e) {
		// tracking if the mouse is down
		//console.log("tracking ON");
		// Note: 'tracking' flag indicates interest in mousemove, it's turned off
		// on mouseup
		this.tracking = true;
		this.target = e.target;
		this.dispatchTarget = e.dispatchTarget;
		this.targetEvent = e;
		this.px0 = e.pageX;
		this.py0 = e.pageY;
	},
	move: function(e) {
		if (this.tracking) {
			this.dx = e.pageX - this.px0;
			this.dy = e.pageY - this.py0;
			if (this.dragEvent) {
				this.sendDrag(e);
			} else if (Math.sqrt(this.dy*this.dy + this.dx*this.dx) >= this.hysteresis) {
				this.sendDragStart(e);
			}
		}
	},
	up: function(e) {
		this.tracking = false;
		this.stopDragging(e);
	},
	leave: function(e) {
		if (this.dragEvent) {
			this.sendDragOut(e);
		}
	},
	stopDragging: function(e) {
		if (this.dragEvent) {
			this.sendDrop(e);
			var handled = this.sendDragFinish(e);
			this.dragEvent = null;
			return handled;
		}
	},
	makeDragEvent: function(inType, inTarget, inEvent, inInfo) {
		var adx = Math.abs(this.dx), ady = Math.abs(this.dy);
		var h = adx > ady;
		// suggest locking if off-axis < 22.5 degrees
		var l = (h ? ady/adx : adx/ady) < 0.414;
		return {
			type: inType,
			dx: this.dx,
			dy: this.dy,
			pageX: inEvent.pageX,
			pageY: inEvent.pageY,
			horizontal: h,
			vertical: !h,
			lockable: l,
			target: inTarget,
			dragInfo: inInfo,
			ctrlKey: inEvent.ctrlKey,
			altKey: inEvent.altKey,
			metaKey: inEvent.metaKey,
			shiftKey: inEvent.shiftKey
		};
	},
	sendDragStart: function(e) {
		//console.log("dragstart");
		this.dragEvent = this.makeDragEvent("dragstart", this.target, e);
		enyo.dispatch(this.dragEvent);
	},
	sendDrag: function(e) {
		//console.log("sendDrag to " + this.dragEvent.target.id + ", over to " + e.target.id);
		// send dragOver event to the standard event target
		var synth = this.makeDragEvent("dragover", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
		// send drag event to the drag source
		synth.type = "drag";
		synth.target = this.dragEvent.target;
		enyo.dispatch(synth);
	},
	sendDragFinish: function(e) {
		//console.log("dragfinish");
		var synth = this.makeDragEvent("dragfinish", this.dragEvent.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap();
		};
		enyo.dispatch(synth);
	},
	sendDragOut: function(e) {
		var synth = this.makeDragEvent("dragout", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
	},
	sendDrop: function(e) {
		var synth = this.makeDragEvent("drop", e.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap();
		};
		enyo.dispatch(synth);
	}
};
<commit_msg>* drag: stop dragging on a down event; ensures un-ended drags are aborted before new ones are created.<commit_after>// gesture feature
/**
 enyo.gesture is an event filter for enyo dispatcher.

 This filter monitors DOM events to provide special synthesized events.

 * "back" - sent for the back gesture on webOS devices with a gesture area or on the ESC key in browsers
 * "click" - normally, you get the one sent by the system, but you can get a synthetic "click" when a drag has been initiated
 * "dragstart", "dragfinish" - sent for mouse moves that exceed a certain threshhold
 * "drag", "drop" - sent to the original target of the mousemove to inform it about the item being moved over or released over another element
 * "dragover", "dragout" - sent in place of mouseover and mouseout when there is an active drag
 * "mousehold", "mouseholdpulse", and "mouserelease" - sent for mouse moves that stay within the drag threshhold.  Used to implement hold actions.

 There are no public methods defined here.
 */

//* @protected
enyo.dispatcher.features.push(
	function(e) {
		// NOTE: beware of properties in enyo.gesture inadvertantly mapped to event types
		if (enyo.gesture.drag[e.type]) {
			return enyo.gesture.drag[e.type](e);
		}
	}
);

//* @public
enyo.gesture.drag = {
	//* @protected
	hysteresis: 4,
	down: function(e) {
		// tracking if the mouse is down
		//console.log("tracking ON");
		// Note: 'tracking' flag indicates interest in mousemove, it's turned off
		// on mouseup
		// make sure to stop dragging in case the up event was not received.
		this.stopDragging(e);
		this.tracking = true;
		this.target = e.target;
		this.dispatchTarget = e.dispatchTarget;
		this.targetEvent = e;
		this.px0 = e.pageX;
		this.py0 = e.pageY;
	},
	move: function(e) {
		if (this.tracking) {
			this.dx = e.pageX - this.px0;
			this.dy = e.pageY - this.py0;
			if (this.dragEvent) {
				this.sendDrag(e);
			} else if (Math.sqrt(this.dy*this.dy + this.dx*this.dx) >= this.hysteresis) {
				this.sendDragStart(e);
			}
		}
	},
	up: function(e) {
		this.tracking = false;
		this.stopDragging(e);
	},
	leave: function(e) {
		if (this.dragEvent) {
			this.sendDragOut(e);
		}
	},
	stopDragging: function(e) {
		if (this.dragEvent) {
			this.sendDrop(e);
			var handled = this.sendDragFinish(e);
			this.dragEvent = null;
			return handled;
		}
	},
	makeDragEvent: function(inType, inTarget, inEvent, inInfo) {
		var adx = Math.abs(this.dx), ady = Math.abs(this.dy);
		var h = adx > ady;
		// suggest locking if off-axis < 22.5 degrees
		var l = (h ? ady/adx : adx/ady) < 0.414;
		return {
			type: inType,
			dx: this.dx,
			dy: this.dy,
			pageX: inEvent.pageX,
			pageY: inEvent.pageY,
			horizontal: h,
			vertical: !h,
			lockable: l,
			target: inTarget,
			dragInfo: inInfo,
			ctrlKey: inEvent.ctrlKey,
			altKey: inEvent.altKey,
			metaKey: inEvent.metaKey,
			shiftKey: inEvent.shiftKey
		};
	},
	sendDragStart: function(e) {
		//console.log("dragstart");
		this.dragEvent = this.makeDragEvent("dragstart", this.target, e);
		enyo.dispatch(this.dragEvent);
	},
	sendDrag: function(e) {
		//console.log("sendDrag to " + this.dragEvent.target.id + ", over to " + e.target.id);
		// send dragOver event to the standard event target
		var synth = this.makeDragEvent("dragover", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
		// send drag event to the drag source
		synth.type = "drag";
		synth.target = this.dragEvent.target;
		enyo.dispatch(synth);
	},
	sendDragFinish: function(e) {
		//console.log("dragfinish");
		var synth = this.makeDragEvent("dragfinish", this.dragEvent.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap && e.preventTap();
		};
		enyo.dispatch(synth);
	},
	sendDragOut: function(e) {
		var synth = this.makeDragEvent("dragout", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
	},
	sendDrop: function(e) {
		var synth = this.makeDragEvent("drop", e.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap && e.preventTap();
		};
		enyo.dispatch(synth);
	}
};
<|endoftext|>


<commit_before>/**
	Enyo supports a cross-platform set of drag events.  These events allow users
	to write a single set of event handlers for applications that run on both
	mobile and desktop platforms.

	The following events are provided:

	* "dragstart" and "dragfinish" are sent for pointer moves that exceed a
		certain threshhold.

	* "drag" and "drop" are sent to the original target of the pointer move, to
		provide information about the item being moved over (or released over)
		another element.

	* "dragover" and "dragout" are sent in addition to "over" and "out" while
		there is an active drag.

	* "hold" is generated when the pointer is held down without moving for a
		short period of time (about 200ms).

	* "release" is generated when the pointer is released after being held down,
		or is moved off of the node while still held down.  The target is the
		same as that of the "hold" event.

	* "holdpulse" is generated when the pointer is held down without moving for
		a short period of time; it repeats periodically about once every 200ms.
		Use	this event to trigger an action after a given period of time.  The
		elapsed time is available in the _holdTime_ property.

	* "flick" is generated when the user flicks the pointer quickly.  This event
		provides flick velocity data through the properties _xVelocity_
		(velocity with respect to the horizontal axis) and _yVelocity_ (velocity
		with respect to the vertical axis).

	Note: On the Android platform, the "touchmove" event must be prevented via
	_inEvent.preventDefault()_, or the Enyo dragging system will not function
	correctly.
*/

//* @protected
enyo.dispatcher.features.push(
	function(e) {
		// NOTE: beware of properties in enyo.gesture inadvertently mapped to event types
		if (enyo.gesture.drag[e.type]) {
			return enyo.gesture.drag[e.type](e);
		}
	}
);

//* @public
enyo.gesture.drag = {
	//* @protected
	hysteresisSquared: 16,
	holdPulseDelay: 200,
	trackCount: 5,
	minFlick: 0.1,
	minTrack: 8,
	down: function(e) {
		// tracking if the mouse is down
		//console.log("tracking ON");
		// Note: 'tracking' flag indicates interest in mousemove, it's turned off
		// on mouseup
		// make sure to stop dragging in case the up event was not received.
		this.stopDragging(e);
		this.cancelHold();
		this.target = e.target;
		this.startTracking(e);
		this.beginHold(e);
	},
	move: function(e) {
		if (this.tracking) {
			this.track(e);
			// If the mouse is not down and we're tracking a drag, abort.
			// this error condition can occur on IE/Webkit after interaction with a scrollbar.
			if (!e.which) {
				this.stopDragging(e);
				this.cancelHold();
				this.tracking = false;
				//console.log("enyo.gesture.drag: mouse must be down to drag.");
				return;
			}
			if (this.dragEvent) {
				this.sendDrag(e);
			} else if (this.dy*this.dy + this.dx*this.dx >= this.hysteresisSquared) {
				this.sendDragStart(e);
				this.cancelHold();
			}
		}
	},
	up: function(e) {
		this.endTracking(e);
		this.stopDragging(e);
		this.cancelHold();
	},
	leave: function(e) {
		if (this.dragEvent) {
			this.sendDragOut(e);
		}
	},
	stopDragging: function(e) {
		if (this.dragEvent) {
			this.sendDrop(e);
			var handled = this.sendDragFinish(e);
			this.dragEvent = null;
			return handled;
		}
	},
	makeDragEvent: function(inType, inTarget, inEvent, inInfo) {
		var adx = Math.abs(this.dx), ady = Math.abs(this.dy);
		var h = adx > ady;
		// suggest locking if off-axis < 22.5 degrees
		var l = (h ? ady/adx : adx/ady) < 0.414;
		var e = {
			type: inType,
			dx: this.dx,
			dy: this.dy,
			ddx: this.dx - this.lastDx,
			ddy: this.dy - this.lastDy,
			xDirection: this.xDirection,
			yDirection: this.yDirection,
			pageX: inEvent.pageX,
			pageY: inEvent.pageY,
			clientX: inEvent.clientX,
			clientY: inEvent.clientY,
			horizontal: h,
			vertical: !h,
			lockable: l,
			target: inTarget,
			dragInfo: inInfo,
			ctrlKey: inEvent.ctrlKey,
			altKey: inEvent.altKey,
			metaKey: inEvent.metaKey,
			shiftKey: inEvent.shiftKey,
			srcEvent: inEvent.srcEvent
		};
		//Fix for IE8, which doesn't include pageX and pageY properties
		if(enyo.platform.ie==8 && e.target) {
			e.pageX = e.clientX + e.target.scrollLeft;
			e.pageY = e.clientY + e.target.scrollTop;
		}
		e.preventDefault = enyo.gesture.preventDefault;
		e.disablePrevention = enyo.gesture.disablePrevention;
		return e;
	},
	sendDragStart: function(e) {
		//console.log("dragstart");
		this.dragEvent = this.makeDragEvent("dragstart", this.target, e);
		enyo.dispatch(this.dragEvent);
	},
	sendDrag: function(e) {
		//console.log("sendDrag to " + this.dragEvent.target.id + ", over to " + e.target.id);
		// send dragOver event to the standard event target
		var synth = this.makeDragEvent("dragover", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
		// send drag event to the drag source
		synth.type = "drag";
		synth.target = this.dragEvent.target;
		enyo.dispatch(synth);
	},
	sendDragFinish: function(e) {
		//console.log("dragfinish");
		var synth = this.makeDragEvent("dragfinish", this.dragEvent.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap && e.preventTap();
		};
		enyo.dispatch(synth);
	},
	sendDragOut: function(e) {
		var synth = this.makeDragEvent("dragout", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
	},
	sendDrop: function(e) {
		var synth = this.makeDragEvent("drop", e.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap && e.preventTap();
		};
		enyo.dispatch(synth);
	},
	startTracking: function(e) {
		this.tracking = true;
		// note: use clientX/Y to be compatible with ie8
		this.px0 = e.clientX;
		this.py0 = e.clientY;
		this.flickInfo = {startEvent: e, moves: []};
		this.track(e);
	},
	track: function(e) {
		this.lastDx = this.dx;
		this.lastDy = this.dy;
		this.dx = e.clientX - this.px0;
		this.dy = e.clientY - this.py0;
		this.xDirection = this.calcDirection(this.dx - this.lastDx, 0);
		this.yDirection = this.calcDirection(this.dy - this.lastDy, 0);
		//
		var ti = this.flickInfo;
		ti.moves.push({
			x: e.clientX,
			y: e.clientY,
			t: enyo.now()
		});
		// track specified # of points
		if (ti.moves.length > this.trackCount) {
			ti.moves.shift();
		}
	},
	endTracking: function(e) {
		this.tracking = false;
		var ti = this.flickInfo;
		var moves = ti && ti.moves;
		if (moves && moves.length > 1) {
			// note: important to use up time to reduce flick
			// velocity based on time between move and up.
			var l = moves[moves.length-1];
			var n = enyo.now();
			// take the greatest of flick between each tracked move and last move
			for (var i=moves.length-2, dt=0, x1=0, y1=0, x=0, y=0, sx=0, sy=0, m; m=moves[i]; i--) {
				// this flick (this move - last move) / (this time - last time)
				dt = n - m.t;
				x1 = (l.x - m.x) / dt;
				y1 = (l.y - m.y) / dt;
				// establish flick direction
				sx = sx || (x1 < 0 ? -1 : (x1 > 0 ? 1 : 0));
				sy = sy || (y1 < 0 ? -1 : (y1 > 0 ? 1 : 0));
				// if either axis is a greater flick than previously recorded use this one
				if ((x1 * sx > x * sx) || (y1 * sy > y * sy)) {
					x = x1;
					y = y1;
				}
			}
			var v = Math.sqrt(x*x + y*y);
			if (v > this.minFlick) {
				// generate the flick using the start event so it has those coordinates
				this.sendFlick(ti.startEvent, x, y, v);
			}
		}
		this.flickInfo = null;
	},
	calcDirection: function(inNum, inDefault) {
		return inNum > 0 ? 1 : (inNum < 0 ? -1 : inDefault);
	},
	beginHold: function(e) {
		this.holdStart = enyo.now();
		this.holdJob = setInterval(enyo.bind(this, "sendHoldPulse", e), this.holdPulseDelay);
	},
	cancelHold: function() {
		clearInterval(this.holdJob);
		this.holdJob = null;
		if (this.sentHold) {
			this.sentHold = false;
			this.sendRelease(this.holdEvent);
		}
	},
	sendHoldPulse: function(inEvent) {
		if (!this.sentHold) {
			this.sentHold = true;
			this.sendHold(inEvent);
		}
		var e = enyo.gesture.makeEvent("holdpulse", inEvent);
		e.holdTime = enyo.now() - this.holdStart;
		enyo.dispatch(e);
	},
	sendHold: function(inEvent) {
		this.holdEvent = inEvent;
		var e = enyo.gesture.makeEvent("hold", inEvent);
		enyo.dispatch(e);
	},
	sendRelease: function(inEvent) {
		var e = enyo.gesture.makeEvent("release", inEvent);
		enyo.dispatch(e);
	},
	sendFlick: function(inEvent, inX, inY, inV) {
		var e = enyo.gesture.makeEvent("flick", inEvent);
		e.xVelocity = inX;
		e.yVelocity = inY;
		e.velocity = inV;
		enyo.dispatch(e);
	}
};
<commit_msg>Fixes ENYO-429; slighly updated docs for "release" event<commit_after>/**
	Enyo supports a cross-platform set of drag events.  These events allow users
	to write a single set of event handlers for applications that run on both
	mobile and desktop platforms.

	The following events are provided:

	* "dragstart" and "dragfinish" are sent for pointer moves that exceed a
		certain threshhold.

	* "drag" and "drop" are sent to the original target of the pointer move, to
		provide information about the item being moved over (or released over)
		another element.

	* "dragover" and "dragout" are sent in addition to "over" and "out" while
		there is an active drag.

	* "hold" is generated when the pointer is held down without moving for a
		short period of time (about 200ms).

	* "release" is generated when the pointer is released after being held down,
		or is moved off of the node while still held down, but before any potential dragstart event.
		The target is the same as that of the "hold" event.

	* "holdpulse" is generated when the pointer is held down without moving for
		a short period of time; it repeats periodically about once every 200ms.
		Use	this event to trigger an action after a given period of time.  The
		elapsed time is available in the _holdTime_ property.

	* "flick" is generated when the user flicks the pointer quickly.  This event
		provides flick velocity data through the properties _xVelocity_
		(velocity with respect to the horizontal axis) and _yVelocity_ (velocity
		with respect to the vertical axis).

	Note: On the Android platform, the "touchmove" event must be prevented via
	_inEvent.preventDefault()_, or the Enyo dragging system will not function
	correctly.
*/

//* @protected
enyo.dispatcher.features.push(
	function(e) {
		// NOTE: beware of properties in enyo.gesture inadvertently mapped to event types
		if (enyo.gesture.drag[e.type]) {
			return enyo.gesture.drag[e.type](e);
		}
	}
);

//* @public
enyo.gesture.drag = {
	//* @protected
	hysteresisSquared: 16,
	holdPulseDelay: 200,
	trackCount: 5,
	minFlick: 0.1,
	minTrack: 8,
	down: function(e) {
		// tracking if the mouse is down
		//console.log("tracking ON");
		// Note: 'tracking' flag indicates interest in mousemove, it's turned off
		// on mouseup
		// make sure to stop dragging in case the up event was not received.
		this.stopDragging(e);
		this.cancelHold();
		this.target = e.target;
		this.startTracking(e);
		this.beginHold(e);
	},
	move: function(e) {
		if (this.tracking) {
			this.track(e);
			// If the mouse is not down and we're tracking a drag, abort.
			// this error condition can occur on IE/Webkit after interaction with a scrollbar.
			if (!e.which) {
				this.stopDragging(e);
				this.cancelHold();
				this.tracking = false;
				//console.log("enyo.gesture.drag: mouse must be down to drag.");
				return;
			}
			if (this.dragEvent) {
				this.sendDrag(e);
			} else if (this.dy*this.dy + this.dx*this.dx >= this.hysteresisSquared) {
				this.sendDragStart(e);
				this.cancelHold();
			}
		}
	},
	up: function(e) {
		this.endTracking(e);
		this.stopDragging(e);
		this.cancelHold();
	},
	leave: function(e) {
		if (this.dragEvent) {
			this.sendDragOut(e);
		}
	},
	stopDragging: function(e) {
		if (this.dragEvent) {
			this.sendDrop(e);
			var handled = this.sendDragFinish(e);
			this.dragEvent = null;
			return handled;
		}
	},
	makeDragEvent: function(inType, inTarget, inEvent, inInfo) {
		var adx = Math.abs(this.dx), ady = Math.abs(this.dy);
		var h = adx > ady;
		// suggest locking if off-axis < 22.5 degrees
		var l = (h ? ady/adx : adx/ady) < 0.414;
		var e = {
			type: inType,
			dx: this.dx,
			dy: this.dy,
			ddx: this.dx - this.lastDx,
			ddy: this.dy - this.lastDy,
			xDirection: this.xDirection,
			yDirection: this.yDirection,
			pageX: inEvent.pageX,
			pageY: inEvent.pageY,
			clientX: inEvent.clientX,
			clientY: inEvent.clientY,
			horizontal: h,
			vertical: !h,
			lockable: l,
			target: inTarget,
			dragInfo: inInfo,
			ctrlKey: inEvent.ctrlKey,
			altKey: inEvent.altKey,
			metaKey: inEvent.metaKey,
			shiftKey: inEvent.shiftKey,
			srcEvent: inEvent.srcEvent
		};
		//Fix for IE8, which doesn't include pageX and pageY properties
		if(enyo.platform.ie==8 && e.target) {
			e.pageX = e.clientX + e.target.scrollLeft;
			e.pageY = e.clientY + e.target.scrollTop;
		}
		e.preventDefault = enyo.gesture.preventDefault;
		e.disablePrevention = enyo.gesture.disablePrevention;
		return e;
	},
	sendDragStart: function(e) {
		//console.log("dragstart");
		this.dragEvent = this.makeDragEvent("dragstart", this.target, e);
		enyo.dispatch(this.dragEvent);
	},
	sendDrag: function(e) {
		//console.log("sendDrag to " + this.dragEvent.target.id + ", over to " + e.target.id);
		// send dragOver event to the standard event target
		var synth = this.makeDragEvent("dragover", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
		// send drag event to the drag source
		synth.type = "drag";
		synth.target = this.dragEvent.target;
		enyo.dispatch(synth);
	},
	sendDragFinish: function(e) {
		//console.log("dragfinish");
		var synth = this.makeDragEvent("dragfinish", this.dragEvent.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap && e.preventTap();
		};
		enyo.dispatch(synth);
	},
	sendDragOut: function(e) {
		var synth = this.makeDragEvent("dragout", e.target, e, this.dragEvent.dragInfo);
		enyo.dispatch(synth);
	},
	sendDrop: function(e) {
		var synth = this.makeDragEvent("drop", e.target, e, this.dragEvent.dragInfo);
		synth.preventTap = function() {
			e.preventTap && e.preventTap();
		};
		enyo.dispatch(synth);
	},
	startTracking: function(e) {
		this.tracking = true;
		// note: use clientX/Y to be compatible with ie8
		this.px0 = e.clientX;
		this.py0 = e.clientY;
		this.flickInfo = {startEvent: e, moves: []};
		this.track(e);
	},
	track: function(e) {
		this.lastDx = this.dx;
		this.lastDy = this.dy;
		this.dx = e.clientX - this.px0;
		this.dy = e.clientY - this.py0;
		this.xDirection = this.calcDirection(this.dx - this.lastDx, 0);
		this.yDirection = this.calcDirection(this.dy - this.lastDy, 0);
		//
		var ti = this.flickInfo;
		ti.moves.push({
			x: e.clientX,
			y: e.clientY,
			t: enyo.now()
		});
		// track specified # of points
		if (ti.moves.length > this.trackCount) {
			ti.moves.shift();
		}
	},
	endTracking: function(e) {
		this.tracking = false;
		var ti = this.flickInfo;
		var moves = ti && ti.moves;
		if (moves && moves.length > 1) {
			// note: important to use up time to reduce flick
			// velocity based on time between move and up.
			var l = moves[moves.length-1];
			var n = enyo.now();
			// take the greatest of flick between each tracked move and last move
			for (var i=moves.length-2, dt=0, x1=0, y1=0, x=0, y=0, sx=0, sy=0, m; m=moves[i]; i--) {
				// this flick (this move - last move) / (this time - last time)
				dt = n - m.t;
				x1 = (l.x - m.x) / dt;
				y1 = (l.y - m.y) / dt;
				// establish flick direction
				sx = sx || (x1 < 0 ? -1 : (x1 > 0 ? 1 : 0));
				sy = sy || (y1 < 0 ? -1 : (y1 > 0 ? 1 : 0));
				// if either axis is a greater flick than previously recorded use this one
				if ((x1 * sx > x * sx) || (y1 * sy > y * sy)) {
					x = x1;
					y = y1;
				}
			}
			var v = Math.sqrt(x*x + y*y);
			if (v > this.minFlick) {
				// generate the flick using the start event so it has those coordinates
				this.sendFlick(ti.startEvent, x, y, v);
			}
		}
		this.flickInfo = null;
	},
	calcDirection: function(inNum, inDefault) {
		return inNum > 0 ? 1 : (inNum < 0 ? -1 : inDefault);
	},
	beginHold: function(e) {
		this.holdStart = enyo.now();
		this.holdJob = setInterval(enyo.bind(this, "sendHoldPulse", e), this.holdPulseDelay);
	},
	cancelHold: function() {
		clearInterval(this.holdJob);
		this.holdJob = null;
		if (this.sentHold) {
			this.sentHold = false;
			this.sendRelease(this.holdEvent);
		}
	},
	sendHoldPulse: function(inEvent) {
		if (!this.sentHold) {
			this.sentHold = true;
			this.sendHold(inEvent);
		}
		var e = enyo.gesture.makeEvent("holdpulse", inEvent);
		e.holdTime = enyo.now() - this.holdStart;
		enyo.dispatch(e);
	},
	sendHold: function(inEvent) {
		this.holdEvent = inEvent;
		var e = enyo.gesture.makeEvent("hold", inEvent);
		enyo.dispatch(e);
	},
	sendRelease: function(inEvent) {
		var e = enyo.gesture.makeEvent("release", inEvent);
		enyo.dispatch(e);
	},
	sendFlick: function(inEvent, inX, inY, inV) {
		var e = enyo.gesture.makeEvent("flick", inEvent);
		e.xVelocity = inX;
		e.yVelocity = inY;
		e.velocity = inV;
		enyo.dispatch(e);
	}
};
<|endoftext|>


<commit_before>/* ***************************************
 * CLASS: PLUGIN
 * ***************************************/
 class Plugin 	extends Dom_FILTER
 {
	constructor ( plugin )
	{	let self = super();

		('undefined' != typeof $.plugin.list && $.plugin.list.length >= 1 ) &&
		$.plugin.list.forEach(( element ) =>{

			$.forIn(element,(index, value)=>{

				var execute = value.toString().replace("\n","");

				let pos1 = execute.indexOf("(");
				let pos2 = execute.indexOf(")");
				var data = execute.substr(pos1+1, pos2+pos1-1);

				execute = execute.replace("("+data+")=>{","");
				execute = execute.substr(0, execute.length-1);

				data = data.replace(/\s+|\s+/g, "");

				window.self=self;

				let nFun = new Function(data, execute);

				self[index]=nFun;

			})

		});

		return self;
	}
}<commit_msg>Delete 08_Plungin.js<commit_after><|endoftext|>