all files / montage/core/ range-controller.js

50.28% Statements 90/179
40.5% Branches 49/121
38.24% Functions 13/34
50.28% Lines 90/179
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                                                                              60×     60×   60× 60×                               60×                     29×         46×       46× 46×     46×                                       75× 75× 75× 75× 75×   75×   75×   75×   79×         79×           79× 79×                   75× 75×   50×   25×   75× 75×   75×             70×                                     70×                                                                               60× 60×   60× 60× 60×   60× 60× 60× 60×               60×   60× 60×     60×     60×       60× 60× 60× 60×   60×   60×                                                                                                                                                                                                                                                                                                           407×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         107× 10×     10×   10× 10×     10×                                                                                                     44×                             120×                                                                                                  
/**
 * @module montage/core/range-controller
 */
var Montage = require("./core").Montage;
var GenericCollection = require("collections/generic-collection");
var observableArrayProperties = require("collections/listen/array-changes").observableArrayProperties;
var deprecate = require("core/deprecate");
 
// The content controller is responsible for determining which content from a
// source collection are visible, their order of appearance, and whether they
// are selected. Multiple repetitions may share a single content controller
// and thus their selection state.
 
// The controller manages a series of visible iterations. Each iteration has a
// corresponding "object" and whether that iteration is "selected". The
// controller uses a bidirectional binding to ensure that the controller's
// "selections" collection and the "selected" property of each iteration are in
// sync.
 
// The controller can determine which content to display and the order in which
// to render them in a variety of ways. You can use a "selector" to
// filter and sort the content. The controller binds the content of
// "organizedContent" depending on which strategy you use.
 
// The content of "organizedContent" is then reflected with corresponding
// incremental changes to "iterations". The "iterations" array will always
// have an "iteration" corresponding to the "object" in "organizedContent" at
// the same position.
 
/**
 * @const {Array}
 */
var EMPTY_ARRAY = Object.freeze([]);
 
/**
 * A `_RangeSelection` is a special kind of `Array` that knows about a `RangeController`
 * and maintains invariants about itself relative to the properties of the
 * `RangeController`. A `_RangeSelection` should only be modified using the `splice`
 * method. Changes by directly using other `Array` methods can break the invariants.
 *
 * @class _RangeSelection
 * @private
 */
 
var _RangeSelection = function(content, rangeController) {
    var self = content;
    //Moved to RangeSelection.prototype for optimization
    //self.makeObservable();
    self.__proto__ = _RangeSelection.prototype;
 
    self.rangeController = rangeController;
    self.contentEquals = content && content.contentEquals || Object.is;
 
    //Moved to _RangeSelection.prototype for optimization
    // Object.defineProperty(self, "clone", {
    //     value: function(){
    //         return this.slice();
    //     }
    // });
     // Object.defineProperty(self, "swap", {
     //     configurable: false,
     //     value: _RangeSelection.prototype.swap
     // });
     // Object.defineProperty(self, "push", {
     //     configurable: false,
     //     value: _RangeSelection.prototype.push
     // });
    return self;
};
_RangeSelection.prototype = Object.create(Array.prototype, observableArrayProperties);
Object.defineProperty(_RangeSelection.prototype, "clone", {
    value: function(){
        return this.slice();
    }
});
var oldSwap = self.swap;
Object.defineProperty(_RangeSelection.prototype, "oldSwap", {
    configurable: false,
    value: observableArrayProperties.swap.value
});
Object.defineProperty(_RangeSelection.prototype, "swap", {
    configurable: false,
    value: function(start, howMany, itemsToAdd) {
        return this.swap_or_push(start, howMany, itemsToAdd);
    }
});
_RangeSelection.prototype.oldPush = observableArrayProperties.push.value;
Object.defineProperty(_RangeSelection.prototype, "push", {
    configurable: false,
    value: function() {
          var i = -1,
              l = arguments.length,
              x = Array(l);
 
          while (++i < l) {
            x[i] = arguments[i];
          }
 
        this.swap_or_push(this.length, 0, x);
    }
});
 
