DrawerComponentView.js 20.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
/*
 *
 * ADOBE CONFIDENTIAL
 * __________________
 *
 *  Copyright 2014 Adobe Systems Incorporated
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */
define('ux/views/DrawerComponentView', [
    'underscore',
    'jquery',
    'util/Util',
    'views/BaseView'
], function(_, $, Util, BaseView) {
    'use strict';

    var DRAWER_CLASSES = {
        drawerClass: 'screens-DrawerComponent-drawer',
        handleClass: 'screens-DrawerComponent-handle',
        contentClass: 'screens-DrawerComponent-content',
        drawerIsOpen: 'drawer-is-open'
    };

    var DEFAULT_OPTIONS = {
        drawerContentElement: null,
        contentElement: null,
        parentClassName: '',
        pullDirection: 'bottom',
        drawerClass: DRAWER_CLASSES.drawerClass,
        handleClass: DRAWER_CLASSES.handleClass,
        contentClass: DRAWER_CLASSES.contentClass,
        drawerOpenLocation: 0,
        drawerCloseLocation: -100,
        handleOpenLocation: 0,
        handleCloseLocation: -100,
        contentOpenLocation: 0,
        contentCloseLocation: -100,
        autoResizesContentView: false,
        contentViewMinimumSize: 0,
        contentViewMaximumSize: 0,
        allowedDragOnHandle: true
    };

    var TRANSITION_DURATION = 300;

    var DrawerComponentView = BaseView.extend(/** @lends DrawerComponentView.prototype */{

        // the drawer consists of a drawer, a handle, and content
        templateDrawer: function(options, defaults, handleContentClass) {
            var tmpl = _.template(
                    '<div class="<%=options.drawerClass%> <%=defaults.drawerClass%>">' +
                    '</div>' +
                    '<div class="<%=handleContentClass%>" style="width:100%; height:100%; display:inline-block; position:relative">' +
                        '<div class="<%=options.handleClass%> <%=defaults.handleClass%>"/>' +
                        '<div class="<%=options.contentClass%> <%=defaults.contentClass%>"/>' +
                    '</div>'
            );

            return tmpl({
                options: options,
                defaults: defaults,
                handleContentClass: handleContentClass
            });
        },

        tagName: 'div',

        id: '',

        className: 'screens-DrawerComponent',

        events: {
            // we don't need to handle tap since pointerdown and pointerup will do that
            'pointerdown .screens-DrawerComponent-handle': 'handleDrawerDragStart',
            'pointermove': '_handleDrawerDragging',
            'pointerup': '_handleDrawerDragEnd'
        },

        sistineOptions: {
            events: {
                'press .screens-DrawerComponent-handle': '_handlePressOnHandle'
            },

            recognizers: [
                {name: 'press', options: {eventName: 'press', duration: 0}}
            ]
        },

        /**
         * Creates a new drawer component
         *
         * @class DrawerComponentView
         * @extends BaseView
         *
         * @param {Object} [options] An object of configurable options.
         * @param {String} [options.parentClassName='']               The css class name of the parent div that contains this drawer component
         * @param {String} [options.pullDirection='bottom']           Either top, left, right, or bottom, pull to open
         * @param {HTMLElement|jQuery} options.drawerContentElement   The content inside the drawer
         * @param {HTMLElement|jQuery} options.contentElement         The content that is attached outside of this drawer
         * @param {String} [options.drawerClass=DRAWER_CLASSES.drawerClass]     The css class name of the drawer itself
         * @param {String} [options.handleClass=DRAWER_CLASSES.handleClass]     The css class name of the handle
         * @param {String} [options.contentClass=DRAWER_CLASSES.contentClass]   The css class name of the content that is attached to this drawer
         * @param {Number} [options.drawerOpenLocation=0]              The location of either 'top or left' when the drawer opened
         * @param {Number} [options.drawerCloseLocation=-100]          The location of either 'top or left' when the drawer closed
         * @param {Number} [options.handleOpenLocation=0]              The location of either 'top or left' of the handle when the drawer is open
         * @param {Number} [options.handleCloseLocation=-100]          The location of either 'top or left' of the handle when the drawer is closed
         * @param {Number} [options.contentOpenLocation=0]             The location of either 'top or left' of the content when the drawer is open
         * @param {Number} [options.contentCloseLocation=-100]         The location of either 'top or left' of the content when the drawer is closed
         * @param {Boolean} [options.autoResizesContentView=false]     If this is set to true, we will resize the contentView's width when the drawer is moving
         * @param {Number} [options.contentViewMinimumSize=0]          The size of the content view when the drawer is open, only used when autoResizesContentView is set to true
         * @param {Number} [options.contentViewMaximumSize=0]          The size of the content view when the drawer is collapsed, only used when autoResizesContentView is set to true
         * @param {Boolean} [options.allowedDragOnHandle=true]         Options to allow dragging on handle to close drawer
         */
        constructor: function(options) {
            this._initOptions(options, DEFAULT_OPTIONS);
            DrawerComponentView.__super__.constructor.apply(this, arguments);
        },

        initialize: function() {
            DrawerComponentView.__super__.initialize.apply(this, arguments);

            // local variables
            // a flag to tell whether we drag on the handle, if we didn't drag, we can act like tap
            this._handleDidDrag = false;
            // this is to keep track of the last location of the mouse/touch so that we can increase/decrease the size of the drawer on drag
            this._lastDragLocation = null;

            if (this.options.autoResizesContentView) {
                this._cssContentSize = (this.options.pullDirection === 'left' || this.options.pullDirection === 'right') ? 'width' : 'height';
            }
            this._cachedDivs = null;
            this._handleContentGroupName = this.options.handleClass + this.options.contentClass;
            this._currentHandleLocation = null;
            this._currentDrawerLocation = null;
        },

        render: function() {
            // prevent re-render
            if (this.setRendered(true)) {
                return this;
            }

            var thisDrawerComponent = this.$el.html(this.templateDrawer(this.options, DRAWER_CLASSES, this._handleContentGroupName));

            // add drawerContentElement to screens-DrawerComponent-drawer
            var theDrawer = thisDrawerComponent.find('.' + this.options.drawerClass);
            theDrawer.append($(this.options.drawerContentElement));

            // add contentElement to screens-DrawerComponent-content
            var theContent = thisDrawerComponent.find('.' + this.options.contentClass);
            theContent.append($(this.options.contentElement));

            // collapse the drawer by default
            this.collapseDrawer(true);

            return this;
        },

        destroy: function() {
            this._cachedDivs = null;
            return DrawerComponentView.__super__.destroy.apply(this, arguments);
        },

        /**
         * open the drawer
         *
         * @param {Boolean} [immediately=false] if this is true, we will skip the animation
         */
        openDrawer: function(immediately) {
            var divsInDrawer = this._getDivsInDrawer(this.$el);
            divsInDrawer.drawer.addClass(DRAWER_CLASSES.drawerIsOpen);
            var transitionDuration = TRANSITION_DURATION;
            if (immediately) {
                transitionDuration = 0;
            }
            this._handleMove(divsInDrawer, this.options.drawerOpenLocation, this.options.handleOpenLocation, this.options.contentOpenLocation, this.options.contentViewMinimumSize, transitionDuration);
        },

        /**
         * close the drawer with transition
         *
         * @param {Boolean}  [immediately=false] if this is true, we will skip the animation
         * @param {Function} [fnc]               the callback function to call
         */
        collapseDrawer: function(immediately, fnc) {
            var divsInDrawer = this._getDivsInDrawer(this.$el);
            divsInDrawer.drawer.removeClass(DRAWER_CLASSES.drawerIsOpen);
            var transitionDuration = TRANSITION_DURATION;
            if (immediately) {
                transitionDuration = 0;
            }
            this._handleMove(divsInDrawer, this.options.drawerCloseLocation, this.options.handleCloseLocation, this.options.contentCloseLocation, this.options.contentViewMaximumSize, transitionDuration);
            if (_.isFunction(fnc)) {
                if (transitionDuration === 0) {
                    fnc();
                } else {
                    // todo: use proper animation complete events
                    setTimeout(fnc, TRANSITION_DURATION);
                }
            }
        },

        /**
         * toggle the open/close of the drawer with transition
         *<
         * @param {Boolean} [immediately=false] if this is true, we will skip the animation
         */
        toggleDrawer: function(immediately) {
            var parentElement = this.$el;
            var drawerEl = parentElement.find('.' + this.options.drawerClass);
            if (drawerEl.hasClass(DRAWER_CLASSES.drawerIsOpen)) {
                this.collapseDrawer(immediately);
            } else {
                this.openDrawer(immediately);
            }
        },

        /**
         * Checks whether the drawer is opened or not.
         *
         * @returns {Boolean} true when the drawer is open, false otherwise
         */
        isDrawerOpen: function() {
            var drawerEl = this.$el.find('.' + this.options.drawerClass);
            return drawerEl.hasClass(DRAWER_CLASSES.drawerIsOpen);
        },

        /**
         * set data to the drawer
         *
         * @param {String|HTMLElement|Array} [htmlData] The html string data for the drawer such as buttons, etc
         */
        setDrawerData: function(htmlData) {
            this.options.drawerContentElement = htmlData;
            var theDrawer = this.$el.find('.' + this.options.drawerClass);
            theDrawer.append(htmlData);
        },

        /**
         * set data to the content that is attached to this drawer
         *
         * @param {String} [htmlData] The html string data of the content
         */
        setContentData: function(htmlData) {
            this.options.contentElement = htmlData;
            var theContent = this.$el.find('.' + this.options.contentClass);
            theContent.append(htmlData);
        },

        _handleMove: function(divs, drawerLocation, handleLocation, contentLocation, contentViewSize, duration) {
            var self = this;
            var newStatus = 'close';
            if (contentLocation === this.options.contentOpenLocation) {
                newStatus = 'open';
            }
            // before toggling the drawer, send drawer-sizewillchange event
            self.dispatchEvent('drawer-sizewillchange', {
                duration: duration,
                newStatus: newStatus
            });

            this._currentHandleLocation = handleLocation;
            this._currentDrawerLocation = drawerLocation;

            var onHandleMoveAnimEnd = _.after(3, function() {
                self.dispatchEvent('drawer-sizechanged');
                self.dispatchEvent('drawer-sizechangedended');
            });

            if (this.options.pullDirection === 'left' || this.options.pullDirection === 'right') {
                // TODO: implement autoRemoveChildren
                divs.drawer.transition({x: drawerLocation}, duration, onHandleMoveAnimEnd);
                divs.handleContentGroup.transition({x: handleLocation}, duration, onHandleMoveAnimEnd);
            } else {
                // TODO: implement autoRemoveChildren
                divs.drawer.transition({y: drawerLocation}, duration, onHandleMoveAnimEnd);
                divs.handleContentGroup.transition({y: handleLocation}, duration, onHandleMoveAnimEnd);
            }
            if (this.options.autoResizesContentView) {
                var args = {};
                args[this._cssContentSize] = contentViewSize;
                // TODO: improve animation by replacing width/height animations
                divs.content.transition(args, duration, onHandleMoveAnimEnd);
            } else {
                // This is a workaround which ensures that the "animation end"
                // callback is called properly.
                onHandleMoveAnimEnd();
            }

        },

        /**
         * check to see if we are hitting this drawer's handle, if we do,
         * set up some flags so that we can handle the dragging of drawer's handle
         * @param {jquery.Event} [ev] the pointerdown event
         */
        handleDrawerDragStart: function(ev) {
            if (!this.options.allowedDragOnHandle) {
                return;
            }
            var target = $(ev.currentTarget);
            var parentElem = target.closest(this.options.parentClassName);
            var handleEl = parentElem.find('.' + this.options.handleClass);

            // if we didn't hit this handle, don't do anything
            if (ev.target !== handleEl.get(0)) {
                return;
            }
            this._handleDidDrag = false;
            this._lastDragLocation = ev.originalEvent.clientY;
            if (this.options.pullDirection === 'left' || this.options.pullDirection === 'right') {
                this._lastDragLocation = ev.originalEvent.clientX;
            }
        },

        _handleDrawerDragging: function(e) {
            // as we drag, we animate the cssAnimationProperty of this drawer
            if (this._lastDragLocation === null) {
                return;
            }
            this._handleDidDrag = true;

            // console.log("dragging");
            var ev = e.originalEvent;
            var target = $(e.currentTarget);
            var parentElem = target.closest(this.options.parentClassName);
            var currentLocation = ev.clientY;

            if (this.options.pullDirection === 'left' || this.options.pullDirection === 'right') {
                currentLocation = ev.clientX;
            }

            if (currentLocation !== this._lastDragLocation) {
                var divsInDrawer = this._getDivsInDrawer(parentElem);
                var newVal = currentLocation - this._lastDragLocation + this._currentHandleLocation;
                newVal = Math.max(this.options.handleCloseLocation, newVal);
                newVal = Math.min(newVal, this.options.handleOpenLocation);
                var valToChange = newVal - this._currentHandleLocation;

                this._currentDrawerLocation += valToChange;
                this._currentHandleLocation += valToChange;

                // move only the drawer and handleContentGroup
                if (this.options.pullDirection === 'left' || this.options.pullDirection === 'right') {
                    // TODO: implement autoRemoveChildren
                    divsInDrawer.drawer.css({x: this._currentDrawerLocation});
                    divsInDrawer.handleContentGroup.css({x: this._currentHandleLocation});
                } else {
                    divsInDrawer.drawer.css({y: this._currentDrawerLocation});
                    divsInDrawer.handleContentGroup.css({y: this._currentHandleLocation});
                }

                if (this.options.autoResizesContentView) {
                    var existingSize = parseInt(divsInDrawer.content.css(this._cssContentSize), 10);
                    divsInDrawer.content.css(this._cssContentSize, existingSize - valToChange + 'px');
                }
            }

            this._lastDragLocation = currentLocation;

            this.dispatchEvent('drawer-sizechanged');
        },

        _handleDrawerDragEnd: function(ev) {
            var target = $(ev.currentTarget);
            var parentElem = target.closest(this.options.parentClassName);
            var handleEl = parentElem.find('.' + this.options.handleClass);
            handleEl.removeClass('active');

            if (!this._lastDragLocation) {
                // console.log("dragEnd without start");
                return;
            }

            if (this._snapDrawerOnDragDirection(this._lastDragLocation, parentElem, ev)) {
                this._lastDragLocation = null;
                return;
            }

            this._lastDragLocation = null;

            // if we did not drag, act like tap
            if (!this._handleDidDrag) {
                this.toggleDrawer();
                return;
            }
            this._handleDidDrag = false;

            // if the drawer is open or closed more than half way, snap it to either open or close
            if (this._currentDrawerLocation < this.options.drawerCloseLocation / 2) {
                this.collapseDrawer();
            } else {
                this.openDrawer();
            }
        },

        /**
         * if we are dragging on the handle, snap the handle toward the drag direction if appropriate
         *
         * @param {Number} lastDragLocation    The last position
         * @param {jQuery}  parentElem          The parent elmement
         * @param {Event}   ev                  The event that was triggered
         *
         * @returns {Boolean} Whether to snap the drawer or not
         */
        _snapDrawerOnDragDirection: function(lastDragLocation, parentElem, ev) {
            var currentLocation = ev.clientY;
            if (this.options.pullDirection === 'left' || this.options.pullDirection === 'right') {
                currentLocation = ev.clientX;
            }

            if (lastDragLocation === currentLocation) {
                return false;
            }

            var snapClose = false;
            var snapOpen = false;
            var drawerEl = parentElem.find('.' + this.options.drawerClass);
            var drawerIsOpen = drawerEl.hasClass(DRAWER_CLASSES.drawerIsOpen);

            if ((this.options.pullDirection === 'right') || (this.options.pullDirection === 'bottom')) {
                if (drawerIsOpen && lastDragLocation > currentLocation) {
                    snapClose = true;
                } else if (lastDragLocation < currentLocation) {
                    snapOpen = true;
                }
            } else if (drawerIsOpen && lastDragLocation < currentLocation) {
                snapClose = true;
            } else if (lastDragLocation > currentLocation) {
                snapOpen = true;
            }

            if (snapClose) {
                this.collapseDrawer();
                return true;
            } else if (snapOpen) {
                this.openDrawer();
                return true;
            }

            return false;
        },

        _getDivsInDrawer: function(parentElement) {
            if (!this._cachedDivs) {
                var allDivs = {};

                var drawerEl = parentElement.find('.' + this.options.drawerClass);
                allDivs.drawer = drawerEl;

                var contentEl = parentElement.find('.' + this.options.contentClass);
                allDivs.content = contentEl;

                var handleContentGroupEL = parentElement.find('.' + this._handleContentGroupName);
                allDivs.handleContentGroup = handleContentGroupEL;

                this._cachedDivs = allDivs;
            }
            return this._cachedDivs;
        },

        _handlePressOnHandle: function(ev) {
            Util.buttonPressedUIHandler(ev);
        }
    });

    // return module export
    return DrawerComponentView;
});