<commit_before>define( 'argumenta/widgets/Argument',
[
    "require-jquery",
    "argumenta/widgets/Base",
    "text!./Argument/template.html.mustache",
    "argumenta/widgets/Discussion",
    "argumenta/widgets/DiscussionEditor",
    "argumenta/widgets/Proposition",
    "argumenta/sandbox"
],
function( $, Base, Template, Discussion, DiscussionEditor, Proposition, Sandbox ) {

    /**
     * @class Argument
     *
     * Widget options may be set in a combination of four ways:
     *
     *   1. As a module default on the prototype.
     *   2. As instance options.
     *   3. As individual custom `data-<option>` attributes in HTML.
     *   4. As bundle of JSON properties in a `data-<moduleID>` HTML attribute.
     *
     * Example JS for module defaults:
     *
     *     Argument.prototype.defaultOptions = {option: value};
     *
     * Example JS for instance options:
     *
     *     var argument = new Argument({
     *         sha1: <sha1>,
     *         show_propositions: true
     *     });
     *
     * Example HTML with individual attributes:
     *
     *     <div class="argument-widget"
     *          data-sha1="<sha1>"
     *          data-show_propositions="true" >
     *

     *
     * Example HTML with options bundle in a `data-<moduleID>` attribute:
     *
     *     <div class="argument-widget"
     *          data-argument="{sha1: <sha1>, show_propositions: true}" >
     *

     *
     * @param opts {Object} Argument widget options.
     * @param opts.show_discussions {Boolean} Whether to show discussions initially.
     * @param opts.show_propositions {Boolean} Whether to show propositions initially.
     * @param opts.propositions {Array<Object>} An array of argument propositions data.
     * @note Propositions may be set as options, or loaded via AJAX.
     */
    var Argument = Base.module( {

        moduleID: 'Argument',
        template: Template,

        defaults: {
            show_discussions: false,
            show_propositions: true
        },

        init: function( options ) {
            var self = this;
            self.initArgument( options );
        },

        prototype: {

            // Inits this argument widget.
            initArgument: function() {
                var self = this;
                self.propositionWidgets = [];
                self.propositionsVisible = false;
                self._initData();
                if (self.options.show_discussions) {
                    self.toggleDiscussions();
                }
            },

            // Gets the object type.
            getType: function() {
                return this.options.object_type;
            },

            // Gets the object sha1.
            getSha1: function() {
                return this.options.sha1;
            },

            // Sets propositions data, and inits elements.
            setPropositions: function( props ) {
                var self = this;
                self.propositions = props;
                self._initPropositionElements();
            },

            // Gets child proposition widgets.
            getPropositionWidgets: function() {
                var self = this;
                return self.propositionWidgets;
            },

            // Sets discussions data for this argument.
            setDiscussions: function(discussions) {
                var self = this;
                self.discussions = [];
                self.discussionsCount.text(discussions.length);
                self.discussionsContainer.empty();
                for (var i = 0; i < discussions.length; i++) {
                    var discussion = new Discussion(discussions[i]);
                    self.discussions.push(discussion);
                    self.discussionsContainer.append(discussion.element);
                }
                self.options.discussions = discussions;
                self.options.discussions_count = discussions.length;
            },

            // Toggles argument details for widget.
            toggleArgumentDetails: function() {
                var self = this;
                self.togglePropositions();
            },

            // Toggle discussions for widget.
            toggleDiscussions: function() {
                var self = this;
                if ( self.discussions ) {
                    self.discussionsPanel.toggle(300);
                }
                else {
                    self._initDiscussions();
                    self.discussionsPanel.css({ display: 'block' });
                    self.discussionsPanel.show(300);
                }
            },

            // Toggle propositions for widget.
            togglePropositions: function() {
                var self = this;
                if ( self.propositions ) {
                    self.content.toggle(300);
                    self.propositionsVisible = !self.propositionsVisible;
                }
                else {
                    self._initPropositions();
                }
            },

            // Starts a new discussion.
            onDiscuss: function() {
                var self = this;
                if (self.discussionEditor.length == 0) {
                    self._initDiscussionEditor();
                }
                else {
                    self.discussionContainer.toggle(300);
                }
            },

            // Binds UI events, extending Base behavior.
            _bindUI: function() {
                var self = this;

                // Save reference to inner container and menu.
                self.container = self.element.children(".argument-container");
                self.main = self.container.children(".argument-main");
                self.title = self.main.children('.argument-title');
                self.menu = self.container.find('.argument-menu').first();
                self.deleteButton = self.menu.find('.action-delete');
                self.content = self.container.children('.argument-content');
                self.propositionsContainer = self.content.children('.propositions-container');
                self.footer = self.content.children('.argument-footer');
                self.discuss = self.footer.children('.argument-discuss');
                self.discussionContainer = self.footer.children('.discussion-container');
                self.discussionEditor = self.discussionContainer.children('.discussion-editor');
                self.discussionsPanel = self.footer.children('.discussions-panel');
                self.discussionsHeader = self.discussionsPanel.children('.discussions-header');
                self.discussionsCount = self.discussionsHeader.children('.discussions-count');
                self.discussionsContainer = self.discussionsPanel.children('.discussions-container');
                self.showDiscussions = self.footer.children('.show-discussions');

                // Click behavior for title.
                self.title.children('a').on('click', function( event ) {
                    event.stopPropagation();
                });

                // Click behavior for discuss.
                self.discuss.on('click', function( event ) {
                    event.preventDefault();
                    self.discuss.blur();
                    self.onDiscuss();
                });

                // Click behavior for show discussions.
                self.showDiscussions.on('click', function( event ) {
                    event.preventDefault();
                    self.showDiscussions.blur();
                    self.toggleDiscussions();
                });

                // Click behavior for menu.
                self.menu.on('click', function( event ) {
                    self.element.temporaryClass('menu-just-clicked', 300);
                });

                // Click behavior for `Delete Repo`.
                self.deleteButton.on('click', function( event ) {
                    var name = self.options.commit.committer;
                    var repo = self.options.repo;
                    var base = self.options.base_url;
                    var path = '/' + name + '/' + repo + '.json';
                    var url  = base + path;
                    var settings = {
                        type: 'DELETE'
                      , url: url
                    };
                    var success = function( data, textStatus, jqXHR ) {
                        Sandbox.notify( data.message );
                        self.element.remove();
                    };
                    var error = function( data ) {
                        Sandbox.error(data);
                    };
                    $.ajax(settings).done(success).fail(error);
                });

                // Click behavior for main panel.
                self.container.children(".argument-main").on('click', function( event ) {

                    // Don't expand on mouse release after drag.
                    if ( self.element.hasClass('ui-state-just-dragged') )
                        return;

                    // Don't expand on mouse release after menu click.
                    if ( self.element.hasClass('menu-just-clicked') )
                        return;

                    // Toggle details on click.
                    self.toggleArgumentDetails();
                } );

                // Make draggable.
                self.element.draggable( {
                    helper: 'clone',
                    appendTo: $('.drag-container')[0] || $('body'),
                    revert: true,
                    cancel: 'span, input',
                    handle: self.container.children(".argument-main"),
                    cursor: 'move',

                    start: function(event, ui) {
                        // Prevent other actions on drag.
                        ui.helper.addClass('ui-state-just-dragged drag');

                        // Fix clone size.
                        ui.helper.css( {
                            'height': self.element.height() + 'px',
                            'width': self.element.width() + 'px'
                        } );

                        // Hide original.
                        self.element.css('visibility', "hidden");
                    },

                    stop: function(event, ui) {
                        // Prevent other actions on drag, then cleanup.
                        setTimeout(function() {
                            ui.helper.removeClass('ui-state-just-dragged');
                        }, 300);

                        // Reveal original.
                        self.element.css('visibility', "");
                    }
                } );
            },

            // Inits widget data.
            _initData: function() {
                var self = this;
                if ( !self.options.title ||
                     !self.options.premises ||
                     !self.options.conclusion )
                {
                    self._loadDataBySha1();
                }
                else if (self.options.show_propositions) {
                    self._initPropositions();
                }
            },

            // Loads argument data by SHA-1.
            _loadDataBySha1: function() {
                var self = this;
                var sha1 = self.options.sha1;
                var base = self.options.base_url;
                var path = '/arguments/' + sha1 + '.json';
                var url  = base + path;
                var success = function( data ) {
                    $.extend(self.options, data.argument);
                    self.options.commit = data.commit;
                    self._refresh();
                    if ( self.options.show_propositions ) {
                        self._initPropositions();
                    }
                };
                var error = function( data ) {
                    Sandbox.error(data);
                };
                $.ajax(url).done(success).fail(error);
            },

            // Inits discussion editor.
            _initDiscussionEditor: function() {
                var self = this;
                var update = function() {
                    self._updateDiscussions();
                    self.discussionsPanel.show(300);
                    self.discussionContainer.empty();
                    self.discussionEditor = null;
                };
                var discussionEditor = new DiscussionEditor({
                    target_type: self.getType(),
                    target_sha1: self.getSha1(),
                    on_create: update
                });
                self.discussionContainer.append(discussionEditor.element);
                self.discussionEditor = discussionEditor.element;
            },

            // Inits discussions.
            _initDiscussions: function() {
                var self = this;
                self._updateDiscussions();
            },

            // Updates discussions.
            _updateDiscussions: function() {
                var self = this;
                var base = self.options.base_url;
                var sha1 = self.getSha1();
                var path = '/arguments/' + sha1 + '/discussions.json';
                var url = base + path;
                var success = function(data) {
                    self.setDiscussions(data.discussions);
                };
                var error = function(data) {
                    Sandbox.error(data);
                };
                $.get(url).done(success).fail(error);
            },

            // Inits propositions data and elements.
            _initPropositions: function() {
                var self = this;

                if ( self.options.propositions ) {
                    self.setPropositions( self.options.propositions );
                }
                else {
                    var sha1 = this.options.sha1;
                    var base = self.options.base_url;
                    var path = '/arguments/' + sha1 + '/propositions.json';
                    var url  = base + path;
                    var success = function( data ) {
                        self.setPropositions( data.propositions );
                    }
                    var error = function( data ) {
                        Sandbox.error(data);
                    }
                    $.ajax(url).done(success).fail(error);
                }
            },

            // Inits proposition elements.
            _initPropositionElements: function() {
                var self = this;
                var container = self.propositionsContainer;

                // Hide container.
                container.hide();

                // Clear any current propositions.
                container.empty();
                self.propositionWidgets.length = 0;

                // Create the new proposition elements.
                for ( var i=0, len=self.propositions.length; i<len; i++ ) {
                    var data = self.propositions[i];
                    var position = i + 1;
                    var role = (position < len) ? 'premise' : 'conclusion';
                    var index = (role === 'premise') ? position : 'C';

                    // Extend proposition data with its argument index.
                    data = $.extend( {}, data, { 'index': index } );

                    // Create a widget from the proposition data.
                    var proposition = new Proposition( data );

                    // Add a class for this proposition's role.
                    proposition.element.addClass( role );

                    // Append the proposition and save a reference.
                    container.append( proposition.element );
                    self.propositionWidgets.push( proposition );
                }
                // Reveal container.
                container.show();
                self.content.css({ display: 'block' });
                self.content.show();
                self.propositionsVisible = true;
            },

            // Gets view options for template, extending Base behavior.
            _getViewOptions: function() {
                var self = this;
                var base      = self.options.base_url;
                var committer = self.options.commit.committer;
                var reponame  = self.options.repo;
                var repoUrl   = base + '/' + committer + '/' + encodeURIComponent(reponame);
                var viewOptions = {
                    partial_sha1: self.options.sha1.substr(0, 20),
                    repo_url: repoUrl,
                    argument_desc:
                        'Argument Repo\r\n'
                        + self.options.commit.committer + ' / '
                        + self.options.repo,
                    object_desc:
                        'Argument Object\r\n'
                        + 'SHA1: ' + self.options.sha1
                };
                return $.extend( viewOptions, self.options );
            }
        },

        static: {
        }
    } );

    return Argument;
} );
<commit_msg>Fix tests for arguments without commits<commit_after>define( 'argumenta/widgets/Argument',
[
    "require-jquery",
    "argumenta/widgets/Base",
    "text!./Argument/template.html.mustache",
    "argumenta/widgets/Discussion",
    "argumenta/widgets/DiscussionEditor",
    "argumenta/widgets/Proposition",
    "argumenta/sandbox"
],
function( $, Base, Template, Discussion, DiscussionEditor, Proposition, Sandbox ) {

    /**
     * @class Argument
     *
     * Widget options may be set in a combination of four ways:
     *
     *   1. As a module default on the prototype.
     *   2. As instance options.
     *   3. As individual custom `data-<option>` attributes in HTML.
     *   4. As bundle of JSON properties in a `data-<moduleID>` HTML attribute.
     *
     * Example JS for module defaults:
     *
     *     Argument.prototype.defaultOptions = {option: value};
     *
     * Example JS for instance options:
     *
     *     var argument = new Argument({
     *         sha1: <sha1>,
     *         show_propositions: true
     *     });
     *
     * Example HTML with individual attributes:
     *
     *     <div class="argument-widget"
     *          data-sha1="<sha1>"
     *          data-show_propositions="true" >
     *

     *
     * Example HTML with options bundle in a `data-<moduleID>` attribute:
     *
     *     <div class="argument-widget"
     *          data-argument="{sha1: <sha1>, show_propositions: true}" >
     *

     *
     * @param opts {Object} Argument widget options.
     * @param opts.show_discussions {Boolean} Whether to show discussions initially.
     * @param opts.show_propositions {Boolean} Whether to show propositions initially.
     * @param opts.propositions {Array<Object>} An array of argument propositions data.
     * @note Propositions may be set as options, or loaded via AJAX.
     */
    var Argument = Base.module( {

        moduleID: 'Argument',
        template: Template,

        defaults: {
            show_discussions: false,
            show_propositions: true
        },

        init: function( options ) {
            var self = this;
            self.initArgument( options );
        },

        prototype: {

            // Inits this argument widget.
            initArgument: function() {
                var self = this;
                self.propositionWidgets = [];
                self.propositionsVisible = false;
                self._initData();
                if (self.options.show_discussions) {
                    self.toggleDiscussions();
                }
            },

            // Gets the object type.
            getType: function() {
                return this.options.object_type;
            },

            // Gets the object sha1.
            getSha1: function() {
                return this.options.sha1;
            },

            // Gets the committer, if set.
            getCommitter: function() {
                return this.commit ? this.commit.committer : '';
            },

            // Sets propositions data, and inits elements.
            setPropositions: function( props ) {
                var self = this;
                self.propositions = props;
                self._initPropositionElements();
            },

            // Gets child proposition widgets.
            getPropositionWidgets: function() {
                var self = this;
                return self.propositionWidgets;
            },

            // Sets discussions data for this argument.
            setDiscussions: function(discussions) {
                var self = this;
                self.discussions = [];
                self.discussionsCount.text(discussions.length);
                self.discussionsContainer.empty();
                for (var i = 0; i < discussions.length; i++) {
                    var discussion = new Discussion(discussions[i]);
                    self.discussions.push(discussion);
                    self.discussionsContainer.append(discussion.element);
                }
                self.options.discussions = discussions;
                self.options.discussions_count = discussions.length;
            },

            // Toggles argument details for widget.
            toggleArgumentDetails: function() {
                var self = this;
                self.togglePropositions();
            },

            // Toggle discussions for widget.
            toggleDiscussions: function() {
                var self = this;
                if ( self.discussions ) {
                    self.discussionsPanel.toggle(300);
                }
                else {
                    self._initDiscussions();
                    self.discussionsPanel.css({ display: 'block' });
                    self.discussionsPanel.show(300);
                }
            },

            // Toggle propositions for widget.
            togglePropositions: function() {
                var self = this;
                if ( self.propositions ) {
                    self.content.toggle(300);
                    self.propositionsVisible = !self.propositionsVisible;
                }
                else {
                    self._initPropositions();
                }
            },

            // Starts a new discussion.
            onDiscuss: function() {
                var self = this;
                if (self.discussionEditor.length == 0) {
                    self._initDiscussionEditor();
                }
                else {
                    self.discussionContainer.toggle(300);
                }
            },

            // Binds UI events, extending Base behavior.
            _bindUI: function() {
                var self = this;

                // Save reference to inner container and menu.
                self.container = self.element.children(".argument-container");
                self.main = self.container.children(".argument-main");
                self.title = self.main.children('.argument-title');
                self.menu = self.container.find('.argument-menu').first();
                self.deleteButton = self.menu.find('.action-delete');
                self.content = self.container.children('.argument-content');
                self.propositionsContainer = self.content.children('.propositions-container');
                self.footer = self.content.children('.argument-footer');
                self.discuss = self.footer.children('.argument-discuss');
                self.discussionContainer = self.footer.children('.discussion-container');
                self.discussionEditor = self.discussionContainer.children('.discussion-editor');
                self.discussionsPanel = self.footer.children('.discussions-panel');
                self.discussionsHeader = self.discussionsPanel.children('.discussions-header');
                self.discussionsCount = self.discussionsHeader.children('.discussions-count');
                self.discussionsContainer = self.discussionsPanel.children('.discussions-container');
                self.showDiscussions = self.footer.children('.show-discussions');

                // Click behavior for title.
                self.title.children('a').on('click', function( event ) {
                    event.stopPropagation();
                });

                // Click behavior for discuss.
                self.discuss.on('click', function( event ) {
                    event.preventDefault();
                    self.discuss.blur();
                    self.onDiscuss();
                });

                // Click behavior for show discussions.
                self.showDiscussions.on('click', function( event ) {
                    event.preventDefault();
                    self.showDiscussions.blur();
                    self.toggleDiscussions();
                });

                // Click behavior for menu.
                self.menu.on('click', function( event ) {
                    self.element.temporaryClass('menu-just-clicked', 300);
                });

                // Click behavior for `Delete Repo`.
                self.deleteButton.on('click', function( event ) {
                    var name = self.options.commit.committer;
                    var repo = self.options.repo;
                    var base = self.options.base_url;
                    var path = '/' + name + '/' + repo + '.json';
                    var url  = base + path;
                    var settings = {
                        type: 'DELETE'
                      , url: url
                    };
                    var success = function( data, textStatus, jqXHR ) {
                        Sandbox.notify( data.message );
                        self.element.remove();
                    };
                    var error = function( data ) {
                        Sandbox.error(data);
                    };
                    $.ajax(settings).done(success).fail(error);
                });

                // Click behavior for main panel.
                self.container.children(".argument-main").on('click', function( event ) {

                    // Don't expand on mouse release after drag.
                    if ( self.element.hasClass('ui-state-just-dragged') )
                        return;

                    // Don't expand on mouse release after menu click.
                    if ( self.element.hasClass('menu-just-clicked') )
                        return;

                    // Toggle details on click.
                    self.toggleArgumentDetails();
                } );

                // Make draggable.
                self.element.draggable( {
                    helper: 'clone',
                    appendTo: $('.drag-container')[0] || $('body'),
                    revert: true,
                    cancel: 'span, input',
                    handle: self.container.children(".argument-main"),
                    cursor: 'move',

                    start: function(event, ui) {
                        // Prevent other actions on drag.
                        ui.helper.addClass('ui-state-just-dragged drag');

                        // Fix clone size.
                        ui.helper.css( {
                            'height': self.element.height() + 'px',
                            'width': self.element.width() + 'px'
                        } );

                        // Hide original.
                        self.element.css('visibility', "hidden");
                    },

                    stop: function(event, ui) {
                        // Prevent other actions on drag, then cleanup.
                        setTimeout(function() {
                            ui.helper.removeClass('ui-state-just-dragged');
                        }, 300);

                        // Reveal original.
                        self.element.css('visibility', "");
                    }
                } );
            },

            // Inits widget data.
            _initData: function() {
                var self = this;
                if ( !self.options.title ||
                     !self.options.premises ||
                     !self.options.conclusion )
                {
                    self._loadDataBySha1();
                }
                else if (self.options.show_propositions) {
                    self._initPropositions();
                }
            },

            // Loads argument data by SHA-1.
            _loadDataBySha1: function() {
                var self = this;
                var sha1 = self.options.sha1;
                var base = self.options.base_url;
                var path = '/arguments/' + sha1 + '.json';
                var url  = base + path;
                var success = function( data ) {
                    $.extend(self.options, data.argument);
                    self.options.commit = data.commit;
                    self._refresh();
                    if ( self.options.show_propositions ) {
                        self._initPropositions();
                    }
                };
                var error = function( data ) {
                    Sandbox.error(data);
                };
                $.ajax(url).done(success).fail(error);
            },

            // Inits discussion editor.
            _initDiscussionEditor: function() {
                var self = this;
                var update = function() {
                    self._updateDiscussions();
                    self.discussionsPanel.show(300);
                    self.discussionContainer.empty();
                    self.discussionEditor = null;
                };
                var discussionEditor = new DiscussionEditor({
                    target_type: self.getType(),
                    target_sha1: self.getSha1(),
                    on_create: update
                });
                self.discussionContainer.append(discussionEditor.element);
                self.discussionEditor = discussionEditor.element;
            },

            // Inits discussions.
            _initDiscussions: function() {
                var self = this;
                self._updateDiscussions();
            },

            // Updates discussions.
            _updateDiscussions: function() {
                var self = this;
                var base = self.options.base_url;
                var sha1 = self.getSha1();
                var path = '/arguments/' + sha1 + '/discussions.json';
                var url = base + path;
                var success = function(data) {
                    self.setDiscussions(data.discussions);
                };
                var error = function(data) {
                    Sandbox.error(data);
                };
                $.get(url).done(success).fail(error);
            },

            // Inits propositions data and elements.
            _initPropositions: function() {
                var self = this;

                if ( self.options.propositions ) {
                    self.setPropositions( self.options.propositions );
                }
                else {
                    var sha1 = this.options.sha1;
                    var base = self.options.base_url;
                    var path = '/arguments/' + sha1 + '/propositions.json';
                    var url  = base + path;
                    var success = function( data ) {
                        self.setPropositions( data.propositions );
                    }
                    var error = function( data ) {
                        Sandbox.error(data);
                    }
                    $.ajax(url).done(success).fail(error);
                }
            },

            // Inits proposition elements.
            _initPropositionElements: function() {
                var self = this;
                var container = self.propositionsContainer;

                // Hide container.
                container.hide();

                // Clear any current propositions.
                container.empty();
                self.propositionWidgets.length = 0;

                // Create the new proposition elements.
                for ( var i=0, len=self.propositions.length; i<len; i++ ) {
                    var data = self.propositions[i];
                    var position = i + 1;
                    var role = (position < len) ? 'premise' : 'conclusion';
                    var index = (role === 'premise') ? position : 'C';

                    // Extend proposition data with its argument index.
                    data = $.extend( {}, data, { 'index': index } );

                    // Create a widget from the proposition data.
                    var proposition = new Proposition( data );

                    // Add a class for this proposition's role.
                    proposition.element.addClass( role );

                    // Append the proposition and save a reference.
                    container.append( proposition.element );
                    self.propositionWidgets.push( proposition );
                }
                // Reveal container.
                container.show();
                self.content.css({ display: 'block' });
                self.content.show();
                self.propositionsVisible = true;
            },

            // Gets view options for template, extending Base behavior.
            _getViewOptions: function() {
                var self = this;
                var base      = self.options.base_url;
                var reponame  = self.options.repo;
                var committer = self.getCommitter();
                var repoUrl   = base + '/' + committer + '/' + encodeURIComponent(reponame);
                var viewOptions = {
                    partial_sha1: self.options.sha1.substr(0, 20),
                    repo_url: repoUrl,
                    argument_desc:
                        'Argument Repo\r\n'
                        + committer + ' / ' + self.options.repo,
                    object_desc:
                        'Argument Object\r\n'
                        + 'SHA1: ' + self.options.sha1
                };
                return $.extend( viewOptions, self.options );
            }
        },

        static: {
        }
    } );

    return Argument;
} );
<|endoftext|>