/**
 * A custom version of swap to ensure that changes obey the RangeController
 * invariants:
 *  - if rC.allowsMultipleSelection is false, only allow one item in set.
 *  - if rC.avoidsEmtySelection is true, require at least one item in set.
 *  - only add items that are present in rC.content
 *  - enforce uniqueness of items according to the contentEquals of the content
 *
 * @function swap
 * @param {number} start
 * @param {number} howMany
 * @param {Object} itemsToAdd
 *
 */
Object.defineProperty(_RangeSelection.prototype, "swap_or_push", {
    configurable: false,
    value: function(start, howMany, itemsToAdd) {
        var content = this.rangeController.content;
        this.contentEquals = content && content.contentEquals || Object.is;
        start = start >= 0 ? start : this.length + start;
        var oldLength = this.length;
        var minusLength = Math.min(howMany, oldLength - start);
 
		Eif(itemsToAdd) {
 
            itemsToAdd.contentEquals = this.contentEquals;
 
            var plus = itemsToAdd.filter(function(item, index){
                // do not add items to the selection if they aren't in content
                Iif (content && !content.has(item)) {
                    return false;
                }
 
                // if the same item appears twice in the add list, only add it once
                Iif (itemsToAdd.findLast(item) > index) {
                    return false;
                }
 
                // if the item is already in the selection, don't add it
                // unless it's in the part that we're about to delete.
                var indexInSelection = this.find(item);
                return indexInSelection < 0 ||
                        (indexInSelection >= start && indexInSelection < start + minusLength);
 
            }, this);
		}
		else {
			plus = EMPTY_ARRAY;
		}
 
 
        var minus;
        if (minusLength === 0) {
            // minus will be empty
            minus = EMPTY_ARRAY;
        } else {
            minus = Array.prototype.slice.call(this, start, start + minusLength);
        }
        var diff = plus.length - minus.length;
        var newLength = Math.max(this.length + diff, start + plus.length);
 
        if (!this.rangeController.allowsMultipleSelection && newLength > 1) {
            // use the last-supplied item as the sole element of the set
            var last = plus.length ? plus[plus.length-1] : this.one();
            Iif(oldLength === 0) {
                this.oldPush(last);
                return EMPTY_ARRAY;
            }
            else {
                return this.oldSwap(0, oldLength, [last]);
            }
        } else Iif (this.rangeController.avoidsEmptySelection && newLength === 0) {
            // use the first item in the selection, unless it is no longer in the content
            if (content.has(this[0])) {
                if((this.length-1) === 0) {
                    return EMPTY_ARRAY;
                }
                else {
                    return this.oldSwap(1, this.length-1);
                }
            } else {
                if(this.length === 0) {
                    this.oldPush(content.one());
                    return EMPTY_ARRAY;
                }
                else {
                    return this.oldSwap(0, this.length, [content.one()]);
                }
            }
        } else {
            return this.oldSwap(start, howMany, plus);
        }
 
    }
});
 
 
/**
 * A `RangeController` is responsible for managing "ranged content", typically
 * an array, but any collection that implements ranged content change dispatch,
 * `(plus, minus, index)`, would suffice. The controller manages selection and
 * governs the filtering and ordering of the content. `RangeController` is not
 * affiliated with a number range input.
 *
 * A `RangeController` receives a `content` collection, manages what portition
 * of that content is visible and the order of its appearance
 * (`organizedContent`), and projects changes to the the organized content into
 * an array of iteration controllers (`iterations`, containing instances of
 * `Iteration`).
 *
 * The `RangeController` provides a variety of knobs for how to project the
 * content into the organized content, all of which are optional, and the
 * default behavior is to preserve the content and its order.
 * You can use the bindings path expression language (from FRB) to determine
 * the `sortPath` and `filterPath`.
 * There is a `reversed` flag to invert the order of appearance.
 *
 * The `RangeController` is also responsible for managing which content is
 * selected and provides a variety of knobs for that purpose.
 *
 * @class RangeController
 * @classdesc Manages the selection and visible portion of given content,
 * typically an Array for for a [Repetition]{@link Repetition}.
 * @extends Montage
 */
