All files / framework/core/js FluidView.js

87.89% Statements 254/289
78.68% Branches 155/197
85.71% Functions 48/56
87.89% Lines 254/289

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                                  56x   56x     56x                         56x 1x                 56x 4174x 1x 1x 1x     1x 1x             56x 56x 56x 56x 56x           56x                       56x 2613x 2613x                 56x 40673x                     56x 2586x 2586x     2586x 2586x 1x     2585x 2x 1x   2x 2x     2583x 1x                 2582x 2582x   2582x                   56x   2620x       2620x     26887x       9405x     2620x     9409x 9409x 4x   9405x 9405x     9405x 3094x   6311x       6311x 369x   5942x       9405x 9404x 9404x   9405x 9405x 9405x   2620x 17482x 17482x 17482x 17482x   2620x     2620x 520x 520x 520x   520x     520x 520x 1834x       2620x   2620x             56x 2563x                                       56x 2563x 2563x 2563x 1x     2562x 2562x   2562x   2562x 2471x     2562x       2562x     2562x                   56x 2619x         2619x 2619x 2619x                     56x 86x 86x 222x 75x   147x       56x 27x 131x               56x 112x 178x 178x               56x 375x 375x 375x       375x   360x   15x 15x       15x     15x 15x 15x 40x     40x     15x 6x 2x         6x 14x       9x 26x   9x         56x         56x 28x 70x 70x 28x   42x       56x 449x     56x 8x 8x 8x 8x       56x 28x 28x 28x   28x     28x 28x     28x 28x 28x     28x 3x   28x 28x 13x   15x                 56x 717x 717x 717x 717x 717x 717x                   56x 2973x 2973x 2973x   2887x         2887x   86x                   56x 1094x             56x 32467x 32467x       32467x 820x 820x   32467x                 56x 402x   402x     56x                                             56x 1661x 1661x 1661x 76x 76x 6x   76x       56x 6x 6x 6x 6x     56x   56x 1660x 1660x 1660x               56x 1659x 1659x 1659x 711x 711x   948x   1659x                   56x   56x 123x 123x 568x     568x   123x                       56x                                     56x 12x                             56x   5x 5x 5x 5x 7x 7x 7x   5x     5x     5x     5x         5x 7x 7x 7x           5x 5x 5x 5x 5x 5x 5x   5x 5x 1x               5x     56x              
/*
Copyright 2010-2011 Lucendo Development Ltd.
Copyright 2010-2016 OCAD University
Copyright 2012-2014 Raising the Floor - US
Copyright 2014-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
*/
 
/** This file contains functions which depend on the presence of a DOM document
 *  and which depend on the contents of Fluid.js **/
 
var fluid_3_0_0 = fluid_3_0_0 || {};
 