<commit_before>export default function foo() {
  foo = function() {} // this not working is currently a bug in webpack 😝
}
<commit_msg>This really should be part of another PR<commit_after>export default function foo() {}
<|endoftext|>


<commit_before>
/*jslint browser: true, node: true */
/*global makeSlice, Base64Binary, FileReader, bind, Gunzip, isPlatformLittleEndian, deref, DataView,
GUNZIP_MAGIC_COOKIE1, GUNZIP_MAGIC_COOKIE2, numeric */

"use strict";

var papaya = papaya || {};
papaya.volume = papaya.volume || {};

papaya.volume.Volume = papaya.volume.Volume || function (progressMeter) {
    this.progressMeter = progressMeter;
    this.file = null;
    this.fileLength = 0;
    this.url = null;
    this.fileName = null;
    this.compressed = false;
    this.headerType = papaya.volume.Volume.TYPE_UNKNOWN;
    this.header = new papaya.volume.Header();
    this.imageData = new papaya.volume.ImageData();
    this.transform = null;
    this.numTimepoints = 0;
    this.rawData = null;
    this.onFinishedRead = null;
    this.errorMessage = null;
    this.transform = null;
    this.isLoaded = false;
    this.numTimepoints = 1;
    this.loaded = false;
};

papaya.volume.Volume.TYPE_UNKNOWN = 0;
papaya.volume.Volume.TYPE_NIFTI = 1;

