<commit_before>'use strict';

starChat.View = (function () {
    var View = function (sessionClass) {
        this.sessionClass_ = sessionClass;

        initialize(this);
    };
    function initialize(self) {
        self.session_ = new self.sessionClass_();

        // TODO: Model に相当するクラスを作る?
        // TODO: いずれこれらの変数も private (_ 終わり) にする
        self.channels = [];
        self.channelName = '';
        self.newMessages = {};
        self.messageScrollTops = {};
        self.userNames = {};
        self.isEdittingChannels = false;

        self.lastChannelName_ = '';
        self.messageIdsAlreadyInSection_ = {};
        self.dirtyFlags_ = {};
        self.startTime_ = null;
        self.endTime_ = null;
        self.oldMessages_ = {};
    }
    var updateViewChannels = (function () {
        var lastSessionId = 0;
        var cachedChannels = [];
        return function (self) {
            // channels
            var channels = self.channels.sort(function (a, b) {
                if (a.name > b.name) {
                    return 1;
                }
                if (a.name < b.name) {
                    return -1;
                }
                return 0;
            });
            if (self.channelName) {
                self.dirtyFlags_[self.channelName] = false;
            }
            (function () {
                var ul = $('#channels ul');
                ul.empty();
                channels.forEach(function (channel) {
                    var a = $('');
                    var name = channel.name;
                    var href = '#channels/' + encodeURIComponent(channel.name);
                    a.attr('href', href);
                    a.toggleClass('dirty', self.dirtyFlags_[name]);
                    a.text(name);
                    var delLink = $('').click(function () {
                        return self.clickChannelDel_(channel);
                    });
                    var li = $('

').append(a).append(delLink);
                    ul.append(li);
                });
                cachedChannels = [];
                for (var i = 0; i < channels.length; i++) {
                    cachedChannels[i] = channels[i];
                }
                lastSessionId = self.session_.id();
            })();
            if (self.isEdittingChannels) {
                $('#channels li img[data-tool-id="delete"]').show();
            } else {
                $('#channels li img[data-tool-id="delete"]').hide();
            }
        }
    })();
    function getSectionElement(self) {
        if (!self.channelName) {
            return null;
        }
        var sections = $('#messages > section').filter(function (i) {
            return $(this).attr('data-channel-name') === self.channelName &&
                (!self.isShowingOldLogs() &&
                 !$(this).attr('data-start-time') &&
                 !$(this).attr('data-end-time')) ||
                (self.isShowingOldLogs() &&
                 parseInt($(this).attr('data-start-time')) === self.startTime_ &&
                 parseInt($(this).attr('data-end-time'))   === self.endTime_);
        });
        if (sections.length === 1) {
            var section = sections;
            section.find('input[name="year"]').val('');
            section.find('input[name="month"]').val('');
            section.find('input[name="day"]').val('');
            return section;
        }
        if (2 <= sections.length) {
            throw 'invalid sections';
        }
        var section = $('

');
        var channelName = self.channelName;
        section.attr('data-channel-name', channelName);
        if (self.isShowingOldLogs()) {
            section.attr('data-start-time', self.startTime_);
            section.attr('data-end-time',   self.endTime_);
        }
        if (!self.isShowingOldLogs()) {
            section.scroll(function () {
                self.messageScrollTops[channelName] = section.scrollTop();
            });
        }
        var inputYear   = $('<input type="number" name="year" min="0" max="9999" value="" />');
        var inputMonth  = $('<input type="number" name="month" min="1" max="12" value="" />');
        var inputDay    = $('<input type="number" name="day" min="1" max="31" value="" />');
        var inputSubmit = $('<input type="submit" value="Show" />');
        var oldLogsP    = $('

').append('Old Logs: ');
        oldLogsP.append(inputYear).append('-').append(inputMonth).append('-').append(inputDay);
        oldLogsP.append(inputSubmit);
        var oldLogsForm = $('<form action="." method="get"></form>');
        oldLogsForm.append(oldLogsP);
        inputSubmit.click(function () {
            var year  = inputYear.val();
            var month = inputMonth.val();
            var day   = inputDay.val();
            var startTime = (new Date(year, month - 1, day)).getTime() / 1000;
            var endTime   = startTime + 60 * 60 * 24;
            var fragment = 'channels/' + encodeURIComponent(channelName) +
                '/old_logs/by_time_span/' +
                encodeURIComponent(startTime) + ',' + encodeURIComponent(endTime);
            location.hash = fragment;
            return false;
        });
        section.append(oldLogsForm);
        $('#messages h2').after(section);
        return section;
    }
    function messageToElement(message) {
        var messageSection = $('

');
        messageSection.addClass('message');
        var userNameP = $('

').text(message.user_name);
        userNameP.addClass('userName');
        messageSection.append(userNameP);
        var bodyP = $('

').text(message.body);
        bodyP.addClass('body');
        messageSection.append(bodyP);
        var time = new Date();
        time.setTime(message.created_at * 1000);
        var h = time.getHours() + '';
        var m = time.getMinutes() + '';
        if (h.length < 2) {
            h = '0' + h;
        }
        if (m.length < 2) {
            m = '0' + m;
        }
        var timeStr = h + ':' + m;
        var createdAt = $('<time></time>').text(timeStr);
        createdAt.addClass('createdAt');
        createdAt.attr('data-unix-time', message.created_at)
        messageSection.append(createdAt);
        messageSection.attr('data-message-id', message.id);
        return messageSection;
    }
    function updateViewMessages(self) {
        if (self.channelName) {
            if (self.isShowingOldLogs()) {
                var d = new Date(self.startTime_ * 1000);
                if ((self.endTime_ - self.startTime_) === 60 * 60 * 24 &&
                    d.getHours() === 0 &&
                    d.getMinutes() === 0 &&
                    d.getSeconds() === 0) {
                    var startTime = starChat.toISO8601(new Date(self.startTime_ * 1000), 'date');
                    var oldLogs = '(Old Logs: ' + startTime + ')';
                } else {
                    var startTime = starChat.toISO8601(new Date(self.startTime_ * 1000));
                    var endTime   = starChat.toISO8601(new Date(self.endTime_   * 1000));
                    var oldLogs = '(Old Logs: ' + startTime + '/' + endTime + ')';
                }
                $('#messages h2').text(self.channelName + ' ' + oldLogs);
            } else {
                $('#messages h2').text(self.channelName);
            }
        } else {
            $('#messages h2').text("\u00a0");
        }
        if (!self.isShowingOldLogs()) {
            $('#messages > section').filter(function (i) {
                return $(this).attr('data-start-time') || $(this).attr('data-end-time');
            }).remove();
        }
        if (!self.channelName) {
            $('#messages > section').hide();
            self.lastChannelName_ = '';
            return;
        }
        var section = getSectionElement(self);
        $('#messages > section').each(function (i) {
            var e = $(this);
            if (e.attr('data-channel-name') === self.channelName &&
                (!self.isShowingOldLogs() ||
                 (parseInt(e.attr('data-start-time')) === self.startTime_ &&
                  parseInt(e.attr('data-end-time'))   === self.endTime_))) {
                e.show();
            } else {
                e.hide();
            }
        });
        // TODO: sort by id
        if (!self.isShowingOldLogs()) {
            if (self.channelName in self.newMessages) {
                var msgs = self.newMessages[self.channelName];
                msgs.forEach(function (message) {
                    if (self.messageIdsAlreadyInSection_[message.id]) {
                        return;
                    }
                    self.messageIdsAlreadyInSection_[message.id] = true;
                    section.append(messageToElement(message));
                });
                self.newMessages[self.channelName] = [];
            }
        } else {
            var key = self.startTime_ + '_' + self.endTime_;
            if (self.channelName in self.oldMessages_ &&
                key in self.oldMessages_[self.channelName]) {
                // TODO: Refactoring
                section.find('section.message').remove();
                var msgs = self.oldMessages_[self.channelName][key];
                msgs.forEach(function (message) {
                    section.append(messageToElement(message));
                });
            }
        }
        if (!self.isShowingOldLogs()) {
            if (self.lastChannelName_ === self.channelName) {
                var isBottom =
                    section.get(0).scrollHeight - section.scrollTop() ===
                    section.outerHeight();
                if (isBottom) {
                    section.animate({scrollTop: section.get(0).scrollHeight});
                }
            } else {
                if (!self.lastChannelName_ ||
                    !(self.channelName in self.messageScrollTops)) {
                    section.scrollTop(section.get(0).scrollHeight);
                } else {
                    section.scrollTop(self.messageScrollTops[self.channelName]);
                }
            }
            self.messageScrollTops[self.channelName] = section.scrollTop();
            self.lastChannelName_ = self.channelName;
        }
    }
    function updateViewUsers(self) {
        var userNamesObj = self.userNames[self.channelName];
        if (!userNamesObj) {
            userNamesObj = {};
        }
        var userNames = Object.keys(userNamesObj).sort();
        var ul = $('#users ul');
        ul.empty();
        userNames.forEach(function (userName) {
            var li = $('

');
            li.text(userName);
            ul.append(li);
        });
    }
    View.prototype.update = function () {
        if (this.session_.isLoggedIn()) {
            $('#logInForm').hide();
            $('#logOutLink span').text(this.session_.userName());
            $('#logOutLink').show();
            $('#main input').removeAttr('disabled');
            if (this.channelName && !this.isShowingOldLogs()) {
                $('#postMessageForm input').removeAttr('disabled');
            } else {
                $('#postMessageForm input').attr('disabled', 'disabled');
            }
        } else {
            $('#logInForm').show();
            $('#logOutLink').hide();
            $('#main input').attr('disabled', 'disabled');
        }
        updateViewChannels(this);
        updateViewMessages(this);
        updateViewUsers(this);
        $(window).resize();
        $('img[data-image-icon-name]').each(function () {
            var e = $(this);
            if (e.attr('src')) {
                return true;
            }
            var iconName = e.attr('data-image-icon-name');
            e.attr('src', starChat.Icons[iconName]);
        });
    };
    View.prototype.logIn = function (userName, password) {
        this.session_ = new this.sessionClass_($.now, userName, password);
    };
    View.prototype.logOut = function () {
        this.session_ = new this.sessionClass_();
        initialize(this);
    };
    View.prototype.session = function () {
        return this.session_;
    };
    View.prototype.setDirtyFlag = function (channelName, value) {
        this.dirtyFlags_[channelName] = value;
    };
    // TODO: 関数名直すべき?
    View.prototype.clickChannelDel = function (func) {
        this.clickChannelDel_ = func;
        return this;
    };
    View.prototype.resetTimeSpan = function () {
        this.startTime_ = null;
        this.endTime_   = null;
    };
    View.prototype.setTimeSpan = function (startTime, endTime) {
        this.startTime_ = startTime;
        this.endTime_   = endTime;
    };
    View.prototype.isShowingOldLogs = function () {
        return $.isNumeric(this.startTime_) && $.isNumeric(this.endTime_);
    };
    View.prototype.setOldMessages = function (channelName, startTime, endTime, messages) {
        if (!(channelName in this.oldMessages_)) {
            this.oldMessages_[channelName] = {};
        }
        var key = startTime + '_' + endTime;
        this.oldMessages_[channelName][key] = messages;
    };
    return View;
})();
<commit_msg>Refactoring<commit_after>'use strict';

starChat.View = (function () {
    var View = function (sessionClass) {
        this.sessionClass_ = sessionClass;

        initialize(this);
    };
    function initialize(self) {
        self.session_ = new self.sessionClass_();

        // TODO: Model に相当するクラスを作る?
        // TODO: いずれこれらの変数も private (_ 終わり) にする
        self.channels = [];
        self.channelName = '';
        self.newMessages = {};
        self.messageScrollTops = {};
        self.userNames = {};
        self.isEdittingChannels = false;

        self.lastChannelName_ = '';
        self.messageIdsAlreadyInSection_ = {};
        self.dirtyFlags_ = {};
        self.startTime_ = null;
        self.endTime_ = null;
        self.oldMessages_ = {};
    }
    var updateViewChannels = (function () {
        var lastSessionId = 0;
        var cachedChannels = [];
        return function (self) {
            // channels
            var channels = self.channels.sort(function (a, b) {
                if (a.name > b.name) {
                    return 1;
                }
                if (a.name < b.name) {
                    return -1;
                }
                return 0;
            });
            if (self.channelName) {
                self.dirtyFlags_[self.channelName] = false;
            }
            (function () {
                var ul = $('#channels ul');
                ul.empty();
                channels.forEach(function (channel) {
                    var a = $('');
                    var name = channel.name;
                    var href = '#channels/' + encodeURIComponent(channel.name);
                    a.attr('href', href);
                    a.toggleClass('dirty', self.dirtyFlags_[name]);
                    a.text(name);
                    var delLink = $('').click(function () {
                        return self.clickChannelDel_(channel);
                    });
                    var li = $('

').append(a).append(delLink);
                    ul.append(li);
                });
                cachedChannels = [];
                for (var i = 0; i < channels.length; i++) {
                    cachedChannels[i] = channels[i];
                }
                lastSessionId = self.session_.id();
            })();
            if (self.isEdittingChannels) {
                $('#channels li img[data-tool-id="delete"]').show();
            } else {
                $('#channels li img[data-tool-id="delete"]').hide();
            }
        }
    })();
    function getSectionElement(self) {
        if (!self.channelName) {
            return null;
        }
        var sections = $('#messages > section').filter(function (i) {
            return $(this).attr('data-channel-name') === self.channelName &&
                (!self.isShowingOldLogs() &&
                 !$(this).attr('data-start-time') &&
                 !$(this).attr('data-end-time')) ||
                (self.isShowingOldLogs() &&
                 parseInt($(this).attr('data-start-time')) === self.startTime_ &&
                 parseInt($(this).attr('data-end-time'))   === self.endTime_);
        });
        if (sections.length === 1) {
            var section = sections;
            section.find('input[name="year"]').val('');
            section.find('input[name="month"]').val('');
            section.find('input[name="day"]').val('');
            return section;
        }
        if (2 <= sections.length) {
            throw 'invalid sections';
        }
        var section = $('

');
        var channelName = self.channelName;
        section.attr('data-channel-name', channelName);
        if (self.isShowingOldLogs()) {
            section.attr('data-start-time', self.startTime_);
            section.attr('data-end-time',   self.endTime_);
        }
        if (!self.isShowingOldLogs()) {
            section.scroll(function () {
                self.messageScrollTops[channelName] = section.scrollTop();
            });
        }
        var inputYear   = $('<input type="number" name="year" min="0" max="9999" value="" />');
        var inputMonth  = $('<input type="number" name="month" min="1" max="12" value="" />');
        var inputDay    = $('<input type="number" name="day" min="1" max="31" value="" />');
        var inputSubmit = $('<input type="submit" value="Show" />');
        var oldLogsP    = $('

').append('Old Logs: ');
        oldLogsP.append(inputYear).append('-').append(inputMonth).append('-').append(inputDay);
        oldLogsP.append(inputSubmit);
        var oldLogsForm = $('<form action="." method="get"></form>');
        oldLogsForm.append(oldLogsP);
        inputSubmit.click(function () {
            var year  = inputYear.val();
            var month = inputMonth.val();
            var day   = inputDay.val();
            var startTime = (new Date(year, month - 1, day)).getTime() / 1000;
            var endTime   = startTime + 60 * 60 * 24;
            var fragment = 'channels/' + encodeURIComponent(channelName) +
                '/old_logs/by_time_span/' +
                encodeURIComponent(startTime) + ',' + encodeURIComponent(endTime);
            location.hash = fragment;
            return false;
        });
        section.append(oldLogsForm);
        $('#messages h2').after(section);
        return section;
    }
    function messageToElement(message) {
        var messageSection = $('

');
        messageSection.addClass('message');
        var userNameP = $('

').text(message.user_name);
        userNameP.addClass('userName');
        messageSection.append(userNameP);
        var bodyP = $('

').text(message.body);
        bodyP.addClass('body');
        messageSection.append(bodyP);
        var time = new Date();
        time.setTime(message.created_at * 1000);
        var h = time.getHours() + '';
        var m = time.getMinutes() + '';
        if (h.length < 2) {
            h = '0' + h;
        }
        if (m.length < 2) {
            m = '0' + m;
        }
        var timeStr = h + ':' + m;
        var createdAt = $('<time></time>').text(timeStr);
        createdAt.addClass('createdAt');
        createdAt.attr('data-unix-time', message.created_at)
        messageSection.append(createdAt);
        messageSection.attr('data-message-id', message.id);
        return messageSection;
    }
    function updateViewMessages(self) {
        if (self.channelName) {
            if (self.isShowingOldLogs()) {
                var d = new Date(self.startTime_ * 1000);
                if ((self.endTime_ - self.startTime_) === 60 * 60 * 24 &&
                    d.getHours() === 0 &&
                    d.getMinutes() === 0 &&
                    d.getSeconds() === 0) {
                    var startTime = starChat.toISO8601(new Date(self.startTime_ * 1000), 'date');
                    var oldLogs = '(Old Logs: ' + startTime + ')';
                } else {
                    var startTime = starChat.toISO8601(new Date(self.startTime_ * 1000));
                    var endTime   = starChat.toISO8601(new Date(self.endTime_   * 1000));
                    var oldLogs = '(Old Logs: ' + startTime + '/' + endTime + ')';
                }
                $('#messages h2').text(self.channelName + ' ' + oldLogs);
            } else {
                $('#messages h2').text(self.channelName);
            }
        } else {
            $('#messages h2').text("\u00a0");
        }
        if (!self.isShowingOldLogs()) {
            $('#messages > section').filter(function (i) {
                return $(this).attr('data-start-time') || $(this).attr('data-end-time');
            }).remove();
        }
        if (!self.channelName) {
            $('#messages > section').hide();
            self.lastChannelName_ = '';
            return;
        }
        var section = getSectionElement(self);
        $('#messages > section').each(function (i) {
            var e = $(this);
            if (e.attr('data-channel-name') === self.channelName &&
                (!self.isShowingOldLogs() ||
                 (parseInt(e.attr('data-start-time')) === self.startTime_ &&
                  parseInt(e.attr('data-end-time'))   === self.endTime_))) {
                e.show();
            } else {
                e.hide();
            }
        });
        // TODO: sort by id
        if (!self.isShowingOldLogs()) {
            if (self.channelName in self.newMessages) {
                var msgs = self.newMessages[self.channelName];
                msgs.forEach(function (message) {
                    if (self.messageIdsAlreadyInSection_[message.id]) {
                        return;
                    }
                    self.messageIdsAlreadyInSection_[message.id] = true;
                    section.append(messageToElement(message));
                });
                self.newMessages[self.channelName] = [];
            }
        } else {
            var key = self.startTime_ + '_' + self.endTime_;
            if (self.channelName in self.oldMessages_ &&
                key in self.oldMessages_[self.channelName]) {
                // TODO: Refactoring
                section.find('section.message').remove();
                var msgs = self.oldMessages_[self.channelName][key];
                msgs.forEach(function (message) {
                    section.append(messageToElement(message));
                });
            }
        }
        if (!self.isShowingOldLogs()) {
            if (self.lastChannelName_ === self.channelName) {
                var isBottom =
                    section.get(0).scrollHeight - section.scrollTop() ===
                    section.outerHeight();
                if (isBottom) {
                    section.animate({scrollTop: section.get(0).scrollHeight});
                }
            } else {
                if (!self.lastChannelName_ ||
                    !(self.channelName in self.messageScrollTops)) {
                    section.scrollTop(section.get(0).scrollHeight);
                } else {
                    section.scrollTop(self.messageScrollTops[self.channelName]);
                }
            }
            self.messageScrollTops[self.channelName] = section.scrollTop();
            self.lastChannelName_ = self.channelName;
        }
    }
    function updateViewUsers(self) {
        var userNamesObj = self.userNames[self.channelName];
        if (!userNamesObj) {
            userNamesObj = {};
        }
        var userNames = Object.keys(userNamesObj).sort();
        var ul = $('#users ul');
        ul.empty();
        userNames.forEach(function (userName) {
            var li = $('

');
            li.text(userName);
            ul.append(li);
        });
    }
    View.prototype.update = function () {
        if (this.session_.isLoggedIn()) {
            $('#logInForm').hide();
            $('#logOutLink span').text(this.session_.userName());
            $('#logOutLink').show();
            $('#main input').removeAttr('disabled');
            if (this.channelName && !this.isShowingOldLogs()) {
                $('#postMessageForm input').removeAttr('disabled');
            } else {
                $('#postMessageForm input').attr('disabled', 'disabled');
            }
        } else {
            $('#logInForm').show();
            $('#logOutLink').hide();
            $('#main input').attr('disabled', 'disabled');
        }
        updateViewChannels(this);
        updateViewMessages(this);
        updateViewUsers(this);
        $('img[data-image-icon-name]').each(function () {
            var e = $(this);
            if (e.attr('src')) {
                return true;
            }
            var iconName = e.attr('data-image-icon-name');
            e.attr('src', starChat.Icons[iconName]);
        });
        $(window).resize();
    };
    View.prototype.logIn = function (userName, password) {
        this.session_ = new this.sessionClass_($.now, userName, password);
    };
    View.prototype.logOut = function () {
        this.session_ = new this.sessionClass_();
        initialize(this);
    };
    View.prototype.session = function () {
        return this.session_;
    };
    View.prototype.setDirtyFlag = function (channelName, value) {
        this.dirtyFlags_[channelName] = value;
    };
    // TODO: 関数名直すべき?
    View.prototype.clickChannelDel = function (func) {
        this.clickChannelDel_ = func;
        return this;
    };
    View.prototype.resetTimeSpan = function () {
        this.startTime_ = null;
        this.endTime_   = null;
    };
    View.prototype.setTimeSpan = function (startTime, endTime) {
        this.startTime_ = startTime;
        this.endTime_   = endTime;
    };
    View.prototype.isShowingOldLogs = function () {
        return $.isNumeric(this.startTime_) && $.isNumeric(this.endTime_);
    };
    View.prototype.setOldMessages = function (channelName, startTime, endTime, messages) {
        if (!(channelName in this.oldMessages_)) {
            this.oldMessages_[channelName] = {};
        }
        var key = startTime + '_' + endTime;
        this.oldMessages_[channelName][key] = messages;
    };
    return View;
})();
<|endoftext|>


<commit_before>'use strict';

angular.module('eMarketApp').directive('shoppingCart', function(User) {
  return {
    templateUrl: 'views/shoppingCart.html',
    restrict: 'E',
    scope: true,
    replace: true,
    link: function(scope, elem) {
      var page = $(elem[0]);
      var shoppingCartList = page.find('#shoppingCartList');

      var cartSelected = null;
      var selectedCartIndex = null;

      scope.cost = 0;
      scope.shipping = 0;

      var computeTotalCostAndShipping = function() {
        scope.cost = window._.reduce(scope.shoppingCarts, function(prevCart, cart) {
          return prevCart.cost + cart.cost;
        });
        scope.shipping = window._.reduce(scope.shoppingCarts, function(prevCart, cart) {
          return prevCart.cost + cart.cost;
        });
      };

      page.on('pagebeforeshow', function() {
        User.me().getList('carts').then(function(carts) {
          scope.shoppingCarts = carts;
          setTimeout(function() {
            shoppingCartList.listview('refresh');
          });
          computeTotalCostAndShipping();
        });
      });

      scope.selectCart = function(cartItem, index) {
        cartSelected = cartItem;
        selectedCartIndex = index;
      };

      scope.deleteCartItem = function() {
        $.mobile.loading('show');
        User.me().one('carts', cartSelected.cartId).remove().then(function() {
          scope.shoppingCarts.splice(selectedCartIndex, 1);
          computeTotalCostAndShipping();
          shoppingCartList.listview('refresh');
          $.mobile.loading('hide');
        });
      };
    }
  };
});
<commit_msg>Fixed shopping cart subtotal<commit_after>'use strict';

angular.module('eMarketApp').directive('shoppingCart', function(User) {
  return {
    templateUrl: 'views/shoppingCart.html',
    restrict: 'E',
    scope: true,
    replace: true,
    link: function(scope, elem) {
      var page = $(elem[0]);
      var shoppingCartList = page.find('#shoppingCartList');

      var cartSelected = null;
      var selectedCartIndex = null;

      scope.cost = 0;
      scope.shipping = 0;

      var computeTotalCostAndShipping = function() {
        window._.each(scope.shoppingCarts, function(cart) {
          scope.cost += cart.productTotalPrice;

        });
       window._.each(scope.shoppingCarts, function(cart) {
         scope.shipping += cart.shippingPrice;
        });
      };

      page.on('pagebeforeshow', function() {
        User.me().getList('carts').then(function(carts) {
          scope.shoppingCarts = carts;
          setTimeout(function() {
            shoppingCartList.listview('refresh');
          });
          computeTotalCostAndShipping();
        });
      });

      scope.selectCart = function(cartItem, index) {
        cartSelected = cartItem;
        selectedCartIndex = index;
      };

      scope.deleteCartItem = function() {
        $.mobile.loading('show');
        User.me().one('carts', cartSelected.cartId).remove().then(function() {
          scope.shoppingCarts.splice(selectedCartIndex, 1);
          computeTotalCostAndShipping();
          shoppingCartList.listview('refresh');
          $.mobile.loading('hide');
        });
      };
    }
  };
});
<|endoftext|>


<commit_before>/*
 * Replaces file-manager in enketo-core.
 */

import store from './store';

import settings from './settings';
import connection from './connection';
import utils from './utils';
import { getFilename } from 'enketo-core/src/js/utils';
import { t } from './translator';
const URL_RE = /[a-zA-Z0-9+-.]+?:\/\//;
let instanceAttachments;

/**
 * Initialize the file manager .
 *
 * @return {*} promise boolean or rejection with Error
 */
function init() {
    return Promise.resolve( true );
}

/**
 * Whether the filemanager is waiting for user permissions
 *
 * @return {boolean} [description]
 */
function isWaitingForPermissions() {
    return false;
}

/**
 * Sets instanceAttachments containing filename:url map
 * to use in getFileUrl
 *
 * @param attachments
 */
function setInstanceAttachments( attachments ) {
    instanceAttachments = attachments;
}
/**
 * Obtains a url that can be used to show a preview of the file when used
 * as a src attribute.
 *
 * @param  {?string|object} subject - File or filename
 * @return {*}         promise url string or rejection with Error
 */
function getFileUrl( subject ) {
    return new Promise( ( resolve, reject ) => {
        if ( !subject ) {
            resolve( null );
        } else if ( typeof subject === 'string' ) {
            if ( subject.startsWith( '/' ) ) {
                resolve( subject );
            } else if ( instanceAttachments && ( Object.prototype.hasOwnProperty.call( instanceAttachments, subject ) ) ) {
                resolve( instanceAttachments[ subject ] );
            } else if ( !store.available ) {
                // e.g. in an online-only edit view
                reject( new Error( 'store not available' ) );
            } else if ( URL_RE.test( subject ) ) {
                // Any URL values are default binary values. These should only occur in offline-capable views,
                // because the form cache module removed the src attributes
                // (which are /urls/like/this/http:// and are caught above this statement)
                store.survey.resource.get( settings.enketoId, subject )
                    .then( file => {
                        if ( file.item ) {
                            resolve( URL.createObjectURL( file.item ) );
                        } else {
                            reject( new Error( 'File Retrieval Error' ) );
                        }
                    } )
                    .catch( reject );
            } else {
                // obtain file from storage
                store.record.file.get( _getInstanceId(), subject )
                    .then( file => {
                        if ( file.item ) {
                            if ( isTooLarge( file.item ) ) {
                                reject( _getMaxSizeError() );
                            } else {
                                resolve( URL.createObjectURL( file.item ) );
                            }
                        } else {
                            reject( new Error( 'File Retrieval Error' ) );
                        }
                    } )
                    .catch( reject );
            }
        } else if ( typeof subject === 'object' ) {
            if ( isTooLarge( subject ) ) {
                reject( _getMaxSizeError() );
            } else {
                resolve( URL.createObjectURL( subject ) );
            }
        } else {
            reject( new Error( 'Unknown error occurred' ) );
        }
    } );
}

/**
 * Similar to getFileURL, except that this one is guaranteed to return an objectURL
 *
 * It is meant for loading images into a canvas.
 *
 * @param  {?string|object} subject - File or filename in local storage
 * @return {*}         promise url string or rejection with Error
 */
function getObjectUrl( subject ) {
    return getFileUrl( subject )
        .then( url => {
            if ( /https?:\/\//.test( url ) ) {
                return connection.getMediaFile( url ).then( obj => URL.createObjectURL( obj.item ) );
            }

            return url;
        } );
}

/**
 * Obtain files currently stored in file input elements of open record
 *
 * @return {Promise} A promise that resolves with an array of files
 */
function getCurrentFiles() {
    const fileInputs = [ ...document.querySelectorAll( 'form.or input[type="file"], form.or input[type="text"][data-drawing="true"]' ) ];
    const fileTasks = [];

    const _processNameAndSize = function( input, file ){
        if ( file && file.name ) {
            // Correct file names by adding a unique-ish postfix
            // First create a clone, because the name property is immutable
            // TODO: in the future, when browser support increase we can invoke
            // the File constructor to do this.
            const newFilename = getFilename( file, input.dataset.filenamePostfix );
            // If file is resized, get Blob representation of data URI
            if ( input.dataset.resized && input.dataset.resizedDataURI ) {
                file = utils.dataUriToBlobSync( input.dataset.resizedDataURI );
            }
            file = new Blob( [ file ], {
                type: file.type
            } );
            file.name = newFilename;
        }

        return file;
    };

    fileInputs.forEach( input => {
        if ( input.type === 'file' ) {
            // first get any files inside file input elements
            if ( input.files[0] ){
                fileTasks.push( Promise.resolve( _processNameAndSize( input, input.files[ 0 ] ) ) );
            }
        } else if ( input.value ) {
            // then from canvases
            const canvas = input.closest( '.question' ).querySelector( '.draw-widget canvas' );
            if ( canvas && !URL_RE.test( input.value ) ) {
                fileTasks.push( new Promise( resolve => canvas.toBlob( blob => {
                    blob.name = input.value;
                    resolve( _processNameAndSize( input, blob ) );
                } ) ) );
            }
        }

    } );

    return Promise.all( fileTasks )
        .then( files => {
            // get any file names of files that were loaded as DataURI and have remained unchanged (i.e. loaded from Storage)
            fileInputs
                .filter( input => input.matches( '[data-loaded-file-name]' ) )
                .forEach( input => files.push( input.getAttribute( 'data-loaded-file-name' ) ) );

            return files;
        } );
}

/**
 * Traverses files currently stored in file input elements of open record to find a specific file.
 *
 * @param filename
 * @return {Promise} array of files
 */
function getCurrentFile( filename ) {
    let f;
    // relies on all file names to be unique (which they are)
    getCurrentFiles().some( file => {
        if ( file.name === filename ) {
            f = file;

            return true;
        }
    } );

    return f;
}

/**
 * Obtains the instanceId of the current record.
 *
 * @return {?string} [description]
 */
function _getInstanceId() {
    return settings.recordId;
}

/**
 * Whether the file is too large too handle and should be rejected
 *
 * @param  {*}  file - the File
 * @return {boolean}
 */
function isTooLarge( file ) {
    return file && file.size > _getMaxSize();
}

function _getMaxSizeError() {
    return new Error( t( 'filepicker.toolargeerror', {
        maxSize: getMaxSizeReadable()
    } ) );
}

/**
 * Returns the maximum size of a file
 *
 * @return {number}
 */
function _getMaxSize() {
    return settings.maxSize || 5 * 1024 * 1024;
}

function getMaxSizeReadable() {
    return `${Math.round( _getMaxSize() * 100 / ( 1024 * 1024 ) / 100 )}MB`;
}

export default {
    isWaitingForPermissions,
    init,
    setInstanceAttachments,
    getFileUrl,
    getObjectUrl,
    getCurrentFiles,
    getCurrentFile,
    isTooLarge,
    getMaxSizeReadable
};
<commit_msg>fixed: getCurrentFile not working (not used in ee),<commit_after>/*
 * Replaces file-manager in enketo-core.
 */

import store from './store';

import settings from './settings';
import connection from './connection';
import utils from './utils';
import { getFilename } from 'enketo-core/src/js/utils';
import { t } from './translator';
const URL_RE = /[a-zA-Z0-9+-.]+?:\/\//;
let instanceAttachments;

/**
 * Initialize the file manager .
 *
 * @return {*} promise boolean or rejection with Error
 */
function init() {
    return Promise.resolve( true );
}

/**
 * Whether the filemanager is waiting for user permissions
 *
 * @return {boolean} [description]
 */
function isWaitingForPermissions() {
    return false;
}

/**
 * Sets instanceAttachments containing filename:url map
 * to use in getFileUrl
 *
 * @param attachments
 */
function setInstanceAttachments( attachments ) {
    instanceAttachments = attachments;
}
/**
 * Obtains a url that can be used to show a preview of the file when used
 * as a src attribute.
 *
 * @param  {?string|object} subject - File or filename
 * @return {*}         promise url string or rejection with Error
 */
function getFileUrl( subject ) {
    return new Promise( ( resolve, reject ) => {
        if ( !subject ) {
            resolve( null );
        } else if ( typeof subject === 'string' ) {
            if ( subject.startsWith( '/' ) ) {
                resolve( subject );
            } else if ( instanceAttachments && ( Object.prototype.hasOwnProperty.call( instanceAttachments, subject ) ) ) {
                resolve( instanceAttachments[ subject ] );
            } else if ( !store.available ) {
                // e.g. in an online-only edit view
                reject( new Error( 'store not available' ) );
            } else if ( URL_RE.test( subject ) ) {
                // Any URL values are default binary values. These should only occur in offline-capable views,
                // because the form cache module removed the src attributes
                // (which are /urls/like/this/http:// and are caught above this statement)
                store.survey.resource.get( settings.enketoId, subject )
                    .then( file => {
                        if ( file.item ) {
                            resolve( URL.createObjectURL( file.item ) );
                        } else {
                            reject( new Error( 'File Retrieval Error' ) );
                        }
                    } )
                    .catch( reject );
            } else {
                // obtain file from storage
                store.record.file.get( _getInstanceId(), subject )
                    .then( file => {
                        if ( file.item ) {
                            if ( isTooLarge( file.item ) ) {
                                reject( _getMaxSizeError() );
                            } else {
                                resolve( URL.createObjectURL( file.item ) );
                            }
                        } else {
                            reject( new Error( 'File Retrieval Error' ) );
                        }
                    } )
                    .catch( reject );
            }
        } else if ( typeof subject === 'object' ) {
            if ( isTooLarge( subject ) ) {
                reject( _getMaxSizeError() );
            } else {
                resolve( URL.createObjectURL( subject ) );
            }
        } else {
            reject( new Error( 'Unknown error occurred' ) );
        }
    } );
}

/**
 * Similar to getFileURL, except that this one is guaranteed to return an objectURL
 *
 * It is meant for loading images into a canvas.
 *
 * @param  {?string|object} subject - File or filename in local storage
 * @return {*}         promise url string or rejection with Error
 */
function getObjectUrl( subject ) {
    return getFileUrl( subject )
        .then( url => {
            if ( /https?:\/\//.test( url ) ) {
                return connection.getMediaFile( url ).then( obj => URL.createObjectURL( obj.item ) );
            }

            return url;
        } );
}

/**
 * Obtain files currently stored in file input elements of open record
 *
 * @return {Promise} A promise that resolves with an array of files
 */
function getCurrentFiles() {
    const fileInputs = [ ...document.querySelectorAll( 'form.or input[type="file"], form.or input[type="text"][data-drawing="true"]' ) ];
    const fileTasks = [];

    const _processNameAndSize = function( input, file ){
        if ( file && file.name ) {
            // Correct file names by adding a unique-ish postfix
            // First create a clone, because the name property is immutable
            // TODO: in the future, when browser support increase we can invoke
            // the File constructor to do this.
            const newFilename = getFilename( file, input.dataset.filenamePostfix );
            // If file is resized, get Blob representation of data URI
            if ( input.dataset.resized && input.dataset.resizedDataURI ) {
                file = utils.dataUriToBlobSync( input.dataset.resizedDataURI );
            }
            file = new Blob( [ file ], {
                type: file.type
            } );
            file.name = newFilename;
        }

        return file;
    };

    fileInputs.forEach( input => {
        if ( input.type === 'file' ) {
            // first get any files inside file input elements
            if ( input.files[0] ){
                fileTasks.push( Promise.resolve( _processNameAndSize( input, input.files[ 0 ] ) ) );
            }
        } else if ( input.value ) {
            // then from canvases
            const canvas = input.closest( '.question' ).querySelector( '.draw-widget canvas' );
            if ( canvas && !URL_RE.test( input.value ) ) {
                fileTasks.push( new Promise( resolve => canvas.toBlob( blob => {
                    blob.name = input.value;
                    resolve( _processNameAndSize( input, blob ) );
                } ) ) );
            }
        }

    } );

    return Promise.all( fileTasks )
        .then( files => {
            // get any file names of files that were loaded as DataURI and have remained unchanged (i.e. loaded from Storage)
            fileInputs
                .filter( input => input.matches( '[data-loaded-file-name]' ) )
                .forEach( input => files.push( input.getAttribute( 'data-loaded-file-name' ) ) );

            return files;
        } );
}

/**
 * Traverses files currently stored in file input elements of open record to find a specific file.
 *
 * @param filename
 * @return {Promise} array of files
 */
function getCurrentFile( filename ) {
    // relies on all file names to be unique (which they are)
    return getCurrentFiles()
        .then( files => files.find( file => file.name === filename )  );
}

/**
 * Obtains the instanceId of the current record.
 *
 * @return {?string} [description]
 */
function _getInstanceId() {
    return settings.recordId;
}

/**
 * Whether the file is too large too handle and should be rejected
 *
 * @param  {*}  file - the File
 * @return {boolean}
 */
function isTooLarge( file ) {
    return file && file.size > _getMaxSize();
}

function _getMaxSizeError() {
    return new Error( t( 'filepicker.toolargeerror', {
        maxSize: getMaxSizeReadable()
    } ) );
}

/**
 * Returns the maximum size of a file
 *
 * @return {number}
 */
function _getMaxSize() {
    return settings.maxSize || 5 * 1024 * 1024;
}

function getMaxSizeReadable() {
    return `${Math.round( _getMaxSize() * 100 / ( 1024 * 1024 ) / 100 )}MB`;
}

export default {
    isWaitingForPermissions,
    init,
    setInstanceAttachments,
    getFileUrl,
    getObjectUrl,
    getCurrentFiles,
    getCurrentFile,
    isTooLarge,
    getMaxSizeReadable
};
<|endoftext|>


<commit_before>/* globals describe, it, expect, expectObservable, hot */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.bufferCount', function () {
  it('should emit buffers at intervals', function () {
    var values = {
      v: ['a', 'b', 'c'],
      w: ['c', 'd', 'e'],
      x: ['e', 'f', 'g'],
      y: ['g', 'h', 'i'],
      z: ['i']
    };
    var e1 =   hot('--a--b--c--d--e--f--g--h--i--|');
    var expected = '--------v-----w-----x-----y--(z|)';

    expectObservable(e1.bufferCount(3, 2)).toBe(expected, values);
  });

  it('should emit buffers at buffersize of intervals if not specified', function () {
    var values = {
      x: ['a', 'b'],
      y: ['c', 'd'],
      z: ['e', 'f']
    };
    var e1 =   hot('--a--b--c--d--e--f--|');
    var expected = '-----x-----y-----z--|';

    expectObservable(e1.bufferCount(2)).toBe(expected, values);
  });

  it('should emit partial buffers if source completes before reaching specified buffer count', function () {
    var e1 =   hot('--a--b--c--d--|');
    var expected = '--------------(x|)';

    expectObservable(e1.bufferCount(5)).toBe(expected, {x: ['a', 'b', 'c', 'd']});
  });

  it('should emit full buffer then last partial buffer if source completes', function () {
    var e1 =   hot('--a^-b--c--d--e--|');
    var expected =    '--------y-----(z|)';

    expectObservable(e1.bufferCount(3)).toBe(expected, {y: ['b', 'c', 'd'], z: ['e']});
  });

  it('should raise error if source raise error before reaching specified buffer count', function () {
    var e1 =   hot('--a--b--c--d--#');
    var expected = '--------------#';

    expectObservable(e1.bufferCount(5)).toBe(expected);
  });

  it('should emit buffers with specified skip count when skip count is less than window count', function () {
    var values = {
      v: ['a', 'b', 'c'],
      w: ['b', 'c', 'd'],
      x: ['c', 'd', 'e'],
      y: ['d', 'e'],
      z: ['e']
    };
    var e1 =   hot('--a--b--c--d--e--|');
    var expected = '--------v--w--x--(yz|)';

    expectObservable(e1.bufferCount(3, 1)).toBe(expected, values);
  });

  it('should emit buffers with specified skip count when skip count is more than window count', function () {
    var e1 =   hot('--a--b--c--d--e--|');
    var expected = '-----y--------z--|';

    expectObservable(e1.bufferCount(2, 3)).toBe(expected, {y: ['a', 'b'], z: ['d', 'e']});
  });
});<commit_msg>test(bufferCount): add last missing test for bufferCount<commit_after>/* globals describe, it, expect, expectObservable, hot */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.bufferCount', function () {
  it('should emit buffers at intervals', function () {
    var values = {
      v: ['a', 'b', 'c'],
      w: ['c', 'd', 'e'],
      x: ['e', 'f', 'g'],
      y: ['g', 'h', 'i'],
      z: ['i']
    };
    var e1 =   hot('--a--b--c--d--e--f--g--h--i--|');
    var expected = '--------v-----w-----x-----y--(z|)';

    expectObservable(e1.bufferCount(3, 2)).toBe(expected, values);
  });

  it('should emit buffers at buffersize of intervals if not specified', function () {
    var values = {
      x: ['a', 'b'],
      y: ['c', 'd'],
      z: ['e', 'f']
    };
    var e1 =   hot('--a--b--c--d--e--f--|');
    var expected = '-----x-----y-----z--|';

    expectObservable(e1.bufferCount(2)).toBe(expected, values);
  });

  it('should emit partial buffers if source completes before reaching specified buffer count', function () {
    var e1 =   hot('--a--b--c--d--|');
    var expected = '--------------(x|)';

    expectObservable(e1.bufferCount(5)).toBe(expected, {x: ['a', 'b', 'c', 'd']});
  });

  it('should emit full buffer then last partial buffer if source completes', function () {
    var e1 =   hot('--a^-b--c--d--e--|');
    var expected =    '--------y-----(z|)';

    expectObservable(e1.bufferCount(3)).toBe(expected, {y: ['b', 'c', 'd'], z: ['e']});
  });

  it('should emit buffers at intervals, but stop when result is unsubscribed early', function () {
    var values = {
      v: ['a', 'b', 'c'],
      w: ['c', 'd', 'e']
    };
    var e1 =   hot('--a--b--c--d--e--f--g--h--i--|');
    var unsub =    '                  !           ';
    var subs =     '^                 !           ';
    var expected = '--------v-----w----           ';

    expectObservable(e1.bufferCount(3, 2), unsub).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(subs);
  });

  it('should raise error if source raise error before reaching specified buffer count', function () {
    var e1 =   hot('--a--b--c--d--#');
    var expected = '--------------#';

    expectObservable(e1.bufferCount(5)).toBe(expected);
  });

  it('should emit buffers with specified skip count when skip count is less than window count', function () {
    var values = {
      v: ['a', 'b', 'c'],
      w: ['b', 'c', 'd'],
      x: ['c', 'd', 'e'],
      y: ['d', 'e'],
      z: ['e']
    };
    var e1 =   hot('--a--b--c--d--e--|');
    var expected = '--------v--w--x--(yz|)';

    expectObservable(e1.bufferCount(3, 1)).toBe(expected, values);
  });

  it('should emit buffers with specified skip count when skip count is more than window count', function () {
    var e1 =   hot('--a--b--c--d--e--|');
    var expected = '-----y--------z--|';

    expectObservable(e1.bufferCount(2, 3)).toBe(expected, {y: ['a', 'b'], z: ['d', 'e']});
  });
});<|endoftext|>


<commit_before>// main requestAnimFrame for all the animation
window.requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 30);
    };
})();

//// for drawing the joystick
var control_canvas,
c, // context 2D
halfWidth,
halfHeight,
rect_joy,
leftPointerID = -1,	// variable for mouse left button cursor interactions
leftPointerPos = new Vector2(0, 0),
leftPointerStartPos = new Vector2(0, 0),
leftVector = new Vector2(0, 0);
arrow = new VectorLED(0, 0, 0, 0);	// vector for LED direction
joy_arrow = new VectorLED(0, 0, 0, 0);	// vector used for direction calculations

var touches; // collections of pointers

/////////////////////////////// ARDUINO SETUP

// LED setup
//var led1; //-90 D
//var led2; //0 R
//var led3; //90 U
//var led4; //180=-180 L
var max_val; // threshold radius of the joystick
var LEDloopON = false;

///////////////////////////// ARDUINO SETUP END

var username = "noname";	// for socket.io
var arduino_socket;					// for socket.io

document.addEventListener("DOMContentLoaded", init);
window.addEventListener('resize', function(event){ // resize when you resize the browser
	resetCanvas();
});

function init() {
    setupCanvas();
    setupD3();
    //setupMotionDetection();

    touches = new Collection();

    onReady();
}

function onReady() {
////// jQuery for the socket.io
    // username input
        $('input[name=setUsername]').click(function(){
        	if($('input[name=usernameTxt]').val() != ""){
                username = $('input[name=usernameTxt]').val();
                    var msg = {type:'setUsername', user:username};
                    socket.json.send(msg);
                }
            $('#username').slideUp("slow",function(){
                $('#entergame').slideDown("slow");
            });
        });

        $('input[name=openButton]').click(function(){
            var msg = {type:'sendvalveopen'};
            //socket.json.send(msg);
        });
        $('input[name=closeButton]').click(function(){
            var msg = {type:'sendvalveclose'};
            //socket.json.send(msg);
        });
    // chats and score postings
        arduino_socket = new io.connect('http://171.65.102.132:3006');
        var chat = $('#chat');
        var board = $('#board');

        arduino_socket.on('connect', function() {
            console.log("Connected!");
            setupCanvas();
        });

        arduino_socket.on('message', function(message){
        console.log(message);
			var str = message.split("&&");
			if (Number(str[0]))
			{
				chat.append(str[1] + '
');
				console.log(str[1]);
			}else{
				var ledArray = str[1].split("^");
				arrow.int1 = ledArray[0];
				arrow.int2 = ledArray[1];
				arrow.int3 = ledArray[2];
				arrow.int4 = ledArray[3];
			}
        });

        arduino_socket.on('postscore', function(score){
                board.empty();
                for (var i=0;i<score.length;i++){
                        if(i==0){
                                board.append(''+ score[i][0]+'  :  '+score[i][1]+'
');
                        }else{
                                board.append(score[i][0]+'  :  '+score[i][1]+ '
');
                        }
                }
                board.fadeOut('fast');
                board.fadeIn('fast');
                board.fadeOut('fast');
                board.fadeIn('fast');
        });

        arduino_socket.on('disconnect', function() {
                console.log('disconnected');
                chat.html("Disconnected!");
        });

        $("input[name=sendBtn]").click(function(){
                var msg = {type:'chat',message:username + " : " + $("input[name=chatTxt]").val()}
                arduino_socket.json.send(msg);
                $("input[name=chatTxt]").val("");
        });

/////////////////////////////
// Drawing Joystick functions
/////////////////////////////

////// EventListeners for joystick canvas
    control_canvas.addEventListener('pointerdown', onPointerDown, false);
    control_canvas.addEventListener('pointermove', onPointerMove, false);
    control_canvas.addEventListener('pointerup', onPointerUp, false);
    control_canvas.addEventListener('pointerout', onPointerUp, false);
    // start drawing joystick loop
    requestAnimFrame(joystick_draw);
}

function joystick_draw() {
    c.clearRect(0, 0, control_canvas.width, control_canvas.height);

    c.beginPath();
    c.moveTo(halfWidth, halfHeight-4);
    c.strokeStyle = "rgba(250, 102, 0, 1)";
    c.lineWidth = 2;
    c.lineTo(halfWidth, halfHeight+4);
    c.stroke();

    c.beginPath();
    c.moveTo(halfWidth+4, halfHeight);
    c.strokeStyle = "rgba(250, 102, 0, 1)";
    c.lineWidth = 2;
    c.lineTo(halfWidth-4, halfHeight);
    c.stroke();

    drawCircles(halfWidth, halfHeight);

        //// mouse event loop
    touches.forEach(function (touch) {
        if (touch.identifier == leftPointerID) {
	// draw the joystick in the control canvas
            var alpha = arrow.trimArrow(leftVector, max_val);

            c.beginPath();
            c.fillStyle = "rgba(250, 102, 0, 1)";
            c.arc(leftPointerPos.x, leftPointerPos.y, 16, 0, Math.PI * 2, true);
            c.fill();

            c.beginPath();
            c.moveTo(leftPointerStartPos.x,leftPointerStartPos.y);
            c.strokeStyle = "rgba(250, 102, 0, 1)";
            c.lineTo(leftPointerStartPos.x+max_val*(arrow.int2-arrow.int4),leftPointerStartPos.y+max_val*(arrow.int1-arrow.int3));
            c.lineWidth = 3;
            c.stroke();

            c.beginPath();
            c.fillStyle = "rgba(255, 255, 255, "+alpha+")";
            c.arc(halfWidth, halfHeight, 16, 0, Math.PI * 2, true);
            c.fill();

            c.beginPath();
            c.fillStyle = "#fff";
            c.fillText(alpha,halfWidth-10, halfHeight-25);

            c.beginPath();
            c.fillStyle = "#dd6600";
            var theta = leftVector.angle();
            c.fillText(theta.toFixed(0),leftPointerPos.x+10, leftPointerPos.y-20);
            // send the input to johnny five

        }
    });

    requestAnimFrame(joystick_draw);
    if(LEDloopON)
    {
        changeLED(1);
    }
}

/////////////////////////////
// Mouse event functions
/////////////////////////////

function givePointerType(event) {
    switch (event.pointerType) {
        case event.POINTER_TYPE_MOUSE:
            return "MOUSE";
            break;
        case event.POINTER_TYPE_PEN:
            return "PEN";
            break;
        case event.POINTER_TYPE_TOUCH:
            return "TOUCH";
            break;
    }
}

function onPointerDown(e) {
    var newPointer = { identifier: e.pointerId, x: e.clientX, y: e.clientY, type: givePointerType(e) };
    leftPointerID = e.pointerId;
    leftPointerStartPos.reset(halfWidth, halfHeight);
    leftPointerPos.copyFrom(leftPointerStartPos);
    leftVector.reset(0, 0);
    joy_arrow.reset(0, 0, 0, 0);
    touches.add(e.pointerId, newPointer);
}

function onPointerMove(e) {
    if (leftPointerID == e.pointerId) {
        leftPointerPos.reset(e.pageX-rect_joy.left, e.pageY-rect_joy.top);
        leftVector.copyFrom(leftPointerPos);
        leftVector.minusEq(leftPointerStartPos);
        joy_arrow.setArrow(leftVector, max_val);
        LEDloopON = true;
    }
    else {
        if (touches.item(e.pointerId)) {
            touches.item(e.pointerId).x = e.clientX;
            touches.item(e.pointerId).y = e.clientY;
        }
    }
}

function onPointerUp(e) {
    if (leftPointerID == e.pointerId) {
        leftPointerID = -1;
        leftVector.reset(0, 0);
    }
    leftVector.reset(0, 0);
    joy_arrow.reset(0, 0, 0, 0);
    touches.remove(e.pointerId);
    LEDloopON = false; // we are no longer monitoring the mouse input
    changeLED(0); // turn off all LEDs
}

/////////////////////////////
// Arduino control functions
/////////////////////////////

function changeLED(LEDon) { // on joystick inputs
    if(LEDon)
    {
	var msg =
	{type:'/arduino/#sendLEDarrow', user:username, led1:joy_arrow.int1, led2:joy_arrow.int2, led3:joy_arrow.int3, led4:joy_arrow.int4};
    	arduino_socket.json.send(msg);
    }
    else
    {
	var msg =
	{type:'/arduino/#sendLEDarrow', user:username, led1:0, led2:0, led3:0, led4:0};
    	arduino_socket.json.send(msg);
    }
}

/////////////////////////////
// Canvas setup functions
/////////////////////////////

function setupCanvas() { // called in init
    control_canvas = document.getElementById('controlCanvas');
    c = control_canvas.getContext('2d');
    resetCanvas();
    c.strokeStyle = "#ffffff";
    c.lineWidth = 2;
}

function resetCanvas(e) { // on resize events
    max_val = (document.getElementById("joystickArea").offsetWidth-100)/2;
    console.log('max_val :' + max_val);

    // resize the canvas - this clears the canvas
    control_canvas.width = document.getElementById("joystickArea").offsetWidth-20;
    control_canvas.height = control_canvas.width;
    halfWidth = (control_canvas.width)/2;
    halfHeight = (control_canvas.height)/2;

    rect_joy = control_canvas.getBoundingClientRect();

    // make sure we scroll to the top left.
    window.scrollTo(0, 0);
}
<commit_msg>emit all debug<commit_after>// main requestAnimFrame for all the animation
window.requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 30);
    };
})();

//// for drawing the joystick
var control_canvas,
c, // context 2D
halfWidth,
halfHeight,
rect_joy,
leftPointerID = -1,	// variable for mouse left button cursor interactions
leftPointerPos = new Vector2(0, 0),
leftPointerStartPos = new Vector2(0, 0),
leftVector = new Vector2(0, 0);
arrow = new VectorLED(0, 0, 0, 0);	// vector for LED direction
joy_arrow = new VectorLED(0, 0, 0, 0);	// vector used for direction calculations

var touches; // collections of pointers

/////////////////////////////// ARDUINO SETUP

// LED setup
//var led1; //-90 D
//var led2; //0 R
//var led3; //90 U
//var led4; //180=-180 L
var max_val; // threshold radius of the joystick
var LEDloopON = false;

///////////////////////////// ARDUINO SETUP END

var username = "noname";	// for socket.io
var arduino_socket;					// for socket.io

document.addEventListener("DOMContentLoaded", init);
window.addEventListener('resize', function(event){ // resize when you resize the browser
	resetCanvas();
});

function init() {
    setupCanvas();
    setupD3();
    //setupMotionDetection();

    touches = new Collection();

    onReady();
}

function onReady() {
////// jQuery for the socket.io
    // username input
        $('input[name=setUsername]').click(function(){
        	if($('input[name=usernameTxt]').val() != ""){
                username = $('input[name=usernameTxt]').val();
                    var msg = {type:'setUsername', user:username};
                    socket.json.send(msg);
                }
            $('#username').slideUp("slow",function(){
                $('#entergame').slideDown("slow");
            });
        });

        $('input[name=openButton]').click(function(){
            var msg = {type:'sendvalveopen'};
            //socket.json.send(msg);
        });
        $('input[name=closeButton]').click(function(){
            var msg = {type:'sendvalveclose'};
            //socket.json.send(msg);
        });
    // chats and score postings
        arduino_socket = new io.connect('http://171.65.102.132:3006');
        var chat = $('#chat');
        var board = $('#board');

        arduino_socket.on('connect', function() {
            console.log("Connected!");
            setupCanvas();
        });

        arduino_socket.on('client-msg', function(message){
        console.log(message);
			var str = message.split("&&");
			if (Number(str[0]))
			{
				chat.append(str[1] + '
');
				console.log(str[1]);
			}else{
				var ledArray = str[1].split("^");
				arrow.int1 = ledArray[0];
				arrow.int2 = ledArray[1];
				arrow.int3 = ledArray[2];
				arrow.int4 = ledArray[3];
			}
        });

        arduino_socket.on('postscore', function(score){
                board.empty();
                for (var i=0;i<score.length;i++){
                        if(i==0){
                                board.append(''+ score[i][0]+'  :  '+score[i][1]+'
');
                        }else{
                                board.append(score[i][0]+'  :  '+score[i][1]+ '
');
                        }
                }
                board.fadeOut('fast');
                board.fadeIn('fast');
                board.fadeOut('fast');
                board.fadeIn('fast');
        });

        arduino_socket.on('disconnect', function() {
                console.log('disconnected');
                chat.html("Disconnected!");
        });

        $("input[name=sendBtn]").click(function(){
                var msg = {type:'chat',message:username + " : " + $("input[name=chatTxt]").val()}
                arduino_socket.json.send(msg);
                $("input[name=chatTxt]").val("");
        });

/////////////////////////////
// Drawing Joystick functions
/////////////////////////////

////// EventListeners for joystick canvas
    control_canvas.addEventListener('pointerdown', onPointerDown, false);
    control_canvas.addEventListener('pointermove', onPointerMove, false);
    control_canvas.addEventListener('pointerup', onPointerUp, false);
    control_canvas.addEventListener('pointerout', onPointerUp, false);
    // start drawing joystick loop
    requestAnimFrame(joystick_draw);
}

function joystick_draw() {
    c.clearRect(0, 0, control_canvas.width, control_canvas.height);

    c.beginPath();
    c.moveTo(halfWidth, halfHeight-4);
    c.strokeStyle = "rgba(250, 102, 0, 1)";
    c.lineWidth = 2;
    c.lineTo(halfWidth, halfHeight+4);
    c.stroke();

    c.beginPath();
    c.moveTo(halfWidth+4, halfHeight);
    c.strokeStyle = "rgba(250, 102, 0, 1)";
    c.lineWidth = 2;
    c.lineTo(halfWidth-4, halfHeight);
    c.stroke();

    drawCircles(halfWidth, halfHeight);

        //// mouse event loop
    touches.forEach(function (touch) {
        if (touch.identifier == leftPointerID) {
	// draw the joystick in the control canvas
            var alpha = arrow.trimArrow(leftVector, max_val);

            c.beginPath();
            c.fillStyle = "rgba(250, 102, 0, 1)";
            c.arc(leftPointerPos.x, leftPointerPos.y, 16, 0, Math.PI * 2, true);
            c.fill();

            c.beginPath();
            c.moveTo(leftPointerStartPos.x,leftPointerStartPos.y);
            c.strokeStyle = "rgba(250, 102, 0, 1)";
            c.lineTo(leftPointerStartPos.x+max_val*(arrow.int2-arrow.int4),leftPointerStartPos.y+max_val*(arrow.int1-arrow.int3));
            c.lineWidth = 3;
            c.stroke();

            c.beginPath();
            c.fillStyle = "rgba(255, 255, 255, "+alpha+")";
            c.arc(halfWidth, halfHeight, 16, 0, Math.PI * 2, true);
            c.fill();

            c.beginPath();
            c.fillStyle = "#fff";
            c.fillText(alpha,halfWidth-10, halfHeight-25);

            c.beginPath();
            c.fillStyle = "#dd6600";
            var theta = leftVector.angle();
            c.fillText(theta.toFixed(0),leftPointerPos.x+10, leftPointerPos.y-20);
            // send the input to johnny five

        }
    });

    requestAnimFrame(joystick_draw);
    if(LEDloopON)
    {
        changeLED(1);
    }
}

/////////////////////////////
// Mouse event functions
/////////////////////////////

function givePointerType(event) {
    switch (event.pointerType) {
        case event.POINTER_TYPE_MOUSE:
            return "MOUSE";
            break;
        case event.POINTER_TYPE_PEN:
            return "PEN";
            break;
        case event.POINTER_TYPE_TOUCH:
            return "TOUCH";
            break;
    }
}

function onPointerDown(e) {
    var newPointer = { identifier: e.pointerId, x: e.clientX, y: e.clientY, type: givePointerType(e) };
    leftPointerID = e.pointerId;
    leftPointerStartPos.reset(halfWidth, halfHeight);
    leftPointerPos.copyFrom(leftPointerStartPos);
    leftVector.reset(0, 0);
    joy_arrow.reset(0, 0, 0, 0);
    touches.add(e.pointerId, newPointer);
}

function onPointerMove(e) {
    if (leftPointerID == e.pointerId) {
        leftPointerPos.reset(e.pageX-rect_joy.left, e.pageY-rect_joy.top);
        leftVector.copyFrom(leftPointerPos);
        leftVector.minusEq(leftPointerStartPos);
        joy_arrow.setArrow(leftVector, max_val);
        LEDloopON = true;
    }
    else {
        if (touches.item(e.pointerId)) {
            touches.item(e.pointerId).x = e.clientX;
            touches.item(e.pointerId).y = e.clientY;
        }
    }
}

function onPointerUp(e) {
    if (leftPointerID == e.pointerId) {
        leftPointerID = -1;
        leftVector.reset(0, 0);
    }
    leftVector.reset(0, 0);
    joy_arrow.reset(0, 0, 0, 0);
    touches.remove(e.pointerId);
    LEDloopON = false; // we are no longer monitoring the mouse input
    changeLED(0); // turn off all LEDs
}

/////////////////////////////
// Arduino control functions
/////////////////////////////

function changeLED(LEDon) { // on joystick inputs
    if(LEDon)
    {
	var msg =
	{type:'/arduino/#sendLEDarrow', user:username, led1:joy_arrow.int1, led2:joy_arrow.int2, led3:joy_arrow.int3, led4:joy_arrow.int4};
    	arduino_socket.json.send(msg);
    }
    else
    {
	var msg =
	{type:'/arduino/#sendLEDarrow', user:username, led1:0, led2:0, led3:0, led4:0};
    	arduino_socket.json.send(msg);
    }
}

/////////////////////////////
// Canvas setup functions
/////////////////////////////

function setupCanvas() { // called in init
    control_canvas = document.getElementById('controlCanvas');
    c = control_canvas.getContext('2d');
    resetCanvas();
    c.strokeStyle = "#ffffff";
    c.lineWidth = 2;
}

function resetCanvas(e) { // on resize events
    max_val = (document.getElementById("joystickArea").offsetWidth-100)/2;
    console.log('max_val :' + max_val);

    // resize the canvas - this clears the canvas
    control_canvas.width = document.getElementById("joystickArea").offsetWidth-20;
    control_canvas.height = control_canvas.width;
    halfWidth = (control_canvas.width)/2;
    halfHeight = (control_canvas.height)/2;

    rect_joy = control_canvas.getBoundingClientRect();

    // make sure we scroll to the top left.
    window.scrollTo(0, 0);
}
<|endoftext|>


<commit_before>define(["js/ui/View", "sprd/lib/ScrollIntoViewIfNeeded"], function(View, ScrollIntoViewIfNeeded) {
    return View.inherit({

        _renderSelected: function(selected) {

            this.callBase();

            if (selected) {
                ScrollIntoViewIfNeeded(this.$el);
            }
        }

    });
});<commit_msg>fixed selection / deselection of configurations<commit_after>define(["js/ui/View", "sprd/lib/ScrollIntoViewIfNeeded"], function(View, ScrollIntoViewIfNeeded) {
    return View.inherit({

        defaults: {
            scrollDelay: 0
        },

        _renderSelected: function(selected) {

            this.callBase();

            if (selected) {
                var $el = this.$el,
                    self = this;
                setTimeout(function() {
                    self.$.selected && ScrollIntoViewIfNeeded($el);
                }, this.$.scrollDelay)
            }
        }

    });
});<|endoftext|>


<commit_before>/*
 * Sozi - A presentation tool using the SVG standard
 *
 * Copyright (C) 2010-2011 Guillaume Savaton
 *
 * This program is dual licensed under the terms of the MIT license
 * or the GNU General Public License (GPL) version 3.
 * A copy of both licenses is provided in the doc/ folder of the
 * official release of Sozi.
 *
 * See http://sozi.baierouge.fr/wiki/en:license for details.
 */

var sozi = sozi || {};

(function () {
    var player = sozi.player = sozi.player || {},
        display = sozi.display = sozi.display || {},
        window = this,
        document = window.document,
        DRAG_BUTTON = 0, // Left button
        TOC_BUTTON = 1, // Middle button
        SCALE_FACTOR = 1.05,
        ROTATE_STEP = 5,
        dragButtonIsDown = false,
        dragged = false,
        dragClientX = 0,
        dragClientY = 0;

    /*
     * Zooms the display in the given direction.
     *
     * Only the sign of direction is used:
     *    - zoom in when direction > 0
     *    - zoom out when direction <= 0
     *
     * The scaling is centered around point (x, y).
     */
    function zoom(direction, x, y) {
        player.stop();
        display.zoom(direction > 0 ? SCALE_FACTOR : 1 / SCALE_FACTOR, x, y);
    }

    /*
     * Rotate the display in the given direction.
     *
     * Only the sign of direction is used:
     *    - rotate anticlockwise when direction > 0
     *    - rotate clockwise when direction <= 0
     */
    function rotate(direction) {
        player.stop();
        display.rotate(direction > 0 ? ROTATE_STEP : -ROTATE_STEP);
    }

    function toggleFrameList() {
        if (sozi.framelist.isVisible()) {
            sozi.framelist.hide();
            player.restart();
        } else {
            player.stop();
            sozi.framelist.show();
        }
    }

    /*
     * Event handler: mouse down.
     *
     * When the left button is pressed, we register the current coordinates
     * in case the mouse will be dragged. Flag "dragButtonIsDown" is set until
     * the button is released (onMouseUp). This flag is used by onMouseMove.
     *
     * When the middle button is pressed, the table of contents is shown or hidden.
     */
    function onMouseDown(evt) {
        if (evt.button === DRAG_BUTTON) {
            dragButtonIsDown = true;
            dragged = false;
            dragClientX = evt.clientX;
            dragClientY = evt.clientY;
        } else if (evt.button === TOC_BUTTON) {
            toggleFrameList();
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse move.
     *
     * If the left mouse button is down, then the mouse move is a drag action.
     * This method computes the displacement since the button was pressed or
     * since the last move, and updates the reference coordinates for the next move.
     */
    function onMouseMove(evt) {
        if (dragButtonIsDown) {
            player.stop();
            dragged = true;
            sozi.events.fire("cleanup");
            display.drag(evt.clientX - dragClientX, evt.clientY - dragClientY);
            dragClientX = evt.clientX;
            dragClientY = evt.clientY;
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse up.
     *
     * Releasing the left button resets the "dragButtonIsDown" flag.
     */
    function onMouseUp(evt) {
        if (evt.button === DRAG_BUTTON) {
            dragButtonIsDown = false;
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse click.
     *
     * Left-click moves the presentation to the next frame.
     *
     * No "click" event is generated for the middle button.
     * See "onMouseDown" for middle click handling.
     *
     * Dragging the mouse produces a "click" event when the button is released.
     * If flag "dragged" was set by "onMouseMove", then the click event is the result
     * of a drag action.
     */
    function onClick(evt) {
        if (!dragged) {
            player.moveToNext();
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse wheel.
     *
     * Rolling the mouse wheel stops the presentation and zooms the current display.
     */
    function onWheel(evt) {
        var delta = 0;
        if (!evt) {
            evt = window.event;
        }
        if (evt.wheelDelta) { // IE and Opera
            delta = evt.wheelDelta;
            if (window.opera) { // Opera
                delta = -delta;
            }
        } else if (evt.detail) { // Mozilla
            delta = -evt.detail;
        }

        if (delta !== 0) {
            if (evt.shiftKey) {
                rotate(delta);
            } else {
                zoom(delta, evt.clientX, evt.clientY);
            }
        }
        evt.stopPropagation();
        evt.preventDefault();
    }

    /*
     * Event handler: key press.
     *
     * Keyboard handling is split into two methods: onKeyPress and onKeyDown
     * in order to get the same behavior in Mozilla and Webkit.
     *
     * This method handles character keys "+", "-", "=", "F" and "T".
     */
    function onKeyPress(evt) {
        switch (evt.charCode) {
        case 43: // +
            zoom(1, window.innerWidth / 2, window.innerHeight / 2);
            break;
        case 45: // -
            zoom(-1, window.innerWidth / 2, window.innerHeight / 2);
            break;
        case 61: // =
            player.moveToCurrent();
            break;
        case 70: // F
        case 102: // f
            player.showAll();
            break;
        case 84: // T
        case 116: // t
            toggleFrameList();
            break;
        case 82: // R
            rotate(-1);
            break;
        case 114: // r
            rotate(1);
            break;
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: key down.
     *
     * Keyboard handling is split into two methods: onKeyPress and onKeyDown
     * in order to get the same behavior in Mozilla and Webkit.
     *
     * This method handles navigation keys (arrows, page up/down, home, end)
     * and the space and enter keys.
     */
    function onKeyDown(evt) {
        switch (evt.keyCode) {
        case 36: // Home
            player.moveToFirst();
            break;
        case 35: // End
            player.moveToLast();
            break;
        case 38: // Arrow up
            player.jumpToPrevious();
            break;
        case 33: // Page up
        case 37: // Arrow left
            player.moveToPrevious();
            break;
        case 40: // Arrow down
            player.jumpToNext();
            break;
        case 34: // Page down
        case 39: // Arrow right
        case 13: // Enter
        case 32: // Space
            player.moveToNext();
            break;
        }
        evt.stopPropagation();
    }

    function onLoad() {
        var svgRoot = document.documentElement;

        // TODO also use shift-click as an alternative for middle-click
        svgRoot.addEventListener("click", onClick, false);
        svgRoot.addEventListener("mousedown", onMouseDown, false);
        svgRoot.addEventListener("mouseup", onMouseUp, false);
        svgRoot.addEventListener("mousemove", onMouseMove, false);
        svgRoot.addEventListener("keypress", onKeyPress, false);
        svgRoot.addEventListener("keydown", onKeyDown, false);
        svgRoot.addEventListener("DOMMouseScroll", onWheel, false); // Mozilla
        window.onmousewheel = onWheel;
    }

    window.addEventListener("load", onLoad, false);
}());
<commit_msg>Prevent middle-click from moving to next frame in chromium<commit_after>/*
 * Sozi - A presentation tool using the SVG standard
 *
 * Copyright (C) 2010-2011 Guillaume Savaton
 *
 * This program is dual licensed under the terms of the MIT license
 * or the GNU General Public License (GPL) version 3.
 * A copy of both licenses is provided in the doc/ folder of the
 * official release of Sozi.
 *
 * See http://sozi.baierouge.fr/wiki/en:license for details.
 */

var sozi = sozi || {};

(function () {
    var player = sozi.player = sozi.player || {},
        display = sozi.display = sozi.display || {},
        window = this,
        document = window.document,
        DRAG_BUTTON = 0, // Left button
        TOC_BUTTON = 1, // Middle button
        SCALE_FACTOR = 1.05,
        ROTATE_STEP = 5,
        dragButtonIsDown = false,
        dragged = false,
        dragClientX = 0,
        dragClientY = 0;

    /*
     * Zooms the display in the given direction.
     *
     * Only the sign of direction is used:
     *    - zoom in when direction > 0
     *    - zoom out when direction <= 0
     *
     * The scaling is centered around point (x, y).
     */
    function zoom(direction, x, y) {
        player.stop();
        display.zoom(direction > 0 ? SCALE_FACTOR : 1 / SCALE_FACTOR, x, y);
    }

    /*
     * Rotate the display in the given direction.
     *
     * Only the sign of direction is used:
     *    - rotate anticlockwise when direction > 0
     *    - rotate clockwise when direction <= 0
     */
    function rotate(direction) {
        player.stop();
        display.rotate(direction > 0 ? ROTATE_STEP : -ROTATE_STEP);
    }

    function toggleFrameList() {
        if (sozi.framelist.isVisible()) {
            sozi.framelist.hide();
            player.restart();
        } else {
            player.stop();
            sozi.framelist.show();
        }
    }

    /*
     * Event handler: mouse down.
     *
     * When the left button is pressed, we register the current coordinates
     * in case the mouse will be dragged. Flag "dragButtonIsDown" is set until
     * the button is released (onMouseUp). This flag is used by onMouseMove.
     *
     * When the middle button is pressed, the table of contents is shown or hidden.
     */
    function onMouseDown(evt) {
        if (evt.button === DRAG_BUTTON) {
            dragButtonIsDown = true;
            dragged = false;
            dragClientX = evt.clientX;
            dragClientY = evt.clientY;
        } else if (evt.button === TOC_BUTTON) {
            toggleFrameList();
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse move.
     *
     * If the left mouse button is down, then the mouse move is a drag action.
     * This method computes the displacement since the button was pressed or
     * since the last move, and updates the reference coordinates for the next move.
     */
    function onMouseMove(evt) {
        if (dragButtonIsDown) {
            player.stop();
            dragged = true;
            sozi.events.fire("cleanup");
            display.drag(evt.clientX - dragClientX, evt.clientY - dragClientY);
            dragClientX = evt.clientX;
            dragClientY = evt.clientY;
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse up.
     *
     * Releasing the left button resets the "dragButtonIsDown" flag.
     */
    function onMouseUp(evt) {
        if (evt.button === DRAG_BUTTON) {
            dragButtonIsDown = false;
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse click.
     *
     * Left-click moves the presentation to the next frame.
     *
     * No "click" event is generated for the middle button in Firefox.
     * See "onMouseDown" for middle click handling.
     *
     * Dragging the mouse produces a "click" event when the button is released.
     * If flag "dragged" was set by "onMouseMove", then the click event is the result
     * of a drag action.
     */
    function onClick(evt) {
        if (!dragged && evt.button !== TOC_BUTTON) {
            player.moveToNext();
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: mouse wheel.
     *
     * Rolling the mouse wheel stops the presentation and zooms the current display.
     */
    function onWheel(evt) {
        var delta = 0;
        if (!evt) {
            evt = window.event;
        }
        if (evt.wheelDelta) { // IE and Opera
            delta = evt.wheelDelta;
            if (window.opera) { // Opera
                delta = -delta;
            }
        } else if (evt.detail) { // Mozilla
            delta = -evt.detail;
        }

        if (delta !== 0) {
            if (evt.shiftKey) {
                rotate(delta);
            } else {
                zoom(delta, evt.clientX, evt.clientY);
            }
        }
        evt.stopPropagation();
        evt.preventDefault();
    }

    /*
     * Event handler: key press.
     *
     * Keyboard handling is split into two methods: onKeyPress and onKeyDown
     * in order to get the same behavior in Mozilla and Webkit.
     *
     * This method handles character keys "+", "-", "=", "F" and "T".
     */
    function onKeyPress(evt) {
        switch (evt.charCode) {
        case 43: // +
            zoom(1, window.innerWidth / 2, window.innerHeight / 2);
            break;
        case 45: // -
            zoom(-1, window.innerWidth / 2, window.innerHeight / 2);
            break;
        case 61: // =
            player.moveToCurrent();
            break;
        case 70: // F
        case 102: // f
            player.showAll();
            break;
        case 84: // T
        case 116: // t
            toggleFrameList();
            break;
        case 82: // R
            rotate(-1);
            break;
        case 114: // r
            rotate(1);
            break;
        }
        evt.stopPropagation();
    }

    /*
     * Event handler: key down.
     *
     * Keyboard handling is split into two methods: onKeyPress and onKeyDown
     * in order to get the same behavior in Mozilla and Webkit.
     *
     * This method handles navigation keys (arrows, page up/down, home, end)
     * and the space and enter keys.
     */
    function onKeyDown(evt) {
        switch (evt.keyCode) {
        case 36: // Home
            player.moveToFirst();
            break;
        case 35: // End
            player.moveToLast();
            break;
        case 38: // Arrow up
            player.jumpToPrevious();
            break;
        case 33: // Page up
        case 37: // Arrow left
            player.moveToPrevious();
            break;
        case 40: // Arrow down
            player.jumpToNext();
            break;
        case 34: // Page down
        case 39: // Arrow right
        case 13: // Enter
        case 32: // Space
            player.moveToNext();
            break;
        }
        evt.stopPropagation();
    }

    function onLoad() {
        var svgRoot = document.documentElement;

        // TODO also use shift-click as an alternative for middle-click
        svgRoot.addEventListener("click", onClick, false);
        svgRoot.addEventListener("mousedown", onMouseDown, false);
        svgRoot.addEventListener("mouseup", onMouseUp, false);
        svgRoot.addEventListener("mousemove", onMouseMove, false);
        svgRoot.addEventListener("keypress", onKeyPress, false);
        svgRoot.addEventListener("keydown", onKeyDown, false);
        svgRoot.addEventListener("DOMMouseScroll", onWheel, false); // Mozilla
        window.onmousewheel = onWheel;
    }

    window.addEventListener("load", onLoad, false);
}());
<|endoftext|>


<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'gfycat.com',
    prepareImgLinks:function (callback) {
        $('a[href*="gfycat.com/"]').one('mouseenter', function() {
            var link = $(this),
                gfyId = this.href.replace(/.*gfycat.com\/(gifs\/)?(detail\/)?(\w+).*/, '$3');
            $.get('https://gfycat.com/cajax/get/' + gfyId, function (data) {
                if (data && data.gfyItem) {
                    link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.webmUrl : data.gfyItem.gifUrl]
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        });
    }
});
<commit_msg>Support for Lang in URL in Gfycat plugin<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'gfycat.com',
    prepareImgLinks:function (callback) {
        $('a[href*="gfycat.com/"]').one('mouseenter', function() {
            var link = $(this),
                gfyId = this.href.replace(/.*gfycat.com\/(..\/)?(gifs\/)?(detail\/)?(\w+).*/, '$4');
            $.get('https://gfycat.com/cajax/get/' + gfyId, function (data) {
                if (data && data.gfyItem) {
                    link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.webmUrl : data.gfyItem.gifUrl]
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        });
    }
});
<|endoftext|>


<commit_before>var redis = require('redis');

var Github = function() {
  this.auto = ['listen'];
};

Github.prototype.listen = function(bot) {
  var redisClient = redis.createClient(bot.redisConf.port, bot.redisConf.host),
      pattern = [bot.redisConf.prefix, 'github/*'].join(':');

  redisClient.on('message', function(channel, message) {
    var realChannel = channel.slice(bot.redisConf.prefix.length - 1).split('/'),
        ircChannel = bot.config.github[realChannel];

    bot.say(realChannel, 'I got a message from github.');
  });
  redisClient.psubscribe(pattern);
};

export.Plugin = Github;
<commit_msg>fix typo<commit_after>var redis = require('redis');

var Github = function() {
  this.auto = ['listen'];
};

Github.prototype.listen = function(bot) {
  var redisClient = redis.createClient(bot.redisConf.port, bot.redisConf.host),
      pattern = [bot.redisConf.prefix, 'github/*'].join(':');

  redisClient.on('message', function(channel, message) {
    var realChannel = channel.slice(bot.redisConf.prefix.length - 1).split('/'),
        ircChannel = bot.config.github[realChannel];

    bot.say(realChannel, 'I got a message from github.');
  });
  redisClient.psubscribe(pattern);
};

exports.Plugin = Github;
<|endoftext|>


<commit_before>/*
 * Copyright (c), Log-Normal, Inc.
 */

/**
\file memory.js
Plugin to collect memory metrics when available.
see: http://code.google.com/p/chromium/issues/detail?id=43281
*/

(function() {
var w, p={}, d, m, s, n, b, impl;
// First make sure BOOMR is actually defined.  It's possible that your plugin is loaded before boomerang, in which case
// you'll need this.
BOOMR = BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
if (BOOMR.plugins.Memory) {
	return;
}

function nodeList(type) {
	try {
		return d.getElementsByTagName(type);
	}
	catch(err) {
		BOOMR.addError(err, "Memory.nodeList." + type);
		return [];
	}
}

function errorWrap(condition, callback, component) {
	if(condition) {
		try {
			callback();
		}
		catch(err) {
			BOOMR.addError(err, "Memory.done." + component);
		}
	}
}

// A private object to encapsulate all your implementation details
impl = {
	done: function() {
		var res, doms={}, a;
		// If we have resource timing, get number of resources
		if(p && p.getEntriesByType && p.getEntriesByType("resource").length) {
			res = p.getEntriesByType("resource");
			BOOMR.addVar("dom.res", res.length);

			a = document.createElement("a");

			res.forEach(function(r) {
				a.href=r.name;
				doms[a.hostname] = true;
			});

			BOOMR.addVar("dom.doms", Object.keys(doms).length);
		}
		else {
			BOOMR.removeVar("dom.res");
		}

		if(m) {
			BOOMR.addVar({
				"mem.total": m.totalJSHeapSize,
				"mem.used" : m.usedJSHeapSize
			});
		}

		errorWrap(s,
			function() {
				BOOMR.addVar({
					"scr.xy": s.width + "x" + s.height,
					"scr.bpp": s.colorDepth + "/" + s.pixelDepth
				});
				if(s.orientation) {
					BOOMR.addVar("scr.orn", s.orientation.angle + "/" + s.orientation.type);
				}
				if(w.devicePixelRatio > 1) {
					BOOMR.addVar("scr.dpx", w.devicePixelRatio);
				}
			},
			"screen"
		);

		errorWrap(n,
			function() {
				if(n.hardwareConcurrency) {
					BOOMR.addVar("cpu.cnc", n.hardwareConcurrency);
				}
				if(n.maxTouchPoints) {
					BOOMR.addVar("scr.mtp", n.maxTouchPoints);
				}
			},
			"navigator"
		);

		errorWrap(b,
			function() {
				BOOMR.addVar("bat.lvl", b.level);
			},
			"battery"
		);

		BOOMR.addVar({
			"dom.ln": nodeList("*").length,
			"dom.sz": nodeList("html")[0].innerHTML.length,
			"dom.img": nodeList("img").length,
			"dom.script": nodeList("script").length
		});

		// no need of sendBeacon because we're called when the beacon is being sent
	}
};

BOOMR.plugins.Memory = {
	init: function() {
		var c;

		try {
			w = BOOMR.window;
			d = w.document;
			p = w.performance;
			c = w.console;
			s = w.screen;
			n = w.navigator;
			if(n.battery) {
				b = n.battery;
			}
			else if(n.getBattery) {
				n.getBattery().then(function(battery) {
					b = battery;
				});
			}
		}
		catch(err) {
			BOOMR.addError(err, "Memory.init");
		}

		m = (p && p.memory ? p.memory : (c && c.memory ? c.memory : null));

		// we do this before sending a beacon to get the snapshot when the beacon is sent
		BOOMR.subscribe("before_beacon", impl.done, null, impl);
		return this;
	},

	is_complete: function() {
		// Always true since we run on before_beacon, which happens after the check
		return true;
	}
};

}());

<commit_msg>figure out which nodeCount call causes a memory issue<commit_after>/*
 * Copyright (c), Log-Normal, Inc.
 */

/**
\file memory.js
Plugin to collect memory metrics when available.
see: http://code.google.com/p/chromium/issues/detail?id=43281
*/

(function() {
var w, p={}, d, m, s, n, b, impl;
// First make sure BOOMR is actually defined.  It's possible that your plugin is loaded before boomerang, in which case
// you'll need this.
BOOMR = BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
if (BOOMR.plugins.Memory) {
	return;
}

function nodeCount(type) {
	try {
		return d.getElementsByTagName(type).length;
	}
	catch(err) {
		BOOMR.addError(err, "Memory.nodeList." + type);
		return 0;
	}
}

function errorWrap(condition, callback, component) {
	if(condition) {
		try {
			callback();
		}
		catch(err) {
			BOOMR.addError(err, "Memory.done." + component);
		}
	}
}

// A private object to encapsulate all your implementation details
impl = {
	done: function() {
		var res, doms={}, a;
		// If we have resource timing, get number of resources
		if(p && p.getEntriesByType && p.getEntriesByType("resource").length) {
			res = p.getEntriesByType("resource");
			BOOMR.addVar("dom.res", res.length);

			a = document.createElement("a");

			res.forEach(function(r) {
				a.href=r.name;
				doms[a.hostname] = true;
			});

			BOOMR.addVar("dom.doms", Object.keys(doms).length);
		}
		else {
			BOOMR.removeVar("dom.res");
		}

		if(m) {
			BOOMR.addVar({
				"mem.total": m.totalJSHeapSize,
				"mem.used" : m.usedJSHeapSize
			});
		}

		errorWrap(s,
			function() {
				BOOMR.addVar({
					"scr.xy": s.width + "x" + s.height,
					"scr.bpp": s.colorDepth + "/" + s.pixelDepth
				});
				if(s.orientation) {
					BOOMR.addVar("scr.orn", s.orientation.angle + "/" + s.orientation.type);
				}
				if(w.devicePixelRatio > 1) {
					BOOMR.addVar("scr.dpx", w.devicePixelRatio);
				}
			},
			"screen"
		);

		errorWrap(n,
			function() {
				if(n.hardwareConcurrency) {
					BOOMR.addVar("cpu.cnc", n.hardwareConcurrency);
				}
				if(n.maxTouchPoints) {
					BOOMR.addVar("scr.mtp", n.maxTouchPoints);
				}
			},
			"navigator"
		);

		errorWrap(b,
			function() {
				BOOMR.addVar("bat.lvl", b.level);
			},
			"battery"
		);

		errorWrap(true,
			function() {
				BOOMR.addVar({
					"dom.ln": nodeCount("*"),
					"dom.img": nodeCount("img"),
					"dom.script": nodeCount("script")
				});
				BOOMR.addVar("dom.sz", d.documentElement.innerHTML.length);
			},
			"dom"
		);

		// no need of sendBeacon because we're called when the beacon is being sent
	}
};

BOOMR.plugins.Memory = {
	init: function() {
		var c;

		try {
			w = BOOMR.window;
			d = w.document;
			p = w.performance;
			c = w.console;
			s = w.screen;
			n = w.navigator;
			if(n.battery) {
				b = n.battery;
			}
			else if(n.getBattery) {
				n.getBattery().then(function(battery) {
					b = battery;
				});
			}
		}
		catch(err) {
			BOOMR.addError(err, "Memory.init");
		}

		m = (p && p.memory ? p.memory : (c && c.memory ? c.memory : null));

		// we do this before sending a beacon to get the snapshot when the beacon is sent
		BOOMR.subscribe("before_beacon", impl.done, null, impl);
		return this;
	},

	is_complete: function() {
		// Always true since we run on before_beacon, which happens after the check
		return true;
	}
};

}());

<|endoftext|>


<commit_before>exports.cli = function (db, config) {
  db.commands.push(function (db, config, cb) {
    var args = config._.slice()
    if(args.shift() != 'readme') return
    var module = args.shift()
    db.sublevel('pkg').createReadStream({
      min: module, max: module
    }).on('data', function (data) {
      console.log(data.value.readme)
    })
    .on('end', cb)
    return true
  })
}
<commit_msg>switch from stream to normal data<commit_after>exports.cli = function (db, config) {
  db.commands.push(function (db, config, cb) {
    var args = config._.slice()
    if(args.shift() != 'readme') return
    var module = args.shift()
    db.sublevel('pkg').get(module, function (err, data) {
      if(err) return cb(err)
      console.log(data.readme)
      cb(null, data.readme)
    })
  })
}
<|endoftext|>