(function ($, fluid) {
    "use strict";
 
    fluid.defaults("fluid.viewComponent", {
        gradeNames: ["fluid.modelComponent"],
        initFunction: "fluid.initView",
        argumentMap: {
            container: 0,
            options: 1
        },
        members: { // Used to allow early access to DOM binder via IoC, but to also avoid triggering evaluation of selectors
            dom: "@expand:fluid.initDomBinder({that}, {that}.options.selectors)"
        }
    });
 
    // unsupported, NON-API function
    fluid.dumpSelector = function (selectable) {
        return typeof (selectable) === "string" ? selectable :
            selectable.selector ? selectable.selector : "";
    };
 
    // unsupported, NON-API function
    // NOTE: this function represents a temporary strategy until we have more integrated IoC debugging.
    // It preserves the 1.3 and previous framework behaviour for the 1.x releases, but provides a more informative
    // diagnostic - in fact, it is perfectly acceptable for a component's creator to return no value and
    // the failure is really in assumptions in fluid.initLittleComponent. Revisit this issue for 2.0
    fluid.diagnoseFailedView = function (componentName, that, options, args) {
        if (!that && fluid.hasGrade(options, "fluid.viewComponent")) {
            var container = fluid.wrap(args[1]);
            var message1 = "Instantiation of view component with type " + componentName + " failed, since ";
            Iif (!container) {
                fluid.fail(message1 + " container argument is empty");
            }
            else Eif (container.length === 0) {
                fluid.fail(message1 + "selector \"", fluid.dumpSelector(args[1]), "\" did not match any markup in the document");
            } else {
                fluid.fail(message1 + " component creator function did not return a value");
            }
        }
    };
 
    fluid.checkTryCatchParameter = function () {
        var location = window.location || { search: "", protocol: "file:" };
        var GETparams = location.search.slice(1).split("&");
        return fluid.find(GETparams, function (param) {
            Iif (param.indexOf("notrycatch") === 0) {
                return true;
            }
        }) === true;
    };
 
    fluid.notrycatch = fluid.checkTryCatchParameter();
 
 
    /**
     * Wraps an object in a jQuery if it isn't already one. This function is useful since
     * it ensures to wrap a null or otherwise falsy argument to itself, rather than the
     * often unhelpful jQuery default of returning the overall document node.
     *
     * @param {Object} obj - the object to wrap in a jQuery
     * @param {jQuery} [userJQuery] - the jQuery object to use for the wrapping, optional - use the current jQuery if absent
     * @return {jQuery} - The wrapped object.
     */
    fluid.wrap = function (obj, userJQuery) {
        userJQuery = userJQuery || $;
        return ((!obj || obj.jquery) ? obj : userJQuery(obj));
    };
 
    /**
     * If obj is a jQuery, this function will return the first DOM element within it. Otherwise, the object will be returned unchanged.
     *
     * @param {jQuery} obj - The jQuery instance to unwrap into a pure DOM element.
     * @return {Object} - The unwrapped object.
     */
    fluid.unwrap = function (obj) {
        return obj && obj.jquery ? obj[0] : obj;
    };
 
    /**
     * Fetches a single container element and returns it as a jQuery.
     *
     * @param {String|jQuery|element} containerSpec - an id string, a single-element jQuery, or a DOM element specifying a unique container
     * @param {Boolean} fallible - <code>true</code> if an empty container is to be reported as a valid condition
     * @param {jQuery} [userJQuery] - the jQuery object to use for the wrapping, optional - use the current jQuery if absent
     * @return {jQuery} - A single-element jQuery container.
     */
    fluid.container = function (containerSpec, fallible, userJQuery) {
        var selector = containerSpec.selector || containerSpec;
        Iif (userJQuery) {
            containerSpec = fluid.unwrap(containerSpec);
        }
        var container = fluid.wrap(containerSpec, userJQuery);
        if (fallible && (!container || container.length === 0)) {
            return null;
        }
 
        if (!container || !container.jquery || container.length !== 1) {
            if (typeof (containerSpec) !== "string") {
                containerSpec = container.selector;
            }
            var count = container.length !== undefined ? container.length : 0;
            fluid.fail((count > 1 ? "More than one (" + count + ") container elements were"
                    : "No container element was") + " found for selector " + containerSpec);
        }
        if (!fluid.isDOMNode(container[0])) {
            fluid.fail("fluid.container was supplied a non-jQueryable element");
        }
 
        // To address FLUID-5966, manually adding back the selector and context properties that were removed from jQuery v3.0.
        // ( see: https://jquery.com/upgrade-guide/3.0/#breaking-change-deprecated-context-and-selector-properties-removed )
        // In most cases the "selector" property will already be restored through the DOM binder;
        // however, when a selector or pure jQuery element is supplied directly as a component's container, we need to add them
        // if it is possible to infer them. This feature is rarely used but is crucial for the prefs framework infrastructure
        // in Panels.js fluid.prefs.subPanel.resetDomBinder
        container.selector = selector;
        container.context = container.context || containerSpec.ownerDocument || document;
 
        return container;
    };
 
    /**
     * Creates a new DOM Binder instance, used to locate elements in the DOM by name.
     *
     * @param {Object} container - the root element in which to locate named elements
     * @param {Object} selectors - a collection of named jQuery selectors
     * @return {Object} - The new DOM binder.
     */
    fluid.createDomBinder = function (container, selectors) {
        // don't put on a typename to avoid confusing primitive visitComponentChildren
        var that = {
            id: fluid.allocateGuid(),
            cache: {}
        };
        var userJQuery = container.constructor;
 
        function cacheKey(name, thisContainer) {
            return fluid.allocateSimpleId(thisContainer) + "-" + name;
        }
 
        function record(name, thisContainer, result) {
            that.cache[cacheKey(name, thisContainer)] = result;
        }
 
        that.locate = function (name, localContainer) {
            var selector, thisContainer, togo;
 
            selector = selectors[name];
            if (selector === undefined) {
                return undefined;
            }
            thisContainer = localContainer ? $(localContainer) : container;
            Iif (!thisContainer) {
                fluid.fail("DOM binder invoked for selector " + name + " without container");
            }
            if (selector === "") {
                togo = thisContainer;
            }
            else Iif (!selector) {
                togo = userJQuery();
            }
            else {
                if (typeof (selector) === "function") {
                    togo = userJQuery(selector.call(null, fluid.unwrap(thisContainer)));
                } else {
                    togo = userJQuery(selector, thisContainer);
                }
            }
 
            if (!togo.selector) {
                togo.selector = selector;
                togo.context = thisContainer;
            }
            togo.selectorName = name;
            record(name, thisContainer, togo);
            return togo;
        };
        that.fastLocate = function (name, localContainer) {
            var thisContainer = localContainer ? localContainer : container;
            var key = cacheKey(name, thisContainer);
            var togo = that.cache[key];
            return togo ? togo : that.locate(name, localContainer);
        };
        that.clear = function () {
            that.cache = {};
        };
        that.refresh = function (names, localContainer) {
            var thisContainer = localContainer ? localContainer : container;
            Eif (typeof names === "string") {
                names = [names];
            }
            Iif (thisContainer.length === undefined) {
                thisContainer = [thisContainer];
            }
            for (var i = 0; i < names.length; ++i) {
                for (var j = 0; j < thisContainer.length; ++j) {
                    that.locate(names[i], thisContainer[j]);
                }
            }
        };
        that.resolvePathSegment = that.locate;
 
        return that;
    };
 
    /* Expect that jQuery selector query has resulted in a non-empty set of
     * results. If none are found, this function will fail with a diagnostic message,
     * with the supplied message prepended.
     */
    fluid.expectFilledSelector = function (result, message) {
        Iif (result && result.length === 0 && result.jquery) {
            fluid.fail(message + ": selector \"" + result.selector + "\" with name " + result.selectorName +
                       " returned no results in context " + fluid.dumpEl(result.context));
        }
    };
 
    /**
     * The central initialiation method called as the first act of every Fluid
     * component. This function automatically merges user options with defaults,
     * attaches a DOM Binder to the instance, and configures events.
     *
     * @param {String} componentName - The unique "name" of the component, which will be used
     * to fetch the default options from store. By recommendation, this should be the global
     * name of the component's creator function.
     * @param {jQueryable} containerSpec - A specifier for the single root "container node" in the
     * DOM which will house all the markup for this component.
     * @param {Object} userOptions - The user configuration options for this component.
     * @param {Object} localOptions - The local configuration options for this component.  Unsupported, see comments for initLittleComponent.
     * @return {Object|null} - The newly created component, or `null` id the container does not exist.
     */
    fluid.initView = function (componentName, containerSpec, userOptions, localOptions) {
        var container = fluid.container(containerSpec, true);
        fluid.expectFilledSelector(container, "Error instantiating component with name \"" + componentName);
        if (!container) {
            return null;
        }
        // Need to ensure container is set early, without relying on an IoC mechanism - rethink this with asynchrony
        var receiver = function (that) {
            that.container = container;
        };
        var that = fluid.initLittleComponent(componentName, userOptions, localOptions || {gradeNames: ["fluid.viewComponent"]}, receiver);
 
        if (!that.dom) {
            fluid.initDomBinder(that);
        }
        // TODO: cannot afford a mutable container - put this into proper workflow
        var userJQuery = that.options.jQuery; // Do it a second time to correct for jQuery injection
        // if (userJQuery) {
        //    container = fluid.container(containerSpec, true, userJQuery);
        // }
        fluid.log("Constructing view component " + componentName + " with container " + container.constructor.expando +
            (userJQuery ? " user jQuery " + userJQuery.expando : "") + " env: " + $.expando);
 
        return that;
    };
 
    /**
     * Creates a new DOM Binder instance for the specified component and mixes it in.
     *
     * @param {Object} that - The component instance to attach the new DOM Binder to.
     * @param {Object} selectors - a collection of named jQuery selectors
     * @return {Object} - The DOM for the component.
     */
    fluid.initDomBinder = function (that, selectors) {
        Iif (!that.container) {
            fluid.fail("fluid.initDomBinder called for component with typeName " + that.typeName +
                " without an initialised container - this has probably resulted from placing \"fluid.viewComponent\" in incorrect position in grade merging order. " +
                " Make sure to place it to the right of any non-view grades in the gradeNames list to ensure that it overrides properly: resolved gradeNames is ", that.options.gradeNames, " for component ", that);
        }
        that.dom = fluid.createDomBinder(that.container, selectors || that.options.selectors || {});
        that.locate = that.dom.locate;
        return that.dom;
    };
 
    // DOM Utilities.
 
    /**
     * Finds the nearest ancestor of the element that matches a predicate
     * @param {Element} element - DOM element
     * @param {Function} test - A function (predicate) accepting a DOM element, returning a truthy value representing a match
     * @return {Element|undefined} - The first element parent for which the predicate returns truthy - or undefined if no parent matches
     */
    fluid.findAncestor = function (element, test) {
        element = fluid.unwrap(element);
        while (element) {
            if (test(element)) {
                return element;
            }
            element = element.parentNode;
        }
    };
 
    fluid.findForm = function (node) {
        return fluid.findAncestor(node, function (element) {
            return element.nodeName.toLowerCase() === "form";
        });
    };
 
    /* A utility with the same signature as jQuery.text and jQuery.html, but without the API irregularity
     * that treats a single argument of undefined as different to no arguments */
    // in jQuery 1.7.1, jQuery pulled the same dumb trick with $.text() that they did with $.val() previously,
    // see comment in fluid.value below
    fluid.each(["text", "html"], function (method) {
        fluid[method] = function (node, newValue) {
            node = $(node);
            return newValue === undefined ? node[method]() : node[method](newValue);
        };
    });
 
    /* A generalisation of jQuery.val to correctly handle the case of acquiring and
     * setting the value of clustered radio button/checkbox sets, potentially, given
     * a node corresponding to just one element.
     */
    fluid.value = function (nodeIn, newValue) {
        var node = fluid.unwrap(nodeIn);
        var multiple = false;
        Iif (node.nodeType === undefined && node.length > 1) {
            node = node[0];
            multiple = true;
        }
        if ("input" !== node.nodeName.toLowerCase() || !/radio|checkbox/.test(node.type)) {
            // resist changes to contract of jQuery.val() in jQuery 1.5.1 (see FLUID-4113)
            return newValue === undefined ? $(node).val() : $(node).val(newValue);
        }
        var name = node.name;
        Iif (name === undefined) {
            fluid.fail("Cannot acquire value from node " + fluid.dumpEl(node) + " which does not have name attribute set");
        }
        var elements;
        Iif (multiple) {
            elements = nodeIn;
        } else {
            elements = node.ownerDocument.getElementsByName(name);
            var scope = fluid.findForm(node);
            elements = $.grep(elements, function (element) {
                Iif (element.name !== name) {
                    return false;
                }
                return !scope || fluid.dom.isContainer(scope, element);
            });
        }
        if (newValue !== undefined) {
            if (typeof(newValue) === "boolean") {
                newValue = (newValue ? "true" : "false");
            }
            // jQuery gets this partially right, but when dealing with radio button array will
            // set all of their values to "newValue" rather than setting the checked property
            // of the corresponding control.
            $.each(elements, function () {
                this.checked = (newValue instanceof Array ?
                    newValue.indexOf(this.value) !== -1 : newValue === this.value);
            });
        } else { // this part jQuery will not do - extracting value from <input> array
            var checked = $.map(elements, function (element) {
                return element.checked ? element.value : null;
            });
            return node.type === "radio" ? checked[0] : checked;
        }
    };
 
 
    fluid.BINDING_ROOT_KEY = "fluid-binding-root";
 
    /* Recursively find any data stored under a given name from a node upwards
     * in its DOM hierarchy **/
 
    fluid.findData = function (elem, name) {
        while (elem) {
            var data = $.data(elem, name);
            if (data) {
                return data;
            }
            elem = elem.parentNode;
        }
    };
 
    fluid.bindFossils = function (node, data, fossils) {
        $.data(node, fluid.BINDING_ROOT_KEY, {data: data, fossils: fossils});
    };
 
    fluid.boundPathForNode = function (node, fossils) {
        node = fluid.unwrap(node);
        var key = node.name || node.id;
        var record = fossils[key];
        return record ? record.EL : null;
    };
 
    /* relevant, the changed value received at the given DOM node */
    fluid.applyBoundChange = function (node, newValue, applier) {
        node = fluid.unwrap(node);
        Eif (newValue === undefined) {
            newValue = fluid.value(node);
        }
        Iif (node.nodeType === undefined && node.length > 0) {
            node = node[0];
        } // assume here that they share name and parent
        var root = fluid.findData(node, fluid.BINDING_ROOT_KEY);
        Iif (!root) {
            fluid.fail("Bound data could not be discovered in any node above " + fluid.dumpEl(node));
        }
        var name = node.name;
        var fossil = root.fossils[name];
        Iif (!fossil) {
            fluid.fail("No fossil discovered for name " + name + " in fossil record above " + fluid.dumpEl(node));
        }
        if (typeof(fossil.oldvalue) === "boolean") { // deal with the case of an "isolated checkbox"
            newValue = newValue[0] ? true : false;
        }
        var EL = root.fossils[name].EL;
        if (applier) {
            applier.fireChangeRequest({path: EL, value: newValue, source: "DOM:" + node.id});
        } else {
            fluid.set(root.data, EL, newValue);
        }
    };
 
 
    /*
     * Returns a jQuery object given the id of a DOM node. In the case the element
     * is not found, will return an empty list.
     */
    fluid.jById = function (id, dokkument) {
        dokkument = dokkument && dokkument.nodeType === 9 ? dokkument : document;
        var element = fluid.byId(id, dokkument);
        var togo = element ? $(element) : [];
        togo.selector = "#" + id;
        togo.context = dokkument;
        return togo;
    };
 
    /**
     * Returns an DOM element quickly, given an id
     *
     * @param {Object} id - the id of the DOM node to find
     * @param {Document} dokkument - the document in which it is to be found (if left empty, use the current document)
     * @return {Object} - The DOM element with this id, or null, if none exists in the document.
     */
    fluid.byId = function (id, dokkument) {
        dokkument = dokkument && dokkument.nodeType === 9 ? dokkument : document;
        var el = dokkument.getElementById(id);
        if (el) {
        // Use element id property here rather than attribute, to work around FLUID-3953
            Iif (el.id !== id) {
                fluid.fail("Problem in document structure - picked up element " +
                    fluid.dumpEl(el) + " for id " + id +
                    " without this id - most likely the element has a name which conflicts with this id");
            }
            return el;
        } else {
            return null;
        }
    };
 
    /**
     * Returns the id attribute from a jQuery or pure DOM element.
     *
     * @param {jQuery|Element} element - the element to return the id attribute for.
     * @return {String} - The id attribute of the element.
     */
    fluid.getId = function (element) {
        return fluid.unwrap(element).id;
    };
 
    /*
     * Allocate an id to the supplied element if it has none already, by a simple
     * scheme resulting in ids "fluid-id-nnnn" where nnnn is an increasing integer.
     */
    fluid.allocateSimpleId = function (element) {
        element = fluid.unwrap(element);
        Iif (!element || fluid.isPrimitive(element)) {
            return null;
        }
 
        if (!element.id) {
            var simpleId = "fluid-id-" + fluid.allocateGuid();
            element.id = simpleId;
        }
        return element.id;
    };
 
    /**
     * Returns the document to which an element belongs, or the element itself if it is already a document
     *
     * @param {jQuery|Element} element - The element to return the document for
     * @return {Document} - The document in which it is to be found
     */
    fluid.getDocument = function (element) {
        var node = fluid.unwrap(element);
        // DOCUMENT_NODE - guide to node types at https://developer.mozilla.org/en/docs/Web/API/Node/nodeType
        return node.nodeType === 9 ? node : node.ownerDocument;
    };
 
    fluid.defaults("fluid.ariaLabeller", {
        gradeNames: ["fluid.viewComponent"],
        labelAttribute: "aria-label",
        liveRegionMarkup: "<div class=\"liveRegion fl-hidden-accessible\" aria-live=\"polite\"></div>",
        liveRegionId: "fluid-ariaLabeller-liveRegion",
        invokers: {
            generateLiveElement: {
                funcName: "fluid.ariaLabeller.generateLiveElement",
                args: "{that}"
            },
            update: {
                funcName: "fluid.ariaLabeller.update",
                args: ["{that}", "{arguments}.0"]
            }
        },
        listeners: {
            onCreate: {
                func: "{that}.update",
                args: [null]
            }
        }
    });
 
    fluid.ariaLabeller.update = function (that, newOptions) {
        newOptions = newOptions || that.options;
        that.container.attr(that.options.labelAttribute, newOptions.text);
        if (newOptions.dynamicLabel) {
            var live = fluid.jById(that.options.liveRegionId);
            if (live.length === 0) {
                live = that.generateLiveElement();
            }
            live.text(newOptions.text);
        }
    };
 
    fluid.ariaLabeller.generateLiveElement = function (that) {
        var liveEl = $(that.options.liveRegionMarkup);
        liveEl.prop("id", that.options.liveRegionId);
        $("body").append(liveEl);
        return liveEl;
    };
 
    var LABEL_KEY = "aria-labelling";
 
    fluid.getAriaLabeller = function (element) {
        element = $(element);
        var that = fluid.getScopedData(element, LABEL_KEY);
        return that;
    };
 
    /* Manages an ARIA-mediated label attached to a given DOM element. An
     * aria-labelledby attribute and target node is fabricated in the document
     * if they do not exist already, and a "little component" is returned exposing a method
     * "update" that allows the text to be updated. */
 
    fluid.updateAriaLabel = function (element, text, options) {
        options = $.extend({}, options || {}, {text: text});
        var that = fluid.getAriaLabeller(element);
        if (!that) {
            that = fluid.ariaLabeller(element, options);
            fluid.setScopedData(element, LABEL_KEY, that);
        } else {
            that.update(options);
        }
        return that;
    };
 
    /* "Global Dismissal Handler" for the entire page. Attaches a click handler to the
     * document root that will cause dismissal of any elements (typically dialogs) which
     * have registered themselves. Dismissal through this route will automatically clean up
     * the record - however, the dismisser themselves must take care to deregister in the case
     * dismissal is triggered through the dialog interface itself. This component can also be
     * automatically configured by fluid.deadMansBlur by means of the "cancelByDefault" option */
 
    var dismissList = {};
 
    $(document).click(function (event) {
        var target = fluid.resolveEventTarget(event);
        while (target) {
            Iif (dismissList[target.id]) {
                return;
            }
            target = target.parentNode;
        }
        fluid.each(dismissList, function (dismissFunc, key) {
            dismissFunc(event);
            delete dismissList[key];
        });
    });
    // TODO: extend a configurable equivalent of the above dealing with "focusin" events
 
    /* Accepts a free hash of nodes and an optional "dismissal function".
     * If dismissFunc is set, this "arms" the dismissal system, such that when a click
     * is received OUTSIDE any of the hierarchy covered by "nodes", the dismissal function
     * will be executed.
     */
    fluid.globalDismissal = function (nodes, dismissFunc) {
        fluid.each(nodes, function (node) {
          // Don't bother to use the real id if it is from a foreign document - we will never receive events
          // from it directly in any case - and foreign documents may be under the control of malign fiends
          // such as tinyMCE who allocate the same id to everything
            var id = fluid.unwrap(node).ownerDocument === document ? fluid.allocateSimpleId(node) : fluid.allocateGuid();
            if (dismissFunc) {
                dismissList[id] = dismissFunc;
            }
            else {
                delete dismissList[id];
            }
        });
    };
 
    /* Provides an abstraction for determing the current time.
     * This is to provide a fix for FLUID-4762, where IE6 - IE8
     * do not support Date.now().
     */
    fluid.now = function () {
        return Date.now ? Date.now() : (new Date()).getTime();
    };
 
 
    /* Sets an interation on a target control, which morally manages a "blur" for
     * a possibly composite region.
     * A timed blur listener is set on the control, which waits for a short period of
     * time (options.delay, defaults to 150ms) to discover whether the reason for the
     * blur interaction is that either a focus or click is being serviced on a nominated
     * set of "exclusions" (options.exclusions, a free hash of elements or jQueries).
     * If no such event is received within the window, options.handler will be called
     * with the argument "control", to service whatever interaction is required of the
     * blur.
     */
 
    fluid.deadMansBlur = function (control, options) {
        // TODO: This should be rewritten as a proper component
        var that = {options: $.extend(true, {}, fluid.defaults("fluid.deadMansBlur"), options)};
        that.blurPending = false;
        that.lastCancel = 0;
        that.canceller = function (event) {
            fluid.log("Cancellation through " + event.type + " on " + fluid.dumpEl(event.target));
            that.lastCancel = fluid.now();
            that.blurPending = false;
        };
        that.noteProceeded = function () {
            fluid.globalDismissal(that.options.exclusions);
        };
        that.reArm = function () {
            fluid.globalDismissal(that.options.exclusions, that.proceed);
        };
        that.addExclusion = function (exclusions) {
            fluid.globalDismissal(exclusions, that.proceed);
        };
        that.proceed = function (event) {
            fluid.log("Direct proceed through " + event.type + " on " + fluid.dumpEl(event.target));
            that.blurPending = false;
            that.options.handler(control);
        };
        fluid.each(that.options.exclusions, function (exclusion) {
            exclusion = $(exclusion);
            fluid.each(exclusion, function (excludeEl) {
                $(excludeEl).on("focusin", that.canceller).
                    on("fluid-focus", that.canceller).
                    click(that.canceller).mousedown(that.canceller);
    // Mousedown is added for FLUID-4212, as a result of Chrome bug 6759, 14204
            });
        });
        Eif (!that.options.cancelByDefault) {
            $(control).on("focusout", function (event) {
                fluid.log("Starting blur timer for element " + fluid.dumpEl(event.target));
                var now = fluid.now();
                fluid.log("back delay: " + (now - that.lastCancel));
                Eif (now - that.lastCancel > that.options.backDelay) {
                    that.blurPending = true;
                }
                setTimeout(function () {
                    if (that.blurPending) {
                        that.options.handler(control);
                    }
                }, that.options.delay);
            });
        }
        else {
            that.reArm();
        }
        return that;
    };
 
    fluid.defaults("fluid.deadMansBlur", {
        gradeNames: "fluid.function",
        delay: 150,
        backDelay: 100
    });
 
})(jQuery, fluid_3_0_0);