papaya.volume.Volume.prototype.findFileType = function (filename) {
    if (filename.indexOf(".nii") !== -1) {
        return papaya.volume.Volume.TYPE_NIFTI;
    }

    return papaya.volume.Volume.TYPE_UNKNOWN;
};

papaya.volume.Volume.prototype.findFileTypeByMagicNumber = function (data) {
    var buf, mag1, mag2, mag3;

    buf = new DataView(data);

    mag1 = buf.getUint8(papaya.volume.nifti.MAGIC_NUMBER_LOCATION);
    mag2 = buf.getUint8(papaya.volume.nifti.MAGIC_NUMBER_LOCATION + 1);
    mag3 = buf.getUint8(papaya.volume.nifti.MAGIC_NUMBER_LOCATION + 2);

    if ((mag1 === papaya.volume.nifti.MAGIC_NUMBER[0]) && (mag2 === papaya.volume.nifti.MAGIC_NUMBER[1]) && (mag3 === papaya.volume.nifti.MAGIC_NUMBER[2])) {
        return papaya.volume.Volume.TYPE_NIFTI;
    }

    return papaya.volume.Volume.TYPE_UNKNOWN;
};

papaya.volume.Volume.prototype.fileIsCompressed = function (filename, data) {
    var buf, magicCookie1, magicCookie2;

    if (filename.indexOf(".gz") !== -1) {
        return true;
    }

    if (data) {
        buf = new DataView(data);

        magicCookie1 = buf.getUint8(0);
        magicCookie2 = buf.getUint8(1);

        if (magicCookie1 === GUNZIP_MAGIC_COOKIE1) {
            return true;
        }

        if (magicCookie2 === GUNZIP_MAGIC_COOKIE2) {
            return true;
        }
    }

    return false;
};

papaya.volume.Volume.prototype.readFile = function (file, callback) {
    this.file = file;
    this.fileName = file.name;
    this.onFinishedRead = callback;

    this.headerType = this.findFileType(this.fileName);

    if (this.headerType === papaya.volume.Volume.TYPE_UNKNOWN) {
        this.errorMessage = "File type is not recognized!";
        this.finishedLoad();
    } else {
        this.compressed = this.fileIsCompressed(this.fileName);
        this.fileLength = this.file.size;
        var blob = makeSlice(this.file, 0, this.file.size);
        this.readData(this, blob);
    }
};

papaya.volume.Volume.prototype.readURL = function (url, callback) {
    var vol = null, supported, xhr;

    try {
        this.url = url;
        this.fileName = url.substr(url.lastIndexOf("/") + 1, url.length);
        this.onFinishedRead = callback;

        this.headerType = this.findFileType(this.fileName);
        this.compressed = this.fileIsCompressed(this.fileName);

        vol = this;

        supported = typeof new XMLHttpRequest().responseType === 'string';
        if (supported) {
            xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'arraybuffer';

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        vol.rawData = xhr.response;
                        vol.fileLength = vol.rawData.byteLength;
                        vol.decompress(vol);
                    } else {
                        vol.errorMessage = "There was a problem reading that file (" + vol.fileName + "):\n\nResponse status = " + xhr.status;
                        vol.finishedLoad();
                    }
                }
            };

            xhr.onprogress = function (evt) {
                vol.progressMeter.drawProgress(evt.loaded / evt.total);
                console.log(evt.loaded / evt.total);
            };

            xhr.send(null);
        } else {
            vol.errorMessage = "There was a problem reading that file (" + vol.fileName + "):\n\nResponse type is not supported.";
            vol.finishedLoad();
        }
    } catch (err) {
        if (vol !== null) {
            vol.errorMessage = "There was a problem reading that file (" + vol.fileName + "):\n\n" + err.message;
            vol.finishedLoad();
        }
    }
};