var RangeController = exports.RangeController = Montage.specialize( /** @lends RangeController.prototype # */ {
    /**
     * @constructs RangeController
     */
    constructor: {
        value: function RangeController(content) {
            this.content = null;
            this._selection = new _RangeSelection([], this);
 
            this.sortPath = null;
            this.filterPath = null;
            this.reversed = false;
 
            this.selectAddedContent = false;
            this.deselectInvisibleContent = false;
            this.clearSelectionOnOrderChange = false;
            this.avoidsEmptySelection = false;
 
            // The following establishes a pipeline for projecting the
            // underlying content into organizedContent.
            // The filterPath, sortedPath and reversed are all optional stages
            // in that pipeline and used if non-null and in that order.
            // The _filteredContent and _sortedContent are intermediate variables
            // from which organizedContent is generated.
            this.organizedContent = [];
            // dispatches handleOrganizedContentRangeChange
            this.organizedContent.addRangeChangeListener(this, "organizedContent");
            this.defineBinding("_filteredContent", {
                "<-": "$filterPath.defined() ? content.filter{path($filterPath)} : content"
            });
            this.defineBinding("_sortedContent", {
                "<-": "$sortPath.defined() ? _filteredContent.sorted{path($sortPath)} : _filteredContent"
            });
            this.defineBinding("organizedContent.rangeContent()", {
                "<-": "$reversed ?? 0 ? _sortedContent.reversed() : _sortedContent"
            });
 
            this.addRangeAtPathChangeListener("content", this, "handleContentRangeChange");
            this.addPathChangeListener("sortPath", this, "handleOrderChange");
            this.addPathChangeListener("reversed", this, "handleOrderChange");
            this.addOwnPropertyChangeListener("allowsMultipleSelection", this);
 
            this.iterations = [];
 
            Iif (content) {
                this.initWithContent(content);
            }
        }
    },
 
    /**
     * Initializes a range controller with a backing collection.
     *
     * @function
     * @param {Array|SortedSet} content - Any collection that produces range change events
     * @returns this
     */
    initWithContent: {
        value: function (content) {
            this.content = content;
            return this;
        }
    },
 
    // Organizing Content
    // ------------------
 
    /**
     * An FRB expression that determines how to sort the content, like "name"
     * to sort by name.
     * If the `sortPath` is null, the content is not sorted.
     *
     * @property {string} value
     */
    sortPath: {value: null},
 
    /**
     * Whether to reverse the order of the sorted content.
     *
     * @property {boolean} value
     */
    reversed: {value: null},
 
    /**
     * An FRB expression that determines how to filter content like
     * "name.startsWith('A')" to see only names starting with 'A'.
     * If the `filterPath` is null, all content is accepted.
     *
     * @property {string} value
     */
    filterPath: {value: null},
 
 
    // Managing Selection
    // ------------------
 
    /**
     * Whether to select new content automatically.
     * @property {boolean}
     * @default false
     *
     * @todo make this work
     */
    selectAddedContent: {value: false},
 
    /**
     * Whether to automatically deselect content that disappears from the
     * `organizedContent`.
     *
     * @default false
     * @property {boolean}
     */
    deselectInvisibleContent: {value: false},
 
    /**
     * Whether to automatically clear the selection whenever the
     * `sortPath`, `filterPath`, or `reversed`
     * knobs change.
     *
     * @default false
     * @property {boolean}
     */
    clearSelectionOnOrderChange: {value: false},
 
    /**
     * Whether to automatically reselect a value if it is the last value
     * removed from the selection.
     *
     * @default false
     * @property {boolean}
     */
    avoidsEmptySelection: {value: false},
 
    /**
     * Whether to automatically deselect all previously selected content when a
     * new selection is made.
     *
     * @default false
     * @property {boolean}
     */
    allowsMultipleSelection: {value: false},
 
    /**
     * @deprecated
     */
    multiSelect: {
        set: function (multiSelect) {
            deprecate.deprecationWarning("multiSelect", "allowsMultipleSelection");
            this.allowsMultipleSelection = !!multiSelect;
        },
        get: function () {
            deprecate.deprecationWarning("multiSelect", "allowsMultipleSelection");
            return this.allowsMultipleSelection;
        }
    },
 
 
    // Properties managed by the controller
    // ------------------------------------
 
    /**
     * An array incrementally projected from `content` through sort,
     * reversed and filter.
     *
     * @property {Array.<Object>}
     */
    organizedContent: {value: null},
 
    /**
     * An array of iterations corresponding to each of the values in
     * `organizedContent`, providing an interface for getting or
     * setting whether each is selected.
     *
     * @property {Array.<Iteration>}
     */
    iterations: {value: null},
 
    _selection: {value: null},
 
    /**
     * A subset of the `content` that are selected.
     * The user may safely reassign this property and all iterations will react
     * to the change.
     * The selection may be `null`.
     * The selection may be any collection that supports range change events
     * like `Array` or `SortedSet`.
     *
     * Deprecation warning: setting the `selection` will not replace it with the provided.
     * collection. Instead, it will empty the selection and then shallow-copy the
     * contents of the argument into the existing selection array. This is done to
     * maintain the complicated invariants about what the selection can be.
     *
     * @property {?Array|Set|SortedSet}
     */
    selection: {
        get: function () {
            return this._selection;
        },
        set: function (collection) {
            var args = [0, this._selection.length];
            Eif (collection && collection.toArray) {
                args = args.concat(collection.toArray());
            }
            this._selection.splice.apply(this._selection, args);
        }
    },
 
    /**
     * A managed interface for adding values to the selection, accounting for
     * `allowsMultipleSelection`.
     * You can however directly manipulate the selection, but that will update
     * the selection asynchronously because the controller cannot change the
     * selection while handling a selection change event.
     *
     * @function
     * @param value
     */
    select: {
        value: function (value) {
            if (!this.allowsMultipleSelection && this.selection.length >= 1) {
                this.selection.clear();
            }
            this.selection.add(value);
        }
    },
 
    /**
     * A managed interface for removing values from the selection, accounting
     * for `avoidsEmptySelection`.
     * You can however directly manipulate the selection, but that will update
     * the selection asynchronously because the controller cannot change the
     * selection while handling a selection change event.
     *
     * @function
     * @param value
     */
    deselect: {
        value: function (value) {
            if (!this.avoidsEmptySelection || this.selection.length > 1) {
                this.selection["delete"](value);
            }
        }
    },
 
    /**
     * A managed interface for clearing the selection, accounting for
     * `avoidsEmptySelection`.
     * You can however directly manipulate the selection, but that will update
     * the selection asynchronously because the controller cannot change the
     * selection while handling a selection change event.
     *
     * @function
     */
    clearSelection: {
        value: function () {
            if (!this.avoidsEmptySelection || this.selection.length > 1) {
                this.selection.clear();
            }
        }
    },
 
    /**
     * Proxies adding content to the underlying collection, accounting for
     * `selectAddedContent`.
     *
     * @function
     * @param value
     * @returns {boolean} whether the value was added
     */
    add: {
        value: function (value) {
            var result;
 
            if (!this.content) {
                this.content = [];
            }
            result = this.content.add(value);
            if (result) {
                this.handleAdd(value);
            }
            return result;
        }
    },
 
    /**
     * Proxies pushing content to the underlying collection, accounting for
     * `selectAddedContent`.
     *
     * @function
     * @param ...values
     * @returns {boolean} whether the value was added
     */
    push: {
        value: function () {
            var result = this.content.push.apply(this.content, arguments);
            for (var index = 0; index < arguments.length; index++) {
                this.handleAdd(arguments[index]);
            }
            return result;
        }
    },
 
    /**
     * Proxies popping content from the underlying collection.
     *
     * @function
     * @returns the popped value
     */
    pop: {
        value: function () {
            return this.content.pop();
        }
    },
 
    /**
     * Proxies shifting content from the underlying collection.
     *
     * @function
     * @returns the shifted value
     */
    shift: {
        value: function () {
            return this.content.shift();
        }
    },
 
    /**
     * Proxies unshifting content to the underlying collection, accounting for
     * `selectAddedContent`.
     *
     * @function
     * @param ...values
     * @returns {boolean} whether the value was added
     */
    unshift: {
        value: function () {
            var result = this.content.unshift.apply(this.content, arguments);
            for (var index = 0; index < arguments.length; index++) {
                this.handleAdd(arguments[index]);
            }
            return result;
        }
    },
 
    /**
     * Proxies splicing values into the underlying collection.
     * Accounts for * `selectAddedContent`.
     *
     * @function
     * @returns the resulting content
     */
    splice: {
        value: function () {
            var result = this.content.splice.apply(this.content, arguments);
            for (var index = 2; index < arguments.length; index++) {
                this.handleAdd(arguments[index]);
            }
            return result;
        }
    },
 
    /**
     * Proxies swapping values in the underlying collection.
     * Accounts for * `selectAddedContent`
     *
     * @function
     * @param {number} index the position at which to remove values
     * @param {number} minusLength the number of values to remove
     * @param {Array} plus the values to add
     * @returns {Array} `minus`, the removed values from the content
     */
    swap: {
        value: function (index, length, values) {
            var result = this.content.swap.apply(this.content, arguments);
            if (values) {
                for (var index = 2; index < values.length; index++) {
                    this.handleAdd(values[index]);
                }
            }
            return result;
        }
    },
 
    /**
     * Proxies deleting content from the underlying collection.
     *
     * @function
     * @param value
     * @returns {boolean} whether the value was found and deleted successfully
     */
    "delete": {
        value: function (value) {
            return this.content["delete"](value);
        }
    },
 
    /**
     * Does the value exist in the content?
     *
     * @function
     * @param {object} value the value to test for
     * @returns {boolean}
     */
    has: {
        value: function (value) {
            if (this.content) {
                return this.content.has(value);
            } else {
                return false;
            }
        }
    },
 
    /**
     * Proxies adding each value into the underlying collection.
     *
     * @function
     * @param {...object} values
     */
    addEach: {
        value: GenericCollection.prototype.addEach
    },
 
    /**
     * Proxies deleting each value out from the underlying collection.
     * @function
     * @param {...object} values
     */
    deleteEach: {
        value: GenericCollection.prototype.deleteEach
    },
 
    /**
     * Proxies clearing the underlying content collection.
     * @function
     */
    clear: {
        value: function () {
            this.content.clear();
        }
    },
 
    /**
     * Creates content and adds it to the controller and its backing
     * collection.
     * Uses `add` and `contentConstructor`.
     * @function
     * @returns the value constructed and added
     */
    addContent: {
        value: function () {
            var content = new this.contentConstructor();
            this.add(content);
            return content;
        }
    },
 
    /**
     * @private
     */
    _contentConstructor: {
        value: null
    },
 
    /**
     * Creates a content value for this range controller.
     * If the backing
     * collection has an intrinsic type, uses its `contentConstructor`.
     * Otherwise, creates and returns simple, empty objects.
     *
     * This property can be set to an alternate content constructor, which will
     * take precedence over either of the above defaults.
     *
     * @type {function}
     */
    contentConstructor: {
        get: function () {
            if (this._contentConstructor) {
                return this._contentConstructor;
            } else if (this.content && this.content.contentConstructor) {
                return this.content.contentConstructor;
            } else {
                return Object;
            }
        },
        set: function (contentConstructor) {
            this._contentConstructor = contentConstructor;
        }
    },
 
    /**
     * Dispatched by range changes to the controller's content, arranged in
     * constructor.
     *
     * Reacts to content changes to ensure that content that no
     * longer exists is removed from the selection, regardless of whether it is
     * from the user or any other entity modifying the backing collection.
     * @private
     */
    handleContentRangeChange: {
        value: function (plus, minus, index) {
            if (this.selection.length > 0) {
                var equals = this.content && this.content.contentEquals || Object.is;
                // remove all values from the selection that were removed (but
                // not added back)
                minus.deleteEach(plus, equals);
 
                Eif (this.selection.length) {
                    this.selection.deleteEach(minus);
 
                    // ensure selection always has content
                    Iif (this.selection.length === 0 && this.content && this.content.length &&
                        this.avoidsEmptySelection && !this.allowsMultipleSelection) {
                        // selection can't contain previous content value as content already changed
                        this.selection.add(this.content[this.content.length - 1]);
                    }
                }
            }
        }
    },
 
    /**
     * Watches changes to the private reflection of the public selection,
     * enforcing the `allowsMultipleSelection` and `avoidsEmptySelection` invariants.
     *
     * @private
     * @todo this doesn't seem to be used anywhere
     */
    handleSelectionRangeChange : {
        value: function (plus, minus, index) {
            if (this.selection) {
                if (this.content) {
                    var notInContent = [];
                    for (var i=0;i<plus.length;i++) {
                        if (!this.content.has(plus[i])) {
                            notInContent.push(plus[i]);
                        }
                    }
                    this._selection.deleteEach(notInContent);
                    if (!this.allowsMultipleSelection && this._selection.length > 1) {
                        var last = this._selection.pop();
                        this._selection.clear();
                        this._selection.add(last);
                    }
                    if (this.avoidsEmptySelection && this._selection.length == 0) {
                        this._selection.add(minus[0]);
                    }
                } else {
                    this._selection.clear();
                }
            }
        }
    },
 
    /**
     * Dispatched by a range-at-path change listener arranged in constructor.
     * Synchronizes the `iterations` with changes to `organizedContent`.
     * Also manages the `deselectInvisibleContent` invariant.
     * @private
     */
    handleOrganizedContentRangeChange: {
        value: function (plus, minus, index) {
            Iif (this.deselectInvisibleContent && this.selection) {
                var diff = minus.clone(1);
                diff.deleteEach(plus);
                this.selection.deleteEach(minus);
            }
        }
    },
 
    /**
     * Dispatched by changes to sortPath, filterPath, and reversed to maintain
     * the `clearSelectionOnOrderChange` invariant.
     * @private
     */
    handleOrderChange: {
        value: function () {
            Iif (this.clearSelectionOnOrderChange && this.selection) {
                this.selection.clear();
            }
        }
    },
 
    /**
     * Dispatched manually by all of the managed methods for adding values to
     * the underlying content, like `add` and `push`, to support `allowsMultipleSelection`.
     * @private
     */
    handleAdd: {
        value: function (value) {
            if (this.selectAddedContent && this.selection) {
                if (!this.allowsMultipleSelection && this.selection.length) {
                    this.selection.swap(0, this.selection.length, [value]);
                } else {
                    this.selection.add(value);
                }
            }
        }
    },
 
    /**
     * Enforces the `allowsMultipleSelection` invariant when that property becomes true.
     * @private
     */
    handleAllowsMultipleSelectionChange: {
        value: function () {
            Eif (this.selection) {
                var length = this.selection.length;
                if (!this.allowsMultipleSelection && length > 1) {
                    var last = this._selection.pop();
                    this._selection.clear();
                    this._selection.add(last);
                }
            }
        }
    }
 
}, /** @lends RangeController */ {
 
    blueprintModuleId:require("./core")._blueprintModuleIdDescriptor,
 
    blueprint:require("./core")._blueprintDescriptor
 
});
 
// TODO @kriskowal scrollIndex, scrollDelegate -> scrollDelegate.scrollBy(offset)
 
// TODO allowsMultipleSelectionWithModifiers to support ctrl/command/shift selection such
// that individual values and ranges of values.
 
// TODO @kriskowal decouple such that content controllers can be chained using
// adapter pattern