All files / components/reorderer/js Reorderer.js

77.04% Statements 255/331
69.05% Branches 87/126
75.47% Functions 40/53
77.04% Lines 255/331

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965                                6x   6x     6x   6x                                                                     6x 56x 56x       56x                             56x 56x       6x 56x 56x 56x 56x             6x                 6x                                         6x     225x                 81x                 6x 89x 89x     6x 56x                                               6x                                                                                                                                                                                                                                                                                                               6x 101x       6x 290x 459x 93x     197x       6x 91x       6x 308x 15x     293x 293x   91x 89x 89x 89x 89x   91x     202x       6x 202x 202x     202x 202x 247x 247x 247x 59x   188x   188x 188x 188x 7x     181x 80x 80x     80x 80x 5x 2x 2x   3x     80x 77x     101x 97x 97x   181x   21x       6x 101x 6x   95x     95x 86x 86x   86x 86x 86x 86x 86x   9x       6x 77x   77x 4x   73x         73x   73x 73x       73x   73x   73x   73x       6x         6x 56x 56x                   6x 175x     6x 53x 53x 53x 53x     6x 371x 371x 371x 371x     6x 130x 262x 262x     130x 621x 621x     130x 1x 1x 1x       130x 130x 1501x 1501x 591x   591x 591x 591x   591x 591x 591x 591x     130x 56x               6x 621x   621x 109x     621x 621x 621x 621x 621x 621x           6x 573x 573x 573x   573x           573x           573x   573x                                                                                                           6x 130x 130x 130x     130x 1444x 1444x 573x 573x         130x 53x     130x   130x                       130x   130x       6x 130x 130x 130x 130x 130x 74x 74x   130x             6x           6x         6x         6x 6x 6x 6x 6x     6x 56x 188x 188x 188x                     6x 1561x             11572x     1397x 1397x             1561x     6x                         6x                                                   6x                                   6x 33x                   6x                                                                                                                       6x 56x       6x 56x       6x 130x 130x 130x 1501x 1501x 1501x 1501x 1501x 1501x 74x 74x   74x 38x 38x 38x 38x     74x   1501x         6x 73x     73x 73x 73x             6x 1648x 1648x 251x   1648x       6x 1648x 1648x 1648x   1648x 1648x   1648x 74x   1648x             1648x 1648x 1648x              
/*
Copyright 2007-2009 University of Toronto
Copyright 2007-2010 University of Cambridge
Copyright 2010-2016 OCAD University
Copyright 2010-2011 Lucendo Development Ltd.
Copyright 2012-2014 Raising the Floor - US
Copyright 2015-2016 Raising the Floor - International
 
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
 
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
 
var fluid_3_0_0 = fluid_3_0_0 || {};
 
(function ($, fluid) {
    "use strict";
 
    fluid.registerNamespace("fluid.reorderer");
 
    fluid.reorderer.defaultAvatarCreator = function (item, cssClass, dropWarning) {
        fluid.dom.cleanseScripts(fluid.unwrap(item));
        var avatar = $(item).clone();
 
        fluid.dom.iterateDom(avatar.get(0), function (node) {
            node.removeAttribute("id");
            if (node.tagName.toLowerCase() === "input") {
                node.setAttribute("disabled", "disabled");
            }
        });
 
        avatar.removeProp("id");
        avatar.removeClass("ui-droppable");
        avatar.addClass(cssClass);
 
        if (dropWarning) {
            // Will a 'div' always be valid in this position?
            var avatarContainer = $(document.createElement("div"));
            avatarContainer.append(avatar);
            avatarContainer.append(dropWarning);
            avatar = avatarContainer;
        }
        $("body").append(avatar);
        if (!$.browser.safari) {
            // FLUID-1597: Safari appears incapable of correctly determining the dimensions of elements
            avatar.css("display", "block").width(item.offsetWidth).height(item.offsetHeight);
        }
 
        if ($.browser.opera) { // FLUID-1490. Without this detect, curCSS explodes on the avatar on Firefox.
            avatar.hide();
        }
        return avatar;
    };
 
    // unsupported, NON-API function
    fluid.reorderer.bindHandlersToContainer = function (container, keyDownHandler, keyUpHandler) {
        var actualKeyDown = keyDownHandler;
        var advancedPrevention = false;
 
        // FLUID-1598 and others: Opera will refuse to honour a "preventDefault" on a keydown.
        // http://forums.devshed.com/javascript-development-115/onkeydown-preventdefault-opera-485371.html
        Iif ($.browser.opera) {
            container.keypress(function (evt) {
                if (advancedPrevention) {
                    advancedPrevention = false;
                    evt.preventDefault();
                    return false;
                }
            });
            actualKeyDown = function (evt) {
                var oldret = keyDownHandler(evt);
                if (oldret === false) {
                    advancedPrevention = true;
                }
            };
        }
        container.keydown(actualKeyDown);
        container.keyup(keyUpHandler);
    };
 
    // unsupported, NON-API function
    fluid.reorderer.addRolesToContainer = function (that) {
        that.container.attr("role", that.options.containerRole.container);
        that.container.attr("aria-multiselectable", "false");
        that.container.attr("aria-readonly", "false");
        that.container.attr("aria-disabled", "false");
        // FLUID-3707: We require to have BOTH application role as well as our named role
        // This however breaks the component completely under NVDA and causes it to perpetually drop back into "browse mode"
        //that.container.wrap("<div role=\"application\"></div>");
    };
 
    // unsupported, NON-API function
    fluid.reorderer.createAvatarId = function (parentId) {
        // Generating the avatar's id to be containerId_avatar
        // This is safe since there is only a single avatar at a time
        return parentId + "_avatar";
    };
 
    /**
     * Constants for key codes in events.
     */
    fluid.reorderer.keys = {
        TAB: 9,
        ENTER: 13,
        SHIFT: 16,
        CTRL: 17,
        ALT: 18,
        META: 19,
        SPACE: 32,
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        i: 73,
        j: 74,
        k: 75,
        m: 77
    };
 
    /**
     * The default key sets for the Reorderer. Should be moved into the proper component defaults.
     */
    fluid.reorderer.defaultKeysets = [
        {
            modifier : function (evt) {
                return evt.ctrlKey;
            },
            up : fluid.reorderer.keys.UP,
            down : fluid.reorderer.keys.DOWN,
            right : fluid.reorderer.keys.RIGHT,
            left : fluid.reorderer.keys.LEFT
        },
        {
            modifier : function (evt) {
                return evt.ctrlKey;
            },
            up : fluid.reorderer.keys.i,
            down : fluid.reorderer.keys.m,
            right : fluid.reorderer.keys.k,
            left : fluid.reorderer.keys.j
        }
    ];
 
    fluid.reorderer.keysetsPolicy = function (target, source) {
        var value = source ? source : target;
        return fluid.makeArray(value);
    };
 
    fluid.reorderer.copyDropWarning = function (dropWarning) {
        return dropWarning ? dropWarning.clone() : dropWarning;
    };
 
    /**
     * @param container - A jQueryable designator for the root node of the reorderer (a selector, a DOM node, or a jQuery instance)
     * @param options - an object containing any of the available options:
     *                  containerRole - indicates the role, or general use, for this instance of the Reorderer
     *                  keysets - an object containing sets of keycodes to use for directional navigation. Must contain:
     *                            modifier - a function that returns a boolean, indicating whether or not the required modifier(s) are activated
     *                            up
     *                            down
     *                            right
     *                            left
     *                  styles - an object containing class names for styling the Reorderer
     *                                  defaultStyle
     *                                  selected
     *                                  dragging
     *                                  hover
     *                                  dropMarker
     *                                  mouseDrag
     *                                  avatar
     *                  avatarCreator - a function that returns a valid DOM node to be used as the dragging avatar
     */
 
    fluid.defaults("fluid.reorderer", {
        gradeNames: ["fluid.viewComponent"],
        styles: {
            defaultStyle: "fl-reorderer-movable-default",
            selected: "fl-reorderer-movable-selected",
            dragging: "fl-reorderer-movable-dragging",
            mouseDrag: "fl-reorderer-movable-dragging",
            hover: "fl-reorderer-movable-hover",
            dropMarker: "fl-reorderer-dropMarker",
            avatar: "fl-reorderer-avatar"
        },
        selectors: {
            dropWarning: ".flc-reorderer-dropWarning",
            movables:    ".flc-reorderer-movable",
            selectables: ".flc-reorderer-movable",
            dropTargets: ".flc-reorderer-movable",
            grabHandle: ""
        },
        avatarCreator: fluid.reorderer.defaultAvatarCreator,
        keysets: fluid.reorderer.defaultKeysets,
        // These two ginger options injected "upwards" from layoutHandler and actually time its construction (before FLUID-4925)
        containerRole:       "{that}.layoutHandler.options.containerRole",
        selectablesTabindex: "{that}.layoutHandler.options.selectablesTabindex",
        layoutHandler: "fluid.listLayoutHandler",
 
        members: {
            dropManager: "@expand:fluid.dropManager()", // TODO: this is an old-style "that" which can no longer be supported as a component
            activeItem: null,
            kbDropWarning: "{that}.dom.dropWarning",
            mouseDropWarning: "@expand:fluid.reorderer.copyDropWarning({that}.kbDropWarning)"
        },
        events: {
            onShowKeyboardDropWarning: null,
            onSelect: null,
            onBeginMove: "preventable",
            onMove: null,
            afterMove: null,
            onHover: null, // item, state
            onRefresh: null
        },
        listeners: {
            onCreate: [ {
                namespace: "bindKeyHandlers",
                funcName: "fluid.reorderer.bindHandlersToContainer",
                args: ["{that}.container", "{that}.handleKeyDown", "{that}.handleKeyUp"]
            }, {
                namespace: "addContainerRoles",
                funcName: "fluid.reorderer.addRolesToContainer",
                args: "{that}"
            }, {
                namespace: "makeTabbable",
                funcName: "fluid.tabbable",
                args: "{that}.container"
            }, {
                namespace: "processAfterMoveCallback",
                funcName: "fluid.reorderer.processAfterMoveCallbackUrl",
                args: "{that}"
            },
            "{that}.refresh"],
            onRefresh: {
                listener: "fluid.reorderer.initItems",
                args: "{that}",
                priority: -1000 // TODO: Can't be "first" since moduleLayout needs to respond first
            },
            onHover: {
                funcName: "fluid.reorderer.hoverStyleHandler",
                args: ["{that}.dom", "{that}.options.styles", "{arguments}.0", "{arguments}.1"] // item, state
            }
        },
        invokers: {
            changeSelectedToDefault: {
                funcName: "fluid.reorderer.changeSelectedToDefault",
                args: ["{arguments}.0", "{that}.options.styles"]
            },
            setDropEffects: {
                funcName: "fluid.reorderer.setDropEffects",
                args: ["{that}.dom", "{arguments}.0"]
            },
            createDropMarker: {
                funcName: "fluid.reorderer.createDropMarker",
                args: ["{arguments}.0", "{that}.options.styles.dropMarker"]
            },
            refresh: {
                funcName: "fluid.reorderer.refresh",
                args: ["{that}.dom", "{that}.events", "{that}.selectableContext", "{that}.activeItem"]
            },
            selectItem: {
                funcName: "fluid.reorderer.selectItem",
                args: ["{that}", "{arguments}.0"]
            },
            initSelectables: { // unsupported, NON-API function
                funcName: "fluid.reorderer.initSelectables",
                args: ["{that}"]
            },
            initMovable: { // unsupported, NON-API function
                funcName: "fluid.reorderer.initMovable",
                args: ["{that}", "{that}.dropManager", "{arguments}.0"]
            },
            isMove: { // unsupported, NON-API function
                funcName: "fluid.reorderer.isMove",
                args: ["{that}.options.keysets", "{arguments}.0"] // evt
            },
            isActiveItemMovable: { // unsupported, NON-API function
                funcName: "fluid.reorderer.isActiveItemMovable",
                args: ["{that}.activeItem", "{that}.dom"]
            },
            handleKeyDown: { // unsupported, NON-API function
                funcName: "fluid.reorderer.handleKeyDown",
                args: ["{that}", "{that}.options.styles", "{arguments}.0"] // evt
            },
            handleDirectionKeyDown: { // unsupported, NON-API function
                funcName: "fluid.reorderer.handleDirectionKeyDown",
                args: ["{that}", "{arguments}.0"] // evt
            },
            handleKeyUp: { // unsupported, NON-API function
                funcName: "fluid.reorderer.handleKeyUp",
                args: ["{that}", "{that}.options.styles", "{arguments}.0"] // evt
            },
            requestMovement: { // unsupported, NON-API function
                funcName: "fluid.reorderer.requestMovement",
                args: ["{that}", "{arguments}.0", "{arguments}.1"] // requestedPosition, item
            }
        },
 
        mergePolicy: {
            keysets: fluid.reorderer.keysetsPolicy,
            "selectors.labelSource": "selectors.grabHandle",
            "selectors.selectables": "selectors.movables",
            "selectors.dropTargets": "selectors.movables"
        },
        components: {
            layoutHandler: {
                type: "{that}.options.layoutHandler",
                container: "{reorderer}.container"
            },
            labeller: {
                type: "fluid.reorderer.labeller",
                options: {
                    members: {
                        dom: "{reorderer}.dom"
                    },
                    getGeometricInfo: "{reorderer}.layoutHandler.getGeometricInfo",
                    orientation: "{reorderer}.layoutHandler.options.orientation",
                    layoutType: "{reorderer}.options.layoutHandler"
                }
            }
        },
 
        // The user option to enable or disable wrapping of elements within the container
        disableWrap: false
    });
 
    fluid.reorderer.noModifier = function (evt) {
        return (!evt.ctrlKey && !evt.altKey && !evt.shiftKey && !evt.metaKey);
    };
 
    // unsupported, NON-API function
    fluid.reorderer.isMove = function (keysets, evt) { // NB, needs dynamic binding
        for (var i = 0; i < keysets.length; i++) {
            if (keysets[i].modifier(evt)) {
                return true;
            }
        }
        return false;
    };
 
    // unsupported, NON-API function
    fluid.reorderer.isActiveItemMovable = function (activeItem, dom) {
        return $.inArray(activeItem, dom.fastLocate("movables")) >= 0;
    };
 
    // unsupported, NON-API function
    fluid.reorderer.handleKeyDown = function (thatReorderer, styles, evt) {
        if (!thatReorderer.activeItem || thatReorderer.activeItem !== evt.target) {
            return true;
        }
        // If the key pressed is ctrl, and the active item is movable we want to restyle the active item.
        var jActiveItem = $(thatReorderer.activeItem);
        if (!jActiveItem.hasClass(styles.dragging) && thatReorderer.isMove(evt)) {
           // Don't treat the active item as dragging unless it is a movable.
            if (thatReorderer.isActiveItemMovable()) {
                jActiveItem.removeClass(styles.selected);
                jActiveItem.addClass(styles.dragging);
                jActiveItem.attr("aria-grabbed", "true");
                thatReorderer.setDropEffects("move");
            }
            return false;
        }
        // The only other keys we listen for are the arrows.
        return thatReorderer.handleDirectionKeyDown(evt);
    };
 
    // unsupported, NON-API function
    fluid.reorderer.handleDirectionKeyDown = function (thatReorderer, evt) {
        var item = thatReorderer.activeItem;
        Iif (!item) {
            return true;
        }
        var keysets = thatReorderer.options.keysets;
        for (var i = 0; i < keysets.length; i++) {
            var keyset = keysets[i];
            var keydir = fluid.keyForValue(keyset, evt.keyCode);
            if (!keydir) {
                continue;
            }
            var isMovement = keyset.modifier(evt);
 
            var dirnum = fluid.keycodeDirection[keydir];
            var relativeItem = thatReorderer.layoutHandler.getRelativePosition(item, dirnum, !isMovement);
            if (!relativeItem) {
                continue;
            }
 
            if (isMovement) {
                var prevent = thatReorderer.events.onBeginMove.fire(item);
                Iif (prevent === false) {
                    return false;
                }
                var kbDropWarning = thatReorderer.kbDropWarning;
                if (kbDropWarning.length > 0) {
                    if (relativeItem.clazz === "locked") {
                        thatReorderer.events.onShowKeyboardDropWarning.fire(item, kbDropWarning);
                        kbDropWarning.show();
                    } else {
                        kbDropWarning.hide();
                    }
                }
                if (relativeItem.element) {
                    thatReorderer.requestMovement(relativeItem, item);
                }
 
            } else if (fluid.reorderer.noModifier(evt)) {
                fluid.blur(item);
                fluid.focus($(relativeItem.element));
            }
            return false;
        }
        return true;
    };
 
    // unsupported, NON-API function
    fluid.reorderer.handleKeyUp = function (thatReorderer, styles, evt) {
        if (!thatReorderer.activeItem || thatReorderer.activeItem !== evt.target) {
            return true;
        }
        var jActiveItem = $(thatReorderer.activeItem);
 
        // Handle a key up event for the modifier
        if (jActiveItem.hasClass(styles.dragging) && !thatReorderer.isMove(evt)) {
            Eif (thatReorderer.kbDropWarning) {
                thatReorderer.kbDropWarning.hide();
            }
            jActiveItem.removeClass(styles.dragging);
            jActiveItem.addClass(styles.selected);
            jActiveItem.attr("aria-grabbed", "false");
            thatReorderer.setDropEffects("none");
            return false;
        }
        return false;
    };
 
    // unsupported, NON-API function
    fluid.reorderer.requestMovement = function (thatReorderer, requestedPosition, item) {
        item = fluid.unwrap(item);
        // Temporary censoring to get around ModuleLayout inability to update relative to self.
        if (!requestedPosition || fluid.unwrap(requestedPosition.element) === item) {
            return;
        }
        var activeItem = $(thatReorderer.activeItem);
 
        // Fixes FLUID-3288.
        // Need to remove the blur event as safari will call blur on movements.
        // This caused the user to have to double tap the arrow keys to move.
        activeItem.off("blur.fluid.reorderer");
 
        thatReorderer.events.onMove.fire(item, requestedPosition);
        thatReorderer.dropManager.geometricMove(item, requestedPosition.element, requestedPosition.position);
        //$(thatReorderer.activeItem).removeClass(options.styles.selected);
 
        // refocus on the active item because moving places focus on the body
        fluid.focus(activeItem);
 
        thatReorderer.refresh();
 
        thatReorderer.dropManager.updateGeometry(thatReorderer.layoutHandler.getGeometricInfo());
 
        thatReorderer.events.afterMove.fire(item, requestedPosition, thatReorderer.dom.fastLocate("movables"));
    };
 
    // unsupported, NON-API function
    fluid.reorderer.hoverStyleHandler = function (dom, styles, item, state) {
        dom.fastLocate("grabHandle", item)[state ? "addClass" : "removeClass"](styles.hover);
    };
 
    // unsupported, NON-API function
    fluid.reorderer.processAfterMoveCallbackUrl = function (thatReorderer) {
        var options = thatReorderer.options;
        Iif (options.afterMoveCallbackUrl) {
            thatReorderer.events.afterMove.addListener(function () {
                var layoutHandler = thatReorderer.layoutHandler;
                var model = layoutHandler.getModel ? layoutHandler.getModel() :
                        options.acquireModel(thatReorderer);
                $.post(options.afterMoveCallbackUrl, JSON.stringify(model));
            }, "postModel");
        }
    };
 
    fluid.reorderer.setDropEffects = function (dom, value) {
        dom.fastLocate("dropTargets").attr("aria-dropeffect", value);
    };
 
    fluid.reorderer.createDropMarker = function (tagName, dropClass) {
        var dropMarker = $(document.createElement(tagName));
        dropMarker.addClass(dropClass);
        dropMarker.hide();
        return dropMarker;
    };
 
    fluid.reorderer.changeSelectedToDefault = function (jItem, styles) {
        jItem.removeClass(styles.selected);
        jItem.removeClass(styles.dragging);
        jItem.addClass(styles.defaultStyle);
        jItem.attr("aria-selected", "false");
    };
 
    fluid.reorderer.initSelectables = function (thatReorderer) {
        var handleBlur = function (evt) {
            thatReorderer.changeSelectedToDefault($(this));
            return evt.stopPropagation();
        };
 
        var handleFocus = function (evt) {
            thatReorderer.selectItem(this);
            return evt.stopPropagation();
        };
 
        var handleClick = function (evt) {
            var handle = fluid.unwrap(thatReorderer.dom.fastLocate("grabHandle", this));
            Eif (fluid.dom.isContainer(handle, evt.target)) {
                $(this).focus();
            }
        };
 
        var selectables = thatReorderer.dom.fastLocate("selectables");
        for (var i = 0; i < selectables.length; ++i) {
            var selectable = $(selectables[i]);
            if (!$.data(selectable[0], "fluid.reorderer.selectable-initialised")) {
                selectable.addClass(thatReorderer.options.styles.defaultStyle);
 
                selectable.on("blur.fluid.reorderer", handleBlur);
                selectable.focus(handleFocus);
                selectable.click(handleClick);
 
                selectable.attr("role", thatReorderer.options.containerRole.item);
                selectable.attr("aria-selected", "false");
                selectable.attr("aria-disabled", "false");
                $.data(selectable[0], "fluid.reorderer.selectable-initialised", true);
            }
        }
        if (!thatReorderer.selectableContext) {
            thatReorderer.selectableContext = fluid.selectable(thatReorderer.container, {
                selectableElements: selectables,
                selectablesTabindex: thatReorderer.options.selectablesTabindex,
                direction: null
            });
        }
    };
 
    fluid.reorderer.selectItem = function (thatReorderer, anItem) {
        thatReorderer.events.onSelect.fire(anItem);
        // Set the previous active item back to its default state.
        if (thatReorderer.activeItem && thatReorderer.activeItem !== anItem) {
            thatReorderer.changeSelectedToDefault($(thatReorderer.activeItem));
        }
        // Then select the new item.
        thatReorderer.activeItem = anItem;
        var jItem = $(anItem);
        var styles = thatReorderer.options.styles;
        jItem.removeClass(styles.defaultStyle);
        jItem.addClass(styles.selected);
        jItem.attr("aria-selected", "true");
    };
 
    /*
     * Takes a $ object and adds 'movable' functionality to it
     */
    fluid.reorderer.initMovable = function (thatReorderer, dropManager, item) {
        var options = thatReorderer.options;
        var styles = options.styles;
        item.attr("aria-grabbed", "false");
 
        item.mouseover(
            function () {
                thatReorderer.events.onHover.fire(item, true);
            }
        );
 
        item.mouseout(
            function () {
                thatReorderer.events.onHover.fire(item, false);
            }
        );
        var avatar;
        var handle = thatReorderer.dom.fastLocate("grabHandle", item);
 
        item.draggable({
            refreshPositions: false,
            scroll: true,
            helper: function () {
                var dropWarningEl;
                if (thatReorderer.mouseDropWarning) {
                    dropWarningEl = thatReorderer.mouseDropWarning[0];
                }
                avatar = $(options.avatarCreator(item[0], styles.avatar, dropWarningEl));
                avatar.prop("id", fluid.reorderer.createAvatarId(thatReorderer.container.id));
                return avatar;
            },
            start: function (e) {
                var prevent = thatReorderer.events.onBeginMove.fire(item);
                if (prevent === false) {
                    return false;
                }
                var handle = thatReorderer.dom.fastLocate("grabHandle", item)[0];
                var handlePos = fluid.dom.computeAbsolutePosition(handle);
                var handleWidth = handle.offsetWidth;
                var handleHeight = handle.offsetHeight;
                item.focus();
                item.removeClass(options.styles.selected);
                // all this junk should happen in handler for a new event - although note that mouseDrag style might cause display: none,
                // invalidating dimensions
                item.addClass(options.styles.mouseDrag);
                item.attr("aria-grabbed", "true");
                thatReorderer.setDropEffects("move");
                dropManager.startDrag(e, handlePos, handleWidth, handleHeight);
                avatar.show();
            },
            stop: function (e, ui) {
                item.removeClass(options.styles.mouseDrag);
                item.addClass(options.styles.selected);
                $(thatReorderer.activeItem).attr("aria-grabbed", "false");
                var markerNode = fluid.unwrap(thatReorderer.dropMarker);
                if (markerNode.parentNode) {
                    markerNode.parentNode.removeChild(markerNode);
                }
                avatar.hide();
                ui.helper = null;
                thatReorderer.setDropEffects("none");
                dropManager.endDrag();
 
                thatReorderer.requestMovement(dropManager.lastPosition(), item);
                // refocus on the active item because moving places focus on the body
                thatReorderer.activeItem.focus();
            },
            // This explicit detection is now required for jQuery UI after version 1.10.2 since the upstream API has been broken permanently.
            // See https://github.com/jquery/jquery-ui/pull/963
            handle: fluid.unwrap(handle) === fluid.unwrap(item) ? null : handle
        });
    };
 
    fluid.reorderer.initItems = function (thatReorderer) {
        var movables = thatReorderer.dom.fastLocate("movables");
        var dropTargets = thatReorderer.dom.fastLocate("dropTargets");
        thatReorderer.initSelectables();
 
        // Setup movables
        for (var i = 0; i < movables.length; i++) {
            var item = movables[i];
            if (!$.data(item, "fluid.reorderer.movable-initialised")) {
                thatReorderer.initMovable($(item));
                $.data(item, "fluid.reorderer.movable-initialised", true);
            }
        }
        // In order to create valid html, the drop marker is the same type as the node being dragged.
        // This creates a confusing UI in cases such as an ordered list.
        if (movables.length > 0 && !thatReorderer.dropMarker) {
            thatReorderer.dropMarker = thatReorderer.createDropMarker(movables[0].tagName);
        }
 
        thatReorderer.dropManager.updateGeometry(thatReorderer.layoutHandler.getGeometricInfo());
 
        var dropChangeListener = function (dropTarget) {
            fluid.dom.moveDom(thatReorderer.dropMarker, dropTarget.element, dropTarget.position);
            thatReorderer.dropMarker.css("display", "");
            if (thatReorderer.mouseDropWarning) {
                if (dropTarget.lockedelem) {
                    thatReorderer.mouseDropWarning.show();
                } else {
                    thatReorderer.mouseDropWarning.hide();
                }
            }
        };
 
        thatReorderer.dropManager.dropChangeFirer.addListener(dropChangeListener, "fluid.reorderer");
        // Set up dropTargets
        dropTargets.attr("aria-dropeffect", "none");
 
    };
 
    fluid.reorderer.refresh = function (dom, events, selectableContext, activeItem) {
        dom.refresh("movables");
        dom.refresh("selectables");
        dom.refresh("grabHandle", dom.fastLocate("movables"));
        dom.refresh("dropTargets");
        if (selectableContext) { // if it didn't exist on dispatch, it must be up to date now
            selectableContext.selectables = dom.fastLocate("selectables");
            selectableContext.selectablesUpdated(activeItem);
        }
        events.onRefresh.fire(); // This should be last otherwise handlers will see stale DOM binder contents
    };
 
    /**
     * These roles are used to add ARIA roles to orderable items. This list can be extended as needed,
     * but the values of the container and item roles must match ARIA-specified roles.
     */
    fluid.reorderer.roles = {
        GRID: { container: "grid", item: "gridcell" },
        LIST: { container: "list", item: "listitem" },
        REGIONS: { container: "main", item: "article" }
    };
 
    fluid.defaults("fluid.reorderList", {
        gradeNames: ["fluid.reorderer"],
        layoutHandler: "fluid.listLayoutHandler"
    });
 
    fluid.defaults("fluid.reorderGrid", {
        gradeNames: ["fluid.reorderer"],
        layoutHandler: "fluid.gridLayoutHandler"
    });
 
    fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY = "shuffleProjectFrom";
    fluid.reorderer.GEOMETRIC_STRATEGY         = "projectFrom";
    fluid.reorderer.LOGICAL_STRATEGY           = "logicalFrom";
    fluid.reorderer.WRAP_LOCKED_STRATEGY       = "lockedWrapFrom";
    fluid.reorderer.NO_STRATEGY = null;
 
    // unsupported, NON-API function
    fluid.reorderer.relativeInfoGetter = function (orientation, coStrategy, contraStrategy, dropManager, disableWrap) {
        return function (item, direction, forSelection) {
            var dirorient = fluid.directionOrientation(direction);
            var strategy = dirorient === orientation ? coStrategy : contraStrategy;
            return strategy !== null ? dropManager[strategy](item, direction, forSelection, disableWrap) : null;
        };
    };
 
 
 
    /*******************
     * Layout Handlers *
     *******************/
 
    // unsupported, NON-API function
    fluid.reorderer.makeGeometricInfoGetter = function (orientation, sentinelize, dom) {
        var that = {
            sentinelize: sentinelize,
            extents: [{
                orientation: orientation,
                elements: dom.fastLocate("dropTargets")
            }],
            elementMapper: function (element) {
                return $.inArray(element, dom.fastLocate("movables")) === -1 ? "locked" : null;
            },
            elementIndexer: function (element) {
                var selectables = dom.fastLocate("selectables");
                return {
                    elementClass: that.elementMapper(element),
                    index: $.inArray(element, selectables),
                    length: selectables.length
                };
            }
        };
        return that;
    };
 
    fluid.defaults("fluid.layoutHandler", {
        gradeNames: ["fluid.viewComponent"],
        disableWrap: "{reorderer}.options.disableWrap",
        members: {
            reordererDom: "{reorderer}.dom",
            dropManager: "{reorderer}.dropManager"
        },
        invokers: { // overridden in moduleLayoutHandler
            getGeometricInfo: "fluid.reorderer.makeGeometricInfoGetter({that}.options.orientation, {that}.options.sentinelize, {that}.reordererDom)"
        }
    });
 
    // Public layout handlers.
    fluid.defaults("fluid.listLayoutHandler", {
        gradeNames: ["fluid.layoutHandler"],
        orientation:         fluid.orientation.VERTICAL,
        containerRole:       fluid.reorderer.roles.LIST,
        selectablesTabindex: -1,
        sentinelize:         true,
        members: {
            getRelativePosition: { // TODO: an old-fashioned function member - convert to invoker
                expander: {
                    funcName: "fluid.reorderer.relativeInfoGetter",
                    args: [ "{that}.options.orientation", fluid.reorderer.LOGICAL_STRATEGY, null,
                        "{that}.dropManager", "{that}.options.disableWrap"]
                }
            }
        }
    });
 
    /*
     * Items in the Lightbox are stored in a list, but they are visually presented as a grid that
     * changes dimensions when the window changes size. As a result, when the user presses the up or
     * down arrow key, what lies above or below depends on the current window size.
     *
     * The GridLayoutHandler is responsible for handling changes to this virtual 'grid' of items
     * in the window, and of informing the Lightbox of which items surround a given item.
     */
 
    fluid.defaults("fluid.gridLayoutHandler", {
        gradeNames: ["fluid.layoutHandler"],
        orientation:         fluid.orientation.HORIZONTAL,
        containerRole:       fluid.reorderer.roles.GRID,
        selectablesTabindex: -1,
        sentinelize:         false,
        coStrategy: "@expand:fluid.gridLayoutHandler.computeCoStrategy({that}.options.disableWrap)",
        members: {
            getRelativePosition: { // TODO: an old-fashioned function member - convert to invoker
                expander: {
                    funcName: "fluid.reorderer.relativeInfoGetter",
                    args: [ "{that}.options.orientation", "{that}.options.coStrategy", fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY,
                        "{that}.dropManager", "{that}.options.disableWrap"]
                }
            }
        }
    });
 
    fluid.gridLayoutHandler.computeCoStrategy = function (disableWrap) {
        return disableWrap ? fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY : fluid.reorderer.LOGICAL_STRATEGY;
    };
 
    /*************
     * Labelling *
     *************/
 
    /** ARIA labeller component which decorates the reorderer with the function of announcing the current
      * focused position of the reorderer as well as the coordinates of any requested move */
 
    fluid.defaults("fluid.reorderer.labeller", {
        gradeNames: ["fluid.component"],
        members: {
            movedMap: {},
            moduleCell: {
                expander: {
                    funcName: "fluid.reorderer.labeller.computeModuleCell",
                    args: ["{that}.resolver", "{that}.options.orientation"]
                }
            },
            layoutType: {
                expander: {
                    funcName: "fluid.computeNickName",
                    args: "{that}.options.layoutType"
                }
            },
            positionTemplate: {
                expander: {
                    funcName: "fluid.reorderer.labeller.computePositionTemplate",
                    args: ["{that}.resolver", "{that}.layoutType"]
                }
            }
        },
        strings: {
            overallTemplate: "%recentStatus %item %position %movable",
            position:        "%index of %length",
            position_moduleLayoutHandler: "%index of %length in %moduleCell %moduleIndex of %moduleLength",
            moduleCell_0:    "row", // NB, these keys must agree with fluid.a11y.orientation constants
            moduleCell_1:    "column",
            movable:         "movable",
            fixed:           "fixed",
            recentStatus:    "moved from position %position"
        },
        components: {
            resolver: {
                type: "fluid.messageResolver",
                options: {
                    messageBase: "{labeller}.options.strings"
                }
            }
        },
        invokers: {
            renderLabel: {
                funcName: "fluid.reorderer.labeller.renderLabel",
                args: ["{labeller}", "{arguments}.0", "{arguments}.1"]
            }
        },
        listeners: {
            "{reorderer}.events.onRefresh": {
                listener: "fluid.reorderer.labeller.onRefresh",
                args: "{that}"
            },
            "{reorderer}.events.onMove": {
                listener: "fluid.reorderer.labeller.onMove",
                args: ["{that}", "{arguments}.0", "{arguments}.1"] // item, newPosition
            }
        }
    });
 
    // unsupported, NON-API function
    fluid.reorderer.labeller.computeModuleCell = function (resolver, orientation) {
        return resolver.resolve("moduleCell_" + orientation);
    };
 
    // unsupported, NON-API function
    fluid.reorderer.labeller.computePositionTemplate = function (resolver, layoutType) {
        return resolver.lookup(["position_" + layoutType, "position"]);
    };
 
    // unsupported, NON-API function
    fluid.reorderer.labeller.onRefresh = function (that) {
        var selectables = that.dom.locate("selectables");
        var movedMap = that.movedMap;
        fluid.each(selectables, function (selectable) {
            var labelOptions = {};
            var id = fluid.allocateSimpleId(selectable);
            var moved = movedMap[id];
            var label = that.renderLabel(selectable);
            var plainLabel = label;
            if (moved) {
                moved.newRender = plainLabel;
                label = that.renderLabel(selectable, moved.oldRender.position);
                // once we move focus out of the element which just moved, return its ARIA label to be the new plain label
                $(selectable).one("focusout.ariaLabeller", function () {
                    Eif (movedMap[id]) {
                        var oldLabel = movedMap[id].newRender.label;
                        delete movedMap[id];
                        fluid.updateAriaLabel(selectable, oldLabel);
                    }
                });
                labelOptions.dynamicLabel = true;
            }
            fluid.updateAriaLabel(selectable, label.label, labelOptions);
        });
    };
 
    // unsupported, NON-API function
    fluid.reorderer.labeller.onMove = function (that, item) {
        fluid.clear(that.movedMap); // if we somehow were fooled into missing a defocus, at least clear the map on a 2nd move
        // This "off" is needed for FLUID-4693 with Chrome 18, which generates a focusOut when
        // simply doing the DOM manipulation to move the element to a new position.
        $(item).off("focusout.ariaLabeller");
        var movingId = fluid.allocateSimpleId(item);
        that.movedMap[movingId] = {
            oldRender: that.renderLabel(item)
        };
    };
 
    // unsupported, NON-API function
    // Convert from 0-based to 1-based indices for announcement
    fluid.reorderer.indexRebaser = function (indices) {
        indices.index++;
        if (indices.moduleIndex !== undefined) {
            indices.moduleIndex++;
        }
        return indices;
    };
 
    // unsupported, NON-API function
    fluid.reorderer.labeller.renderLabel = function (that, selectable, recentPosition) {
        var geom = that.options.getGeometricInfo();
        var indices = fluid.reorderer.indexRebaser(geom.elementIndexer(selectable));
        indices.moduleCell = that.moduleCell;
 
        var elementClass = geom.elementMapper(selectable);
        var labelSource = that.dom.locate("labelSource", selectable);
        var recentStatus;
        if (recentPosition) {
            recentStatus = that.resolver.resolve("recentStatus", {position: recentPosition});
        }
        var topModel = {
            item: typeof (labelSource) === "string" ? labelSource : fluid.dom.getElementText(fluid.unwrap(labelSource)),
            position: that.positionTemplate.resolveFunc(that.positionTemplate.template, indices),
            movable: that.resolver.resolve(elementClass === "locked" ? "fixed" : "movable"),
            recentStatus: recentStatus || ""
        };
 
        var template = that.resolver.lookup(["overallTemplate"]);
        var label = template.resolveFunc(template.template, topModel);
        return {
            position: topModel.position,
            label: label
        };
    };
 
})(jQuery, fluid_3_0_0);