papaya.volume.Volume.prototype.readEncodedData = function (name, callback) {
    var vol = null;

    try {
        this.fileName = name;
        this.onFinishedRead = callback;

        vol = this;

        vol.rawData = Base64Binary.decodeArrayBuffer(deref(name));

        this.headerType = this.findFileType(this.fileName);
        this.compressed = this.fileIsCompressed(this.fileName, vol.rawData);

        this.fileLength = vol.rawData.byteLength;

        vol.decompress(vol);
    } catch (err) {
        if (vol) {
            vol.errorMessage = "There was a problem reading that file:\n\n" + err.message;
            vol.finishedLoad();
        }
    }
};

papaya.volume.Volume.prototype.getVoxelAtIndex = function (ctrX, ctrY, ctrZ, timepoint, useNN) {
    return this.transform.getVoxelAtIndex(ctrX, ctrY, ctrZ, timepoint, useNN);
};

papaya.volume.Volume.prototype.getVoxelAtCoordinate = function (xLoc, yLoc, zLoc, timepoint, useNN) {
    return this.transform.getVoxelAtCoordinate(xLoc, yLoc, zLoc, timepoint, useNN);
};

papaya.volume.Volume.prototype.getVoxelAtMM = function (xLoc, yLoc, zLoc, timepoint, useNN) {
    return this.transform.getVoxelAtMM(xLoc, yLoc, zLoc, timepoint, useNN);
};

papaya.volume.Volume.prototype.hasError = function () {
    return (this.errorMessage !== null);
};

papaya.volume.Volume.prototype.getXDim = function () {
    return this.header.imageDimensions.xDim;
};

papaya.volume.Volume.prototype.getYDim = function () {
    return this.header.imageDimensions.yDim;
};

papaya.volume.Volume.prototype.getZDim = function () {
    return this.header.imageDimensions.zDim;
};

papaya.volume.Volume.prototype.getXSize = function () {
    return this.header.voxelDimensions.xSize;
};

papaya.volume.Volume.prototype.getYSize = function () {
    return this.header.voxelDimensions.ySize;
};

papaya.volume.Volume.prototype.getZSize = function () {
    return this.header.voxelDimensions.zSize;
};

papaya.volume.Volume.prototype.readData = function (vol, blob) {
    try {
        var reader = new FileReader();

        reader.onloadend = bind(vol, function (evt) {
            if (evt.target.readyState === FileReader.DONE) {
                vol.rawData = evt.target.result;
                setTimeout(function () {vol.decompress(vol); }, 0);
            }
        });

        reader.onerror = bind(vol, function (evt) {
            vol.errorMessage = "There was a problem reading that file:\n\n" + evt.getMessage();
            vol.finishedLoad();
        });

        reader.readAsArrayBuffer(blob);
    } catch (err) {
        vol.errorMessage = "There was a problem reading that file:\n\n" + err.message;
        vol.finishedLoad();
    }
};

papaya.volume.Volume.prototype.decompress = function (vol) {
    if (vol.compressed) {
        var gunzip = new Gunzip(this.progressMeter);
        gunzip.gunzip(vol.rawData, function (data) {vol.finishedDecompress(vol, data); });

        if (gunzip.hasError()) {
            vol.errorMessage = gunzip.getError();
            vol.finishedLoad();
        }
    } else {
        setTimeout(function () {vol.finishedReadData(vol); }, 0);
    }
};

papaya.volume.Volume.prototype.finishedDecompress = function (vol, data) {
    vol.rawData = data;

    if (this.headerType === papaya.volume.Volume.TYPE_UNKNOWN) {  // try again to determine type by reading magic cookie
        this.headerType = this.findFileTypeByMagicNumber(vol.rawData);
    }

    setTimeout(function () {vol.finishedReadData(vol); }, 0);
};

papaya.volume.Volume.prototype.finishedReadData = function (vol) {
    vol.header.readData(vol.headerType, vol.rawData, this.compressed);
    vol.header.imageType.swapped = (vol.header.imageType.littleEndian !== isPlatformLittleEndian());

    if (vol.header.hasError()) {
        vol.errorMessage = vol.header.errorMessage;
        vol.onFinishedRead(vol);
        return;
    }

    vol.imageData.readData(vol.header, vol.rawData, bind(vol, vol.finishedLoad));
};

papaya.volume.Volume.prototype.finishedLoad = function () {
    if (!this.loaded) {
        this.loaded = true;
        if (this.onFinishedRead) {
            if (!this.hasError()) {
                this.transform = new papaya.volume.Transform(papaya.volume.Transform.IDENTITY.clone(), this);
                this.numTimepoints = this.header.imageDimensions.timepoints || 1;

                this.applyBestTransform();
            }

            this.isLoaded = true;
            this.rawData = null;
            this.onFinishedRead(this);
        }
    }
};

papaya.volume.Volume.prototype.setOrigin = function (coord) {
    var coordNew = this.header.orientation.convertCoordinate(coord, new papaya.core.Coordinate(0, 0, 0));
    this.header.origin.setCoordinate(coordNew.x, coordNew.y, coordNew.z);
};

papaya.volume.Volume.prototype.getOrigin = function () {
    return this.header.orientation.convertCoordinate(this.header.origin, new papaya.core.Coordinate(0, 0, 0));
};

papaya.volume.Volume.prototype.applyBestTransform = function () {
    var bestXform = this.header.getBestTransform();

    if (bestXform !== null) {
        this.transform.worldMatNifti = numeric.inv(bestXform);
        this.setOrigin(this.header.getBestTransformOrigin());
        this.transform.updateWorldMat();
    }
};
<commit_msg>took out debugging statement<commit_after>
/*jslint browser: true, node: true */
/*global makeSlice, Base64Binary, FileReader, bind, Gunzip, isPlatformLittleEndian, deref, DataView,
GUNZIP_MAGIC_COOKIE1, GUNZIP_MAGIC_COOKIE2, numeric */

"use strict";

var papaya = papaya || {};
papaya.volume = papaya.volume || {};

papaya.volume.Volume = papaya.volume.Volume || function (progressMeter) {
    this.progressMeter = progressMeter;
    this.file = null;
    this.fileLength = 0;
    this.url = null;
    this.fileName = null;
    this.compressed = false;
    this.headerType = papaya.volume.Volume.TYPE_UNKNOWN;
    this.header = new papaya.volume.Header();
    this.imageData = new papaya.volume.ImageData();
    this.transform = null;
    this.numTimepoints = 0;
    this.rawData = null;
    this.onFinishedRead = null;
    this.errorMessage = null;
    this.transform = null;
    this.isLoaded = false;
    this.numTimepoints = 1;
    this.loaded = false;
};

papaya.volume.Volume.TYPE_UNKNOWN = 0;
papaya.volume.Volume.TYPE_NIFTI = 1;

papaya.volume.Volume.prototype.findFileType = function (filename) {
    if (filename.indexOf(".nii") !== -1) {
        return papaya.volume.Volume.TYPE_NIFTI;
    }

    return papaya.volume.Volume.TYPE_UNKNOWN;
};

papaya.volume.Volume.prototype.findFileTypeByMagicNumber = function (data) {
    var buf, mag1, mag2, mag3;

    buf = new DataView(data);

    mag1 = buf.getUint8(papaya.volume.nifti.MAGIC_NUMBER_LOCATION);
    mag2 = buf.getUint8(papaya.volume.nifti.MAGIC_NUMBER_LOCATION + 1);
    mag3 = buf.getUint8(papaya.volume.nifti.MAGIC_NUMBER_LOCATION + 2);

    if ((mag1 === papaya.volume.nifti.MAGIC_NUMBER[0]) && (mag2 === papaya.volume.nifti.MAGIC_NUMBER[1]) && (mag3 === papaya.volume.nifti.MAGIC_NUMBER[2])) {
        return papaya.volume.Volume.TYPE_NIFTI;
    }

    return papaya.volume.Volume.TYPE_UNKNOWN;
};

papaya.volume.Volume.prototype.fileIsCompressed = function (filename, data) {
    var buf, magicCookie1, magicCookie2;

    if (filename.indexOf(".gz") !== -1) {
        return true;
    }

    if (data) {
        buf = new DataView(data);

        magicCookie1 = buf.getUint8(0);
        magicCookie2 = buf.getUint8(1);

        if (magicCookie1 === GUNZIP_MAGIC_COOKIE1) {
            return true;
        }

        if (magicCookie2 === GUNZIP_MAGIC_COOKIE2) {
            return true;
        }
    }

    return false;
};

papaya.volume.Volume.prototype.readFile = function (file, callback) {
    this.file = file;
    this.fileName = file.name;
    this.onFinishedRead = callback;

    this.headerType = this.findFileType(this.fileName);

    if (this.headerType === papaya.volume.Volume.TYPE_UNKNOWN) {
        this.errorMessage = "File type is not recognized!";
        this.finishedLoad();
    } else {
        this.compressed = this.fileIsCompressed(this.fileName);
        this.fileLength = this.file.size;
        var blob = makeSlice(this.file, 0, this.file.size);
        this.readData(this, blob);
    }
};

papaya.volume.Volume.prototype.readURL = function (url, callback) {
    var vol = null, supported, xhr;

    try {
        this.url = url;
        this.fileName = url.substr(url.lastIndexOf("/") + 1, url.length);
        this.onFinishedRead = callback;

        this.headerType = this.findFileType(this.fileName);
        this.compressed = this.fileIsCompressed(this.fileName);

        vol = this;

        supported = typeof new XMLHttpRequest().responseType === 'string';
        if (supported) {
            xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'arraybuffer';

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        vol.rawData = xhr.response;
                        vol.fileLength = vol.rawData.byteLength;
                        vol.decompress(vol);
                    } else {
                        vol.errorMessage = "There was a problem reading that file (" + vol.fileName + "):\n\nResponse status = " + xhr.status;
                        vol.finishedLoad();
                    }
                }
            };

            xhr.onprogress = function (evt) {
                vol.progressMeter.drawProgress(evt.loaded / evt.total);
            };

            xhr.send(null);
        } else {
            vol.errorMessage = "There was a problem reading that file (" + vol.fileName + "):\n\nResponse type is not supported.";
            vol.finishedLoad();
        }
    } catch (err) {
        if (vol !== null) {
            vol.errorMessage = "There was a problem reading that file (" + vol.fileName + "):\n\n" + err.message;
            vol.finishedLoad();
        }
    }
};

papaya.volume.Volume.prototype.readEncodedData = function (name, callback) {
    var vol = null;

    try {
        this.fileName = name;
        this.onFinishedRead = callback;

        vol = this;

        vol.rawData = Base64Binary.decodeArrayBuffer(deref(name));

        this.headerType = this.findFileType(this.fileName);
        this.compressed = this.fileIsCompressed(this.fileName, vol.rawData);

        this.fileLength = vol.rawData.byteLength;

        vol.decompress(vol);
    } catch (err) {
        if (vol) {
            vol.errorMessage = "There was a problem reading that file:\n\n" + err.message;
            vol.finishedLoad();
        }
    }
};

papaya.volume.Volume.prototype.getVoxelAtIndex = function (ctrX, ctrY, ctrZ, timepoint, useNN) {
    return this.transform.getVoxelAtIndex(ctrX, ctrY, ctrZ, timepoint, useNN);
};

papaya.volume.Volume.prototype.getVoxelAtCoordinate = function (xLoc, yLoc, zLoc, timepoint, useNN) {
    return this.transform.getVoxelAtCoordinate(xLoc, yLoc, zLoc, timepoint, useNN);
};

papaya.volume.Volume.prototype.getVoxelAtMM = function (xLoc, yLoc, zLoc, timepoint, useNN) {
    return this.transform.getVoxelAtMM(xLoc, yLoc, zLoc, timepoint, useNN);
};

papaya.volume.Volume.prototype.hasError = function () {
    return (this.errorMessage !== null);
};

papaya.volume.Volume.prototype.getXDim = function () {
    return this.header.imageDimensions.xDim;
};

papaya.volume.Volume.prototype.getYDim = function () {
    return this.header.imageDimensions.yDim;
};

papaya.volume.Volume.prototype.getZDim = function () {
    return this.header.imageDimensions.zDim;
};

papaya.volume.Volume.prototype.getXSize = function () {
    return this.header.voxelDimensions.xSize;
};

papaya.volume.Volume.prototype.getYSize = function () {
    return this.header.voxelDimensions.ySize;
};

papaya.volume.Volume.prototype.getZSize = function () {
    return this.header.voxelDimensions.zSize;
};

papaya.volume.Volume.prototype.readData = function (vol, blob) {
    try {
        var reader = new FileReader();

        reader.onloadend = bind(vol, function (evt) {
            if (evt.target.readyState === FileReader.DONE) {
                vol.rawData = evt.target.result;
                setTimeout(function () {vol.decompress(vol); }, 0);
            }
        });

        reader.onerror = bind(vol, function (evt) {
            vol.errorMessage = "There was a problem reading that file:\n\n" + evt.getMessage();
            vol.finishedLoad();
        });

        reader.readAsArrayBuffer(blob);
    } catch (err) {
        vol.errorMessage = "There was a problem reading that file:\n\n" + err.message;
        vol.finishedLoad();
    }
};

papaya.volume.Volume.prototype.decompress = function (vol) {
    if (vol.compressed) {
        var gunzip = new Gunzip(this.progressMeter);
        gunzip.gunzip(vol.rawData, function (data) {vol.finishedDecompress(vol, data); });

        if (gunzip.hasError()) {
            vol.errorMessage = gunzip.getError();
            vol.finishedLoad();
        }
    } else {
        setTimeout(function () {vol.finishedReadData(vol); }, 0);
    }
};

papaya.volume.Volume.prototype.finishedDecompress = function (vol, data) {
    vol.rawData = data;

    if (this.headerType === papaya.volume.Volume.TYPE_UNKNOWN) {  // try again to determine type by reading magic cookie
        this.headerType = this.findFileTypeByMagicNumber(vol.rawData);
    }

    setTimeout(function () {vol.finishedReadData(vol); }, 0);
};

papaya.volume.Volume.prototype.finishedReadData = function (vol) {
    vol.header.readData(vol.headerType, vol.rawData, this.compressed);
    vol.header.imageType.swapped = (vol.header.imageType.littleEndian !== isPlatformLittleEndian());

    if (vol.header.hasError()) {
        vol.errorMessage = vol.header.errorMessage;
        vol.onFinishedRead(vol);
        return;
    }

    vol.imageData.readData(vol.header, vol.rawData, bind(vol, vol.finishedLoad));
};

papaya.volume.Volume.prototype.finishedLoad = function () {
    if (!this.loaded) {
        this.loaded = true;
        if (this.onFinishedRead) {
            if (!this.hasError()) {
                this.transform = new papaya.volume.Transform(papaya.volume.Transform.IDENTITY.clone(), this);
                this.numTimepoints = this.header.imageDimensions.timepoints || 1;

                this.applyBestTransform();
            }

            this.isLoaded = true;
            this.rawData = null;
            this.onFinishedRead(this);
        }
    }
};

papaya.volume.Volume.prototype.setOrigin = function (coord) {
    var coordNew = this.header.orientation.convertCoordinate(coord, new papaya.core.Coordinate(0, 0, 0));
    this.header.origin.setCoordinate(coordNew.x, coordNew.y, coordNew.z);
};

papaya.volume.Volume.prototype.getOrigin = function () {
    return this.header.orientation.convertCoordinate(this.header.origin, new papaya.core.Coordinate(0, 0, 0));
};

papaya.volume.Volume.prototype.applyBestTransform = function () {
    var bestXform = this.header.getBestTransform();

    if (bestXform !== null) {
        this.transform.worldMatNifti = numeric.inv(bestXform);
        this.setOrigin(this.header.getBestTransformOrigin());
        this.transform.updateWorldMat();
    }
};
<|endoftext|>


<commit_before>jQuery.fn.extend({

	// overwrite the old show method
	_show: jQuery.fn.show,

	/**
	 * The effects module overloads the show method to now allow
	 * for a speed to the show operation. What actually happens is
	 * that the height, width, and opacity to the matched elements
	 * are changed dynamically. The only three current speeds are
	 * "slow", "normal", and "fast". For example:
	 *   $("p").show("slow");
	 * Note: You should not run the show method on things
	 * that are already shown. This can be circumvented by doing this:
	 *   $("p:hidden").show("slow");
	 */
	show: function(speed,callback){
		return speed ? this.animate({
			height: "show", width: "show", opacity: "show"
		}, speed, callback) : this._show();
	},

	// Overwrite the old hide method
	_hide: jQuery.fn.hide,

	/**
	 * The hide function behaves very similary to the show function,
	 * but is just the opposite.
	 *   $("p:visible").hide("slow");
	 */
	hide: function(speed,callback){
		return speed ? this.animate({
			height: "hide", width: "hide", opacity: "hide"
		}, speed, callback) : this._hide();
	},

	/**
	 * This function increases the height and opacity for all matched
	 * elements. This is very similar to 'show', but does not change
	 * the width - creating a neat sliding effect.
	 *   $("p:hidden").slideDown("slow");
	 */
	slideDown: function(speed,callback){
		return this.animate({height: "show"}, speed, callback);
	},

	/**
	 * Just like slideDown, only it hides all matched elements.
	 *   $("p:visible").slideUp("slow");
	 */
	slideUp: function(speed,callback){
		return this.animate({height: "hide"}, speed, callback);
	},

	/**
	 * Adjusts the opacity of all matched elements from a hidden,
	 * to a fully visible, state.
	 *   $("p:hidden").fadeIn("slow");
	 */
	fadeIn: function(speed,callback){
		return this.animate({opacity: "show"}, speed, callback);
	},

	/**
	 * Same as fadeIn, but transitions from a visible, to a hidden state.
	 *   $("p:visible").fadeOut("slow");
	 */
	fadeOut: function(speed,callback){
		return this.animate({opacity: "hide"}, speed, callback);
	},

	/**
	 * ...
	 */
	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},

	/**
	 *
	 */
	animate: function(prop,speed,callback) {
		return this.queue(function(){
			var i = 0;
			for ( var p in prop ) {
				var e = new jQuery.fx( this, jQuery.speed(speed,callback,i++), p );
				if ( prop[p].constructor == Number )
					e.custom( e.cur(), prop[p] );
				else
					e[ prop[p] ]();
			}
		});
	},

	/**
	 *
	 * @private
	 */
	queue: function(type,fn){
		if ( !fn ) {
			fn = type;
			type = "fx";
		}

		return this.each(function(){
			if ( !this.queue )
				this.queue = {};

			if ( !this.queue[type] )
				this.queue[type] = [];

			this.queue[type].push( fn );

			if ( this.queue[type].length == 1 )
				fn.apply(this);
		});
	}

});

jQuery.extend({

	setAuto: function(e,p) {
		// Remember the original height
		var a = e.style[p];

		// Figure out the size of the height right now
		var o = jQuery.curCSS(e,p,1);

		// Set the height to auto
		e.style[p] = e.currentStyle ? "" : "auto";

		// See what the size of "auto" is
		var n = jQuery.curCSS(e,p,1);

		// Revert back to the original size
		if ( o != n && n != "auto" ) e.style[p] = a;
	},

	speed: function(s,o,i) {
		o = o || {};

		if ( o.constructor == Function )
			o = { complete: o };

		var ss = { slow: 600, fast: 200 };
		o.duration = (s && s.constructor == Number ? s : ss[s]) || 400;

		// Queueing
		o.oldComplete = o.complete;
		o.complete = function(){
			jQuery.dequeue(this, "fx");
			if ( o.oldComplete && o.oldComplete.constructor == Function )
				o.oldComplete.apply( this );
		};

		if ( i > 0 )
			o.complete = null;

		return o;
	},

	queue: {},

	dequeue: function(elem,type){
		type = type || "fx";

		if ( elem.queue && elem.queue[type] ) {
			// Remove self
			elem.queue[type].shift();

			// Get next function
			var f = elem.queue[type][0];

			if ( f ) f.apply( elem );
		}
	},

	/*
	 * I originally wrote fx() as a clone of moo.fx and in the process
	 * of making it small in size the code became illegible to sane
	 * people. You've been warned.
	 */

	fx: function( elem, options, prop ){

		var z = this;

		// The users options
		z.o = {
			duration: options.duration || 400,
			complete: options.complete
		};

		// The element
		z.el = elem;

		// The styles
		var y = z.el.style;

		// Simple function for setting a style value
		z.a = function(){
			if ( prop == "opacity" ) {
				if (z.now == 1) z.now = 0.9999;
				if (window.ActiveXObject)
					y.filter = "alpha(opacity=" + z.now*100 + ")";
				else
					y.opacity = z.now;

			// My hate for IE will never die
			} else if ( parseInt(z.now) )
				y[prop] = parseInt(z.now) + "px";
		};

		// Figure out the maximum number to run to
		z.max = function(){
			return parseFloat( jQuery.css(z.el,prop) );
		};

		// Get the current size
		z.cur = function(){
			return parseFloat( jQuery.curCSS(z.el, prop) ) || z.max();
		};

		// Start an animation from one number to another
		z.custom = function(from,to){
			z.startTime = (new Date()).getTime();
			z.now = from;
			z.a();

			z.timer = setInterval(function(){
				z.step(from, to);
			}, 13);
		};

		// Simple 'show' function
		z.show = function(){
			if ( !z.el.orig ) z.el.orig = {};

			// Remember where we started, so that we can go back to it later
			z.el.orig[prop] = this.cur();

			if ( !y[prop] ) z.o.auto = true;

			z.custom(0,z.max());

			// Stupid IE, look what you made me do
			if ( prop != "opacity" )
				y[prop] = "1px";

			y.display = "block";
		};

		// Simple 'hide' function
		z.hide = function(){
			if ( !z.el.orig ) z.el.orig = {};

			// Remember where we started, so that we can go back to it later
			z.el.orig[prop] = this.cur();

			z.o.hide = true;

			// Begin the animation
			z.custom(z.cur(),0);
		};

		// IE has trouble with opacity if it does not have layout
		if ( jQuery.browser.msie && !z.el.currentStyle.hasLayout )
			y.zoom = "1";

		// Remember  the overflow of the element
		z.oldOverflow = y.overflow;

		// Make sure that nothing sneaks out
		y.overflow = "hidden";

		// Each step of an animation
		z.step = function(firstNum, lastNum){
			var t = (new Date()).getTime();

			if (t > z.o.duration + z.startTime) {
				// Stop the timer
				clearInterval(z.timer);
				z.timer = null;

				z.now = lastNum;
				z.a();

				// Hide the element if the "hide" operation was done
				if ( z.o.hide ) y.display = 'none';

				// Reset the overflow
				y.overflow = z.oldOverflow;

				// If a callback was provided, execute it
				if( z.o.complete && z.o.complete.constructor == Function )
					// Execute the complete function
					z.o.complete.apply( z.el );

				// Reset the property, if the item has been hidden
				if ( z.o.hide )
					y[ prop ] = z.el.orig[ prop ].constructor == Number && prop != "opacity" ?
						z.el.orig[prop] + "px" : z.el.orig[prop];

				// set its height and/or width to auto
				jQuery.setAuto( z.el, prop );
			} else {
				// Figure out where in the animation we are and set the number
				var p = (t - this.startTime) / z.o.duration;
				z.now = ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;

				// Perform the next step of the animation
				z.a();
			}
		};

	}

});
<commit_msg>Fixed width/height animations don't lapse back to auto. There's no longer a flicker for fixed sized items. The overflow for items is no longer tampered with, if it doesn't have to be. .cur() is used for all animations in place of .max(), with much better results.<commit_after>jQuery.fn.extend({

	// overwrite the old show method
	_show: jQuery.fn.show,

	/**
	 * The effects module overloads the show method to now allow
	 * for a speed to the show operation. What actually happens is
	 * that the height, width, and opacity to the matched elements
	 * are changed dynamically. The only three current speeds are
	 * "slow", "normal", and "fast". For example:
	 *   $("p").show("slow");
	 * Note: You should not run the show method on things
	 * that are already shown. This can be circumvented by doing this:
	 *   $("p:hidden").show("slow");
	 */
	show: function(speed,callback){
		return speed ? this.animate({
			height: "show", width: "show", opacity: "show"
		}, speed, callback) : this._show();
	},

	// Overwrite the old hide method
	_hide: jQuery.fn.hide,

	/**
	 * The hide function behaves very similary to the show function,
	 * but is just the opposite.
	 *   $("p:visible").hide("slow");
	 */
	hide: function(speed,callback){
		return speed ? this.animate({
			height: "hide", width: "hide", opacity: "hide"
		}, speed, callback) : this._hide();
	},

	/**
	 * This function increases the height and opacity for all matched
	 * elements. This is very similar to 'show', but does not change
	 * the width - creating a neat sliding effect.
	 *   $("p:hidden").slideDown("slow");
	 */
	slideDown: function(speed,callback){
		return this.animate({height: "show"}, speed, callback);
	},

	/**
	 * Just like slideDown, only it hides all matched elements.
	 *   $("p:visible").slideUp("slow");
	 */
	slideUp: function(speed,callback){
		return this.animate({height: "hide"}, speed, callback);
	},

	/**
	 * Adjusts the opacity of all matched elements from a hidden,
	 * to a fully visible, state.
	 *   $("p:hidden").fadeIn("slow");
	 */
	fadeIn: function(speed,callback){
		return this.animate({opacity: "show"}, speed, callback);
	},

	/**
	 * Same as fadeIn, but transitions from a visible, to a hidden state.
	 *   $("p:visible").fadeOut("slow");
	 */
	fadeOut: function(speed,callback){
		return this.animate({opacity: "hide"}, speed, callback);
	},

	/**
	 * ...
	 */
	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},

	/**
	 *
	 */
	animate: function(prop,speed,callback) {
		return this.queue(function(){
			var i = 0;
			for ( var p in prop ) {
				var e = new jQuery.fx( this, jQuery.speed(speed,callback,i++), p );
				if ( prop[p].constructor == Number )
					e.custom( e.cur(), prop[p] );
				else
					e[ prop[p] ]( prop );
			}
		});
	},

	/**
	 *
	 * @private
	 */
	queue: function(type,fn){
		if ( !fn ) {
			fn = type;
			type = "fx";
		}

		return this.each(function(){
			if ( !this.queue )
				this.queue = {};

			if ( !this.queue[type] )
				this.queue[type] = [];

			this.queue[type].push( fn );

			if ( this.queue[type].length == 1 )
				fn.apply(this);
		});
	}

});

jQuery.extend({

	setAuto: function(e,p) {
		if ( e.notAuto ) return;

		if ( p == "height" && e.scrollHeight != parseInt(jQuery.curCSS(e,p)) ) return;
		if ( p == "width" && e.scrollWidth != parseInt(jQuery.curCSS(e,p)) ) return;

		// Remember the original height
		var a = e.style[p];

		// Figure out the size of the height right now
		var o = jQuery.curCSS(e,p,1);

		if ( p == "height" && e.scrollHeight != o ||
			p == "width" && e.scrollWidth != o ) return;

		// Set the height to auto
		e.style[p] = e.currentStyle ? "" : "auto";

		// See what the size of "auto" is
		var n = jQuery.curCSS(e,p,1);

		// Revert back to the original size
		if ( o != n && n != "auto" ) {
			e.style[p] = a;
			e.notAuto = true;
		}
	},

	speed: function(s,o,i) {
		o = o || {};

		if ( o.constructor == Function )
			o = { complete: o };

		var ss = { slow: 600, fast: 200 };
		o.duration = (s && s.constructor == Number ? s : ss[s]) || 400;

		// Queueing
		o.oldComplete = o.complete;
		o.complete = function(){
			jQuery.dequeue(this, "fx");
			if ( o.oldComplete && o.oldComplete.constructor == Function )
				o.oldComplete.apply( this );
		};

		if ( i > 0 )
			o.complete = null;

		return o;
	},

	queue: {},

	dequeue: function(elem,type){
		type = type || "fx";

		if ( elem.queue && elem.queue[type] ) {
			// Remove self
			elem.queue[type].shift();

			// Get next function
			var f = elem.queue[type][0];

			if ( f ) f.apply( elem );
		}
	},

	/*
	 * I originally wrote fx() as a clone of moo.fx and in the process
	 * of making it small in size the code became illegible to sane
	 * people. You've been warned.
	 */

	fx: function( elem, options, prop ){

		var z = this;

		// The users options
		z.o = {
			duration: options.duration || 400,
			complete: options.complete
		};

		// The element
		z.el = elem;

		// The styles
		var y = z.el.style;

		// Simple function for setting a style value
		z.a = function(){
			if ( prop == "opacity" ) {
				if (z.now == 1) z.now = 0.9999;
				if (window.ActiveXObject)
					y.filter = "alpha(opacity=" + z.now*100 + ")";
				else
					y.opacity = z.now;

			// My hate for IE will never die
			} else if ( parseInt(z.now) )
				y[prop] = parseInt(z.now) + "px";
			y.display = "block";
		};

		// Figure out the maximum number to run to
		z.max = function(){
			return parseFloat( jQuery.css(z.el,prop) );
		};

		// Get the current size
		z.cur = function(){
			return parseFloat( jQuery.curCSS(z.el, prop) ) || z.max();
		};

		// Start an animation from one number to another
		z.custom = function(from,to){
			z.startTime = (new Date()).getTime();
			z.now = from;
			z.a();

			z.timer = setInterval(function(){
				z.step(from, to);
			}, 13);
		};

		// Simple 'show' function
		z.show = function( p ){
			if ( !z.el.orig ) z.el.orig = {};

			// Remember where we started, so that we can go back to it later
			z.el.orig[prop] = this.cur();

			z.custom( 0, z.el.orig[prop] );

			// Stupid IE, look what you made me do
			if ( prop != "opacity" )
				y[prop] = "1px";
		};

		// Simple 'hide' function
		z.hide = function(){
			if ( !z.el.orig ) z.el.orig = {};

			// Remember where we started, so that we can go back to it later
			z.el.orig[prop] = this.cur();

			z.o.hide = true;

			// Begin the animation
			z.custom(z.cur(),0);
		};

		// IE has trouble with opacity if it does not have layout
		if ( jQuery.browser.msie && !z.el.currentStyle.hasLayout )
			y.zoom = "1";

		// Remember  the overflow of the element
		if ( !z.el.oldOverlay )
			z.el.oldOverflow = jQuery.css( z.el, "overflow" );

		// Make sure that nothing sneaks out
		if ( z.el.oldOverlay == "visible" )
			y.overflow = "hidden";

		// Each step of an animation
		z.step = function(firstNum, lastNum){
			var t = (new Date()).getTime();

			if (t > z.o.duration + z.startTime) {
				// Stop the timer
				clearInterval(z.timer);
				z.timer = null;

				z.now = lastNum;
				z.a();

				// Hide the element if the "hide" operation was done
				if ( z.o.hide ) y.display = 'none';

				// Reset the overflow
				y.overflow = z.el.oldOverflow;

				// If a callback was provided, execute it
				if( z.o.complete && z.o.complete.constructor == Function )
					// Execute the complete function
					z.o.complete.apply( z.el );

				// Reset the property, if the item has been hidden
				if ( z.o.hide )
					y[ prop ] = z.el.orig[ prop ].constructor == Number && prop != "opacity" ?
						z.el.orig[prop] + "px" : z.el.orig[prop];

				// set its height and/or width to auto
				jQuery.setAuto( z.el, prop );
			} else {
				// Figure out where in the animation we are and set the number
				var p = (t - this.startTime) / z.o.duration;
				z.now = ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;

				// Perform the next step of the animation
				z.a();
			}
		};

	}

});
<|endoftext|>


<commit_before>import React from 'react';

const compare = (attempt, randomNum) => {
  // let show;
  //
  // if (!attempt) {
  //   show =

  //
Try Your Luck!

  //

  // } else if (attempt > randomNum) {
  //   show =

  //
Your Last Guess Was

  //
{attempt}

  //
Nice try! You're too high!

  //

  // } else if (attempt < randomNum) {
  //   show =

  //
Your Last Guess Was

  //
{attempt}

  //
Uh oh! You're too low!

  //

  // } else {
  //   show =

  //
Your Last Guess Was

  //
{attempt}

  //
Right on the money!

  //

  // }
  //
  // return (
  //
{show}

  // )
};

export default compare;
<commit_msg>add conditional statements<commit_after>import React from 'react';

const compareGuess = (guess, randomNum) => {

  if (guess > randomNum) {
    return "Nice try! You're too high!"
  }
  if (guess < randomNum) {
    return "Uh oh! You're too low!"
  }
  if (guess === randomNum){
    return "Right on the money!"
  }
};

export default compareGuess;
<|endoftext|>


<commit_before>(function(w, d, undefined) {
  'use strict';

  /*
   * aliases
   * w: window global object
   * d: document
   * undefined: undefined
   */

  // polyfill
  function polyfill() {
    // return when scrollBehavior interface is supported
    if ('scrollBehavior' in d.documentElement.style) {
      return;
    }

    /*
     * globals
     */
    var Element = w.HTMLElement || w.Element;
    var SCROLL_TIME = 468;

    /*
     * object gathering original scroll methods
     */
    var original = {
      scroll: w.scroll || w.scrollTo,
      scrollBy: w.scrollBy,
      elScroll: Element.prototype.scroll || scrollElement,
      scrollIntoView: Element.prototype.scrollIntoView
    };

    /*
     * define timing method
     */
    var now = w.performance && w.performance.now
      ? w.performance.now.bind(w.performance) : Date.now;

    /**
     * changes scroll position inside an element
     * @method scrollElement
     * @param {Number} x
     * @param {Number} y
     */
    function scrollElement(x, y) {
      this.scrollLeft = x;
      this.scrollTop = y;
    }

    /**
     * returns result of applying ease math function to a number
     * @method ease
     * @param {Number} k
     * @returns {Number}
     */
    function ease(k) {
      return 0.5 * (1 - Math.cos(Math.PI * k));
    }

    /**
     * indicates if a smooth behavior should be applied
     * @method shouldBailOut
     * @param {Number|Object} x
     * @returns {Boolean}
     */
    function shouldBailOut(x) {
      if (typeof x !== 'object'
            || x === null
            || x.behavior === undefined
            || x.behavior === 'auto'
            || x.behavior === 'instant') {
        // first arg not an object/null
        // or behavior is auto, instant or undefined
        return true;
      }

      if (typeof x === 'object'
            && x.behavior === 'smooth') {
        // first argument is an object and behavior is smooth
        return false;
      }

      // throw error when behavior is not supported
      throw new TypeError('behavior not valid');
    }

    /**
     * finds scrollable parent of an element
     * @method findScrollableParent
     * @param {Node} el
     * @returns {Node} el
     */
    function findScrollableParent(el) {
      var isBody;
      var hasScrollableSpace;
      var hasVisibleOverflow;

      do {
        el = el.parentNode;

        // set condition variables
        isBody = el === d.body;
        hasScrollableSpace =
          el.clientHeight < el.scrollHeight ||
          el.clientWidth < el.scrollWidth;
        hasVisibleOverflow =
          w.getComputedStyle(el, null).overflow === 'visible';
      } while (!isBody && !(hasScrollableSpace && !hasVisibleOverflow));

      isBody = hasScrollableSpace = hasVisibleOverflow = null;

      return el;
    }

    /**
     * self invoked function that, given a context, steps through scrolling
     * @method step
     * @param {Object} context
     */
    function step(context) {
      var time = now();
      var value;
      var currentX;
      var currentY;
      var elapsed = (time - context.startTime) / SCROLL_TIME;

      // avoid elapsed times higher than one
      elapsed = elapsed > 1 ? 1 : elapsed;

      // apply easing to elapsed time
      value = ease(elapsed);

      currentX = context.startX + (context.x - context.startX) * value;
      currentY = context.startY + (context.y - context.startY) * value;

      context.method.call(context.scrollable, currentX, currentY);

      // scroll more if we have not reached our destination
      if (currentX !== context.x || currentY !== context.y) {
        w.requestAnimationFrame(step.bind(w, context));
      }
    }

    /**
     * scrolls window with a smooth behavior
     * @method smoothScroll
     * @param {Object|Node} el
     * @param {Number} x
     * @param {Number} y
     */
    function smoothScroll(el, x, y) {
      var scrollable;
      var startX;
      var startY;
      var method;
      var startTime = now();

      // define scroll context
      if (el === d.body) {
        scrollable = w;
        startX = w.scrollX || w.pageXOffset;
        startY = w.scrollY || w.pageYOffset;
        method = original.scroll;
      } else {
        scrollable = el;
        startX = el.scrollLeft;
        startY = el.scrollTop;
        method = scrollElement;
      }

      // scroll looping over a frame
      step({
        scrollable: scrollable,
        method: method,
        startTime: startTime,
        startX: startX,
        startY: startY,
        x: x,
        y: y
      });
    }

    /*
     * ORIGINAL METHODS OVERRIDES
     */

    // w.scroll and w.scrollTo
    w.scroll = w.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scroll.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left,
        ~~arguments[0].top
      );
    };

    // w.scrollBy
    w.scrollBy = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollBy.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left + (w.scrollX || w.pageXOffset),
        ~~arguments[0].top + (w.scrollY || w.pageYOffset)
      );
    };

    // Element.prototype.scroll and Element.prototype.scrollTo
    Element.prototype.scroll = Element.prototype.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.elScroll.call(
            this,
            arguments[0].left || arguments[0],
            arguments[0].top || arguments[1]
        );
        return;
      }

      var left = arguments[0].left;
      var top = arguments[0].top;

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
          this,
          this,
          typeof left === 'number' ? left : this.scrollLeft,
          typeof top === 'number' ? top : this.scrollTop
      );
    };

    // Element.prototype.scrollBy
    Element.prototype.scrollBy = function() {
      var arg0 = arguments[0];

      if (typeof arg0 === 'object') {
        this.scroll({
          left: arg0.left + this.scrollLeft,
          top: arg0.top + this.scrollTop,
          behavior: arg0.behavior
        });
      } else {
        this.scroll(
          this.scrollLeft + arg0,
          this.scrollTop + arguments[1]
        );
      }
    };

    // Element.prototype.scrollIntoView
    Element.prototype.scrollIntoView = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollIntoView.call(this, arguments[0] === undefined ? true : arguments[0]);
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      var scrollableParent = findScrollableParent(this);
      var parentRects = scrollableParent.getBoundingClientRect();
      var clientRects = this.getBoundingClientRect();

      if (scrollableParent !== d.body) {
        // reveal element inside parent
        smoothScroll.call(
          this,
          scrollableParent,
          scrollableParent.scrollLeft + clientRects.left - parentRects.left,
          scrollableParent.scrollTop + clientRects.top - parentRects.top
        );
        // reveal parent in viewport
        w.scrollBy({
          left: parentRects.left,
          top: parentRects.top,
          behavior: 'smooth'
        });
      } else {
        // reveal element in viewport
        w.scrollBy({
          left: clientRects.left,
          top: clientRects.top,
          behavior: 'smooth'
        });
      }
    };
  }

  if (typeof exports === 'object') {
    // commonjs
    module.exports = { polyfill: polyfill };
  } else {
    // global
    polyfill();
  }
})(window, document);
<commit_msg>Add a tolerance for clientHeight in Microsoft Browsers<commit_after>(function(w, d, undefined) {
  'use strict';

  /*
   * aliases
   * w: window global object
   * d: document
   * undefined: undefined
   */

  // polyfill
  function polyfill() {
    // return when scrollBehavior interface is supported
    if ('scrollBehavior' in d.documentElement.style) {
      return;
    }

    /*
     * globals
     */
    var Element = w.HTMLElement || w.Element;
    var SCROLL_TIME = 468;

    /*
     * object gathering original scroll methods
     */
    var original = {
      scroll: w.scroll || w.scrollTo,
      scrollBy: w.scrollBy,
      elScroll: Element.prototype.scroll || scrollElement,
      scrollIntoView: Element.prototype.scrollIntoView
    };

    /*
     * define timing method
     */
    var now = w.performance && w.performance.now
      ? w.performance.now.bind(w.performance) : Date.now;

    /**
     * changes scroll position inside an element
     * @method scrollElement
     * @param {Number} x
     * @param {Number} y
     */
    function scrollElement(x, y) {
      this.scrollLeft = x;
      this.scrollTop = y;
    }

    /**
     * returns result of applying ease math function to a number
     * @method ease
     * @param {Number} k
     * @returns {Number}
     */
    function ease(k) {
      return 0.5 * (1 - Math.cos(Math.PI * k));
    }

    /**
     * indicates if a smooth behavior should be applied
     * @method shouldBailOut
     * @param {Number|Object} x
     * @returns {Boolean}
     */
    function shouldBailOut(x) {
      if (typeof x !== 'object'
            || x === null
            || x.behavior === undefined
            || x.behavior === 'auto'
            || x.behavior === 'instant') {
        // first arg not an object/null
        // or behavior is auto, instant or undefined
        return true;
      }

      if (typeof x === 'object'
            && x.behavior === 'smooth') {
        // first argument is an object and behavior is smooth
        return false;
      }

      // throw error when behavior is not supported
      throw new TypeError('behavior not valid');
    }

    /**
     * indicates if a the current browser is made by Microsoft
     * @method isMicrosoftBrowser
     * @param {string} userAgent
     * @returns {Boolean}
     */
    function isMicrosoftBrowser(userAgent) {
      var userAgentPatterns = ['MSIE ', 'Trident/', 'Edge/'];
      return new RegExp(userAgentPatterns.join('|')).test(userAgent);
    }

    /**
     * finds scrollable parent of an element
     * @method findScrollableParent
     * @param {Node} el
     * @returns {Node} el
     */
    function findScrollableParent(el) {
      /*
        Microsoft browsers can round a computed height that contains a
        fraction of a pixel up for clientHeight, and down for scrollHeight.
      */
      var roundingTolerance = isMicrosoftBrowser(w.navigator.userAgent) ? 1 : 0;
      var isBody;
      var hasScrollableSpace;
      var hasVisibleOverflow;

      do {
        el = el.parentNode;

        // set condition variables
        isBody = el === d.body;
        hasScrollableSpace =
          el.clientHeight + roundingTolerance < el.scrollHeight ||
          el.clientWidth + roundingTolerance < el.scrollWidth;
        hasVisibleOverflow =
          w.getComputedStyle(el, null).overflow === 'visible';
      } while (!isBody && !(hasScrollableSpace && !hasVisibleOverflow));

      isBody = hasScrollableSpace = hasVisibleOverflow = null;

      return el;
    }

    /**
     * self invoked function that, given a context, steps through scrolling
     * @method step
     * @param {Object} context
     */
    function step(context) {
      var time = now();
      var value;
      var currentX;
      var currentY;
      var elapsed = (time - context.startTime) / SCROLL_TIME;

      // avoid elapsed times higher than one
      elapsed = elapsed > 1 ? 1 : elapsed;

      // apply easing to elapsed time
      value = ease(elapsed);

      currentX = context.startX + (context.x - context.startX) * value;
      currentY = context.startY + (context.y - context.startY) * value;

      context.method.call(context.scrollable, currentX, currentY);

      // scroll more if we have not reached our destination
      if (currentX !== context.x || currentY !== context.y) {
        w.requestAnimationFrame(step.bind(w, context));
      }
    }

    /**
     * scrolls window with a smooth behavior
     * @method smoothScroll
     * @param {Object|Node} el
     * @param {Number} x
     * @param {Number} y
     */
    function smoothScroll(el, x, y) {
      var scrollable;
      var startX;
      var startY;
      var method;
      var startTime = now();

      // define scroll context
      if (el === d.body) {
        scrollable = w;
        startX = w.scrollX || w.pageXOffset;
        startY = w.scrollY || w.pageYOffset;
        method = original.scroll;
      } else {
        scrollable = el;
        startX = el.scrollLeft;
        startY = el.scrollTop;
        method = scrollElement;
      }

      // scroll looping over a frame
      step({
        scrollable: scrollable,
        method: method,
        startTime: startTime,
        startX: startX,
        startY: startY,
        x: x,
        y: y
      });
    }

    /*
     * ORIGINAL METHODS OVERRIDES
     */

    // w.scroll and w.scrollTo
    w.scroll = w.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scroll.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left,
        ~~arguments[0].top
      );
    };

    // w.scrollBy
    w.scrollBy = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollBy.call(
          w,
          arguments[0].left || arguments[0],
          arguments[0].top || arguments[1]
        );
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
        w,
        d.body,
        ~~arguments[0].left + (w.scrollX || w.pageXOffset),
        ~~arguments[0].top + (w.scrollY || w.pageYOffset)
      );
    };

    // Element.prototype.scroll and Element.prototype.scrollTo
    Element.prototype.scroll = Element.prototype.scrollTo = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.elScroll.call(
            this,
            arguments[0].left || arguments[0],
            arguments[0].top || arguments[1]
        );
        return;
      }

      var left = arguments[0].left;
      var top = arguments[0].top;

      // LET THE SMOOTHNESS BEGIN!
      smoothScroll.call(
          this,
          this,
          typeof left === 'number' ? left : this.scrollLeft,
          typeof top === 'number' ? top : this.scrollTop
      );
    };

    // Element.prototype.scrollBy
    Element.prototype.scrollBy = function() {
      var arg0 = arguments[0];

      if (typeof arg0 === 'object') {
        this.scroll({
          left: arg0.left + this.scrollLeft,
          top: arg0.top + this.scrollTop,
          behavior: arg0.behavior
        });
      } else {
        this.scroll(
          this.scrollLeft + arg0,
          this.scrollTop + arguments[1]
        );
      }
    };

    // Element.prototype.scrollIntoView
    Element.prototype.scrollIntoView = function() {
      // avoid smooth behavior if not required
      if (shouldBailOut(arguments[0])) {
        original.scrollIntoView.call(this, arguments[0] === undefined ? true : arguments[0]);
        return;
      }

      // LET THE SMOOTHNESS BEGIN!
      var scrollableParent = findScrollableParent(this);
      var parentRects = scrollableParent.getBoundingClientRect();
      var clientRects = this.getBoundingClientRect();

      if (scrollableParent !== d.body) {
        // reveal element inside parent
        smoothScroll.call(
          this,
          scrollableParent,
          scrollableParent.scrollLeft + clientRects.left - parentRects.left,
          scrollableParent.scrollTop + clientRects.top - parentRects.top
        );
        // reveal parent in viewport
        w.scrollBy({
          left: parentRects.left,
          top: parentRects.top,
          behavior: 'smooth'
        });
      } else {
        // reveal element in viewport
        w.scrollBy({
          left: clientRects.left,
          top: clientRects.top,
          behavior: 'smooth'
        });
      }
    };
  }

  if (typeof exports === 'object') {
    // commonjs
    module.exports = { polyfill: polyfill };
  } else {
    // global
    polyfill();
  }
})(window, document);
<|endoftext|>