/// /*! © Microsoft. All rights reserved. This library is supported for use in Windows Store apps only. Build: 1.0.9600.17018.winblue_gdr.140204-1946 Version: Microsoft.WinJS.2.0 */ msWriteProfilerMark("Microsoft.WinJS.2.0 1.0.9600.17018.winblue_gdr.140204-1946 ui.js,StartTM"); /// /// (function animationsInit(WinJS) { "use strict"; var thisWinUI = WinJS.UI; var mstransform = "transform"; // Default to 11 pixel from the left (or right if RTL) var defaultOffset = [{ top: "0px", left: "11px", rtlflip: true }]; var OffsetArray = WinJS.Class.define(function OffsetArray_ctor(offset, keyframe, defOffset) { // Constructor defOffset = defOffset || defaultOffset; if (Array.isArray(offset) && offset.length > 0) { this.offsetArray = offset; if (offset.length === 1) { this.keyframe = checkKeyframe(offset[0], defOffset[0], keyframe); } } else if (offset && offset.hasOwnProperty("top") && offset.hasOwnProperty("left")) { this.offsetArray = [offset]; this.keyframe = checkKeyframe(offset, defOffset[0], keyframe); } else { this.offsetArray = defOffset; this.keyframe = chooseKeyframe(defOffset[0], keyframe); } }, { // Public Members getOffset: function (i) { if (i >= this.offsetArray.length) { i = this.offsetArray.length - 1; } return this.offsetArray[i]; } }, { // Static Members supportedForProcessing: false, }); function checkKeyframe(offset, defOffset, keyframe) { if (offset.keyframe) { return offset.keyframe; } if (!keyframe || offset.left !== defOffset.left || offset.top !== defOffset.top || (offset.rtlflip && !defOffset.rtlflip)) { return null; } if (!offset.rtlflip) { return keyframe; } return keyframeCallback(keyframe); } function chooseKeyframe(defOffset, keyframe) { if (!keyframe || !defOffset.rtlflip) { return keyframe; } return keyframeCallback(keyframe); } function keyframeCallback(keyframe) { var keyframeRtl = keyframe + "-rtl"; return function (i, elem) { return window.getComputedStyle(elem).direction === "ltr" ? keyframe : keyframeRtl; } } function makeArray(elements) { if (Array.isArray(elements) || elements instanceof NodeList || elements instanceof HTMLCollection) { return elements; } else if (elements) { return [elements]; } else { return []; } } function collectOffsetArray(elemArray) { var offsetArray = []; for (var i = 0; i < elemArray.length; i++) { var offset = { top: elemArray[i].offsetTop, left: elemArray[i].offsetLeft }; var matrix = window.getComputedStyle(elemArray[i], null).transform.split(","); if (matrix.length === 6) { offset.left += parseFloat(matrix[4]); offset.top += parseFloat(matrix[5]); } offsetArray.push(offset); } return offsetArray; } function staggerDelay(initialDelay, extraDelay, delayFactor, delayCap) { return function (i) { var ret = initialDelay; for (var j = 0; j < i; j++) { extraDelay *= delayFactor; ret += extraDelay; } if (delayCap) { ret = Math.min(ret, delayCap); } return ret; }; } function makeOffsetsRelative(elemArray, offsetArray) { for (var i = 0; i < offsetArray.length; i++) { offsetArray[i].top -= elemArray[i].offsetTop; offsetArray[i].left -= elemArray[i].offsetLeft; } } function animTranslate2DTransform(elemArray, offsetArray, transition) { makeOffsetsRelative(elemArray, offsetArray); for (var i = 0; i < elemArray.length; i++) { if (offsetArray[i].top !== 0 || offsetArray[i].left !== 0) { elemArray[i].style.transform = "translate(" + offsetArray[i].left + "px, " + offsetArray[i].top + "px)"; } } return thisWinUI.executeTransition(elemArray, transition); } function translateCallback(offsetArray, prefix) { prefix = prefix || ""; return function (i, elem) { var offset = offsetArray.getOffset(i); var left = offset.left; if (offset.rtlflip && window.getComputedStyle(elem).direction === "rtl") { left = left.toString(); if (left.charAt(0) === "-") { left = left.substring(1); } else { left = "-" + left; } } return prefix + "translate(" + left + ", " + offset.top + ")"; }; } function translateCallbackAnimate(offsetArray, suffix) { suffix = suffix || ""; return function (i, elem) { var offset = offsetArray[i]; return "translate(" + offset.left + "px, " + offset.top + "px) " + suffix; }; } function keyframeCallbackAnimate(offsetArray, keyframe) { return function (i, elem) { var offset = offsetArray[i]; return (offset.left === 0 && offset.top === 0) ? keyframe : null; }; } function layoutTransition(LayoutTransition, target, affected, extra) { var targetArray = makeArray(target); var affectedArray = makeArray(affected); var offsetArray = collectOffsetArray(affectedArray); return new LayoutTransition(targetArray, affectedArray, offsetArray, extra); } var ExpandAnimation = WinJS.Class.define(function ExpandAnimation_ctor(revealedArray, affectedArray, offsetArray) { // Constructor this.revealedArray = revealedArray; this.affectedArray = affectedArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { var promise1 = thisWinUI.executeAnimation( this.revealedArray, { keyframe: "WinJS-opacity-in", property: "opacity", delay: this.affectedArray.length > 0 ? 200 : 0, duration: 167, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 0, to: 1 }); var promise2 = animTranslate2DTransform( this.affectedArray, this.offsetArray, { property: mstransform, delay: 0, duration: 367, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); return WinJS.Promise.join([promise1, promise2]); } }, { // Static Members supportedForProcessing: false, }); var CollapseAnimation = WinJS.Class.define(function CollapseAnimation_ctor(hiddenArray, affectedArray, offsetArray) { // Constructor this.hiddenArray = hiddenArray; this.affectedArray = affectedArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { var promise1 = thisWinUI.executeAnimation( this.hiddenArray, { keyframe: "WinJS-opacity-out", property: "opacity", delay: 0, duration: 167, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 1, to: 0 }); var promise2 = animTranslate2DTransform( this.affectedArray, this.offsetArray, { property: mstransform, delay: this.hiddenArray.length > 0 ? 167 : 0, duration: 367, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); return WinJS.Promise.join([promise1, promise2]); } }, { // Static Members supportedForProcessing: false, }); var RepositionAnimation = WinJS.Class.define(function RepositionAnimation_ctor(target, elementArray, offsetArray) { // Constructor this.elementArray = elementArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { return animTranslate2DTransform( this.elementArray, this.offsetArray, { property: mstransform, delay: staggerDelay(0, 33, 1, 250), duration: 367, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); } }, { // Static Members supportedForProcessing: false, }); var AddToListAnimation = WinJS.Class.define(function AddToListAnimation_ctor(addedArray, affectedArray, offsetArray) { // Constructor this.addedArray = addedArray; this.affectedArray = affectedArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { var delay = this.affectedArray.length > 0 ? 240 : 0; var promise1 = thisWinUI.executeAnimation( this.addedArray, [{ keyframe: "WinJS-scale-up", property: mstransform, delay: delay, duration: 120, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: "scale(0.85)", to: "none" }, { keyframe: "WinJS-opacity-in", property: "opacity", delay: delay, duration: 120, timing: "linear", from: 0, to: 1 }] ); var promise2 = animTranslate2DTransform( this.affectedArray, this.offsetArray, { property: mstransform, delay: 0, duration: 400, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); return WinJS.Promise.join([promise1, promise2]); } }, { // Static Members supportedForProcessing: false, }); var DeleteFromListAnimation = WinJS.Class.define(function DeleteFromListAnimation_ctor(deletedArray, remainingArray, offsetArray) { // Constructor this.deletedArray = deletedArray; this.remainingArray = remainingArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { var promise1 = thisWinUI.executeAnimation( this.deletedArray, [{ keyframe: "WinJS-scale-down", property: mstransform, delay: 0, duration: 120, timing: "cubic-bezier(0.11, 0.5, 0.24, .96)", from: "none", to: "scale(0.85)" }, { keyframe: "WinJS-opacity-out", property: "opacity", delay: 0, duration: 120, timing: "linear", from: 1, to: 0 }]); var promise2 = animTranslate2DTransform( this.remainingArray, this.offsetArray, { property: mstransform, delay: this.deletedArray.length > 0 ? 60 : 0, duration: 400, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); return WinJS.Promise.join([promise1, promise2]); } }, { // Static Members supportedForProcessing: false, }); var _UpdateListAnimation = WinJS.Class.define(function _UpdateListAnimation_ctor(addedArray, affectedArray, offsetArray, deleted) { // Constructor this.addedArray = addedArray; this.affectedArray = affectedArray; this.offsetArray = offsetArray; var deletedArray = makeArray(deleted); this.deletedArray = deletedArray; this.deletedOffsetArray = collectOffsetArray(deletedArray); }, { // Public Members execute: function () { makeOffsetsRelative(this.deletedArray, this.deletedOffsetArray); var delay = 0; var promise1 = thisWinUI.executeAnimation( this.deletedArray, [{ keyframe: keyframeCallbackAnimate(this.deletedOffsetArray, "WinJS-scale-down"), property: mstransform, delay: 0, duration: 120, timing: "cubic-bezier(0.11, 0.5, 0.24, .96)", from: translateCallbackAnimate(this.deletedOffsetArray), to: translateCallbackAnimate(this.deletedOffsetArray, "scale(0.85)") }, { keyframe: "WinJS-opacity-out", property: "opacity", delay: 0, duration: 120, timing: "linear", from: 1, to: 0 }]); if (this.deletedArray.length > 0) { delay += 60; } var promise2 = animTranslate2DTransform( this.affectedArray, this.offsetArray, { property: mstransform, delay: delay, duration: 400, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); if (this.affectedArray.length > 0) { delay += 240; } else if (delay) { delay += 60; } var promise3 = thisWinUI.executeAnimation( this.addedArray, [{ keyframe: "WinJS-scale-up", property: mstransform, delay: delay, duration: 120, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: "scale(0.85)", to: "none" }, { keyframe: "WinJS-opacity-in", property: "opacity", delay: delay, duration: 120, timing: "linear", from: 0, to: 1 }] ); return WinJS.Promise.join([promise1, promise2, promise3]); } }, { // Static Members supportedForProcessing: false, }); var AddToSearchListAnimation = WinJS.Class.define(function AddToSearchListAnimation_ctor(addedArray, affectedArray, offsetArray) { // Constructor this.addedArray = addedArray; this.affectedArray = affectedArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { var promise1 = thisWinUI.executeAnimation( this.addedArray, { keyframe: "WinJS-opacity-in", property: "opacity", delay: this.affectedArray.length > 0 ? 240 : 0, duration: 117, timing: "linear", from: 0, to: 1 }); var promise2 = animTranslate2DTransform( this.affectedArray, this.offsetArray, { property: mstransform, delay: 0, duration: 400, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); return WinJS.Promise.join([promise1, promise2]); } }, { // Static Members supportedForProcessing: false, }); var DeleteFromSearchListAnimation = WinJS.Class.define(function DeleteFromSearchListAnimation_ctor(deletedArray, remainingArray, offsetArray) { // Constructor this.deletedArray = deletedArray; this.remainingArray = remainingArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { var promise1 = thisWinUI.executeAnimation( this.deletedArray, { keyframe: "WinJS-opacity-out", property: "opacity", delay: 0, duration: 93, timing: "linear", from: 1, to: 0 }); var promise2 = animTranslate2DTransform( this.remainingArray, this.offsetArray, { property: mstransform, delay: this.deletedArray.length > 0 ? 60 : 0, duration: 400, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); return WinJS.Promise.join([promise1, promise2]); } }, { // Static Members supportedForProcessing: false, }); var PeekAnimation = WinJS.Class.define(function PeekAnimation_ctor(target, elementArray, offsetArray) { // Constructor this.elementArray = elementArray; this.offsetArray = offsetArray; }, { // Public Members execute: function () { return animTranslate2DTransform( this.elementArray, this.offsetArray, { property: mstransform, delay: 0, duration: 2000, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); } }, { // Static Members supportedForProcessing: false, }); WinJS.Namespace.define("WinJS.UI.Animation", { createExpandAnimation: function (revealed, affected) { /// /// /// Creates an expand animation. /// After creating the ExpandAnimation object, /// modify the document to move the elements to their new positions, /// then call the execute method on the ExpandAnimation object. /// /// /// Single element or collection of elements which were revealed. /// /// /// Single element or collection of elements whose positions were /// affected by the expand. /// /// /// ExpandAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(ExpandAnimation, revealed, affected); }, createCollapseAnimation: function (hidden, affected) { /// /// /// Creates a collapse animation. /// After creating the CollapseAnimation object, /// modify the document to move the elements to their new positions, /// then call the execute method on the CollapseAnimation object. /// /// /// Single element or collection of elements being removed from view. /// When the animation completes, the application should hide the elements /// or remove them from the document. /// /// /// Single element or collection of elements whose positions were /// affected by the collapse. /// /// /// CollapseAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(CollapseAnimation, hidden, affected); }, createRepositionAnimation: function (element) { /// /// /// Creates a reposition animation. /// After creating the RepositionAnimation object, /// modify the document to move the elements to their new positions, /// then call the execute method on the RepositionAnimation object. /// /// /// Single element or collection of elements which were repositioned. /// /// /// RepositionAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(RepositionAnimation, null, element); }, fadeIn: function (shown) { /// /// /// Execute a fade-in animation. /// /// /// Single element or collection of elements to fade in. /// At the end of the animation, the opacity of the elements is 1. /// /// /// Promise object that completes when the animation is complete. /// /// return thisWinUI.executeTransition( shown, { property: "opacity", delay: 0, duration: 250, timing: "linear", from: 0, to: 1 }); }, fadeOut: function (hidden) { /// /// /// Execute a fade-out animation. /// /// /// Single element or collection of elements to fade out. /// At the end of the animation, the opacity of the elements is 0. /// /// /// Promise object that completes when the animation is complete. /// /// return thisWinUI.executeTransition( hidden, { property: "opacity", delay: 0, duration: 167, timing: "linear", to: 0 }); }, createAddToListAnimation: function (added, affected) { /// /// /// Creates an animation for adding to a list. /// After creating the AddToListAnimation object, /// modify the document to move the elements to their new positions, /// then call the execute method on the AddToListAnimation object. /// /// /// Single element or collection of elements which were added. /// /// /// Single element or collection of elements whose positions were /// affected by the add. /// /// /// AddToListAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(AddToListAnimation, added, affected); }, createDeleteFromListAnimation: function (deleted, remaining) { /// /// /// Crestes an animation for deleting from a list. /// After creating the DeleteFromListAnimation object, /// modify the document to reflect the deletion, /// then call the execute method on the DeleteFromListAnimation object. /// /// /// Single element or collection of elements which will be deleted. /// When the animation completes, the application should hide the elements /// or remove them from the document. /// /// /// Single element or collection of elements whose positions were /// affected by the deletion. /// /// /// DeleteFromListAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(DeleteFromListAnimation, deleted, remaining); }, _createUpdateListAnimation: function (added, deleted, affected) { return layoutTransition(_UpdateListAnimation, added, affected, deleted); }, createAddToSearchListAnimation: function (added, affected) { /// /// /// Creates an animation for adding to a list of search results. /// This is similar to an AddToListAnimation, but faster. /// After creating the AddToSearchListAnimation object, /// modify the document to move the elements to their new positions, /// then call the execute method on the AddToSearchListAnimation object. /// /// /// Single element or collection of elements which were added. /// /// /// Single element or collection of elements whose positions were /// affected by the add. /// /// /// AddToSearchListAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(AddToSearchListAnimation, added, affected); }, createDeleteFromSearchListAnimation: function (deleted, remaining) { /// /// /// Creates an animation for deleting from a list of search results. /// This is similar to an DeleteFromListAnimation, but faster. /// After creating the DeleteFromSearchListAnimation object, /// modify the document to move the elements to their new positions, /// then call the execute method on the DeleteFromSearchListAnimation object. /// /// /// Single element or collection of elements which will be deleted. /// When the animation completes, the application should hide the elements /// or remove them from the document. /// /// /// Single element or collection of elements whose positions were /// affected by the deletion. /// /// /// DeleteFromSearchListAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(DeleteFromSearchListAnimation, deleted, remaining); }, showEdgeUI: function (element, offset, options) { /// /// /// Slides an element or elements into position at the edge of the screen. /// This animation is designed for a small object like an appbar. /// /// /// Single element or collection of elements to be slid into position. /// The elements should be at their final positions /// at the time the function is called. /// /// /// Optional offset object or collection of offset objects /// array describing the starting point of the animation. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Optional object which can specify the mechanism to use to play the animation. By default css /// animations are used but if { mechanism: "transition" } is provided css transitions will be used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-showEdgeUI", [{ top: "-70px", left: "0px" }]); return thisWinUI[((options && options.mechanism === "transition") ? "executeTransition" : "executeAnimation")]( element, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 367, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: offsetArray.keyframe || translateCallback(offsetArray), to: "none" }); }, showPanel: function (element, offset) { /// /// /// Slides an element or elements into position at the edge of the screen. /// This animation is designed for a large object like a keyboard. /// /// /// Single element or collection of elements to be slid into position. /// The elements should be at their final positions /// at the time the function is called. /// /// /// Optional offset object or collection of offset objects /// array describing the starting point of the animation. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// promise object /// /// var offsetArray = new OffsetArray(offset, "WinJS-showPanel", [{ top: "0px", left: "364px", rtlflip: true }]); return thisWinUI.executeAnimation( element, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 550, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: offsetArray.keyframe || translateCallback(offsetArray), to: "none" }); }, hideEdgeUI: function (element, offset, options) { /// /// /// Slides an element or elements at the edge of the screen out of view. /// This animation is designed for a small object like an appbar. /// /// /// Single element or collection of elements to be slid out. /// The elements should be at their onscreen positions /// at the time the function is called. /// /// /// Optional offset object or collection of offset objects /// array describing the ending point of the animation. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Optional object which can specify the mechanism to use to play the animation. By default css /// animations are used but if { mechanism: "transition" } is provided css transitions will be used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-hideEdgeUI", [{ top: "-70px", left: "0px" }]); return thisWinUI[((options && options.mechanism === "transition") ? "executeTransition" : "executeAnimation")]( element, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 367, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: "none", to: offsetArray.keyframe || translateCallback(offsetArray) }); }, hidePanel: function (element, offset) { /// /// /// Slides an element or elements at the edge of the screen out of view. /// This animation is designed for a large object like a keyboard. /// /// /// Single element or collection of elements to be slid out. /// The elements should be at their onscreen positions /// at the time the function is called. /// /// /// Optional offset object or collection of offset objects /// array describing the ending point of the animation. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-hidePanel", [{ top: "0px", left: "364px", rtlflip: true }]); return thisWinUI.executeAnimation( element, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 550, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: "none", to: offsetArray.keyframe || translateCallback(offsetArray) }); }, showPopup: function (element, offset) { /// /// /// Displays an element or elements in the style of a popup. /// /// /// Single element or collection of elements to be shown like a popup. /// /// /// Optional offset object or collection of offset objects /// array describing the starting point of the animation. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-showPopup", [{ top: "50px", left: "0px" }]); return thisWinUI.executeAnimation( element, [{ keyframe: "WinJS-opacity-in", property: "opacity", delay: 83, duration: 83, timing: "linear", from: 0, to: 1 }, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 367, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: offsetArray.keyframe || translateCallback(offsetArray), to: "none" }]); }, hidePopup: function (element) { /// /// /// Removes a popup from the screen. /// /// /// Single element or collection of elements to be hidden like a popup. /// When the animation completes, the application should hide the elements /// or remove them from the document. /// /// /// Promise object that completes when the animation is complete. /// /// return thisWinUI.executeAnimation( element, { keyframe: "WinJS-opacity-out", property: "opacity", delay: 0, duration: 83, timing: "linear", from: 1, to: 0 }); }, pointerDown: function (element) { /// /// /// Execute a pointer-down animation. /// Use the pointerUp animation to reverse the effect of this animation. /// /// /// Single element or collection of elements responding to the /// pointer-down event. /// At the end of the animation, the elements' properties have been /// modified to reflect the pointer-down state. /// /// /// Promise object that completes when the animation is complete. /// /// return thisWinUI.executeTransition( element, { property: mstransform, delay: 0, duration: 167, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "scale(0.975, 0.975)" }); }, pointerUp: function (element) { /// /// /// Execute a pointer-up animation. /// This reverses the effect of a pointerDown animation. /// /// /// Single element or collection of elements responding to /// the pointer-up event. /// At the end of the animation, the elements' properties have been /// returned to normal. /// /// /// Promise object that completes when the animation is complete. /// /// return thisWinUI.executeTransition( element, { property: mstransform, delay: 0, duration: 167, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); }, dragSourceStart: function (dragSource, affected) { /// /// /// Execute a drag-start animation. /// Use the dragSourceEnd animation to reverse the effects of this animation. /// /// /// Single element or collection of elements being dragged. /// At the end of the animation, the elements' properties have been /// modified to reflect the drag state. /// /// /// Single element or collection of elements to highlight as not /// being dragged. /// At the end of the animation, the elements' properties have been /// modified to reflect the drag state. /// /// /// Promise object that completes when the animation is complete. /// /// var promise1 = thisWinUI.executeTransition( dragSource, [{ property: mstransform, delay: 0, duration: 240, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "scale(1.05)" }, { property: "opacity", delay: 0, duration: 240, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: 0.65 }]); var promise2 = thisWinUI.executeTransition( affected, { property: mstransform, delay: 0, duration: 240, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "scale(0.95)" }); return WinJS.Promise.join([promise1, promise2]); }, dragSourceEnd: function (dragSource, offset, affected) { /// /// /// Execute a drag-end animation. /// This reverses the effect of the dragSourceStart animation. /// /// /// Single element or collection of elements no longer being dragged. /// At the end of the animation, the elements' properties have been /// returned to normal. /// /// /// Optional offset object or collection of offset objects /// array describing the starting point of the animation. /// If the number of offset objects is less than the length of the /// dragSource parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Single element or collection of elements which were highlighted as not /// being dragged. /// At the end of the animation, the elements' properties have been /// returned to normal. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-dragSourceEnd"); var promise1 = thisWinUI.executeTransition( dragSource, [{ property: mstransform, delay: 0, duration: 500, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" // this removes the scale }, { property: "opacity", delay: 0, duration: 500, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: 1 }]); var promise2 = thisWinUI.executeAnimation( dragSource, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 500, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: offsetArray.keyframe || translateCallback(offsetArray, "scale(1.05) "), to: "none" }); var promise3 = thisWinUI.executeTransition( affected, { property: mstransform, delay: 0, duration: 500, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); return WinJS.Promise.join([promise1, promise2, promise3]); }, enterContent: function (incoming, offset, options) { /// /// /// Execute an enter-content animation. /// /// /// Single element or collection of elements which represent /// the incoming content. /// At the end of the animation, the opacity of the elements is 1. /// /// /// Optional offset object or collection of offset objects /// array describing the starting point of the animation. /// If the number of offset objects is less than the length of the /// incoming parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Optional object which can specify the mechanism to use to play the animation. By default css /// animations are used but if { mechanism: "transition" } is provided css transitions will be used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-enterContent", [{ top: "0px", left: "40px", rtlflip: true }]); if (options && options.mechanism === "transition") { return thisWinUI.executeTransition( incoming, [{ property: mstransform, delay: 0, duration: 550, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: translateCallback(offsetArray), to: "none" }, { property: "opacity", delay: 0, duration: 170, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 0, to: 1 }]); } else { var promise1 = thisWinUI.executeAnimation( incoming, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 550, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: offsetArray.keyframe || translateCallback(offsetArray), to: "none" }); var promise2 = thisWinUI.executeTransition( incoming, { property: "opacity", delay: 0, duration: 170, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 0, to: 1 }); return WinJS.Promise.join([promise1, promise2]); } }, exitContent: function (outgoing, offset) { /// /// /// Execute an exit-content animation. /// /// /// Single element or collection of elements which represent /// the outgoing content. /// At the end of the animation, the opacity of the elements is 0. /// /// /// Optional offset object or collection of offset objects /// array describing the ending point of the animation. /// If the number of offset objects is less than the length of the /// outgoing parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-exit", [{ top: "0px", left: "0px" }]); var promise1 = thisWinUI.executeAnimation( outgoing, offset && { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 117, timing: "linear", from: "none", to: offsetArray.keyframe || translateCallback(offsetArray) }); var promise2 = thisWinUI.executeTransition( outgoing, { property: "opacity", delay: 0, duration: 117, timing: "linear", to: 0 }); return WinJS.Promise.join([promise1, promise2]); }, dragBetweenEnter: function (target, offset) { /// /// /// Execute an animation which indicates that a dragged object /// can be dropped between other elements. /// Use the dragBetweenLeave animation to reverse the effects of this animation. /// /// /// Single element or collection of elements (usually two) /// that the dragged object can be dropped between. /// At the end of the animation, the elements' properties have been /// modified to reflect the drag-between state. /// /// /// Optional offset object or collection of offset objects /// array describing the ending point of the animation. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, null, [{ top: "-40px", left: "0px" }, { top: "40px", left: "0px" }]); return thisWinUI.executeTransition( target, { property: mstransform, delay: 0, duration: 200, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: translateCallback(offsetArray, "scale(0.95) ") }); }, dragBetweenLeave: function (target) { /// /// /// Execute an animation which indicates that a dragged object /// will no longer be dropped between other elements. /// This reverses the effect of the dragBetweenEnter animation. /// /// /// Single element or collection of elements (usually two) /// that the dragged object no longer will be dropped between. /// At the end of the animation, the elements' properties have been /// set to the dragSourceStart state. /// /// /// Promise object that completes when the animation is complete. /// /// return thisWinUI.executeTransition( target, { property: mstransform, delay: 0, duration: 200, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "scale(0.95)" }); }, swipeSelect: function (selected, selection) { /// /// /// Slide a swipe-selected object back into position when the /// pointer is released, and show the selection mark. /// /// /// Single element or collection of elements being selected. /// At the end of the animation, the elements' properties have been /// returned to normal. /// /// /// Single element or collection of elements that is the selection mark. /// /// /// Promise object that completes when the animation is complete. /// /// var promise1 = thisWinUI.executeTransition( selected, { property: mstransform, delay: 0, duration: 300, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); var promise2 = thisWinUI.executeAnimation( selection, { keyframe: "WinJS-opacity-in", property: "opacity", delay: 0, duration: 300, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 0, to: 1 }); return WinJS.Promise.join([promise1, promise2]); }, swipeDeselect: function (deselected, selection) { /// /// /// Slide a swipe-deselected object back into position when the /// pointer is released, and hide the selection mark. /// /// /// Single element or collection of elements being deselected. /// At the end of the animation, the elements' properties have been /// returned to normal. /// /// /// Single element or collection of elements that is the selection mark. /// /// /// Promise object that completes when the animation is complete. /// /// var promise1 = thisWinUI.executeTransition( deselected, { property: mstransform, delay: 0, duration: 300, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" }); var promise2 = thisWinUI.executeAnimation( selection, { keyframe: "WinJS-opacity-out", property: "opacity", delay: 0, duration: 300, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 1, to: 0 }); return WinJS.Promise.join([promise1, promise2]); }, swipeReveal: function (target, offset) { /// /// /// Reveal an object as the result of a swipe, or slide the /// swipe-selected object back into position after the reveal. /// /// /// Single element or collection of elements being selected. /// At the end of the animation, the elements' properties have been /// modified to reflect the specified offset. /// /// /// Optional offset object or collection of offset objects /// array describing the ending point of the animation. /// When moving the object back into position, the offset should be /// { top: "0px", left: "0px" }. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// The default value describes the motion for a reveal. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, null, [{ top: "25px", left: "0px" }]); return thisWinUI.executeTransition( target, { property: mstransform, delay: 0, duration: 300, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: translateCallback(offsetArray) }); }, enterPage: function (element, offset) { /// /// /// Execute an enterPage animation. /// /// /// Single element or collection of elements representing the /// incoming page. /// At the end of the animation, the opacity of the elements is 1. /// /// /// Optional offset object or collection of offset objects /// array describing the starting point of the animation. /// If the number of offset objects is less than the length of the /// element parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-enterPage", [{ top: "0px", left: "100px", rtlflip: true }]); var promise1 = thisWinUI.executeAnimation( element, { keyframe: offsetArray.keyframe, property: mstransform, delay: staggerDelay(0, 83, 1, 333), duration: 1000, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: offsetArray.keyframe || translateCallback(offsetArray), to: "none" }); var promise2 = thisWinUI.executeTransition( element, { property: "opacity", delay: staggerDelay(0, 83, 1, 333), duration: 170, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 0, to: 1 }); return WinJS.Promise.join([promise1, promise2]); }, exitPage: function (outgoing, offset) { /// /// /// Execute an exitPage animation. /// /// /// Single element or collection of elements representing /// the outgoing page. /// At the end of the animation, the opacity of the elements is 0. /// /// /// Optional offset object or collection of offset objects /// array describing the ending point of the animation. /// If the number of offset objects is less than the length of the /// outgoing parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-exit", [{ top: "0px", left: "0px" }]); var promise1 = thisWinUI.executeAnimation( outgoing, offset && { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 117, timing: "linear", from: "none", to: offsetArray.keyframe || translateCallback(offsetArray) }); var promise2 = thisWinUI.executeTransition( outgoing, { property: "opacity", delay: 0, duration: 117, timing: "linear", to: 0 }); return WinJS.Promise.join([promise1, promise2]); }, crossFade: function (incoming, outgoing) { /// /// /// Execute a crossFade animation. /// /// /// Single incoming element or collection of incoming elements. /// At the end of the animation, the opacity of the elements is 1. /// /// /// Single outgoing element or collection of outgoing elements. /// At the end of the animation, the opacity of the elements is 0. /// /// /// Promise object that completes when the animation is complete. /// /// var promise1 = thisWinUI.executeTransition( incoming, { property: "opacity", delay: 0, duration: 167, timing: "linear", to: 1 }); var promise2 = thisWinUI.executeTransition( outgoing, { property: "opacity", delay: 0, duration: 167, timing: "linear", to: 0 }); return WinJS.Promise.join([promise1, promise2]); }, createPeekAnimation: function (element) { /// /// /// Creates a peek animation. /// After creating the PeekAnimation object, /// modify the document to move the elements to their new positions, /// then call the execute method on the PeekAnimation object. /// /// /// Single element or collection of elements to be repositioned for peek. /// /// /// PeekAnimation object whose execute method returns /// a Promise that completes when the animation is complete. /// /// return layoutTransition(PeekAnimation, null, element); }, updateBadge: function (incoming, offset) { /// /// /// Execute an updateBadge animation. /// /// /// Single element or collection of elements representing the /// incoming badge. /// /// /// Optional offset object or collection of offset objects /// array describing the starting point of the animation. /// If the number of offset objects is less than the length of the /// incoming parameter, then the last value is repeated for all /// remaining elements. /// If this parameter is omitted, then a default value is used. /// /// /// Promise object that completes when the animation is complete. /// /// var offsetArray = new OffsetArray(offset, "WinJS-updateBadge", [{ top: "24px", left: "0px" }]); return thisWinUI.executeAnimation( incoming, [{ keyframe: "WinJS-opacity-in", property: "opacity", delay: 0, duration: 367, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: 0, to: 1 }, { keyframe: offsetArray.keyframe, property: mstransform, delay: 0, duration: 1333, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", from: offsetArray.keyframe || translateCallback(offsetArray), to: "none" }]); } }); })(WinJS); /*#DBG var _ASSERT = function (condition) { if (!condition) { throw "ASSERT FAILED"; } }; var _TRACE = function (text) { if (window.console && console.log) { console.log(text); } }; #DBG*/ // WinJS.Binding.ListDataSource // (function bindingListDataSourceInit(global, undefined) { "use strict"; WinJS.Namespace.define("WinJS.Binding", { _BindingListDataSource: WinJS.Namespace._lazy(function () { var errors = { get noLongerMeaningful() { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.EditError.noLongerMeaningful)); } }; function findNextKey(list, index) { var len = list.length; while (index < len - 1) { var item = list.getItem(++index); if (item) { return item.key; } } return null; } function findPreviousKey(list, index) { while (index > 0) { var item = list.getItem(--index); if (item) { return item.key; } } return null; } function subscribe(target, handlers) { Object.keys(handlers).forEach(function (handler) { target.addEventListener(handler, handlers[handler]); }); } function unsubscribe(target, handlers) { Object.keys(handlers).forEach(function (handler) { target.removeEventListener(handler, handlers[handler]); }); } var CompletePromise = WinJS.Promise.wrap().constructor; var NullWrappedItem = WinJS.Class.derive(CompletePromise, function () { this._value = null; }, { release: function () { }, retain: function () { return this; } }, { supportedForProcessing: false, } ); var WrappedItem = WinJS.Class.derive(CompletePromise, function (listBinding, item) { this._value = item; this._listBinding = listBinding; }, { handle: { get: function () { return this._value.key; } }, index: { get: function () { return this._value.index; } }, release: function () { this._listBinding._release(this._value, this._listBinding._list.indexOfKey(this._value.key)); }, retain: function () { this._listBinding._addRef(this._value, this._listBinding._list.indexOfKey(this._value.key)); return this; } }, { supportedForProcessing: false, } ); var AsyncWrappedItem = WinJS.Class.derive(WinJS.Promise, function (listBinding, item, name) { var that = this; this._item = item; this._listBinding = listBinding; WinJS.Promise.call(this, function (c) { WinJS.Utilities.Scheduler.schedule(function () { if (listBinding._released) { that.cancel(); return; } c(item); }, WinJS.Utilities.Scheduler.Priority.normal, null, "WinJS.Binding.List." + name); }); }, { handle: { get: function () { return this._item.key; } }, index: { get: function () { return this._item.index; } }, release: function () { this._listBinding._release(this._item, this._listBinding._list.indexOfKey(this._item.key)); }, retain: function () { this._listBinding._addRef(this._item, this._listBinding._list.indexOfKey(this._item.key)); return this; } }, { supportedForProcessing: false, } ); function wrap(listBinding, item) { return item ? new WrappedItem(listBinding, item) : new NullWrappedItem(); } function wrapAsync(listBinding, item, name) { return item ? new AsyncWrappedItem(listBinding, item, name) : new NullWrappedItem(); } function cloneWithIndex(list, item, index) { return item && list._annotateWithIndex(item, index); } var ListBinding = WinJS.Class.define(function ListBinding_ctor(dataSource, list, notificationHandler, id) { this._dataSource = dataSource; this._list = list; this._editsCount = 0; this._notificationHandler = notificationHandler; this._pos = -1; this._retained = []; this._retained.length = list.length; this._retainedKeys = {}; this._affectedRange = null; // When in WebContext, weakref utility functions don't work as desired so we capture this // ListBinding object in the handler's closure. This causes the same leak as in 1.0. var fallbackReference = null; if (!WinJS.Utilities.hasWinRT || !global.msSetWeakWinRTProperty || !global.msGetWeakWinRTProperty) { fallbackReference = this; } if (notificationHandler) { var handleEvent = function (eventName, eventArg) { var lb = WinJS.Utilities._getWeakRefElement(id) || fallbackReference; if (lb) { lb["_" + eventName](eventArg); return true; } return false; }; this._handlers = { itemchanged: function handler(event) { if (!handleEvent("itemchanged", event)) { list.removeEventListener("itemchanged", handler); } }, iteminserted: function handler(event) { if (!handleEvent("iteminserted", event)) { list.removeEventListener("iteminserted", handler); } }, itemmoved: function handler(event) { if (!handleEvent("itemmoved", event)) { list.removeEventListener("itemmoved", handler); } }, itemremoved: function handler(event) { if (!handleEvent("itemremoved", event)) { list.removeEventListener("itemremoved", handler); } }, reload: function handler() { if (!handleEvent("reload")) { list.removeEventListener("reload", handler); } } }; subscribe(this._list, this._handlers); } }, { _itemchanged: function (event) { var key = event.detail.key; var index = event.detail.index; this._updateAffectedRange(index, "changed"); var newItem = event.detail.newItem; var oldItem = this._retained[index]; if (oldItem) { var handler = this._notificationHandler; if (oldItem.index !== index) { var oldIndex = oldItem.index; oldItem.index = index; if (handler && handler.indexChanged) { handler.indexChanged(newItem.key, index, oldIndex); } } newItem = cloneWithIndex(this._list, newItem, index); newItem._retainedCount = oldItem._retainedCount; this._retained[index] = newItem; this._retainedKeys[key] = newItem; this._beginEdits(this._list.length); if (handler && handler.changed) { handler.changed( newItem, oldItem ); } this._endEdits(); } else { // Item was not retained, but we still want to batch this change with the other edits to send the affectedRange notification. this._beginEdits(this._list.length); this._endEdits(); } }, _iteminserted: function (event) { var key = event.detail.key; var index = event.detail.index; this._updateAffectedRange(index, "inserted"); this._beginEdits(this._list.length - 1); if (index <= this._pos) { this._pos = Math.min(this._pos + 1, this._list.length); } var retained = this._retained; // create a hole for this thing and then immediately make it undefined retained.splice(index, 0, 0); delete retained[index]; if (this._shouldNotify(index) || this._list.length === 1) { var handler = this._notificationHandler; if (handler && handler.inserted) { handler.inserted( wrap(this, cloneWithIndex(this._list, this._list.getItem(index), index)), findPreviousKey(this._list, index), findNextKey(this._list, index) ); } } this._endEdits(); }, _itemmoved: function (event) { var key = event.detail.key; var oldIndex = event.detail.oldIndex; var newIndex = event.detail.newIndex; this._updateAffectedRange(oldIndex, "moved"); this._updateAffectedRange(newIndex, "moved"); this._beginEdits(this._list.length); if (oldIndex < this._pos || newIndex <= this._pos) { if (newIndex > this._pos) { this._pos = Math.max(-1, this._pos - 1); } else if (oldIndex > this._pos) { this._pos = Math.min(this._pos + 1, this._list.length); } } var retained = this._retained; var item = retained.splice(oldIndex, 1)[0]; retained.splice(newIndex, 0, item); if (!item) { delete retained[newIndex]; item = cloneWithIndex(this._list, this._list.getItem(newIndex), newIndex); } item._moved = true; this._addRef(item, newIndex); this._endEdits(); }, _itemremoved: function (event) { var key = event.detail.key; var index = event.detail.index; this._updateAffectedRange(index, "removed"); this._beginEdits(this._list.length + 1); if (index < this._pos) { this._pos = Math.max(-1, this._pos - 1); } var retained = this._retained; var retainedKeys = this._retainedKeys; var wasRetained = index in retained; retained.splice(index, 1); delete retainedKeys[key]; var handler = this._notificationHandler; if (wasRetained && handler && handler.removed) { handler.removed(key, false); } this._endEdits(); }, _reload: function () { this._retained = []; this._retainedKeys = {}; var handler = this._notificationHandler; if (handler && handler.reload) { handler.reload(); } }, _addRef: function (item, index) { if (index in this._retained) { this._retained[index]._retainedCount++; } else { this._retained[index] = item; this._retainedKeys[item.key] = item; item._retainedCount = 1; } }, _release: function (item, index) { var retained = this._retained[index]; if (retained) { //#DBG _ASSERT(retained.key === item.key); if (retained._retainedCount === 1) { delete this._retained[index]; delete this._retainedKeys[retained.key]; } else { retained._retainedCount--; } } /*#DBG // If an item isn't found in the retained map, it was either removed from retainedCount reaching zero, or removed from the map by a removed notification. // We'll decrement the count here for debugging purposes. If retainedCount is less than zero, there's a refcounting error somewhere. if (!retained) { item._retainedCount--; _ASSERT(item._retainedCount >= 0); } #DBG*/ }, _shouldNotify: function (index) { var retained = this._retained; return index in retained || index + 1 in retained || index - 1 in retained; }, _updateAffectedRange: function ListBinding_updateAffectedRange(index, operation) { // Creates a range of affected indices [start, end). // Definition of _affectedRange.start: All items in the set of data with indices < _affectedRange.start have not been directly modified. // Definition of _affectedRange.end: All items in the set of data with indices >= _affectedRange.end have not been directly modified. if (!this._notificationHandler.affectedRange) { return; } //[newStart, newEnd) var newStart = index; var newEnd = (operation !== "removed") ? index + 1 : index; if (this._affectedRange) { switch (operation) { case "inserted": if (index <= this._affectedRange.end) { ++this._affectedRange.end; } break; case "removed": if (index < this._affectedRange.end) { --this._affectedRange.end; } break; case "moved": case "changed": break; } this._affectedRange.start = Math.min(this._affectedRange.start, newStart); this._affectedRange.end = Math.max(this._affectedRange.end, newEnd); } else { // Handle the initial state this._affectedRange = { start: newStart, end: newEnd }; } }, _notifyAffectedRange: function ListBinding_notifyAffectedRange() { if (this._affectedRange) { if (this._notificationHandler && this._notificationHandler.affectedRange) { this._notificationHandler.affectedRange(this._affectedRange); } // reset range this._affectedRange = null; } }, _notifyCountChanged: function () { var oldCount = this._countAtBeginEdits; var newCount = this._list.length; if (oldCount !== newCount) { var handler = this._notificationHandler; if (handler && handler.countChanged) { handler.countChanged(newCount, oldCount); } } }, _notifyIndicesChanged: function () { var retained = this._retained; for (var i = 0, len = retained.length; i < len; i++) { var item = retained[i]; if (item && item.index !== i) { var newIndex = i; var oldIndex = item.index; item.index = newIndex; var handler = this._notificationHandler; if (handler && handler.indexChanged) { handler.indexChanged(item.key, newIndex, oldIndex); } } } }, _notifyMoved: function () { var retained = this._retained; for (var i = 0, len = retained.length; i < len; i++) { var item = retained[i]; if (item && item._moved) { item._moved = false; this._release(item, i); if (this._shouldNotify(i)) { var handler = this._notificationHandler; if (handler && handler.moved) { handler.moved( wrap(this, item), findPreviousKey(this._list, i), findNextKey(this._list, i) ); } } } } }, _beginEdits: function (length, explicit) { this._editsCount++; var handler = this._notificationHandler; if (this._editsCount === 1 && handler) { if (!explicit) { // Batch all edits between now and the job running. This has the effect // of batching synchronous edits. // this._editsCount++; var that = this; WinJS.Utilities.Scheduler.schedule(function () { that._endEdits(); }, WinJS.Utilities.Scheduler.Priority.high, null, "WinJS.Binding.List._endEdits"); } if (handler.beginNotifications) { handler.beginNotifications(); } this._countAtBeginEdits = length; } }, _endEdits: function () { this._editsCount--; var handler = this._notificationHandler; if (this._editsCount === 0 && handler) { this._notifyIndicesChanged(); this._notifyMoved(); this._notifyCountChanged(); // It's important to notify the affectedRange after _notifyCountChanged since we expect developers // may take a dependancy on the count being up to date when they recieve the affected range. this._notifyAffectedRange(); if (handler.endNotifications) { handler.endNotifications(); } } }, jumpToItem: function (item) { var index = this._list.indexOfKey(item.handle); if (index === -1) { return WinJS.Promise.wrap(null); } this._pos = index; return this.current(); }, current: function () { return this.fromIndex(this._pos); }, previous: function () { this._pos = Math.max(-1, this._pos - 1); return this._fromIndex(this._pos, true, "previous"); }, next: function () { this._pos = Math.min(this._pos + 1, this._list.length); return this._fromIndex(this._pos, true, "next"); }, releaseItem: function (item) { if (item.release) { item.release(); } else { this._release(item, this._list.indexOfKey(item.key)); } }, release: function () { if (this._notificationHandler) { unsubscribe(this._list, this._handlers); } this._notificationHandler = null; this._dataSource._releaseBinding(this); this._released = true; }, first: function () { return this.fromIndex(0); }, last: function () { return this.fromIndex(this._list.length - 1); }, fromKey: function (key) { var retainedKeys = this._retainedKeys; var item; if (key in retainedKeys) { item = retainedKeys[key]; } else { item = cloneWithIndex(this._list, this._list.getItemFromKey(key), this._list.indexOfKey(key)); } return wrap(this, item); }, fromIndex: function (index) { return this._fromIndex(index, false, "fromIndex"); }, _fromIndex: function (index, async, name) { var retained = this._retained; var item; if (index in retained) { item = retained[index]; } else { item = cloneWithIndex(this._list, this._list.getItem(index), index); } return async ? wrapAsync(this, item, name) : wrap(this, item); }, }, { supportedForProcessing: false, }); function insertAtStart(unused, data) { // List ignores the key because its key management is internal this._list.unshift(data); return this.itemFromIndex(0); } function insertBefore(unused, data, nextKey) { // List ignores the key because its key management is internal var index = this._list.indexOfKey(nextKey); if (index === -1) { return errors.noLongerMeaningful; } this._list.splice(index, 0, data); return this.itemFromIndex(index); } function insertAfter(unused, data, previousKey) { // List ignores the key because its key management is internal var index = this._list.indexOfKey(previousKey); if (index === -1) { return errors.noLongerMeaningful; } index += 1; this._list.splice(index, 0, data); return this.itemFromIndex(index); } function insertAtEnd(unused, data) { // List ignores the key because its key management is internal this._list.push(data); return this.itemFromIndex(this._list.length - 1); } function change(key, newData) { var index = this._list.indexOfKey(key); if (index === -1) { return errors.noLongerMeaningful; } this._list.setAt(index, newData); return this.itemFromIndex(index); } function moveToStart(key) { var sourceIndex = this._list.indexOfKey(key); if (sourceIndex === -1) { return errors.noLongerMeaningful; } var targetIndex = 0; this._list.move(sourceIndex, targetIndex); return this.itemFromIndex(targetIndex); } function moveBefore(key, nextKey) { var sourceIndex = this._list.indexOfKey(key); var targetIndex = this._list.indexOfKey(nextKey); if (sourceIndex === -1 || targetIndex === -1) { return errors.noLongerMeaningful; } targetIndex = sourceIndex < targetIndex ? targetIndex - 1 : targetIndex; this._list.move(sourceIndex, targetIndex); return this.itemFromIndex(targetIndex); } function moveAfter(key, previousKey) { var sourceIndex = this._list.indexOfKey(key); var targetIndex = this._list.indexOfKey(previousKey); if (sourceIndex === -1 || targetIndex === -1) { return errors.noLongerMeaningful; } targetIndex = sourceIndex <= targetIndex ? targetIndex : targetIndex + 1; this._list.move(sourceIndex, targetIndex); return this.itemFromIndex(targetIndex); } function moveToEnd(key) { var sourceIndex = this._list.indexOfKey(key); if (sourceIndex === -1) { return errors.noLongerMeaningful; } var targetIndex = this._list.length - 1; this._list.move(sourceIndex, targetIndex); return this.itemFromIndex(targetIndex); } function remove(key) { var index = this._list.indexOfKey(key); if (index === -1) { return errors.noLongerMeaningful; } this._list.splice(index, 1); return WinJS.Promise.wrap(); } var bindingId = 0; var DataSource = WinJS.Class.define(function DataSource_ctor(list) { this._usingWeakRef = WinJS.Utilities.hasWinRT && global.msSetWeakWinRTProperty && global.msGetWeakWinRTProperty; this._bindings = {}; this._list = list; if (list.unshift) { this.insertAtStart = insertAtStart; } if (list.push) { this.insertAtEnd = insertAtEnd; } if (list.setAt) { this.change = change; } if (list.splice) { this.insertAfter = insertAfter; this.insertBefore = insertBefore; this.remove = remove; } if (list.move) { this.moveAfter = moveAfter; this.moveBefore = moveBefore; this.moveToEnd = moveToEnd; this.moveToStart = moveToStart; } }, { _releaseBinding: function (binding) { delete this._bindings[binding._id]; }, addEventListener: function () { // nop, we don't send statusChanged }, removeEventListener: function () { // nop, we don't send statusChanged }, createListBinding: function (notificationHandler) { var id = "ds_" + (++bindingId); var binding = new ListBinding(this, this._list, notificationHandler, id); binding._id = id; if (this._usingWeakRef) { WinJS.Utilities._createWeakRef(binding, id); this._bindings[id] = id; } else { this._bindings[id] = binding; } return binding; }, getCount: function () { return WinJS.Promise.wrap(this._list.length); }, itemFromKey: function (key) { // Clone with a dummy index var list = this._list, item = cloneWithIndex(list, list.getItemFromKey(key), -1); // Override the index property with a getter Object.defineProperty(item, "index", { get: function () { return list.indexOfKey(key); }, enumerable: false, configurable: true }); return WinJS.Promise.wrap(item); }, itemFromIndex: function (index) { return WinJS.Promise.wrap(cloneWithIndex(this._list, this._list.getItem(index), index)); }, list: { get: function () { return this._list; } }, beginEdits: function () { var length = this._list.length; this._forEachBinding(function (binding) { binding._beginEdits(length, true); }); }, endEdits: function () { this._forEachBinding(function (binding) { binding._endEdits(); }); }, _forEachBinding: function (callback) { if (this._usingWeakRef) { var toBeDeleted = []; Object.keys(this._bindings).forEach(function (id) { var lb = WinJS.Utilities._getWeakRefElement(id); if (lb) { callback(lb); } else { toBeDeleted.push(id); } }); for (var i = 0, len = toBeDeleted.length; i < len; i++) { delete this._bindings[toBeDeleted[i]]; } } else { var that = this; Object.keys(this._bindings).forEach(function (id) { callback(that._bindings[id]); }); } }, invalidateAll: function () { return WinJS.Promise.wrap(); }, // // insert* and change are not implemented as I don't understand how they are // used by the controls since it is hard to fathom how they would be able // to make up unique keys. Manual editing of the List is meant to go through // the list itself. // // move* are implemented only if the underlying list supports move(). The // GroupsListProjection for instance does not. // moveAfter: undefined, moveBefore: undefined, moveToEnd: undefined, moveToStart: undefined }, { supportedForProcessing: false, }); return DataSource; }) }); }(this)); // Virtualized Data Source (function listDataSourceInit(undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { DataSourceStatus: { ready: "ready", waiting: "waiting", failure: "failure" }, CountResult: { unknown: "unknown" }, CountError: { noResponse: "noResponse" }, FetchError: { noResponse: "noResponse", doesNotExist: "doesNotExist" }, EditError: { noResponse: "noResponse", canceled: "canceled", notPermitted: "notPermitted", noLongerMeaningful: "noLongerMeaningful" }, VirtualizedDataSource: WinJS.Namespace._lazy(function () { var MAX_BEGINREFRESH_COUNT = 100; var uniqueID = 1; var Promise = WinJS.Promise, Signal = WinJS._Signal, Scheduler = WinJS.Utilities.Scheduler, UI = WinJS.UI; // Private statics var strings = { get listDataAdapterIsInvalid() { return WinJS.Resources._getWinJSString("ui/listDataAdapterIsInvalid").value; }, get indexIsInvalid() { return WinJS.Resources._getWinJSString("ui/indexIsInvalid").value; }, get keyIsInvalid() { return WinJS.Resources._getWinJSString("ui/keyIsInvalid").value; }, get invalidItemReturned() { return WinJS.Resources._getWinJSString("ui/undefinedItemReturned").value; }, get invalidKeyReturned() { return WinJS.Resources._getWinJSString("ui/invalidKeyReturned").value; }, get invalidIndexReturned() { return WinJS.Resources._getWinJSString("ui/invalidIndexReturned").value; }, get invalidCountReturned() { return WinJS.Resources._getWinJSString("ui/invalidCountReturned").value; }, get invalidRequestedCountReturned() { return WinJS.Resources._getWinJSString("ui/invalidRequestedCountReturned").value; }, get refreshCycleIdentified() { return WinJS.Resources._getWinJSString("ui/refreshCycleIdentified").value; }, }; var statusChangedEvent = "statuschanged"; function _baseDataSourceConstructor(listDataAdapter, options) { /// /// /// Initializes the VirtualizedDataSource base class of a custom data source. /// /// /// An object that implements IListDataAdapter and supplies data to the VirtualizedDataSource. /// /// /// An object that contains properties that specify additonal options for the VirtualizedDataSource: /// /// cacheSize /// A Number that specifies minimum number of unrequested items to cache in case they are requested. /// /// The options parameter is optional. /// /// // Private members var listDataNotificationHandler, cacheSize, status, statusPending, statusChangePosted, bindingMap, nextListBindingID, nextHandle, nextListenerID, getCountPromise, resultsProcessed, beginEditsCalled, editsInProgress, firstEditInProgress, editQueue, editsQueued, synchronousEdit, waitForRefresh, dataNotificationsInProgress, countDelta, indexUpdateDeferred, nextTempKey, currentRefreshID, fetchesPosted, nextFetchID, fetchesInProgress, fetchCompleteCallbacks, startMarker, endMarker, knownCount, slotsStart, slotListEnd, slotsEnd, handleMap, keyMap, indexMap, releasedSlots, lastSlotReleased, reduceReleasedSlotCountPosted, refreshRequested, refreshInProgress, refreshSignal, refreshFetchesInProgress, refreshItemsFetched, refreshCount, refreshStart, refreshEnd, keyFetchIDs, refreshKeyMap, refreshIndexMap, deletedKeys, synchronousProgress, reentrantContinue, synchronousRefresh, reentrantRefresh; var beginRefreshCount = 0, refreshHistory = new Array(100), refreshHistoryPos = -1; var itemsFromKey, itemsFromIndex, itemsFromStart, itemsFromEnd, itemsFromDescription; if (listDataAdapter.itemsFromKey) { itemsFromKey = function (fetchID, key, countBefore, countAfter, hints) { var perfID = "fetchItemsFromKey id=" + fetchID + " key=" + key + " countBefore=" + countBefore + " countAfter=" + countAfter; profilerMarkStart(perfID); refreshHistory[++refreshHistoryPos % refreshHistory.length] = { kind: "itemsFromKey", key: key, countBefore: countBefore, countAfter: countAfter }; var result = listDataAdapter.itemsFromKey(key, countBefore, countAfter, hints); profilerMarkEnd(perfID); return result; }; } if (listDataAdapter.itemsFromIndex) { itemsFromIndex = function (fetchID, index, countBefore, countAfter) { var perfID = "fetchItemsFromIndex id=" + fetchID + " index=" + index + " countBefore=" + countBefore + " countAfter=" + countAfter; profilerMarkStart(perfID); refreshHistory[++refreshHistoryPos % refreshHistory.length] = { kind: "itemsFromIndex", index: index, countBefore: countBefore, countAfter: countAfter }; var result = listDataAdapter.itemsFromIndex(index, countBefore, countAfter); profilerMarkEnd(perfID); return result; }; } if (listDataAdapter.itemsFromStart) { itemsFromStart = function (fetchID, count) { var perfID = "fetchItemsFromStart id=" + fetchID + " count=" + count; profilerMarkStart(perfID); refreshHistory[++refreshHistoryPos % refreshHistory.length] = { kind: "itemsFromStart", count: count }; var result = listDataAdapter.itemsFromStart(count); profilerMarkEnd(perfID); return result; }; } if (listDataAdapter.itemsFromEnd) { itemsFromEnd = function (fetchID, count) { var perfID = "fetchItemsFromEnd id=" + fetchID + " count=" + count; profilerMarkStart(perfID); refreshHistory[++refreshHistoryPos % refreshHistory.length] = { kind: "itemsFromEnd", count: count }; var result = listDataAdapter.itemsFromEnd(count); profilerMarkEnd(perfID); return result; }; } if (listDataAdapter.itemsFromDescription) { itemsFromDescription = function (fetchID, description, countBefore, countAfter) { var perfID = "fetchItemsFromDescription id=" + fetchID + " desc=" + description + " countBefore=" + countBefore + " countAfter=" + countAfter; profilerMarkStart(perfID); refreshHistory[++refreshHistoryPos % refreshHistory.length] = { kind: "itemsFromDescription", description: description, countBefore: countBefore, countAfter: countAfter }; var result = listDataAdapter.itemsFromDescription(description, countBefore, countAfter); profilerMarkEnd(perfID); return result; }; } var dataSourceID = ++uniqueID; function profilerMarkStart(text) { var message = "WinJS.UI.VirtualizedDataSource:" + dataSourceID + ":" + text + ",StartTM"; msWriteProfilerMark(message); WinJS.log && WinJS.log(message, "winjs vds", "perf"); } function profilerMarkEnd(text) { var message = "WinJS.UI.VirtualizedDataSource:" + dataSourceID + ":" + text + ",StopTM"; msWriteProfilerMark(message); WinJS.log && WinJS.log(message, "winjs vds", "perf"); } /*#DBG var totalSlots = 0; function VERIFYLIST() { _ASSERT(slotListEnd.lastInSequence); _ASSERT(slotsEnd.firstInSequence); checkListIntegrity(slotsStart, slotsEnd, keyMap, indexMap); } function VERIFYREFRESHLIST() { checkListIntegrity(refreshStart, refreshEnd, refreshKeyMap, refreshIndexMap); } function checkListIntegrity(listStart, listEnd, keyMapForSlot, indexMapForSlot) { if (UI.VirtualizedDataSource._internalValidation) { var listEndReached, slotWithoutIndexReached; for (var slotCheck = listStart; slotCheck !== listEnd; slotCheck = slotCheck.next) { _ASSERT(slotCheck.next); _ASSERT(slotCheck.next.prev === slotCheck); if (slotCheck.lastInSequence) { _ASSERT(slotCheck.next.firstInSequence); } if (slotCheck !== listStart) { _ASSERT(slotCheck.prev); _ASSERT(slotCheck.prev.next === slotCheck); if (slotCheck.firstInSequence) { _ASSERT(slotCheck.prev.lastInSequence); } } if (slotCheck.item || slotCheck.itemNew) { _ASSERT(editsQueued || slotCheck.key); } if (slotCheck.key) { _ASSERT(keyMapForSlot[slotCheck.key] === slotCheck); if (slotCheck.item) { _ASSERT(slotCheck.item.key === slotCheck.key); } } if (typeof slotCheck.index === "number") { _ASSERT(!listEndReached); if (!indexUpdateDeferred) { _ASSERT(indexMapForSlot[slotCheck.index] === slotCheck); _ASSERT(slotCheck === listStart || slotCheck.prev.index < slotCheck.index); _ASSERT(!slotCheck.firstInSequence || !slotCheck.prev || slotCheck.prev.index !== slotCheck.index - 1); _ASSERT(!slotCheck.lastInSequence || !slotCheck.next || slotCheck.next.index !== slotCheck.index + 1); if (slotCheck.item) { _ASSERT(listStart === refreshStart || slotCheck.item.index === slotCheck.index); } } } else { slotWithoutIndexReached = true; } if (slotCheck === slotListEnd) { listEndReached = true; } if (slotCheck.lastInSequence && !listEndReached && !indexUpdateDeferred) { _ASSERT(!slotWithoutIndexReached); } } } } function OUTPUTLIST() { outputList("Main List", slotsStart); } function OUTPUTREFRESHLIST() { outputList("Refresh List", refreshStart); } function outputList(header, slotFirst) { _TRACE("-- " + header + " --"); for (var slot = slotFirst; slot; slot = slot.next) { var line = (slot.firstInSequence ? "[" : " "); if (slot.index !== undefined && slot !== slotsStart && slot !== refreshStart) { line += slot.index + ": "; } if (slot === slotsStart || slot === refreshStart) { line += "{"; } else if (slot === slotListEnd || slot === refreshEnd) { line += "}"; } else if (slot === slotsEnd) { line += "-"; } else { line += (slot.key ? '"' + slot.key + '"' : "?"); } if (slot.bindingMap) { line += " ("; var first = true; for (var listBindingID in slot.bindingMap) { if (first) { first = false; } else { line += ", "; } line += listBindingID; } line += ")"; } if (slot.itemNew) { line += " itemNew"; } if (slot.item) { line += " item"; } if (slot.fetchListeners) { line += " fetching"; } if (slot.directFetchListeners) { line += " directFetching"; } if (slot.indexRequested) { line += " index"; } if (slot.keyRequested) { line += " key"; } if (slot.description) { line += " description=" + JSON.stringify(slot.description); } if (slotFetchInProgress(slot)) { line += " now"; } if (typeof slot.handle === "string") { line += " <" + slot.handle + ">"; } if (slot.lastInSequence) { line += "]"; } _TRACE(line); } } #DBG*/ function isNonNegativeNumber(n) { return (typeof n === "number") && n >= 0; } function isNonNegativeInteger(n) { return isNonNegativeNumber(n) && n === Math.floor(n); } function validateIndexReturned(index) { // Ensure that index is always undefined or a non-negative integer if (index === null) { index = undefined; } else if (index !== undefined && !isNonNegativeInteger(index)) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.InvalidIndexReturned", strings.invalidIndexReturned); } return index; } function validateCountReturned(count) { // Ensure that count is always undefined or a non-negative integer if (count === null) { count = undefined; } else if (count !== undefined && !isNonNegativeInteger(count) && count !== CountResult.unknown) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.InvalidCountReturned", strings.invalidCountReturned); } return count; } // Slot List function createSlot() { var handle = (nextHandle++).toString(), slotNew = { handle: handle, item: null, itemNew: null, fetchListeners: null, cursorCount: 0, bindingMap: null }; // Deliberately not initialized: // - directFetchListeners handleMap[handle] = slotNew; return slotNew; } function createPrimarySlot() { /*#DBG totalSlots++; #DBG*/ return createSlot(); } function insertSlot(slot, slotNext) { //#DBG _ASSERT(slotNext); //#DBG _ASSERT(slotNext.prev); slot.prev = slotNext.prev; slot.next = slotNext; slot.prev.next = slot; slotNext.prev = slot; } function removeSlot(slot) { //#DBG _ASSERT(slot.prev.next === slot); //#DBG _ASSERT(slot.next.prev === slot); //#DBG _ASSERT(slot !== slotsStart && slot !== slotListEnd && slot !== slotsEnd); if (slot.lastInSequence) { delete slot.lastInSequence; slot.prev.lastInSequence = true; } if (slot.firstInSequence) { delete slot.firstInSequence; slot.next.firstInSequence = true; } slot.prev.next = slot.next; slot.next.prev = slot.prev; } function sequenceStart(slot) { while (!slot.firstInSequence) { slot = slot.prev; } return slot; } function sequenceEnd(slot) { while (!slot.lastInSequence) { slot = slot.next; } return slot; } // Does a little careful surgery to the slot sequence from slotFirst to slotLast before slotNext function moveSequenceBefore(slotNext, slotFirst, slotLast) { //#DBG _ASSERT(slotFirst !== slotsStart && slotLast !== slotListEnd && slotLast !== slotsEnd); //#DBG _ASSERT(slotFirst.firstInSequence && slotLast.lastInSequence); //#DBG _ASSERT(slotNext.firstInSequence && slotNext.prev.lastInSequence); slotFirst.prev.next = slotLast.next; slotLast.next.prev = slotFirst.prev; slotFirst.prev = slotNext.prev; slotLast.next = slotNext; slotFirst.prev.next = slotFirst; slotNext.prev = slotLast; return true; } // Does a little careful surgery to the slot sequence from slotFirst to slotLast after slotPrev function moveSequenceAfter(slotPrev, slotFirst, slotLast) { //#DBG _ASSERT(slotFirst !== slotsStart && slotLast !== slotsEnd); //#DBG _ASSERT(slotFirst.firstInSequence && slotLast.lastInSequence); //#DBG _ASSERT(slotPrev.lastInSequence && slotPrev.next.firstInSequence); slotFirst.prev.next = slotLast.next; slotLast.next.prev = slotFirst.prev; slotFirst.prev = slotPrev; slotLast.next = slotPrev.next; slotPrev.next = slotFirst; slotLast.next.prev = slotLast; return true; } function mergeSequences(slotPrev) { delete slotPrev.lastInSequence; delete slotPrev.next.firstInSequence; } function splitSequence(slotPrev) { var slotNext = slotPrev.next; slotPrev.lastInSequence = true; slotNext.firstInSequence = true; if (slotNext === slotListEnd) { // Clear slotListEnd's index, as that's now unknown changeSlotIndex(slotListEnd, undefined); } } // Inserts a slot in the middle of a sequence or between sequences. If the latter, mergeWithPrev and mergeWithNext // parameters specify whether to merge the slot with the previous sequence, or next, or neither. function insertAndMergeSlot(slot, slotNext, mergeWithPrev, mergeWithNext) { insertSlot(slot, slotNext); var slotPrev = slot.prev; if (slotPrev.lastInSequence) { //#DBG _ASSERT(slotNext.firstInSequence); if (mergeWithPrev) { delete slotPrev.lastInSequence; } else { slot.firstInSequence = true; } if (mergeWithNext) { delete slotNext.firstInSequence; } else { slot.lastInSequence = true; } } } // Keys and Indices function setSlotKey(slot, key) { //#DBG _ASSERT(!slot.key); //#DBG _ASSERT(!keyMap[key]); slot.key = key; // Add the slot to the keyMap, so it is possible to quickly find the slot given its key keyMap[slot.key] = slot; } function setSlotIndex(slot, index, indexMapForSlot) { // Tolerate NaN, so clients can pass (undefined - 1) or (undefined + 1) if (+index === index) { //#DBG _ASSERT(indexUpdateDeferred || !indexMapForSlot[index]); slot.index = index; // Add the slot to the indexMap, so it is possible to quickly find the slot given its index indexMapForSlot[index] = slot; if (!indexUpdateDeferred) { // See if any sequences should be merged if (slot.firstInSequence && slot.prev && slot.prev.index === index - 1) { mergeSequences(slot.prev); } if (slot.lastInSequence && slot.next && slot.next.index === index + 1) { mergeSequences(slot); } } } } // Creates a new slot and adds it to the slot list before slotNext function createAndAddSlot(slotNext, indexMapForSlot) { var slotNew = (indexMapForSlot === indexMap ? createPrimarySlot() : createSlot()); insertSlot(slotNew, slotNext); return slotNew; } function createSlotSequence(slotNext, index, indexMapForSlot) { //#DBG _ASSERT(slotNext.prev.lastInSequence); //#DBG _ASSERT(slotNext.firstInSequence); var slotNew = createAndAddSlot(slotNext, indexMapForSlot); slotNew.firstInSequence = true; slotNew.lastInSequence = true; setSlotIndex(slotNew, index, indexMapForSlot); return slotNew; } function createPrimarySlotSequence(slotNext, index) { return createSlotSequence(slotNext, index, indexMap); } function addSlotBefore(slotNext, indexMapForSlot) { //#DBG _ASSERT(slotNext.firstInSequence); //#DBG _ASSERT(slotNext.prev.lastInSequence); var slotNew = createAndAddSlot(slotNext, indexMapForSlot); delete slotNext.firstInSequence; // See if we've bumped into the previous sequence if (slotNew.prev.index === slotNew.index - 1) { delete slotNew.prev.lastInSequence; } else { slotNew.firstInSequence = true; } setSlotIndex(slotNew, slotNext.index - 1, indexMapForSlot); return slotNew; } function addSlotAfter(slotPrev, indexMapForSlot) { //#DBG _ASSERT(slotPrev !== slotListEnd); //#DBG _ASSERT(slotPrev.lastInSequence); //#DBG _ASSERT(slotPrev.next.firstInSequence); var slotNew = createAndAddSlot(slotPrev.next, indexMapForSlot); delete slotPrev.lastInSequence; // See if we've bumped into the next sequence if (slotNew.next.index === slotNew.index + 1) { delete slotNew.next.firstInSequence; } else { slotNew.lastInSequence = true; } setSlotIndex(slotNew, slotPrev.index + 1, indexMapForSlot); return slotNew; } function reinsertSlot(slot, slotNext, mergeWithPrev, mergeWithNext) { insertAndMergeSlot(slot, slotNext, mergeWithPrev, mergeWithNext); //#DBG _ASSERT(!keyMap[slot.key]); keyMap[slot.key] = slot; var index = slot.index; if (slot.index !== undefined) { indexMap[slot.index] = slot; } } function removeSlotPermanently(slot) { /*#DBG _ASSERT(totalSlots > 0); totalSlots--; #DBG*/ removeSlot(slot); if (slot.key) { delete keyMap[slot.key]; } if (slot.index !== undefined && indexMap[slot.index] === slot) { delete indexMap[slot.index]; } var bindingMap = slot.bindingMap; for (var listBindingID in bindingMap) { var handle = bindingMap[listBindingID].handle; if (handle && handleMap[handle] === slot) { delete handleMap[handle]; } } // Invalidating the slot's handle marks it as deleted if (handleMap[slot.handle] === slot) { delete handleMap[slot.handle]; } } function slotPermanentlyRemoved(slot) { return !handleMap[slot.handle]; } function successorFromIndex(index, indexMapForSlot, listStart, listEnd, skipPreviousIndex) { //#DBG _ASSERT(index !== undefined); // Try the previous index var slotNext = (skipPreviousIndex ? null : indexMapForSlot[index - 1]); if (slotNext && (slotNext.next !== listEnd || listEnd.firstInSequence)) { // We want the successor slotNext = slotNext.next; } else { // Try the next index slotNext = indexMapForSlot[index + 1]; if (!slotNext) { // Resort to a linear search slotNext = listStart.next; var lastSequenceStart; while (true) { //#DBG _ASSERT(slotNext); //#DBG _ASSERT(slotNext.index !== index); if (slotNext.firstInSequence) { lastSequenceStart = slotNext; } if (!(index >= slotNext.index) || slotNext === listEnd) { break; } slotNext = slotNext.next; } if (slotNext === listEnd && !listEnd.firstInSequence) { // Return the last insertion point between sequences, or undefined if none slotNext = (lastSequenceStart && lastSequenceStart.index === undefined ? lastSequenceStart : undefined); } } } return slotNext; } // Slot Items function isPlaceholder(slot) { //#DBG _ASSERT(slot !== slotsStart && slot !== slotsEnd); return !slot.item && !slot.itemNew && slot !== slotListEnd; } function defineHandleProperty(item, handle) { Object.defineProperty(item, "handle", { value: handle, writable: false, enumerable: false, configurable: true }); } function defineCommonItemProperties(item, slot, handle) { defineHandleProperty(item, handle); Object.defineProperty(item, "index", { get: function () { while (slot.slotMergedWith) { slot = slot.slotMergedWith; } return slot.index; }, enumerable: false, configurable: true }); } function validateData(data) { if (data === undefined) { return data; } else { // Convert the data object to JSON to enforce the constraints we want. For example, we don't want // functions, arrays with extra properties, DOM objects, cyclic or acyclic graphs, or undefined values. var dataValidated = JSON.stringify(data); if (dataValidated === undefined) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.ObjectIsNotValidJson", strings.objectIsNotValidJson); } return dataValidated; } } function itemSignature(item) { return ( listDataAdapter.itemSignature ? listDataAdapter.itemSignature(item.data) : validateData(item.data) ); } function prepareSlotItem(slot) { var item = slot.itemNew; slot.itemNew = null; if (item) { item = Object.create(item); defineCommonItemProperties(item, slot, slot.handle); if (!listDataAdapter.compareByIdentity) { // Store the item signature or a stringified copy of the data for comparison later slot.signature = itemSignature(item); } } slot.item = item; delete slot.indexRequested; delete slot.keyRequested; } // Slot Caching function slotRetained(slot) { return slot.bindingMap || slot.cursorCount > 0; } function slotRequested(slot) { return slotRetained(slot) || slot.fetchListeners || slot.directFetchListeners; } function slotLive(slot) { return slotRequested(slot) || (!slot.firstInSequence && slotRetained(slot.prev)) || (!slot.lastInSequence && slotRetained(slot.next)) || (!itemsFromIndex && ( (!slot.firstInSequence && slot.prev !== slotsStart && !(slot.prev.item || slot.prev.itemNew)) | (!slot.lastInSequence && slot.next !== slotListEnd && !(slot.next.item || slot.next.itemNew)) )); } function deleteUnnecessarySlot(slot) { splitSequence(slot); removeSlotPermanently(slot); } function reduceReleasedSlotCount() { // Must not release slots while edits are queued, as undo queue might refer to them if (!editsQueued) { // If lastSlotReleased is no longer valid, use the end of the list instead if (!lastSlotReleased || slotPermanentlyRemoved(lastSlotReleased)) { lastSlotReleased = slotListEnd.prev; } // Now use the simple heuristic of walking outwards in both directions from lastSlotReleased until the // desired cache size is reached, then removing everything else. var slotPrev = lastSlotReleased.prev, slotNext = lastSlotReleased.next, releasedSlotsFound = 0; var considerDeletingSlot = function (slotToDelete) { if (slotToDelete !== slotListEnd && !slotLive(slotToDelete)) { if (releasedSlotsFound <= cacheSize) { releasedSlotsFound++; } else { deleteUnnecessarySlot(slotToDelete); } } } while (slotPrev || slotNext) { if (slotPrev) { var slotPrevToDelete = slotPrev; slotPrev = slotPrevToDelete.prev; if (slotPrevToDelete !== slotsStart) { considerDeletingSlot(slotPrevToDelete); } } if (slotNext) { var slotNextToDelete = slotNext; slotNext = slotNextToDelete.next; if (slotNextToDelete !== slotsEnd) { considerDeletingSlot(slotNextToDelete); } } } // Reset the count to zero, so this method is only called periodically releasedSlots = 0; } } function releaseSlotIfUnrequested(slot) { if (!slotRequested(slot)) { if (UI._PerfMeasurement_leakSlots) { return; } releasedSlots++; // Must not release slots while edits are queued, as undo queue might refer to them. If a refresh is in // progress, retain all slots, just in case the user re-requests some of them before the refresh completes. if (!editsQueued && !refreshInProgress) { // Track which slot was released most recently lastSlotReleased = slot; // See if the number of released slots has exceeded the cache size. In practice there will be more // live slots than retained slots, so this is just a heuristic to periodically shrink the cache. if (releasedSlots > cacheSize && !reduceReleasedSlotCountPosted) { reduceReleasedSlotCountPosted = true; Scheduler.schedule(function () { reduceReleasedSlotCountPosted = false; reduceReleasedSlotCount(); }, Scheduler.Priority.idle, null, "WinJS.UI.VirtualizedDataSource.releaseSlotIfUnrequested"); } } } } // Notifications function forEachBindingRecord(callback) { for (var listBindingID in bindingMap) { callback(bindingMap[listBindingID]); } } function forEachBindingRecordOfSlot(slot, callback) { for (var listBindingID in slot.bindingMap) { callback(slot.bindingMap[listBindingID].bindingRecord, listBindingID); } } function handlerToNotify(bindingRecord) { //#DBG _ASSERT(bindingRecord.notificationHandler); if (!bindingRecord.notificationsSent) { bindingRecord.notificationsSent = true; if (bindingRecord.notificationHandler.beginNotifications) { bindingRecord.notificationHandler.beginNotifications(); } } return bindingRecord.notificationHandler; } function finishNotifications() { if (!editsInProgress && !dataNotificationsInProgress) { forEachBindingRecord(function (bindingRecord) { if (bindingRecord.notificationsSent) { //#DBG _ASSERT(bindingRecord.notificationHandler); bindingRecord.notificationsSent = false; if (bindingRecord.notificationHandler.endNotifications) { bindingRecord.notificationHandler.endNotifications(); } } }); } } function handleForBinding(slot, listBindingID) { var bindingMap = slot.bindingMap; if (bindingMap) { var slotBinding = bindingMap[listBindingID]; if (slotBinding) { var handle = slotBinding.handle; if (handle) { return handle; } } } return slot.handle; } function itemForBinding(item, handle) { if (item && item.handle !== handle) { item = Object.create(item); defineHandleProperty(item, handle); } return item; } function changeCount(count) { var oldCount = knownCount; knownCount = count; forEachBindingRecord(function (bindingRecord) { if (bindingRecord.notificationHandler && bindingRecord.notificationHandler.countChanged) { handlerToNotify(bindingRecord).countChanged(knownCount, oldCount); } }); } function sendIndexChangedNotifications(slot, indexOld) { forEachBindingRecordOfSlot(slot, function (bindingRecord, listBindingID) { //#DBG _ASSERT(bindingRecord.notificationHandler); if (bindingRecord.notificationHandler.indexChanged) { handlerToNotify(bindingRecord).indexChanged(handleForBinding(slot, listBindingID), slot.index, indexOld); } }); } function changeSlotIndex(slot, index) { //#DBG _ASSERT(indexUpdateDeferred || ((typeof slot.index !== "number" || indexMap[slot.index] === slot) && !indexMap[index])); var indexOld = slot.index; if (indexOld !== undefined && indexMap[indexOld] === slot) { // Remove the slot's old index from the indexMap delete indexMap[indexOld]; } // Tolerate NaN, so clients can pass (undefined - 1) or (undefined + 1) if (+index === index) { setSlotIndex(slot, index, indexMap); } else if (+indexOld === indexOld) { //#DBG _ASSERT(!slot.indexRequested); delete slot.index; } else { // If neither the new index or the old index is defined then there was no index changed. return; } sendIndexChangedNotifications(slot, indexOld); } function insertionNotificationRecipients(slot, slotPrev, slotNext, mergeWithPrev, mergeWithNext) { var bindingMapRecipients = {}; // Start with the intersection of the bindings for the two adjacent slots if ((mergeWithPrev || !slotPrev.lastInSequence) && (mergeWithNext || !slotNext.firstInSequence)) { if (slotPrev === slotsStart) { if (slotNext === slotListEnd) { // Special case: if the list was empty, broadcast the insertion to all ListBindings with // notification handlers. for (var listBindingID in bindingMap) { bindingMapRecipients[listBindingID] = bindingMap[listBindingID]; } } else { // Include every binding on the next slot for (var listBindingID in slotNext.bindingMap) { bindingMapRecipients[listBindingID] = bindingMap[listBindingID]; } } } else if (slotNext === slotListEnd || slotNext.bindingMap) { for (var listBindingID in slotPrev.bindingMap) { if (slotNext === slotListEnd || slotNext.bindingMap[listBindingID]) { bindingMapRecipients[listBindingID] = bindingMap[listBindingID]; } } } } // Use the union of that result with the bindings for the slot being inserted for (var listBindingID in slot.bindingMap) { bindingMapRecipients[listBindingID] = bindingMap[listBindingID]; } return bindingMapRecipients; } function sendInsertedNotification(slot) { var slotPrev = slot.prev, slotNext = slot.next, bindingMapRecipients = insertionNotificationRecipients(slot, slotPrev, slotNext), listBindingID; for (listBindingID in bindingMapRecipients) { var bindingRecord = bindingMapRecipients[listBindingID]; if (bindingRecord.notificationHandler) { handlerToNotify(bindingRecord).inserted(bindingRecord.itemPromiseFromKnownSlot(slot), slotPrev.lastInSequence || slotPrev === slotsStart ? null : handleForBinding(slotPrev, listBindingID), slotNext.firstInSequence || slotNext === slotListEnd ? null : handleForBinding(slotNext, listBindingID) ); } } } function changeSlot(slot) { var itemOld = slot.item; prepareSlotItem(slot); forEachBindingRecordOfSlot(slot, function (bindingRecord, listBindingID) { //#DBG _ASSERT(bindingRecord.notificationHandler); var handle = handleForBinding(slot, listBindingID); handlerToNotify(bindingRecord).changed(itemForBinding(slot.item, handle), itemForBinding(itemOld, handle)); }); } function moveSlot(slot, slotMoveBefore, mergeWithPrev, mergeWithNext, skipNotifications) { var slotMoveAfter = slotMoveBefore.prev, listBindingID; // If the slot is being moved before or after itself, adjust slotMoveAfter or slotMoveBefore accordingly. If // nothing is going to change in the slot list, don't send a notification. if (slotMoveBefore === slot) { if (!slot.firstInSequence || !mergeWithPrev) { return; } slotMoveBefore = slot.next; } else if (slotMoveAfter === slot) { if (!slot.lastInSequence || !mergeWithNext) { return; } slotMoveAfter = slot.prev; } if (!skipNotifications) { // Determine which bindings to notify var bindingMapRecipients = insertionNotificationRecipients(slot, slotMoveAfter, slotMoveBefore, mergeWithPrev, mergeWithNext); // Send the notification before the move for (listBindingID in bindingMapRecipients) { var bindingRecord = bindingMapRecipients[listBindingID]; //#DBG _ASSERT(bindingRecord.notificationHandler); handlerToNotify(bindingRecord).moved(bindingRecord.itemPromiseFromKnownSlot(slot), ((slotMoveAfter.lastInSequence || slotMoveAfter === slot.prev) && !mergeWithPrev) || slotMoveAfter === slotsStart ? null : handleForBinding(slotMoveAfter, listBindingID), ((slotMoveBefore.firstInSequence || slotMoveBefore === slot.next) && !mergeWithNext) || slotMoveBefore === slotListEnd ? null : handleForBinding(slotMoveBefore, listBindingID) ); } // If a ListBinding cursor is at the slot that's moving, adjust the cursor forEachBindingRecord(function (bindingRecord) { bindingRecord.adjustCurrentSlot(slot); }); } removeSlot(slot); insertAndMergeSlot(slot, slotMoveBefore, mergeWithPrev, mergeWithNext); } function deleteSlot(slot, mirage) { //#DBG _ASSERT((!slot.fetchListeners && !slot.directFetchListeners) || !slot.item); completeFetchPromises(slot, true); forEachBindingRecordOfSlot(slot, function (bindingRecord, listBindingID) { //#DBG _ASSERT(bindingRecord.notificationHandler); handlerToNotify(bindingRecord).removed(handleForBinding(slot, listBindingID), mirage); }); // If a ListBinding cursor is at the slot that's being removed, adjust the cursor forEachBindingRecord(function (bindingRecord) { bindingRecord.adjustCurrentSlot(slot); }); removeSlotPermanently(slot); } function deleteMirageSequence(slot) { // Remove the slots in order while (!slot.firstInSequence) { slot = slot.prev; } //#DBG _ASSERT(slot !== slotsStart); var last; do { last = slot.lastInSequence; var slotNext = slot.next; deleteSlot(slot, true); slot = slotNext; } while (!last); } // Deferred Index Updates // Returns the index of the slot taking into account any outstanding index updates function adjustedIndex(slot) { var undefinedIndex; if (!slot) { return undefinedIndex; } var delta = 0; while (!slot.firstInSequence) { //#DBG _ASSERT(typeof slot.indexNew !== "number"); delta++; slot = slot.prev; } return ( typeof slot.indexNew === "number" ? slot.indexNew + delta : typeof slot.index === "number" ? slot.index + delta : undefinedIndex ); } // Updates the new index of the first slot in each sequence after the given slot function updateNewIndicesAfterSlot(slot, indexDelta) { // Adjust all the indexNews after this slot for (slot = slot.next; slot; slot = slot.next) { if (slot.firstInSequence) { var indexNew = (slot.indexNew !== undefined ? slot.indexNew : slot.index); if (indexNew !== undefined) { slot.indexNew = indexNew + indexDelta; } } } // Adjust the overall count countDelta += indexDelta; indexUpdateDeferred = true; // Increment currentRefreshID so any outstanding fetches don't cause trouble. If a refresh is in progress, // restart it (which will also increment currentRefreshID). if (refreshInProgress) { beginRefresh(); } else { currentRefreshID++; } } // Updates the new index of the given slot if necessary, and all subsequent new indices function updateNewIndices(slot, indexDelta) { //#DBG _ASSERT(indexDelta !== 0); // If this slot is at the start of a sequence, transfer the indexNew if (slot.firstInSequence) { var indexNew; if (indexDelta < 0) { // The given slot is about to be removed indexNew = slot.indexNew; if (indexNew !== undefined) { delete slot.indexNew; } else { indexNew = slot.index; } if (!slot.lastInSequence) { // Update the next slot now slot = slot.next; if (indexNew !== undefined) { slot.indexNew = indexNew; } } } else { // The given slot was just inserted if (!slot.lastInSequence) { var slotNext = slot.next; indexNew = slotNext.indexNew; if (indexNew !== undefined) { delete slotNext.indexNew; } else { indexNew = slotNext.index; } if (indexNew !== undefined) { slot.indexNew = indexNew; } } } } updateNewIndicesAfterSlot(slot, indexDelta); } // Updates the new index of the first slot in each sequence after the given new index function updateNewIndicesFromIndex(index, indexDelta) { //#DBG _ASSERT(indexDelta !== 0); for (var slot = slotsStart; slot !== slotListEnd; slot = slot.next) { var indexNew = slot.indexNew; if (indexNew !== undefined && index <= indexNew) { updateNewIndicesAfterSlot(slot, indexDelta); break; } } } // Adjust the indices of all slots to be consistent with any indexNew properties, and strip off the indexNews function updateIndices() { var slot, slotFirstInSequence, indexNew; for (slot = slotsStart; ; slot = slot.next) { if (slot.firstInSequence) { slotFirstInSequence = slot; if (slot.indexNew !== undefined) { indexNew = slot.indexNew; delete slot.indexNew; if (isNaN(indexNew)) { break; } } else { indexNew = slot.index; } // See if this sequence should be merged with the previous one if (slot !== slotsStart && slot.prev.index === indexNew - 1) { mergeSequences(slot.prev); } } if (slot.lastInSequence) { var index = indexNew; for (var slotUpdate = slotFirstInSequence; slotUpdate !== slot.next; slotUpdate = slotUpdate.next) { //#DBG _ASSERT(index !== slotUpdate.index || +index !== index || indexMap[index] === slotUpdate); if (index !== slotUpdate.index) { changeSlotIndex(slotUpdate, index); } if (+index === index) { index++; } } } if (slot === slotListEnd) { break; } } // Clear any indices on slots that were moved adjacent to slots without indices for (; slot !== slotsEnd; slot = slot.next) { if (slot.index !== undefined && slot !== slotListEnd) { changeSlotIndex(slot, undefined); } } indexUpdateDeferred = false; if (countDelta && +knownCount === knownCount) { if (getCountPromise) { getCountPromise.reset(); } else { changeCount(knownCount + countDelta); } countDelta = 0; } } // Fetch Promises function createFetchPromise(slot, listenersProperty, listenerID, listBindingID, onComplete) { if (slot.item) { return new Promise(function (complete) { if (onComplete) { onComplete(complete, slot.item); } else { complete(slot.item); } }); } else { var listener = { listBindingID: listBindingID, retained: false }; if (!slot[listenersProperty]) { slot[listenersProperty] = {}; } slot[listenersProperty][listenerID] = listener; listener.promise = new Promise(function (complete, error) { listener.complete = (onComplete ? function (item) { onComplete(complete, item); } : complete); listener.error = error; }, function () { // By now the slot might have been merged with another while (slot.slotMergedWith) { slot = slot.slotMergedWith; } var fetchListeners = slot[listenersProperty]; if (fetchListeners) { delete fetchListeners[listenerID]; // See if there are any other listeners for (var listenerID2 in fetchListeners) { return; } delete slot[listenersProperty]; } releaseSlotIfUnrequested(slot); }); return listener.promise; } } function completePromises(item, listeners) { for (var listenerID in listeners) { listeners[listenerID].complete(item); } } function completeFetchPromises(slot, completeSynchronously) { var fetchListeners = slot.fetchListeners, directFetchListeners = slot.directFetchListeners; if (fetchListeners || directFetchListeners) { prepareSlotItem(slot); // By default, complete asynchronously to minimize reentrancy var item = slot.item; var completeOrQueuePromises = function (listeners) { if (completeSynchronously) { completePromises(item, listeners); } else { fetchCompleteCallbacks.push(function () { completePromises(item, listeners); }); } } if (directFetchListeners) { slot.directFetchListeners = null; completeOrQueuePromises(directFetchListeners); } if (fetchListeners) { slot.fetchListeners = null; completeOrQueuePromises(fetchListeners); } releaseSlotIfUnrequested(slot); } } function callFetchCompleteCallbacks() { var callbacks = fetchCompleteCallbacks; // Clear fetchCompleteCallbacks first to avoid reentrancy problems fetchCompleteCallbacks = []; for (var i = 0, len = callbacks.length; i < len; i++) { callbacks[i](); } } function returnDirectFetchError(slot, error) { var directFetchListeners = slot.directFetchListeners; if (directFetchListeners) { slot.directFetchListeners = null; for (var listenerID in directFetchListeners) { directFetchListeners[listenerID].error(error); } releaseSlotIfUnrequested(slot); } } // Item Requests function requestSlot(slot) { // Ensure that there's a slot on either side of each requested item if (slot.firstInSequence) { //#DBG _ASSERT(slot.index - 1 !== slot.prev.index); addSlotBefore(slot, indexMap); } if (slot.lastInSequence) { //#DBG _ASSERT(slot.index + 1 !== slot.next.index); addSlotAfter(slot, indexMap); } // If the item has already been fetched, prepare it now to be returned to the client if (slot.itemNew) { prepareSlotItem(slot); } // Start a new fetch if necessary postFetch(); return slot; } function requestSlotBefore(slotNext) { // First, see if the previous slot already exists if (!slotNext.firstInSequence) { var slotPrev = slotNext.prev; // Next, see if the item is known to not exist return (slotPrev === slotsStart ? null : requestSlot(slotPrev)); } return requestSlot(addSlotBefore(slotNext, indexMap)); } function requestSlotAfter(slotPrev) { // First, see if the next slot already exists if (!slotPrev.lastInSequence) { var slotNext = slotPrev.next; // Next, see if the item is known to not exist return (slotNext === slotListEnd ? null : requestSlot(slotNext)); } return requestSlot(addSlotAfter(slotPrev, indexMap)); } function itemDirectlyFromSlot(slot) { // Return a complete promise for a non-existent slot return ( slot ? createFetchPromise(slot, "directFetchListeners", (nextListenerID++).toString()) : Promise.wrap(null) ); } function validateKey(key) { if (typeof key !== "string" || !key) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.KeyIsInvalid", strings.keyIsInvalid); } } function createSlotForKey(key) { var slot = createPrimarySlotSequence(slotsEnd); setSlotKey(slot, key); slot.keyRequested = true; return slot; } function slotFromKey(key, hints) { validateKey(key); var slot = keyMap[key]; if (!slot) { slot = createSlotForKey(key); slot.hints = hints; } //#DBG _ASSERT(slot.key === key); return requestSlot(slot); } function slotFromIndex(index) { if (typeof index !== "number" || index < 0) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.IndexIsInvalid", strings.indexIsInvalid); } if (slotListEnd.index <= index) { return null; } var slot = indexMap[index]; //#DBG _ASSERT(slot !== slotListEnd); if (!slot) { var slotNext = successorFromIndex(index, indexMap, slotsStart, slotListEnd); if (!slotNext) { // The complete list has been observed, and this index isn't a part of it; a refresh may be necessary return null; } if (slotNext === slotListEnd && index >= slotListEnd) { // Clear slotListEnd's index, as that's now unknown changeSlotIndex(slotListEnd, undefined); } // Create a new slot and start a request for it if (slotNext.prev.index === index - 1) { slot = addSlotAfter(slotNext.prev, indexMap); } else if (slotNext.index === index + 1) { slot = addSlotBefore(slotNext, indexMap); } else { slot = createPrimarySlotSequence(slotNext, index); } } //#DBG _ASSERT(slot.index === index); if (!slot.item) { slot.indexRequested = true; } return requestSlot(slot); } function slotFromDescription(description) { // Create a new slot and start a request for it var slot = createPrimarySlotSequence(slotsEnd); slot.description = description; return requestSlot(slot); } // Status var that = this; function setStatus(statusNew) { statusPending = statusNew; if (status !== statusPending) { var dispatch = function () { statusChangePosted = false; if (status !== statusPending) { status = statusPending; that.dispatchEvent(statusChangedEvent, status); } }; if (statusPending === WinJS.UI.DataSourceStatus.failure) { dispatch(); } else if (!statusChangePosted) { statusChangePosted = true; // Delay the event to filter out rapid changes setTimeout(dispatch, 40); } } } // Slot Fetching function slotFetchInProgress(slot) { var fetchID = slot.fetchID; return fetchID && fetchesInProgress[fetchID]; } function setFetchID(slot, fetchID) { slot.fetchID = fetchID; } function newFetchID() { var fetchID = nextFetchID; nextFetchID++; fetchesInProgress[fetchID] = true; return fetchID; } function setFetchIDs(slot, countBefore, countAfter) { var fetchID = newFetchID(); setFetchID(slot, fetchID); var slotBefore = slot; while (!slotBefore.firstInSequence && countBefore > 0) { slotBefore = slotBefore.prev; countBefore--; setFetchID(slotBefore, fetchID); } var slotAfter = slot; while (!slotAfter.lastInSequence && countAfter > 0) { slotAfter = slotAfter.next; countAfter--; setFetchID(slotAfter, fetchID); } return fetchID; } // Adds markers on behalf of the data adapter if their presence can be deduced function addMarkers(fetchResult) { var items = fetchResult.items, offset = fetchResult.offset, totalCount = fetchResult.totalCount, absoluteIndex = fetchResult.absoluteIndex, atStart = fetchResult.atStart, atEnd = fetchResult.atEnd; if (isNonNegativeNumber(absoluteIndex)) { if (isNonNegativeNumber(totalCount)) { var itemsLength = items.length; if (absoluteIndex - offset + itemsLength === totalCount) { atEnd = true; } } if (offset === absoluteIndex) { atStart = true; } } if (atStart) { items.unshift(startMarker); fetchResult.offset++; } if (atEnd) { items.push(endMarker); } } function resultsValid(slot, refreshID, fetchID) { // This fetch has completed, whatever it has returned //#DBG _ASSERT(!fetchID || fetchesInProgress[fetchID]); delete fetchesInProgress[fetchID]; if (refreshID !== currentRefreshID || slotPermanentlyRemoved(slot)) { // This information is out of date, or the slot has since been discarded postFetch(); return false; } return true; } function fetchItems(slot, fetchID, promiseItems, index) { var refreshID = currentRefreshID; promiseItems.then(function (fetchResult) { if (fetchResult.items && fetchResult.items.length) { var perfID = "itemsFetched id=" + fetchID + " count=" + fetchResult.items.length; profilerMarkStart(perfID); if (resultsValid(slot, refreshID, fetchID)) { if (+index === index) { fetchResult.absoluteIndex = index; } addMarkers(fetchResult); processResults(slot, fetchResult.items, fetchResult.offset, fetchResult.totalCount, fetchResult.absoluteIndex); } profilerMarkEnd(perfID); } else { return Promise.wrapError(new WinJS.ErrorFromName(FetchError.doesNotExist)); } }).then(null, function (error) { if (resultsValid(slot, refreshID, fetchID)) { processErrorResult(slot, error); } }); } function fetchItemsForIndex(indexRequested, slot, fetchID, promiseItems) { var refreshID = currentRefreshID; promiseItems.then(function (fetchResult) { if (fetchResult.items && fetchResult.items.length) { var perfID = "itemsFetched id=" + fetchID + " count=" + fetchResult.items.length; profilerMarkStart(perfID); if (resultsValid(slot, refreshID, fetchID)) { //#DBG _ASSERT(+indexRequested === indexRequested); fetchResult.absoluteIndex = indexRequested; addMarkers(fetchResult); processResultsForIndex(indexRequested, slot, fetchResult.items, fetchResult.offset, fetchResult.totalCount, fetchResult.absoluteIndex); } profilerMarkEnd(perfID); } else { return Promise.wrapError(new WinJS.ErrorFromName(FetchError.doesNotExist)); } }).then(null, function (error) { if (resultsValid(slot, refreshID, fetchID)) { processErrorResultForIndex(indexRequested, slot, refreshID, name); } }); } function fetchItemsFromStart(slot, count) { //#DBG _ASSERT(!refreshInProgress); var fetchID = setFetchIDs(slot, 0, count - 1); if (itemsFromStart) { fetchItems(slot, fetchID, itemsFromStart(fetchID, count), 0); } else { fetchItems(slot, fetchID, itemsFromIndex(fetchID, 0, 0, count - 1), 0); } } function fetchItemsFromEnd(slot, count) { //#DBG _ASSERT(!refreshInProgress); var fetchID = setFetchIDs(slot, count - 1, 0); fetchItems(slot, fetchID, itemsFromEnd(fetchID, count)); } function fetchItemsFromKey(slot, countBefore, countAfter) { //#DBG _ASSERT(!refreshInProgress); //#DBG _ASSERT(itemsFromKey); //#DBG _ASSERT(slot.key); var fetchID = setFetchIDs(slot, countBefore, countAfter); fetchItems(slot, fetchID, itemsFromKey(fetchID, slot.key, countBefore, countAfter, slot.hints)); } function fetchItemsFromIndex(slot, countBefore, countAfter) { //#DBG _ASSERT(!refreshInProgress); //#DBG _ASSERT(slot !== slotsStart); var index = slot.index; // Don't ask for items with negative indices if (countBefore > index) { countBefore = index; } if (itemsFromIndex) { var fetchID = setFetchIDs(slot, countBefore, countAfter); fetchItems(slot, fetchID, itemsFromIndex(fetchID, index, countBefore, countAfter), index); } else { // If the slot key is known, we just need to request the surrounding items if (slot.key) { fetchItemsFromKey(slot, countBefore, countAfter); } else { // Search for the slot with the closest index that has a known key (using the start of the list as a // last resort). var slotClosest = slotsStart, closestDelta = index + 1, slotSearch, delta; // First search backwards for (slotSearch = slot.prev; slotSearch !== slotsStart; slotSearch = slotSearch.prev) { if (slotSearch.index !== undefined && slotSearch.key) { //#DBG _ASSERT(index > slotSearch.index); delta = index - slotSearch.index; if (closestDelta > delta) { closestDelta = delta; slotClosest = slotSearch; } break; } } // Then search forwards for (slotSearch = slot.next; slotSearch !== slotListEnd; slotSearch = slotSearch.next) { if (slotSearch.index !== undefined && slotSearch.key) { //#DBG _ASSERT(slotSearch.index > index); delta = slotSearch.index - index; if (closestDelta > delta) { closestDelta = delta; slotClosest = slotSearch; } break; } } if (slotClosest === slotsStart) { var fetchID = setFetchIDs(slot, 0, index + 1); fetchItemsForIndex(0, slot, fetchID, itemsFromStart(fetchID, index + 1)); } else { var fetchBefore = Math.max(slotClosest.index - index, 0); var fetchAfter = Math.max(index - slotClosest.index, 0); var fetchID = setFetchIDs(slotClosest, fetchBefore, fetchAfter); fetchItemsForIndex(slotClosest.index, slot, fetchID, itemsFromKey(fetchID, slotClosest.key, fetchBefore, fetchAfter, slot.hints )); } } } } function fetchItemsFromDescription(slot, countBefore, countAfter) { //#DBG _ASSERT(!refreshInProgress); var fetchID = setFetchIDs(slot, countBefore, countAfter); fetchItems(slot, fetchID, itemsFromDescription(fetchID, slot.description, countBefore, countAfter)); } function fetchItemsForAllSlots() { if (!refreshInProgress) { var slotFirstPlaceholder, placeholderCount, fetchInProgress = false, fetchesInProgress = false, slotRequestedByKey, requestedKeyOffset, slotRequestedByDescription, requestedDescriptionOffset, slotRequestedByIndex, requestedIndexOffset; for (var slot = slotsStart.next; slot !== slotsEnd;) { var slotNext = slot.next; if (slot !== slotListEnd && isPlaceholder(slot)) { fetchesInProgress = true; if (!slotFirstPlaceholder) { slotFirstPlaceholder = slot; placeholderCount = 1; } else { placeholderCount++; } if (slotFetchInProgress(slot)) { fetchInProgress = true; } if (slot.keyRequested && !slotRequestedByKey) { //#DBG _ASSERT(slot.key); slotRequestedByKey = slot; requestedKeyOffset = placeholderCount - 1; } if (slot.description !== undefined && !slotRequestedByDescription) { slotRequestedByDescription = slot; requestedDescriptionOffset = placeholderCount - 1; } if (slot.indexRequested && !slotRequestedByIndex) { //#DBG _ASSERT(typeof slot.index === "number"); slotRequestedByIndex = slot; requestedIndexOffset = placeholderCount - 1; } if (slot.lastInSequence || slotNext === slotsEnd || !isPlaceholder(slotNext)) { if (fetchInProgress) { fetchInProgress = false; } else { resultsProcessed = false; // Start a new fetch for this placeholder sequence // Prefer fetches in terms of a known item if (!slotFirstPlaceholder.firstInSequence && slotFirstPlaceholder.prev.key && itemsFromKey) { fetchItemsFromKey(slotFirstPlaceholder.prev, 0, placeholderCount); } else if (!slot.lastInSequence && slotNext.key && itemsFromKey) { fetchItemsFromKey(slotNext, placeholderCount, 0); } else if (slotFirstPlaceholder.prev === slotsStart && !slotFirstPlaceholder.firstInSequence && (itemsFromStart || itemsFromIndex)) { fetchItemsFromStart(slotFirstPlaceholder, placeholderCount); } else if (slotNext === slotListEnd && !slot.lastInSequence && itemsFromEnd) { fetchItemsFromEnd(slot, placeholderCount); } else if (slotRequestedByKey) { fetchItemsFromKey(slotRequestedByKey, requestedKeyOffset, placeholderCount - 1 - requestedKeyOffset); } else if (slotRequestedByDescription) { fetchItemsFromDescription(slotRequestedByDescription, requestedDescriptionOffset, placeholderCount - 1 - requestedDescriptionOffset); } else if (slotRequestedByIndex) { fetchItemsFromIndex(slotRequestedByIndex, requestedIndexOffset, placeholderCount - 1 - requestedIndexOffset); } else if (typeof slotFirstPlaceholder.index === "number") { fetchItemsFromIndex(slotFirstPlaceholder, placeholderCount - 1, 0); } else { // There is no way to fetch anything in this sequence //#DBG _ASSERT(slot.lastInSequence); deleteMirageSequence(slotFirstPlaceholder); } if (resultsProcessed) { // A re-entrant fetch might have altered the slots list - start again postFetch(); return; } if (refreshInProgress) { // A re-entrant fetch might also have caused a refresh return; } } slotFirstPlaceholder = slotRequestedByIndex = slotRequestedByKey = null; } } slot = slotNext; } setStatus(fetchesInProgress ? DataSourceStatus.waiting : DataSourceStatus.ready); } } function postFetch() { if (!fetchesPosted) { fetchesPosted = true; Scheduler.schedule(function () { fetchesPosted = false; fetchItemsForAllSlots(); // A mirage sequence might have been removed finishNotifications(); }, Scheduler.Priority.max, null, "WinJS.UI.ListDataSource._fetch"); } } // Fetch Result Processing function itemChanged(slot) { var itemNew = slot.itemNew; if (!itemNew) { return false; } var item = slot.item; for (var property in item) { switch (property) { case "data": // This is handled below break; default: //#DBG _ASSERT(property !== "handle"); //#DBG _ASSERT(property !== "index"); if (item[property] !== itemNew[property]) { return true; } break; } } return ( listDataAdapter.compareByIdentity ? item.data !== itemNew.data : slot.signature !== itemSignature(itemNew) ); } function changeSlotIfNecessary(slot) { if (!slotRequested(slot)) { // There's no need for any notifications, just delete the old item slot.item = null; } else if (itemChanged(slot)) { changeSlot(slot); } else { slot.itemNew = null; } } function updateSlotItem(slot) { //#DBG _ASSERT(slot.itemNew); if (slot.item) { changeSlotIfNecessary(slot); } else { //#DBG _ASSERT(slot.key); completeFetchPromises(slot); } } function updateSlot(slot, item) { //#DBG _ASSERT(item !== startMarker && item !== endMarker); if (!slot.key) { setSlotKey(slot, item.key); } slot.itemNew = item; //#DBG _ASSERT(slot.key === item.key); updateSlotItem(slot); } function sendMirageNotifications(slot, slotToDiscard, listBindingIDsToDelete) { var bindingMap = slotToDiscard.bindingMap; if (bindingMap) { for (var listBindingID in listBindingIDsToDelete) { if (bindingMap[listBindingID]) { var fetchListeners = slotToDiscard.fetchListeners; for (var listenerID in fetchListeners) { var listener = fetchListeners[listenerID]; if (listener.listBindingID === listBindingID && listener.retained) { delete fetchListeners[listenerID]; listener.complete(null); } } var bindingRecord = bindingMap[listBindingID].bindingRecord; //#DBG _ASSERT(bindingRecord.notificationHandler); handlerToNotify(bindingRecord).removed(handleForBinding(slotToDiscard, listBindingID), true, handleForBinding(slot, listBindingID)); // A re-entrant call to release from the removed handler might have cleared slotToDiscard.bindingMap if (slotToDiscard.bindingMap) { delete slotToDiscard.bindingMap[listBindingID]; } } } } } function mergeSlots(slot, slotToDiscard) { // This shouldn't be called on a slot that has a pending change notification //#DBG _ASSERT(!slot.item || !slot.itemNew); // Only one of the two slots should have a key //#DBG _ASSERT(!slot.key || !slotToDiscard.key); // If slotToDiscard is about to acquire an index, send the notifications now; in rare cases, multiple // indexChanged notifications will be sent for a given item during a refresh, but that's fine. if (slot.index !== slotToDiscard.index) { // If slotToDiscard has a defined index, that should have been transferred already //#DBG _ASSERT(refreshInProgress || slot.index !== undefined); var indexOld = slotToDiscard.index; slotToDiscard.index = slot.index; sendIndexChangedNotifications(slotToDiscard, indexOld); } slotToDiscard.slotMergedWith = slot; // Transfer the slotBindings from slotToDiscard to slot var bindingMap = slotToDiscard.bindingMap; for (var listBindingID in bindingMap) { if (!slot.bindingMap) { slot.bindingMap = {}; } //#DBG _ASSERT(!slot.bindingMap[listBindingID]); var slotBinding = bindingMap[listBindingID]; if (!slotBinding.handle) { slotBinding.handle = slotToDiscard.handle; } //#DBG _ASSERT(handleMap[slotBinding.handle] === slotToDiscard); handleMap[slotBinding.handle] = slot; slot.bindingMap[listBindingID] = slotBinding; } // Update any ListBinding cursors pointing to slotToDiscard forEachBindingRecord(function (bindingRecord) { bindingRecord.adjustCurrentSlot(slotToDiscard, slot); }); // See if the item needs to be transferred from slotToDiscard to slot var item = slotToDiscard.itemNew || slotToDiscard.item; //#DBG _ASSERT(!item || !slot.key); if (item) { item = Object.create(item); defineCommonItemProperties(item, slot, slot.handle); updateSlot(slot, item); } // Transfer the fetch listeners from slotToDiscard to slot, or complete them if item is known if (slot.item) { if (slotToDiscard.directFetchListeners) { fetchCompleteCallbacks.push(function () { completePromises(slot.item, slotToDiscard.directFetchListeners); }); } if (slotToDiscard.fetchListeners) { fetchCompleteCallbacks.push(function () { completePromises(slot.item, slotToDiscard.fetchListeners); }); } } else { var listenerID; for (listenerID in slotToDiscard.directFetchListeners) { if (!slot.directFetchListeners) { slot.directFetchListeners = {}; } slot.directFetchListeners[listenerID] = slotToDiscard.directFetchListeners[listenerID]; } for (listenerID in slotToDiscard.fetchListeners) { if (!slot.fetchListeners) { slot.fetchListeners = {}; } slot.fetchListeners[listenerID] = slotToDiscard.fetchListeners[listenerID]; } } // This might be the first time this slot's item can be prepared if (slot.itemNew) { completeFetchPromises(slot); } // Give slotToDiscard an unused handle so it appears to be permanently removed slotToDiscard.handle = (nextHandle++).toString(); splitSequence(slotToDiscard); removeSlotPermanently(slotToDiscard); } function mergeSlotsAndItem(slot, slotToDiscard, item) { if (slotToDiscard && slotToDiscard.key) { //#DBG _ASSERT(!item || slotToDiscard.key === item.key); //#DBG _ASSERT(!slotToDiscard.bindingMap); if (!item) { item = slotToDiscard.itemNew || slotToDiscard.item; } // Free up the key for the promoted slot delete slotToDiscard.key; delete keyMap[item.key]; slotToDiscard.itemNew = null; slotToDiscard.item = null; } if (item) { updateSlot(slot, item); } if (slotToDiscard) { mergeSlots(slot, slotToDiscard); } } function slotFromResult(result) { if (typeof result !== "object") { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.InvalidItemReturned", strings.invalidItemReturned); } else if (result === startMarker) { return slotsStart; } else if (result === endMarker) { return slotListEnd; } else if (!result.key) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.InvalidKeyReturned", strings.invalidKeyReturned); } else { if (WinJS.validation) { validateKey(result.key); } return keyMap[result.key]; } } function matchSlot(slot, result) { //#DBG _ASSERT(result !== startMarker && result !== endMarker); // First see if there is an existing slot that needs to be merged var slotExisting = slotFromResult(result); if (slotExisting === slot) { slotExisting = null; } if (slotExisting) { sendMirageNotifications(slot, slotExisting, slot.bindingMap); } mergeSlotsAndItem(slot, slotExisting, result); } function promoteSlot(slot, item, index, insertionPoint) { //#DBG _ASSERT(typeof slot.index !== "number"); //#DBG _ASSERT(+index === index || !indexMap[index]); if (item && slot.key && slot.key !== item.key) { // A contradiction has been found beginRefresh(); return false; } // The slot with the key "wins"; slots without bindings can be merged without any change in observable behavior var slotWithIndex = indexMap[index]; if (slotWithIndex) { if (slotWithIndex === slot) { slotWithIndex = null; } else if (slotWithIndex.key && (slot.key || (item && slotWithIndex.key !== item.key))) { // A contradiction has been found beginRefresh(); return false; } else if (!slot.key && slotWithIndex.bindingMap) { return false; } } var slotWithKey; if (item) { slotWithKey = keyMap[item.key]; if (slotWithKey === slot) { slotWithKey = null; } else if (slotWithKey && slotWithKey.bindingMap) { return false; } } if (slotWithIndex) { sendMirageNotifications(slot, slotWithIndex, slot.bindingMap); // Transfer the index to the promoted slot delete indexMap[index]; changeSlotIndex(slot, index); // See if this sequence should be merged with its neighbors if (slot.prev.index === index - 1) { mergeSequences(slot.prev); } if (slot.next.index === index + 1) { mergeSequences(slot); } insertionPoint.slotNext = slotWithIndex.slotNext; if (!item) { item = slotWithIndex.itemNew || slotWithIndex.item; if (item) { slotWithKey = keyMap[item.key]; } } } else { changeSlotIndex(slot, index); } if (slotWithKey && slotWithIndex !== slotWithKey) { sendMirageNotifications(slot, slotWithKey, slot.bindingMap); } mergeSlotsAndItem(slot, slotWithKey, item); // Do this after mergeSlotsAndItem, since its call to updateSlot might send changed notifications, and those // wouldn't make sense to clients that never saw the old item. if (slotWithIndex && slotWithIndex !== slotWithKey) { mergeSlots(slot, slotWithIndex); } //#DBG _ASSERT(!slotWithIndex || slotWithIndex.prev.next !== slotWithIndex); return true; } function mergeAdjacentSlot(slotExisting, slot, listBindingIDsToDelete) { if (slot.key && slotExisting.key && slot.key !== slotExisting.key) { // A contradiction has been found beginRefresh(); return false; } for (var listBindingID in slotExisting.bindingMap) { listBindingIDsToDelete[listBindingID] = true; } sendMirageNotifications(slotExisting, slot, listBindingIDsToDelete); mergeSlotsAndItem(slotExisting, slot); return true; } function mergeSlotsBefore(slot, slotExisting) { var listBindingIDsToDelete = {}; while (slot) { var slotPrev = (slot.firstInSequence ? null : slot.prev); if (!slotExisting.firstInSequence && slotExisting.prev === slotsStart) { deleteSlot(slot, true); } else { if (slotExisting.firstInSequence) { slotExisting = addSlotBefore(slotExisting, indexMap); } else { slotExisting = slotExisting.prev; } if (!mergeAdjacentSlot(slotExisting, slot, listBindingIDsToDelete)) { return; } } slot = slotPrev; } } function mergeSlotsAfter(slot, slotExisting) { var listBindingIDsToDelete = {}; while (slot) { var slotNext = (slot.lastInSequence ? null : slot.next); if (!slotExisting.lastInSequence && slotExisting.next === slotListEnd) { deleteSlot(slot, true); } else { if (slotExisting.lastInSequence) { slotExisting = addSlotAfter(slotExisting, indexMap); } else { slotExisting = slotExisting.next; } if (!mergeAdjacentSlot(slotExisting, slot, listBindingIDsToDelete)) { return; } } slot = slotNext; } } function mergeSequencePairs(sequencePairsToMerge) { for (var i = 0; i < sequencePairsToMerge.length; i++) { var sequencePairToMerge = sequencePairsToMerge[i]; mergeSlotsBefore(sequencePairToMerge.slotBeforeSequence, sequencePairToMerge.slotFirstInSequence); mergeSlotsAfter(sequencePairToMerge.slotAfterSequence, sequencePairToMerge.slotLastInSequence); } } // Removes any placeholders with indices that exceed the given upper bound on the count function removeMirageIndices(countMax, indexFirstKnown) { //#DBG _ASSERT(isNonNegativeInteger(countMax)); var placeholdersAtEnd = 0; function removePlaceholdersAfterSlot(slotRemoveAfter) { for (var slot2 = slotListEnd.prev; !(slot2.index < countMax) && slot2 !== slotRemoveAfter;) { var slotPrev2 = slot2.prev; if (slot2.index !== undefined) { deleteSlot(slot2, true); } slot2 = slotPrev2; } placeholdersAtEnd = 0; } for (var slot = slotListEnd.prev; !(slot.index < countMax) || placeholdersAtEnd > 0;) { //#DBG _ASSERT(!refreshInProgress); var slotPrev = slot.prev; if (slot === slotsStart) { removePlaceholdersAfterSlot(slotsStart); break; } else if (slot.key) { if (slot.index >= countMax) { beginRefresh(); return false; } else if (slot.index >= indexFirstKnown) { removePlaceholdersAfterSlot(slot); //#DBG _ASSERT(slot.index < countMax); } else { if (itemsFromKey) { fetchItemsFromKey(slot, 0, placeholdersAtEnd); } else { fetchItemsFromIndex(slot, 0, placeholdersAtEnd); } // Wait until the fetch has completed before doing anything return false; } } else if (slot.indexRequested || slot.firstInSequence) { removePlaceholdersAfterSlot(slotPrev); } else { placeholdersAtEnd++; } slot = slotPrev; } return true; } // Merges the results of a fetch into the slot list data structure, and determines if any notifications need to be // synthesized. function processResults(slot, results, offset, count, index) { var perfId = "WinJS.UI.ListDataSource.processResults"; profilerMarkStart(perfId); index = validateIndexReturned(index); count = validateCountReturned(count); // If there are edits queued, we need to wait until the slots get back in sync with the data if (editsQueued) { profilerMarkEnd(perfId); return; } if (indexUpdateDeferred) { updateIndices(); } // If the count has changed, and the end of the list has been reached, that's a contradiction if ((isNonNegativeNumber(count) || count === CountResult.unknown) && count !== knownCount && !slotListEnd.firstInSequence) { beginRefresh(); profilerMarkEnd(perfId); return; } resultsProcessed = true; /*#DBG VERIFYLIST(); #DBG*/ (function () { var i, j, resultsCount = results.length, slotExisting, slotBefore; // If an index wasn't passed in, see if the indices of these items can be determined if (typeof index !== "number") { for (i = 0; i < resultsCount; i++) { slotExisting = slotFromResult(results[i]); if (slotExisting && slotExisting.index !== undefined) { index = slotExisting.index + offset - i; break; } } } // See if these results include the end of the list if (typeof index === "number" && results[resultsCount - 1] === endMarker) { // If the count wasn't known, it is now count = index - offset + resultsCount - 1; } else if (isNonNegativeNumber(count) && index == undefined) { // If the index wasn't known, it is now index = count - (resultsCount - 1) + offset; } // If the count is known, remove any mirage placeholders at the end if (isNonNegativeNumber(count) && !removeMirageIndices(count, index - offset)) { // "Forget" the count - a subsequent fetch or refresh will update the count and list end count = undefined; } // Find any existing slots that correspond to the results, and check for contradictions var offsetMap = new Array(resultsCount); for (i = 0; i < resultsCount; i++) { var slotBestMatch = null; slotExisting = slotFromResult(results[i]); if (slotExisting) { // See if this item is currently adjacent to a different item, or has a different index if ((i > 0 && !slotExisting.firstInSequence && slotExisting.prev.key && slotExisting.prev.key !== results[i - 1].key) || (typeof index === "number" && slotExisting.index !== undefined && slotExisting.index !== index - offset + i)) { // A contradiction has been found, so we can't proceed further beginRefresh(); return; } if (slotExisting === slotsStart || slotExisting === slotListEnd || slotExisting.bindingMap) { // First choice is a slot with the given key and at least one binding (or an end of the list) slotBestMatch = slotExisting; } } if (typeof index === "number") { slotExisting = indexMap[index - offset + i]; if (slotExisting) { if (slotExisting.key && slotExisting.key !== results[i].key) { // A contradiction has been found, so we can't proceed further beginRefresh(); return; } if (!slotBestMatch && slotExisting.bindingMap) { // Second choice is a slot with the given index and at least one binding slotBestMatch = slotExisting; } } } if (i === offset) { if ((slot.key && slot.key !== results[i].key) || (typeof slot.index === "number" && typeof index === "number" && slot.index !== index)) { // A contradiction has been found, so we can't proceed further beginRefresh(); return; } if (!slotBestMatch) { // Third choice is the slot that was passed in slotBestMatch = slot; } } offsetMap[i] = slotBestMatch; } // Update items with known indices (and at least one binding) first, as they will not be merged with // anything. for (i = 0; i < resultsCount; i++) { slotExisting = offsetMap[i]; if (slotExisting && slotExisting.index !== undefined && slotExisting !== slotsStart && slotExisting !== slotListEnd) { matchSlot(slotExisting, results[i]); } } var sequencePairsToMerge = []; // Now process the sequences without indices var firstSequence = true; for (i = 0; i < resultsCount; i++) { slotExisting = offsetMap[i]; if (slotExisting && slotExisting !== slotListEnd) { var iLast = i; if (slotExisting.index === undefined) { var insertionPoint = {}; promoteSlot(slotExisting, results[i], index - offset + i, insertionPoint); // Find the extents of the sequence of slots that we can use var slotFirstInSequence = slotExisting, slotLastInSequence = slotExisting, result; for (j = i - 1; !slotFirstInSequence.firstInSequence; j--) { // Keep going until we hit the start marker or a slot that we can't use or promote (it's ok // if j leaves the results range). result = results[j]; if (result === startMarker) { break; } // Avoid assigning negative indices to slots var index2 = index - offset + j; if (index2 < 0) { break; } if (promoteSlot(slotFirstInSequence.prev, result, index2, insertionPoint)) { slotFirstInSequence = slotFirstInSequence.prev; if (j >= 0) { offsetMap[j] = slotFirstInSequence; } } else { break; } } for (j = i + 1; !slotLastInSequence.lastInSequence; j++) { // Keep going until we hit the end marker or a slot that we can't use or promote (it's ok // if j leaves the results range). // If slotListEnd is in this sequence, it should not be separated from any predecessor // slots, but they may need to be promoted. result = results[j]; if ((result === endMarker || j === count) && slotLastInSequence.next !== slotListEnd) { break; } if (slotLastInSequence.next === slotListEnd || promoteSlot(slotLastInSequence.next, result, index - offset + j, insertionPoint)) { slotLastInSequence = slotLastInSequence.next; if (j < resultsCount) { offsetMap[j] = slotLastInSequence; } iLast = j; if (slotLastInSequence === slotListEnd) { break; } } else { break; } } var slotBeforeSequence = (slotFirstInSequence.firstInSequence ? null : slotFirstInSequence.prev), slotAfterSequence = (slotLastInSequence.lastInSequence ? null : slotLastInSequence.next); if (slotBeforeSequence) { splitSequence(slotBeforeSequence); } if (slotAfterSequence) { splitSequence(slotLastInSequence); } // Move the sequence if necessary if (typeof index === "number") { if (slotLastInSequence === slotListEnd) { // Instead of moving the list end, move the sequence before out of the way if (slotBeforeSequence) { moveSequenceAfter(slotListEnd, sequenceStart(slotBeforeSequence), slotBeforeSequence); } //#DBG _ASSERT(!slotAfterSequence); } else { var slotInsertBefore = insertionPoint.slotNext; if (!slotInsertBefore) { slotInsertBefore = successorFromIndex(slotLastInSequence.index, indexMap, slotsStart, slotListEnd, true); } moveSequenceBefore(slotInsertBefore, slotFirstInSequence, slotLastInSequence); } if (slotFirstInSequence.prev.index === slotFirstInSequence.index - 1) { mergeSequences(slotFirstInSequence.prev); } if (slotLastInSequence.next.index === slotLastInSequence.index + 1) { mergeSequences(slotLastInSequence); } } else if (!firstSequence) { //#DBG _ASSERT(slotFirstInSequence === slotExisting); slotBefore = offsetMap[i - 1]; if (slotBefore) { if (slotFirstInSequence.prev !== slotBefore) { if (slotLastInSequence === slotListEnd) { // Instead of moving the list end, move the sequence before out of the way and // the predecessor sequence into place. if (slotBeforeSequence) { moveSequenceAfter(slotListEnd, sequenceStart(slotBeforeSequence), slotBeforeSequence); } moveSequenceBefore(slotFirstInSequence, sequenceStart(slotBefore), slotBefore); } else { moveSequenceAfter(slotBefore, slotFirstInSequence, slotLastInSequence); } } mergeSequences(slotBefore); } } firstSequence = false; if (refreshRequested) { return; } sequencePairsToMerge.push({ slotBeforeSequence: slotBeforeSequence, slotFirstInSequence: slotFirstInSequence, slotLastInSequence: slotLastInSequence, slotAfterSequence: slotAfterSequence }); } // See if the fetched slot needs to be merged if (i === offset && slotExisting !== slot && !slotPermanentlyRemoved(slot)) { //#DBG _ASSERT(!slot.key); slotBeforeSequence = (slot.firstInSequence ? null : slot.prev); slotAfterSequence = (slot.lastInSequence ? null : slot.next); //#DBG _ASSERT(!slotBeforeSequence || !slotBeforeSequence.key); //#DBG _ASSERT(!slotAfterSequence || !slotAfterSequence.key); sendMirageNotifications(slotExisting, slot, slotExisting.bindingMap); mergeSlots(slotExisting, slot); sequencePairsToMerge.push({ slotBeforeSequence: slotBeforeSequence, slotFirstInSequence: slotExisting, slotLastInSequence: slotExisting, slotAfterSequence: slotAfterSequence }); } // Skip past all the other items in the sequence we just processed i = iLast; } } // If the count is known, set the index of the list end (wait until now because promoteSlot can sometimes // delete it; do this before mergeSequencePairs so the list end can have slots inserted immediately before // it). if (isNonNegativeNumber(count) && slotListEnd.index !== count) { changeSlotIndex(slotListEnd, count); } // Now that all the sequences have been moved, merge any colliding slots mergeSequencePairs(sequencePairsToMerge); // Match or cache any leftover items for (i = 0; i < resultsCount; i++) { // Find the first matched item slotExisting = offsetMap[i]; if (slotExisting) { for (j = i - 1; j >= 0; j--) { var slotAfter = offsetMap[j + 1]; matchSlot(offsetMap[j] = (slotAfter.firstInSequence ? addSlotBefore(offsetMap[j + 1], indexMap) : slotAfter.prev), results[j]); } for (j = i + 1; j < resultsCount; j++) { slotBefore = offsetMap[j - 1]; slotExisting = offsetMap[j]; if (!slotExisting) { matchSlot(offsetMap[j] = (slotBefore.lastInSequence ? addSlotAfter(slotBefore, indexMap) : slotBefore.next), results[j]); } else if (slotExisting.firstInSequence) { // Adding the cached items may result in some sequences merging if (slotExisting.prev !== slotBefore) { //#DBG _ASSERT(slotExisting.index === undefined); moveSequenceAfter(slotBefore, slotExisting, sequenceEnd(slotExisting)); } mergeSequences(slotBefore); } } break; } } // The description is no longer required delete slot.description; })(); if (!refreshRequested) { // If the count changed, but that's the only thing, just send the notification if (count !== undefined && count !== knownCount) { changeCount(count); } // See if there are more requests we can now fulfill postFetch(); } finishNotifications(); /*#DBG VERIFYLIST(); #DBG*/ // Finally complete any promises for newly obtained items callFetchCompleteCallbacks(); profilerMarkEnd(perfId); } function processErrorResult(slot, error) { switch (error.name) { case FetchError.noResponse: setStatus(DataSourceStatus.failure); returnDirectFetchError(slot, error); break; case FetchError.doesNotExist: // Don't return an error, just complete with null (when the slot is deleted) if (slot.indexRequested) { //#DBG _ASSERT(isPlaceholder(slot)); //#DBG _ASSERT(slot.index !== undefined); // We now have an upper bound on the count removeMirageIndices(slot.index); } else if (slot.keyRequested || slot.description) { // This item, and any items in the same sequence, count as mirages, since they might never have // existed. deleteMirageSequence(slot); } finishNotifications(); // It's likely that the client requested this item because something has changed since the client's // latest observations of the data. Begin a refresh just in case. beginRefresh(); break; } } function processResultsForIndex(indexRequested, slot, results, offset, count, index) { index = validateIndexReturned(index); count = validateCountReturned(count); var indexFirst = indexRequested - offset; var resultsCount = results.length; if (slot.index >= indexFirst && slot.index < indexFirst + resultsCount) { // The item is in this batch of results - process them all processResults(slot, results, slot.index - indexFirst, count, slot.index); } else if ((offset === resultsCount - 1 && indexRequested < slot.index) || (isNonNegativeNumber(count) && count <= slot.index)) { // The requested index does not exist processErrorResult(slot, new WinJS.ErrorFromName(UI.FetchError.doesNotExist)); } else { // We didn't get all the results we requested - pick up where they left off if (slot.index < indexFirst) { var fetchID = setFetchIDs(slot, 0, indexFirst - slot.index); fetchItemsForIndex(indexFirst, slot, fetchID, itemsFromKey( fetchID, results[0].key, indexFirst - slot.index, 0 )); } else { var indexLast = indexFirst + resultsCount - 1; //#DBG _ASSERT(slot.index > indexLast); var fetchID = setFetchIDs(slot, slot.index - indexLast, 0); fetchItemsForIndex(indexLast, slot, fetchID, itemsFromKey( fetchID, results[resultsCount - 1].key, 0, slot.index - indexLast )); } } } function processErrorResultForIndex(indexRequested, slot, error) { // If the request was for an index other than the initial one, and the result was doesNotExist, this doesn't switch (error.name) { case FetchError.doesNotExist: if (indexRequested === slotsStart.index) { // The request was for the start of the list, so the item must not exist, and we now have an upper // bound of zero for the count. removeMirageIndices(0); processErrorResult(slot, error); // No need to check return value of removeMirageIndices, since processErrorResult is going to start // a refresh anyway. //#DBG _ASSERT(refreshRequested); } else { // Something has changed, but this index might still exist, so request a refresh beginRefresh(); } break; default: processErrorResult(slot, error); break; } } // Refresh function identifyRefreshCycle() { // find refresh cycles, find the first beginRefresh in the refreshHistory and see whether it // matches the next beginRefresh, if so then move the data source into an error state and stop // refreshing. var start = 0; for (; start < refreshHistory.length; start++) { if (refreshHistory[start].kind === "beginRefresh") { break; } } var end = start; for (; end < refreshHistory.length; end++) { if (refreshHistory[end].kind === "beginRefresh") { break; } } if (end > start && (end + (end - start) < refreshHistory.length)) { var match = true; var length = end - start; for (var i = 0; i < length; i++) { if (refreshHistory[start + i].kind !== refreshHistory[end + i].kind) { match = false; break; } } if (match) { if (WinJS.log) { WinJS.log(strings.refreshCycleIdentified, "winjs vds", "error"); for (var i = start; i < end; i++) { WinJS.log("" + (i - start) + ": " + JSON.stringify(refreshHistory[i]), "winjs vds", "error"); } } } return match; } } function resetRefreshState() { if (++beginRefreshCount > MAX_BEGINREFRESH_COUNT) { if (identifyRefreshCycle()) { setState(DataSourceStatus.failure); return; } } refreshHistory[++refreshHistoryPos % refreshHistory.length] = { kind: "beginRefresh" }; // Give the start sentinel an index so we can always use predecessor + 1 refreshStart = { firstInSequence: true, lastInSequence: true, index: -1 }; refreshEnd = { firstInSequence: true, lastInSequence: true }; refreshStart.next = refreshEnd; refreshEnd.prev = refreshStart; /*#DBG refreshStart.debugInfo = "*** refreshStart ***"; refreshEnd.debugInfo = "*** refreshEnd ***"; #DBG*/ refreshItemsFetched = false; refreshCount = undefined; keyFetchIDs = {}; refreshKeyMap = {}; refreshIndexMap = {}; refreshIndexMap[-1] = refreshStart; deletedKeys = {}; } function beginRefresh() { if (refreshRequested) { // There's already a refresh that has yet to start return; } refreshRequested = true; setStatus(DataSourceStatus.waiting); if (waitForRefresh) { waitForRefresh = false; // The edit queue has been paused until the next refresh - resume it now //#DBG _ASSERT(editsQueued); applyNextEdit(); return; } if (editsQueued) { // The refresh will be started once the edit queue empties out return; } var refreshID = ++currentRefreshID; refreshInProgress = true; refreshFetchesInProgress = 0; // Batch calls to beginRefresh Scheduler.schedule(function () { if (currentRefreshID !== refreshID) { return; } //#DBG _ASSERT(refreshRequested); refreshRequested = false; resetRefreshState(); // Remove all slots that aren't live, so we don't waste time fetching them for (var slot = slotsStart.next; slot !== slotsEnd;) { var slotNext = slot.next; if (!slotLive(slot) && slot !== slotListEnd) { deleteUnnecessarySlot(slot); } slot = slotNext; } startRefreshFetches(); }, Scheduler.Priority.high, null, "WinJS.VirtualizedDataSource.beginRefresh"); } function requestRefresh() { refreshSignal = refreshSignal || new Signal(); beginRefresh(); return refreshSignal.promise; } function resultsValidForRefresh(refreshID, fetchID) { // This fetch has completed, whatever it has returned //#DBG _ASSERT(fetchesInProgress[fetchID]); delete fetchesInProgress[fetchID]; if (refreshID !== currentRefreshID) { // This information is out of date. Ignore it. return false; } //#DBG _ASSERT(refreshFetchesInProgress > 0); refreshFetchesInProgress--; return true; } function fetchItemsForRefresh(key, fromStart, fetchID, promiseItems, index) { var refreshID = currentRefreshID; refreshFetchesInProgress++; promiseItems.then(function (fetchResult) { if (fetchResult.items && fetchResult.items.length) { var perfID = "itemsFetched id=" + fetchID + " count=" + fetchResult.items.length; profilerMarkStart(perfID); if (resultsValidForRefresh(refreshID, fetchID)) { addMarkers(fetchResult); processRefreshResults(key, fetchResult.items, fetchResult.offset, fetchResult.totalCount, (typeof index === "number" ? index : fetchResult.absoluteIndex)); } profilerMarkEnd(perfID); } else { return Promise.wrapError(new WinJS.ErrorFromName(FetchError.doesNotExist)); } }).then(null, function (error) { if (resultsValidForRefresh(refreshID, fetchID)) { processRefreshErrorResult(key, fromStart, error); } }); } function refreshRange(slot, fetchID, countBefore, countAfter) { if (itemsFromKey) { // Keys are the preferred identifiers when the item might have moved fetchItemsForRefresh(slot.key, false, fetchID, itemsFromKey(fetchID, slot.key, countBefore, countAfter, slot.hints)); } else { // Request additional items to try to locate items that have moved var searchDelta = 10, index = slot.index; //#DBG _ASSERT(+index === index); if (refreshIndexMap[index] && refreshIndexMap[index].firstInSequence) { // Ensure at least one element is observed before this one fetchItemsForRefresh(slot.key, false, fetchID, itemsFromIndex(fetchID, index - 1, Math.min(countBefore + searchDelta, index) - 1, countAfter + 1 + searchDelta), index - 1); } else if (refreshIndexMap[index] && refreshIndexMap[index].lastInSequence) { // Ask for the next index we need directly fetchItemsForRefresh(slot.key, false, fetchID, itemsFromIndex(fetchID, index + 1, Math.min(countBefore + searchDelta, index) + 1, countAfter - 1 + searchDelta), index + 1); } else { fetchItemsForRefresh(slot.key, false, fetchID, itemsFromIndex(fetchID, index, Math.min(countBefore + searchDelta, index), countAfter + searchDelta), index); } } } function refreshFirstItem(fetchID) { if (itemsFromStart) { fetchItemsForRefresh(null, true, fetchID, itemsFromStart(fetchID, 1), 0); } else if (itemsFromIndex) { fetchItemsForRefresh(null, true, fetchID, itemsFromIndex(fetchID, 0, 0, 0), 0); } } function keyFetchInProgress(key) { return fetchesInProgress[keyFetchIDs[key]]; } function refreshRanges(slotFirst, allRanges) { // Fetch a few extra items each time, to catch insertions without requiring an extra fetch var refreshFetchExtra = 3; var refreshID = currentRefreshID; var slotFetchFirst, slotRefreshFirst, fetchCount = 0, fetchID; // Walk through the slot list looking for keys we haven't fetched or attempted to fetch yet. Rely on the // heuristic that items that were close together before the refresh are likely to remain so after, so batched // fetches will locate most of the previously fetched items. for (var slot = slotFirst; slot !== slotsEnd; slot = slot.next) { if (!slotFetchFirst && slot.key && !deletedKeys[slot.key] && !keyFetchInProgress(slot.key)) { var slotRefresh = refreshKeyMap[slot.key]; // Keep attempting to fetch an item until at least one item on either side of it has been observed, so // we can determine its position relative to others. if (!slotRefresh || slotRefresh.firstInSequence || slotRefresh.lastInSequence) { slotFetchFirst = slot; slotRefreshFirst = slotRefresh; fetchID = newFetchID(); } } if (!slotFetchFirst) { // Also attempt to fetch placeholders for requests for specific keys, just in case those items no // longer exist. if (slot.key && isPlaceholder(slot) && !deletedKeys[slot.key]) { // Fulfill each "itemFromKey" request //#DBG _ASSERT(itemsFromKey); if (!refreshKeyMap[slot.key]) { // Fetch at least one item before and after, just to verify item's position in list fetchID = newFetchID(); fetchItemsForRefresh(slot.key, false, fetchID, itemsFromKey(fetchID, slot.key, 1, 1, slot.hints)); } } } else { var keyAlreadyFetched = keyFetchInProgress(slot.key); if (!deletedKeys[slot.key] && !refreshKeyMap[slot.key] && !keyAlreadyFetched) { if (slot.key) { keyFetchIDs[slot.key] = fetchID; } fetchCount++; } if (slot.lastInSequence || slot.next === slotListEnd || keyAlreadyFetched) { refreshRange(slotFetchFirst, fetchID, (!slotRefreshFirst || slotRefreshFirst.firstInSequence ? refreshFetchExtra : 0), fetchCount - 1 + refreshFetchExtra); /*#DBG fetchID = undefined; #DBG*/ if (!allRanges) { break; } slotFetchFirst = null; fetchCount = 0; } } } if (refreshFetchesInProgress === 0 && !refreshItemsFetched && currentRefreshID === refreshID) { // If nothing was successfully fetched, try fetching the first item, to detect an empty list refreshFirstItem(newFetchID()); } //#DBG _ASSERT(fetchID === undefined); } function startRefreshFetches() { var refreshID = currentRefreshID; do { synchronousProgress = false; reentrantContinue = true; refreshRanges(slotsStart.next, true); reentrantContinue = false; } while (refreshFetchesInProgress === 0 && synchronousProgress && currentRefreshID === refreshID && refreshInProgress); if (refreshFetchesInProgress === 0 && currentRefreshID === refreshID) { concludeRefresh(); } } function continueRefresh(key) { var refreshID = currentRefreshID; // If the key is absent, then the attempt to fetch the first item just completed, and there is nothing else to // fetch. if (key) { var slotContinue = keyMap[key]; if (!slotContinue) { // In a rare case, the slot might have been deleted; just start scanning from the beginning again slotContinue = slotsStart.next; } do { synchronousRefresh = false; reentrantRefresh = true; refreshRanges(slotContinue, false); reentrantRefresh = false; } while (synchronousRefresh && currentRefreshID === refreshID && refreshInProgress); } if (reentrantContinue) { synchronousProgress = true; } else { if (refreshFetchesInProgress === 0 && currentRefreshID === refreshID) { // Walk through the entire list one more time, in case any edits were made during the refresh startRefreshFetches(); } } } function slotRefreshFromResult(result) { if (typeof result !== "object" || !result) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.InvalidItemReturned", strings.invalidItemReturned); } else if (result === startMarker) { return refreshStart; } else if (result === endMarker) { return refreshEnd; } else if (!result.key) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.InvalidKeyReturned", strings.invalidKeyReturned); } else { return refreshKeyMap[result.key]; } } function processRefreshSlotIndex(slot, expectedIndex) { while (slot.index === undefined) { setSlotIndex(slot, expectedIndex, refreshIndexMap); if (slot.firstInSequence) { return true; } slot = slot.prev; expectedIndex--; } if (slot.index !== expectedIndex) { // Something has changed since the refresh began; start again beginRefresh(); return false; } return true; } function setRefreshSlotResult(slotRefresh, result) { //#DBG _ASSERT(result.key); slotRefresh.key = result.key; //#DBG _ASSERT(!refreshKeyMap[slotRefresh.key]); refreshKeyMap[slotRefresh.key] = slotRefresh; slotRefresh.item = result; } // Returns the slot after the last insertion point between sequences function lastRefreshInsertionPoint() { var slotNext = refreshEnd; while (!slotNext.firstInSequence) { slotNext = slotNext.prev; if (slotNext === refreshStart) { return null; } } return slotNext; } function processRefreshResults(key, results, offset, count, index) { index = validateIndexReturned(index); count = validateCountReturned(count); /*#DBG VERIFYREFRESHLIST(); #DBG*/ var keyPresent = false; refreshItemsFetched = true; var indexFirst = index - offset, result = results[0]; if (result.key === key) { keyPresent = true; } var slot = slotRefreshFromResult(result); if (!slot) { if (refreshIndexMap[indexFirst]) { // Something has changed since the refresh began; start again beginRefresh(); return; } // See if these results should be appended to an existing sequence var slotPrev; if (index !== undefined && (slotPrev = refreshIndexMap[indexFirst - 1])) { if (!slotPrev.lastInSequence) { // Something has changed since the refresh began; start again beginRefresh(); return; } slot = addSlotAfter(slotPrev, refreshIndexMap); } else { // Create a new sequence var slotSuccessor = ( +indexFirst === indexFirst ? successorFromIndex(indexFirst, refreshIndexMap, refreshStart, refreshEnd) : lastRefreshInsertionPoint(refreshStart, refreshEnd) ); if (!slotSuccessor) { // Something has changed since the refresh began; start again beginRefresh(); return; } slot = createSlotSequence(slotSuccessor, indexFirst, refreshIndexMap); } setRefreshSlotResult(slot, results[0]); } else { if (+indexFirst === indexFirst) { if (!processRefreshSlotIndex(slot, indexFirst)) { return; } } } var resultsCount = results.length; for (var i = 1; i < resultsCount; i++) { result = results[i]; if (result.key === key) { keyPresent = true; } var slotNext = slotRefreshFromResult(result); if (!slotNext) { if (!slot.lastInSequence) { // Something has changed since the refresh began; start again beginRefresh(); return; } slotNext = addSlotAfter(slot, refreshIndexMap); setRefreshSlotResult(slotNext, result); } else { if (slot.index !== undefined && !processRefreshSlotIndex(slotNext, slot.index + 1)) { return; } // If the slots aren't adjacent, see if it's possible to reorder sequences to make them so if (slotNext !== slot.next) { if (!slot.lastInSequence || !slotNext.firstInSequence) { // Something has changed since the refresh began; start again beginRefresh(); return; } var slotLast = sequenceEnd(slotNext); if (slotLast !== refreshEnd) { moveSequenceAfter(slot, slotNext, slotLast); } else { var slotFirst = sequenceStart(slot); if (slotFirst !== refreshStart) { moveSequenceBefore(slotNext, slotFirst, slot); } else { // Something has changed since the refresh began; start again beginRefresh(); return; } } mergeSequences(slot); } else if (slot.lastInSequence) { //#DBG _ASSERT(slotNext.firstInSequence); mergeSequences(slot); } } slot = slotNext; } if (!keyPresent) { deletedKeys[key] = true; } // If the count wasn't provided, see if it can be determined from the end of the list. if (!isNonNegativeNumber(count) && !refreshEnd.firstInSequence) { var indexLast = refreshEnd.prev.index; if (indexLast !== undefined) { count = indexLast + 1; } } if (isNonNegativeNumber(count) || count === CountResult.unknown) { if (isNonNegativeNumber(refreshCount)) { if (count !== refreshCount) { // Something has changed since the refresh began; start again beginRefresh(); return; } } else { refreshCount = count; } if (isNonNegativeNumber(refreshCount) && !refreshIndexMap[refreshCount]) { setSlotIndex(refreshEnd, refreshCount, refreshIndexMap); } } /*#DBG VERIFYREFRESHLIST(); #DBG*/ if (reentrantRefresh) { synchronousRefresh = true; } else { continueRefresh(key); } } function processRefreshErrorResult(key, fromStart, error) { switch (error.name) { case FetchError.noResponse: setStatus(DataSourceStatus.failure); break; case FetchError.doesNotExist: if (fromStart) { // The attempt to fetch the first item failed, so the list must be empty //#DBG _ASSERT(refreshStart.next === refreshEnd); //#DBG _ASSERT(refreshStart.lastInSequence && refreshEnd.firstInSequence); setSlotIndex(refreshEnd, 0, refreshIndexMap); refreshCount = 0; concludeRefresh(); } else { deletedKeys[key] = true; if (reentrantRefresh) { synchronousRefresh = true; } else { continueRefresh(key); } } break; } } function slotFromSlotRefresh(slotRefresh) { if (slotRefresh === refreshStart) { return slotsStart; } else if (slotRefresh === refreshEnd) { return slotListEnd; } else { return keyMap[slotRefresh.key]; } } function slotRefreshFromSlot(slot) { if (slot === slotsStart) { return refreshStart; } else if (slot === slotListEnd) { return refreshEnd; } else { return refreshKeyMap[slot.key]; } } function mergeSequencesForRefresh(slotPrev) { mergeSequences(slotPrev); // Mark the merge point, so we can distinguish insertions from unrequested items slotPrev.next.mergedForRefresh = true; } function copyRefreshSlotData(slotRefresh, slot) { setSlotKey(slot, slotRefresh.key); slot.itemNew = slotRefresh.item; } function addNewSlotFromRefresh(slotRefresh, slotNext, insertAfter) { var slotNew = createPrimarySlot(); copyRefreshSlotData(slotRefresh, slotNew); insertAndMergeSlot(slotNew, slotNext, insertAfter, !insertAfter); var index = slotRefresh.index; if (+index !== index) { index = (insertAfter ? slotNew.prev.index + 1 : slotNext.next.index - 1); } setSlotIndex(slotNew, index, indexMap); return slotNew; } function matchSlotForRefresh(slotExisting, slot, slotRefresh) { if (slotExisting) { sendMirageNotifications(slotExisting, slot, slotExisting.bindingMap); mergeSlotsAndItem(slotExisting, slot, slotRefresh.item); } else { copyRefreshSlotData(slotRefresh, slot); // If the index was requested, complete the promises now, as the index might be about to change if (slot.indexRequested) { updateSlotItem(slot); } } } function updateSlotForRefresh(slotExisting, slot, slotRefresh) { if (!slot.key) { if (slotExisting) { // Record the relationship between the slot to discard and its neighbors slotRefresh.mergeWithPrev = !slot.firstInSequence; slotRefresh.mergeWithNext = !slot.lastInSequence; } else { slotRefresh.stationary = true; } matchSlotForRefresh(slotExisting, slot, slotRefresh); return true; } else { //#DBG _ASSERT(!slotExisting); return false; } } function indexForRefresh(slot) { var indexNew; if (slot.indexRequested) { //#DBG _ASSERT(!slot.key); indexNew = slot.index; } else { var slotRefresh = slotRefreshFromSlot(slot); if (slotRefresh) { indexNew = slotRefresh.index; } } return indexNew; } function concludeRefresh() { //#DBG _ASSERT(refreshInProgress); //#DBG _ASSERT(!indexUpdateDeferred); beginRefreshCount = 0; refreshHistory = new Array(100); refreshHistoryPos = -1; indexUpdateDeferred = true; keyFetchIDs = {}; var i, j, slot, slotPrev, slotNext, slotBefore, slotAfter, slotRefresh, slotExisting, slotsAvailable = [], slotFirstInSequence, sequenceCountOld, sequencesOld = [], sequenceOld, sequenceOldPrev, sequenceOldBestMatch, sequenceCountNew, sequencesNew = [], sequenceNew, index, offset; /*#DBG VERIFYLIST(); VERIFYREFRESHLIST(); #DBG*/ // Assign a sequence number to each refresh slot sequenceCountNew = 0; for (slotRefresh = refreshStart; slotRefresh; slotRefresh = slotRefresh.next) { slotRefresh.sequenceNumber = sequenceCountNew; if (slotRefresh.firstInSequence) { slotFirstInSequence = slotRefresh; } if (slotRefresh.lastInSequence) { sequencesNew[sequenceCountNew] = { first: slotFirstInSequence, last: slotRefresh, matchingItems: 0 }; sequenceCountNew++; } } // Remove unnecessary information from main slot list, and update the items lastSlotReleased = null; releasedSlots = 0; for (slot = slotsStart.next; slot !== slotsEnd;) { slotRefresh = refreshKeyMap[slot.key]; slotNext = slot.next; if (slot !== slotListEnd) { if (!slotLive(slot)) { // Some more items might have been released since the refresh started. Strip them away from the // main slot list, as they'll just get in the way from now on. Since we're discarding these, but // don't know if they're actually going away, split the sequence as our starting assumption must be // that the items on either side are in separate sequences. deleteUnnecessarySlot(slot); } else if (slot.key && !slotRefresh) { // Remove items that have been deleted (or moved far away) and send removed notifications deleteSlot(slot, false); } else if (refreshCount === 0 || (slot.indexRequested && slot.index >= refreshCount)) { // Remove items that can't exist in the list and send mirage removed notifications deleteSlot(slot, true); } else if (slot.item || slot.keyRequested) { //#DBG _ASSERT(slotRefresh); // Store the new item; this value will be compared with that stored in slot.item later slot.itemNew = slotRefresh.item; } else { //#DBG _ASSERT(!slot.item); // Clear keys and items that have never been observed by client if (slot.key) { if (!slot.keyRequested) { delete keyMap[slot.key]; delete slot.key; } slot.itemNew = null; } } } slot = slotNext; } /*#DBG VERIFYLIST(); #DBG*/ // Placeholders generated by itemsAtIndex should not move. Match these to items now if possible, or merge them // with existing items if necessary. for (slot = slotsStart.next; slot !== slotListEnd;) { slotNext = slot.next; //#DBG _ASSERT(!slot.key || refreshKeyMap[slot.key]); if (slot.indexRequested) { //#DBG _ASSERT(!slot.item); //#DBG _ASSERT(slot.index !== undefined); slotRefresh = refreshIndexMap[slot.index]; if (slotRefresh) { matchSlotForRefresh(slotFromSlotRefresh(slotRefresh), slot, slotRefresh); } } slot = slotNext; } /*#DBG VERIFYLIST(); #DBG*/ // Match old sequences to new sequences var bestMatch, bestMatchCount, previousBestMatch = 0, newSequenceCounts = [], slotIndexRequested, sequenceIndexEnd, sequenceOldEnd; sequenceCountOld = 0; for (slot = slotsStart; slot !== slotsEnd; slot = slot.next) { if (slot.firstInSequence) { slotFirstInSequence = slot; slotIndexRequested = null; for (i = 0; i < sequenceCountNew; i++) { newSequenceCounts[i] = 0; } } if (slot.indexRequested) { slotIndexRequested = slot; } slotRefresh = slotRefreshFromSlot(slot); if (slotRefresh) { //#DBG _ASSERT(slotRefresh.sequenceNumber !== undefined); newSequenceCounts[slotRefresh.sequenceNumber]++; } if (slot.lastInSequence) { // Determine which new sequence is the best match for this old one. Use a simple greedy algorithm to // ensure the relative ordering of matched sequences is the same; out-of-order sequences will require // move notifications. bestMatchCount = 0; for (i = previousBestMatch; i < sequenceCountNew; i++) { if (bestMatchCount < newSequenceCounts[i]) { bestMatchCount = newSequenceCounts[i]; bestMatch = i; } } sequenceOld = { first: slotFirstInSequence, last: slot, sequenceNew: (bestMatchCount > 0 ? sequencesNew[bestMatch] : undefined), matchingItems: bestMatchCount }; if (slotIndexRequested) { sequenceOld.indexRequested = true; sequenceOld.stationarySlot = slotIndexRequested; } sequencesOld[sequenceCountOld] = sequenceOld; if (slot === slotListEnd) { sequenceIndexEnd = sequenceCountOld; sequenceOldEnd = sequenceOld; } sequenceCountOld++; if (sequencesNew[bestMatch].first.index !== undefined) { previousBestMatch = bestMatch; } } } //#DBG _ASSERT(sequenceOldEnd); // Special case: split the old start into a separate sequence if the new start isn't its best match if (sequencesOld[0].sequenceNew !== sequencesNew[0]) { //#DBG _ASSERT(sequencesOld[0].first === slotsStart); //#DBG _ASSERT(!slotsStart.lastInSequence); splitSequence(slotsStart); sequencesOld[0].first = slotsStart.next; sequencesOld.unshift({ first: slotsStart, last: slotsStart, sequenceNew: sequencesNew[0], matchingItems: 1 }); sequenceIndexEnd++; sequenceCountOld++; } var listEndObserved = !slotListEnd.firstInSequence; // Special case: split the old end into a separate sequence if the new end isn't its best match if (sequenceOldEnd.sequenceNew !== sequencesNew[sequenceCountNew - 1]) { //#DBG _ASSERT(sequenceOldEnd.last === slotListEnd); //#DBG _ASSERT(!slotListEnd.firstInSequence); splitSequence(slotListEnd.prev); sequenceOldEnd.last = slotListEnd.prev; sequenceIndexEnd++; sequencesOld.splice(sequenceIndexEnd, 0, { first: slotListEnd, last: slotListEnd, sequenceNew: sequencesNew[sequenceCountNew - 1], matchingItems: 1 }); sequenceCountOld++; sequenceOldEnd = sequencesOld[sequenceIndexEnd]; } // Map new sequences to old sequences for (i = 0; i < sequenceCountOld; i++) { sequenceNew = sequencesOld[i].sequenceNew; if (sequenceNew && sequenceNew.matchingItems < sequencesOld[i].matchingItems) { sequenceNew.matchingItems = sequencesOld[i].matchingItems; sequenceNew.sequenceOld = sequencesOld[i]; } } // The old end must always be the best match for the new end (if the new end is also the new start, they will // be merged below). sequencesNew[sequenceCountNew - 1].sequenceOld = sequenceOldEnd; sequenceOldEnd.stationarySlot = slotListEnd; // The old start must always be the best match for the new start sequencesNew[0].sequenceOld = sequencesOld[0]; sequencesOld[0].stationarySlot = slotsStart; /*#DBG VERIFYLIST(); #DBG*/ // Merge additional indexed old sequences when possible // First do a forward pass for (i = 0; i <= sequenceIndexEnd; i++) { sequenceOld = sequencesOld[i]; //#DBG _ASSERT(sequenceOld); if (sequenceOld.sequenceNew && (sequenceOldBestMatch = sequenceOld.sequenceNew.sequenceOld) === sequenceOldPrev && sequenceOldPrev.last !== slotListEnd) { //#DBG _ASSERT(sequenceOldBestMatch.last.next === sequenceOld.first); mergeSequencesForRefresh(sequenceOldBestMatch.last); sequenceOldBestMatch.last = sequenceOld.last; delete sequencesOld[i]; } else { sequenceOldPrev = sequenceOld; } } // Now do a reverse pass sequenceOldPrev = null; for (i = sequenceIndexEnd; i >= 0; i--) { sequenceOld = sequencesOld[i]; // From this point onwards, some members of sequencesOld may be undefined if (sequenceOld) { if (sequenceOld.sequenceNew && (sequenceOldBestMatch = sequenceOld.sequenceNew.sequenceOld) === sequenceOldPrev && sequenceOld.last !== slotListEnd) { //#DBG _ASSERT(sequenceOld.last.next === sequenceOldBestMatch.first); mergeSequencesForRefresh(sequenceOld.last); sequenceOldBestMatch.first = sequenceOld.first; delete sequencesOld[i]; } else { sequenceOldPrev = sequenceOld; } } } // Since we may have forced the list end into a separate sequence, the mergedForRefresh flag may be incorrect if (listEndObserved) { delete slotListEnd.mergedForRefresh; } var sequencePairsToMerge = []; // Find unchanged sequences without indices that can be merged with existing sequences without move // notifications. for (i = sequenceIndexEnd + 1; i < sequenceCountOld; i++) { sequenceOld = sequencesOld[i]; if (sequenceOld && (!sequenceOld.sequenceNew || sequenceOld.sequenceNew.sequenceOld !== sequenceOld)) { //#DBG _ASSERT(!sequenceOld.indexRequested); // If the order of the known items in the sequence is unchanged, then the sequence probably has not // moved, but we now know where it belongs relative to at least one other sequence. var orderPreserved = true, slotRefreshFirst = null, slotRefreshLast = null, sequenceLength = 0; slotRefresh = slotRefreshFromSlot(sequenceOld.first); if (slotRefresh) { slotRefreshFirst = slotRefreshLast = slotRefresh; sequenceLength = 1; } for (slot = sequenceOld.first; slot != sequenceOld.last; slot = slot.next) { var slotRefreshNext = slotRefreshFromSlot(slot.next); if (slotRefresh && slotRefreshNext && (slotRefresh.lastInSequence || slotRefresh.next !== slotRefreshNext)) { orderPreserved = false; break; } if (slotRefresh && !slotRefreshFirst) { slotRefreshFirst = slotRefreshLast = slotRefresh; } if (slotRefreshNext && slotRefreshFirst) { slotRefreshLast = slotRefreshNext; sequenceLength++; } slotRefresh = slotRefreshNext; } // If the stationary sequence has indices, verify that there is enough space for this sequence - if // not, then something somewhere has moved after all. if (orderPreserved && slotRefreshFirst && slotRefreshFirst.index !== undefined) { var indexBefore; if (!slotRefreshFirst.firstInSequence) { slotBefore = slotFromSlotRefresh(slotRefreshFirst.prev); if (slotBefore) { indexBefore = slotBefore.index; } } var indexAfter; if (!slotRefreshLast.lastInSequence) { slotAfter = slotFromSlotRefresh(slotRefreshLast.next); if (slotAfter) { indexAfter = slotAfter.index; } } if ((!slotAfter || slotAfter.lastInSequence || slotAfter.mergedForRefresh) && (indexBefore === undefined || indexAfter === undefined || indexAfter - indexBefore - 1 >= sequenceLength)) { sequenceOld.locationJustDetermined = true; // Mark the individual refresh slots as not requiring move notifications for (slotRefresh = slotRefreshFirst; ; slotRefresh = slotRefresh.next) { slotRefresh.locationJustDetermined = true; if (slotRefresh === slotRefreshLast) { break; } } // Store any adjacent placeholders so they can be merged once the moves and insertions have // been processed. var slotFirstInSequence = slotFromSlotRefresh(slotRefreshFirst), slotLastInSequence = slotFromSlotRefresh(slotRefreshLast); sequencePairsToMerge.push({ slotBeforeSequence: (slotFirstInSequence.firstInSequence ? null : slotFirstInSequence.prev), slotFirstInSequence: slotFirstInSequence, slotLastInSequence: slotLastInSequence, slotAfterSequence: (slotLastInSequence.lastInSequence ? null : slotLastInSequence.next) }); } } } } // Remove placeholders in old sequences that don't map to new sequences (and don't contain requests for a // specific index or key), as they no longer have meaning. for (i = 0; i < sequenceCountOld; i++) { sequenceOld = sequencesOld[i]; if (sequenceOld && !sequenceOld.indexRequested && !sequenceOld.locationJustDetermined && (!sequenceOld.sequenceNew || sequenceOld.sequenceNew.sequenceOld !== sequenceOld)) { sequenceOld.sequenceNew = null; slot = sequenceOld.first; var sequenceEndReached; do { sequenceEndReached = (slot === sequenceOld.last); slotNext = slot.next; if (slot !== slotsStart && slot !== slotListEnd && slot !== slotsEnd && !slot.item && !slot.keyRequested) { //#DBG _ASSERT(!slot.indexRequested); deleteSlot(slot, true); if (sequenceOld.first === slot) { if (sequenceOld.last === slot) { delete sequencesOld[i]; break; } else { sequenceOld.first = slot.next; } } else if (sequenceOld.last === slot) { sequenceOld.last = slot.prev; } } slot = slotNext; } while (!sequenceEndReached); } } /*#DBG VERIFYLIST(); #DBG*/ // Locate boundaries of new items in new sequences for (i = 0; i < sequenceCountNew; i++) { sequenceNew = sequencesNew[i]; for (slotRefresh = sequenceNew.first; !slotFromSlotRefresh(slotRefresh) && !slotRefresh.lastInSequence; slotRefresh = slotRefresh.next) { /*@empty*/ } if (slotRefresh.lastInSequence && !slotFromSlotRefresh(slotRefresh)) { sequenceNew.firstInner = sequenceNew.lastInner = null; } else { sequenceNew.firstInner = slotRefresh; for (slotRefresh = sequenceNew.last; !slotFromSlotRefresh(slotRefresh) ; slotRefresh = slotRefresh.prev) { /*@empty*/ } sequenceNew.lastInner = slotRefresh; } } // Determine which items to move for (i = 0; i < sequenceCountNew; i++) { sequenceNew = sequencesNew[i]; if (sequenceNew && sequenceNew.firstInner) { sequenceOld = sequenceNew.sequenceOld; if (sequenceOld) { // Number the slots in each new sequence with their offset in the corresponding old sequence (or // undefined if in a different old sequence). var ordinal = 0; for (slot = sequenceOld.first; true; slot = slot.next, ordinal++) { slotRefresh = slotRefreshFromSlot(slot); if (slotRefresh && slotRefresh.sequenceNumber === sequenceNew.firstInner.sequenceNumber) { slotRefresh.ordinal = ordinal; } if (slot.lastInSequence) { //#DBG _ASSERT(slot === sequenceOld.last); break; } } // Determine longest subsequence of items that are in the same order before and after var piles = []; for (slotRefresh = sequenceNew.firstInner; true; slotRefresh = slotRefresh.next) { ordinal = slotRefresh.ordinal; if (ordinal !== undefined) { var searchFirst = 0, searchLast = piles.length - 1; while (searchFirst <= searchLast) { var searchMidpoint = Math.floor(0.5 * (searchFirst + searchLast)); if (piles[searchMidpoint].ordinal < ordinal) { searchFirst = searchMidpoint + 1; } else { searchLast = searchMidpoint - 1; } } piles[searchFirst] = slotRefresh; if (searchFirst > 0) { slotRefresh.predecessor = piles[searchFirst - 1]; } } if (slotRefresh === sequenceNew.lastInner) { break; } } // The items in the longest ordered subsequence don't move; everything else does var stationaryItems = [], stationaryItemCount = piles.length; //#DBG _ASSERT(stationaryItemCount > 0); slotRefresh = piles[stationaryItemCount - 1]; for (j = stationaryItemCount; j--;) { slotRefresh.stationary = true; stationaryItems[j] = slotRefresh; slotRefresh = slotRefresh.predecessor; } //#DBG _ASSERT(!slotRefresh); sequenceOld.stationarySlot = slotFromSlotRefresh(stationaryItems[0]); // Try to match new items before the first stationary item to placeholders slotRefresh = stationaryItems[0]; slot = slotFromSlotRefresh(slotRefresh); slotPrev = slot.prev; var sequenceBoundaryReached = slot.firstInSequence; while (!slotRefresh.firstInSequence) { slotRefresh = slotRefresh.prev; slotExisting = slotFromSlotRefresh(slotRefresh); if (!slotExisting || slotRefresh.locationJustDetermined) { // Find the next placeholder walking backwards while (!sequenceBoundaryReached && slotPrev !== slotsStart) { slot = slotPrev; slotPrev = slot.prev; sequenceBoundaryReached = slot.firstInSequence; if (updateSlotForRefresh(slotExisting, slot, slotRefresh)) { break; } } } } // Try to match new items between stationary items to placeholders for (j = 0; j < stationaryItemCount - 1; j++) { slotRefresh = stationaryItems[j]; slot = slotFromSlotRefresh(slotRefresh); //#DBG _ASSERT(slot); var slotRefreshStop = stationaryItems[j + 1], slotRefreshMergePoint = null, slotStop = slotFromSlotRefresh(slotRefreshStop), slotExisting; //#DBG _ASSERT(slotStop); // Find all the new items slotNext = slot.next; for (slotRefresh = slotRefresh.next; slotRefresh !== slotRefreshStop && !slotRefreshMergePoint && slot !== slotStop; slotRefresh = slotRefresh.next) { slotExisting = slotFromSlotRefresh(slotRefresh); if (!slotExisting || slotRefresh.locationJustDetermined) { // Find the next placeholder while (slotNext !== slotStop) { // If a merge point is reached, match the remainder of the placeholders by walking backwards if (slotNext.mergedForRefresh) { slotRefreshMergePoint = slotRefresh.prev; break; } slot = slotNext; slotNext = slot.next; if (updateSlotForRefresh(slotExisting, slot, slotRefresh)) { break; } } } } // Walk backwards to the first merge point if necessary if (slotRefreshMergePoint) { slotPrev = slotStop.prev; for (slotRefresh = slotRefreshStop.prev; slotRefresh !== slotRefreshMergePoint && slotStop !== slot; slotRefresh = slotRefresh.prev) { slotExisting = slotFromSlotRefresh(slotRefresh); if (!slotExisting || slotRefresh.locationJustDetermined) { // Find the next placeholder walking backwards while (slotPrev !== slot) { slotStop = slotPrev; slotPrev = slotStop.prev; if (updateSlotForRefresh(slotExisting, slotStop, slotRefresh)) { break; } } } } } // Delete remaining placeholders, sending notifications while (slotNext !== slotStop) { slot = slotNext; slotNext = slot.next; if (slot !== slotsStart && isPlaceholder(slot) && !slot.keyRequested) { // This might occur due to two sequences - requested by different clients - being // merged. However, since only sequences with indices are merged, if this placehholder // is no longer necessary, it means an item actually was removed, so this doesn't count // as a mirage. deleteSlot(slot); } } } // Try to match new items after the last stationary item to placeholders slotRefresh = stationaryItems[stationaryItemCount - 1]; slot = slotFromSlotRefresh(slotRefresh); slotNext = slot.next; sequenceBoundaryReached = slot.lastInSequence; while (!slotRefresh.lastInSequence) { slotRefresh = slotRefresh.next; slotExisting = slotFromSlotRefresh(slotRefresh); if (!slotExisting || slotRefresh.locationJustDetermined) { // Find the next placeholder while (!sequenceBoundaryReached && slotNext !== slotListEnd) { slot = slotNext; slotNext = slot.next; sequenceBoundaryReached = slot.lastInSequence; if (updateSlotForRefresh(slotExisting, slot, slotRefresh)) { break; } } } } } } } /*#DBG VERIFYLIST(); #DBG*/ // Move items and send notifications for (i = 0; i < sequenceCountNew; i++) { sequenceNew = sequencesNew[i]; if (sequenceNew.firstInner) { slotPrev = null; for (slotRefresh = sequenceNew.firstInner; true; slotRefresh = slotRefresh.next) { slot = slotFromSlotRefresh(slotRefresh); if (slot) { if (!slotRefresh.stationary) { //#DBG _ASSERT(slot !== slotsStart); //#DBG _ASSERT(slot !== slotsEnd); var slotMoveBefore, mergeWithPrev = false, mergeWithNext = false; if (slotPrev) { slotMoveBefore = slotPrev.next; mergeWithPrev = true; } else { // The first item will be inserted before the first stationary item, so find that now var slotRefreshStationary; for (slotRefreshStationary = sequenceNew.firstInner; !slotRefreshStationary.stationary && slotRefreshStationary !== sequenceNew.lastInner; slotRefreshStationary = slotRefreshStationary.next) { /*@empty*/ } if (!slotRefreshStationary.stationary) { // There are no stationary items, as all the items are moving from another old // sequence. index = slotRefresh.index; // Find the best place to insert the new sequence if (index === 0) { // Index 0 is a special case slotMoveBefore = slotsStart.next; mergeWithPrev = true; } else if (index === undefined) { slotMoveBefore = slotsEnd; } else { // Use a linear search; unlike successorFromIndex, prefer the last insertion // point between sequences over the precise index slotMoveBefore = slotsStart.next; var lastSequenceStart = null; while (true) { if (slotMoveBefore.firstInSequence) { lastSequenceStart = slotMoveBefore; } if ((index < slotMoveBefore.index && lastSequenceStart) || slotMoveBefore === slotListEnd) { break; } slotMoveBefore = slotMoveBefore.next; } if (!slotMoveBefore.firstInSequence && lastSequenceStart) { slotMoveBefore = lastSequenceStart; } } } else { slotMoveBefore = slotFromSlotRefresh(slotRefreshStationary); mergeWithNext = true; } } // Preserve merge boundaries if (slot.mergedForRefresh) { delete slot.mergedForRefresh; if (!slot.lastInSequence) { slot.next.mergedForRefresh = true; } } mergeWithPrev = mergeWithPrev || slotRefresh.mergeWithPrev; mergeWithNext = mergeWithNext || slotRefresh.mergeWithNext; var skipNotifications = slotRefresh.locationJustDetermined; moveSlot(slot, slotMoveBefore, mergeWithPrev, mergeWithNext, skipNotifications); if (skipNotifications && mergeWithNext) { // Since this item was moved without a notification, this is an implicit merge of // sequences. Mark the item's successor as mergedForRefresh. slotMoveBefore.mergedForRefresh = true; } } slotPrev = slot; } if (slotRefresh === sequenceNew.lastInner) { break; } } } } /*#DBG VERIFYLIST(); #DBG*/ // Insert new items (with new indices) and send notifications for (i = 0; i < sequenceCountNew; i++) { sequenceNew = sequencesNew[i]; if (sequenceNew.firstInner) { slotPrev = null; for (slotRefresh = sequenceNew.firstInner; true; slotRefresh = slotRefresh.next) { slot = slotFromSlotRefresh(slotRefresh); if (!slot) { var slotInsertBefore; if (slotPrev) { slotInsertBefore = slotPrev.next; } else { // The first item will be inserted *before* the first old item, so find that now var slotRefreshOld; for (slotRefreshOld = sequenceNew.firstInner; !slotFromSlotRefresh(slotRefreshOld) ; slotRefreshOld = slotRefreshOld.next) { /*@empty*/ //#DBG _ASSERT(slotRefreshOld !== sequenceNew.lastInner); } slotInsertBefore = slotFromSlotRefresh(slotRefreshOld); } // Create a new slot for the item slot = addNewSlotFromRefresh(slotRefresh, slotInsertBefore, !!slotPrev); var slotRefreshNext = slotRefreshFromSlot(slotInsertBefore); if (!slotInsertBefore.mergedForRefresh && (!slotRefreshNext || !slotRefreshNext.locationJustDetermined)) { prepareSlotItem(slot); // Send the notification after the insertion sendInsertedNotification(slot); } } slotPrev = slot; if (slotRefresh === sequenceNew.lastInner) { break; } } } } /*#DBG VERIFYLIST(); #DBG*/ // Rebuild the indexMap from scratch, so it is possible to detect colliding indices indexMap = []; // Send indexChanged and changed notifications var indexFirst = -1; for (slot = slotsStart, offset = 0; slot !== slotsEnd; offset++) { var slotNext = slot.next; if (slot.firstInSequence) { slotFirstInSequence = slot; offset = 0; } if (indexFirst === undefined) { var indexNew = indexForRefresh(slot); if (indexNew !== undefined) { indexFirst = indexNew - offset; } } // See if the next slot would cause a contradiction, in which case split the sequences if (indexFirst !== undefined && !slot.lastInSequence) { var indexNewNext = indexForRefresh(slot.next); if (indexNewNext !== undefined && indexNewNext !== indexFirst + offset + 1) { splitSequence(slot); // 'Move' the items in-place individually, so move notifications are sent. In rare cases, this // will result in multiple move notifications being sent for a given item, but that's fine. var first = true; for (var slotMove = slot.next, lastInSequence = false; !lastInSequence && slotMove !== slotListEnd;) { var slotMoveNext = slotMove.next; lastInSequence = slotMove.lastInSequence; moveSlot(slotMove, slotMoveNext, !first, false); first = false; slotMove = slotMoveNext; } } } if (slot.lastInSequence) { index = indexFirst; for (var slotUpdate = slotFirstInSequence; slotUpdate !== slotNext;) { var slotUpdateNext = slotUpdate.next; if (index >= refreshCount && slotUpdate !== slotListEnd) { deleteSlot(slotUpdate, true); } else { var slotWithIndex = indexMap[index]; if (index !== slotUpdate.index) { delete indexMap[index]; changeSlotIndex(slotUpdate, index); } else if (+index === index && indexMap[index] !== slotUpdate) { indexMap[index] = slotUpdate; } if (slotUpdate.itemNew) { updateSlotItem(slotUpdate); } if (slotWithIndex) { // Two slots' indices have collided - merge them if (slotUpdate.key) { sendMirageNotifications(slotUpdate, slotWithIndex, slotUpdate.bindingMap); mergeSlots(slotUpdate, slotWithIndex); if (+index === index) { indexMap[index] = slotUpdate; } } else { sendMirageNotifications(slotWithIndex, slotUpdate, slotWithIndex.bindingMap); mergeSlots(slotWithIndex, slotUpdate); if (+index === index) { indexMap[index] = slotWithIndex; } } } if (+index === index) { index++; } } slotUpdate = slotUpdateNext; } indexFirst = undefined; } slot = slotNext; } // See if any sequences need to be moved and/or merged var indexMax = -2, listEndReached; for (slot = slotsStart, offset = 0; slot !== slotsEnd; offset++) { var slotNext = slot.next; if (slot.firstInSequence) { slotFirstInSequence = slot; offset = 0; } // Clean up during this pass delete slot.mergedForRefresh; if (slot.lastInSequence) { // Move sequence if necessary if (slotFirstInSequence.index === undefined) { slotBefore = slotFirstInSequence.prev; var slotRefreshBefore; if (slotBefore && (slotRefreshBefore = slotRefreshFromSlot(slotBefore)) && !slotRefreshBefore.lastInSequence && (slotRefresh = slotRefreshFromSlot(slot)) && slotRefresh.prev === slotRefreshBefore) { moveSequenceAfter(slotBefore, slotFirstInSequence, slot); mergeSequences(slotBefore); } else if (slot !== slotListEnd && !listEndReached) { moveSequenceBefore(slotsEnd, slotFirstInSequence, slot); } } else { //#DBG _ASSERT(slot.index !== undefined); if (indexMax < slot.index && !listEndReached) { indexMax = slot.index; } else { // Find the correct insertion point for (slotAfter = slotsStart.next; slotAfter.index < slot.index; slotAfter = slotAfter.next) { /*@empty*/ } // Move the items individually, so move notifications are sent for (var slotMove = slotFirstInSequence; slotMove !== slotNext;) { var slotMoveNext = slotMove.next; slotRefresh = slotRefreshFromSlot(slotMove); moveSlot(slotMove, slotAfter, slotAfter.prev.index === slotMove.index - 1, slotAfter.index === slotMove.index + 1, slotRefresh && slotRefresh.locationJustDetermined); slotMove = slotMoveNext; } } // Store slotBefore here since the sequence might have just been moved slotBefore = slotFirstInSequence.prev; // See if this sequence should be merged with the previous one if (slotBefore && slotBefore.index === slotFirstInSequence.index - 1) { mergeSequences(slotBefore); } } } if (slot === slotListEnd) { listEndReached = true; } slot = slotNext; } indexUpdateDeferred = false; /*#DBG VERIFYLIST(); #DBG*/ // Now that all the sequences have been moved, merge any colliding slots mergeSequencePairs(sequencePairsToMerge); /*#DBG VERIFYLIST(); #DBG*/ // Send countChanged notification if (refreshCount !== undefined && refreshCount !== knownCount) { changeCount(refreshCount); } /*#DBG VERIFYLIST(); #DBG*/ finishNotifications(); // Before discarding the refresh slot list, see if any fetch requests can be completed by pretending each range // of refresh slots is an incoming array of results. var fetchResults = []; for (i = 0; i < sequenceCountNew; i++) { sequenceNew = sequencesNew[i]; var results = []; slot = null; offset = 0; var slotOffset; for (slotRefresh = sequenceNew.first; true; slotRefresh = slotRefresh.next, offset++) { if (slotRefresh === refreshStart) { results.push(startMarker); } else if (slotRefresh === refreshEnd) { results.push(endMarker); } else { results.push(slotRefresh.item); if (!slot) { slot = slotFromSlotRefresh(slotRefresh); slotOffset = offset; } } if (slotRefresh.lastInSequence) { //#DBG _ASSERT(slotRefresh === sequenceNew.last); break; } } if (slot) { fetchResults.push({ slot: slot, results: results, offset: slotOffset }); } } resetRefreshState(); refreshInProgress = false; /*#DBG VERIFYLIST(); #DBG*/ // Complete any promises for newly obtained items callFetchCompleteCallbacks(); // Now process the 'extra' results from the refresh list for (i = 0; i < fetchResults.length; i++) { var fetchResult = fetchResults[i]; processResults(fetchResult.slot, fetchResult.results, fetchResult.offset, knownCount, fetchResult.slot.index); } if (refreshSignal) { var signal = refreshSignal; refreshSignal = null; signal.complete(); } // Finally, kick-start fetches for any remaining placeholders postFetch(); } // Edit Queue // Queues an edit and immediately "optimistically" apply it to the slots list, sending re-entrant notifications function queueEdit(applyEdit, editType, complete, error, keyUpdate, updateSlots, undo) { var editQueueTail = editQueue.prev, edit = { prev: editQueueTail, next: editQueue, applyEdit: applyEdit, editType: editType, complete: complete, error: error, keyUpdate: keyUpdate }; editQueueTail.next = edit; editQueue.prev = edit; editsQueued = true; // If there's a refresh in progress, abandon it, but request that a new one be started once the edits complete if (refreshRequested || refreshInProgress) { currentRefreshID++; refreshInProgress = false; refreshRequested = true; } if (editQueue.next === edit) { // Attempt the edit immediately, in case it completes synchronously applyNextEdit(); } // If the edit succeeded or is still pending, apply it to the slots (in the latter case, "optimistically") if (!edit.failed) { updateSlots(); // Supply the undo function now edit.undo = undo; } if (!editsInProgress) { completeEdits(); } } function dequeueEdit() { firstEditInProgress = false; //#DBG _ASSERT(editQueue.next !== editQueue); var editNext = editQueue.next.next; editQueue.next = editNext; editNext.prev = editQueue; } // Undo all queued edits, starting with the most recent function discardEditQueue() { while (editQueue.prev !== editQueue) { var editLast = editQueue.prev; if (editLast.error) { editLast.error(new WinJS.ErrorFromName(UI.EditError.canceled)); } // Edits that haven't been applied to the slots yet don't need to be undone if (editLast.undo && !refreshRequested) { editLast.undo(); } editQueue.prev = editLast.prev; } editQueue.next = editQueue; editsInProgress = false; completeEdits(); } var EditType = { insert: "insert", change: "change", move: "move", remove: "remove" }; function attemptEdit(edit) { if (firstEditInProgress) { return; } var reentrant = true; function continueEdits() { if (!waitForRefresh) { if (reentrant) { synchronousEdit = true; } else { applyNextEdit(); } } } var keyUpdate = edit.keyUpdate; function onEditComplete(item) { if (item) { if (keyUpdate && keyUpdate.key !== item.key) { //#DBG _ASSERT(edit.editType === EditType.insert); var keyNew = item.key; if (!edit.undo) { // If the edit is in the process of being queued, we can use the correct key when we update the // slots, so there's no need for a later update. keyUpdate.key = keyNew; } else { var slot = keyUpdate.slot; if (slot) { var keyOld = slot.key; if (keyOld) { //#DBG _ASSERT(slot.key === keyOld); //#DBG _ASSERT(keyMap[keyOld] === slot); delete keyMap[keyOld]; } /*#DBG // setSlotKey asserts that the slot key is absent delete slot.key; #DBG*/ setSlotKey(slot, keyNew); slot.itemNew = item; if (slot.item) { changeSlot(slot); finishNotifications(); } else { completeFetchPromises(slot); } } } } else if (edit.editType === EditType.change) { //#DBG _ASSERT(slot.item); slot.itemNew = item; if (!reentrant) { changeSlotIfNecessary(slot); } } } dequeueEdit(); if (edit.complete) { edit.complete(item); } continueEdits(); } function onEditError(error) { switch (error.Name) { case EditError.noResponse: // Report the failure to the client, but do not dequeue the edit setStatus(DataSourceStatus.failure); waitForRefresh = true; firstEditInProgress = false; // Don't report the error, as the edit will be attempted again on the next refresh return; case EditError.notPermitted: break; case EditError.noLongerMeaningful: // Something has changed, so request a refresh beginRefresh(); break; default: break; } // Discard all remaining edits, rather than try to determine which subsequent ones depend on this one edit.failed = true; dequeueEdit(); discardEditQueue(); if (edit.error) { edit.error(error); } continueEdits(); } if (listDataAdapter.beginEdits && !beginEditsCalled) { beginEditsCalled = true; listDataAdapter.beginEdits(); } // Call the applyEdit function for the given edit, passing in our own wrapper of the error handler that the // client passed in. firstEditInProgress = true; edit.applyEdit().then(onEditComplete, onEditError); reentrant = false; } function applyNextEdit() { // See if there are any outstanding edits, and try to process as many as possible synchronously while (editQueue.next !== editQueue) { synchronousEdit = false; attemptEdit(editQueue.next); if (!synchronousEdit) { return; } } // The queue emptied out synchronously (or was empty to begin with) concludeEdits(); } function completeEdits() { //#DBG _ASSERT(!editsInProgress); updateIndices(); finishNotifications(); callFetchCompleteCallbacks(); if (editQueue.next === editQueue) { concludeEdits(); } } // Once the edit queue has emptied, update state appropriately and resume normal operation function concludeEdits() { editsQueued = false; if (listDataAdapter.endEdits && beginEditsCalled && !editsInProgress) { beginEditsCalled = false; listDataAdapter.endEdits(); } // See if there's a refresh that needs to begin if (refreshRequested) { refreshRequested = false; beginRefresh(); } else { // Otherwise, see if anything needs to be fetched postFetch(); } } // Editing Operations function getSlotForEdit(key) { validateKey(key); return keyMap[key] || createSlotForKey(key); } function insertNewSlot(key, itemNew, slotInsertBefore, mergeWithPrev, mergeWithNext) { // Create a new slot, but don't worry about its index, as indices will be updated during endEdits var slot = createPrimarySlot(); insertAndMergeSlot(slot, slotInsertBefore, mergeWithPrev, mergeWithNext); if (key) { setSlotKey(slot, key); } slot.itemNew = itemNew; updateNewIndices(slot, 1); // If this isn't part of a batch of changes, set the slot index now so renderers can see it if (!editsInProgress && !dataNotificationsInProgress) { if (!slot.firstInSequence && typeof slot.prev.index === "number") { setSlotIndex(slot, slot.prev.index + 1, indexMap); } else if (!slot.lastInSequence && typeof slot.next.index === "number") { setSlotIndex(slot, slot.next.index - 1, indexMap); } } prepareSlotItem(slot); // Send the notification after the insertion sendInsertedNotification(slot); return slot; } function insertItem(key, data, slotInsertBefore, append, applyEdit) { var keyUpdate = { key: key }; return new Promise(function (complete, error) { queueEdit( applyEdit, EditType.insert, complete, error, keyUpdate, // updateSlots function () { if (slotInsertBefore) { var itemNew = { key: keyUpdate.key, data: data }; keyUpdate.slot = insertNewSlot(keyUpdate.key, itemNew, slotInsertBefore, append, !append); } }, // undo function () { var slot = keyUpdate.slot; if (slot) { updateNewIndices(slot, -1); deleteSlot(slot, false); } } ); }); } function moveItem(slot, slotMoveBefore, append, applyEdit) { return new Promise(function (complete, error) { var mergeAdjacent, slotNext, firstInSequence, lastInSequence; queueEdit( applyEdit, EditType.move, complete, error, // keyUpdate null, // updateSlots function () { slotNext = slot.next; firstInSequence = slot.firstInSequence; lastInSequence = slot.lastInSequence; var slotPrev = slot.prev; mergeAdjacent = (typeof slot.index !== "number" && (firstInSequence || !slotPrev.item) && (lastInSequence || !slotNext.item)); updateNewIndices(slot, -1); moveSlot(slot, slotMoveBefore, append, !append); updateNewIndices(slot, 1); if (mergeAdjacent) { splitSequence(slotPrev); if (!firstInSequence) { mergeSlotsBefore(slotPrev, slot); } if (!lastInSequence) { mergeSlotsAfter(slotNext, slot); } } }, // undo function () { if (!mergeAdjacent) { updateNewIndices(slot, -1); moveSlot(slot, slotNext, !firstInSequence, !lastInSequence); updateNewIndices(slot, 1); } else { beginRefresh(); } } ); }); } function ListDataNotificationHandler() { /// /// /// An implementation of IListDataNotificationHandler that is passed to the /// IListDataAdapter.setNotificationHandler method. /// /// this.invalidateAll = function () { /// /// /// Notifies the VirtualizedDataSource that some data has changed, without specifying which data. It might /// be impractical for some data sources to call this method for any or all changes, so this call is optional. /// But if a given data adapter never calls it, the application should periodically call /// invalidateAll on the VirtualizedDataSource to refresh the data. /// /// /// A Promise that completes when the data has been completely refreshed and all change notifications have /// been sent. /// /// if (knownCount === 0) { this.reload(); return Promise.wrap(); } return requestRefresh(); }; this.reload = function () { /// /// /// Notifies the list data source that the list data has changed so much that it is better /// to reload the data from scratch. /// /// // Cancel all promises if (getCountPromise) { getCountPromise.cancel(); } if (refreshSignal) { refreshSignal.cancel(); } for (var slot = slotsStart.next; slot !== slotsEnd; slot = slot.next) { var fetchListeners = slot.fetchListeners; for (var listenerID in fetchListeners) { fetchListeners[listenerID].promise.cancel(); } var directFetchListeners = slot.directFetchListeners; for (var listenerID in directFetchListeners) { directFetchListeners[listenerID].promise.cancel(); } } resetState(); forEachBindingRecord(function (bindingRecord) { if (bindingRecord.notificationHandler) { bindingRecord.notificationHandler.reload(); } }); }; this.beginNotifications = function () { /// /// /// Indicates the start of a notification batch. /// Call it before a sequence of other notification calls to minimize the number of countChanged and /// indexChanged notifications sent to the client of the VirtualizedDataSource. You must pair it with a call /// to endNotifications, and pairs can't be nested. /// /// dataNotificationsInProgress = true; }; function completeNotification() { if (!dataNotificationsInProgress) { updateIndices(); finishNotifications(); callFetchCompleteCallbacks(); } } this.inserted = function (newItem, previousKey, nextKey, index) { /// /// /// Raises a notification that an item was inserted. /// /// /// The inserted item. It must have a key and a data property (it must implement the IItem interface). /// /// /// The key of the item before the insertion point, or null if the item was inserted at the start of the /// list. It can be null if you specified nextKey. /// /// /// The key of the item after the insertion point, or null if the item was inserted at the end of the list. /// It can be null if you specified previousKey. /// /// /// The index of the inserted item. /// /// if (editsQueued) { // We can't change the slots out from under any queued edits beginRefresh(); } else { var key = newItem.key, slotPrev = keyMap[previousKey], slotNext = keyMap[nextKey]; var havePreviousKey = typeof previousKey === "string", haveNextKey = typeof nextKey === "string"; // Only one of previousKey, nextKey needs to be passed in // if (havePreviousKey) { if (slotNext && !slotNext.firstInSequence) { slotPrev = slotNext.prev; } } else if (haveNextKey) { if (slotPrev && !slotPrev.lastInSequence) { slotNext = slotPrev.next; } } // If the VDS believes the list is empty but the data adapter believes the item has // a adjacent item start a refresh. // if ((havePreviousKey || haveNextKey) && !(slotPrev || slotNext) && (slotsStart.next === slotListEnd)) { beginRefresh(); return; } // If this key is known, something has changed, start a refresh. // if (keyMap[key]) { beginRefresh(); return; } // If the slots aren't adjacent or are thought to be distinct sequences by the // VDS something has changed so start a refresh. // if (slotPrev && slotNext) { if (slotPrev.next !== slotNext || slotPrev.lastInSequence || slotNext.firstInSequence) { beginRefresh(); return; } } // If one of the adjacent keys or indicies has only just been requested - rare, // and easier to deal with in a refresh. // if ((slotPrev && (slotPrev.keyRequested || slotPrev.indexRequested)) || (slotNext && (slotNext.keyRequested || slotNext.indexRequested))) { beginRefresh(); return; } if (slotPrev || slotNext) { insertNewSlot(key, newItem, (slotNext ? slotNext : slotPrev.next), !!slotPrev, !!slotNext); } else if (slotsStart.next === slotListEnd) { insertNewSlot(key, newItem, slotsStart.next, true, true); } else if (index !== undefined) { updateNewIndicesFromIndex(index, 1); } else { // We could not find a previous or next slot and an index was not provided, start a refresh // beginRefresh(); return; } completeNotification(); } }; this.changed = function (item) { /// /// /// Raises a notification that an item changed. /// /// /// An IItem that represents the item that changed. /// /// if (editsQueued) { // We can't change the slots out from under any queued edits beginRefresh(); } else { var key = item.key, slot = keyMap[key]; if (slot) { if (slot.keyRequested) { // The key has only just been requested - rare, and easier to deal with in a refresh beginRefresh(); } else { slot.itemNew = item; if (slot.item) { changeSlot(slot); completeNotification(); } } } } }; this.moved = function (item, previousKey, nextKey, oldIndex, newIndex) { /// /// /// Raises a notfication that an item was moved. /// /// /// The item that was moved. /// /// /// The key of the item before the insertion point, or null if the item was moved to the beginning of the list. /// It can be null if you specified nextKey. /// /// /// The key of the item after the insertion point, or null if the item was moved to the end of the list. /// It can be null if you specified previousKey. /// /// /// The index of the item before it was moved. /// /// /// The index of the item after it was moved. /// /// if (editsQueued) { // We can't change the slots out from under any queued edits beginRefresh(); } else { var key = item.key, slot = keyMap[key], slotPrev = keyMap[previousKey], slotNext = keyMap[nextKey]; if ((slot && slot.keyRequested) || (slotPrev && slotPrev.keyRequested) || (slotNext && slotNext.keyRequested)) { // One of the keys has only just been requested - rare, and easier to deal with in a refresh beginRefresh(); } else if (slot) { if (slotPrev && slotNext && (slotPrev.next !== slotNext || slotPrev.lastInSequence || slotNext.firstInSequence)) { // Something has changed, start a refresh beginRefresh(); } else if (!slotPrev && !slotNext) { // If we can't tell where the item moved to, treat this like a removal updateNewIndices(slot, -1); deleteSlot(slot, false); if (oldIndex !== undefined) { if (oldIndex < newIndex) { newIndex--; } updateNewIndicesFromIndex(newIndex, 1); } completeNotification(); } else { updateNewIndices(slot, -1); moveSlot(slot, (slotNext ? slotNext : slotPrev.next), !!slotPrev, !!slotNext); updateNewIndices(slot, 1); completeNotification(); } } else if (slotPrev || slotNext) { // If previousKey or nextKey is known, but key isn't, treat this like an insertion. if (oldIndex !== undefined) { updateNewIndicesFromIndex(oldIndex, -1); if (oldIndex < newIndex) { newIndex--; } } this.inserted(item, previousKey, nextKey, newIndex); } else if (oldIndex !== undefined) { updateNewIndicesFromIndex(oldIndex, -1); if (oldIndex < newIndex) { newIndex--; } updateNewIndicesFromIndex(newIndex, 1); completeNotification(); } } }; this.removed = function (key, index) { /// /// /// Raises a notification that an item was removed. /// /// /// The key of the item that was removed. /// /// /// The index of the item that was removed. /// /// if (editsQueued) { // We can't change the slots out from under any queued edits beginRefresh(); } else { var slot; if (typeof key === "string") { slot = keyMap[key]; } else { slot = indexMap[index]; } if (slot) { if (slot.keyRequested) { // The key has only just been requested - rare, and easier to deal with in a refresh beginRefresh(); } else { updateNewIndices(slot, -1); deleteSlot(slot, false); completeNotification(); } } else if (index !== undefined) { updateNewIndicesFromIndex(index, -1); completeNotification(); } } }; this.endNotifications = function () { /// /// /// Concludes a sequence of notifications that began with a call to beginNotifications. /// /// dataNotificationsInProgress = false; completeNotification(); }; } // ListDataNotificationHandler function resetState() { setStatus(DataSourceStatus.ready); // Track count promises getCountPromise = null; // Track whether listDataAdapter.endEdits needs to be called beginEditsCalled = false; // Track whether finishNotifications should be called after each edit editsInProgress = false; // Track whether the first queued edit should be attempted firstEditInProgress = false; // Queue of edis that have yet to be completed editQueue = {}; editQueue.next = editQueue; editQueue.prev = editQueue; /*#DBG editQueue.debugInfo = "*** editQueueHead/Tail ***"; #DBG*/ // Track whether there are currently edits queued editsQueued = false; // If an edit has returned noResponse, the edit queue will be reapplied when the next refresh is requested waitForRefresh = false; // Change to count while multiple edits are taking place countDelta = 0; // True while the indices are temporarily in a bad state due to multiple edits indexUpdateDeferred = false; // Next temporary key to use nextTempKey = 0; // Set of fetches for which results have not yet arrived fetchesInProgress = {}; // Queue of complete callbacks for fetches fetchCompleteCallbacks = []; // Tracks the count returned explicitly or implicitly by the data adapter knownCount = CountResult.unknown; // Sentinel objects for list of slots // Give the start sentinel an index so we can always use predecessor + 1. slotsStart = { firstInSequence: true, lastInSequence: true, index: -1 }; slotListEnd = { firstInSequence: true, lastInSequence: true }; slotsEnd = { firstInSequence: true, lastInSequence: true }; slotsStart.next = slotListEnd; slotListEnd.prev = slotsStart; slotListEnd.next = slotsEnd; slotsEnd.prev = slotListEnd; /*#DBG slotsStart.debugInfo = "*** slotsStart ***"; slotListEnd.debugInfo = "*** slotListEnd ***"; slotsEnd.debugInfo = "*** slotsEnd ***"; #DBG*/ // Map of request IDs to slots handleMap = {}; // Map of keys to slots keyMap = {}; // Map of indices to slots indexMap = {}; indexMap[-1] = slotsStart; // Count of slots that have been released but not deleted releasedSlots = 0; lastSlotReleased = null; // At most one call to reduce the number of refresh slots should be posted at any given time reduceReleasedSlotCountPosted = false; // Multiple refresh requests are coalesced refreshRequested = false; // Requests do not cause fetches while a refresh is in progress refreshInProgress = false; // Refresh requests yield the same promise until a refresh completes refreshSignal = null; } // Construction // Process creation parameters if (!listDataAdapter) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.ListDataAdapterIsInvalid", strings.listDataAdapterIsInvalid); } // Minimum number of released slots to retain cacheSize = (listDataAdapter.compareByIdentity ? 0 : 200); if (options) { if (typeof options.cacheSize === "number") { cacheSize = options.cacheSize; } } // Cached listDataNotificationHandler initially undefined if (listDataAdapter.setNotificationHandler) { listDataNotificationHandler = new ListDataNotificationHandler(); listDataAdapter.setNotificationHandler(listDataNotificationHandler); } // Current status status = DataSourceStatus.ready; // Track whether a change to the status has been posted already statusChangePosted = false; // Map of bindingIDs to binding records bindingMap = {}; // ID to assign to the next ListBinding, incremented each time one is created nextListBindingID = 0; // ID assigned to a slot, incremented each time one is created - start with 1 so "if (handle)" tests are valid nextHandle = 1; // ID assigned to a fetch listener, incremented each time one is created nextListenerID = 0; // ID of the refresh in progress, incremented each time a new refresh is started currentRefreshID = 0; // Track whether fetchItemsForAllSlots has been posted already fetchesPosted = false; // ID of a fetch, incremented each time a new fetch is initiated - start with 1 so "if (fetchID)" tests are valid nextFetchID = 1; // Sentinel objects for results arrays startMarker = {}; endMarker = {}; resetState(); /*#DBG this._debugBuild = true; Object.defineProperty(this, "_totalSlots", { get: function () { return totalSlots; } }); Object.defineProperty(this, "_releasedSlots", { get: function () { return releasedSlots; } }); #DBG*/ // Public methods this.createListBinding = function (notificationHandler) { /// /// /// Creates an IListBinding object that allows a client to read from the list and receive notifications for /// changes that affect those portions of the list that the client already read. /// /// /// An object that implements the IListNotificationHandler interface. If you omit this parameter, /// change notifications won't be available. /// /// /// An object that implements the IListBinding interface. /// /// var listBindingID = (nextListBindingID++).toString(), slotCurrent = null, released = false; function retainSlotForCursor(slot) { if (slot) { slot.cursorCount++; } } function releaseSlotForCursor(slot) { if (slot) { //#DBG _ASSERT(slot.cursorCount > 0); if (--slot.cursorCount === 0) { releaseSlotIfUnrequested(slot); } } } function moveCursor(slot) { // Retain the new slot first just in case it's the same slot retainSlotForCursor(slot); releaseSlotForCursor(slotCurrent); slotCurrent = slot; } function adjustCurrentSlot(slot, slotNew) { if (slot === slotCurrent) { if (!slotNew) { slotNew = ( !slotCurrent || slotCurrent.lastInSequence || slotCurrent.next === slotListEnd ? null : slotCurrent.next ); } moveCursor(slotNew); } } function releaseSlotFromListBinding(slot) { var bindingMap = slot.bindingMap, bindingHandle = bindingMap[listBindingID].handle; delete slot.bindingMap[listBindingID]; // See if there are any listBindings left in the map var releaseBindingMap = true, releaseHandle = true; for (var listBindingID2 in bindingMap) { releaseBindingMap = false; if (bindingHandle && bindingMap[listBindingID2].handle === bindingHandle) { releaseHandle = false; break; } } if (bindingHandle && releaseHandle) { delete handleMap[bindingHandle]; } if (releaseBindingMap) { slot.bindingMap = null; releaseSlotIfUnrequested(slot); } } function retainItem(slot, listenerID) { if (!slot.bindingMap) { slot.bindingMap = {}; } var slotBinding = slot.bindingMap[listBindingID]; if (slotBinding) { slotBinding.count++; } else { slot.bindingMap[listBindingID] = { bindingRecord: bindingMap[listBindingID], count: 1 }; } if (slot.fetchListeners) { var listener = slot.fetchListeners[listenerID]; if (listener) { listener.retained = true; } } } function releaseItem(handle) { var slot = handleMap[handle]; //#DBG _ASSERT(slot); if (slot) { var slotBinding = slot.bindingMap[listBindingID]; if (--slotBinding.count === 0) { var fetchListeners = slot.fetchListeners; for (var listenerID in fetchListeners) { var listener = fetchListeners[listenerID]; if (listener.listBindingID === listBindingID) { listener.retained = false; } } releaseSlotFromListBinding(slot); } } } function itemPromiseFromKnownSlot(slot) { var handle = handleForBinding(slot, listBindingID), listenerID = (nextListenerID++).toString(); var itemPromise = createFetchPromise(slot, "fetchListeners", listenerID, listBindingID, function (complete, item) { complete(itemForBinding(item, handle)); } ); defineCommonItemProperties(itemPromise, slot, handle); // Only implement retain and release methods if a notification handler has been supplied if (notificationHandler) { itemPromise.retain = function () { listBinding._retainItem(slot, listenerID); return itemPromise; }; itemPromise.release = function () { listBinding._releaseItem(handle); }; } return itemPromise; } bindingMap[listBindingID] = { notificationHandler: notificationHandler, notificationsSent: false, adjustCurrentSlot: adjustCurrentSlot, itemPromiseFromKnownSlot: itemPromiseFromKnownSlot, }; function itemPromiseFromSlot(slot) { var itemPromise; if (!released && slot) { itemPromise = itemPromiseFromKnownSlot(slot); } else { // Return a complete promise for a non-existent slot if (released) { itemPromise = new Promise(function () { }); itemPromise.cancel(); } else { itemPromise = Promise.wrap(null); } defineHandleProperty(itemPromise, null); // Only implement retain and release methods if a notification handler has been supplied if (notificationHandler) { itemPromise.retain = function () { return itemPromise; }; itemPromise.release = function () { }; } } moveCursor(slot); return itemPromise; } /// /// /// An interface that enables a client to read from the list and receive notifications for changes that affect /// those portions of the list that the client already read. IListBinding can also enumerate through lists /// that can change at any time. /// /// var listBinding = { _retainItem: function (slot, listenerID) { retainItem(slot, listenerID); }, _releaseItem: function (handle) { releaseItem(handle); }, jumpToItem: function (item) { /// /// /// Makes the specified item the current item. /// /// /// The IItem or IItemPromise to make the current item. /// /// /// An object that implements the IItemPromise interface and serves as a promise for the specified item. If /// the specified item is not in the list, the promise completes with a value of null. /// /// return itemPromiseFromSlot(item ? handleMap[item.handle] : null); }, current: function () { /// /// /// Retrieves the current item. /// /// /// An object that implements the IItemPromise interface and serves as a promise for the current item. /// If the cursor has moved past the start or end of the list, the promise completes with a value /// of null. If the current item has been deleted or moved, the promise returns an error. /// /// return itemPromiseFromSlot(slotCurrent); }, previous: function () { /// /// /// Retrieves the item before the current item and makes it the current item. /// /// /// An object that implements the IItemPromise interface and serves as a promise for the previous item. /// If the cursor moves past the start of the list, the promise completes with a value of null. /// /// return itemPromiseFromSlot(slotCurrent ? requestSlotBefore(slotCurrent) : null); }, next: function () { /// /// /// Retrieves the item after the current item and makes it the current item. /// /// /// An object that implements the IItemPromise interface and serves as a promise for the next item. If /// the cursor moves past the end of the list, the promise completes with a value of null. /// /// return itemPromiseFromSlot(slotCurrent ? requestSlotAfter(slotCurrent) : null); }, releaseItem: function (item) { /// /// /// Creates a request to stop change notfications for the specified item. The item is released only when the /// number of release calls matches the number of IItemPromise.retain calls. The number of release calls cannot /// exceed the number of retain calls. This method is present only if you passed an IListNotificationHandler /// to IListDataSource.createListBinding when it created this IListBinding. /// /// /// The IItem or IItemPromise to release. /// /// this._releaseItem(item.handle); }, release: function () { /// /// /// Releases resources, stops notifications, and cancels outstanding promises /// for all tracked items that this IListBinding returned. /// /// released = true; releaseSlotForCursor(slotCurrent); slotCurrent = null; for (var slot = slotsStart.next; slot !== slotsEnd;) { var slotNext = slot.next; var fetchListeners = slot.fetchListeners; for (var listenerID in fetchListeners) { var listener = fetchListeners[listenerID]; if (listener.listBindingID === listBindingID) { listener.promise.cancel(); delete fetchListeners[listenerID]; } } if (slot.bindingMap && slot.bindingMap[listBindingID]) { releaseSlotFromListBinding(slot); } slot = slotNext; } delete bindingMap[listBindingID]; } }; // Only implement each navigation method if the data adapter implements certain methods if (itemsFromStart || itemsFromIndex) { listBinding.first = function () { /// /// /// Retrieves the first item in the list and makes it the current item. /// /// /// An IItemPromise that serves as a promise for the requested item. /// If the list is empty, the Promise completes with a value of null. /// /// return itemPromiseFromSlot(requestSlotAfter(slotsStart)); }; } if (itemsFromEnd) { listBinding.last = function () { /// /// /// Retrieves the last item in the list and makes it the current item. /// /// /// An IItemPromise that serves as a promise for the requested item. /// If the list is empty, the Promise completes with a value of null. /// /// return itemPromiseFromSlot(requestSlotBefore(slotListEnd)); }; } if (itemsFromKey) { listBinding.fromKey = function (key, hints) { /// /// /// Retrieves the item with the specified key and makes it the current item. /// /// /// The key of the requested item. It must be a non-empty string. /// /// /// Domain-specific hints to the IListDataAdapter /// about the location of the item to improve retrieval time. /// /// /// An IItemPromise that serves as a promise for the requested item. /// If the list doesn't contain an item with the specified key, the Promise completes with a value of null. /// /// return itemPromiseFromSlot(slotFromKey(key, hints)); }; } if (itemsFromIndex || (itemsFromStart && itemsFromKey)) { listBinding.fromIndex = function (index) { /// /// /// Retrieves the item with the specified index and makes it the current item. /// /// /// A value greater than or equal to 0 that is the index of the item to retrieve. /// /// /// An IItemPromise that serves as a promise for the requested item. /// If the list doesn't contain an item with the specified index, the IItemPromise completes with a value of null. /// /// return itemPromiseFromSlot(slotFromIndex(index)); }; } if (itemsFromDescription) { listBinding.fromDescription = function (description) { /// /// /// Retrieves the item with the specified description and makes it the current item. /// /// /// The domain-specific description of the requested item, to be interpreted by the list data adapter. /// /// /// A Promise for the requested item. If the list doesn't contain an item with the specified description, /// the IItemPromise completes with a value of null. /// /// return itemPromiseFromSlot(slotFromDescription(description)); }; } return listBinding; }; this.invalidateAll = function () { /// /// /// Makes the data source refresh its cached items by re-requesting them from the data adapter. /// The data source generates notifications if the data has changed. /// /// /// A Promise that completes when the data has been completely refreshed and all change notifications have been /// sent. /// /// return requestRefresh(); }; // Create a helper which issues new promises for the result of the input promise // but have their cancelations ref-counted so that any given consumer canceling // their promise doesn't result in the incoming promise being canceled unless // all consumers are no longer interested in the result. // var countedCancelation = function (incomingPromise, dataSource) { var signal = new WinJS._Signal(); incomingPromise.then( function (v) { signal.complete(v); }, function (e) { signal.error(e); } ); var resultPromise = signal.promise.then(null, function (e) { if (e.name === "WinJS.UI.VirtualizedDataSource.resetCount") { getCountPromise = null; return incomingPromise = dataSource.getCount(); } return Promise.wrapError(e); }); var count = 0; var currentGetCountPromise = { get: function () { count++; return new Promise( function (c, e) { resultPromise.then(c, e); }, function () { if (--count === 0) { // when the count reaches zero cancel the incoming promise signal.promise.cancel() incomingPromise.cancel(); if (currentGetCountPromise === getCountPromise) { getCountPromise = null; } } } ); }, reset: function () { signal.error(new WinJS.ErrorFromName("WinJS.UI.VirtualizedDataSource.resetCount")); }, cancel: function () { // if explicitly asked to cancel the incoming promise signal.promise.cancel() incomingPromise.cancel(); if (currentGetCountPromise === getCountPromise) { getCountPromise = null; } } }; return currentGetCountPromise; } this.getCount = function () { /// /// /// Retrieves the number of items in the data source. /// /// if (listDataAdapter.getCount) { // Always do a fetch, even if there is a cached result // var that = this; return Promise.wrap().then(function () { if (editsInProgress || editsQueued) { return knownCount; } var requestPromise; if (!getCountPromise) { var relatedGetCountPromise; // Make a request for the count // requestPromise = listDataAdapter.getCount(); var synchronous; requestPromise.then( function () { if (getCountPromise === relatedGetCountPromise) { getCountPromise = null; } synchronous = true; }, function () { if (getCountPromise === relatedGetCountPromise) { getCountPromise = null; } synchronous = true; } ); // Every time we make a new request for the count we can consider the // countDelta to be invalidated // countDelta = 0; // Wrap the result in a cancelation counter which will block cancelation // of the outstanding promise unless all consumers cancel. // if (!synchronous) { relatedGetCountPromise = getCountPromise = countedCancelation(requestPromise, that); } } return getCountPromise ? getCountPromise.get() : requestPromise; }).then(function (count) { if (!isNonNegativeInteger(count) && count !== undefined) { throw new WinJS.ErrorFromName("WinJS.UI.ListDataSource.InvalidRequestedCountReturned", strings.invalidRequestedCountReturned); } if (count !== knownCount) { if (knownCount === CountResult.unknown) { knownCount = count; } else { changeCount(count); finishNotifications(); } } if (count === 0) { if (slotsStart.next !== slotListEnd || slotListEnd.next !== slotsEnd) { // A contradiction has been found beginRefresh(); } else if (slotsStart.lastInSequence) { // Now we know the list is empty mergeSequences(slotsStart); slotListEnd.index = 0; } } return count; }).then(null, function (error) { if (error.name === UI.CountError.noResponse) { // Report the failure, but still report last known count setStatus(DataSourceStatus.failure); return knownCount; } return WinJS.Promise.wrapError(error); }); } else { // If the data adapter doesn't support the count method, return the VirtualizedDataSource's // reckoning of the count. return Promise.wrap(knownCount); } }; if (itemsFromKey) { this.itemFromKey = function (key, hints) { /// /// /// Retrieves the item with the specified key. /// /// /// The key of the requested item. It must be a non-empty string. /// /// /// Domain-specific hints to IListDataAdapter about the location of the item /// to improve the retrieval time. /// /// /// A Promise for the requested item. If the list doesn't contain an item with the specified key, /// the Promise completes with a value of null. /// /// return itemDirectlyFromSlot(slotFromKey(key, hints)); }; } if (itemsFromIndex || (itemsFromStart && itemsFromKey)) { this.itemFromIndex = function (index) { /// /// /// Retrieves the item at the specified index. /// /// /// A value greater than or equal to zero that is the index of the requested item. /// /// /// A Promise for the requested item. If the list doesn't contain an item with the specified index, /// the Promise completes with a value of null. /// /// return itemDirectlyFromSlot(slotFromIndex(index)); }; } if (itemsFromDescription) { this.itemFromDescription = function (description) { /// /// /// Retrieves the item with the specified description. /// /// /// Domain-specific info that describes the item to retrieve, to be interpreted by the IListDataAdapter, /// /// /// A Promise for the requested item. If the list doesn't contain an item with the specified description, /// the Promise completes with a value of null. /// /// return itemDirectlyFromSlot(slotFromDescription(description)); }; } this.beginEdits = function () { /// /// /// Notifies the data source that a sequence of edits is about to begin. The data source calls /// IListNotificationHandler.beginNotifications and endNotifications each one time for a sequence of edits. /// /// editsInProgress = true; }; // Only implement each editing method if the data adapter implements the corresponding ListDataAdapter method if (listDataAdapter.insertAtStart) { this.insertAtStart = function (key, data) { /// /// /// Adds an item to the beginning of the data source. /// /// /// The key of the item to insert, if known; otherwise, null. /// /// /// The data for the item to add. /// /// /// A Promise that contains the IItem that was added or an EditError if an error occurred. /// /// // Add item to start of list, only notify if the first item was requested return insertItem( key, data, // slotInsertBefore, append (slotsStart.lastInSequence ? null : slotsStart.next), true, // applyEdit function () { return listDataAdapter.insertAtStart(key, data); } ); }; } if (listDataAdapter.insertBefore) { this.insertBefore = function (key, data, nextKey) { /// /// /// Inserts an item before another item. /// /// /// The key of the item to insert, if known; otherwise, null. /// /// /// The data for the item to insert. /// /// /// The key of an item in the data source. The new data is inserted before this item. /// /// /// A Promise that contains the IItem that was added or an EditError if an error occurred. /// /// var slotNext = getSlotForEdit(nextKey); // Add item before given item and send notification return insertItem( key, data, // slotInsertBefore, append slotNext, false, // applyEdit function () { return listDataAdapter.insertBefore(key, data, nextKey, adjustedIndex(slotNext)); } ); }; } if (listDataAdapter.insertAfter) { this.insertAfter = function (key, data, previousKey) { /// /// /// Inserts an item after another item. /// /// /// The key of the item to insert, if known; otherwise, null. /// /// /// The data for the item to insert. /// /// /// The key for an item in the data source. The new item is added after this item. /// /// /// A Promise that contains the IItem that was added or an EditError if an error occurred. /// /// var slotPrev = getSlotForEdit(previousKey); // Add item after given item and send notification return insertItem( key, data, // slotInsertBefore, append (slotPrev ? slotPrev.next : null), true, // applyEdit function () { return listDataAdapter.insertAfter(key, data, previousKey, adjustedIndex(slotPrev)); } ); }; } if (listDataAdapter.insertAtEnd) { this.insertAtEnd = function (key, data) { /// /// /// Adds an item to the end of the data source. /// /// /// The key of the item to insert, if known; otherwise, null. /// /// /// The data for the item to insert. /// /// /// A Promise that contains the IItem that was added or an EditError if an error occurred. /// /// // Add item to end of list, only notify if the last item was requested return insertItem( key, data, // slotInsertBefore, append (slotListEnd.firstInSequence ? null : slotListEnd), false, // applyEdit function () { return listDataAdapter.insertAtEnd(key, data); } ); }; } if (listDataAdapter.change) { this.change = function (key, newData) { /// /// /// Overwrites the data of the specified item. /// /// /// The key for the item to replace. /// /// /// The new data for the item. /// /// /// A Promise that contains the IItem that was updated or an EditError if an error occurred. /// /// var slot = getSlotForEdit(key); return new Promise(function (complete, error) { var itemOld; queueEdit( // applyEdit function () { return listDataAdapter.change(key, newData, adjustedIndex(slot)); }, EditType.change, complete, error, // keyUpdate null, // updateSlots function () { itemOld = slot.item; slot.itemNew = { key: key, data: newData }; if (itemOld) { changeSlot(slot); } else { completeFetchPromises(slot); } }, // undo function () { if (itemOld) { slot.itemNew = itemOld; changeSlot(slot); } else { beginRefresh(); } } ); }); }; } if (listDataAdapter.moveToStart) { this.moveToStart = function (key) { /// /// /// Moves the specified item to the beginning of the data source. /// /// /// The key of the item to move. /// /// /// A Promise that contains the IItem that was moved or an EditError if an error occurred. /// /// var slot = getSlotForEdit(key); return moveItem( slot, // slotMoveBefore, append slotsStart.next, true, // applyEdit function () { return listDataAdapter.moveToStart(key, adjustedIndex(slot)); } ); }; } if (listDataAdapter.moveBefore) { this.moveBefore = function (key, nextKey) { /// /// /// Moves the specified item before another item. /// /// /// The key of the item to move. /// /// /// The key of another item in the data source. The item specified by the key parameter /// is moved to a position immediately before this item. /// /// /// A Promise that contains the IItem that was moved or an EditError if an error occurred. /// /// var slot = getSlotForEdit(key), slotNext = getSlotForEdit(nextKey); return moveItem( slot, // slotMoveBefore, append slotNext, false, // applyEdit function () { return listDataAdapter.moveBefore(key, nextKey, adjustedIndex(slot), adjustedIndex(slotNext)); } ); }; } if (listDataAdapter.moveAfter) { this.moveAfter = function (key, previousKey) { /// /// /// Moves an item after another item. /// /// /// The key of the item to move. /// /// /// The key of another item in the data source. The item specified by the key parameter will /// is moved to a position immediately after this item. /// /// /// A Promise that contains the IItem that was moved or an EditError if an error occurred. /// /// var slot = getSlotForEdit(key), slotPrev = getSlotForEdit(previousKey); return moveItem( slot, // slotMoveBefore, append slotPrev.next, true, // applyEdit function () { return listDataAdapter.moveAfter(key, previousKey, adjustedIndex(slot), adjustedIndex(slotPrev)); } ); }; } if (listDataAdapter.moveToEnd) { this.moveToEnd = function (key) { /// /// /// Moves an item to the end of the data source. /// /// /// The key of the item to move. /// /// /// A Promise that contains the IItem that was moved or an EditError if an error occurred. /// /// var slot = getSlotForEdit(key); return moveItem( slot, // slotMoveBefore, append slotListEnd, false, // applyEdit function () { return listDataAdapter.moveToEnd(key, adjustedIndex(slot)); } ); }; } if (listDataAdapter.remove) { this.remove = function (key) { /// /// /// Removes an item from the data source. /// /// /// The key of the item to remove. /// /// /// A Promise that contains nothing if the operation was successful or an EditError if an error occurred. /// /// validateKey(key); var slot = keyMap[key]; return new Promise(function (complete, error) { var slotNext, firstInSequence, lastInSequence; queueEdit( // applyEdit function () { return listDataAdapter.remove(key, adjustedIndex(slot)); }, EditType.remove, complete, error, // keyUpdate null, // updateSlots function () { if (slot) { slotNext = slot.next; firstInSequence = slot.firstInSequence; lastInSequence = slot.lastInSequence; updateNewIndices(slot, -1); deleteSlot(slot, false); } }, // undo function () { if (slot) { reinsertSlot(slot, slotNext, !firstInSequence, !lastInSequence); updateNewIndices(slot, 1); sendInsertedNotification(slot); } } ); }); }; } this.endEdits = function () { /// /// /// Notifies the data source that a sequence of edits has ended. The data source will call /// IListNotificationHandler.beginNotifications and endNotifications once each for a sequence of edits. /// /// editsInProgress = false; completeEdits(); }; } // _baseDataSourceConstructor var VDS = WinJS.Class.define(function () { /// /// /// Use as a base class when defining a custom data source. Do not instantiate directly. /// /// /// Raised when the status of the VirtualizedDataSource changes between ready, waiting, and failure states. /// /// }, { _baseDataSourceConstructor: _baseDataSourceConstructor }, { // Static Members supportedForProcessing: false, }); WinJS.Class.mix(VDS, WinJS.Utilities.eventMixin); return VDS; }), }); var DataSourceStatus = WinJS.UI.DataSourceStatus, CountResult = WinJS.UI.CountResult, FetchError = WinJS.UI.FetchError, EditError = WinJS.UI.EditError; })(); // Group Data Source (function groupDataSourceInit() { "use strict"; WinJS.Namespace.define("WinJS.UI", { _GroupDataSource: WinJS.Namespace._lazy(function () { var UI = WinJS.UI; var Promise = WinJS.Promise, Scheduler = WinJS.Utilities.Scheduler; // Private statics function errorDoesNotExist() { return new WinJS.ErrorFromName(UI.FetchError.doesNotExist); } var batchSizeDefault = 101; function groupReady(group) { return group && group.firstReached && group.lastReached; } var ListNotificationHandler = WinJS.Class.define(function ListNotificationHandler_ctor(groupDataAdapter) { // Constructor this._groupDataAdapter = groupDataAdapter; }, { // Public methods beginNotifications: function () { }, // itemAvailable: not implemented inserted: function (itemPromise, previousHandle, nextHandle) { this._groupDataAdapter._inserted(itemPromise, previousHandle, nextHandle); }, changed: function (newItem, oldItem) { this._groupDataAdapter._changed(newItem, oldItem); }, moved: function (itemPromise, previousHandle, nextHandle) { this._groupDataAdapter._moved(itemPromise, previousHandle, nextHandle); }, removed: function (handle, mirage) { this._groupDataAdapter._removed(handle, mirage); }, countChanged: function (newCount, oldCount) { if (newCount === 0 && oldCount !== 0) { this._groupDataAdapter.invalidateGroups(); } }, indexChanged: function (handle, newIndex, oldIndex) { this._groupDataAdapter._indexChanged(handle, newIndex, oldIndex); }, endNotifications: function () { this._groupDataAdapter._endNotifications(); }, reload: function () { this._groupDataAdapter._reload(); } }, { supportedForProcessing: false, }); var GroupDataAdapter = WinJS.Class.define(function GroupDataAdapater_ctor(listDataSource, groupKey, groupData, options) { // Constructor this._listBinding = listDataSource.createListBinding(new ListNotificationHandler(this)); this._groupKey = groupKey; this._groupData = groupData; // _initializeState clears the count, so call this before processing the groupCountEstimate option this._initializeState(); this._batchSize = batchSizeDefault; this._count = null; if (options) { if (typeof options.groupCountEstimate === "number") { this._count = (options.groupCountEstimate < 0 ? null : Math.max(options.groupCountEstimate, 1)); } if (typeof options.batchSize === "number") { this._batchSize = options.batchSize + 1; } } if (this._listBinding.last) { this.itemsFromEnd = function (count) { var that = this; return this._fetchItems( // getGroup function () { return that._lastGroup; }, // mayExist function (failed) { if (failed) { return false; } var count = that._count; if (+count !== count) { return true; } if (count > 0) { return true; } }, // fetchInitialBatch function () { that._fetchBatch(that._listBinding.last(), that._batchSize - 1, 0); }, count - 1, 0 ); }; } }, { // Public members setNotificationHandler: function (notificationHandler) { this._listDataNotificationHandler = notificationHandler; }, // The ListDataSource should always compare these items by identity; in rare cases, it will do some unnecessary // rerendering, but at least fetching will not stringify items we already know to be valid and that we know // have not changed. compareByIdentity: true, // itemsFromStart: not implemented // itemsFromEnd: implemented in constructor itemsFromKey: function (key, countBefore, countAfter, hints) { var that = this; return this._fetchItems( // getGroup function () { return that._keyMap[key]; }, // mayExist function (failed) { var lastGroup = that._lastGroup; if (!lastGroup) { return true; } if (+lastGroup.index !== lastGroup.index) { return true; } }, // fetchInitialBatch function () { hints = hints || {}; var itemPromise = ( typeof hints.groupMemberKey === "string" && that._listBinding.fromKey ? that._listBinding.fromKey(hints.groupMemberKey) : typeof hints.groupMemberIndex === "number" && that._listBinding.fromIndex ? that._listBinding.fromIndex(hints.groupMemberIndex) : hints.groupMemberDescription !== undefined && that._listBinding.fromDescription ? that._listBinding.fromDescription(hints.groupMemberDescription) : that._listBinding.first() ); var fetchBefore = Math.floor(0.5 * (that._batchSize - 1)); that._fetchBatch(itemPromise, fetchBefore, that._batchSize - 1 - fetchBefore); }, countBefore, countAfter ); }, itemsFromIndex: function (index, countBefore, countAfter) { var that = this; return this._fetchItems( // getGroup function () { return that._indexMap[index]; }, // mayExist function (failed) { var lastGroup = that._lastGroup; if (!lastGroup) { return true; } if (+lastGroup.index !== lastGroup.index) { return true; } if (index <= lastGroup.index) { return true; } }, // fetchInitialBatch function () { that._fetchNextIndex(); }, countBefore, countAfter ); }, // itemsFromDescription: not implemented getCount: function () { if (this._lastGroup && typeof this._lastGroup.index === "number") { //#DBG _ASSERT(this._count === this._lastGroup.index); return Promise.wrap(this._count); } else { // Even if there's a current estimate for _count, consider this call to be a request to determine the true // count. var that = this; var countPromise = new Promise(function (complete) { var fetch = { initialBatch: function () { that._fetchNextIndex(); }, getGroup: function () { return null; }, countBefore: 0, countAfter: 0, complete: function (failed) { if (failed) { that._count = 0; } var count = that._count; if (typeof count === "number") { complete(count); return true; } else { return false; } } }; that._fetchQueue.push(fetch); if (!that._itemBatch) { //#DBG _ASSERT(that._fetchQueue[0] === fetch); that._continueFetch(fetch); } }); return (typeof this._count === "number" ? Promise.wrap(this._count) : countPromise); } }, invalidateGroups: function () { this._beginRefresh(); this._initializeState(); }, // Editing methods not implemented // Private members _initializeState: function () { this._count = null; this._indexMax = null; this._keyMap = {}; this._indexMap = {}; this._lastGroup = null; this._handleMap = {}; this._fetchQueue = []; this._itemBatch = null; this._itemsToFetch = 0; this._indicesChanged = false; }, _releaseItem: function (item) { delete this._handleMap[item.handle]; this._listBinding.releaseItem(item); }, _processBatch: function () { var previousItem = null, previousGroup = null, firstItemInGroup = null, itemsSinceStart = 0, failed = true; for (var i = 0; i < this._batchSize; i++) { var item = this._itemBatch[i], groupKey = (item ? this._groupKey(item) : null); if (item) { failed = false; } if (previousGroup && groupKey !== null && groupKey === previousGroup.key) { // This item is in the same group as the last item. The only thing to do is advance the group's // lastItem if this is definitely the last item that has been processed for the group. itemsSinceStart++; if (previousGroup.lastItem === previousItem) { if (previousGroup.lastItem.handle !== previousGroup.firstItem.handle) { this._releaseItem(previousGroup.lastItem); } previousGroup.lastItem = item; this._handleMap[item.handle] = previousGroup; previousGroup.size++; } else if (previousGroup.firstItem === item) { if (previousGroup.firstItem.handle !== previousGroup.lastItem.handle) { this._releaseItem(previousGroup.firstItem); } previousGroup.firstItem = firstItemInGroup; this._handleMap[firstItemInGroup.handle] = previousGroup; previousGroup.size += itemsSinceStart; } } else { var index = null; if (previousGroup) { previousGroup.lastReached = true; if (typeof previousGroup.index === "number") { index = previousGroup.index + 1; } } if (item) { // See if the current group has already been processed var group = this._keyMap[groupKey]; if (!group) { group = { key: groupKey, data: this._groupData(item), firstItem: item, lastItem: item, size: 1 }; this._keyMap[group.key] = group; this._handleMap[item.handle] = group; } if (i > 0) { group.firstReached = true; if (!previousGroup) { index = 0; } } if (typeof group.index !== "number" && typeof index === "number") { // Set the indices of as many groups as possible for (var group2 = group; group2; group2 = this._nextGroup(group2)) { //#DBG _ASSERT(typeof this._indexMap[index] !== "number"); group2.index = index; this._indexMap[index] = group2; index++; } this._indexMax = index; if (typeof this._count === "number" && !this._lastGroup && this._count <= this._indexMax) { this._count = this._indexMax + 1; } } firstItemInGroup = item; itemsSinceStart = 0; previousGroup = group; } else { if (previousGroup) { this._lastGroup = previousGroup; if (typeof previousGroup.index === "number") { this._count = (previousGroup.index + 1); } // Force a client refresh (which should be fast) to ensure that a countChanged notification is // sent. this._listDataNotificationHandler.invalidateAll(); previousGroup = null; } } } previousItem = item; } // See how many fetches have now completed var fetch; for (fetch = this._fetchQueue[0]; fetch && fetch.complete(failed) ; fetch = this._fetchQueue[0]) { this._fetchQueue.splice(0, 1); } // Continue work on the next fetch, if any if (fetch) { var that = this; // Avoid reentering _processBatch Scheduler.schedule(function () { that._continueFetch(fetch); }, Scheduler.Priority.normal, null, "WinJS.UI._GroupDataSource._continueFetch"); } else { this._itemBatch = null; } }, _processPromise: function (itemPromise, batchIndex) { itemPromise.retain(); this._itemBatch[batchIndex] = itemPromise; var that = this; itemPromise.then(function (item) { that._itemBatch[batchIndex] = item; if (--that._itemsToFetch === 0) { that._processBatch(); } }); }, _fetchBatch: function (itemPromise, countBefore, countAfter) { //#DBG _ASSERT(countBefore + 1 + countAfter === this._batchSize); this._itemBatch = new Array(this._batchSize); this._itemsToFetch = this._batchSize; this._processPromise(itemPromise, countBefore); var batchIndex; this._listBinding.jumpToItem(itemPromise); for (batchIndex = countBefore - 1; batchIndex >= 0; batchIndex--) { this._processPromise(this._listBinding.previous(), batchIndex); } this._listBinding.jumpToItem(itemPromise); for (batchIndex = countBefore + 1; batchIndex < this._batchSize; batchIndex++) { this._processPromise(this._listBinding.next(), batchIndex); } }, _fetchAdjacent: function (item, after) { // Batches overlap by one so group boundaries always fall within at least one batch this._fetchBatch( (this._listBinding.fromKey ? this._listBinding.fromKey(item.key) : this._listBinding.fromIndex(item.index)), (after ? 0 : this._batchSize - 1), (after ? this._batchSize - 1 : 0) ); }, _fetchNextIndex: function () { var groupHighestIndex = this._indexMap[this._indexMax - 1]; if (groupHighestIndex) { // We've already fetched some of the first items, so continue where we left off //#DBG _ASSERT(groupHighestIndex.firstReached); this._fetchAdjacent(groupHighestIndex.lastItem, true); } else { // Fetch one non-existent item before the list so _processBatch knows the start was reached this._fetchBatch(this._listBinding.first(), 1, this._batchSize - 2); } }, _continueFetch: function (fetch) { if (fetch.initialBatch) { fetch.initialBatch(); fetch.initialBatch = null; } else { var group = fetch.getGroup(); if (group) { var groupPrev, groupNext; if (!group.firstReached) { this._fetchAdjacent(group.firstItem, false); } else if (!group.lastReached) { this._fetchAdjacent(group.lastItem, true); } else if (fetch.countBefore > 0 && group.index !== 0 && !groupReady(groupPrev = this._previousGroup(group))) { this._fetchAdjacent((groupPrev && groupPrev.lastReached ? groupPrev.firstItem : group.firstItem), false); } else { groupNext = this._nextGroup(group); //#DBG _ASSERT(fetch.countAfter > 0 && !groupReady(groupNext)); this._fetchAdjacent((groupNext && groupNext.firstReached ? groupNext.lastItem : group.lastItem), true); } } else { // Assume we're searching for a key, index or the count by brute force this._fetchNextIndex(); } } }, _fetchComplete: function (group, countBefore, countAfter, firstRequest, complete, error) { if (groupReady(group)) { // Check if the minimal requirements for the request are met var groupPrev = this._previousGroup(group); if (firstRequest || groupReady(groupPrev) || group.index === 0 || countBefore === 0) { var groupNext = this._nextGroup(group); if (firstRequest || groupReady(groupNext) || this._lastGroup === group || countAfter === 0) { // Time to return the fetch results // Find the first available group to return (don't return more than asked for) var countAvailableBefore = 0, groupFirst = group; while (countAvailableBefore < countBefore) { groupPrev = this._previousGroup(groupFirst); if (!groupReady(groupPrev)) { break; } groupFirst = groupPrev; countAvailableBefore++; } // Find the last available group to return var countAvailableAfter = 0, groupLast = group; while (countAvailableAfter < countAfter) { groupNext = this._nextGroup(groupLast); if (!groupReady(groupNext)) { break; } groupLast = groupNext; countAvailableAfter++; } // Now create the items to return var len = countAvailableBefore + 1 + countAvailableAfter, items = new Array(len); for (var i = 0; i < len; i++) { var item = { key: groupFirst.key, data: groupFirst.data, firstItemKey: groupFirst.firstItem.key, groupSize: groupFirst.size }; var firstItemIndex = groupFirst.firstItem.index; if (typeof firstItemIndex === "number") { item.firstItemIndexHint = firstItemIndex; } items[i] = item; groupFirst = this._nextGroup(groupFirst); } var result = { items: items, offset: countAvailableBefore }; result.totalCount = ( typeof this._count === "number" ? this._count : UI.CountResult.unknown ); if (typeof group.index === "number") { result.absoluteIndex = group.index; } if (groupLast === this._lastGroup) { result.atEnd = true; } complete(result); return true; } } } return false; }, _fetchItems: function (getGroup, mayExist, fetchInitialBatch, countBefore, countAfter) { var that = this; return new Promise(function (complete, error) { var group = getGroup(), firstRequest = !group, failureCount = 0; function fetchComplete(failed) { var group2 = getGroup(); if (group2) { return that._fetchComplete(group2, countBefore, countAfter, firstRequest, complete, error); } else if (firstRequest && !mayExist(failed)) { error(errorDoesNotExist()); return true; } else if (failureCount > 2) { error(errorDoesNotExist()); return true; } else { // only consider consecutive failures if (failed) { failureCount++; } else { failureCount = 0; } // _continueFetch will switch to a brute force search return false; } } if (!fetchComplete()) { var fetch = { initialBatch: firstRequest ? fetchInitialBatch : null, getGroup: getGroup, countBefore: countBefore, countAfter: countAfter, complete: fetchComplete }; that._fetchQueue.push(fetch); if (!that._itemBatch) { //#DBG _ASSERT(that._fetchQueue[0] === fetch); that._continueFetch(fetch); } } }); }, _previousGroup: function (group) { if (group && group.firstReached) { this._listBinding.jumpToItem(group.firstItem); return this._handleMap[this._listBinding.previous().handle]; } else { return null; } }, _nextGroup: function (group) { if (group && group.lastReached) { this._listBinding.jumpToItem(group.lastItem); return this._handleMap[this._listBinding.next().handle]; } else { return null; } }, _invalidateIndices: function (group) { this._count = null; this._lastGroup = null; if (typeof group.index === "number") { this._indexMax = (group.index > 0 ? group.index : null); } // Delete the indices of this and all subsequent groups for (var group2 = group; group2 && typeof group2.index === "number"; group2 = this._nextGroup(group2)) { delete this._indexMap[group2.index]; group2.index = null; } }, _releaseGroup: function (group) { this._invalidateIndices(group); delete this._keyMap[group.key]; if (this._lastGroup === group) { this._lastGroup = null; } if (group.firstItem !== group.lastItem) { this._releaseItem(group.firstItem); } this._releaseItem(group.lastItem); }, _beginRefresh: function () { // Abandon all current fetches this._fetchQueue = []; if (this._itemBatch) { for (var i = 0; i < this._batchSize; i++) { var item = this._itemBatch[i]; if (item) { if (item.cancel) { item.cancel(); } this._listBinding.releaseItem(item); } } this._itemBatch = null; } this._itemsToFetch = 0; this._listDataNotificationHandler.invalidateAll(); }, _processInsertion: function (item, previousHandle, nextHandle) { var groupPrev = this._handleMap[previousHandle], groupNext = this._handleMap[nextHandle], groupKey = null; if (groupPrev) { // If an item in a different group from groupPrev is being inserted after it, no need to discard groupPrev if (!groupPrev.lastReached || previousHandle !== groupPrev.lastItem.handle || (groupKey = this._groupKey(item)) === groupPrev.key) { this._releaseGroup(groupPrev); } else if (this._lastGroup === groupPrev) { this._lastGroup = null; this._count = null; } this._beginRefresh(); } if (groupNext && groupNext !== groupPrev) { this._invalidateIndices(groupNext); // If an item in a different group from groupNext is being inserted before it, no need to discard groupNext if (!groupNext.firstReached || nextHandle !== groupNext.firstItem.handle || (groupKey !== null ? groupKey : this._groupKey(item)) === groupNext.key) { this._releaseGroup(groupNext); } this._beginRefresh(); } }, _processRemoval: function (handle) { var group = this._handleMap[handle]; if (group && (handle === group.firstItem.handle || handle === group.lastItem.handle)) { this._releaseGroup(group); this._beginRefresh(); } else if (this._itemBatch) { for (var i = 0; i < this._batchSize; i++) { var item = this._itemBatch[i]; if (item && item.handle === handle) { this._beginRefresh(); break; } } } }, _inserted: function (itemPromise, previousHandle, nextHandle) { var that = this; itemPromise.then(function (item) { that._processInsertion(item, previousHandle, nextHandle); }); }, _changed: function (newItem, oldItem) { // A change to the first item could affect the group item var group = this._handleMap[newItem.handle]; if (group && newItem.handle === group.firstItem.handle) { this._releaseGroup(group); this._beginRefresh(); } // If the item is now in a different group, treat this as a move if (this._groupKey(newItem) !== this._groupKey(oldItem)) { this._listBinding.jumpToItem(newItem); var previousHandle = this._listBinding.previous().handle; this._listBinding.jumpToItem(newItem); var nextHandle = this._listBinding.next().handle; this._processRemoval(newItem.handle); this._processInsertion(newItem, previousHandle, nextHandle); } }, _moved: function (itemPromise, previousHandle, nextHandle) { this._processRemoval(itemPromise.handle); var that = this; itemPromise.then(function (item) { that._processInsertion(item, previousHandle, nextHandle); }); }, _removed: function (handle, mirage) { // Mirage removals will just result in null items, which can be ignored if (!mirage) { this._processRemoval(handle); } }, _indexChanged: function (handle, newIndex, oldIndex) { if (typeof oldIndex === "number") { this._indicesChanged = true; } }, _endNotifications: function () { if (this._indicesChanged) { this._indicesChanged = false; // Update the group sizes for (var key in this._keyMap) { var group = this._keyMap[key]; if (group.firstReached && group.lastReached) { var newSize = group.lastItem.index + 1 - group.firstItem.index; if (!isNaN(newSize)) { group.size = newSize; } } } // Invalidate the client, since some firstItemIndexHint properties have probably changed this._beginRefresh(); } }, _reload: function () { this._initializeState(); this._listDataNotificationHandler.reload(); } }, { supportedForProcessing: false, }); return WinJS.Class.derive(UI.VirtualizedDataSource, function (listDataSource, groupKey, groupData, options) { var groupDataAdapter = new GroupDataAdapter(listDataSource, groupKey, groupData, options); this._baseDataSourceConstructor(groupDataAdapter); this.extensions = { invalidateGroups: function () { groupDataAdapter.invalidateGroups(); } }; }, { /* empty */ }, { supportedForProcessing: false, }); }) }); })(); // Grouped Item Data Source (function groupedItemDataSourceInit() { "use strict"; WinJS.Namespace.define("WinJS.UI", { computeDataSourceGroups: function (listDataSource, groupKey, groupData, options) { /// /// /// Returns a data source that adds group information to the items of another data source. The "groups" property /// of this data source evaluates to yet another data source that enumerates the groups themselves. /// /// /// The data source for the individual items to group. /// /// /// A callback function that takes an item in the list as an argument. The function is called /// for each item in the list and returns the group key for the item as a string. /// /// /// A callback function that takes an item in the IListDataSource as an argument. /// The function is called on one item in each group and returns /// an object that represents the header of that group. /// /// /// An object that can contain properties that specify additional options: /// /// groupCountEstimate: /// A Number value that is the initial estimate for the number of groups. If you specify -1, /// this function returns no result is until the actual number of groups /// has been determined. /// /// batchSize: /// A Number greater than 0 that specifies the number of items to fetch during each processing pass when /// searching for groups. (In addition to the number specified, one item from the previous batch /// is always included.) /// /// /// An IListDataSource that contains the items in the original data source and provides additional /// group info in a "groups" property. The "groups" property returns another /// IListDataSource that enumerates the different groups in the list. /// /// var groupedItemDataSource = Object.create(listDataSource); function createGroupedItem(item) { if (item) { var groupedItem = Object.create(item); groupedItem.groupKey = groupKey(item); if (groupData) { groupedItem.groupData = groupData(item); } return groupedItem; } else { return null; } } function createGroupedItemPromise(itemPromise) { var groupedItemPromise = Object.create(itemPromise); groupedItemPromise.then = function (onComplete, onError, onCancel) { return itemPromise.then(function (item) { return onComplete(createGroupedItem(item)); }, onError, onCancel); }; return groupedItemPromise; } groupedItemDataSource.createListBinding = function (notificationHandler) { var groupedNotificationHandler; if (notificationHandler) { groupedNotificationHandler = Object.create(notificationHandler); groupedNotificationHandler.inserted = function (itemPromise, previousHandle, nextHandle) { return notificationHandler.inserted(createGroupedItemPromise(itemPromise), previousHandle, nextHandle); }; groupedNotificationHandler.changed = function (newItem, oldItem) { return notificationHandler.changed(createGroupedItem(newItem), createGroupedItem(oldItem)); }; groupedNotificationHandler.moved = function (itemPromise, previousHandle, nextHandle) { return notificationHandler.moved(createGroupedItemPromise(itemPromise), previousHandle, nextHandle); }; } else { groupedNotificationHandler = null; } var listBinding = listDataSource.createListBinding(groupedNotificationHandler), groupedItemListBinding = Object.create(listBinding); var listBindingMethods = [ "first", "last", "fromDescription", "jumpToItem", "current" ]; for (var i = 0, len = listBindingMethods.length; i < len; i++) { (function (listBindingMethod) { if (listBinding[listBindingMethod]) { groupedItemListBinding[listBindingMethod] = function () { return createGroupedItemPromise(listBinding[listBindingMethod].apply(listBinding, arguments)); } } })(listBindingMethods[i]); } // The following methods should be fast if (listBinding.fromKey) { groupedItemListBinding.fromKey = function (key) { return createGroupedItemPromise(listBinding.fromKey(key)); }; } if (listBinding.fromIndex) { groupedItemListBinding.fromIndex = function (index) { return createGroupedItemPromise(listBinding.fromIndex(index)); }; } groupedItemListBinding.prev = function () { return createGroupedItemPromise(listBinding.prev()); }; groupedItemListBinding.next = function () { return createGroupedItemPromise(listBinding.next()); }; return groupedItemListBinding; }; var listDataSourceMethods = [ "itemFromKey", "itemFromIndex", "itemFromDescription", "insertAtStart", "insertBefore", "insertAfter", "insertAtEnd", "change", "moveToStart", "moveBefore", "moveAfter", "moveToEnd" // remove does not return an itemPromise ]; for (var i = 0, len = listDataSourceMethods.length; i < len; i++) { (function (listDataSourceMethod) { if (listDataSource[listDataSourceMethod]) { groupedItemDataSource[listDataSourceMethod] = function () { return createGroupedItemPromise(listDataSource[listDataSourceMethod].apply(listDataSource, arguments)); } } })(listDataSourceMethods[i]); } ["addEventListener", "removeEventListener", "dispatchEvent"].forEach(function (methodName) { if (listDataSource[methodName]) { groupedItemDataSource[methodName] = function () { return listDataSource[methodName].apply(listDataSource, arguments); } } }); var groupDataSource = null; Object.defineProperty(groupedItemDataSource, "groups", { get: function () { if (!groupDataSource) { groupDataSource = new WinJS.UI._GroupDataSource(listDataSource, groupKey, groupData, options); } return groupDataSource; }, enumerable: true, configurable: true }); return groupedItemDataSource; } }); })(); // Storage Item Data Source (function storageDataSourceInit(global) { "use strict"; WinJS.Namespace.define("WinJS.UI", { StorageDataSource: WinJS.Namespace._lazy(function () { var StorageDataAdapter = WinJS.Class.define(function StorageDataAdapter_ctor(query, options) { // Constructor msWriteProfilerMark("WinJS.UI.StorageDataSource:constructor,StartTM"); var mode = Windows.Storage.FileProperties.ThumbnailMode.singleItem, size = 256, flags = Windows.Storage.FileProperties.ThumbnailOptions.useCurrentScale, delayLoad = true, library; if (query === "Pictures") { mode = Windows.Storage.FileProperties.ThumbnailMode.picturesView; library = Windows.Storage.KnownFolders.picturesLibrary; size = 190; } else if (query === "Music") { mode = Windows.Storage.FileProperties.ThumbnailMode.musicView; library = Windows.Storage.KnownFolders.musicLibrary; size = 256; } else if (query === "Documents") { mode = Windows.Storage.FileProperties.ThumbnailMode.documentsView; library = Windows.Storage.KnownFolders.documentsLibrary; size = 40; } else if (query === "Videos") { mode = Windows.Storage.FileProperties.ThumbnailMode.videosView; library = Windows.Storage.KnownFolders.videosLibrary; size = 190; } if (!library) { this._query = query; } else { var queryOptions = new Windows.Storage.Search.QueryOptions; queryOptions.folderDepth = Windows.Storage.Search.FolderDepth.deep; queryOptions.indexerOption = Windows.Storage.Search.IndexerOption.useIndexerWhenAvailable; this._query = library.createFileQueryWithOptions(queryOptions); } if (options) { if (typeof options.mode === "number") { mode = options.mode; } if (typeof options.requestedThumbnailSize === "number") { size = Math.max(1, Math.min(options.requestedThumbnailSize, 1024)); } else { switch (mode) { case Windows.Storage.FileProperties.ThumbnailMode.picturesView: case Windows.Storage.FileProperties.ThumbnailMode.videosView: size = 190; break; case Windows.Storage.FileProperties.ThumbnailMode.documentsView: case Windows.Storage.FileProperties.ThumbnailMode.listView: size = 40; break; case Windows.Storage.FileProperties.ThumbnailMode.musicView: case Windows.Storage.FileProperties.ThumbnailMode.singleItem: size = 256; break; } } if (typeof options.thumbnailOptions === "number") { flags = options.thumbnailOptions; } if (typeof options.waitForFileLoad === "boolean") { delayLoad = !options.waitForFileLoad; } } this._loader = new Windows.Storage.BulkAccess.FileInformationFactory(this._query, mode, size, flags, delayLoad); this.compareByIdentity = false; this.firstDataRequest = true; msWriteProfilerMark("WinJS.UI.StorageDataSource:constructor,StopTM"); }, { // Public members setNotificationHandler: function (notificationHandler) { this._notificationHandler = notificationHandler; this._query.addEventListener("contentschanged", function () { notificationHandler.invalidateAll(); }); this._query.addEventListener("optionschanged", function () { notificationHandler.invalidateAll(); }); }, itemsFromEnd: function (count) { var that = this; msWriteProfilerMark("WinJS.UI.StorageDataSource:itemsFromEnd,info"); return this.getCount().then(function (totalCount) { if (totalCount === 0) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist)); } // Intentionally passing countAfter = 1 to go one over the end so that itemsFromIndex will // report the vector size since its known. return that.itemsFromIndex(totalCount - 1, Math.min(totalCount - 1, count - 1), 1); }); }, itemsFromIndex: function (index, countBefore, countAfter) { // don't allow more than 64 items to be retrieved at once if (countBefore + countAfter > 64) { countBefore = Math.min(countBefore, 32); countAfter = 64 - (countBefore + 1); } var first = (index - countBefore), count = (countBefore + 1 + countAfter); var that = this; // Fetch a minimum of 32 items on the first request for smoothness. Otherwise // listview displays 2 items first and then the rest of the page. if (that.firstDataRequest) { that.firstDataRequest = false; count = Math.max(count, 32); } function listener(ev) { that._notificationHandler.changed(that._item(ev.target)); }; var perfId = "WinJS.UI.StorageDataSource:itemsFromIndex(" + first + "-" + (first + count - 1) + ")"; msWriteProfilerMark(perfId + ",StartTM"); return this._loader.getItemsAsync(first, count).then(function (itemsVector) { var vectorSize = itemsVector.size; if (vectorSize <= countBefore) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist)); } var items = new Array(vectorSize); var localItemsVector = new Array(vectorSize); itemsVector.getMany(0, localItemsVector); for (var i = 0; i < vectorSize; i++) { items[i] = that._item(localItemsVector[i]); localItemsVector[i].addEventListener("propertiesupdated", listener); } var result = { items: items, offset: countBefore, absoluteIndex: index }; // set the totalCount only when we know it (when we retrieived fewer items than were asked for) if (vectorSize < count) { result.totalCount = first + vectorSize; } msWriteProfilerMark(perfId + ",StopTM"); return result; }); }, itemsFromDescription: function (description, countBefore, countAfter) { var that = this; msWriteProfilerMark("WinJS.UI.StorageDataSource:itemsFromDescription,info"); return this._query.findStartIndexAsync(description).then(function (index) { return that.itemsFromIndex(index, countBefore, countAfter); }); }, getCount: function () { msWriteProfilerMark("WinJS.UI.StorageDataSource:getCount,info"); return this._query.getItemCountAsync(); }, itemSignature: function (item) { return item.folderRelativeId; }, // compareByIdentity: set in constructor // itemsFromStart: not implemented // itemsFromKey: not implemented // insertAtStart: not implemented // insertBefore: not implemented // insertAfter: not implemented // insertAtEnd: not implemented // change: not implemented // moveToStart: not implemented // moveBefore: not implemented // moveAfter: not implemented // moveToEnd: not implemented // remove: not implemented // Private members _item: function (item) { return { key: item.path || item.folderRelativeId, data: item }; } }, { supportedForProcessing: false, }); return WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (query, options) { /// /// /// Creates a data source that enumerates an IStorageQueryResultBase. /// /// /// The object to enumerate. It must support IStorageQueryResultBase. /// /// /// An object that specifies options for the data source. This parameter is optional. It can contain these properties: /// /// mode: /// A Windows.Storage.FileProperties.ThumbnailMode - a value that specifies whether to request /// thumbnails and the type of thumbnails to request. /// /// requestedThumbnailSize: /// A Number that specifies the size of the thumbnails. /// /// thumbnailOptions: /// A Windows.Storage.FileProperties.ThumbnailOptions value that specifies additional options for the thumbnails. /// /// waitForFileLoad: /// If you set this to true, the data source returns items only after it loads their properties and thumbnails. /// /// /// this._baseDataSourceConstructor(new StorageDataAdapter(query, options)); }, { /* empty */ }, { loadThumbnail: function (item, image) { /// /// /// Returns a promise for an image element that completes when the full quality thumbnail of the provided item is drawn to the /// image element. /// /// /// The item to retrieve a thumbnail for. /// /// /// The image element to use. If not provided, a new image element is created. /// /// var thumbnailUpdateHandler, thumbnailPromise, shouldRespondToThumbnailUpdate = false; return new WinJS.Promise(function (complete, error, progress) { // Load a thumbnail if it exists. The promise completes when a full quality thumbnail is visible. var tagSupplied = (image ? true : false); var processThumbnail = function (thumbnail) { if (thumbnail) { var url = URL.createObjectURL(thumbnail, {oneTimeOnly: true}); // If this is the first version of the thumbnail we're loading, fade it in. if (!thumbnailPromise) { thumbnailPromise = item.loadImage(url, image).then(function (image) { // Wrapping the fadeIn call in a promise for the image returned by loadImage allows us to // pipe the result of loadImage to further chained promises. This is necessary because the // image element provided to loadThumbnail is optional, and loadImage will create an image // element if none is provided. return item.isOnScreen().then(function (visible) { var imagePromise; if (visible && tagSupplied) { imagePromise = WinJS.UI.Animation.fadeIn(image).then(function () { return image; }); } else { image.style.opacity = 1; imagePromise = WinJS.Promise.wrap(image); } return imagePromise; }); }); } // Otherwise, replace the existing version without animation. else { thumbnailPromise = thumbnailPromise.then(function (image) { return item.loadImage(url, image); }); } // If we have the full resolution thumbnail, we can cancel further updates and complete the promise // when current work is complete. if ((thumbnail.type != Windows.Storage.FileProperties.ThumbnailType.icon) && !thumbnail.returnedSmallerCachedSize) { msWriteProfilerMark("WinJS.UI.StorageDataSource:loadThumbnail complete,info"); item.data.removeEventListener("thumbnailupdated", thumbnailUpdateHandler); shouldRespondToThumbnailUpdate = false; thumbnailPromise = thumbnailPromise.then(function (image) { thumbnailUpdateHandler = null; thumbnailPromise = null; complete(image); }); } } }; thumbnailUpdateHandler = function (e) { // Ensure that a zombie update handler does not get invoked. if (shouldRespondToThumbnailUpdate) { processThumbnail(e.target.thumbnail); } }; item.data.addEventListener("thumbnailupdated", thumbnailUpdateHandler); shouldRespondToThumbnailUpdate = true; // If we already have a thumbnail we should render it now. processThumbnail(item.data.thumbnail); }, function () { item.data.removeEventListener("thumbnailupdated", thumbnailUpdateHandler); shouldRespondToThumbnailUpdate = false; thumbnailUpdateHandler = null; if (thumbnailPromise) { thumbnailPromise.cancel(); thumbnailPromise = null; } }); }, supportedForProcessing: false, }); }) }); })(); // Items Manager (function itemsManagerInit(global) { "use strict"; /*#DBG function dbg_stackTraceDefault() { return "add global function dbg_stackTrace to see stack traces"; } global.dbg_stackTrace = global.dbg_stackTrace || dbg_stackTraceDefault; #DBG*/ var markSupportedForProcessing = WinJS.Utilities.markSupportedForProcessing; WinJS.Namespace.define("WinJS.UI", { _normalizeRendererReturn: function (v) { if (v) { if (typeof v === "object" && v.element) { var elementPromise = WinJS.Promise.as(v.element); return elementPromise.then(function (e) { return { element: e, renderComplete: WinJS.Promise.as(v.renderComplete) } }); } else { var elementPromise = WinJS.Promise.as(v); return elementPromise.then(function (e) { return { element: e, renderComplete: WinJS.Promise.as() } }); } } else { return { element: null, renderComplete: WinJS.Promise.as() }; } }, simpleItemRenderer: function (f) { return markSupportedForProcessing(function (itemPromise, element) { return itemPromise.then(function (item) { return (item ? f(item, element) : null); }); }); } }); var Promise = WinJS.Promise; var Signal = WinJS._Signal; var Scheduler = WinJS.Utilities.Scheduler; var UI = WinJS.UI; // Private statics var strings = { get listDataSourceIsInvalid() { return WinJS.Resources._getWinJSString("ui/listDataSourceIsInvalid").value; }, get itemRendererIsInvalid() { return WinJS.Resources._getWinJSString("ui/itemRendererIsInvalid").value; }, get itemIsInvalid() { return WinJS.Resources._getWinJSString("ui/itemIsInvalid").value; }, get invalidItemsManagerCallback() { return WinJS.Resources._getWinJSString("ui/invalidItemsManagerCallback").value; } }; var imageLoader; var lastSort = new Date(); var minDurationBetweenImageSort = 64; // This optimization is good for a couple of reasons: // - It is a global optimizer, which means that all on screen images take precedence over all off screen images. // - It avoids resorting too frequently by only resorting when a new image loads and it has been at least 64 ms since // the last sort. // Also, it is worth noting that "sort" on an empty queue does no work (besides the function call). function compareImageLoadPriority(a, b) { var aon = false; var bon = false; // Currently isOnScreen is synchronous and fast for list view a.isOnScreen().then(function (v) { aon = v; }); b.isOnScreen().then(function (v) { bon = v; }); return (aon ? 0 : 1) - (bon ? 0 : 1); } var nextImageLoaderId = 0; var seenUrls = {}; var seenUrlsMRU = []; var SEEN_URLS_MAXSIZE = 250; var SEEN_URLS_MRU_MAXSIZE = 1000; function seenUrl(srcUrl) { if ((/^blob:/i).test(srcUrl)) { return; } seenUrls[srcUrl] = true; seenUrlsMRU.push(srcUrl); if (seenUrlsMRU.length > SEEN_URLS_MRU_MAXSIZE) { var mru = seenUrlsMRU; seenUrls = {}; seenUrlsMRU = []; for (var count = 0, i = mru.length - 1; i >= 0 && count < SEEN_URLS_MAXSIZE; i--) { var url = mru[i]; if (!seenUrls[url]) { seenUrls[url] = true; count++; } } } } // Exposing the seenUrl related members to use them in unit tests WinJS.Namespace.define("WinJS.UI", { _seenUrl: seenUrl, _getSeenUrls: function () { return seenUrls; }, _getSeenUrlsMRU: function () { return seenUrlsMRU; }, _seenUrlsMaxSize: SEEN_URLS_MAXSIZE, _seenUrlsMRUMaxSize: SEEN_URLS_MRU_MAXSIZE }); function loadImage(srcUrl, image, data) { var imageId = nextImageLoaderId++; imageLoader = imageLoader || new WinJS.UI._ParallelWorkQueue(6); return imageLoader.queue(function () { return new WinJS.Promise(function (c, e, p) { Scheduler.schedule(function (jobInfo) { if (!image) { image = document.createElement("img"); } var seen = seenUrls[srcUrl]; if (!seen) { jobInfo.setPromise(new WinJS.Promise(function (imageLoadComplete) { var tempImage = document.createElement("img"); var cleanup = function () { tempImage.removeEventListener("load", loadComplete, false); tempImage.removeEventListener("error", loadError, false); // One time use blob images are cleaned up as soon as they are not referenced by images any longer. // We set the image src before clearing the tempImage src to make sure the blob image is always // referenced. image.src = srcUrl; var currentDate = new Date(); if (currentDate - lastSort > minDurationBetweenImageSort) { lastSort = currentDate; imageLoader.sort(compareImageLoadPriority); } } var loadComplete = function () { imageLoadComplete(jobComplete); }; var loadError = function () { imageLoadComplete(jobError); }; var jobComplete = function () { seenUrl(srcUrl); cleanup(); c(image); }; var jobError = function () { cleanup(); e(image); }; tempImage.addEventListener("load", loadComplete, false); tempImage.addEventListener("error", loadError, false); tempImage.src = srcUrl; })); } else { seenUrl(srcUrl); image.src = srcUrl; c(image); } }, Scheduler.Priority.normal, null, "WinJS.UI._ImageLoader._image" + imageId); }); }, data); } function isImageCached(srcUrl) { return seenUrls[srcUrl]; } function defaultRenderer(item) { return document.createElement("div"); } // Type-checks a callback parameter, since a failure will be hard to diagnose when it occurs function checkCallback(callback, name) { if (typeof callback !== "function") { throw new WinJS.ErrorFromName("WinJS.UI.ItemsManager.CallbackIsInvalid", WinJS.Resources._formatString(strings.invalidItemsManagerCallback, name)); } } // Public definitions WinJS.Namespace.define("WinJS.UI", { _createItemsManager: WinJS.Namespace._lazy(function () { var ListNotificationHandler = WinJS.Class.define(function ListNotificationHandler_ctor(itemsManager) { // Constructor this._itemsManager = itemsManager; /*#DBG this._notificationsCount = 0; #DBG*/ }, { // Public methods beginNotifications: function () { /*#DBG if (this._notificationsCount !== 0) { throw new "ACK! Unbalanced beginNotifications call"; } this._notificationsCount++; #DBG*/ this._itemsManager._versionManager.beginNotifications(); this._itemsManager._beginNotifications(); }, // itemAvailable: not implemented inserted: function (itemPromise, previousHandle, nextHandle) { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._inserted(itemPromise, previousHandle, nextHandle); }, changed: function (newItem, oldItem) { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._changed(newItem, oldItem); }, moved: function (itemPromise, previousHandle, nextHandle) { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._moved(itemPromise, previousHandle, nextHandle); }, removed: function (handle, mirage) { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._removed(handle, mirage); }, countChanged: function (newCount, oldCount) { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._countChanged(newCount, oldCount); }, indexChanged: function (handle, newIndex, oldIndex) { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._indexChanged(handle, newIndex, oldIndex); }, affectedRange: function (range) { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._affectedRange(range); }, endNotifications: function () { /*#DBG if (this._notificationsCount !== 1) { throw new "ACK! Unbalanced endNotifications call"; } this._notificationsCount--; #DBG*/ this._itemsManager._versionManager.endNotifications(); this._itemsManager._endNotifications(); }, reload: function () { this._itemsManager._versionManager.receivedNotification(); this._itemsManager._reload(); } }, { // Static Members supportedForProcessing: false, }); var ItemsManager = WinJS.Class.define(function ItemsManager_ctor(listDataSource, itemRenderer, elementNotificationHandler, options) { // Constructor if (!listDataSource) { throw new WinJS.ErrorFromName("WinJS.UI.ItemsManager.ListDataSourceIsInvalid", strings.listDataSourceIsInvalid); } if (!itemRenderer) { throw new WinJS.ErrorFromName("WinJS.UI.ItemsManager.ItemRendererIsInvalid", strings.itemRendererIsInvalid); } this.$pipeline_callbacksMap = {}; this._listDataSource = listDataSource; this.dataSource = this._listDataSource; this._elementNotificationHandler = elementNotificationHandler; this._listBinding = this._listDataSource.createListBinding(new ListNotificationHandler(this)); if (options) { if (options.ownerElement) { this._ownerElement = options.ownerElement; } this._profilerId = options.profilerId; this._versionManager = options.versionManager || new WinJS.UI._VersionManager(); } this._indexInView = options && options.indexInView; this._itemRenderer = itemRenderer; this._viewCallsReady = options && options.viewCallsReady; // Map of (the uniqueIDs of) elements to records for items this._elementMap = {}; // Map of handles to records for items this._handleMap = {}; // Owner for use with jobs on the scheduler. Allows for easy cancellation of jobs during clean up. this._jobOwner = Scheduler.createOwnerToken(); // Boolean to track whether endNotifications needs to be called on the ElementNotificationHandler this._notificationsSent = false; // Only enable the lastItem method if the data source implements the itemsFromEnd method if (this._listBinding.last) { this.lastItem = function () { return this._elementForItem(this._listBinding.last()); }; } }, { _itemFromItemPromise: function (itemPromise) { return this._waitForElement(this._elementForItem(itemPromise)) }, // If stage 0 is not yet complete, caller is responsible for transitioning the item from stage 0 to stage 1 _itemFromItemPromiseThrottled: function (itemPromise) { return this._waitForElement(this._elementForItem(itemPromise, true)) }, _itemAtIndex: function (index) { /*#DBG var that = this; var startVersion = that._versionManager.version; #DBG*/ var itemPromise = this._itemPromiseAtIndex(index) var result = this._itemFromItemPromise(itemPromise)/*#DBG . then(function (v) { var rec = that._recordFromElement(v); var endVersion = that._versionManager.version; if (rec.item.index !== index) { throw "ACK! inconsistent index"; } if (startVersion !== endVersion) { throw "ACK! inconsistent version"; } if (WinJS.Utilities.data(v).itemData && WinJS.Utilities.data(v).itemData.itemsManagerRecord.item.index !== index) { throw "ACK! inconsistent itemData.index"; } return v; }) #DBG*/; return result.then(null, function (e) { itemPromise.cancel(); return WinJS.Promise.wrapError(e); }); }, _itemPromiseAtIndex: function (index) { /*#DBG var that = this; var startVersion = that._versionManager.version; if (that._versionManager.locked) { throw "ACK! Attempt to get an item while editing"; } #DBG*/ var itemPromise = this._listBinding.fromIndex(index); /*#DBG itemPromise.then(function (item) { var endVersion = that._versionManager.version; if (item.index !== index) { throw "ACK! inconsistent index"; } if (startVersion !== endVersion) { throw "ACK! inconsistent version"; } return item; }); #DBG*/ return itemPromise; }, _waitForElement: function (possiblePlaceholder) { var that = this; return new WinJS.Promise(function (c, e, p) { if (possiblePlaceholder) { if (!that.isPlaceholder(possiblePlaceholder)) { c(possiblePlaceholder); } else { var placeholderID = possiblePlaceholder.uniqueID; var callbacks = that.$pipeline_callbacksMap[placeholderID]; if (!callbacks) { that.$pipeline_callbacksMap[placeholderID] = [c]; } else { callbacks.push(c); } } } else { c(possiblePlaceholder); } }); }, _updateElement: function (newElement, oldElement) { var placeholderID = oldElement.uniqueID; var callbacks = this.$pipeline_callbacksMap[placeholderID]; if (callbacks) { delete this.$pipeline_callbacksMap[placeholderID]; callbacks.forEach(function (c) { c(newElement); }); } }, _firstItem: function () { return this._waitForElement(this._elementForItem(this._listBinding.first())); }, _lastItem: function () { return this._waitForElement(this._elementForItem(this._listBinding.last())); }, _previousItem: function (element) { this._listBinding.jumpToItem(this._itemFromElement(element)); return this._waitForElement(this._elementForItem(this._listBinding.previous())); }, _nextItem: function (element) { this._listBinding.jumpToItem(this._itemFromElement(element)); return this._waitForElement(this._elementForItem(this._listBinding.next())); }, _itemFromPromise: function (itemPromise) { return this._waitForElement(this._elementForItem(itemPromise)); }, isPlaceholder: function (item) { return !!this._recordFromElement(item).elementIsPlaceholder; }, itemObject: function (element) { return this._itemFromElement(element); }, release: function () { this._listBinding.release(); this._elementNotificationHandler = null; this._listBinding = null; this._jobOwner.cancelAll(); this._released = true; }, releaseItemPromise: function (itemPromise) { var handle = itemPromise.handle; var record = this._handleMap[handle]; if (!record) { // The item promise is not in our handle map so we didn't even try to render it yet. itemPromise.cancel(); } else { this._releaseRecord(record); } }, releaseItem: function (element) { var record = this._elementMap[element.uniqueID]; this._releaseRecord(record); }, _releaseRecord: function (record) { if (!record) { return; } /*#DBG if (record.released) { throw "ACK! Double release on item"; } #DBG*/ if (record.renderPromise) { record.renderPromise.cancel(); } if (record.itemPromise) { record.itemPromise.cancel(); } if (record.imagePromises) { record.imagePromises.forEach(function (promise) { promise.cancel(); }); } if (record.itemReadyPromise) { record.itemReadyPromise.cancel(); } if (record.renderComplete) { record.renderComplete.cancel(); } this._removeEntryFromElementMap(record.element); this._removeEntryFromHandleMap(record.itemPromise.handle, record); if (record.item) { this._listBinding.releaseItem(record.item); } /*#DBG record.released = true; if (record.updater) { throw "ACK! attempt to release item current held by updater"; } #DBG*/ }, refresh: function () { return this._listDataSource.invalidateAll(); }, // Private members _handlerToNotifyCaresAboutItemAvailable: function () { return !!(this._elementNotificationHandler && this._elementNotificationHandler.itemAvailable); }, _handlerToNotify: function () { if (!this._notificationsSent) { this._notificationsSent = true; if (this._elementNotificationHandler && this._elementNotificationHandler.beginNotifications) { this._elementNotificationHandler.beginNotifications(); } } return this._elementNotificationHandler; }, _defineIndexProperty: function (itemForRenderer, item, record) { record.indexObserved = false; Object.defineProperty(itemForRenderer, "index", { get: function () { record.indexObserved = true; return item.index; } }); }, _renderPlaceholder: function (record) { var itemForRenderer = {}; var elementPlaceholder = defaultRenderer(itemForRenderer); record.elementIsPlaceholder = true; return elementPlaceholder; }, _renderItem: function (itemPromise, record, callerThrottlesStage1) { var that = this; var indexInView = that._indexInView || function () { return true; }; var stage1Signal = new Signal(); var readySignal = new Signal(); var perfItemPromiseId = "_renderItem(" + record.item.index + "):itemPromise"; var stage0RunningSync = true; var stage0Ran = false; itemPromise.then(function (item) { stage0Ran = true; if (stage0RunningSync) { stage1Signal.complete(item); } }); stage0RunningSync = false; var itemForRendererPromise = stage1Signal.promise.then(function (item) { if (item) { var itemForRenderer = Object.create(item); // Derive a new item and override its index property, to track whether it is read that._defineIndexProperty(itemForRenderer, item, record); itemForRenderer.ready = readySignal.promise; itemForRenderer.isOnScreen = function () { return Promise.wrap(indexInView(item.index)); }; itemForRenderer.loadImage = function (srcUrl, image) { var loadImagePromise = loadImage(srcUrl, image, itemForRenderer); if (record.imagePromises) { record.imagePromises.push(loadImagePromise); } else { record.imagePromises = [loadImagePromise]; } return loadImagePromise; }; itemForRenderer.isImageCached = isImageCached; return itemForRenderer; } else { return WinJS.Promise.cancel; } }); function queueAsyncStage1() { itemPromise.then(function (item) { that._writeProfilerMark(perfItemPromiseId + ",StartTM"); stage1Signal.complete(item); that._writeProfilerMark(perfItemPromiseId + ",StopTM"); }); } if (!stage0Ran) { if (callerThrottlesStage1) { record.stage0 = itemPromise; record.startStage1 = function () { record.startStage1 = null; queueAsyncStage1(); } } else { queueAsyncStage1(); } } itemForRendererPromise.handle = itemPromise.handle; record.itemPromise = itemForRendererPromise; record.itemReadyPromise = readySignal.promise; record.readyComplete = false; // perfRendererWorkId = stage 1 rendering (if itemPromise is async) or stage 1+2 (if itemPromise is sync and ran inline) // perfItemPromiseId = stage 2 rendering only (should only be emitted if itemPromise was async) // perfItemReadyId = stage 3 rendering var perfRendererWorkId = "_renderItem(" + record.item.index + (stage0Ran ? "):syncItemPromise" : "):placeholder"); var perfItemReadyId = "_renderItem(" + record.item.index + "):itemReady"; this._writeProfilerMark(perfRendererWorkId + ",StartTM"); var rendererPromise = WinJS.Promise.as(that._itemRenderer(itemForRendererPromise, record.element)). then(WinJS.UI._normalizeRendererReturn). then(function (v) { if (that._released) { return WinJS.Promise.cancel; } itemForRendererPromise.then(function (item) { // Store pending ready callback off record so ScrollView can call it during realizePage. Otherwise // call it ourselves. record.pendingReady = function () { if (record.pendingReady) { record.pendingReady = null; record.readyComplete = true; that._writeProfilerMark(perfItemReadyId + ",StartTM"); readySignal.complete(item); that._writeProfilerMark(perfItemReadyId + ",StopTM"); } } if (!that._viewCallsReady) { var job = Scheduler.schedule(record.pendingReady, Scheduler.Priority.normal, record, "WinJS.UI._ItemsManager._pendingReady"); job.owner = that._jobOwner; } }); return v; }); this._writeProfilerMark(perfRendererWorkId + ",StopTM"); return rendererPromise; }, _replaceElement: function (record, elementNew) { /*#DBG if (!this._handleInHandleMap(record.item.handle)) { throw "ACK! replacing element not present in handle map"; } #DBG*/ this._removeEntryFromElementMap(record.element); record.element = elementNew; this._addEntryToElementMap(elementNew, record); }, _changeElement: function (record, elementNew, elementNewIsPlaceholder) { //#DBG _ASSERT(elementNew); record.renderPromise = null; var elementOld = record.element, itemOld = record.item; if (record.newItem) { record.item = record.newItem; record.newItem = null; } this._replaceElement(record, elementNew); if (record.item && record.elementIsPlaceholder && !elementNewIsPlaceholder) { record.elementDelayed = null; record.elementIsPlaceholder = false; this._updateElement(record.element, elementOld); if (this._handlerToNotifyCaresAboutItemAvailable()) { this._handlerToNotify().itemAvailable(record.element, elementOld); } } else { this._handlerToNotify().changed(elementNew, elementOld, itemOld); } }, _elementForItem: function (itemPromise, callerThrottlesStage1) { var handle = itemPromise.handle, record = this._recordFromHandle(handle, true), element; if (!handle) { return null; } if (record) { element = record.element; } else { // Create a new record for this item record = { item: itemPromise, itemPromise: itemPromise }; this._addEntryToHandleMap(handle, record); var that = this; var mirage = false; var synchronous = false; var renderPromise = that._renderItem(itemPromise, record, callerThrottlesStage1). then(function (v) { var elementNew = v.element; record.renderComplete = v.renderComplete; itemPromise.then(function (item) { record.item = item; if (!item) { mirage = true; element = null; } }); synchronous = true; record.renderPromise = null; if (elementNew) { if (element) { that._presentElements(record, elementNew); } else { element = elementNew; } } }); if (!mirage) { if (!synchronous) { record.renderPromise = renderPromise; } if (!element) { element = this._renderPlaceholder(record); } record.element = element; this._addEntryToElementMap(element, record); itemPromise.retain(); } } return element; }, _addEntryToElementMap: function (element, record) { /*#DBG if (WinJS.Utilities.data(element).itemsManagerRecord) { throw "ACK! Extra call to _addEntryToElementMap, ref counting error"; } WinJS.Utilities.data(element).itemsManagerRecord = record; #DBG*/ this._elementMap[element.uniqueID] = record; }, _removeEntryFromElementMap: function (element) { /*#DBG if (!WinJS.Utilities.data(element).itemsManagerRecord) { throw "ACK! Extra call to _removeEntryFromElementMap, ref counting error"; } WinJS.Utilities.data(element).removeElementMapRecord = WinJS.Utilities.data(element).itemsManagerRecord; WinJS.Utilities.data(element).removeEntryMapStack = dbg_stackTrace(); delete WinJS.Utilities.data(element).itemsManagerRecord; #DBG*/ delete this._elementMap[element.uniqueID]; }, _recordFromElement: function (element, ignoreFailure) { var record = this._elementMap[element.uniqueID]; if (!record) { /*#DBG var removeElementMapRecord = WinJS.Utilities.data(element).removeElementMapRecord; var itemsManagerRecord = WinJS.Utilities.data(element).itemsManagerRecord; #DBG*/ this._writeProfilerMark("_recordFromElement:ItemIsInvalidError,info"); throw new WinJS.ErrorFromName("WinJS.UI.ItemsManager.ItemIsInvalid", strings.itemIsInvalid); } return record; }, _addEntryToHandleMap: function (handle, record) { /*#DBG if (this._handleMap[handle]) { throw "ACK! Extra call to _addEntryToHandleMap, ref counting error"; } this._handleMapLeak = this._handleMapLeak || {}; this._handleMapLeak[handle] = { record: record, addHandleMapStack: dbg_stackTrace() }; #DBG*/ this._handleMap[handle] = record; }, _removeEntryFromHandleMap: function (handle, record) { /*#DBG if (!this._handleMap[handle]) { throw "ACK! Extra call to _removeEntryFromHandleMap, ref counting error"; } this._handleMapLeak[handle].removeHandleMapStack = dbg_stackTrace(); #DBG*/ delete this._handleMap[handle]; }, _handleInHandleMap: function (handle) { return !!this._handleMap[handle]; }, _recordFromHandle: function (handle, ignoreFailure) { var record = this._handleMap[handle]; if (!record && !ignoreFailure) { /*#DBG var leak = this._handleMapLeak[handle]; #DBG*/ throw new WinJS.ErrorFromName("WinJS.UI.ItemsManager.ItemIsInvalid", strings.itemIsInvalid); } return record; }, _foreachRecord: function (callback) { var records = this._handleMap; for (var property in records) { var record = records[property]; callback(record); } }, _itemFromElement: function (element) { return this._recordFromElement(element).item; }, _elementFromHandle: function (handle) { if (handle) { var record = this._recordFromHandle(handle, true); if (record && record.element) { return record.element; } } return null; }, _inserted: function (itemPromise, previousHandle, nextHandle) { this._handlerToNotify().inserted(itemPromise, previousHandle, nextHandle); }, _changed: function (newItem, oldItem) { if (!this._handleInHandleMap(oldItem.handle)) { return; } var record = this._recordFromHandle(oldItem.handle); //#DBG _ASSERT(record); if (record.renderPromise) { record.renderPromise.cancel(); } if (record.itemPromise) { record.itemPromise.cancel(); } if (record.imagePromises) { record.imagePromises.forEach(function (promise) { promise.cancel(); }); } if (record.itemReadyPromise) { record.itemReadyPromise.cancel(); } if (record.renderComplete) { record.renderComplete.cancel(); } record.newItem = newItem; var that = this; var newItemPromise = WinJS.Promise.as(newItem); newItemPromise.handle = record.itemPromise.handle; record.renderPromise = this._renderItem(newItemPromise, record). then(function (v) { record.renderComplete = v.renderComplete; that._changeElement(record, v.element, false); that._presentElements(record); }); }, _moved: function (itemPromise, previousHandle, nextHandle) { // no check for haveHandle, as we get move notification for items we // are "next" to, so we handle the "null element" cases below // var element = this._elementFromHandle(itemPromise.handle); var previous = this._elementFromHandle(previousHandle); var next = this._elementFromHandle(nextHandle); this._handlerToNotify().moved(element, previous, next, itemPromise); this._presentAllElements(); }, _removed: function (handle, mirage) { if (this._handleInHandleMap(handle)) { var element = this._elementFromHandle(handle); //#DBG _ASSERT(element); this._handlerToNotify().removed(element, mirage, handle); this.releaseItem(element); this._presentAllElements(); } else { this._handlerToNotify().removed(null, mirage, handle); } }, _countChanged: function (newCount, oldCount) { if (this._elementNotificationHandler && this._elementNotificationHandler.countChanged) { this._handlerToNotify().countChanged(newCount, oldCount); } }, _indexChanged: function (handle, newIndex, oldIndex) { var element; if (this._handleInHandleMap(handle)) { var record = this._recordFromHandle(handle); if (record.indexObserved) { if (!record.elementIsPlaceholder) { if (record.item.index !== newIndex) { if (record.renderPromise) { record.renderPromise.cancel(); } if (record.renderComplete) { record.renderComplete.cancel(); } var itemToRender = record.newItem || record.item; itemToRender.index = newIndex; var newItemPromise = WinJS.Promise.as(itemToRender); newItemPromise.handle = record.itemPromise.handle; var that = this; record.renderPromise = this._renderItem(newItemPromise, record). then(function (v) { record.renderComplete = v.renderComplete; that._changeElement(record, v.element, false); that._presentElements(record); }); } } else { this._changeElement(record, this._renderPlaceholder(record), true); } } element = record.element; } if (this._elementNotificationHandler && this._elementNotificationHandler.indexChanged) { this._handlerToNotify().indexChanged(element, newIndex, oldIndex); } }, _affectedRange: function (range) { if (this._elementNotificationHandler && this._elementNotificationHandler.updateAffectedRange) { this._handlerToNotify().updateAffectedRange(range); } }, _beginNotifications: function () { // accessing _handlerToNotify will force the call to beginNotifications on the client // this._externalBegin = true; var x = this._handlerToNotify(); }, _endNotifications: function () { if (this._notificationsSent) { this._notificationsSent = false; this._externalBegin = false; if (this._elementNotificationHandler && this._elementNotificationHandler.endNotifications) { this._elementNotificationHandler.endNotifications(); } } }, _reload: function () { if (this._elementNotificationHandler && this._elementNotificationHandler.reload) { this._elementNotificationHandler.reload(); } }, // Some functions may be called synchronously or asynchronously, so it's best to post _endNotifications to avoid // calling it prematurely. _postEndNotifications: function () { if (this._notificationsSent && !this._externalBegin && !this._endNotificationsPosted) { this._endNotificationsPosted = true; var that = this; Scheduler.schedule(function () { that._endNotificationsPosted = false; that._endNotifications(); }, Scheduler.Priority.high, null, "WinJS.UI._ItemsManager._postEndNotifications"); } }, _presentElement: function (record) { var elementOld = record.element; //#DBG _ASSERT(elementOld); // Finish modifying the slot before calling back into user code, in case there is a reentrant call this._replaceElement(record, record.elementDelayed); record.elementDelayed = null; record.elementIsPlaceholder = false; this._updateElement(record.element, elementOld); if (this._handlerToNotifyCaresAboutItemAvailable()) { this._handlerToNotify().itemAvailable(record.element, elementOld); } }, _presentElements: function (record, elementDelayed) { if (elementDelayed) { record.elementDelayed = elementDelayed; } this._listBinding.jumpToItem(record.item); if (record.elementDelayed) { this._presentElement(record); } this._postEndNotifications(); }, // Presents all delayed elements _presentAllElements: function () { var that = this; this._foreachRecord(function (record) { if (record.elementDelayed) { that._presentElement(record); } }); }, _writeProfilerMark: function (text) { var message = "WinJS.UI._ItemsManager:" + (this._profilerId ? (this._profilerId + ":") : ":") + text; msWriteProfilerMark(message); } }, { // Static Members supportedForProcessing: false, }); return function (dataSource, itemRenderer, elementNotificationHandler, options) { return new ItemsManager(dataSource, itemRenderer, elementNotificationHandler, options); }; }) }); })(this); (function parallelWorkQueueInit(global) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _ParallelWorkQueue : WinJS.Namespace._lazy(function () { return WinJS.Class.define(function ParallelWorkQueue_ctor(maxRunning) { var workIndex = 0; var workItems = {}; var workQueue = []; maxRunning = maxRunning || 3; var running = 0; var processing = 0; function runNext() { running--; // if we have fallen out of this loop, then we know we are already // async, so "post" is OK. If we are still in the loop, then the // loop will continue to run, so we don't need to "post" or // recurse. This avoids stack overflow in the sync case. // if (!processing) { WinJS.Utilities.Scheduler.schedule(run, WinJS.Utilities.Scheduler.Priority.normal, null, "WinJS._ParallelWorkQueue.runNext"); } } function run() { processing++; for (; running < maxRunning; running++) { var next; var nextWork; do { next = workQueue.shift(); nextWork = next && workItems[next]; } while (next && !nextWork); if (nextWork) { delete workItems[next] try { nextWork().then(runNext, runNext); } catch (err) { // this will only get hit if there is a queued item that // fails to return something that conforms to the Promise // contract // runNext(); } } else { break; } } processing--; } function queue(f, data, first) { var id = "w" + (workIndex++); var workPromise; return new WinJS.Promise( function (c, e, p) { var w = function () { workPromise = f().then(c, e, p); return workPromise; }; w.data = data; workItems[id] = w; if (first) { workQueue.unshift(id); } else { workQueue.push(id); } run(); }, function () { delete workItems[id]; if (workPromise) { workPromise.cancel(); } } ); } this.sort = function (f) { workQueue.sort(function (a, b) { a = workItems[a]; b = workItems[b]; return a === undefined && b === undefined ? 0 : a === undefined ? 1 : b === undefined ? -1 : f(a.data, b.data); }); }; this.queue = queue; }, { /* empty */ }, { supportedForProcessing: false, }); }) }); })(this); (function versionManagerInit(global) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _VersionManager: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function _VersionManager_ctor() { this._unlocked = new WinJS._Signal(); this._unlocked.complete(); }, { _cancelCount: 0, _notificationCount: 0, _updateCount: 0, _version: 0, // This should be used generally for all logic that should be suspended while data changes are happening // locked: { get: function () { return this._notificationCount !== 0 || this._updateCount !== 0; } }, // this should only be accessed by the update logic in ListViewImpl.js // noOutstandingNotifications: { get: function () { return this._notificationCount === 0; } }, version: { get: function () { return this._version; } }, unlocked: { get: function () { return this._unlocked.promise; } }, _dispose: function () { if (this._unlocked) { this._unlocked.cancel(); this._unlocked = null; } }, beginUpdating: function () { this._checkLocked(); /*#DBG if (this._updateCount !== 0) { throw "ACK! incorrect begin/endUpdating pair on version manager"; } #DBG*/ this._updateCount++; }, endUpdating: function() { this._updateCount--; /*#DBG if (this._updateCount < 0) { throw "ACK! incorrect begin/endUpdating pair on version manager"; } #DBG*/ this._checkUnlocked(); }, beginNotifications: function () { this._checkLocked(); this._notificationCount++; }, endNotifications: function () { this._notificationCount--; /*#DBG if (this._notificationCount < 0) { throw "ACK! incorrect begin/endNotifications pair on version manager"; } #DBG*/ this._checkUnlocked(); }, _checkLocked: function () { if (!this.locked) { this._dispose(); this._unlocked = new WinJS._Signal(); } }, _checkUnlocked: function () { if (!this.locked) { this._unlocked.complete(); } }, receivedNotification: function () { this._version++; if (this._cancel) { var cancel = this._cancel; this._cancel = null; cancel.forEach(function (p) { p && p.cancel(); }); } }, cancelOnNotification: function (promise) { if (!this._cancel) { this._cancel = []; this._cancelCount = 0; } this._cancel[this._cancelCount++] = promise; return this._cancelCount - 1; }, clearCancelOnNotification: function (token) { if (this._cancel) { delete this._cancel[token]; } } }, { supportedForProcessing: false, }); }) }); })(); (function flipperInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Displays a collection, such as a set of photos, one item at a time. /// /// /// /// ]]> /// Raised when the number of items in the itemDataSource changes. /// Raised when a FlipView page becomes visible or invisible. /// Raised when the FlipView flips to a page. /// Raised when the FlipView flips to a page and its renderer function completes. /// The entire FlipView control. /// The general class for all FlipView navigation buttons. /// The left navigation button. /// The right navigation button. /// The top navigation button. /// The bottom navigation button. /// /// /// FlipView: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; var utilities = WinJS.Utilities; var Scheduler = WinJS.Utilities.Scheduler; var animation = WinJS.UI.Animation; // Class names var navButtonClass = "win-navbutton", flipViewClass = "win-flipview", navButtonLeftClass = "win-navleft", navButtonRightClass = "win-navright", navButtonTopClass = "win-navtop", navButtonBottomClass = "win-navbottom"; // Aria labels var previousButtonLabel = "Previous", nextButtonLabel = "Next"; var buttonFadeDelay = 3000, avoidTrapDelay = 500, leftArrowGlyph = "", rightArrowGlyph = "", topArrowGlyph = "", bottomArrowGlyph = "", animationMoveDelta = 40; function flipViewPropertyChanged(list) { var that = list[0].target.winControl; if (that && that instanceof WinJS.UI.FlipView) { if (list.some(function (record) { if (record.attributeName === "dir") { return true; } else if (record.attributeName === "style") { return (that._cachedStyleDir != record.target.style.direction); } else { return false; } })) { that._cachedStyleDir = that._flipviewDiv.style.direction; that._rtl = window.getComputedStyle(that._flipviewDiv, null).direction === "rtl"; that._setupOrientation(); } } } function flipviewResized(e) { var that = e.srcElement && e.srcElement.winControl; if (that && that instanceof WinJS.UI.FlipView) { msWriteProfilerMark("WinJS.UI.FlipView:resize,StartTM"); that._resize(); } } var strings = { get badAxis() { return WinJS.Resources._getWinJSString("ui/badAxis").value; }, get badCurrentPage() { return WinJS.Resources._getWinJSString("ui/badCurrentPage").value; }, get noitemsManagerForCount() { return WinJS.Resources._getWinJSString("ui/noitemsManagerForCount").value; }, get badItemSpacingAmount() { return WinJS.Resources._getWinJSString("ui/badItemSpacingAmount").value; }, get navigationDuringStateChange() { return WinJS.Resources._getWinJSString("ui/flipViewNavigationDuringStateChange").value; }, get panningContainerAriaLabel() { return WinJS.Resources._getWinJSString("ui/flipViewPanningContainerAriaLabel").value; } }; var FlipView = WinJS.Class.define(function FlipView_ctor(element, options) { /// /// /// Creates a new FlipView. /// /// /// The DOM element that hosts the control. /// /// /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". For example, to provide a handler for the pageselected event, /// add a property named "onpageselected" to the options object and set its value to the event handler. /// This parameter is optional. /// /// /// The new FlipView control. /// /// msWriteProfilerMark("WinJS.UI.FlipView:constructor,StartTM"); this._disposed = false; element = element || document.createElement("div"); var horizontal = true, dataSource = null, itemRenderer = WinJS.UI._trivialHtmlRenderer, initialIndex = 0, itemSpacing = 0; if (options) { // flipAxis parameter checking. Must be a string, either "horizontal" or "vertical" if (options.orientation) { if (typeof options.orientation === "string") { switch (options.orientation.toLowerCase()) { case "horizontal": horizontal = true; break; case "vertical": horizontal = false; break; } } } if (options.currentPage) { initialIndex = options.currentPage >> 0; initialIndex = initialIndex < 0 ? 0 : initialIndex; } if (options.itemDataSource) { dataSource = options.itemDataSource; } if (options.itemTemplate) { itemRenderer = this._getItemRenderer(options.itemTemplate); } if (options.itemSpacing) { itemSpacing = options.itemSpacing >> 0; itemSpacing = itemSpacing < 0 ? 0 : itemSpacing; } } if (!dataSource) { var list = new WinJS.Binding.List(); dataSource = list.dataSource; } utilities.empty(element); this._initializeFlipView(element, horizontal, dataSource, itemRenderer, initialIndex, itemSpacing); element.winControl = this; WinJS.Utilities.addClass(element, "win-disposable"); // Call _setOption with eventsOnly flag on WinJS.UI._setOptions(this, options, true); this._avoidTrappingTime = 0; this._windowWheelHandlerBound = this._windowWheelHandler.bind(this); window.addEventListener('wheel', this._windowWheelHandlerBound); msWriteProfilerMark("WinJS.UI.FlipView:constructor,StopTM"); }, { // Public methods dispose: function FlipView_dispose() { /// /// /// Disposes this FlipView. /// /// msWriteProfilerMark("WinJS.UI.FlipView:dispose,StopTM"); if (this._disposed) { return; } window.removeEventListener('wheel', this._windowWheelHandlerBound); this._disposed = true; this._pageManager.dispose(); this._itemsManager.release(); this.itemDataSource = null; }, next: function FlipView_next() { /// /// /// Navigates to the next item. /// /// /// true if the FlipView begins navigating to the next page; /// false if the FlipView is at the last page or is in the middle of another navigation animation. /// /// msWriteProfilerMark("WinJS.UI.FlipView:next,info"); var cancelAnimationCallback = this._nextAnimation ? null : this._cancelDefaultAnimation; return this._navigate(true, cancelAnimationCallback); }, previous: function FlipView_previous() { /// /// /// Navigates to the previous item. /// /// /// true if FlipView begins navigating to the previous page; /// false if the FlipView is already at the first page or is in the middle of another navigation animation. /// /// msWriteProfilerMark("WinJS.UI.FlipView:prev,info"); var cancelAnimationCallback = this._prevAnimation ? null : this._cancelDefaultAnimation; return this._navigate(false, cancelAnimationCallback); }, /// element: { get: function () { return this._flipviewDiv; } }, /// /// Gets or sets the index of the currently displayed page. The minimum value is 0 and the maximum value is one less than the total number of items returned by the data source. /// currentPage: { get: function () { return this._getCurrentIndex(); }, set: function (index) { msWriteProfilerMark("WinJS.UI.FlipView:set_currentPage,info"); if (this._pageManager._notificationsEndedSignal) { var that = this; this._pageManager._notificationsEndedSignal.promise.done(function () { that._pageManager._notificationsEndedSignal = null; that.currentPage = index; }); return; } if (this._animating && !this._cancelAnimation()) { return; } index = index >> 0; index = index < 0 ? 0 : index; if (this._refreshTimer) { this._indexAfterRefresh = index; } else { if (this._pageManager._cachedSize > 0) { index = Math.min(this._pageManager._cachedSize - 1, index); } else if (this._pageManager._cachedSize === 0) { index = 0; } var that = this; if (this._jumpingToIndex === index) { return; } var clearJumpToIndex = function () { that._jumpingToIndex = null; }; this._jumpingToIndex = index; var jumpAnimation = (this._jumpAnimation ? this._jumpAnimation : this._defaultAnimation.bind(this)), cancelAnimationCallback = (this._jumpAnimation ? null : this._cancelDefaultAnimation), completionCallback = function () { that._completeJump(); }; this._pageManager.startAnimatedJump(index, cancelAnimationCallback, completionCallback). then(function (elements) { if (elements) { that._animationsStarted(); var currElement = elements.oldPage.pageRoot; var newCurrElement = elements.newPage.pageRoot; that._contentDiv.appendChild(currElement); that._contentDiv.appendChild(newCurrElement); that._completeJumpPending = true; jumpAnimation(currElement, newCurrElement). then(function () { if (that._completeJumpPending) { completionCallback(); msWriteProfilerMark("WinJS.UI.FlipView:set_currentPage.animationComplete,info"); } }).done(clearJumpToIndex, clearJumpToIndex); } else { clearJumpToIndex(); } }, clearJumpToIndex); } } }, /// /// Gets or sets the layout orientation of the FlipView, horizontal or vertical. /// orientation: { get: function () { return this._axisAsString(); }, set: function (orientation) { msWriteProfilerMark("WinJS.UI.FlipView:set_orientation,info"); var horizontal = orientation === "horizontal"; if (horizontal !== this._horizontal) { this._horizontal = horizontal; this._setupOrientation(); this._pageManager.setOrientation(this._horizontal); } } }, /// /// Gets or sets the data source that provides the FlipView with items to display. /// The FlipView displays one item at a time, each on its own page. /// itemDataSource: { get: function () { return this._dataSource; }, set: function (dataSource) { msWriteProfilerMark("WinJS.UI.FlipView:set_itemDataSource,info"); this._dataSourceAfterRefresh = dataSource || new WinJS.Binding.List().dataSource; this._refresh(); } }, /// /// Gets or sets a WinJS.Binding.Template or a function that defines the HTML for each item's page. /// itemTemplate: { get: function () { return this._itemRenderer; }, set: function (itemTemplate) { msWriteProfilerMark("WinJS.UI.FlipView:set_itemTemplate,info"); this._itemRendererAfterRefresh = this._getItemRenderer(itemTemplate); this._refresh(); } }, /// /// Gets or sets the spacing between items, in pixels. /// itemSpacing: { get: function () { return this._pageManager.getItemSpacing(); }, set: function (spacing) { msWriteProfilerMark("WinJS.UI.FlipView:set_itemSpacing,info"); spacing = spacing >> 0; spacing = spacing < 0 ? 0 : spacing; this._pageManager.setItemSpacing(spacing); } }, count: function FlipView_count() { /// /// /// Returns the number of items in the FlipView object's itemDataSource. /// /// /// A Promise that contains the number of items in the list /// or WinJS.UI.CountResult.unknown if the count is unavailable. /// /// msWriteProfilerMark("WinJS.UI.FlipView:count,info"); var that = this; return new WinJS.Promise(function (complete, error) { if (that._itemsManager) { if (that._pageManager._cachedSize === WinJS.UI.CountResult.unknown || that._pageManager._cachedSize >= 0) { complete(that._pageManager._cachedSize); } else { that._dataSource.getCount().then(function (count) { that._pageManager._cachedSize = count; complete(count); }); } } else { error(thisWinUI.FlipView.noitemsManagerForCount); } }); }, setCustomAnimations: function FlipView_setCustomAnimations(animations) { /// /// /// Sets custom animations for the FlipView to use when navigating between pages. /// /// /// An object containing up to three fields, one for each navigation action: next, previous, and jump /// Each of those fields must be a function with this signature: function (outgoingPage, incomingPage). /// This function returns a WinJS.Promise object that completes once the animations are finished. /// If a field is null or undefined, the FlipView reverts to its default animation for that action. /// /// msWriteProfilerMark("WinJS.UI.FlipView:setCustomAnimations,info"); if (animations.next !== undefined) { this._nextAnimation = animations.next; } if (animations.previous !== undefined) { this._prevAnimation = animations.previous; } if (animations.jump !== undefined) { this._jumpAnimation = animations.jump; } }, forceLayout: function FlipView_forceLayout() { /// /// /// Forces the FlipView to update its layout. /// Use this function when making the FlipView visible again after its style.display property had been set to "none". /// /// msWriteProfilerMark("WinJS.UI.FlipView:forceLayout,info"); this._pageManager.resized(); }, // Private members _initializeFlipView: function FlipView_initializeFlipView(element, horizontal, dataSource, itemRenderer, initialIndex, itemSpacing) { this._flipviewDiv = element; utilities.addClass(this._flipviewDiv, flipViewClass); this._contentDiv = document.createElement("div"); this._panningDivContainer = document.createElement("div"); this._panningDivContainer.className = "win-surface"; this._panningDiv = document.createElement("div"); this._prevButton = document.createElement("button"); this._nextButton = document.createElement("button"); this._horizontal = horizontal; this._dataSource = dataSource; this._itemRenderer = itemRenderer; this._itemsManager = null; this._pageManager = null; var accName = this._flipviewDiv.getAttribute("aria-label"); if (!accName) { this._flipviewDiv.setAttribute("aria-label", ""); } this._flipviewDiv.setAttribute("role", "listbox"); if (!this._flipviewDiv.style.overflow) { this._flipviewDiv.style.overflow = "hidden"; } this._contentDiv.style.position = "relative"; this._contentDiv.style.zIndex = 0; this._contentDiv.style.width = "100%"; this._contentDiv.style.height = "100%"; this._panningDiv.style.position = "relative"; this._panningDivContainer.style.position = "relative"; this._panningDivContainer.style.width = "100%"; this._panningDivContainer.style.height = "100%"; this._panningDivContainer.setAttribute("role", "group"); this._panningDivContainer.setAttribute("aria-label", strings.panningContainerAriaLabel); this._contentDiv.appendChild(this._panningDivContainer); this._flipviewDiv.appendChild(this._contentDiv); this._panningDiv.style.width = "100%"; this._panningDiv.style.height = "100%"; this._setupOrientation(); function setUpButton(button) { button.setAttribute("aria-hidden", true); button.style.visibility = "hidden"; button.style.opacity = 0.0; button.tabIndex = -1; button.style.zIndex = 1000; } setUpButton(this._prevButton); setUpButton(this._nextButton); this._prevButton.setAttribute("aria-label", previousButtonLabel); this._nextButton.setAttribute("aria-label", nextButtonLabel); this._prevButton.setAttribute("type", "button"); this._nextButton.setAttribute("type", "button"); this._panningDivContainer.appendChild(this._panningDiv); this._contentDiv.appendChild(this._prevButton); this._contentDiv.appendChild(this._nextButton); var that = this; this._itemsManagerCallback = { // Callbacks for itemsManager inserted: function FlipView_inserted(itemPromise, previousHandle, nextHandle) { that._itemsManager._itemFromPromise(itemPromise).then(function (element) { var previous = that._itemsManager._elementFromHandle(previousHandle); var next = that._itemsManager._elementFromHandle(nextHandle); that._pageManager.inserted(element, previous, next, true); }); }, countChanged: function FlipView_countChanged(newCount, oldCount) { that._pageManager._cachedSize = newCount; // Don't fire the datasourcecountchanged event when there is a state transition if (oldCount !== WinJS.UI.CountResult.unknown) { that._fireDatasourceCountChangedEvent(); } }, changed: function FlipView_changed(newElement, oldElement) { that._pageManager.changed(newElement, oldElement); }, moved: function FlipView_moved(element, prev, next, itemPromise) { var elementReady = function (element) { //#DBG _ASSERT(element); that._pageManager.moved(element, prev, next); }; // If we haven't instantiated this item yet, do so now if (!element) { that._itemsManager._itemFromPromise(itemPromise).then(elementReady); } else { elementReady(element); } }, removed: function FlipView_removed(element, mirage) { if (element) { that._pageManager.removed(element, mirage, true); } }, knownUpdatesComplete: function FlipView_knownUpdatesComplete() { }, beginNotifications: function FlipView_beginNotifications() { that._cancelAnimation(); that._pageManager.notificationsStarted(); }, endNotifications: function FlipView_endNotifications() { that._pageManager.notificationsEnded(); }, itemAvailable: function FlipView_itemAvailable(real, placeholder) { that._pageManager.itemRetrieved(real, placeholder); }, reload: function FlipView_reload() { that._pageManager.reload(); } }; if (this._dataSource) { this._itemsManager = thisWinUI._createItemsManager(this._dataSource, this._itemRenderer, this._itemsManagerCallback, { ownerElement: this._flipviewDiv }); } this._pageManager = new thisWinUI._FlipPageManager(this._flipviewDiv, this._panningDiv, this._panningDivContainer, this._itemsManager, itemSpacing, { hidePreviousButton: function () { that._hasPrevContent = false; that._fadeOutButton("prev"); that._prevButton.setAttribute("aria-hidden", true); }, showPreviousButton: function () { that._hasPrevContent = true; that._fadeInButton("prev"); that._prevButton.setAttribute("aria-hidden", false); }, hideNextButton: function () { that._hasNextContent = false; that._fadeOutButton("next"); that._nextButton.setAttribute("aria-hidden", true); }, showNextButton: function () { that._hasNextContent = true; that._fadeInButton("next"); that._nextButton.setAttribute("aria-hidden", false); } }); this._pageManager.initialize(initialIndex, this._horizontal); this._dataSource.getCount().then(function (count) { that._pageManager._cachedSize = count; }); this._prevButton.addEventListener("click", function () { that.previous(); }, false); this._nextButton.addEventListener("click", function () { that.next(); }, false); new MutationObserver(flipViewPropertyChanged).observe(this._flipviewDiv, { attributes: true, attributeFilter: ["dir", "style"] }); this._cachedStyleDir = this._flipviewDiv.style.direction; this._flipviewDiv.addEventListener("mselementresize", flipviewResized); this._contentDiv.addEventListener("mouseleave", function () { that._mouseInViewport = false; }, false); var PT_TOUCH = MSPointerEvent.MSPOINTER_TYPE_TOUCH || "touch"; function handleShowButtons(e) { if (e.pointerType !== PT_TOUCH) { that._touchInteraction = false; if (e.screenX === that._lastMouseX && e.screenY === that._lastMouseY) { return; } that._lastMouseX = e.screenX; that._lastMouseY = e.screenY; that._mouseInViewport = true; that._fadeInButton("prev"); that._fadeInButton("next"); that._fadeOutButtons(); } } this._contentDiv.addEventListener("pointermove", handleShowButtons, false); this._contentDiv.addEventListener("pointerdown", function (e) { if (e.pointerType === PT_TOUCH) { that._mouseInViewport = false; that._touchInteraction = true; that._fadeOutButtons(true); } else { that._touchInteraction = false; if (!that._isInteractive(e.srcElement)) { // Disable the default behavior of the mouse wheel button to avoid auto-scroll if ((e.buttons & 4) !== 0) { e.stopPropagation(); e.preventDefault(); } } } }, false); this._contentDiv.addEventListener("pointerup", function (e) { if (e.pointerType !== PT_TOUCH) { that._touchInteraction = false; } }, false); this._panningDivContainer.addEventListener("scroll", function () { that._scrollPosChanged(); }, false); this._panningDiv.addEventListener("deactivate", function (event) { if (!that._touchInteraction) { that._fadeOutButtons(); } }, true); // When an element is removed and inserted, its scroll position gets reset to 0 (and no onscroll event is generated). This is a major problem // for the flipview thanks to the fact that we 1) Do a lot of inserts/removes of child elements, and 2) Depend on our scroll location being right to // display the right stuff. The page manager preserves scroll location. When a flipview element is reinserted, it'll fire DOMNodeInserted and we can reset // its scroll location there. // This event handler won't be hit in IE8. this._flipviewDiv.addEventListener("DOMNodeInserted", function (event) { if (event.target === that._flipviewDiv) { that._pageManager.resized(); } }, false); this._flipviewDiv.addEventListener("keydown", function (event) { function isInteractive(element) { if (element.parentNode) { var matches = element.parentNode.querySelectorAll(".win-interactive, .win-interactive *"); for (var i = 0, len = matches.length; i < len; i++) { if (matches[i] === element) { return true; } } } return false; } var cancelBubbleIfHandled = true; if (!that._isInteractive(event.srcElement)) { var Key = utilities.Key, handled = false; if (that._horizontal) { switch (event.keyCode) { case Key.leftArrow: (that._rtl ? that.next() : that.previous()); handled = true; break; case Key.pageUp: that.previous(); handled = true; break; case Key.rightArrow: (that._rtl ? that.previous() : that.next()); handled = true; break; case Key.pageDown: that.next(); handled = true; break; // Prevent scrolling pixel by pixel, but let the event bubble up case Key.upArrow: case Key.downArrow: handled = true; cancelBubbleIfHandled = false; break; } } else { switch (event.keyCode) { case Key.upArrow: case Key.pageUp: that.previous(); handled = true; break; case Key.downArrow: case Key.pageDown: that.next(); handled = true; break; case Key.space: handled = true; break; } } switch (event.keyCode) { case Key.home: that.currentPage = 0; handled = true; break; case Key.end: if (that._pageManager._cachedSize > 0) { that.currentPage = that._pageManager._cachedSize - 1; } handled = true; break; } if (handled) { event.preventDefault(); event.cancelBubble = cancelBubbleIfHandled; return true; } } }, false); }, _windowWheelHandler: function FlipView_windowWheelHandler(ev) { // When you are using the mouse wheel to scroll a horizontal area such as a WinJS.UI.Hub and one of the sections // has a WinJS.UI.FlipView you may get stuck on that item. This logic is to allow a scroll event to skip the flipview's // overflow scroll div and instead go to the parent scroller. We only skip the scroll wheel event for a fixed amount of time var wheelWithinFlipper = ev.srcElement && (this._flipviewDiv.contains(ev.srcElement) || this._flipviewDiv === ev.srcElement); var that = this; var now = performance.now(); var withinAvoidTime = this._avoidTrappingTime > now; if (!wheelWithinFlipper || withinAvoidTime) { this._avoidTrappingTime = now + avoidTrapDelay; } if (wheelWithinFlipper && withinAvoidTime) { this._panningDivContainer.style["overflow-x"] = "hidden"; this._panningDivContainer.style["overflow-y"] = "hidden"; setImmediate(function () { // Avoid being stuck between items that._pageManager._ensureCentered(); if (that._horizontal) { that._panningDivContainer.style["overflow-x"] = "scroll"; that._panningDivContainer.style["overflow-y"] = "hidden"; } else { that._panningDivContainer.style["overflow-y"] = "scroll"; that._panningDivContainer.style["overflow-x"] = "hidden"; } }); } }, _isInteractive: function FlipView_isInteractive(element) { if (element.parentNode) { var matches = element.parentNode.querySelectorAll(".win-interactive, .win-interactive *"); for (var i = 0, len = matches.length; i < len; i++) { if (matches[i] === element) { return true; } } } return false; }, _refreshHandler: function FlipView_refreshHandler() { var dataSource = this._dataSourceAfterRefresh || this._dataSource, renderer = this._itemRendererAfterRefresh || this._itemRenderer, initialIndex = this._indexAfterRefresh || 0; this._setDatasource(dataSource, renderer, initialIndex); this._dataSourceAfterRefresh = null; this._itemRendererAfterRefresh = null; this._indexAfterRefresh = 0; this._refreshTimer = false; }, _refresh: function FlipView_refresh() { if (!this._refreshTimer) { var that = this; this._refreshTimer = true; // Batch calls to _refresh Scheduler.schedule(function FlipView_refreshHandler() { if (that._refreshTimer && !that._disposed) { that._refreshHandler(); } }, Scheduler.Priority.high, null, "WinJS.UI.FlipView._refreshHandler"); } }, _getItemRenderer: function FlipView_getItemRenderer(itemTemplate) { var itemRenderer = null; if (typeof itemTemplate === "function") { var itemPromise = new WinJS.Promise(function (c, e, p) { }); var itemTemplateResult = itemTemplate(itemPromise); if (itemTemplateResult.element) { if (typeof itemTemplateResult.element === "object" && typeof itemTemplateResult.element.then === "function") { // This renderer returns a promise to an element itemRenderer = function (itemPromise) { var elementRoot = document.createElement("div"); elementRoot.className = "win-template"; WinJS.Utilities.markDisposable(elementRoot); return { element: elementRoot, renderComplete: itemTemplate(itemPromise).element.then(function (element) { elementRoot.appendChild(element); }) }; }; } else { // This renderer already returns a placeholder itemRenderer = itemTemplate; } } else { // Return a renderer that has return a placeholder itemRenderer = function (itemPromise) { var elementRoot = document.createElement("div"); elementRoot.className = "win-template"; WinJS.Utilities.markDisposable(elementRoot); // The pagecompleted event relies on this elementRoot // to ensure that we are still looking at the same // item after the render completes. return { element: elementRoot, renderComplete: itemPromise.then(function (item) { return WinJS.Promise.as(itemTemplate(itemPromise)).then(function (element) { elementRoot.appendChild(element); }); }) }; } }; } else if (typeof itemTemplate === "object") { itemRenderer = itemTemplate.renderItem; } return itemRenderer; }, _navigate: function FlipView_navigate(goForward, cancelAnimationCallback) { if (WinJS.validation && this._refreshTimer) { throw new WinJS.ErrorFromName("WinJS.UI.FlipView.NavigationDuringStateChange", strings.navigationDuringStateChange); } if (!this._animating) { this._animatingForward = goForward; } this._goForward = goForward; if (this._animating && !this._cancelAnimation()) { return false; } var that = this; var customAnimation = (goForward ? this._nextAnimation : this._prevAnimation), animation = (customAnimation ? customAnimation : this._defaultAnimation.bind(this)), completionCallback = function (goForward) { that._completeNavigation(goForward); }, elements = this._pageManager.startAnimatedNavigation(goForward, cancelAnimationCallback, completionCallback); if (elements) { this._animationsStarted(); var outgoingElement = elements.outgoing.pageRoot, incomingElement = elements.incoming.pageRoot; this._contentDiv.appendChild(outgoingElement); this._contentDiv.appendChild(incomingElement); this._completeNavigationPending = true; animation(outgoingElement, incomingElement).then(function () { if (that._completeNavigationPending) { completionCallback(that._goForward); } }).done(); return true; } else { return false; } }, _cancelDefaultAnimation: function FlipView_cancelDefaultAnimation(outgoingElement, incomingElement) { // Cancel the fadeOut animation outgoingElement.style.opacity = 0; // Cancel the enterContent animation incomingElement.style.animationName = ""; incomingElement.style.opacity = 1; }, _cancelAnimation: function FlipView_cancelAnimation() { if (this._pageManager._navigationAnimationRecord && this._pageManager._navigationAnimationRecord.completionCallback) { var cancelCallback = this._pageManager._navigationAnimationRecord.cancelAnimationCallback; if (cancelCallback) { cancelCallback = cancelCallback.bind(this); } if (this._pageManager._navigationAnimationRecord && this._pageManager._navigationAnimationRecord.elementContainers) { var outgoingPage = this._pageManager._navigationAnimationRecord.elementContainers[0], incomingPage = this._pageManager._navigationAnimationRecord.elementContainers[1], outgoingElement = outgoingPage.pageRoot, incomingElement = incomingPage.pageRoot; // Invoke the function that will cancel the animation if (cancelCallback) { cancelCallback(outgoingElement, incomingElement); } // Invoke the completion function after cancelling the animation this._pageManager._navigationAnimationRecord.completionCallback(this._animatingForward); return true; } } return false; }, _completeNavigation: function FlipView_completeNavigation(goForward) { if (this._disposed) { return; } this._pageManager._resizing = false; if (this._pageManager._navigationAnimationRecord && this._pageManager._navigationAnimationRecord.elementContainers) { var outgoingPage = this._pageManager._navigationAnimationRecord.elementContainers[0], incomingPage = this._pageManager._navigationAnimationRecord.elementContainers[1], outgoingElement = outgoingPage.pageRoot, incomingElement = incomingPage.pageRoot; if (outgoingElement.parentNode) { outgoingElement.parentNode.removeChild(outgoingElement); } if (incomingElement.parentNode) { incomingElement.parentNode.removeChild(incomingElement); } this._pageManager.endAnimatedNavigation(goForward, outgoingPage, incomingPage); this._fadeOutButtons(); this._scrollPosChanged(); this._pageManager._ensureCentered(true); this._animationsFinished(); } this._completeNavigationPending = false; }, _completeJump: function FlipView_completeJump() { if (this._disposed) { return; } this._pageManager._resizing = false; if (this._pageManager._navigationAnimationRecord && this._pageManager._navigationAnimationRecord.elementContainers) { var outgoingPage = this._pageManager._navigationAnimationRecord.elementContainers[0], incomingPage = this._pageManager._navigationAnimationRecord.elementContainers[1], outgoingElement = outgoingPage.pageRoot, incomingElement = incomingPage.pageRoot; if (outgoingElement.parentNode) { outgoingElement.parentNode.removeChild(outgoingElement); } if (incomingElement.parentNode) { incomingElement.parentNode.removeChild(incomingElement); } this._pageManager.endAnimatedJump(outgoingPage, incomingPage); this._animationsFinished(); } this._completeJumpPending = false; }, _resize: function FlipView_resize() { this._pageManager.resized(); }, _setCurrentIndex: function FlipView_setCurrentIndex(index) { return this._pageManager.jumpToIndex(index); }, _getCurrentIndex: function FlipView_getCurrentIndex() { return this._pageManager.currentIndex(); }, _setDatasource: function FlipView_setDatasource(source, template, index) { if (this._animating) { this._cancelAnimation(); } var initialIndex = 0; if (index !== undefined) { initialIndex = index; } this._dataSource = source; this._itemRenderer = template; var oldItemsManager = this._itemsManager; this._itemsManager = thisWinUI._createItemsManager(this._dataSource, this._itemRenderer, this._itemsManagerCallback, { ownerElement: this._flipviewDiv }); this._dataSource = this._itemsManager.dataSource; var that = this; this._dataSource.getCount().then(function (count) { that._pageManager._cachedSize = count; }); this._pageManager.setNewItemsManager(this._itemsManager, initialIndex); oldItemsManager && oldItemsManager.release(); }, _fireDatasourceCountChangedEvent: function FlipView_fireDatasourceCountChangedEvent() { var that = this; Scheduler.schedule(function FlipView_dispatchDataSourceCountChangedEvent() { var event = document.createEvent("Event"); event.initEvent(thisWinUI.FlipView.datasourceCountChangedEvent, true, true); msWriteProfilerMark("WinJS.UI.FlipView:dataSourceCountChangedEvent,info"); that._flipviewDiv.dispatchEvent(event); }, Scheduler.Priority.normal, null, "WinJS.UI.FlipView._dispatchDataSourceCountChangedEvent"); }, _scrollPosChanged: function FlipView_scrollPosChanged() { this._pageManager.scrollPosChanged(); }, _axisAsString: function FlipView_axisAsString() { return (this._horizontal ? "horizontal" : "vertical"); }, _setupOrientation: function FlipView_setupOrientation() { if (this._horizontal) { this._panningDivContainer.style["overflow-x"] = "scroll"; this._panningDivContainer.style["overflow-y"] = "hidden"; var rtl = window.getComputedStyle(this._flipviewDiv, null).direction === "rtl"; this._rtl = rtl; if (rtl) { this._prevButton.className = navButtonClass + " " + navButtonRightClass; this._nextButton.className = navButtonClass + " " + navButtonLeftClass; } else { this._prevButton.className = navButtonClass + " " + navButtonLeftClass; this._nextButton.className = navButtonClass + " " + navButtonRightClass; } this._prevButton.innerHTML = (rtl ? rightArrowGlyph : leftArrowGlyph); this._nextButton.innerHTML = (rtl ? leftArrowGlyph : rightArrowGlyph); } else { this._panningDivContainer.style["overflow-y"] = "scroll"; this._panningDivContainer.style["overflow-x"] = "hidden"; this._prevButton.className = navButtonClass + " " + navButtonTopClass; this._nextButton.className = navButtonClass + " " + navButtonBottomClass; this._prevButton.innerHTML = topArrowGlyph; this._nextButton.innerHTML = bottomArrowGlyph; } this._panningDivContainer.style["-ms-overflow-style"] = "none"; }, _fadeInButton: function FlipView_fadeInButton(button, forceShow) { if (this._mouseInViewport || forceShow) { if (button === "next" && this._hasNextContent) { if (this._nextButtonAnimation) { this._nextButtonAnimation.cancel(); this._nextButtonAnimation = null; } this._nextButton.style.visibility = "visible"; this._nextButtonAnimation = this._fadeInFromCurrentValue(this._nextButton); } else if (button === "prev" && this._hasPrevContent) { if (this._prevButtonAnimation) { this._prevButtonAnimation.cancel(); this._prevButtonAnimation = null; } this._prevButton.style.visibility = "visible"; this._prevButtonAnimation = this._fadeInFromCurrentValue(this._prevButton); } } }, _fadeOutButton: function FlipView_fadeOutButton(button) { var that = this; if (button === "next") { if (this._nextButtonAnimation) { this._nextButtonAnimation.cancel(); this._nextButtonAnimation = null; } this._nextButtonAnimation = animation.fadeOut(this._nextButton). then(function () { that._nextButton.style.visibility = "hidden"; }); return this._nextButtonAnimation; } else { if (this._prevButtonAnimation) { this._prevButtonAnimation.cancel(); this._prevButtonAnimation = null; } this._prevButtonAnimation = animation.fadeOut(this._prevButton). then(function () { that._prevButton.style.visibility = "hidden"; }); return this._prevButtonAnimation; } }, _fadeOutButtons: function FlipView_fadeOutButtons(immediately) { if (this._buttonFadePromise) { this._buttonFadePromise.cancel(); this._buttonFadePromise = null; } var that = this; this._buttonFadePromise = (immediately ? WinJS.Promise.wrap() : WinJS.Promise.timeout(buttonFadeDelay)).then(function () { that._fadeOutButton("prev"); that._fadeOutButton("next"); that._buttonFadePromise = null; }); }, _animationsStarted: function FlipView_animationsStarted() { this._animating = true; }, _animationsFinished: function FlipView_animationsFinished() { this._animating = false; }, _defaultAnimation: function FlipView_defaultAnimation(curr, next) { var incomingPageMove = {}; next.style.left = "0px"; next.style.top = "0px"; next.style.opacity = 0.0; var pageDirection = ((curr.itemIndex > next.itemIndex) ? -animationMoveDelta : animationMoveDelta); incomingPageMove.left = (this._horizontal ? (this._rtl ? -pageDirection : pageDirection) : 0) + "px"; incomingPageMove.top = (this._horizontal ? 0 : pageDirection) + "px"; var fadeOutPromise = animation.fadeOut(curr), enterContentPromise = animation.enterContent(next, [incomingPageMove], { mechanism: "transition" }); return WinJS.Promise.join([fadeOutPromise, enterContentPromise]); }, _fadeInFromCurrentValue: function FlipView_fadeInFromCurrentValue(shown) { // Intentionally not using the PVL fadeIn animation because we don't want // to start always from 0 in some cases return thisWinUI.executeTransition( shown, { property: "opacity", delay: 0, duration: 167, timing: "linear", to: 1 }); } }); // Statics / Events FlipView.datasourceCountChangedEvent = "datasourcecountchanged"; FlipView.pageVisibilityChangedEvent = "pagevisibilitychanged"; FlipView.pageSelectedEvent = "pageselected"; FlipView.pageCompletedEvent = "pagecompleted"; WinJS.Class.mix(FlipView, WinJS.Utilities.createEventProperties( FlipView.datasourceCountChangedEvent, FlipView.pageVisibilityChangedEvent, FlipView.pageSelectedEvent, FlipView.pageCompletedEvent)); WinJS.Class.mix(FlipView, WinJS.UI.DOMEventMixin); return FlipView; }) }); })(WinJS); (function flipperPageManagerInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { // Definition of our private utility _FlipPageManager: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; // Utilities are private and global pointer will be deleted so we need to cache it locally var utilities = WinJS.Utilities; var Scheduler = WinJS.Utilities.Scheduler; var animations = WinJS.UI.Animation; var leftBufferAmount = 50, itemSelectedEventDelay = 250; var strings = { get badCurrentPage() { return WinJS.Resources._getWinJSString("ui/badCurrentPage").value; } }; function isFlipper(element) { var control = element.winControl; if (control && control instanceof WinJS.UI.FlipView) { return true; } return false; } function flipperPropertyChanged(list) { list.forEach(function (record) { var element = record.target; if (element.winControl && element.tabIndex >= 0) { element.winControl._pageManager._updateTabIndex(element.tabIndex); element.tabIndex = -1; } var that = element.winControl; if (that && that instanceof WinJS.UI.FlipView) { var dirChanged = false; if (record.attributeName === "dir") { dirChanged = true; } else if (record.attributeName === "style") { dirChanged = (that._cachedStyleDir != element.style.direction); } if (dirChanged) { that._cachedStyleDir = element.style.direction; that._pageManager._rtl = window.getComputedStyle(that._pageManager._flipperDiv, null).direction === "rtl"; that._pageManager.resized(); } } }); } var _FlipPageManager = WinJS.Class.define(function _FlipPageManager_ctor(flipperDiv, panningDiv, panningDivContainer, itemsManager, itemSpacing, buttonVisibilityHandler) { // Construction this._visibleElements = []; this._flipperDiv = flipperDiv; this._panningDiv = panningDiv; this._panningDivContainer = panningDivContainer; this._buttonVisibilityHandler = buttonVisibilityHandler; this._currentPage = null; this._rtl = window.getComputedStyle(this._flipperDiv, null).direction === "rtl"; this._itemsManager = itemsManager; this._itemSpacing = itemSpacing; this._tabIndex = (flipperDiv.tabIndex !== undefined && flipperDiv.tabIndex >= 0 ? flipperDiv.tabIndex : 0); flipperDiv.tabIndex = -1; this._tabManager = new WinJS.UI.TabContainer(this._panningDivContainer); this._tabManager.tabIndex = this._tabIndex; this._lastSelectedPage = null; this._lastSelectedElement = null; this._bufferSize = thisWinUI._FlipPageManager.flipPageBufferCount; this._cachedSize = -1; var that = this; this._panningDiv.addEventListener("keydown", function (event) { if (that._blockTabs && event.keyCode === utilities.Key.tab) { event.stopImmediatePropagation(); event.preventDefault(); } }, true); this._flipperDiv.addEventListener("focus", function (event) { if (event.srcElement === that._flipperDiv) { if (that._currentPage.element) { try { that._currentPage.element.setActive(); } catch (e) { } } } }, false); new MutationObserver(flipperPropertyChanged).observe(this._flipperDiv, { attributes: true, attributeFilter: ["dir", "style", "tabindex"] }); this._cachedStyleDir = this._flipperDiv.style.direction; this._panningDiv.addEventListener("activate", function (event) { that._hasFocus = true; }, true); this._panningDiv.addEventListener("deactivate", function (event) { that._hasFocus = false; }, true); this._panningDivContainer.addEventListener("MSManipulationStateChanged", function (event) { that._manipulationState = event.currentState; if (event.currentState === 0 && event.srcElement === that._panningDivContainer) { that._itemSettledOn(); that._ensureCentered(); } }, true); }, { // Public Methods initialize: function (initialIndex, horizontal) { var currPage = null; // Every call to offsetWidth/offsetHeight causes an switch from Script to Layout which affects // the performance of the control. The values will be cached and will be updated when a resize occurs. this._panningDivContainerOffsetWidth = this._panningDivContainer.offsetWidth; this._panningDivContainerOffsetHeight = this._panningDivContainer.offsetHeight; this._horizontal = horizontal; if (!this._currentPage) { this._bufferAriaStartMarker = document.createElement("div"); this._bufferAriaStartMarker.id = this._bufferAriaStartMarker.uniqueID; this._panningDiv.appendChild(this._bufferAriaStartMarker); this._currentPage = this._createFlipPage(null, this); currPage = this._currentPage; this._panningDiv.appendChild(currPage.pageRoot); // flipPageBufferCount is added here twice. // Once for the buffer prior to the current item, and once for the buffer ahead of the current item. var pagesToInit = 2 * this._bufferSize; for (var i = 0; i < pagesToInit; i++) { currPage = this._createFlipPage(currPage, this); this._panningDiv.appendChild(currPage.pageRoot); } this._bufferAriaEndMarker = document.createElement("div"); this._bufferAriaEndMarker.id = this._bufferAriaEndMarker.uniqueID; this._panningDiv.appendChild(this._bufferAriaEndMarker); } this._prevMarker = this._currentPage.prev.prev; if (this._itemsManager) { this.setNewItemsManager(this._itemsManager, initialIndex); } }, dispose: function () { var curPage = this._currentPage; var tmpPage = curPage; do { WinJS.Utilities._disposeElement(tmpPage.element); tmpPage = tmpPage.next; } while (tmpPage !== curPage); }, setOrientation: function (horizontal) { if (this._notificationsEndedSignal) { var that = this; this._notificationsEndedSignal.promise.done(function () { that._notificationsEndedSignal = null; that.setOrientation(horizontal); }); return; } if (horizontal !== this._horizontal) { this._isOrientationChanging = true; this._horizontal = horizontal; this._forEachPage(function (curr) { var currStyle = curr.pageRoot.style; currStyle.left = "0px"; currStyle.top = "0px"; }); this._panningDivContainer.scrollLeft = 0; this._panningDivContainer.scrollTop = 0; var containerStyle = this._panningDivContainer.style; containerStyle["overflow-x"] = "hidden"; containerStyle["overflow-y"] = "hidden"; var that = this; requestAnimationFrame(function () { that._isOrientationChanging = false; containerStyle["overflow-x"] = that._horizontal ? "scroll" : "hidden"; containerStyle["overflow-y"] = that._horizontal ? "hidden" : "scroll"; that._ensureCentered(); }); } }, resetState: function (initialIndex) { this._writeProfilerMark("WinJS.UI.FlipView:resetState,info"); if (initialIndex !== 0) { var indexValid = this.jumpToIndex(initialIndex, true); if (!indexValid && WinJS.validation) { throw new WinJS.ErrorFromName("WinJS.UI.FlipView.BadCurrentPage", strings.badCurrentPage); } return indexValid; } else { WinJS.Utilities.disposeSubTree(this._flipperDiv); this._resetBuffer(null, true); var that = this; var work = WinJS.Promise.wrap(true); if (this._itemsManager) { work = that._itemsManager._firstItem().then(function (e) { that._currentPage.setElement(e); return that._fetchPreviousItems(true). then(function () { return that._fetchNextItems(); }).then(function () { that._setButtonStates(); }); }); } return work.then(function () { that._tabManager.childFocus = that._currentPage.element; that._ensureCentered(); that._itemSettledOn(); }); } }, setNewItemsManager: function (manager, initialIndex) { this._itemsManager = manager; var that = this; return this.resetState(initialIndex).then(function () { // resetState already configures the tabManager, calls _ensureCentered and _itemSettledOn when the initial index is 0 if (initialIndex !== 0) { that._tabManager.childFocus = that._currentPage.element; that._ensureCentered(); that._itemSettledOn(); } }); }, currentIndex: function () { if (!this._itemsManager) { return 0; } var index = 0; var element = (this._navigationAnimationRecord ? this._navigationAnimationRecord.newCurrentElement : this._currentPage.element); if (element) { index = this._getElementIndex(element); } return index; }, resetScrollPos: function () { this._ensureCentered(); }, scrollPosChanged: function () { if (!this._itemsManager || !this._currentPage.element || this._isOrientationChanging) { return; } var newPos = this._viewportStart(), bufferEnd = (this._lastScrollPos > newPos ? this._getTailOfBuffer() : this._getHeadOfBuffer()); if (newPos === this._lastScrollPos) { return; } while (this._currentPage.element && this._itemStart(this._currentPage) > newPos && this._currentPage.prev.element) { this._currentPage = this._currentPage.prev; this._fetchOnePrevious(bufferEnd.prev); bufferEnd = bufferEnd.prev; } while (this._currentPage.element && this._itemEnd(this._currentPage) <= newPos && this._currentPage.next.element) { this._currentPage = this._currentPage.next; this._fetchOneNext(bufferEnd.next); bufferEnd = bufferEnd.next; } this._setButtonStates(); this._checkElementVisibility(false); this._blockTabs = true; this._lastScrollPos = newPos; this._tabManager.childFocus = this._currentPage.pageRoot; this._setListEnds(); if (!this._manipulationState && this._viewportOnItemStart()) { // Setup a timeout to invoke _itemSettledOn in cases where the scroll position is changed, and the control // does not know when it has settled on an item (e.g. 1-finger swipe with narrator touch). this._currentPage.element.setAttribute("aria-setsize", this._cachedSize); this._currentPage.element.setAttribute("aria-posinset", this.currentIndex() + 1); this._timeoutPageSelection(); } }, itemRetrieved: function (real, placeholder) { var that = this; this._forEachPage(function (curr) { if (curr.element === placeholder) { if (curr === that._currentPage || curr === that._currentPage.next) { that._changeFlipPage(curr, placeholder, real); } else { curr.setElement(real, true); } return true; } }); if (this._navigationAnimationRecord && this._navigationAnimationRecord.elementContainers) { var animatingElements = this._navigationAnimationRecord.elementContainers; for (var i = 0, len = animatingElements.length; i < len; i++) { if (animatingElements[i].element === placeholder) { that._changeFlipPage(animatingElements[i], placeholder, real); animatingElements[i].element = real; } } } this._checkElementVisibility(false); }, resized: function () { this._panningDivContainerOffsetWidth = this._panningDivContainer.offsetWidth; this._panningDivContainerOffsetHeight = this._panningDivContainer.offsetHeight; var that = this; this._forEachPage(function (curr) { curr.pageRoot.style.width = that._panningDivContainerOffsetWidth + "px"; curr.pageRoot.style.height = that._panningDivContainerOffsetHeight + "px"; }); // Call _ensureCentered to adjust all the width/height of the pages in the buffer this._ensureCentered(); this._writeProfilerMark("WinJS.UI.FlipView:resize,StopTM"); }, jumpToIndex: function (index, forceJump) { // If we force jumping to an index, we are not interested in making sure that there is distance // between the current and the new index. if (!forceJump) { if (!this._itemsManager || !this._currentPage.element || index < 0) { return WinJS.Promise.wrap(false); } // If we have to keep our pages in memory, we need to iterate through every single item from our current position to the desired target var i, currIndex = this._getElementIndex(this._currentPage.element), distance = Math.abs(index - currIndex); if (distance === 0) { return WinJS.Promise.wrap(false); } } var tail = WinJS.Promise.wrap(true); var that = this; tail = tail.then(function () { var itemPromise = that._itemsManager._itemPromiseAtIndex(index); return WinJS.Promise.join({ element: that._itemsManager._itemFromItemPromise(itemPromise), item: itemPromise }).then(function (v) { var elementAtIndex = v.element; // Reset the buffer regardless of whether we have elementAtIndex or not that._resetBuffer(elementAtIndex, forceJump); if (!elementAtIndex) { return false; } that._currentPage.setElement(elementAtIndex); return that._fetchNextItems(). then(function () { return that._fetchPreviousItems(true); }). then(function () { return true; }); }); }); tail = tail.then(function (v) { that._setButtonStates(); return v; }); return tail; }, startAnimatedNavigation: function (goForward, cancelAnimationCallback, completionCallback) { this._writeProfilerMark("WinJS.UI.FlipView:startAnimatedNavigation,info"); if (this._currentPage.element) { var outgoingPage = this._currentPage, incomingPage = (goForward ? this._currentPage.next : this._currentPage.prev); if (incomingPage.element) { if (this._hasFocus) { try { // Give focus to the panning div ONLY if anything inside the flipview control currently has // focus; otherwise, it will be lost when the current page is animated during the navigation. this._panningDiv.setActive(); } catch (e) { } } this._navigationAnimationRecord = {}; this._navigationAnimationRecord.goForward = goForward; this._navigationAnimationRecord.cancelAnimationCallback = cancelAnimationCallback; this._navigationAnimationRecord.completionCallback = completionCallback; this._navigationAnimationRecord.oldCurrentPage = outgoingPage; this._navigationAnimationRecord.newCurrentPage = incomingPage; var outgoingElement = outgoingPage.element; var incomingElement = incomingPage.element; this._navigationAnimationRecord.newCurrentElement = incomingElement; // When a page element is animated during a navigation, it is temporarily appended on a different container during the animation (see _createDiscardablePage). // However, updates in the data source can happen (change, remove, insert, etc) during the animation affecting the element that is being animated. // Therefore, the page object also maintains the elementUniqueID, and the functions that deal with re-building the internal buffer (shifting/remove/etc) // do all the comparissons, based on the page.elementUniqueID that way even if the element of the page is being animated, we are able to restore/discard it // into the internal buffer back in the correct place. outgoingPage.setElement(null, true); outgoingPage.elementUniqueID = outgoingElement.uniqueID; incomingPage.setElement(null, true); incomingPage.elementUniqueID = incomingElement.uniqueID; var outgoingFlipPage = this._createDiscardablePage(outgoingElement), incomingFlipPage = this._createDiscardablePage(incomingElement); outgoingFlipPage.pageRoot.itemIndex = this._getElementIndex(outgoingElement); incomingFlipPage.pageRoot.itemIndex = outgoingFlipPage.pageRoot.itemIndex + (goForward ? 1 : -1); outgoingFlipPage.pageRoot.style.position = "absolute"; incomingFlipPage.pageRoot.style.position = "absolute"; outgoingFlipPage.pageRoot.style.zIndex = 1; incomingFlipPage.pageRoot.style.zIndex = 2; this._itemStart(outgoingFlipPage, 0, 0); this._itemStart(incomingFlipPage, 0, 0); this._blockTabs = true; this._visibleElements.push(incomingElement); this._announceElementVisible(incomingElement); this._navigationAnimationRecord.elementContainers = [outgoingFlipPage, incomingFlipPage]; return { outgoing: outgoingFlipPage, incoming: incomingFlipPage }; } } return null; }, endAnimatedNavigation: function (goForward, outgoing, incoming) { this._writeProfilerMark("WinJS.UI.FlipView:endAnimatedNavigation,info"); if (this._navigationAnimationRecord && this._navigationAnimationRecord.oldCurrentPage && this._navigationAnimationRecord.newCurrentPage) { var outgoingRemoved = this._restoreAnimatedElement(this._navigationAnimationRecord.oldCurrentPage, outgoing); this._restoreAnimatedElement(this._navigationAnimationRecord.newCurrentPage, incoming); if (!outgoingRemoved) { // Advance only when the element in the current page was not removed because if it did, all the pages // were shifted. this._viewportStart(this._itemStart(goForward ? this._currentPage.next : this._currentPage.prev)); } this._navigationAnimationRecord = null; this._itemSettledOn(); } }, startAnimatedJump: function (index, cancelAnimationCallback, completionCallback) { this._writeProfilerMark("WinJS.UI.FlipView:startAnimatedJump,info"); if (this._currentPage.element) { var oldElement = this._currentPage.element; var oldIndex = this._getElementIndex(oldElement); var that = this; return that.jumpToIndex(index).then(function (v) { if (!v) { return null; } that._navigationAnimationRecord = {}; that._navigationAnimationRecord.cancelAnimationCallback = cancelAnimationCallback; that._navigationAnimationRecord.completionCallback = completionCallback; that._navigationAnimationRecord.oldCurrentPage = null; that._forEachPage(function (curr) { if (curr.element === oldElement) { that._navigationAnimationRecord.oldCurrentPage = curr; return true; } }); that._navigationAnimationRecord.newCurrentPage = that._currentPage; if (that._navigationAnimationRecord.newCurrentPage === that._navigationAnimationRecord.oldCurrentPage) { return null; } var newElement = that._currentPage.element; that._navigationAnimationRecord.newCurrentElement = newElement; // When a page element is animated during a jump, it is temporarily appended on a different container during the animation (see _createDiscardablePage). // However, updates in the data source can happen (change, remove, insert, etc) during the animation affecting the element that is being animated. // Therefore, the page object also maintains the elementUniqueID, and the functions that deal with re-building the internal buffer (shifting/remove/etc) // do all the comparissons, based on the page.elementUniqueID that way even if the element of the page is being animated, we are able to restore/discard it // into the internal buffer back in the correct place. that._currentPage.setElement(null, true); that._currentPage.elementUniqueID = newElement.uniqueID; if (that._navigationAnimationRecord.oldCurrentPage) { that._navigationAnimationRecord.oldCurrentPage.setElement(null, true); } var oldFlipPage = that._createDiscardablePage(oldElement), newFlipPage = that._createDiscardablePage(newElement); oldFlipPage.pageRoot.itemIndex = oldIndex; newFlipPage.pageRoot.itemIndex = index; oldFlipPage.pageRoot.style.position = "absolute"; newFlipPage.pageRoot.style.position = "absolute"; oldFlipPage.pageRoot.style.zIndex = 1; newFlipPage.pageRoot.style.zIndex = 2; that._itemStart(oldFlipPage, 0, 0); that._itemStart(newFlipPage, that._itemSize(that._currentPage), 0); that._visibleElements.push(newElement); that._announceElementVisible(newElement); that._navigationAnimationRecord.elementContainers = [oldFlipPage, newFlipPage]; that._blockTabs = true; return { oldPage: oldFlipPage, newPage: newFlipPage }; }); } return WinJS.Promise.wrap(null); }, endAnimatedJump: function (oldCurr, newCurr) { this._writeProfilerMark("WinJS.UI.FlipView:endAnimatedJump,info"); if (this._navigationAnimationRecord.oldCurrentPage) { this._navigationAnimationRecord.oldCurrentPage.setElement(oldCurr.element, true); } else { if (oldCurr.element.parentNode) { oldCurr.element.parentNode.removeChild(oldCurr.element); } } this._navigationAnimationRecord.newCurrentPage.setElement(newCurr.element, true); this._navigationAnimationRecord = null; this._ensureCentered(); this._itemSettledOn(); }, inserted: function (element, prev, next, animateInsertion) { this._writeProfilerMark("WinJS.UI.FlipView:inserted,info"); var curr = this._prevMarker, passedCurrent = false, elementSuccessfullyPlaced = false; if (animateInsertion) { this._createAnimationRecord(element.uniqueID, null); this._getAnimationRecord(element).inserted = true; } if (!prev) { if (!next) { this._currentPage.setElement(element); } else { while (curr.next !== this._prevMarker && curr.elementUniqueID !== next.uniqueID) { if (curr === this._currentPage) { passedCurrent = true; } curr = curr.next; } // We never should go past current if prev is null/undefined. //#DBG _ASSERT(!passedCurrent); if (curr.elementUniqueID === next.uniqueID && curr !== this._prevMarker) { curr.prev.setElement(element); elementSuccessfullyPlaced = true; } else { this._releaseElementIfNotAnimated(element); } } } else { do { if (curr === this._currentPage) { passedCurrent = true; } if (curr.elementUniqueID === prev.uniqueID) { elementSuccessfullyPlaced = true; var pageShifted = curr, lastElementMoved = element, lastElementMovedUniqueID = element.uniqueID, temp; if (passedCurrent) { while (pageShifted.next !== this._prevMarker) { temp = pageShifted.next.element; lastElementMovedUniqueID = pageShifted.next.elementUniqueID; pageShifted.next.setElement(lastElementMoved, true); if (!lastElementMoved && lastElementMovedUniqueID) { // Shift the uniqueID of the page manually since its element is being animated. // This page will not contain the element until the animation completes. pageShifted.next.elementUniqueID = lastElementMovedUniqueID; } lastElementMoved = temp; pageShifted = pageShifted.next; } } else { if (curr.elementUniqueID === curr.next.elementUniqueID && curr.elementUniqueID) { pageShifted = curr.next; } while (pageShifted.next !== this._prevMarker) { temp = pageShifted.element; lastElementMovedUniqueID = pageShifted.elementUniqueID; pageShifted.setElement(lastElementMoved, true); if (!lastElementMoved && lastElementMovedUniqueID) { // Shift the uniqueID of the page manually since its element is being animated. // This page will not contain the element until the animation completes. pageShifted.elementUniqueID = lastElementMovedUniqueID; } lastElementMoved = temp; pageShifted = pageShifted.prev; } } if (lastElementMoved) { var reused = false; this._forEachPage(function (curr) { if (lastElementMoved.uniqueID === curr.elementUniqueID) { reused = true; return true; } }); if (!reused) { this._releaseElementIfNotAnimated(lastElementMoved); } } break; } curr = curr.next; } while (curr !== this._prevMarker); } this._getAnimationRecord(element).successfullyMoved = elementSuccessfullyPlaced; this._setButtonStates(); }, changed: function (newVal, element) { this._writeProfilerMark("WinJS.UI.FlipView:changed,info"); var curr = this._prevMarker; var that = this; this._forEachPage(function (curr) { if (curr.elementUniqueID === element.uniqueID) { var record = that._animationRecords[curr.elementUniqueID]; record.changed = true; record.oldElement = element; record.newElement = newVal; curr.element = newVal; // We set curr's element field here so that next/prev works, but we won't update the visual until endNotifications curr.elementUniqueID = newVal.uniqueID; that._animationRecords[newVal.uniqueID] = record; return true; } }); if (this._navigationAnimationRecord && this._navigationAnimationRecord.elementContainers) { for (var i = 0, len = this._navigationAnimationRecord.elementContainers.length; i < len; i++) { var page = this._navigationAnimationRecord.elementContainers[i]; if (page && page.elementUniqueID === element.uniqueID) { page.element = newVal; page.elementUniqueID = newVal.uniqueID; } } var newElement = this._navigationAnimationRecord.newCurrentElement; if (newElement && newElement.uniqueID === element.uniqueID) { this._navigationAnimationRecord.newCurrentElement = newVal; } } }, moved: function (element, prev, next) { this._writeProfilerMark("WinJS.UI.FlipView:moved,info"); var record = this._getAnimationRecord(element); if (!record) { /*#DBG // When a moved notification is received, and it doesn't have a record, it shouldn't be in the buffer this._forEachPage(function (curr) { _ASSERT(curr.element !== element); }); #DBG*/ record = this._createAnimationRecord(element.uniqueID); } record.moved = true; this.removed(element, false, false); if (prev || next) { this.inserted(element, prev, next, false); } else { record.successfullyMoved = false; } }, removed: function (element, mirage, animateRemoval) { this._writeProfilerMark("WinJS.UI.FlipView:removed,info"); var that = this; var prevMarker = this._prevMarker; var work = WinJS.Promise.wrap(); if (mirage) { var clearNext = false; this._forEachPage(function (curr) { if (curr.elementUniqueID === element.uniqueID || clearNext) { curr.setElement(null, true); clearNext = true; } }); this._setButtonStates(); return; } if (animateRemoval) { var record = this._getAnimationRecord(element); if (record) { record.removed = true; } } if (this._currentPage.elementUniqueID === element.uniqueID) { if (this._currentPage.next.elementUniqueID) { this._shiftLeft(this._currentPage); this._ensureCentered(); } else if (this._currentPage.prev.elementUniqueID) { this._shiftRight(this._currentPage); } else { this._currentPage.setElement(null, true); } } else if (prevMarker.elementUniqueID === element.uniqueID) { if (prevMarker.next.element) { work = this._itemsManager._previousItem(prevMarker.next.element). then(function (e) { if (e === element) { // Because the VDS and Binding.List can send notifications in // different states we accomodate this here by fixing the case // where VDS hasn't yet removed an item when it sends a removed // or moved notification. // e = that._itemsManager._previousItem(e); } return e; }). then(function (e) { prevMarker.setElement(e, true); }); } else { prevMarker.setElement(null, true); } } else if (prevMarker.prev.elementUniqueID === element.uniqueID) { if (prevMarker.prev.prev && prevMarker.prev.prev.element) { work = this._itemsManager._nextItem(prevMarker.prev.prev.element). then(function (e) { if (e === element) { // Because the VDS and Binding.List can send notifications in // different states we accomodate this here by fixing the case // where VDS hasn't yet removed an item when it sends a removed // or moved notification. // e = that._itemsManager._nextItem(e); } return e; }). then(function (e) { prevMarker.prev.setElement(e, true); }); } else { prevMarker.prev.setElement(null, true); } } else { var curr = this._currentPage.prev, handled = false; while (curr !== prevMarker && !handled) { if (curr.elementUniqueID === element.uniqueID) { this._shiftRight(curr); handled = true; } curr = curr.prev; } curr = this._currentPage.next; while (curr !== prevMarker && !handled) { if (curr.elementUniqueID === element.uniqueID) { this._shiftLeft(curr); handled = true; } curr = curr.next; } } return work.then(function () { that._setButtonStates(); }); }, reload: function () { this._writeProfilerMark("WinJS.UI.FlipView:reload,info"); this.resetState(0); }, getItemSpacing: function () { return this._itemSpacing; }, setItemSpacing: function (space) { this._itemSpacing = space; this._ensureCentered(); }, notificationsStarted: function () { this._writeProfilerMark("WinJS.UI.FlipView:changeNotifications,StartTM"); this._logBuffer(); this._notificationsStarted = this._notificationsStarted || 0; this._notificationsStarted++; this._notificationsEndedSignal = new WinJS._Signal(); this._temporaryKeys = []; this._animationRecords = {}; var that = this; this._forEachPage(function (curr) { that._createAnimationRecord(curr.elementUniqueID, curr); }); // Since the current item is defined as the left-most item in the view, the only possible elements that can be in view at any time are // the current item and the item proceeding it. We'll save these two elements for animations during the notificationsEnded cycle this._animationRecords.currentPage = this._currentPage.element; this._animationRecords.nextPage = this._currentPage.next.element; }, notificationsEnded: function () { // The animations are broken down into three parts. // First, we move everything back to where it was before the changes happened. Elements that were inserted between two pages won't have their flip pages moved. // Next, we figure out what happened to the two elements that used to be in view. If they were removed/moved, they get animated as appropriate in this order: // removed, moved // Finally, we figure out how the items that are now in view got there, and animate them as necessary, in this order: moved, inserted. // The moved animation of the last part is joined with the moved animation of the previous part, so in the end it is: // removed -> moved items in view + moved items not in view -> inserted. var that = this; this._endNotificationsWork && this._endNotificationsWork.cancel(); this._endNotificationsWork = this._ensureBufferConsistency().then(function () { var animationPromises = []; that._forEachPage(function (curr) { var record = that._getAnimationRecord(curr.element); if (record) { if (record.changed) { record.oldElement.removedFromChange = true; animationPromises.push(that._changeFlipPage(curr, record.oldElement, record.newElement)); } record.newLocation = curr.location; that._itemStart(curr, record.originalLocation); if (record.inserted) { curr.elementRoot.style.opacity = 0.0; } } }); function flipPageFromElement(element) { var flipPage = null; that._forEachPage(function (curr) { if (curr.element === element) { flipPage = curr; return true; } }); return flipPage; } function animateOldViewportItemRemoved(record, item) { that._writeProfilerMark("WinJS.UI.FlipView:_animateOldViewportItemRemoved,info"); var removedPage = that._createDiscardablePage(item); that._itemStart(removedPage, record.originalLocation); animationPromises.push(that._deleteFlipPage(removedPage)); } function animateOldViewportItemMoved(record, item) { that._writeProfilerMark("WinJS.UI.FlipView:_animateOldViewportItemMoved,info"); var newLocation = record.originalLocation, movedPage; if (!record.successfullyMoved) { // If the old visible item got moved, but the next/prev of that item don't match up with anything // currently in our flip page buffer, we need to figure out in which direction it moved. // The exact location doesn't matter since we'll be deleting it anyways, but we do need to // animate it going in the right direction. movedPage = that._createDiscardablePage(item); var indexMovedTo = that._getElementIndex(item); var newCurrentIndex = (that._currentPage.element ? that._getElementIndex(that._currentPage.element) : 0); newLocation += (newCurrentIndex > indexMovedTo ? -100 * that._bufferSize : 100 * that._bufferSize); } else { movedPage = flipPageFromElement(item); newLocation = record.newLocation; } if (movedPage) { that._itemStart(movedPage, record.originalLocation); animationPromises.push(that._moveFlipPage(movedPage, function () { that._itemStart(movedPage, newLocation); })); } } var oldCurrent = that._animationRecords.currentPage, oldCurrentRecord = that._getAnimationRecord(oldCurrent), oldNext = that._animationRecords.nextPage, oldNextRecord = that._getAnimationRecord(oldNext); if (oldCurrentRecord && oldCurrentRecord.changed) { oldCurrent = oldCurrentRecord.newElement; } if (oldNextRecord && oldNextRecord.changed) { oldNext = oldNextRecord.newElement; } if (oldCurrent !== that._currentPage.element || oldNext !== that._currentPage.next.element) { if (oldCurrentRecord && oldCurrentRecord.removed) { animateOldViewportItemRemoved(oldCurrentRecord, oldCurrent); } if (oldNextRecord && oldNextRecord.removed) { animateOldViewportItemRemoved(oldNextRecord, oldNext); } } function joinAnimationPromises() { if (animationPromises.length === 0) { animationPromises.push(WinJS.Promise.wrap()); } return WinJS.Promise.join(animationPromises); } that._blockTabs = true; joinAnimationPromises().then(function () { animationPromises = []; if (oldCurrentRecord && oldCurrentRecord.moved) { animateOldViewportItemMoved(oldCurrentRecord, oldCurrent); } if (oldNextRecord && oldNextRecord.moved) { animateOldViewportItemMoved(oldNextRecord, oldNext); } var newCurrRecord = that._getAnimationRecord(that._currentPage.element), newNextRecord = that._getAnimationRecord(that._currentPage.next.element); that._forEachPage(function (curr) { var record = that._getAnimationRecord(curr.element); if (record) { if (!record.inserted) { if (record.originalLocation !== record.newLocation) { if ((record !== oldCurrentRecord && record !== oldNextRecord) || (record === oldCurrentRecord && !oldCurrentRecord.moved) || (record === oldNextRecord && !oldNextRecord.moved)) { animationPromises.push(that._moveFlipPage(curr, function () { that._itemStart(curr, record.newLocation); })); } } } else if (record !== newCurrRecord && record !== newNextRecord) { curr.elementRoot.style.opacity = 1.0; } } }); joinAnimationPromises().then(function () { animationPromises = []; if (newCurrRecord && newCurrRecord.inserted) { animationPromises.push(that._insertFlipPage(that._currentPage)); } if (newNextRecord && newNextRecord.inserted) { animationPromises.push(that._insertFlipPage(that._currentPage.next)); } joinAnimationPromises().then(function () { that._checkElementVisibility(false); that._itemSettledOn(); that._setListEnds(); that._notificationsStarted--; if (that._notificationsStarted === 0) { that._notificationsEndedSignal.complete(); } that._writeProfilerMark("WinJS.UI.FlipView:changeNotifications,StopTM"); that._logBuffer(); that._endNotificationsWork = null; }); }); }); }); }, // Private methods _timeoutPageSelection: function () { var that = this; if (this._lastTimeoutRequest) { this._lastTimeoutRequest.cancel(); } this._lastTimeoutRequest = WinJS.Promise.timeout(itemSelectedEventDelay).then(function () { that._itemSettledOn(); }); }, _updateTabIndex: function (newIndex) { this._forEachPage(function (curr) { if (curr.element) { curr.element.tabIndex = newIndex; } }); this._tabIndex = newIndex; this._tabManager.tabIndex = newIndex; }, _releaseElementIfNotAnimated: function (element) { var animatedRecord = this._getAnimationRecord(element); if (!(animatedRecord && (animatedRecord.changed || animatedRecord.inserted || animatedRecord.moved || animatedRecord.removed))) { this._itemsManager.releaseItem(element); } }, _getAnimationRecord: function (element) { return (element ? this._animationRecords[element.uniqueID] : null); }, _createAnimationRecord: function (elementUniqueID, flipPage) { if (elementUniqueID) { var record = this._animationRecords[elementUniqueID] = { removed: false, changed: false, inserted: false }; if (flipPage) { record.originalLocation = flipPage.location; } return record; } }, _writeProfilerMark: function(message) { msWriteProfilerMark(message); if (WinJS.UI.FlipView._enabledDebug) { WinJS.log && WinJS.log(message, null, "flipviewdebug"); } }, _getElementIndex: function(element) { var index = 0; try { index = this._itemsManager.itemObject(element).index; } catch (e) { // Failures are expected in cases where items are moved and then deleted. Animations will simply animate as if the item // moved to the beginning of the list. } return index; }, _resetBuffer: function (elementToSave, skipReleases) { this._writeProfilerMark("WinJS.UI.FlipView:_resetBuffer,info"); var head = this._currentPage, curr = head; do { if ((curr.element && curr.element === elementToSave) || skipReleases) { curr.setElement(null, true); } else { curr.setElement(null); } curr = curr.next; } while (curr !== head); }, _getHeadOfBuffer: function () { return this._prevMarker.prev; }, _getTailOfBuffer: function () { return this._prevMarker; }, _insertNewFlipPage: function (prevElement) { this._writeProfilerMark("WinJS.UI.FlipView:_insertNewFlipPage,info"); var newPage = this._createFlipPage(prevElement, this); this._panningDiv.appendChild(newPage.pageRoot); return newPage; }, _fetchNextItems: function () { this._writeProfilerMark("WinJS.UI.FlipView:_fetchNextItems,info"); var tail = WinJS.Promise.wrap(this._currentPage); var that = this; for (var i = 0; i < this._bufferSize; i++) { tail = tail.then(function (curr) { if (curr.next === that._prevMarker) { that._insertNewFlipPage(curr); } if (curr.element) { return that._itemsManager._nextItem(curr.element). then(function (element) { curr.next.setElement(element); return curr.next; }); } else { curr.next.setElement(null); return curr.next; } }); } return tail; }, _fetchOneNext: function (target) { this._writeProfilerMark("WinJS.UI.FlipView:_fetchOneNext,info"); var prevElement = target.prev.element; // If the target we want to fill with the next item is the end of the circular buffer but we want to keep everything in memory, we've got to increase the buffer size // so that we don't reuse prevMarker. if (this._prevMarker === target) { this._prevMarker = this._prevMarker.next; } if (!prevElement) { target.setElement(null); return; } var that = this; return this._itemsManager._nextItem(prevElement). then(function (element) { target.setElement(element); that._movePageAhead(target.prev, target); }); }, _fetchPreviousItems: function (setPrevMarker) { this._writeProfilerMark("WinJS.UI.FlipView:_fetchPreviousItems,info"); var that = this; var tail = WinJS.Promise.wrap(this._currentPage); for (var i = 0; i < this._bufferSize; i++) { tail = tail.then(function (curr) { if (curr.element) { return that._itemsManager._previousItem(curr.element). then(function (element) { curr.prev.setElement(element); return curr.prev; }); } else { curr.prev.setElement(null); return curr.prev; } }); } return tail.then(function (curr) { if (setPrevMarker) { that._prevMarker = curr; } }); }, _fetchOnePrevious: function (target) { this._writeProfilerMark("WinJS.UI.FlipView:_fetchOnePrevious,info"); var nextElement = target.next.element; // If the target we want to fill with the previous item is the end of the circular buffer but we want to keep everything in memory, we've got to increase the buffer size // so that we don't reuse prevMarker. We'll add a new element to be prevMarker's prev, then set prevMarker to point to that new element. if (this._prevMarker === target.next) { this._prevMarker = this._prevMarker.prev; } if (!nextElement) { target.setElement(null); return WinJS.Promise.wrap(); } var that = this; return this._itemsManager._previousItem(nextElement). then(function (element) { target.setElement(element); that._movePageBehind(target.next, target); }); }, _setButtonStates: function () { if (this._currentPage.prev.element) { this._buttonVisibilityHandler.showPreviousButton(); } else { this._buttonVisibilityHandler.hidePreviousButton(); } if (this._currentPage.next.element) { this._buttonVisibilityHandler.showNextButton(); } else { this._buttonVisibilityHandler.hideNextButton(); } }, _ensureCentered: function (delayBoundariesSet) { this._writeProfilerMark("WinJS.UI.FlipView:_ensureCentered,info"); this._itemStart(this._currentPage, leftBufferAmount * this._viewportSize()); var curr = this._currentPage; while (curr !== this._prevMarker) { this._movePageBehind(curr, curr.prev); curr = curr.prev; } curr = this._currentPage; while (curr.next !== this._prevMarker) { this._movePageAhead(curr, curr.next); curr = curr.next; } var boundariesSet = false; if (this._lastScrollPos && !delayBoundariesSet) { this._setListEnds(); boundariesSet = true; } this._lastScrollPos = this._itemStart(this._currentPage); this._viewportStart(this._lastScrollPos); this._checkElementVisibility(true); this._setupSnapPoints(); if (!boundariesSet) { this._setListEnds(); } }, _ensureBufferConsistency: function () { var that = this; var currentElement = this._currentPage.element; if (!currentElement) { return WinJS.Promise.wrap(); } var refreshBuffer = false; var seenUniqueIDs = {}; var seenLocations = {}; this._forEachPage(function (page) { if (page && page.elementUniqueID) { if (!seenUniqueIDs[page.elementUniqueID]) { seenUniqueIDs[page.elementUniqueID] = true; } else { refreshBuffer = true; return true; } if (page.location > 0) { if (!seenLocations[page.location]) { seenLocations[page.location] = true; } else { refreshBuffer = true; return true; } } } }); var animationKeys = Object.keys(this._animationRecords); animationKeys.forEach(function (key) { var record = that._animationRecords[key]; if (record && (record.changed || record.inserted || record.moved || record.removed)) { refreshBuffer = true; } }); if (refreshBuffer) { this._resetBuffer(null, true); this._currentPage.setElement(currentElement); return this._fetchNextItems(). then(function () { return that._fetchPreviousItems(true); }). then(function () { that._ensureCentered(); }); } else { return WinJS.Promise.wrap(); } }, _shiftLeft: function (startingPoint) { this._writeProfilerMark("WinJS.UI.FlipView:_shiftLeft,info"); var curr = startingPoint, nextEl = null; while (curr !== this._prevMarker && curr.next !== this._prevMarker) { nextEl = curr.next.element; if (!nextEl && curr.next.elementUniqueID) { // Shift the uniqueID of the page manually since its element is being animated. // This page will not contain the element until the animation completes. curr.elementUniqueID = curr.next.elementUniqueID; } curr.next.setElement(null, true); curr.setElement(nextEl, true); curr = curr.next; } if (curr !== this._prevMarker && curr.prev.element) { var that = this; return this._itemsManager._nextItem(curr.prev.element). then(function (element) { curr.setElement(element); that._createAnimationRecord(curr.elementUniqueID, curr); }); } }, _logBuffer: function () { if (WinJS.UI.FlipView._enabledDebug) { WinJS.log && WinJS.log(this._currentPage.next.next.next.elementUniqueID + "\t@:" + this._currentPage.next.next.next.location + (this._currentPage.next.next.next.element ? ("\t" + this._currentPage.next.next.next.element.innerText) : ""), null, "flipviewdebug"); WinJS.log && WinJS.log(this._currentPage.next.next.next.next.elementUniqueID + "\t@:" + this._currentPage.next.next.next.next.location + (this._currentPage.next.next.next.next.element ? ("\t" + this._currentPage.next.next.next.next.element.innerText) : ""), null, "flipviewdebug"); WinJS.log && WinJS.log("> " + this._currentPage.elementUniqueID + "\t@:" + this._currentPage.location + (this._currentPage.element ? ("\t" + this._currentPage.element.innerText) : ""), null, "flipviewdebug"); WinJS.log && WinJS.log(this._currentPage.next.elementUniqueID + "\t@:" + this._currentPage.next.location + (this._currentPage.next.element ? ("\t" + this._currentPage.next.element.innerText) : ""), null, "flipviewdebug"); WinJS.log && WinJS.log(this._currentPage.next.next.elementUniqueID + "\t@:" + this._currentPage.next.next.location + (this._currentPage.next.next.element ? ("\t" + this._currentPage.next.next.element.innerText) : ""), null, "flipviewdebug"); var keys = Object.keys(this._itemsManager._elementMap); var bufferKeys = []; this._forEachPage(function (page) { if (page && page.elementUniqueID) { bufferKeys.push(page.elementUniqueID); } }); WinJS.log && WinJS.log("itemsmanager = [" + keys.join(" ") + "] flipview [" + bufferKeys.join(" ") + "]", null, "flipviewdebug"); } }, _shiftRight: function (startingPoint) { this._writeProfilerMark("WinJS.UI.FlipView:_shiftRight,info"); var curr = startingPoint, prevEl = null; while (curr !== this._prevMarker) { prevEl = curr.prev.element; if (!prevEl && curr.prev.elementUniqueID) { // Shift the uniqueID of the page manually since its element is being animated. // This page will not contain the element until the animation completes. curr.elementUniqueID = curr.prev.elementUniqueID; } curr.prev.setElement(null, true); curr.setElement(prevEl, true); curr = curr.prev; } if (curr.next.element) { var that = this; return this._itemsManager._previousItem(curr.next.element). then(function (element) { curr.setElement(element); that._createAnimationRecord(curr.elementUniqueID, curr); }); } }, _checkElementVisibility: function (viewWasReset) { var i, len; if (viewWasReset) { var currentElement = this._currentPage.element; for (i = 0, len = this._visibleElements.length; i < len; i++) { if (this._visibleElements[i] !== currentElement) { this._announceElementInvisible(this._visibleElements[i]); } } this._visibleElements = []; if (currentElement) { this._visibleElements.push(currentElement); this._announceElementVisible(currentElement); } } else { // Elements that have been removed completely from the flipper still need to raise pageVisibilityChangedEvents if they were visible prior to being removed, // so before going through all the elements we go through the ones that we knew were visible and see if they're missing a parentNode. If they are, // the elements were removed and we announce them as invisible. for (i = 0, len = this._visibleElements.length; i < len; i++) { if (!this._visibleElements[i].parentNode || this._visibleElements[i].removedFromChange) { this._announceElementInvisible(this._visibleElements[i]); } } this._visibleElements = []; var that = this; this._forEachPage(function (curr) { var element = curr.element; if (element) { if (that._itemInView(curr)) { that._visibleElements.push(element); that._announceElementVisible(element); } else { that._announceElementInvisible(element); } } }); } }, _announceElementVisible: function (element) { if (element && !element.visible) { element.visible = true; var event = document.createEvent("CustomEvent"); this._writeProfilerMark("WinJS.UI.FlipView:pageVisibilityChangedEvent(visible:true),info"); event.initCustomEvent(thisWinUI.FlipView.pageVisibilityChangedEvent, true, false, { source: this._flipperDiv, visible: true }); element.dispatchEvent(event); } }, _announceElementInvisible: function (element) { if (element && element.visible) { element.visible = false; // Elements that have been removed from the flipper still need to fire invisible events, but they can't do that without being in the DOM. // To fix that, we add the element back into the flipper, fire the event, then remove it. var addedToDomForEvent = false; if (!element.parentNode) { addedToDomForEvent = true; this._panningDivContainer.appendChild(element); } var event = document.createEvent("CustomEvent"); this._writeProfilerMark("WinJS.UI.FlipView:pageVisibilityChangedEvent(visible:false),info"); event.initCustomEvent(thisWinUI.FlipView.pageVisibilityChangedEvent, true, false, { source: this._flipperDiv, visible: false }); element.dispatchEvent(event); if (addedToDomForEvent) { this._panningDivContainer.removeChild(element); } } }, _createDiscardablePage: function (content) { var pageDivs = this._createPageContainer(), page = { pageRoot: pageDivs.root, elementRoot: pageDivs.elementContainer, discardable: true, element: content, elementUniqueID: content.uniqueID, discard: function () { if (page.pageRoot.parentNode) { page.pageRoot.parentNode.removeChild(page.pageRoot); } if (page.element.parentNode) { page.element.parentNode.removeChild(page.element); } } }; page.pageRoot.style.top = "0px"; page.elementRoot.appendChild(content); this._panningDiv.appendChild(page.pageRoot); return page; }, _createPageContainer: function () { var width = this._panningDivContainerOffsetWidth, height = this._panningDivContainerOffsetHeight, parentDiv = document.createElement("div"), pageStyle = parentDiv.style, flexBox = document.createElement("div"); flexBox.className = "win-item"; pageStyle.position = "absolute"; pageStyle.overflow = "hidden"; pageStyle.width = width + "px"; pageStyle.height = height + "px"; parentDiv.appendChild(flexBox); return { root: parentDiv, elementContainer: flexBox }; }, _createFlipPage: function (prev, manager) { var page = {}; page.element = null; page.elementUniqueID = null; // The flip pages are managed as a circular doubly-linked list. this.currentItem should always refer to the current item in view, and this._prevMarker marks the point // in the list where the last previous item is stored. Why a circular linked list? // The virtualized flipper reuses its flip pages. When a new item is requested, the flipper needs to reuse an old item from the buffer. In the case of previous items, // the flipper has to go all the way back to the farthest next item in the buffer and recycle it (which is why having a .prev pointer on the farthest previous item is really useful), // and in the case of the next-most item, it needs to recycle next's next (ie, the this._prevMarker). The linked structure comes in really handy when iterating through the list // and separating out prev items from next items (like removed and ensureCentered do). If we were to use a structure like an array it would be pretty messy to do that and still // maintain a buffer of recyclable items. if (!prev) { page.next = page; page.prev = page; } else { page.prev = prev; page.next = prev.next; page.next.prev = page; prev.next = page; } var pageContainer = this._createPageContainer(); page.elementRoot = pageContainer.elementContainer; page.elementRoot.style["-ms-overflow-style"] = "auto"; page.pageRoot = pageContainer.root; // Sets the element to display in this flip page page.setElement = function (element, isReplacement) { if (element === undefined) { element = null; } if (element === page.element) { if (!element) { // If there are data source updates during the animation (e.g. item removed), a page element can be set to null when the shiftLeft/Right functions // call this function with a null element. However, since the element in the page is in the middle of an animation its page.elementUniqueID // is still set, so we need to explicitly clear its value so that when the animation completes, the animated element is not // restored back into the internal buffer. page.elementUniqueID = null; } return; } if (page.element) { if (!isReplacement) { manager._itemsManager.releaseItem(page.element); WinJS.Utilities._disposeElement(page.element); } } page.element = element; page.elementUniqueID = (element ? element.uniqueID : null); utilities.empty(page.elementRoot); if (page.element) { if (!isFlipper(page.element)) { page.element.tabIndex = manager._tabIndex; page.element.setAttribute("role", "option"); page.element.setAttribute("aria-selected", false); if (!page.element.id) { page.element.id = page.element.uniqueID; } var setFlowAttribute = function (source, target, attributeName) { source.setAttribute(attributeName, target.id); } var isEnd = !page.next.element || page === manager._prevMarker.prev; if (isEnd) { setFlowAttribute(page.element, manager._bufferAriaEndMarker, "aria-flowto"); setFlowAttribute(manager._bufferAriaEndMarker, page.element, "x-ms-aria-flowfrom"); } if (page !== manager._prevMarker && page.prev.element) { setFlowAttribute(page.prev.element, page.element, "aria-flowto"); setFlowAttribute(page.element, page.prev.element, "x-ms-aria-flowfrom"); } if (page.next !== manager._prevMarker && page.next.element) { setFlowAttribute(page.element, page.next.element, "aria-flowto"); setFlowAttribute(page.next.element, page.element, "x-ms-aria-flowfrom"); } if (!page.prev.element) { setFlowAttribute(page.element, manager._bufferAriaStartMarker, "x-ms-aria-flowfrom"); // aria-flowto in the start marker is configured in itemSettledOn to point to the current page in view } } page.elementRoot.appendChild(page.element); } }; return page; }, _itemInView: function (flipPage) { return this._itemEnd(flipPage) > this._viewportStart() && this._itemStart(flipPage) < this._viewportEnd(); }, _viewportStart: function (newValue) { if (!this._panningDivContainer.parentNode) { return; } if (this._horizontal) { if (newValue === undefined) { return this._panningDivContainer.scrollLeft; } this._panningDivContainer.scrollLeft = newValue; } else { if (newValue === undefined) { return this._panningDivContainer.scrollTop; } this._panningDivContainer.scrollTop = newValue; } }, _viewportEnd: function () { var element = this._panningDivContainer; if (this._horizontal) { if (this._rtl) { return this._viewportStart() + this._panningDivContainerOffsetWidth; } else { return element.scrollLeft + this._panningDivContainerOffsetWidth; } } else { return element.scrollTop + this._panningDivContainerOffsetHeight; } }, _viewportSize: function () { return this._horizontal ? this._panningDivContainerOffsetWidth : this._panningDivContainerOffsetHeight; }, _itemStart: function (flipPage, newValue) { if (newValue === undefined) { return flipPage.location; } if (this._horizontal) { flipPage.pageRoot.style.left = (this._rtl ? -newValue : newValue) + "px"; } else { flipPage.pageRoot.style.top = newValue + "px"; } flipPage.location = newValue; }, _itemEnd: function (flipPage) { return (this._horizontal ? flipPage.location + this._panningDivContainerOffsetWidth : flipPage.location + this._panningDivContainerOffsetHeight) + this._itemSpacing; }, _itemSize: function (flipPage) { return this._horizontal ? this._panningDivContainerOffsetWidth : this._panningDivContainerOffsetHeight; }, _movePageAhead: function (referencePage, pageToPlace) { var delta = this._itemSize(referencePage) + this._itemSpacing; this._itemStart(pageToPlace, this._itemStart(referencePage) + delta); }, _movePageBehind: function (referencePage, pageToPlace) { var delta = this._itemSize(referencePage) + this._itemSpacing; this._itemStart(pageToPlace, this._itemStart(referencePage) - delta); }, _setupSnapPoints: function () { var containerStyle = this._panningDivContainer.style; containerStyle["-ms-scroll-snap-type"] = "mandatory"; var viewportSize = this._viewportSize(); var snapInterval = viewportSize + this._itemSpacing; var propertyName = "-ms-scroll-snap-points"; var startSnap = 0; var currPos = this._itemStart(this._currentPage); startSnap = currPos % (viewportSize + this._itemSpacing); containerStyle[(this._horizontal ? propertyName + "-x" : propertyName + "-y")] = "snapInterval(" + startSnap + "px, " + snapInterval + "px)"; }, _setListEnds: function () { if (this._currentPage.element) { var containerStyle = this._panningDivContainer.style, startScroll = 0, endScroll = 0, startNonEmptyPage = this._getTailOfBuffer(), endNonEmptyPage = this._getHeadOfBuffer(), startBoundaryStyle = "-ms-scroll-limit-" + (this._horizontal ? "x-min" : "y-min"), endBoundaryStyle = "-ms-scroll-limit-" + (this._horizontal ? "x-max" : "y-max"); while (!endNonEmptyPage.element) { endNonEmptyPage = endNonEmptyPage.prev; // We started at the item before prevMarker (going backwards), so we will exit if all // the pages in the buffer are empty. if (endNonEmptyPage == this._prevMarker.prev) { break; } } while (!startNonEmptyPage.element) { startNonEmptyPage = startNonEmptyPage.next; // We started at prevMarker (going forward), so we will exit if all the pages in the // buffer are empty. if (startNonEmptyPage == this._prevMarker) { break; } } endScroll = this._itemStart(endNonEmptyPage); startScroll = this._itemStart(startNonEmptyPage); containerStyle[startBoundaryStyle] = startScroll + "px"; containerStyle[endBoundaryStyle] = endScroll + "px"; } }, _viewportOnItemStart: function () { return this._itemStart(this._currentPage) === this._viewportStart(); }, _restoreAnimatedElement: function (oldPage, discardablePage) { var removed = true; // Restore the element in the old page only if it still matches the uniqueID, and the page // does not have new updated content. If the element was removed, it won't be restore in the // old page. if (oldPage.elementUniqueID === discardablePage.element.uniqueID && !oldPage.element) { oldPage.setElement(discardablePage.element, true); removed = false; } else { // Iterate through the pages to see if the element was moved this._forEachPage(function (curr) { if (curr.elementUniqueID === discardablePage.elementUniqueID && !curr.element) { curr.setElement(discardablePage.element, true); removed = false; } }); } return removed; }, _itemSettledOn: function () { if (this._lastTimeoutRequest) { this._lastTimeoutRequest.cancel(); this._lastTimeoutRequest = null; } var that = this; // Need to yield to the host here setImmediate(function () { if (that._viewportOnItemStart()) { that._blockTabs = false; if (that._currentPage.element) { if (that._hasFocus) { try { that._currentPage.element.setActive(); that._tabManager.childFocus = that._currentPage.element; } catch (e) { } } if (that._lastSelectedElement !== that._currentPage.element) { if (that._lastSelectedPage && that._lastSelectedPage.element && !isFlipper(that._lastSelectedPage.element)) { that._lastSelectedPage.element.setAttribute("aria-selected", false); } that._lastSelectedPage = that._currentPage; that._lastSelectedElement = that._currentPage.element; if (!isFlipper(that._currentPage.element)) { that._currentPage.element.setAttribute("aria-selected", true); } // Need to schedule this: // - to be able to register for the pageselected event after instantiating the control and still get the event // - in case a FlipView navigation is triggered inside the pageselected listener (avoid reentering _itemSettledOn) Scheduler.schedule(function FlipView_dispatchPageSelectedEvent() { if (that._currentPage.element) { var event = document.createEvent("CustomEvent"); event.initCustomEvent(thisWinUI.FlipView.pageSelectedEvent, true, false, { source: that._flipperDiv }); that._writeProfilerMark("WinJS.UI.FlipView:pageSelectedEvent,info"); that._currentPage.element.dispatchEvent(event); // Fire the pagecompleted event when the render completes if we are still looking at the same element. // Check that the current element is not null, since the app could've triggered a navigation inside the // pageselected event handler. var originalElement = that._currentPage.element; if (originalElement) { var record = that._itemsManager._recordFromElement(originalElement, true); if (record) { record.renderComplete.then(function () { if (originalElement === that._currentPage.element) { that._currentPage.element.setAttribute("aria-setsize", that._cachedSize); that._currentPage.element.setAttribute("aria-posinset", that.currentIndex() + 1); that._bufferAriaStartMarker.setAttribute("aria-flowto", that._currentPage.element.id); event = document.createEvent("CustomEvent"); event.initCustomEvent(thisWinUI.FlipView.pageCompletedEvent, true, false, { source: that._flipperDiv }); that._writeProfilerMark("WinJS.UI.FlipView:pageCompletedEvent,info"); that._currentPage.element.dispatchEvent(event); } }); } } } }, Scheduler.Priority.normal, null, "WinJS.UI.FlipView._dispatchPageSelectedEvent"); } } } }); }, _forEachPage: function (callback) { var go = true; var curr = this._prevMarker; while (go) { if (callback(curr)) { break; } curr = curr.next; go = (curr !== this._prevMarker); } }, _changeFlipPage: function (page, oldElement, newElement) { this._writeProfilerMark("WinJS.UI.FlipView:_changeFlipPage,info"); page.element = null; if (page.setElement) { page.setElement(newElement, true); } else { // Discardable pages that are created for animations aren't full fleged pages, and won't have some of the functions a normal page would. // changeFlipPage will be called on them when an item that's animating gets fetched. When that happens, we need to replace its element // manually, then center it. oldElement.parentNode.removeChild(oldElement); page.elementRoot.appendChild(newElement); } var style = oldElement.style; style.position = "absolute"; style.left = "0px"; style.top = "0px"; style.opacity = 1.0; page.pageRoot.appendChild(oldElement); oldElement.style.left = Math.max(0, (page.pageRoot.offsetWidth - oldElement.offsetWidth) / 2) + "px"; oldElement.style.top = Math.max(0, (page.pageRoot.offsetHeight - oldElement.offsetHeight) / 2) + "px"; return animations.fadeOut(oldElement).then(function () { oldElement.parentNode && oldElement.parentNode.removeChild(oldElement); }); }, _deleteFlipPage: function (page) { msWriteProfilerMark("WinJS.UI.FlipView:_deleteFlipPage,info"); page.elementRoot.style.opacity = 0; var animation = animations.createDeleteFromListAnimation([page.elementRoot]); var that = this; return animation.execute().then(function () { if (page.discardable) { page.discard(); that._itemsManager.releaseItem(page.element); } }); }, _insertFlipPage: function (page) { msWriteProfilerMark("WinJS.UI.FlipView:_insertFlipPage,info"); page.elementRoot.style.opacity = 1.0; var animation = animations.createAddToListAnimation([page.elementRoot]); return animation.execute().then(function () { if (page.discardable) { page.discard(); } }); }, _moveFlipPage: function (page, move) { msWriteProfilerMark("WinJS.UI.FlipView:_moveFlipPage,info"); var animation = animations.createRepositionAnimation(page.pageRoot); move(); var that = this; return animation.execute().then(function () { if (page.discardable) { page.discard(); var animationRecord = that._getAnimationRecord(page.element); if (animationRecord && !animationRecord.successfullyMoved) { // If the animationRecord was not succesfully moved, the item is now outside of the buffer, // and we can release it. that._itemsManager.releaseItem(page.element); } } }); } }, { supportedForProcessing: false, }); _FlipPageManager.flipPageBufferCount = 2; // The number of items that should surround the current item as a buffer at any time return _FlipPageManager; }) }); })(WinJS); (function browseModeInit(global, WinJS, undefined) { "use strict"; // This component is responsible for handling input in Browse Mode. // When the user clicks on an item in this mode itemInvoked event is fired. WinJS.Namespace.define("WinJS.UI", { _getCursorPos: function (eventObject) { var docElement = document.documentElement; return { left: eventObject.clientX + (document.body.dir === "rtl" ? -docElement.scrollLeft : docElement.scrollLeft), top: eventObject.clientY + docElement.scrollTop }; }, _getElementsByClasses: function (parent, classes) { var retVal = [] for (var i = 0, len = classes.length; i < len; i++) { var element = parent.querySelector("." + classes[i]); if (element) { retVal.push(element); } } return retVal; }, _SelectionMode: WinJS.Namespace._lazy(function () { var utilities = WinJS.Utilities, Promise = WinJS.Promise, Animation = WinJS.UI.Animation; function clampToRange(first, last, x) { return Math.max(first, Math.min(last, x)); } function dispatchKeyboardNavigating(element, oldEntity, newEntity) { var navigationEvent = document.createEvent("CustomEvent"); navigationEvent.initCustomEvent("keyboardnavigating", true, true, { oldFocus: oldEntity.index, oldFocusType: oldEntity.type, newFocus: newEntity.index, newFocusType: newEntity.type }); return element.dispatchEvent(navigationEvent); } var _SelectionMode = function (modeSite) { this.inboundFocusHandled = false; this._pressedContainer = null; this._pressedItemBox = null; this._pressedHeader = null; this._pressedEntity = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }; this._pressedPosition = null; this.initialize(modeSite); }; _SelectionMode.prototype = { _dispose: function () { if (this._itemEventsHandler) { this._itemEventsHandler.dispose(); } if (this._setNewFocusItemOffsetPromise) { this._setNewFocusItemOffsetPromise.cancel(); } }, initialize: function (modeSite) { this.site = modeSite; this._keyboardNavigationHandlers = {}; this._keyboardAcceleratorHandlers = {}; var site = this.site, that = this; this._itemEventsHandler = new WinJS.UI._ItemEventsHandler(Object.create({ containerFromElement: function (element) { return site._view.items.containerFrom(element); }, indexForItemElement: function (element) { return site._view.items.index(element); }, indexForHeaderElement: function (element) { return site._groups.index(element); }, itemBoxAtIndex: function (index) { return site._view.items.itemBoxAt(index); }, itemAtIndex: function (index) { return site._view.items.itemAt(index); }, headerAtIndex: function (index) { return site._groups.group(index).header; }, containerAtIndex: function (index) { return site._view.items.containerAt(index); }, isZombie: function () { return site._isZombie(); }, getItemPosition: function (entity) { return site._getItemPosition(entity); }, rtl: function () { return site._rtl(); }, fireInvokeEvent: function (entity, itemElement) { return that._fireInvokeEvent(entity, itemElement); }, verifySelectionAllowed: function (index) { return that._verifySelectionAllowed(index); }, changeFocus: function (newFocus, skipSelection, ctrlKeyDown, skipEnsureVisible, keyboardFocused) { return site._changeFocus(newFocus, skipSelection, ctrlKeyDown, skipEnsureVisible, keyboardFocused); }, selectRange: function (firstIndex, lastIndex, additive) { return that._selectRange(firstIndex, lastIndex, additive); } }, { pressedEntity: { enumerable: true, get: function () { return that._pressedEntity; }, set: function (value) { that._pressedEntity = value; } }, pressedContainerScaleTransform: { enumerable: true, get: function () { return that._pressedContainerScaleTransform; }, set: function (value) { that._pressedContainerScaleTransform = value; } }, pressedContainer: { enumerable: true, get: function () { return that._pressedContainer; }, set: function (value) { that._pressedContainer = value; } }, pressedItemBox: { enumerable: true, get: function () { return that._pressedItemBox; }, set: function (value) { that._pressedItemBox = value; } }, pressedHeader: { enumerable: true, get: function () { return that._pressedHeader; }, set: function (value) { return that._pressedHeader = value; } }, pressedPosition: { enumerable: true, get: function () { return that._pressedPosition; }, set: function (value) { that._pressedPosition = value; } }, pressedElement: { enumerable: true, set: function (value) { that._pressedElement = value; } }, swipeBehavior: { enumerable: true, get: function () { return site._swipeBehavior; } }, eventHandlerRoot: { enumerable: true, get: function () { return site._viewport; } }, selectionMode: { enumerable: true, get: function () { return site._selectionMode; } }, accessibleItemClass: { enumerable: true, get: function () { // CSS class of the element with the aria role return WinJS.UI._itemClass; } }, canvasProxy: { enumerable: true, get: function () { return site._canvasProxy; } }, tapBehavior: { enumerable: true, get: function () { return site._tap; } }, draggable: { enumerable: true, get: function () { return site.itemsDraggable || site.itemsReorderable; } }, selection: { enumerable: true, get: function () { return site._selection; } }, horizontal: { enumerable: true, get: function () { return site._horizontal(); } }, customFootprintParent: { enumerable: true, get: function () { return null; } } })); function createArrowHandler(direction, clampToBounds) { var handler = function (oldFocus) { return modeSite._view.getAdjacent(oldFocus, direction); }; handler.clampToBounds = clampToBounds; return handler; } var Key = utilities.Key; this._keyboardNavigationHandlers[Key.upArrow] = createArrowHandler(Key.upArrow); this._keyboardNavigationHandlers[Key.downArrow] = createArrowHandler(Key.downArrow); this._keyboardNavigationHandlers[Key.leftArrow] = createArrowHandler(Key.leftArrow); this._keyboardNavigationHandlers[Key.rightArrow] = createArrowHandler(Key.rightArrow); this._keyboardNavigationHandlers[Key.pageUp] = createArrowHandler(Key.pageUp, true); this._keyboardNavigationHandlers[Key.pageDown] = createArrowHandler(Key.pageDown, true); this._keyboardNavigationHandlers[Key.home] = function (oldFocus) { return WinJS.Promise.wrap({ type: oldFocus.type, index: 0 }); }; this._keyboardNavigationHandlers[Key.end] = function (oldFocus) { if (oldFocus.type === WinJS.UI.ObjectType.groupHeader) { return WinJS.Promise.wrap({ type: oldFocus.type, index: site._groups.length() - 1 }); } else { // Get the index of the last container return that.site._view.finalItem().then(function (index) { return { type: oldFocus.type, index: index }; }, function (error) { return WinJS.Promise.wrapError(error); }); } }; this._keyboardAcceleratorHandlers[Key.a] = function () { if (that.site._multiSelection()) { that._selectAll(); } }; }, staticMode: function SelectionMode_staticMode() { return this.site._tap === WinJS.UI.TapBehavior.none && this.site._selectionMode === WinJS.UI.SelectionMode.none; }, itemUnrealized: function SelectionMode_itemUnrealized(index, itemBox) { if (this._pressedEntity.type === WinJS.UI.ObjectType.groupHeader) { return; } if (this._pressedEntity.index === index) { this._resetPointerDownState(); } if (this._itemBeingDragged(index)) { for (var i = this._draggedItemBoxes.length - 1; i >= 0; i--) { if (this._draggedItemBoxes[i] === itemBox) { utilities.removeClass(itemBox, WinJS.UI._dragSourceClass); this._draggedItemBoxes.splice(i, 1); } } } }, _fireInvokeEvent: function SelectionMode_fireInvokeEvent(entity, itemElement) { if (!itemElement) { return; } var that = this; function fireInvokeEventImpl(dataSource, isHeader) { var listBinding = dataSource.createListBinding(), promise = listBinding.fromIndex(entity.index), eventName = isHeader ? "groupheaderinvoked" : "iteminvoked"; promise.done(function (item) { listBinding.release(); }); var eventObject = document.createEvent("CustomEvent"); eventObject.initCustomEvent(eventName, true, true, isHeader ? { groupHeaderPromise: promise, groupHeaderIndex: entity.index } : { itemPromise: promise, itemIndex: entity.index }); // If preventDefault was not called, call the default action on the site if (itemElement.dispatchEvent(eventObject)) { that.site._defaultInvoke(entity); } } if (entity.type === WinJS.UI.ObjectType.groupHeader) { if (this.site._groupHeaderTap === WinJS.UI.GroupHeaderTapBehavior.invoke && entity.index !== WinJS.UI._INVALID_INDEX) { fireInvokeEventImpl(this.site.groupDataSource, true); } } else { if (this.site._tap !== WinJS.UI.TapBehavior.none && entity.index !== WinJS.UI._INVALID_INDEX) { fireInvokeEventImpl(this.site.itemDataSource, false); } } }, _verifySelectionAllowed: function SelectionMode_verifySelectionAllowed(entity) { if (entity.type === WinJS.UI.ObjectType.groupHeader) { return { canSelect: false, canTapSelect: false }; } var itemIndex = entity.index; var site = this.site; var item = this.site._view.items.itemAt(itemIndex); if (site._selectionAllowed() && (site._selectOnTap() || site._swipeBehavior === WinJS.UI.SwipeBehavior.select) && !(item && utilities.hasClass(item, WinJS.UI._nonSelectableClass))) { var selected = site._selection._isIncluded(itemIndex), single = !site._multiSelection(), newSelection = site._selection._cloneSelection(); if (selected) { if (single) { newSelection.clear(); } else { newSelection.remove(itemIndex); } } else { if (single) { newSelection.set(itemIndex); } else { newSelection.add(itemIndex); } } var eventObject = document.createEvent("CustomEvent"), newSelectionUpdated = Promise.wrap(), completed = false, preventTap = false, included; eventObject.initCustomEvent("selectionchanging", true, true, { newSelection: newSelection, preventTapBehavior: function () { preventTap = true; }, setPromise: function (promise) { /// /// /// Used to inform the ListView that asynchronous work is being performed, and that this /// event handler should not be considered complete until the promise completes. /// /// /// The promise to wait for. /// /// newSelectionUpdated = promise; } }); var defaultBehavior = site._element.dispatchEvent(eventObject); newSelectionUpdated.then(function () { completed = true; included = newSelection._isIncluded(itemIndex); newSelection.clear(); }); var canSelect = defaultBehavior && completed && (selected || included); return { canSelect: canSelect, canTapSelect: canSelect && !preventTap }; } else { return { canSelect: false, canTapSelect: false }; } }, _containedInElementWithClass: function SelectionMode_containedInElementWithClass(element, className) { if (element.parentNode) { var matches = element.parentNode.querySelectorAll("." + className + ", ." + className + " *"); for (var i = 0, len = matches.length; i < len; i++) { if (matches[i] === element) { return true; } } } return false; }, _isDraggable: function SelectionMode_isDraggable(element) { return (!this._containedInElementWithClass(element, WinJS.UI._nonDraggableClass)); }, _isInteractive: function SelectionMode_isInteractive(element) { return this._containedInElementWithClass(element, "win-interactive"); }, _resetPointerDownState: function SelectionMode_resetPointerDownState() { this._itemEventsHandler.resetPointerDownState(); }, onMSManipulationStateChanged: function (eventObject) { this._itemEventsHandler.onMSManipulationStateChanged(eventObject); }, onPointerDown: function SelectionMode_onPointerDown(eventObject) { this._itemEventsHandler.onPointerDown(eventObject); }, onclick: function SelectionMode_onclick(eventObject) { this._itemEventsHandler.onClick(eventObject); }, onPointerUp: function SelectionMode_onPointerUp(eventObject) { this._itemEventsHandler.onPointerUp(eventObject); }, onPointerCancel: function SelectionMode_onPointerCancel(eventObject) { this._itemEventsHandler.onPointerCancel(eventObject); }, onLostPointerCapture: function SelectionMode_onLostPointerCapture(eventObject) { this._itemEventsHandler.onLostPointerCapture(eventObject); }, onContextMenu: function SelectionMode_onContextMenu(eventObject) { this._itemEventsHandler.onContextMenu(eventObject); }, onMSHoldVisual: function SelectionMode_onMSHoldVisual(eventObject) { this._itemEventsHandler.onMSHoldVisual(eventObject); }, onDataChanged: function SelectionMode_onDataChanged(eventObject) { this._itemEventsHandler.onDataChanged(eventObject); }, _removeTransform: function SelectionMode_removeTransform(element, transform) { if (transform && element.style.transform.indexOf(transform) !== -1) { element.style.transform = element.style.transform.replace(transform, ""); } }, _selectAll: function SelectionMode_selectAll() { var unselectableRealizedItems = []; this.site._view.items.each(function (index, item, itemData) { if (item && utilities.hasClass(item, WinJS.UI._nonSelectableClass)) { unselectableRealizedItems.push(index); } }); this.site._selection.selectAll(); if (unselectableRealizedItems.length > 0) { this.site._selection.remove(unselectableRealizedItems); } }, _selectRange: function SelectionMode_selectRange(firstIndex, lastIndex, additive) { var ranges = []; var currentStartRange = -1; for (var i = firstIndex; i <= lastIndex; i++) { var item = this.site._view.items.itemAt(i); if (item && utilities.hasClass(item, WinJS.UI._nonSelectableClass)) { if (currentStartRange !== -1) { ranges.push({ firstIndex: currentStartRange, lastIndex: i - 1 }); currentStartRange = -1; } } else if (currentStartRange === -1) { currentStartRange = i; } } if (currentStartRange !== -1) { ranges.push({ firstIndex: currentStartRange, lastIndex: lastIndex }); } if (ranges.length > 0) { this.site._selection[additive ? "add" : "set"](ranges); } }, onDragStart: function SelectionMode_onDragStart(eventObject) { this._pressedEntity = { type: WinJS.UI.ObjectType.item, index: this.site._view.items.index(eventObject.srcElement) }; this.site._selection._pivot = WinJS.UI._INVALID_INDEX; // Drag shouldn't be initiated when the user holds down the mouse on a win-interactive element and moves. // The problem is that the dragstart event's srcElement+target will both be an itembox (which has draggable=true), so we can't check for win-interactive in the dragstart event handler. // The itemEventsHandler sets our _pressedElement field on MSPointerDown, so we use that instead when checking for interactive. if (this._pressedEntity.index !== WinJS.UI._INVALID_INDEX && (this.site.itemsDraggable || this.site.itemsReorderable) && !this.site._view.animating && this._isDraggable(eventObject.srcElement) && (!this._pressedElement || !this._isInteractive(this._pressedElement))) { this._dragging = true; this._dragDataTransfer = eventObject.dataTransfer; this._pressedPosition = WinJS.UI._getCursorPos(eventObject); this._dragInfo = null; this._lastEnteredElement = eventObject.srcElement; if (this.site._selection._isIncluded(this._pressedEntity.index)) { this._dragInfo = this.site.selection; } else { this._draggingUnselectedItem = true; this._dragInfo = new WinJS.UI._Selection(this.site, [{ firstIndex: this._pressedEntity.index, lastIndex: this._pressedEntity.index }]); } var dropTarget = this.site.itemsReorderable; var event = document.createEvent("CustomEvent"); event.initCustomEvent("itemdragstart", true, false, { dataTransfer: eventObject.dataTransfer, dragInfo: this._dragInfo }); this.site.element.dispatchEvent(event); if (this.site.itemsDraggable && !this.site.itemsReorderable) { if (!this._firedDragEnter) { if (this._fireDragEnterEvent(eventObject.dataTransfer)) { dropTarget = true; this._dragUnderstood = true; } } } if (dropTarget) { this._addedDragOverClass = true; utilities.addClass(this.site._element, WinJS.UI._dragOverClass); } this._draggedItemBoxes = []; var that = this; // A dragged element can be removed from the DOM by a number of actions - datasource removes/changes, being scrolled outside of the realized range, etc. // The dragend event is fired on the original source element of the drag. If that element isn't in the DOM, though, the dragend event will only be fired on the element // itself and not bubble up through the ListView's tree to the _viewport element where all the other drag event handlers are. // The dragend event handler has to be added to the event's srcElement so that we always receive the event, even when the source element is unrealized. var sourceElement = eventObject.srcElement; sourceElement.addEventListener("dragend", function itemDragEnd(eventObject) { sourceElement.removeEventListener("dragend", itemDragEnd); that.onDragEnd(eventObject); }); // We delay setting the opacity of the dragged items so that IE has time to create a thumbnail before me make them invisible setImmediate(function () { if (that._dragging) { var indicesSelected = that._dragInfo.getIndices(); for (var i = 0, len = indicesSelected.length; i < len; i++) { var itemData = that.site._view.items.itemDataAt(indicesSelected[i]); if (itemData && itemData.itemBox) { that._addDragSourceClass(itemData.itemBox); } } } }); } else { eventObject.preventDefault(); } }, onDragEnter: function (eventObject) { var eventHandled = this._dragUnderstood; this._lastEnteredElement = eventObject.srcElement; if (this._exitEventTimer) { clearTimeout(this._exitEventTimer); this._exitEventTimer = 0; } if (!this._firedDragEnter) { if (this._fireDragEnterEvent(eventObject.dataTransfer)) { eventHandled = true; } } if (eventHandled || (this._dragging && this.site.itemsReorderable)) { eventObject.preventDefault(); this._dragUnderstood = true; if (!this._addedDragOverClass) { this._addedDragOverClass = true; utilities.addClass(this.site._element, WinJS.UI._dragOverClass); } } this._pointerLeftRegion = false; }, onDragLeave: function (eventObject) { if (eventObject.srcElement === this._lastEnteredElement) { this._pointerLeftRegion = true; this._handleExitEvent(); } }, fireDragUpdateEvent: function () { var event = document.createEvent("CustomEvent"); event.initCustomEvent("itemdragchanged", true, false, { dataTransfer: this._dragDataTransfer, dragInfo: this._dragInfo }); this.site.element.dispatchEvent(event); }, _fireDragEnterEvent: function (dataTransfer) { var event = document.createEvent("CustomEvent"); event.initCustomEvent("itemdragenter", true, true, { dataTransfer: dataTransfer }); // The end developer must tell a ListView when a drag can be understood by calling preventDefault() on the event we fire var dropTarget = (!this.site.element.dispatchEvent(event)); this._firedDragEnter = true; return dropTarget; }, _fireDragBetweenEvent: function (index, insertAfterIndex, dataTransfer) { var event = document.createEvent("CustomEvent"); event.initCustomEvent("itemdragbetween", true, true, { index: index, insertAfterIndex: insertAfterIndex, dataTransfer: dataTransfer }); return this.site.element.dispatchEvent(event); }, _fireDropEvent: function (index, insertAfterIndex, dataTransfer) { var event = document.createEvent("CustomEvent"); event.initCustomEvent("itemdragdrop", true, true, { index: index, insertAfterIndex: insertAfterIndex, dataTransfer: dataTransfer }); return this.site.element.dispatchEvent(event); }, _handleExitEvent: function () { if (this._exitEventTimer) { clearTimeout(this._exitEventTimer); this._exitEventTimer = 0; } var that = this; this._exitEventTimer = setTimeout(function () { if (that._pointerLeftRegion) { that.site._layout.dragLeave && that.site._layout.dragLeave(); that._pointerLeftRegion = false; that._dragUnderstood = false; that._lastEnteredElement = null; that._lastInsertPoint = null; that._dragBetweenDisabled = false; if (that._firedDragEnter) { var event = document.createEvent("CustomEvent"); event.initCustomEvent("itemdragleave", true, false, { }); that.site.element.dispatchEvent(event); that._firedDragEnter = false; } if (that._addedDragOverClass) { that._addedDragOverClass = false; utilities.removeClass(that.site._element, WinJS.UI._dragOverClass); } that._exitEventTimer = 0; that._stopAutoScroll(); } }, 40); }, _getEventPositionInElementSpace: function (element, eventObject) { var elementRect = { left: 0, top: 0 }; try { elementRect = element.getBoundingClientRect(); } catch (err) { } var computedStyle = window.getComputedStyle(element, null), paddingLeft = parseInt(computedStyle["paddingLeft"]), paddingTop = parseInt(computedStyle["paddingTop"]), borderLeft = parseInt(computedStyle["borderLeftWidth"]), borderTop = parseInt(computedStyle["borderTopWidth"]), clientX = eventObject.clientX, clientY = eventObject.clientY; var position = { x: +clientX === clientX ? (clientX - elementRect.left - paddingLeft - borderLeft) : 0, y: +clientY === clientY ? (clientY - elementRect.top - paddingTop - borderTop) : 0 }; if (this.site._rtl()) { position.x = (elementRect.right - elementRect.left) - position.x; } return position; }, _getPositionInCanvasSpace: function (eventObject) { var scrollLeft = this.site._horizontal() ? this.site.scrollPosition : 0, scrollTop = this.site._horizontal() ? 0 : this.site.scrollPosition, position = this._getEventPositionInElementSpace(this.site.element, eventObject); return { x: position.x + scrollLeft, y: position.y + scrollTop }; }, _itemBeingDragged: function (itemIndex) { if (!this._dragging) { return false; } return ((this._draggingUnselectedItem && this._dragInfo._isIncluded(itemIndex)) || (!this._draggingUnselectedItem && this.site._isSelected(itemIndex))); }, _addDragSourceClass: function (itemBox) { this._draggedItemBoxes.push(itemBox); utilities.addClass(itemBox, WinJS.UI._dragSourceClass); if (itemBox.parentNode) { utilities.addClass(itemBox.parentNode, WinJS.UI._footprintClass); } }, renderDragSourceOnRealizedItem: function (itemIndex, itemBox) { if (this._itemBeingDragged(itemIndex)) { this._addDragSourceClass(itemBox); } }, onDragOver: function (eventObject) { if (!this._dragUnderstood) { return; } this._pointerLeftRegion = false; eventObject.preventDefault(); var cursorPositionInCanvas = this._getPositionInCanvasSpace(eventObject), cursorPositionInRoot = this._getEventPositionInElementSpace(this.site.element, eventObject); this._checkAutoScroll(cursorPositionInRoot.x, cursorPositionInRoot.y); if (this.site._layout.hitTest) { if (this._autoScrollFrame) { if (this._lastInsertPoint) { this.site._layout.dragLeave(); this._lastInsertPoint = null; } } else { var insertPoint = this.site._view.hitTest(cursorPositionInCanvas.x, cursorPositionInCanvas.y); insertPoint.insertAfterIndex = clampToRange(-1, this.site._cachedCount - 1, insertPoint.insertAfterIndex); if (!this._lastInsertPoint || this._lastInsertPoint.insertAfterIndex !== insertPoint.insertAfterIndex || this._lastInsertPoint.index !== insertPoint.index) { this._dragBetweenDisabled = !this._fireDragBetweenEvent(insertPoint.index, insertPoint.insertAfterIndex, eventObject.dataTransfer); if (!this._dragBetweenDisabled) { this.site._layout.dragOver(cursorPositionInCanvas.x, cursorPositionInCanvas.y, this._dragInfo); } else { this.site._layout.dragLeave(); } } this._lastInsertPoint = insertPoint; } } }, _clearDragProperties: function () { if (this._addedDragOverClass) { this._addedDragOverClass = false; utilities.removeClass(this.site._element, WinJS.UI._dragOverClass); } if (this._draggedItemBoxes) { for (var i = 0, len = this._draggedItemBoxes.length; i < len; i++) { utilities.removeClass(this._draggedItemBoxes[i], WinJS.UI._dragSourceClass); if (this._draggedItemBoxes[i].parentNode) { utilities.removeClass(this._draggedItemBoxes[i].parentNode, WinJS.UI._footprintClass); } } this._draggedItemBoxes = []; } this.site._layout.dragLeave(); this._dragging = false; this._dragInfo = null; this._draggingUnselectedItem = false; this._dragDataTransfer = null; this._lastInsertPoint = null; this._resetPointerDownState(); this._lastEnteredElement = null; this._dragBetweenDisabled = false; this._firedDragEnter = false; this._dragUnderstood = false; this._stopAutoScroll(); }, onDragEnd: function (eventObject) { var event = document.createEvent("CustomEvent"); event.initCustomEvent("itemdragend", true, false, {}); this.site.element.dispatchEvent(event); this._clearDragProperties(); }, _findFirstAvailableInsertPoint: function (selectedItems, startIndex, searchForwards) { var indicesSelected = selectedItems.getIndices(), dropIndexInSelection = -1, count = this.site._cachedCount, selectionCount = indicesSelected.length, startIndexInSelection = -1, dropIndex = startIndex; for (var i = 0; i < selectionCount; i++) { if (indicesSelected[i] === dropIndex) { dropIndexInSelection = i; startIndexInSelection = i; break; } } while (dropIndexInSelection >= 0 && dropIndex >= 0) { if (searchForwards) { dropIndex++; if (dropIndexInSelection < selectionCount && indicesSelected[dropIndexInSelection + 1] === dropIndex && dropIndex < count) { dropIndexInSelection++; } else if (dropIndex >= count) { // If we hit the end of the list when looking for a new location ahead of our start index, it means everything from the starting point // to the end is selected, so no valid index can be located to move the items. We need to start searching again, moving backwards // from the starting location, to find the first available insert location to move the selected items. searchForwards = false; dropIndex = startIndex; dropIndexInSelection = startIndexInSelection; } else { dropIndexInSelection = -1; } } else { dropIndex--; if (dropIndexInSelection > 0 && indicesSelected[dropIndexInSelection - 1] === dropIndex) { dropIndexInSelection--; } else { dropIndexInSelection = -1; } } } return dropIndex; }, _reorderItems: function (dropIndex, reorderedItems, reorderingUnselectedItem, useMoveBefore, ensureVisibleAtEnd) { var site = this.site; var updateSelection = function updatedSelectionOnDrop(items) { // Update selection if the items were selected. If there is a range with length > 0 a move operation // on the first or last item removes the range. if (!reorderingUnselectedItem) { site._selection.set({ firstKey: items[0].key, lastKey: items[items.length - 1].key }); } else { site._selection.remove({ key: items[0].key }); } if (ensureVisibleAtEnd) { site.ensureVisible(site._selection._getFocused()); } } reorderedItems.getItems().then(function (items) { var ds = site.itemDataSource; if (dropIndex === -1) { ds.beginEdits(); for (var i = items.length - 1; i >= 0; i--) { ds.moveToStart(items[i].key); } ds.endEdits(); updateSelection(items); } else { var listBinding = ds.createListBinding(); listBinding.fromIndex(dropIndex).then(function (item) { listBinding.release(); ds.beginEdits(); if (useMoveBefore) { for (var i = 0, len = items.length; i < len; i++) { ds.moveBefore(items[i].key, item.key); } } else { for (var i = items.length - 1; i >= 0; i--) { ds.moveAfter(items[i].key, item.key); } } ds.endEdits(); updateSelection(items); }); } }); }, onDrop: function SelectionMode_onDrop(eventObject) { // If the listview or the handler of the drop event we fire triggers a reorder, the dragged items can end up having different container nodes than what they started with. // Because of that, we need to remove the footprint class from the item boxes' containers before we do any processing of the drop event. if (this._draggedItemBoxes) { for (var i = 0, len = this._draggedItemBoxes.length; i < len; i++) { if (this._draggedItemBoxes[i].parentNode) { utilities.removeClass(this._draggedItemBoxes[i].parentNode, WinJS.UI._footprintClass); } } } if (!this._dragBetweenDisabled) { var cursorPosition = this._getPositionInCanvasSpace(eventObject); var dropLocation = this.site._view.hitTest(cursorPosition.x, cursorPosition.y), dropIndex = clampToRange(-1, this.site._cachedCount - 1, dropLocation.insertAfterIndex), allowDrop = true; // We don't fire dragBetween events during autoscroll, so if a user drops during autoscroll, we need to get up to date information // on the drop location, and fire dragBetween before the insert so that the developer can prevent the drop if they choose. if (!this._lastInsertPoint || this._lastInsertPoint.insertAfterIndex !== dropIndex || this._lastInsertPoint.index !== dropLocation.index) { allowDrop = this._fireDragBetweenEvent(dropLocation.index, dropIndex, eventObject.dataTransfer); } if (allowDrop) { this._lastInsertPoint = null; this.site._layout.dragLeave(); if (this._fireDropEvent(dropLocation.index, dropIndex, eventObject.dataTransfer) && this._dragging && this.site.itemsReorderable) { if (this._dragInfo.isEverything() || this.site._groupsEnabled()) { return; } dropIndex = this._findFirstAvailableInsertPoint(this._dragInfo, dropIndex, false); this._reorderItems(dropIndex, this._dragInfo, this._draggingUnselectedItem); } } } this._clearDragProperties(); }, _checkAutoScroll: function (x, y) { var viewportSize = this.site._getViewportLength(), horizontal = this.site._horizontal(), cursorPositionInViewport = (horizontal ? x : y), rtl = this.site._rtl(), canvasMargins = this.site._getCanvasMargins(), canvasSize = this.site._canvas[horizontal ? "offsetWidth" : "offsetHeight"] + canvasMargins[(horizontal ? (rtl ? "right" : "left") : "top")], scrollPosition = Math.floor(this.site.scrollPosition), travelRate = 0; if (cursorPositionInViewport < WinJS.UI._AUTOSCROLL_THRESHOLD) { travelRate = cursorPositionInViewport - WinJS.UI._AUTOSCROLL_THRESHOLD; } else if (cursorPositionInViewport > (viewportSize - WinJS.UI._AUTOSCROLL_THRESHOLD)) { travelRate = (cursorPositionInViewport - (viewportSize - WinJS.UI._AUTOSCROLL_THRESHOLD)); } travelRate = Math.round((travelRate / WinJS.UI._AUTOSCROLL_THRESHOLD) * (WinJS.UI._MAX_AUTOSCROLL_RATE - WinJS.UI._MIN_AUTOSCROLL_RATE)); // If we're at the edge of the content, we don't need to keep scrolling. We'll set travelRate to 0 to stop the autoscroll timer. if ((scrollPosition === 0 && travelRate < 0) || (scrollPosition >= (canvasSize - viewportSize) && travelRate > 0)) { travelRate = 0; } if (travelRate === 0) { if (this._autoScrollDelay) { clearTimeout(this._autoScrollDelay); this._autoScrollDelay = 0; } } else { if (!this._autoScrollDelay && !this._autoScrollFrame) { var that = this; this._autoScrollDelay = setTimeout(function () { if (that._autoScrollRate) { that._lastDragTimeout = performance.now(); var nextFrame = function () { if ((!that._autoScrollRate && that._autoScrollFrame) || that.site._disposed) { that._stopAutoScroll(); } else { // Timeout callbacks aren't reliably timed, so extra math is needed to figure out how far the scroll position should move since the last callback var currentTime = performance.now(); var delta = that._autoScrollRate * ((currentTime - that._lastDragTimeout) / 1000); delta = (delta < 0 ? Math.min(-1, delta) : Math.max(1, delta)); that.site._viewport[that.site._scrollProperty] += delta; that._lastDragTimeout = currentTime; that._autoScrollFrame = requestAnimationFrame(nextFrame); } }; that._autoScrollFrame = requestAnimationFrame(nextFrame); } }, WinJS.UI._AUTOSCROLL_DELAY); } } this._autoScrollRate = travelRate; }, _stopAutoScroll: function () { if (this._autoScrollDelay) { clearTimeout(this._autoScrollDelay); this._autoScrollDelay = 0; } this._autoScrollRate = 0; this._autoScrollFrame = 0; }, onKeyDown: function SelectionMode_onKeyDown(eventObject) { var that = this, site = this.site, swipeEnabled = site._swipeBehavior === WinJS.UI.SwipeBehavior.select, view = site._view, oldEntity = site._selection._getFocused(), handled = true, handlerName, ctrlKeyDown = eventObject.ctrlKey; function setNewFocus(newEntity, skipSelection, clampToBounds) { function setNewFocusImpl(maxIndex) { var moveView = true, invalidIndex = false; // Since getKeyboardNavigatedItem is purely geometry oriented, it can return us out of bounds numbers, so this check is necessary if (clampToBounds) { newEntity.index = Math.max(0, Math.min(maxIndex, newEntity.index)); } else if (newEntity.index < 0 || newEntity.index > maxIndex) { invalidIndex = true; } if (!invalidIndex && (oldEntity.index !== newEntity.index || oldEntity.type !== newEntity.type)) { var changeFocus = dispatchKeyboardNavigating(site._element, oldEntity, newEntity); if (changeFocus) { moveView = false; // If the oldEntity is completely off-screen then we mimic the desktop // behavior. This is consistent with navbar keyboarding. if (that._setNewFocusItemOffsetPromise) { that._setNewFocusItemOffsetPromise.cancel(); } site._batchViewUpdates(WinJS.UI._ViewChange.realize, WinJS.UI._ScrollToPriority.high, function () { that._setNewFocusItemOffsetPromise = site._getItemOffset(oldEntity, true).then(function (range) { range = site._convertFromCanvasCoordinates(range); var oldItemOffscreen = range.end <= site.scrollPosition || range.begin >= site.scrollPosition + site._getViewportLength() - 1; that._setNewFocusItemOffsetPromise = site._getItemOffset(newEntity).then(function (range) { that._setNewFocusItemOffsetPromise = null; var retVal = { position: site.scrollPosition, direction: "right" }; if (oldItemOffscreen) { // oldEntity is completely off-screen site._selection._setFocused(newEntity, true); range = site._convertFromCanvasCoordinates(range); if (newEntity.index > oldEntity.index) { retVal.direction = "right"; retVal.position = range.end - site._getViewportLength(); } else { retVal.direction = "left"; retVal.position = range.begin; } } site._changeFocus(newEntity, skipSelection, ctrlKeyDown, oldItemOffscreen, true); if (!oldItemOffscreen) { return Promise.cancel; } else { return retVal; } }, function (error) { site._changeFocus(newEntity, skipSelection, ctrlKeyDown, true, true); return Promise.wrapError(error); }); return that._setNewFocusItemOffsetPromise; }, function (error) { site._changeFocus(newEntity, skipSelection, ctrlKeyDown, true, true); return Promise.wrapError(error); }); return that._setNewFocusItemOffsetPromise; }, true); } } // When a key is pressed, we want to make sure the current focus is in view. If the keypress is changing to a new valid index, // _changeFocus will handle moving the viewport for us. If the focus isn't moving, though, we need to put the view back on // the current item ourselves and call setFocused(oldFocus, true) to make sure that the listview knows the focused item was // focused via keyboard and renders the rectangle appropriately. if (moveView) { site._selection._setFocused(oldEntity, true); site.ensureVisible(oldEntity); } if (invalidIndex) { return { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }; } else { return newEntity; } } // We need to get the final item in the view so that we don't try setting focus out of bounds. if (newEntity.type !== WinJS.UI.ObjectType.groupHeader) { return view.finalItem().then(setNewFocusImpl); } else { return Promise.wrap(site._groups.length() - 1).then(setNewFocusImpl); } } var Key = utilities.Key, keyCode = eventObject.keyCode, rtl = site._rtl(); if (!this._isInteractive(eventObject.srcElement)) { if (eventObject.ctrlKey && !eventObject.altKey && !eventObject.shiftKey && this._keyboardAcceleratorHandlers[keyCode]) { this._keyboardAcceleratorHandlers[keyCode](); } if (site.itemsReorderable && (!eventObject.ctrlKey && eventObject.altKey && eventObject.shiftKey && oldEntity.type === WinJS.UI.ObjectType.item) && (keyCode === Key.leftArrow || keyCode === Key.rightArrow || keyCode === Key.upArrow || keyCode === Key.downArrow)) { var selection = site._selection, focusedIndex = oldEntity.index, movingUnselectedItem = false, processReorder = true; if (!selection.isEverything()) { if (!selection._isIncluded(focusedIndex)) { var item = site._view.items.itemAt(focusedIndex); // Selected items should never be marked as non draggable, so we only need to check for nonDraggableClass when trying to reorder an unselected item. if (item && utilities.hasClass(item, WinJS.UI._nonDraggableClass)) { processReorder = false; } else { movingUnselectedItem = true; selection = new WinJS.UI._Selection(this.site, [{ firstIndex: focusedIndex, lastIndex: focusedIndex }]); } } if (processReorder) { var dropIndex = focusedIndex; if (keyCode === Key.rightArrow) { dropIndex += (rtl ? -1 : 1); } else if (keyCode === Key.leftArrow) { dropIndex += (rtl ? 1 : -1); } else if (keyCode === Key.upArrow) { dropIndex--; } else { dropIndex++; } // If the dropIndex is larger than the original index, we're trying to move items forward, so the search for the first unselected item to insert after should move forward. var movingAhead = (dropIndex > focusedIndex), searchForward = movingAhead; if (movingAhead && dropIndex >= this.site._cachedCount) { // If we're at the end of the list and trying to move items forward, dropIndex should be >= cachedCount. // That doesn't mean we don't have to do any reordering, though. A selection could be broken down into // a few blocks. We need to make the selection contiguous after this reorder, so we've got to search backwards // to find the first unselected item, then move everything in the selection after it. searchForward = false; dropIndex = this.site._cachedCount - 1; } dropIndex = this._findFirstAvailableInsertPoint(selection, dropIndex, searchForward); dropIndex = Math.min(Math.max(-1, dropIndex), this.site._cachedCount - 1); var reportedInsertAfterIndex = dropIndex - (movingAhead || dropIndex === -1 ? 0 : 1), reportedIndex = dropIndex, groupsEnabled = this.site._groupsEnabled(); if (groupsEnabled) { // The indices we picked for the index/insertAfterIndex to report in our events is always correct in an ungrouped list, // and mostly correct in a grouped list. The only problem occurs when you move an item (or items) ahead into a new group, // or back into a previous group, such that the items should be the first/last in the group. Take this list as an example: // [Group A] [a] [b] [c] [Group B] [d] [e] // When [d] is focused, right/down arrow reports index: 4, insertAfterIndex: 4, which is right -- it means move [d] after [e]. // Similarily, when [c] is focused and left/up is pressed, we report index: 1, insertAfterIndex: 0 -- move [c] to after [a]. // Take note that index does not tell us where focus is / what item is being moved. // Like mouse/touch DnD, index tells us what the dragBetween slots would be were we to animate a dragBetween. // The problem cases are moving backwards into a previous group, or forward into the next group. // If [c] were focused and the user pressed right/down, we would report index: 3, insertAfterIndex: 3. In other words, move [c] after [d]. // That's not right at all - [c] needs to become the first element of [Group B]. When we're moving ahead, then, and our dropIndex // is the first index of a new group, we adjust insertAfterIndex to be dropIndex - 1. Now we'll report index:3, insertAfterIndex: 2, which means // [c] is now the first element of [Group B], rather than the last element of [Group A]. This is exactly the same as what we would report when // the user mouse/touch drags [c] right before [d]. // Similarily, when [d] is focused and we press left/up, without the logic below we would report index: 2, insertAfterIndex: 1, so we'd try to move // [d] ahead of [b]. Again, [d] first needs the opportunity to become the last element in [Group A], so we adjust the insertAfterIndex up by 1. // We then will report index:2, insertAfterIndex:2, meaning insert [d] in [Group A] after [c], which again mimics the mouse/touch API. var groups = this.site._groups, groupIndex = (dropIndex > -1 ? groups.groupFromItem(dropIndex) : 0); if (movingAhead) { if (groups.group(groupIndex).startIndex === dropIndex) { reportedInsertAfterIndex--; } } else if (groupIndex < (groups.length() - 1) && dropIndex === (groups.group(groupIndex + 1).startIndex - 1)) { reportedInsertAfterIndex++; } } if (this._fireDragBetweenEvent(reportedIndex, reportedInsertAfterIndex, null) && this._fireDropEvent(reportedIndex, reportedInsertAfterIndex, null)) { if (groupsEnabled) { return; } this._reorderItems(dropIndex, selection, movingUnselectedItem, !movingAhead, true); } } } } else if (!eventObject.altKey) { if (this._keyboardNavigationHandlers[keyCode]) { this._keyboardNavigationHandlers[keyCode](oldEntity).then(function (newEntity) { var clampToBounds = that._keyboardNavigationHandlers[keyCode].clampToBounds; if (newEntity.type !== WinJS.UI.ObjectType.groupHeader && eventObject.shiftKey && site._selectionAllowed() && site._multiSelection()) { // Shift selection should work when shift or shift+ctrl are depressed if (site._selection._pivot === WinJS.UI._INVALID_INDEX) { site._selection._pivot = oldEntity.index; } setNewFocus(newEntity, true, clampToBounds).then(function (newEntity) { if (newEntity.index !== WinJS.UI._INVALID_INDEX) { var firstIndex = Math.min(newEntity.index, site._selection._pivot), lastIndex = Math.max(newEntity.index, site._selection._pivot), additive = (eventObject.ctrlKey || site._tap === WinJS.UI.TapBehavior.toggleSelect); that._selectRange(firstIndex, lastIndex, additive); } }); } else { site._selection._pivot = WinJS.UI._INVALID_INDEX; setNewFocus(newEntity, false, clampToBounds); } }); } else if (!eventObject.ctrlKey && keyCode === Key.enter) { var element = oldEntity.type === WinJS.UI.ObjectType.groupHeader ? site._groups.group(oldEntity.index).header : site._view.items.itemBoxAt(oldEntity.index); if (element) { if (oldEntity.type === WinJS.UI.ObjectType.groupHeader) { this._pressedHeader = element; this._pressedItemBox = null; this._pressedContainer = null; } else { this._pressedItemBox = element; this._pressedContainer = site._view.items.containerAt(oldEntity.index); this._pressedHeader = null; } var allowed = this._verifySelectionAllowed(oldEntity); if (allowed.canTapSelect) { this._itemEventsHandler.handleTap(oldEntity); } this._fireInvokeEvent(oldEntity, element); } } else if (oldEntity.type !== WinJS.UI.ObjectType.groupHeader && ((eventObject.ctrlKey && keyCode === Key.enter) || (swipeEnabled && eventObject.shiftKey && keyCode === Key.F10) || (swipeEnabled && keyCode === Key.menu) || keyCode === Key.space)) { // Swipe emulation this._itemEventsHandler.handleSwipeBehavior(oldEntity.index); site._changeFocus(oldEntity, true, ctrlKeyDown, false, true); } else if (keyCode === Key.escape && site._selection.count() > 0) { site._selection._pivot = WinJS.UI._INVALID_INDEX; site._selection.clear(); } else { handled = false; } } else { handled = false; } this._keyDownHandled = handled; if (handled) { eventObject.stopPropagation(); eventObject.preventDefault(); } } if (keyCode === Key.tab) { this.site._keyboardFocusInbound = true; } }, onKeyUp: function (eventObject) { if (this._keyDownHandled) { eventObject.stopPropagation(); eventObject.preventDefault(); } }, onTabEnter: function (eventObject) { if (this.site._groups.length() == 0) { return; } var site = this.site, focused = site._selection._getFocused(), forward = eventObject.detail; // We establish whether focus is incoming on the ListView by checking keyboard focus and the srcElement. // If the ListView did not have keyboard focus, then it is definitely incoming since keyboard focus is cleared // on blur which works for 99% of all scenarios. When the ListView is the only tabbable element on the page, // then tabbing out of the ListView will make focus wrap around and focus the ListView again. The blur event is // handled after TabEnter, so the keyboard focus flag is not yet cleared. Therefore, we examine the srcElement and see // if it is the canvas/surface since it is the first tabbable element in the ListView DOM tree. var inboundFocus = !site._hasKeyboardFocus || eventObject.srcElement === site._canvas; if (inboundFocus) { this.inboundFocusHandled = true; // We tabbed into the ListView focused.index = (focused.index === WinJS.UI._INVALID_INDEX ? 0 : focused.index); if (forward || !this.site._supportsGroupHeaderKeyboarding) { // We tabbed into the ListView from before the ListView, so focus should go to items var entity = { type: WinJS.UI.ObjectType.item }; if (focused.type === WinJS.UI.ObjectType.groupHeader) { entity.index = site._groupFocusCache.getIndexForGroup(focused.index); if (dispatchKeyboardNavigating(site._element, focused, entity)) { site._changeFocus(entity, true, false, false, true); } else { site._changeFocus(focused, true, false, false, true); } } else { entity.index = focused.index; site._changeFocus(entity, true, false, false, true); } } else { // We tabbed into the ListView from after the ListView, focus should go to headers var entity = { type: WinJS.UI.ObjectType.groupHeader }; if (focused.type !== WinJS.UI.ObjectType.groupHeader) { entity.index = site._groups.groupFromItem(focused.index); if (dispatchKeyboardNavigating(site._element, focused, entity)) { site._changeFocus(entity, true, false, false, true); } else { site._changeFocus(focused, true, false, false, true); } } else { entity.index = focused.index; site._changeFocus(entity, true, false, false, true); } } } }, onTabExit: function (eventObject) { if (!this.site._supportsGroupHeaderKeyboarding || this.site._groups.length() == 0) { return; } var site = this.site, focused = site._selection._getFocused(), forward = eventObject.detail; if (forward && focused.type !== WinJS.UI.ObjectType.groupHeader) { // Tabbing and we were focusing an item, go to headers var entity = { type: WinJS.UI.ObjectType.groupHeader, index: site._groups.groupFromItem(focused.index) }; if (dispatchKeyboardNavigating(site._element, focused, entity)) { site._changeFocus(entity, true, false, false, true); } } else if (!forward && focused.type === WinJS.UI.ObjectType.groupHeader) { // Shift tabbing and we were focusing a header, go to items var entity = { type: WinJS.UI.ObjectType.item, index: site._groupFocusCache.getIndexForGroup(focused.index) }; if (dispatchKeyboardNavigating(site._element, focused, entity)) { site._changeFocus(entity, true, false, false, true); } } } }; return _SelectionMode; }) }); })(this, WinJS); (function constantsInit(global, WinJS, undefined) { "use strict"; var thisWinUI = WinJS.UI; thisWinUI._listViewClass = "win-listview"; thisWinUI._viewportClass = "win-viewport"; thisWinUI._rtlListViewClass = "win-rtl"; thisWinUI._horizontalClass = "win-horizontal"; thisWinUI._verticalClass = "win-vertical"; thisWinUI._scrollableClass = "win-surface"; thisWinUI._itemsContainerClass = "win-itemscontainer"; thisWinUI._padderClass = "win-itemscontainer-padder"; thisWinUI._proxyClass = "_win-proxy"; thisWinUI._itemClass = "win-item"; thisWinUI._itemBoxClass = "win-itembox"; thisWinUI._itemsBlockClass = "win-itemsblock"; thisWinUI._containerClass = "win-container"; thisWinUI._backdropClass = "win-backdrop"; thisWinUI._footprintClass = "win-footprint"; thisWinUI._groupsClass = "win-groups"; thisWinUI._selectedClass = "win-selected"; thisWinUI._swipeableClass = "win-swipeable"; thisWinUI._swipeClass = "win-swipe"; thisWinUI._selectionBorderClass = "win-selectionborder"; thisWinUI._selectionBackgroundClass = "win-selectionbackground"; thisWinUI._selectionCheckmarkClass = "win-selectioncheckmark"; thisWinUI._selectionCheckmarkBackgroundClass = "win-selectioncheckmarkbackground"; thisWinUI._selectionPartsSelector = ".win-selectionborder, .win-selectionbackground, .win-selectioncheckmark, .win-selectioncheckmarkbackground"; thisWinUI._pressedClass = "win-pressed"; thisWinUI._headerClass = "win-groupheader"; thisWinUI._headerContainerClass = "win-groupheadercontainer"; thisWinUI._groupLeaderClass = "win-groupleader"; thisWinUI._progressClass = "win-progress"; thisWinUI._selectionHintClass = "win-selectionhint"; thisWinUI._revealedClass = "win-revealed"; thisWinUI._itemFocusClass = "win-focused"; thisWinUI._itemFocusOutlineClass = "win-focusedoutline"; thisWinUI._zoomingXClass = "win-zooming-x"; thisWinUI._zoomingYClass = "win-zooming-y"; thisWinUI._listLayoutClass = "win-listlayout"; thisWinUI._gridLayoutClass = "win-gridlayout"; thisWinUI._headerPositionTopClass = "win-headerpositiontop"; thisWinUI._headerPositionLeftClass = "win-headerpositionleft"; thisWinUI._structuralNodesClass = "win-structuralnodes"; thisWinUI._uniformGridLayoutClass = "win-uniformgridlayout"; thisWinUI._uniformListLayoutClass = "win-uniformlistlayout"; thisWinUI._cellSpanningGridLayoutClass = "win-cellspanninggridlayout"; thisWinUI._laidOutClass = "win-laidout"; thisWinUI._nonDraggableClass = "win-nondraggable"; thisWinUI._nonSelectableClass = "win-nonselectable"; thisWinUI._nonSwipeableClass = "win-nonswipeable"; thisWinUI._dragOverClass = "win-dragover"; thisWinUI._dragSourceClass = "win-dragsource"; thisWinUI._clipClass = "win-clip"; thisWinUI._INVALID_INDEX = -1; thisWinUI._UNINITIALIZED = -1; thisWinUI._LEFT_MSPOINTER_BUTTON = 0; thisWinUI._RIGHT_MSPOINTER_BUTTON = 2; thisWinUI._TAP_END_THRESHOLD = 10; thisWinUI._DEFAULT_PAGES_TO_LOAD = 5; thisWinUI._DEFAULT_PAGE_LOAD_THRESHOLD = 2; thisWinUI._MIN_AUTOSCROLL_RATE = 150; thisWinUI._MAX_AUTOSCROLL_RATE = 1500; thisWinUI._AUTOSCROLL_THRESHOLD = 100; thisWinUI._AUTOSCROLL_DELAY = 50; thisWinUI._DEFERRED_ACTION = 250; thisWinUI._DEFERRED_SCROLL_END = 250; // For horizontal layouts thisWinUI._VERTICAL_SWIPE_SELECTION_THRESHOLD = 39; thisWinUI._VERTICAL_SWIPE_SPEED_BUMP_START = 0; thisWinUI._VERTICAL_SWIPE_SPEED_BUMP_END = 127; thisWinUI._VERTICAL_SWIPE_SELF_REVEAL_GESTURE = 15; // For vertical layouts thisWinUI._HORIZONTAL_SWIPE_SELECTION_THRESHOLD = 27; thisWinUI._HORIZONTAL_SWIPE_SPEED_BUMP_START = 0; thisWinUI._HORIZONTAL_SWIPE_SPEED_BUMP_END = 150; thisWinUI._HORIZONTAL_SWIPE_SELF_REVEAL_GESTURE = 23; thisWinUI._SELECTION_CHECKMARK = "\uE081"; thisWinUI._LISTVIEW_PROGRESS_DELAY = 2000; })(this, WinJS); (function errorMessagesInit(global, WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI._strings", { modeIsInvalid: { get: function () { return WinJS.Resources._getWinJSString("ui/modeIsInvalid").value; } }, loadingBehaviorIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/loadingBehaviorIsDeprecated").value; } }, pagesToLoadIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/pagesToLoadIsDeprecated").value; } }, pagesToLoadThresholdIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/pagesToLoadThresholdIsDeprecated").value; } }, automaticallyLoadPagesIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/automaticallyLoadPagesIsDeprecated").value; } }, invalidTemplate: { get: function () { return WinJS.Resources._getWinJSString("ui/invalidTemplate").value; } }, loadMorePagesIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/loadMorePagesIsDeprecated").value; } }, disableBackdropIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/disableBackdropIsDeprecated").value; } }, backdropColorIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/backdropColorIsDeprecated").value; } }, itemInfoIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/itemInfoIsDeprecated").value; } }, groupInfoIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/groupInfoIsDeprecated").value; } }, resetItemIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/resetItemIsDeprecated").value; } }, resetGroupHeaderIsDeprecated: { get: function () { return WinJS.Resources._getWinJSString("ui/resetGroupHeaderIsDeprecated").value; } }, maxRowsIsDeprecated: { get: function() { return WinJS.Resources._getWinJSString("ui/maxRowsIsDeprecated").value; } } }); })(this, WinJS); (function GroupFocusCacheInit() { "use strict"; WinJS.Namespace.define("WinJS.UI", { _GroupFocusCache: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function GroupFocusCache_ctor(listView) { this._listView = listView; this.clear(); }, { // We store indices as strings in the cache so index=0 does not evaluate to false as // when we check for the existance of an index in the cache. The index is converted // back into a number when calling getIndexForGroup updateCache: function (groupKey, itemKey, itemIndex) { itemIndex = "" + itemIndex; this._itemToIndex[itemKey] = itemIndex; this._groupToItem[groupKey] = itemKey; }, deleteItem: function (itemKey) { if (!this._itemToIndex[itemKey]) { return; } var that = this; var keys = Object.keys(this._groupToItem); for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (that._groupToItem[key] === itemKey) { that.deleteGroup(key); break; } } }, deleteGroup: function (groupKey) { var itemKey = this._groupToItem[groupKey]; if (itemKey) { delete this._itemToIndex[itemKey]; } delete this._groupToItem[groupKey]; }, updateItemIndex: function (itemKey, itemIndex) { if (!this._itemToIndex[itemKey]) { return; } this._itemToIndex[itemKey] = "" + itemIndex; }, getIndexForGroup: function (groupIndex) { var groupKey = this._listView._groups.group(groupIndex).key; var itemKey = this._groupToItem[groupKey]; if (itemKey && this._itemToIndex[itemKey]) { return +this._itemToIndex[itemKey]; } else { return this._listView._groups.fromKey(groupKey).group.startIndex; } }, clear: function () { this._groupToItem = {}; this._itemToIndex = {}; } }); }), _UnsupportedGroupFocusCache: WinJS.Namespace._lazy(function () { return WinJS.Class.define(null, { updateCache: function (groupKey, itemKey, itemIndex) { }, deleteItem: function (itemKey) { }, deleteGroup: function (groupKey) { }, updateItemIndex: function (itemKey, itemIndex) { }, getIndexForGroup: function (groupIndex) { return 0; }, clear: function () { } }); }) }); })(); (function groupsContainerInit(global, WinJS, undefined) { "use strict"; var utilities = WinJS.Utilities, Promise = WinJS.Promise; WinJS.Namespace.define("WinJS.UI", { _GroupsContainerBase: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function () { }, { index: function (element) { var header = this.headerFrom(element); if (header) { for (var i = 0, len = this.groups.length; i < len; i++) { if (header === this.groups[i].header) { return i; } } } return WinJS.UI._INVALID_INDEX; }, headerFrom: function (element) { while (element && !utilities.hasClass(element, WinJS.UI._headerClass)) { element = element.parentNode; } return element; }, requestHeader: function GroupsContainerBase_requestHeader(index) { this._waitingHeaderRequests = this._waitingHeaderRequests || {}; if (!this._waitingHeaderRequests[index]) { this._waitingHeaderRequests[index] = []; } var that = this; return new Promise(function (complete, error) { var group = that.groups[index]; if (group && group.header) { complete(group.header); } else { that._waitingHeaderRequests[index].push(complete); } }); }, notify: function GroupsContainerBase_notify(index, header) { if (this._waitingHeaderRequests && this._waitingHeaderRequests[index]) { var requests = this._waitingHeaderRequests[index]; for (var i = 0, len = requests.length; i < len; i++) { requests[i](header); } this._waitingHeaderRequests[index] = []; } }, groupFromImpl: function GroupsContainerBase_groupFromImpl(fromGroup, toGroup, comp) { if (toGroup < fromGroup) { return null; } var center = fromGroup + Math.floor((toGroup - fromGroup) / 2), centerGroup = this.groups[center]; if (comp(centerGroup, center)) { return this.groupFromImpl(fromGroup, center - 1, comp); } else if (center < toGroup && !comp(this.groups[center + 1], center + 1)) { return this.groupFromImpl(center + 1, toGroup, comp); } else { return center; } }, groupFrom: function GroupsContainerBase_groupFrom(comp) { //#DBG _ASSERT(this.assertValid()); if (this.groups.length > 0) { var lastGroupIndex = this.groups.length - 1, lastGroup = this.groups[lastGroupIndex]; if (!comp(lastGroup, lastGroupIndex)) { return lastGroupIndex; } else { return this.groupFromImpl(0, this.groups.length - 1, comp); } } else { return null; } }, groupFromItem: function GroupsContainerBase_groupFromItem(itemIndex) { return this.groupFrom(function (group) { return itemIndex < group.startIndex; }); }, groupFromOffset: function GroupsContainerBase_groupFromOffset(offset) { //#DBG _ASSERT(this.assertValid()); return this.groupFrom(function (group, groupIndex) { //#DBG _ASSERT(group.offset !== undefined); return offset < group.offset; }); }, group: function GroupsContainerBase_getGroup(index) { return this.groups[index]; }, length: function GroupsContainerBase_length() { return this.groups.length; }, cleanUp: function GroupsContainerBase_cleanUp() { if (this.listBinding) { for (var i = 0, len = this.groups.length; i < len; i++) { var group = this.groups[i]; if (group.userData) { this.listBinding.releaseItem(group.userData); } } this.listBinding.release(); } }, _dispose: function GroupsContainerBase_dispose() { this.cleanUp(); }, /*#DBG assertValid: function () { if (WinJS.validation) { if (this.groups.length) { var prevIndex = this.groups[0].startIndex, prevKey = this.groups[0].key, keys = {}; //#DBG _ASSERT(prevIndex === 0); keys[prevKey] = true; for (var i = 1, len = this.groups.length; i < len; i++) { var group = this.groups[i]; //#DBG _ASSERT(group.startIndex > prevIndex); prevIndex = group.startIndex; //#DBG _ASSERT(!keys[group.key]); keys[group.key] = true; prevKey = group.key; } } } return true; }, #DBG*/ synchronizeGroups: function GroupsContainerBase_synchronizeGroups() { var that = this; this.pendingChanges = []; this.ignoreChanges = true; return this.groupDataSource.invalidateAll().then(function () { return Promise.join(that.pendingChanges); }).then(function () { if (that._listView._ifZombieDispose()) { return WinJS.Promise.cancel; } }).then( function () { that.ignoreChanges = false; }, function (error) { that.ignoreChanges = false; return WinJS.Promise.wrapError(error); } ); }, fromKey: function GroupsContainerBase_fromKey(key) { for (var i = 0, len = this.groups.length; i < len; i++) { var group = this.groups[i]; if (group.key === key) { return { group: group, index: i } } } return null; }, fromHandle: function GroupsContainerBase_fromHandle(handle) { for (var i = 0, len = this.groups.length; i < len; i++) { var group = this.groups[i]; if (group.handle === handle) { return { group: group, index: i } } } return null; } }); }), _UnvirtualizedGroupsContainer: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(WinJS.UI._GroupsContainerBase, function (listView, groupDataSource) { this._listView = listView; this.groupDataSource = groupDataSource; this.groups = []; this.pendingChanges = []; this.dirty = true; var that = this, notificationHandler = { beginNotifications: function GroupsContainer_beginNotifications() { that._listView._versionManager.beginNotifications(); }, endNotifications: function GroupsContainer_endNotifications() { //#DBG _ASSERT(that.assertValid()); that._listView._versionManager.endNotifications(); if (that._listView._ifZombieDispose()) { return; } if (!that.ignoreChanges && that._listView._groupsChanged) { that._listView._scheduleUpdate(); } }, indexChanged: function GroupsContainer_indexChanged(item, newIndex, oldIndex) { that._listView._versionManager.receivedNotification(); if (that._listView._ifZombieDispose()) { return; } this.scheduleUpdate(); }, itemAvailable: function GroupsContainer_itemAvailable(item, placeholder) { }, countChanged: function GroupsContainer_countChanged(newCount, oldCount) { that._listView._versionManager.receivedNotification(); that._listView._writeProfilerMark("groupCountChanged(" + newCount + "),info"); if (that._listView._ifZombieDispose()) { return; } this.scheduleUpdate(); }, changed: function GroupsContainer_changed(newItem, oldItem) { that._listView._versionManager.receivedNotification(); if (that._listView._ifZombieDispose()) { return; } //#DBG _ASSERT(newItem.key == oldItem.key); var groupEntry = that.fromKey(newItem.key); if (groupEntry) { that._listView._writeProfilerMark("groupChanged(" + groupEntry.index + "),info"); groupEntry.group.userData = newItem; groupEntry.group.startIndex = newItem.firstItemIndexHint; //#DBG _ASSERT(that.assertValid()); this.markToRemove(groupEntry.group); } this.scheduleUpdate(); }, removed: function GroupsContainer_removed(itemHandle, mirage) { that._listView._versionManager.receivedNotification(); that._listView._groupRemoved(itemHandle); if (that._listView._ifZombieDispose()) { return; } var groupEntry = that.fromHandle(itemHandle); if (groupEntry) { that._listView._writeProfilerMark("groupRemoved(" + groupEntry.index + "),info"); that.groups.splice(groupEntry.index, 1); var index = that.groups.indexOf(groupEntry.group, groupEntry.index); if (index > -1) { that.groups.splice(index, 1); } //#DBG _ASSERT(that.assertValid()); this.markToRemove(groupEntry.group); } this.scheduleUpdate(); }, inserted: function GroupsContainer_inserted(itemPromise, previousHandle, nextHandle) { that._listView._versionManager.receivedNotification(); if (that._listView._ifZombieDispose()) { return; } that._listView._writeProfilerMark("groupInserted,info"); var notificationHandler = this; itemPromise.retain().then(function (item) { //#DBG _ASSERT(!that.fromKey(item.key)) var index; if (!previousHandle && !nextHandle && !that.groups.length) { index = 0; } else { index = notificationHandler.findIndex(previousHandle, nextHandle); } if (index !== -1) { var newGroup = { key: item.key, startIndex: item.firstItemIndexHint, userData: item, handle: itemPromise.handle }; that.groups.splice(index, 0, newGroup); } notificationHandler.scheduleUpdate(); }); that.pendingChanges.push(itemPromise); }, moved: function GroupsContainer_moved(itemPromise, previousHandle, nextHandle) { that._listView._versionManager.receivedNotification(); if (that._listView._ifZombieDispose()) { return; } that._listView._writeProfilerMark("groupMoved,info"); var notificationHandler = this; itemPromise.then(function (item) { var newIndex = notificationHandler.findIndex(previousHandle, nextHandle), groupEntry = that.fromKey(item.key); if (groupEntry) { that.groups.splice(groupEntry.index, 1); if (newIndex !== -1) { if (groupEntry.index < newIndex) { newIndex--; } groupEntry.group.key = item.key; groupEntry.group.userData = item; groupEntry.group.startIndex = item.firstItemIndexHint; that.groups.splice(newIndex, 0, groupEntry.group); } } else if (newIndex !== -1) { var newGroup = { key: item.key, startIndex: item.firstItemIndexHint, userData: item, handle: itemPromise.handle }; that.groups.splice(newIndex, 0, newGroup); itemPromise.retain(); } //#DBG _ASSERT(that.assertValid()); notificationHandler.scheduleUpdate(); }); that.pendingChanges.push(itemPromise); }, reload: function GroupsContainer_reload() { that._listView._versionManager.receivedNotification(); if (that._listView._ifZombieDispose()) { return; } that._listView._processReload(); }, markToRemove: function GroupsContainer_markToRemove(group) { if (group.header) { var header = group.header; group.header = null; group.left = -1; group.width = -1; group.decorator = null; group.tabIndex = -1; header.tabIndex = -1; that._listView._groupsToRemove[header.uniqueID] = { group: group, header: header }; } }, scheduleUpdate: function GroupsContainer_scheduleUpdate() { that.dirty = true; if (!that.ignoreChanges) { that._listView._groupsChanged = true; } }, findIndex: function GroupsContainer_findIndex(previousHandle, nextHandle) { var index = -1, groupEntry; if (previousHandle) { groupEntry = that.fromHandle(previousHandle); if (groupEntry) { index = groupEntry.index + 1; } } if (index === -1 && nextHandle) { groupEntry = that.fromHandle(nextHandle); if (groupEntry) { index = groupEntry.index; } } return index; }, removeElements: function GroupsContainer_removeElements(group) { if (group.header) { var parentNode = group.header.parentNode; if (parentNode) { WinJS.Utilities.disposeSubTree(group.header); parentNode.removeChild(group.header); } group.header = null; group.left = -1; group.width = -1; } } }; this.listBinding = this.groupDataSource.createListBinding(notificationHandler); }, { initialize: function UnvirtualizedGroupsContainer_initialize() { if (this.initializePromise) { this.initializePromise.cancel(); } this._listView._writeProfilerMark("GroupsContainer_initialize,StartTM"); var that = this; this.initializePromise = this.groupDataSource.getCount().then(function (count) { var promises = []; for (var i = 0; i < count; i++) { promises.push(that.listBinding.fromIndex(i).retain()); } return Promise.join(promises); }).then( function (groups) { that.groups = []; for (var i = 0, len = groups.length; i < len; i++) { var group = groups[i]; that.groups.push({ key: group.key, startIndex: group.firstItemIndexHint, handle: group.handle, userData: group, }); } that._listView._writeProfilerMark("GroupsContainer_initialize groups(" + groups.length + "),info"); that._listView._writeProfilerMark("GroupsContainer_initialize,StopTM"); }, function (error) { that._listView._writeProfilerMark("GroupsContainer_initialize,StopTM"); return WinJS.Promise.wrapError(error); }); return this.initializePromise; }, renderGroup: function UnvirtualizedGroupsContainer_renderGroup(index) { if (this._listView.groupHeaderTemplate) { var group = this.groups[index]; return Promise.wrap(this._listView._groupHeaderRenderer(Promise.wrap(group.userData))).then(WinJS.UI._normalizeRendererReturn); } else { return Promise.wrap(null); } }, setDomElement: function UnvirtualizedGroupsContainer_setDomElement(index, headerElement) { this.groups[index].header = headerElement; this.notify(index, headerElement); }, removeElements: function UnvirtualizedGroupsContainer_removeElements() { var elements = this._listView._groupsToRemove || {}, keys = Object.keys(elements), focusedItemPurged = false; var focused = this._listView._selection._getFocused(); for (var i = 0, len = keys.length; i < len; i++) { var group = elements[keys[i]], header = group.header, groupData = group.group; if (!focusedItemPurged && focused.type === WinJS.UI.ObjectType.groupHeader && groupData.userData.index === focused.index) { this._listView._unsetFocusOnItem(); focusedItemPurged = true; } if (header) { var parentNode = header.parentNode; if (parentNode) { WinJS.Utilities._disposeElement(header); parentNode.removeChild(header); } } } if (focusedItemPurged) { this._listView._setFocusOnItem(focused); } this._listView._groupsToRemove = {}; }, resetGroups: function UnvirtualizedGroupsContainer_resetGroups() { var groups = this.groups.slice(0); for (var i = 0, len = groups.length; i < len; i++) { var group = groups[i]; if (this.listBinding && group.userData) { this.listBinding.releaseItem(group.userData); } } // Set the lengths to zero to clear the arrays, rather than setting = [], which re-instantiates this.groups.length = 0; this.dirty = true; } }); }), _NoGroups: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(WinJS.UI._GroupsContainerBase, function (listView) { this._listView = listView; this.groups = [{ startIndex: 0 }]; this.dirty = true; }, { synchronizeGroups: function () { return WinJS.Promise.wrap(); }, addItem: function (itemIndex, itemPromise) { return WinJS.Promise.wrap(this.groups[0]); }, resetGroups: function () { this.groups = [{ startIndex: 0 }]; delete this.pinnedItem; delete this.pinnedOffset; this.dirty = true; }, renderGroup: function () { return WinJS.Promise.wrap(null); }, ensureFirstGroup: function () { return WinJS.Promise.wrap(this.groups[0]); }, groupOf: function (item) { return WinJS.Promise.wrap(this.groups[0]); }, removeElements: function () { } }); }) }); })(this, WinJS); (function itemEventsHandlerInit(global, WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _ItemEventsHandler: WinJS.Namespace._lazy(function () { var utilities = WinJS.Utilities, Promise = WinJS.Promise, Animation = WinJS.UI.Animation; var PT_TOUCH = MSPointerEvent.MSPOINTER_TYPE_TOUCH || "touch"; function getElementWithClass(parent, className) { return parent.querySelector("." + className); } function createNodeWithClass(className, skipAriaHidden) { var element = document.createElement("div"); element.className = className; if (!skipAriaHidden) { element.setAttribute("aria-hidden", true); } return element; } return WinJS.Class.define(function ItemEventsHandler_ctor(site) { this._site = site; this._work = []; this._animations = {}; this._selectionHintTracker = {}; this._swipeClassTracker = {}; if (this._selectionAllowed()) { var that = this; setTimeout(function () { if (!that._gestureRecognizer && !site.isZombie()) { that._gestureRecognizer = that._createGestureRecognizer(); } }, 500); } }, { dispose: function () { if (this._disposed) { return; } this._disposed = true; this._gestureRecognizer = null; window.removeEventListener("pointerup", this._resetPointerDownStateBound); window.removeEventListener("pointercancel", this._resetPointerDownStateBound); }, onMSManipulationStateChanged: function ItemEventsHandler_onMSManipulationStateChanged(eventObject) { var state = eventObject.currentState; // We're not necessarily guaranteed to get onMSPointerDown before we get a selection event from cross slide, // so if we hit a select state with no pressed item box recorded, we need to set up the pressed info before // processing the selection. if (state === MSManipulationEvent.MS_MANIPULATION_STATE_PRESELECT && !this._site.pressedItemBox) { var currentPressedIndex = this._site.indexForItemElement(eventObject.srcElement); this._site.pressedEntity = { type: WinJS.UI.ObjectType.item, index: currentPressedIndex }; if (this._site.pressedEntity.index !== WinJS.UI._INVALID_INDEX) { this._site.pressedItemBox = this._site.itemBoxAtIndex(this._site.pressedEntity.index); this._site.pressedContainer = this._site.containerAtIndex(this._site.pressedEntity.index); this._site.pressedHeader = null; var allowed = this._site.verifySelectionAllowed(this._site.pressedEntity); this._canSelect = allowed.canSelect; this._canTapSelect = allowed.canTapSelect; this._swipeBehaviorSelectionChanged = false; this._selectionHint = null; if (this._canSelect) { this._addSelectionHint(); } } } if (this._canSelect && (state === MSManipulationEvent.MS_MANIPULATION_STATE_PRESELECT || state === MSManipulationEvent.MS_MANIPULATION_STATE_COMMITTED || state === MSManipulationEvent.MS_MANIPULATION_STATE_CANCELLED || state === MSManipulationEvent.MS_MANIPULATION_STATE_SELECTING || state === MSManipulationEvent.MS_MANIPULATION_STATE_DRAGGING)) { this._dispatchSwipeBehavior(state); } if (state === MSManipulationEvent.MS_MANIPULATION_STATE_COMMITTED || state === MSManipulationEvent.MS_MANIPULATION_STATE_CANCELLED || state === MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED) { this.resetPointerDownState(); } }, onPointerDown: function ItemEventsHandler_onPointerDown(eventObject) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:MSPointerDown,StartTM"); var site = this._site, touchInput = (eventObject.pointerType === PT_TOUCH), leftButton, rightButton; site.pressedElement = eventObject.target; if (utilities.hasWinRT) { // xButton is true when you've x-clicked with a mouse or pen. Otherwise it is false. var currentPoint = this._getCurrentPoint(eventObject); var pointProps = currentPoint.properties; if (!(touchInput || pointProps.isInverted || pointProps.isEraser || pointProps.isMiddleButtonPressed)) { rightButton = pointProps.isRightButtonPressed; leftButton = !rightButton && pointProps.isLeftButtonPressed; } else { leftButton = rightButton = false; } } else { // xButton is true when you've x-clicked with a mouse. Otherwise it is false. leftButton = (eventObject.button === WinJS.UI._LEFT_MSPOINTER_BUTTON); rightButton = (eventObject.button === WinJS.UI._RIGHT_MSPOINTER_BUTTON); } this._DragStartBound = this._DragStartBound || this.onDragStart.bind(this); this._PointerOverBound = this._PointerOverBound || this.onPointerOver.bind(this); this._PointerOutBound = this._PointerOutBound || this.onPointerOut.bind(this); this._swipeBehaviorState = MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED; var swipeEnabled = site.swipeBehavior === WinJS.UI.SwipeBehavior.select, swipeBehavior = touchInput && swipeEnabled, isInteractive = this._isInteractive(eventObject.srcElement), currentPressedIndex = site.indexForItemElement(eventObject.srcElement), currentPressedHeaderIndex = site.indexForHeaderElement(eventObject.srcElement), mustSetCapture = !isInteractive && currentPressedIndex !== WinJS.UI._INVALID_INDEX; if ((touchInput || leftButton || (this._selectionAllowed() && swipeEnabled && rightButton)) && this._site.pressedEntity.index === WinJS.UI._INVALID_INDEX && !isInteractive) { if (currentPressedHeaderIndex === WinJS.UI._INVALID_INDEX) { this._site.pressedEntity = { type: WinJS.UI.ObjectType.item, index: currentPressedIndex }; } else { this._site.pressedEntity = { type: WinJS.UI.ObjectType.groupHeader, index: currentPressedHeaderIndex }; } if (this._site.pressedEntity.index !== WinJS.UI._INVALID_INDEX) { this._site.pressedPosition = WinJS.UI._getCursorPos(eventObject); var allowed = site.verifySelectionAllowed(this._site.pressedEntity); this._canSelect = allowed.canSelect; this._canTapSelect = allowed.canTapSelect; this._swipeBehaviorSelectionChanged = false; this._selectionHint = null; if (this._site.pressedEntity.type !== WinJS.UI.ObjectType.groupHeader) { this._site.pressedItemBox = site.itemBoxAtIndex(this._site.pressedEntity.index); this._site.pressedContainer = site.containerAtIndex(this._site.pressedEntity.index); this._site.pressedHeader = null; this._togglePressed(true); this._site.pressedContainer.addEventListener('dragstart', this._DragStartBound); if (!touchInput) { // This only works for non touch input because on touch input we set capture which immediately fires the MSPointerOut. this._site.pressedContainer.addEventListener('pointerover', this._PointerOverBound); this._site.pressedContainer.addEventListener('pointerout', this._PointerOutBound); } } else { this._site.pressedHeader = eventObject.srcElement; this._site.pressedItemBox = null; this._site.pressedContainer = null; } if (!this._resetPointerDownStateBound) { this._resetPointerDownStateBound = this._resetPointerDownStateForPointerId.bind(this); } if (!touchInput) { window.addEventListener("pointerup", this._resetPointerDownStateBound); window.addEventListener("pointercancel", this._resetPointerDownStateBound); } if (this._canSelect) { if (!this._gestureRecognizer) { this._gestureRecognizer = this._createGestureRecognizer(); } this._addSelectionHint(); } this._pointerId = eventObject.pointerId; this._pointerRightButton = rightButton; this._pointerTriggeredSRG = false; if (this._gestureRecognizer && touchInput) { try { this._gestureRecognizer.addPointer(this._pointerId); } catch (e) { this._gestureRecognizer.stop(); } } } } if (mustSetCapture) { if (touchInput) { try { // Move pointer capture to avoid hover visual on second finger site.canvasProxy.setPointerCapture(eventObject.pointerId); } catch (e) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:MSPointerDown,StopTM"); return; } } } // Once the shift selection pivot is set, it remains the same until the user // performs a left- or right-click without holding the shift key down. if (this._site.pressedEntity.type !== WinJS.UI.ObjectType.groupHeader && this._selectionAllowed() && this._multiSelection() && // Multi selection enabled this._site.pressedEntity.index !== WinJS.UI._INVALID_INDEX && // A valid item was clicked site.selection._getFocused().index !== WinJS.UI._INVALID_INDEX && site.selection._pivot === WinJS.UI._INVALID_INDEX) { site.selection._pivot = site.selection._getFocused().index; } msWriteProfilerMark("WinJS.UI._ItemEventsHandler:MSPointerDown,StopTM"); }, onPointerOver: function ItemEventsHandler_onPointerOver(eventObject) { if (this._site.pressedContainer && this._pointerId === eventObject.pointerId) { this._togglePressed(true); } }, onPointerOut: function ItemEventsHandler_onPointerOut(eventObject) { if (this._site.pressedContainer && this._pointerId === eventObject.pointerId) { this._togglePressed(false, true /* synchronous */); } }, onDragStart: function ItemEventsHandler_onDragStart() { this._resetPressedContainer(); }, _resetPressedContainer: function ItemEventsHandler_resetPressedContainer() { if (this._site.pressedContainer) { this._togglePressed(false); this._site.pressedContainer.removeEventListener('dragstart', this._DragStartBound); this._site.pressedContainer.removeEventListener('pointerover', this._PointerOverBound); this._site.pressedContainer.removeEventListener('pointerout', this._PointerOutBound); } }, onClick: function ItemEventsHandler_onClick(eventObject) { if (!this._skipClick) { // Handle the UIA invoke action on an item. this._skipClick is false which tells us that we received a click // event without an associated MSPointerUp event. This means that the click event was triggered thru UIA // rather than thru the GUI. var entity = { type: WinJS.UI.ObjectType.item, index: this._site.indexForItemElement(eventObject.srcElement) }; if (entity.index === WinJS.UI._INVALID_INDEX) { entity.index = this._site.indexForHeaderElement(eventObject.srcElement); if (entity.index !== WinJS.UI._INVALID_INDEX) { entity.type = WinJS.UI.ObjectType.groupHeader; } } if (entity.index !== WinJS.UI._INVALID_INDEX && (utilities.hasClass(eventObject.srcElement, this._site.accessibleItemClass) || utilities.hasClass(eventObject.srcElement, WinJS.UI._headerClass))) { var allowed = this._site.verifySelectionAllowed(entity); if (allowed.canTapSelect) { this.handleTap(entity); } this._site.fireInvokeEvent(entity, eventObject.srcElement); } } }, onPointerUp: function ItemEventsHandler_onPointerUp(eventObject) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:MSPointerUp,StartTM"); var site = this._site; this._skipClick = true; var that = this; var swipeEnabled = this._site.swipeBehavior === WinJS.UI.SwipeBehavior.select; setImmediate(function () { that._skipClick = false; }); try { // Release the pointer capture to allow in air touch pointers to be reused for multiple interactions site.canvasProxy.releasePointerCapture(eventObject.pointerId); } catch (e) { // This can throw if SeZo had capture or if the pointer was not already captured } var touchInput = (eventObject.pointerType === PT_TOUCH), releasedElement = this._releasedElement(eventObject), releasedIndex = site.indexForItemElement(releasedElement), releasedHeaderIndex = site.indexForHeaderElement(releasedElement); if (this._pointerId === eventObject.pointerId) { var releasedEntity; if (releasedHeaderIndex === WinJS.UI._INVALID_INDEX) { releasedEntity = { type: WinJS.UI.ObjectType.item, index: releasedIndex }; } else { releasedEntity = { type: WinJS.UI.ObjectType.groupHeader, index: releasedHeaderIndex }; } this._resetPressedContainer(); if (this._site.pressedEntity.type !== WinJS.UI.ObjectType.groupHeader && releasedEntity.type !== WinJS.UI.ObjectType.groupHeader && this._site.pressedContainer && this._site.pressedEntity.index === releasedEntity.index) { if (!eventObject.shiftKey) { // Reset the shift selection pivot when the user clicks w/o pressing shift site.selection._pivot = WinJS.UI._INVALID_INDEX; } if (eventObject.shiftKey) { // Shift selection should work when shift or shift+ctrl are depressed for both left- and right-click if (this._selectionAllowed() && this._multiSelection() && site.selection._pivot !== WinJS.UI._INVALID_INDEX) { var firstIndex = Math.min(this._site.pressedEntity.index, site.selection._pivot), lastIndex = Math.max(this._site.pressedEntity.index, site.selection._pivot), additive = (this._pointerRightButton || eventObject.ctrlKey || site.tapBehavior === WinJS.UI.TapBehavior.toggleSelect); site.selectRange(firstIndex, lastIndex, additive); } } else if (eventObject.ctrlKey || (this._selectionAllowed() && swipeEnabled && this._pointerRightButton)) { // Swipe emulation this.handleSwipeBehavior(this._site.pressedEntity.index); } } if ((this._site.pressedHeader || this._site.pressedContainer) && this._swipeBehaviorState !== MSManipulationEvent.MS_MANIPULATION_STATE_COMMITTED) { var upPosition = WinJS.UI._getCursorPos(eventObject); var isTap = Math.abs(upPosition.left - this._site.pressedPosition.left) <= WinJS.UI._TAP_END_THRESHOLD && Math.abs(upPosition.top - this._site.pressedPosition.top) <= WinJS.UI._TAP_END_THRESHOLD; this._endSelfRevealGesture(); this._clearItem(this._site.pressedEntity, this._isSelected(this._site.pressedEntity.index)); // We do not care whether or not the pressed and released indices are equivalent when the user is using touch. The only time they won't be is if the user // tapped the edge of an item and the pressed animation shrank the item such that the user's finger was no longer over it. In this case, the item should // be considered tapped. // However, if the user is using touch then we must perform an extra check. Sometimes we receive MSPointerUp events when the user intended to pan or swipe. // This extra check ensures that these intended pans/swipes aren't treated as taps. if (!this._pointerRightButton && !this._pointerTriggeredSRG && !eventObject.ctrlKey && !eventObject.shiftKey && ((touchInput && isTap) || (!touchInput && this._site.pressedEntity.index === releasedEntity.index && this._site.pressedEntity.type === releasedEntity.type))) { if (releasedEntity.type === WinJS.UI.ObjectType.groupHeader) { this._site.pressedHeader = site.headerAtIndex(releasedEntity.index); this._site.pressedItemBox = null; this._site.pressedContainer = null; } else { this._site.pressedItemBox = site.itemBoxAtIndex(releasedEntity.index); this._site.pressedContainer = site.containerAtIndex(releasedEntity.index); this._site.pressedHeader = null; } if (this._canTapSelect) { this.handleTap(this._site.pressedEntity); } this._site.fireInvokeEvent(this._site.pressedEntity, this._site.pressedItemBox || this._site.pressedHeader); } } if (this._site.pressedEntity.index !== WinJS.UI._INVALID_INDEX) { site.changeFocus(this._site.pressedEntity, true, false, true); } this.resetPointerDownState(); } msWriteProfilerMark("WinJS.UI._ItemEventsHandler:MSPointerUp,StopTM"); }, onPointerCancel: function ItemEventsHandler_onPointerCancel(eventObject) { if (this._pointerId === eventObject.pointerId && this._swipeBehaviorState !== MSManipulationEvent.MS_MANIPULATION_STATE_PRESELECT) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:MSPointerCancel,info"); this.resetPointerDownState(); } }, onLostPointerCapture: function ItemEventsHandler_onLostPointerCapture(eventObject) { if (this._pointerId === eventObject.pointerId && this._swipeBehaviorState !== MSManipulationEvent.MS_MANIPULATION_STATE_PRESELECT) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:MSLostPointerCapture,info"); this.resetPointerDownState(); } }, // In order for the control to play nicely with other UI controls such as the app bar, it calls preventDefault on // contextmenu events. It does this only when selection is enabled, the event occurred on or within an item, and // the event did not occur on an interactive element. onContextMenu: function ItemEventsHandler_onContextMenu(eventObject) { var containerElement = this._site.containerFromElement(eventObject.srcElement); if (this._selectionAllowed() && containerElement && !this._isInteractive(eventObject.srcElement)) { eventObject.preventDefault(); } }, onMSHoldVisual: function ItemEventsHandler_onMSHoldVisual(eventObject) { if (!this._isInteractive(eventObject.srcElement)) { eventObject.preventDefault(); } }, onDataChanged: function ItemEventsHandler_onDataChanged() { this.resetPointerDownState(); }, handleSwipeBehavior: function ItemEventsHandler_handleSwipeBehavior(itemIndex) { if (this._selectionAllowed(itemIndex)) { this._toggleItemSelection(itemIndex); } }, handleTap: function ItemEventsHandler_handleTap(entity) { if (entity.type === WinJS.UI.ObjectType.groupHeader) { return; } var site = this._site, selection = site.selection; if (this._selectionAllowed(entity.index) && this._selectOnTap()) { if (site.tapBehavior === WinJS.UI.TapBehavior.toggleSelect) { this._toggleItemSelection(entity.index); } else { // site.tapBehavior === WinJS.UI.TapBehavior.directSelect so ensure only itemIndex is selected if (site.selectionMode === WinJS.UI.SelectionMode.multi || !selection._isIncluded(entity.index)) { selection.set(entity.index); } } } }, // In single selection mode, in addition to itemIndex's selection state being toggled, // all other items will become deselected _toggleItemSelection: function ItemEventsHandler_toggleItemSelection(itemIndex) { var site = this._site, selection = site.selection, selected = selection._isIncluded(itemIndex); if (site.selectionMode === WinJS.UI.SelectionMode.single) { if (!selected) { selection.set(itemIndex); } else { selection.clear(); } } else { if (!selected) { selection.add(itemIndex); } else { selection.remove(itemIndex); } } }, _getCurrentPoint: function ItemEventsHandler_getCurrentPoint(eventObject) { return Windows.UI.Input.PointerPoint.getCurrentPoint(eventObject.pointerId); }, _containedInElementWithClass: function ItemEventsHandler_containedInElementWithClass(element, className) { if (element.parentNode) { var matches = element.parentNode.querySelectorAll("." + className + ", ." + className + " *"); for (var i = 0, len = matches.length; i < len; i++) { if (matches[i] === element) { return true; } } } return false; }, _isSelected: function ItemEventsHandler_isSelected(index) { return (!this._swipeBehaviorSelectionChanged && this._site.selection._isIncluded(index)) || (this._swipeBehaviorSelectionChanged && this.swipeBehaviorSelected); }, _isInteractive: function ItemEventsHandler_isInteractive(element) { return this._containedInElementWithClass(element, "win-interactive"); }, _togglePressed: function ItemEventsHandler_togglePressed(add, synchronous) { var that = this; if (!this._staticMode()) { if (add) { if (!utilities.hasClass(this._site.pressedContainer, WinJS.UI._pressedClass)) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:applyPressedUI,info"); utilities.addClass(this._site.pressedContainer, WinJS.UI._pressedClass); // Shrink by 97.5% unless that is larger than 7px in either direction. In that case we cap the // scale so that it is no larger than 7px in either direction. We keep the scale uniform in both x // and y directions. Note that this scale cap only works if getItemPosition returns synchronously // which it does for the built in layouts. var scale = 0.975; var maxPixelsToShrink = 7; this._site.getItemPosition(this._site.pressedEntity).then(function (pos) { if (pos.contentWidth > 0) { scale = Math.max(scale, (1 - (maxPixelsToShrink / pos.contentWidth))); } if (pos.contentHeight > 0) { scale = Math.max(scale, (1 - (maxPixelsToShrink / pos.contentHeight))); } }, function () { // Swallow errors in case data source changes }); if (this._site.pressedContainer.style.transform === "") { this._site.pressedContainer.style.transform = "scale(" + scale + "," + scale + ")"; this._site.pressedContainerScaleTransform = this._site.pressedContainer.style.transform; } else { this._site.pressedContainerScaleTransform = ""; } } } else { if (utilities.hasClass(this._site.pressedContainer, WinJS.UI._pressedClass)) { var element = this._site.pressedContainer; var expectingStyle = this._site.pressedContainerScaleTransform; if (synchronous) { togglePressedImpl(element, expectingStyle); } else { // Force removal of the _pressedClass to be asynchronous so that users will see at // least one frame of the shrunken item when doing a quick tap. // // setImmediate is used rather than requestAnimationFrame to ensure that the item // doesn't get stuck down for too long -- apps are told to put long running invoke // code behind a setImmediate and togglePressed's async code needs to run first. setImmediate(function () { if (utilities.hasClass(element, WinJS.UI._pressedClass)) { togglePressedImpl(element, expectingStyle); } }); } } } } function togglePressedImpl(element, expectingStyle) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:removePressedUI,info"); utilities.removeClass(element, WinJS.UI._pressedClass); that._removeTransform(element, expectingStyle); } }, _removeTransform: function ItemEventsHandler_removeTransform(element, transform) { if (transform && element.style.transform.indexOf(transform) !== -1) { element.style.transform = element.style.transform.replace(transform, ""); } }, _endSwipeBehavior: function ItemEventsHandler_endSwipeBehavior() { if (!(this._swipeBehaviorState === MSManipulationEvent.MS_MANIPULATION_STATE_PRESELECT || this._swipeBehaviorState === MSManipulationEvent.MS_MANIPULATION_STATE_SELECTING || this._swipeBehaviorState === MSManipulationEvent.MS_MANIPULATION_STATE_DRAGGING || this._swipeBehaviorState === MSManipulationEvent.MS_MANIPULATION_STATE_COMMITTED || this._swipeBehaviorState === MSManipulationEvent.MS_MANIPULATION_STATE_CANCELLED)) { return; } if (this._site.pressedEntity.type === WinJS.UI.ObjectType.groupHeader) { return; } this._flushUIBatches(); var selectionHint = this._selectionHint; this._selectionHint = null; if (this._site.pressedItemBox) { var pressedIndex = this._site.pressedEntity.index, selected = this._site.selection._isIncluded(pressedIndex); if (selected) { var elementsToShowHide = WinJS.UI._getElementsByClasses(this._site.pressedItemBox, [WinJS.UI._selectionCheckmarkClass, WinJS.UI._selectionCheckmarkBackgroundClass]); for (var i = 0; i < elementsToShowHide.length; i++) { elementsToShowHide[i].style.opacity = 1; } } this._clearItem(this._site.pressedEntity, selected); if (selectionHint) { this._removeSelectionHint(selectionHint); } delete this._animations[pressedIndex]; } }, _createGestureRecognizer: function ItemEventsHandler_createGestureRecognizer() { var rootElement = this._site.eventHandlerRoot; var recognizer = new MSGesture(); recognizer.target = rootElement; var that = this; rootElement.addEventListener("MSGestureHold", function (eventObject) { if (that._site.pressedEntity.index !== -1 && eventObject.detail === MSGestureEvent.MSGESTURE_FLAG_BEGIN) { that._startSelfRevealGesture(); } }); return recognizer; }, _dispatchSwipeBehavior: function ItemEventsHandler_dispatchSwipeBehavior(manipulationState) { if (this._site.pressedEntity.type === WinJS.UI.ObjectType.groupHeader) { return; } this._site.selection._pivot = WinJS.UI._INVALID_INDEX; if (this._site.pressedItemBox) { var pressedIndex = this._site.pressedEntity.index; if (this._swipeBehaviorState !== manipulationState) { if (manipulationState === MSManipulationEvent.MS_MANIPULATION_STATE_DRAGGING && this._canSelect) { this._animateSelectionChange(this._site.selection._isIncluded(pressedIndex)); this._removeSelectionHint(this._selectionHint); } else if (manipulationState === MSManipulationEvent.MS_MANIPULATION_STATE_PRESELECT) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:crossSlidingStarted,info"); var site = this._site, pressedElement = site.itemAtIndex(pressedIndex), selected = site.selection._isIncluded(pressedIndex); if (this._selfRevealGesture) { this._selfRevealGesture.finishAnimation(); this._selfRevealGesture = null; } else if (this._canSelect) { this._prepareItem(this._site.pressedEntity, pressedElement, selected); } if (this._swipeBehaviorState !== MSManipulationEvent.MS_MANIPULATION_STATE_SELECTING) { if (this._site.pressedContainer && utilities.hasClass(this._site.pressedContainer, WinJS.UI._pressedClass)) { utilities.removeClass(this._site.pressedContainer, WinJS.UI._pressedClass); this._removeTransform(this._site.pressedContainer, this._site.pressedContainerScaleTransform); } this._showSelectionHintCheckmark(); } else { this._animateSelectionChange(this._site.selection._isIncluded(pressedIndex)); } } else if (manipulationState === MSManipulationEvent.MS_MANIPULATION_STATE_COMMITTED) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:crossSlidingCompleted,info"); var that = this, site = this._site, selection = site.selection, swipeBehaviorSelectionChanged = this._swipeBehaviorSelectionChanged, swipeBehaviorSelected = this.swipeBehaviorSelected; if (this._swipeBehaviorState === MSManipulationEvent.MS_MANIPULATION_STATE_SELECTING && swipeBehaviorSelectionChanged) { if (this._selectionAllowed() && site.swipeBehavior === WinJS.UI.SwipeBehavior.select) { if (site.selectionMode === WinJS.UI.SelectionMode.single) { if (swipeBehaviorSelected) { selection.set(pressedIndex); } else if (selection._isIncluded(pressedIndex)) { selection.remove(pressedIndex); } } else { if (swipeBehaviorSelected) { selection.add(pressedIndex); } else if (selection._isIncluded(pressedIndex)) { selection.remove(pressedIndex); } } } } // snap back and remove addional elements this._endSwipeBehavior(); } else if (manipulationState === MSManipulationEvent.MS_MANIPULATION_STATE_SELECTING && this._canSelect) { this._animateSelectionChange(!this._site.selection._isIncluded(pressedIndex)); } else if (this._swipeBehaviorState === MSManipulationEvent.MS_MANIPULATION_STATE_SELECTING && this._canSelect) { this._animateSelectionChange(this._site.selection._isIncluded(pressedIndex), (manipulationState === MSManipulationEvent.MS_MANIPULATION_STATE_CANCELLED)); } } } this._swipeBehaviorState = manipulationState; }, _resetPointerDownStateForPointerId: function ItemEventsHandler_resetPointerDownState(eventObject) { if (this._pointerId === eventObject.pointerId) { this.resetPointerDownState(); } }, resetPointerDownState: function ItemEventsHandler_resetPointerDownState() { if (this._gestureRecognizer) { this._endSelfRevealGesture(); this._endSwipeBehavior(); } this._site.pressedElement = null; window.removeEventListener("pointerup", this._resetPointerDownStateBound); window.removeEventListener("pointercancel", this._resetPointerDownStateBound); this._resetPressedContainer(); this._site.pressedContainer = null; this._site.pressedHeader = null; this._site.pressedItemBox = null; this._removeSelectionHint(this._selectionHint); this._selectionHint = null; this._site.pressedEntity = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }; this._pointerId = null; }, // Play the self-reveal gesture (SRG) animation which jiggles the item to reveal the selection hint behind it. // This function is overridden by internal teams to add a tooltip on SRG start - treat this function as a public API for the sake of function name/parameter changes. _startSelfRevealGesture: function ItemEventsHandler_startSelfRevealGesture() { if (this._canSelect && this._site.swipeBehavior === WinJS.UI.SwipeBehavior.select) { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:playSelfRevealGesture,info"); var that = this; var site = this._site, Animation = WinJS.UI.Animation, index = this._site.pressedEntity.index, itemBox = site.itemBoxAtIndex(index), selected = site.selection._isIncluded(index), finished = false; var swipeReveal = function () { var top, left; if (site.horizontal) { top = WinJS.UI._VERTICAL_SWIPE_SELF_REVEAL_GESTURE + "px"; left = "0px"; } else { top = "0px"; left = (site.rtl() ? "" : "-") + WinJS.UI._HORIZONTAL_SWIPE_SELF_REVEAL_GESTURE + "px"; } return Animation.swipeReveal(itemBox, { top: top, left: left }); } var swipeHide = function () { return finished ? WinJS.Promise.wrap() : Animation.swipeReveal(itemBox, { top: "0px", left: "0px" }); } var cleanUp = function (selectionHint) { if (!site.isZombie()) { if (selectionHint) { that._removeSelectionHint(selectionHint); } that._clearItem(site.pressedEntity, site.selection._isIncluded(index)); } } // Immediately begins the last phase of the SRG animation which animates the item back to its original location var finishAnimation = function () { that._selfRevealGesture._promise.cancel(); finished = true; var selectionHint = that._selectionHint; that._selectionHint = null; return swipeHide().then(function () { itemBox.style.transform = ""; cleanUp(selectionHint); }); } this._prepareItem(this._site.pressedEntity, itemBox, selected); this._showSelectionHintCheckmark(); this._pointerTriggeredSRG = true; this._selfRevealGesture = { finishAnimation: finishAnimation, _promise: swipeReveal(). then(swipeHide). then(function () { if (!finished) { that._hideSelectionHintCheckmark(); cleanUp(); that._selfRevealGesture = null; } }) }; } }, // This function is overridden by internal teams to remove a tooltip on SRG completion - treat this function as a public API for the sake of function name/parameter changes _endSelfRevealGesture: function ItemEventsHandler_endSelfRevealGesture() { if (this._selfRevealGesture) { this._selfRevealGesture.finishAnimation(); this._selfRevealGesture = null; } }, _prepareItem: function ItemEventsHandler_prepareItem(pressedEntity, pressedElement, selected) { if (pressedEntity.type === WinJS.UI.ObjectType.groupHeader) { return; } var that = this, site = this._site, pressedIndex = pressedEntity.index; function addSwipeClass(container) { if (!that._swipeClassTracker[container.uniqueID]) { utilities.addClass(container, WinJS.UI._swipeClass); that._swipeClassTracker[container.uniqueID] = 1; } else { that._swipeClassTracker[container.uniqueID]++; } } if (!selected) { (this._animations[pressedIndex] || Promise.wrap()).then(function () { if (!site.isZombie() && pressedEntity.type !== WinJS.UI.ObjectType.groupHeader && site.pressedEntity.index !== -1) { pressedIndex = site.pressedEntity.index; var pressedElement = site.itemAtIndex(pressedIndex), itemBox = site.itemBoxAtIndex(pressedIndex), container = site.containerAtIndex(pressedIndex); addSwipeClass(container); if (!WinJS.UI._isSelectionRendered(itemBox)) { WinJS.UI._ItemEventsHandler.renderSelection(itemBox, pressedElement, true, container); utilities.removeClass(itemBox, WinJS.UI._selectedClass); utilities.removeClass(container, WinJS.UI._selectedClass); var nodes = itemBox.querySelectorAll(WinJS.UI._selectionPartsSelector); for (var i = 0, len = nodes.length; i < len; i++) { nodes[i].style.opacity = 0; } } } }); } else { var container = site.containerAtIndex(pressedIndex); addSwipeClass(container); } }, _clearItem: function ItemEventsHandler_clearItem(pressedEntity, selected) { if (pressedEntity.type !== WinJS.UI.ObjectType.item) { return; } var that = this, site = this._site, container = site.containerAtIndex(pressedEntity.index), itemBox = site.itemBoxAtIndex(pressedEntity.index), element = site.itemAtIndex(pressedEntity.index); function removeSwipeClass(container) { var refCount = --that._swipeClassTracker[container.uniqueID]; if (!refCount) { delete that._swipeClassTracker[container.uniqueID]; utilities.removeClass(container, WinJS.UI._swipeClass); return true; } return false; } function removeSwipeFromItemsBlock(container) { var itemsBlock = container.parentNode; if (itemsBlock && WinJS.Utilities.hasClass(itemsBlock, WinJS.UI._itemsBlockClass)) { removeSwipeClass(itemsBlock); } } if (container && itemBox && element) { var doneSwiping = removeSwipeClass(container); removeSwipeFromItemsBlock(container); if (doneSwiping) { WinJS.UI._ItemEventsHandler.renderSelection(itemBox, element, selected, true, container); } } }, _animateSelectionChange: function ItemEventsHandler_animateSelectionChange(select, includeCheckmark) { var that = this, pressedContainer = this._site.pressedContainer, pressedItemBox = this._site.pressedItemBox; function toggleClasses() { var classOperation = select ? "addClass" : "removeClass"; utilities[classOperation](pressedItemBox, WinJS.UI._selectedClass); utilities[classOperation](pressedContainer, WinJS.UI._selectedClass); if (that._selectionHint) { var hintCheckMark = getElementWithClass(that._selectionHint, WinJS.UI._selectionHintClass); if (hintCheckMark) { utilities[classOperation](hintCheckMark, WinJS.UI._revealedClass); } } } this._swipeBehaviorSelectionChanged = true; this.swipeBehaviorSelected = select; var elementsToShowHide = WinJS.UI._getElementsByClasses(this._site.pressedItemBox, [WinJS.UI._selectionBorderClass, WinJS.UI._selectionBackgroundClass]); if (!select || includeCheckmark) { elementsToShowHide = elementsToShowHide.concat(WinJS.UI._getElementsByClasses(this._site.pressedItemBox, [WinJS.UI._selectionCheckmarkBackgroundClass, WinJS.UI._selectionCheckmarkClass])); } msWriteProfilerMark("WinJS.UI._ItemEventsHandler:" + (select ? "hitSelectThreshold" : "hitUnselectThreshold") + ",info"); this._applyUIInBatches(function () { msWriteProfilerMark("WinJS.UI._ItemEventsHandler:" + (select ? "apply" : "remove") + "SelectionVisual,info"); var opacity = (select ? 1 : 0); for (var i = 0; i < elementsToShowHide.length; i++) { elementsToShowHide[i].style.opacity = opacity; } toggleClasses(); }); }, _showSelectionHintCheckmark: function ItemEventsHandler_showSelectionHintCheckmark() { if (this._selectionHint) { var hintCheckMark = getElementWithClass(this._selectionHint, WinJS.UI._selectionHintClass); if (hintCheckMark) { hintCheckMark.style.display = 'block'; } } }, _hideSelectionHintCheckmark: function ItemEventsHandler_hideSelectionHintCheckmark() { if (this._selectionHint) { var hintCheckMark = getElementWithClass(this._selectionHint, WinJS.UI._selectionHintClass); if (hintCheckMark) { hintCheckMark.style.display = 'none'; } } }, _addSelectionHint: function ItemEventsHandler_addSelectionHint() { if (this._site.pressedEntity.type === WinJS.UI.ObjectType.groupHeader) { return; } var selectionHint, site = this._site; if (site.customFootprintParent) { selectionHint = this._selectionHint = document.createElement("div"); selectionHint.className = WinJS.UI._containerClass; var that = this; site.getItemPosition(this._site.pressedEntity).then(function (pos) { if (!site.isZombie() && that._selectionHint && that._selectionHint === selectionHint) { var style = selectionHint.style; var cssText = ";position:absolute;" + (site.rtl() ? "right:" : "left:") + pos.left + "px;top:" + pos.top + "px;width:" + pos.contentWidth + "px;height:" + pos.contentHeight + "px"; style.cssText += cssText; site.customFootprintParent.insertBefore(that._selectionHint, that._site.pressedItemBox); } }, function () { // Swallow errors in case data source changes }); } else { selectionHint = this._selectionHint = this._site.pressedContainer; } if (!this._selectionHintTracker[selectionHint.uniqueID]) { utilities.addClass(selectionHint, WinJS.UI._footprintClass); if (!site.selection._isIncluded(this._site.pressedEntity.index)) { var element = document.createElement("div"); element.className = WinJS.UI._selectionHintClass; element.innerText = WinJS.UI._SELECTION_CHECKMARK; element.style.display = 'none'; this._selectionHint.insertBefore(element, this._selectionHint.firstElementChild); } this._selectionHintTracker[selectionHint.uniqueID] = 1; } else { this._selectionHintTracker[selectionHint.uniqueID]++; } }, _removeSelectionHint: function ItemEventsHandler_removeSelectionHint(selectionHint) { if (selectionHint) { var refCount = --this._selectionHintTracker[selectionHint.uniqueID]; if (!refCount) { delete this._selectionHintTracker[selectionHint.uniqueID]; if (!this._site.customFootprintParent) { utilities.removeClass(selectionHint, WinJS.UI._footprintClass); var hintCheckMark = getElementWithClass(selectionHint, WinJS.UI._selectionHintClass); if (hintCheckMark) { hintCheckMark.parentNode.removeChild(hintCheckMark); } } else if (selectionHint.parentNode) { selectionHint.parentNode.removeChild(selectionHint); } } } }, _releasedElement: function ItemEventsHandler_releasedElement(eventObject) { return document.elementFromPoint(eventObject.clientX, eventObject.clientY); }, _applyUIInBatches: function ItemEventsHandler_applyUIInBatches(work) { var that = this; this._work.push(work); if (!this._paintedThisFrame) { applyUI(); } function applyUI() { if (that._work.length > 0) { that._flushUIBatches(); that._paintedThisFrame = requestAnimationFrame(applyUI.bind(that)); } else { that._paintedThisFrame = null; } } }, _flushUIBatches: function ItemEventsHandler_flushUIBatches() { if (this._work.length > 0) { var workItems = this._work; this._work = []; for (var i = 0; i < workItems.length; i++) { workItems[i](); } } }, _selectionAllowed: function ItemEventsHandler_selectionAllowed(itemIndex) { var item = (itemIndex !== undefined ? this._site.itemAtIndex(itemIndex) : null), itemSelectable = !(item && utilities.hasClass(item, WinJS.UI._nonSelectableClass)); return itemSelectable && this._site.selectionMode !== WinJS.UI.SelectionMode.none; }, _multiSelection: function ItemEventsHandler_multiSelection() { return this._site.selectionMode === WinJS.UI.SelectionMode.multi; }, _selectOnTap: function ItemEventsHandler_selectOnTap() { return this._site.tapBehavior === WinJS.UI.TapBehavior.toggleSelect || this._site.tapBehavior === WinJS.UI.TapBehavior.directSelect; }, _staticMode: function ItemEventsHandler_staticMode() { return this._site.tapBehavior === WinJS.UI.TapBehavior.none && this._site.selectionMode === WinJS.UI.SelectionMode.none; }, }, { // Avoids unnecessary UIA selection events by only updating aria-selected if it has changed setAriaSelected: function ItemEventsHandler_setAriaSelected(itemElement, isSelected) { var ariaSelected = (itemElement.getAttribute("aria-selected") === "true"); if (isSelected !== ariaSelected) { itemElement.setAttribute("aria-selected", isSelected); } }, renderSelection: function ItemEventsHandler_renderSelection(itemBox, element, selected, aria, container) { if (!WinJS.UI._ItemEventsHandler._selectionTemplate) { WinJS.UI._ItemEventsHandler._selectionTemplate = []; WinJS.UI._ItemEventsHandler._selectionTemplate.push(createNodeWithClass(WinJS.UI._selectionBackgroundClass)); WinJS.UI._ItemEventsHandler._selectionTemplate.push(createNodeWithClass(WinJS.UI._selectionBorderClass)); WinJS.UI._ItemEventsHandler._selectionTemplate.push(createNodeWithClass(WinJS.UI._selectionCheckmarkBackgroundClass)); var checkmark = createNodeWithClass(WinJS.UI._selectionCheckmarkClass); checkmark.innerText = WinJS.UI._SELECTION_CHECKMARK; WinJS.UI._ItemEventsHandler._selectionTemplate.push(checkmark); } // Update the selection rendering if necessary if (selected !== WinJS.UI._isSelectionRendered(itemBox)) { if (selected) { itemBox.insertBefore(WinJS.UI._ItemEventsHandler._selectionTemplate[0].cloneNode(true), itemBox.firstElementChild); for (var i = 1, len = WinJS.UI._ItemEventsHandler._selectionTemplate.length; i < len; i++) { itemBox.appendChild(WinJS.UI._ItemEventsHandler._selectionTemplate[i].cloneNode(true)); } } else { var nodes = itemBox.querySelectorAll(WinJS.UI._selectionPartsSelector); for (var i = 0, len = nodes.length; i < len; i++) { itemBox.removeChild(nodes[i]); } } utilities[selected ? "addClass" : "removeClass"](itemBox, WinJS.UI._selectedClass); if (container) { utilities[selected ? "addClass" : "removeClass"](container, WinJS.UI._selectedClass); } } // To allow itemPropertyChange to work properly, aria needs to be updated after the selection visuals are added to the itemBox if (aria) { WinJS.UI._ItemEventsHandler.setAriaSelected(element, selected); } }, }); }) }); })(this, WinJS); (function itemsContainerInit(global, WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _ItemsContainer: WinJS.Namespace._lazy(function () { var utilities = WinJS.Utilities, Promise = WinJS.Promise; var _ItemsContainer = function (site) { this.site = site; this._itemData = {}; this.waitingItemRequests = {}; }; _ItemsContainer.prototype = { requestItem: function ItemsContainer_requestItem(itemIndex) { if (!this.waitingItemRequests[itemIndex]) { this.waitingItemRequests[itemIndex] = []; } var that = this; var promise = new Promise(function (complete, error) { var itemData = that._itemData[itemIndex]; if (itemData && !itemData.detached && itemData.element) { complete(itemData.element); } else { that.waitingItemRequests[itemIndex].push(complete); } }); return promise; }, removeItem: function (index) { /*#DBG delete WinJS.Utilities.data(this._itemData[index].element).itemData; delete WinJS.Utilities.data(this._itemData[index].element).itemsContainer; #DBG*/ delete this._itemData[index]; }, removeItems: function ItemsContainer_removeItems() { /*#DBG var that = this; Object.keys(this._itemData).forEach(function (k) { delete WinJS.Utilities.data(that._itemData[k].element).itemData; delete WinJS.Utilities.data(that._itemData[k].element).itemsContainer; }); #DBG*/ this._itemData = {}; this.waitingItemRequests = {}; }, setItemAt: function ItemsContainer_setItemAt(itemIndex, itemData) { /*#DBG if (itemData.itemsManagerRecord.released) { throw "ACK! Attempt to use a released itemsManagerRecord"; } var oldItemData = WinJS.Utilities.data(itemData.element).itemData; if (oldItemData || WinJS.Utilities.data(itemData.element).itemsContainer) { if (oldItemData.itemsManagerRecord.item.index !== itemIndex) { throw "ACK! Attempted use of already in-use element"; } } WinJS.Utilities.data(itemData.element).itemData = itemData; WinJS.Utilities.data(itemData.element).itemsContainer = this; #DBG*/ //#DBG _ASSERT(itemData.element && (itemData.element instanceof HTMLElement)); //#DBG _ASSERT(!this._itemData[itemIndex]); this._itemData[itemIndex] = itemData; if (!itemData.detached) { this.notify(itemIndex, itemData); } }, notify: function ItemsContainer_notify(itemIndex, itemData) { if (this.waitingItemRequests[itemIndex]) { var requests = this.waitingItemRequests[itemIndex]; for (var i = 0; i < requests.length; i++) { requests[i](itemData.element); } this.waitingItemRequests[itemIndex] = []; } }, elementAvailable: function ItemsContainer_elementAvailable(itemIndex) { var itemData = this._itemData[itemIndex]; itemData.detached = false; this.notify(itemIndex, itemData); }, itemAt: function ItemsContainer_itemAt(itemIndex) { var itemData = this._itemData[itemIndex]; return itemData ? itemData.element : null; }, itemDataAt: function ItemsContainer_itemDataAt(itemIndex) { return this._itemData[itemIndex]; }, containerAt: function ItemsContainer_containerAt(itemIndex) { var itemData = this._itemData[itemIndex]; return itemData ? itemData.container : null; }, itemBoxAt: function ItemsContainer_itemBoxAt(itemIndex) { var itemData = this._itemData[itemIndex]; return itemData ? itemData.itemBox : null; }, itemBoxFrom: function ItemsContainer_containerFrom(element) { while (element && !utilities.hasClass(element, WinJS.UI._itemBoxClass)) { element = element.parentNode; } return element; }, containerFrom: function ItemsContainer_containerFrom(element) { while (element && !utilities.hasClass(element, WinJS.UI._containerClass)) { element = element.parentNode; } return element; }, index: function ItemsContainer_index(element) { var item = this.containerFrom(element); if (item) { for (var index in this._itemData) { if (this._itemData[index].container === item) { return parseInt(index, 10); } } } return WinJS.UI._INVALID_INDEX; }, each: function ItemsContainer_each(callback) { for (var index in this._itemData) { if (this._itemData.hasOwnProperty(index)) { var itemData = this._itemData[index]; //#DBG _ASSERT(itemData); callback(parseInt(index, 10), itemData.element, itemData); } } }, eachIndex: function ItemsContainer_each(callback) { for (var index in this._itemData) { if (callback(parseInt(index, 10))) { break; } } }, count: function ItemsContainer_count() { return Object.keys(this._itemData).length; } }; return _ItemsContainer; }) }); })(this, WinJS); (function layouts2Init(global, WinJS, undefined) { "use strict"; var Utilities = WinJS.Utilities, Key = Utilities.Key, Scheduler = Utilities.Scheduler; var strings = { get itemInfoIsInvalid() { return WinJS.Resources._getWinJSString("ui/itemInfoIsInvalid").value; }, get groupInfoResultIsInvalid() { return WinJS.Resources._getWinJSString("ui/groupInfoResultIsInvalid").value; } }; // // Helpers for dynamic CSS rules // // Rule deletions are delayed until the next rule insertion. This helps the // scenario where a ListView changes layouts. By doing the rule manipulations // in a single synchronous block, IE will do 1 layout pass instead of 2. // // Dynamic CSS rules will be added to this style element var layoutStyleElem = document.createElement("style"); document.head.appendChild(layoutStyleElem); var nextCssClassId = 0, staleClassNames = []; // The prefix for the class name should not contain dashes function uniqueCssClassName(prefix) { return "_win-dynamic-" + prefix + "-" + (nextCssClassId++); } var dragBetweenTransition = "transform cubic-bezier(0.1, 0.9, 0.2, 1) 167ms"; var dragBetweenDistance = 12; // Removes the dynamic CSS rules corresponding to the classes in staleClassNames // from the DOM. function flushDynamicCssRules() { var rules = layoutStyleElem.sheet.cssRules, classCount = staleClassNames.length, i, ruleCount, j, ruleSuffix; for (i = 0; i < classCount; i++) { ruleSuffix = "." + staleClassNames[i] + " "; for (j = rules.length - 1; j >= 0; j--) { if (rules[j].selectorText.indexOf(ruleSuffix) !== -1) { layoutStyleElem.sheet.deleteRule(j); } } } staleClassNames = []; } // Creates a dynamic CSS rule and adds it to the DOM. uniqueToken is a class name // which uniquely identifies a set of related rules. These rules may be removed // using deleteDynamicCssRule. uniqueToken should be created using uniqueCssClassName. function addDynamicCssRule(uniqueToken, site, selector, body) { flushDynamicCssRules(); var rule = "." + WinJS.UI._listViewClass + " ." + uniqueToken + " " + selector + " { " + body + "}"; var perfId = "_addDynamicCssRule:" + uniqueToken + ",info"; if (site) { site._writeProfilerMark(perfId); } else { msWriteProfilerMark("WinJS.UI.ListView:Layout" + perfId); } layoutStyleElem.sheet.insertRule(rule, 0); } // Marks the CSS rules corresponding to uniqueToken for deletion. The rules // should have been added by addDynamicCssRule. function deleteDynamicCssRule(uniqueToken) { staleClassNames.push(uniqueToken); } // // Helpers shared by all layouts // // Clamps x to the range first <= x <= last function clampToRange(first, last, x) { return Math.max(first, Math.min(last, x)); } function getDimension(element, property) { return WinJS.Utilities.convertToPixels(element, window.getComputedStyle(element, null)[property]); } // Returns the sum of the margin, border, and padding for the side of the // element specified by side. side can be "Left", "Right", "Top", or "Bottom". function getOuter(side, element) { return getDimension(element, "margin" + side) + getDimension(element, "border" + side + "Width") + getDimension(element, "padding" + side); } // Returns the total height of element excluding its content height function getOuterHeight(element) { return getOuter("Top", element) + getOuter("Bottom", element); } // Returns the total width of element excluding its content width function getOuterWidth(element) { return getOuter("Left", element) + getOuter("Right", element); } function forEachContainer(itemsContainer, callback) { if (itemsContainer.items) { for (var i = 0, len = itemsContainer.items.length; i < len; i++) { callback(itemsContainer.items[i], i); } } else { for (var b = 0, index = 0; b < itemsContainer.itemsBlocks.length; b++) { var block = itemsContainer.itemsBlocks[b]; for (var i = 0, len = block.items.length; i < len; i++) { callback(block.items[i], index++); } } } } function containerFromIndex(itemsContainer, index) { if (index < 0) { return null; } if (itemsContainer.items) { return (index < itemsContainer.items.length ? itemsContainer.items[index] : null); } else { var blockSize = itemsContainer.itemsBlocks[0].items.length, blockIndex = Math.floor(index / blockSize), offset = index % blockSize; return (blockIndex < itemsContainer.itemsBlocks.length && offset < itemsContainer.itemsBlocks[blockIndex].items.length ? itemsContainer.itemsBlocks[blockIndex].items[offset] : null); } } function getItemsContainerTree(itemsContainer, tree) { var itemsContainerTree; for (var i = 0, treeLength = tree.length; i < treeLength; i++) { if (tree[i].itemsContainer.element === itemsContainer) { itemsContainerTree = tree[i].itemsContainer; break; } } return itemsContainerTree; } function getItemsContainerLength(itemsContainer) { var blocksCount, itemsCount; if (itemsContainer.itemsBlocks) { blocksCount = itemsContainer.itemsBlocks.length; if (blocksCount > 0) { itemsCount = (itemsContainer.itemsBlocks[0].items.length * (blocksCount - 1)) + itemsContainer.itemsBlocks[blocksCount - 1].items.length; } else { itemsCount = 0; } } else { itemsCount = itemsContainer.items.length; } return itemsCount; } WinJS.Namespace.define("WinJS.UI", { Layout: WinJS.Class.define(function Layout_ctor(options) { /// /// /// Creates a new Layout object. /// /// /// The set of options to be applied initially to the new Layout object. /// /// /// The new Layout object. /// /// }), _LayoutCommon: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(WinJS.UI.Layout, null, { /// /// Gets or sets the position of group headers relative to their items. /// The default value is "top". /// groupHeaderPosition: { enumerable: true, get: function () { return this._groupHeaderPosition; }, set: function (position) { this._groupHeaderPosition = position; this._invalidateLayout(); } }, // Implementation of part of ILayout interface initialize: function _LayoutCommon_initialize(site, groupsEnabled) { site._writeProfilerMark("Layout:initialize,info"); if (!this._inListMode) { Utilities.addClass(site.surface, WinJS.UI._gridLayoutClass); } if (this._backdropColorClassName) { Utilities.addClass(site.surface, this._backdropColorClassName); } if (this._disableBackdropClassName) { Utilities.addClass(site.surface, this._disableBackdropClassName); } this._groups = []; this._groupMap = {}; this._oldGroupHeaderPosition = null; this._usingStructuralNodes = false; this._site = site; this._groupsEnabled = groupsEnabled; this._resetAnimationCaches(true); }, /// /// Gets or sets the orientation for the layout. /// The default value is "horizontal". /// orientation: { enumerable: true, get: function () { return this._orientation; }, set: function (orientation) { this._orientation = orientation; this._horizontal = (orientation === "horizontal"); this._invalidateLayout(); } }, uninitialize: function _LayoutCommon_uninitialize() { var that = this; var perfId = "Layout:uninitialize,info"; function cleanGroups(groups) { var len = groups.length, i; for (i = 0; i < len; i++) { groups[i].cleanUp(true); } } this._elementsToMeasure = {}; if (this._site) { this._site._writeProfilerMark(perfId); Utilities.removeClass(this._site.surface, WinJS.UI._gridLayoutClass); Utilities.removeClass(this._site.surface, WinJS.UI._headerPositionTopClass); Utilities.removeClass(this._site.surface, WinJS.UI._headerPositionLeftClass); WinJS.Utilities.removeClass(this._site.surface, WinJS.UI._structuralNodesClass); this._site.surface.style.cssText = ""; if (this._groups) { cleanGroups(this._groups); this._groups = null; this._groupMap = null; } if (this._layoutPromise) { this._layoutPromise.cancel(); this._layoutPromise = null; } this._resetMeasurements(); this._oldGroupHeaderPosition = null; this._usingStructuralNodes = null; // The properties given to us by the app (_groupInfo, _itemInfo, // _groupHeaderPosition) are not cleaned up so that the values are // remembered if the layout is reused. if (this._backdropColorClassName) { Utilities.removeClass(this._site.surface, this._backdropColorClassName); deleteDynamicCssRule(this._backdropColorClassName); this._backdropColorClassName = null; } if (this._disableBackdropClassName) { Utilities.removeClass(this._site.surface, this._disableBackdropClassName); deleteDynamicCssRule(this._disableBackdropClassName); this._disableBackdropClassName = null; } this._site = null; this._groupsEnabled = null; if (this._animationsRunning) { this._animationsRunning.cancel(); } this._animatingItemsBlocks = {}; } else { msWriteProfilerMark("WinJS.UI.ListView:" + perfId); } }, numberOfItemsPerItemsBlock: { get: function _LayoutCommon_getNumberOfItemsPerItemsBlock() { function allGroupsAreUniform() { var groupCount = that._site.groupCount, i; for (i = 0; i < groupCount; i++) { if (that._isCellSpanning(i)) { return false; } } return true; } var that = this; return that._measureItem(0).then(function () { if (that._sizes.viewportContentSize !== that._getViewportCrossSize()) { that._viewportSizeChanged(that._getViewportCrossSize()); } if (allGroupsAreUniform()) { that._usingStructuralNodes = WinJS.UI._LayoutCommon._barsPerItemsBlock > 0; return WinJS.UI._LayoutCommon._barsPerItemsBlock * that._itemsPerBar; } else { that._usingStructuralNodes = false; return null; } }); } }, layout: function _LayoutCommon_layout(tree, changedRange, modifiedItems, modifiedGroups) { // changedRange implies that the minimum amount of work the layout needs to do is as follows: // - It needs to lay out group shells (header containers and items containers) from // firstChangedGroup thru lastGroup. // - It needs to ask firstChangedGroup thru lastChangedGroup to lay out their // contents (i.e. win-containers). // - For each group included in the changedRange, it needs to lay out its // contents (i.e. win-containers) from firstChangedItem thru lastItem. var that = this; var site = that._site, layoutPerfId = "Layout.layout", realizedRangePerfId = layoutPerfId + ":realizedRange", realizedRangePromise; that._site._writeProfilerMark(layoutPerfId + ",StartTM"); that._site._writeProfilerMark(realizedRangePerfId + ",StartTM"); // Receives an items container's tree and returns a normalized copy. // This allows us to hold on to a snapshot of the tree without // worrying that items may have been unexpectedly inserted/ // removed/moved. The returned tree always appears as though // structural nodes are disabled. function copyItemsContainerTree(itemsContainer) { function copyItems(itemsContainer) { if (that._usingStructuralNodes) { var items = []; itemsContainer.itemsBlocks.forEach(function (itemsBlock) { items = items.concat(itemsBlock.items.slice(0)); }); return items; } else { return itemsContainer.items.slice(0); } } return { element: itemsContainer.element, items: copyItems(itemsContainer) }; } // Updates the GridLayout's internal state to reflect the current tree. // Similarly tells each group to update its internal state via prepareLayout. // After this function runs, the ILayout functions will return results that // are appropriate for the current tree. function updateGroups() { function createGroup(groupInfo, itemsContainer) { var GroupType = (groupInfo.enableCellSpanning ? Groups.CellSpanningGroup : Groups.UniformGroup); return new GroupType(that, itemsContainer); } var oldRealizedItemRange = (that._groups.length > 0 ? that._getRealizationRange() : null), newGroups = [], prepared = [], cleanUpDom = {}, newGroupMap = {}, currentIndex = 0, len = tree.length, i; for (i = 0; i < len; i++) { var oldChangedRealizedRangeInGroup = null, groupInfo = that._getGroupInfo(i), groupKey = that._site.groupFromIndex(i).key, oldGroup = that._groupMap[groupKey], wasCellSpanning = oldGroup instanceof Groups.CellSpanningGroup, isCellSpanning = groupInfo.enableCellSpanning; if (oldGroup) { if (wasCellSpanning !== isCellSpanning) { // The group has changed types so DOM needs to be cleaned up cleanUpDom[groupKey] = true; } else { // Compute the range of changed items that is within the group's realized range var firstChangedIndexInGroup = Math.max(0, changedRange.firstIndex - oldGroup.startIndex), oldRealizedItemRangeInGroup = that._rangeForGroup(oldGroup, oldRealizedItemRange); if (oldRealizedItemRangeInGroup && firstChangedIndexInGroup <= oldRealizedItemRangeInGroup.lastIndex) { // The old changed realized range is non-empty oldChangedRealizedRangeInGroup = { firstIndex: Math.max(firstChangedIndexInGroup, oldRealizedItemRangeInGroup.firstIndex), lastIndex: oldRealizedItemRangeInGroup.lastIndex }; } } } var group = createGroup(groupInfo, tree[i].itemsContainer.element); var prepareLayoutPromise; if (group.prepareLayoutWithCopyOfTree) { prepareLayoutPromise = group.prepareLayoutWithCopyOfTree(copyItemsContainerTree(tree[i].itemsContainer), oldChangedRealizedRangeInGroup, oldGroup, { groupInfo: groupInfo, startIndex: currentIndex, }); } else { prepareLayoutPromise = group.prepareLayout(getItemsContainerLength(tree[i].itemsContainer), oldChangedRealizedRangeInGroup, oldGroup, { groupInfo: groupInfo, startIndex: currentIndex, }); } prepared.push(prepareLayoutPromise); currentIndex += group.count; newGroups.push(group); newGroupMap[groupKey] = group; } return WinJS.Promise.join(prepared).then(function () { var currentOffset = 0; for (var i = 0, len = newGroups.length; i < len; i++) { var group = newGroups[i]; group.offset = currentOffset; currentOffset += that._getGroupSize(group); } // Clean up deleted groups Object.keys(that._groupMap).forEach(function (deletedKey) { var skipDomCleanUp = !cleanUpDom[deletedKey]; that._groupMap[deletedKey].cleanUp(skipDomCleanUp); }); that._groups = newGroups; that._groupMap = newGroupMap; }); } // When doRealizedRange is true, this function is synchronous and has no return value. // When doRealizedRange is false, this function is asynchronous and returns a promise. function layoutGroupContent(groupIndex, realizedItemRange, doRealizedRange) { var group = that._groups[groupIndex], firstChangedIndexInGroup = Math.max(0, changedRange.firstIndex - group.startIndex), realizedItemRangeInGroup = that._rangeForGroup(group, realizedItemRange), beforeRealizedRange; if (doRealizedRange) { group.layoutRealizedRange(firstChangedIndexInGroup, realizedItemRangeInGroup); } else { if (!realizedItemRangeInGroup) { beforeRealizedRange = (group.startIndex + group.count - 1 < realizedItemRange.firstIndex); } return group.layoutUnrealizedRange(firstChangedIndexInGroup, realizedItemRangeInGroup, beforeRealizedRange); } } // Synchronously lays out: // - Realized and unrealized group shells (header containers and items containers). // This is needed so that each realized group will be positioned at the correct offset. // - Realized items. function layoutRealizedRange() { if (that._groups.length === 0) { return; } var realizedItemRange = that._getRealizationRange(), len = tree.length, i, firstChangedGroup = site.groupIndexFromItemIndex(changedRange.firstIndex); for (i = firstChangedGroup; i < len; i++) { layoutGroupContent(i, realizedItemRange, true); that._layoutGroup(i); } } // Asynchronously lays out the unrealized items function layoutUnrealizedRange() { if (that._groups.length === 0) { return WinJS.Promise.wrap(); } var realizedItemRange = that._getRealizationRange(), // Last group before the realized range which contains 1 or more unrealized items lastGroupBefore = site.groupIndexFromItemIndex(realizedItemRange.firstIndex - 1), // First group after the realized range which contains 1 or more unrealized items firstGroupAfter = site.groupIndexFromItemIndex(realizedItemRange.lastIndex + 1), firstChangedGroup = site.groupIndexFromItemIndex(changedRange.firstIndex), layoutPromises = [], groupCount = that._groups.length; var stop = false; var before = lastGroupBefore; var after = Math.max(firstChangedGroup, firstGroupAfter); after = Math.max(before + 1, after); while (!stop) { stop = true; if (before >= firstChangedGroup) { layoutPromises.push(layoutGroupContent(before, realizedItemRange, false)); stop = false; before--; } if (after < groupCount) { layoutPromises.push(layoutGroupContent(after, realizedItemRange, false)); stop = false; after++; } } return WinJS.Promise.join(layoutPromises); } realizedRangePromise = that._measureItem(0).then(function () { WinJS.Utilities[that._usingStructuralNodes ? "addClass" : "removeClass"](that._site.surface, WinJS.UI._structuralNodesClass); if (that._sizes.viewportContentSize !== that._getViewportCrossSize()) { that._viewportSizeChanged(that._getViewportCrossSize()); } // Move deleted elements to their original positions before calling updateGroups can be slow. that._cacheRemovedElements(modifiedItems, that._cachedItemRecords, that._cachedInsertedItemRecords, that._cachedRemovedItems, false); that._cacheRemovedElements(modifiedGroups, that._cachedHeaderRecords, that._cachedInsertedHeaderRecords, that._cachedRemovedHeaders, true); return updateGroups(); }).then(function () { that._syncDomWithGroupHeaderPosition(tree); // Explicitly set the surface width/height. This maintains backwards // compatibility with the original layouts by allowing the items // to be shifted through surface margins. if (that._horizontal) { if (that._groupsEnabled && that._groupHeaderPosition === WinJS.UI.HeaderPosition.left) { site.surface.style.cssText += ";height:" + that._sizes.surfaceContentSize + "px;-ms-grid-columns: (" + that._sizes.headerContainerWidth + "px auto)[" + tree.length + "]"; } else { site.surface.style.height = that._sizes.surfaceContentSize + "px"; } } else { if (that._groupsEnabled && that._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { site.surface.style.cssText += ";width:" + that._sizes.surfaceContentSize + "px;-ms-grid-rows: (" + that._sizes.headerContainerHeight + "px auto)[" + tree.length + "]"; } else { site.surface.style.width = that._sizes.surfaceContentSize + "px"; } } layoutRealizedRange(); that._layoutAnimations(modifiedItems, modifiedGroups); that._site._writeProfilerMark(realizedRangePerfId + ":complete,info"); that._site._writeProfilerMark(realizedRangePerfId + ",StopTM"); }, function (error) { that._site._writeProfilerMark(realizedRangePerfId + ":canceled,info"); that._site._writeProfilerMark(realizedRangePerfId + ",StopTM"); return WinJS.Promise.wrapError(error); }); that._layoutPromise = realizedRangePromise.then(function () { return layoutUnrealizedRange().then(function () { that._site._writeProfilerMark(layoutPerfId + ":complete,info"); that._site._writeProfilerMark(layoutPerfId + ",StopTM"); }, function (error) { that._site._writeProfilerMark(layoutPerfId + ":canceled,info"); that._site._writeProfilerMark(layoutPerfId + ",StopTM"); return WinJS.Promise.wrapError(error); }); }); return { realizedRangeComplete: realizedRangePromise, layoutComplete: that._layoutPromise }; }, itemsFromRange: function _LayoutCommon_itemsFromRange(firstPixel, lastPixel) { if (this._rangeContainsItems(firstPixel, lastPixel)) { return { firstIndex: this._firstItemFromRange(firstPixel), lastIndex: this._lastItemFromRange(lastPixel) }; } else { return { firstIndex: 0, lastIndex: -1 }; } }, getAdjacent: function _LayoutCommon_getAdjacent(currentItem, pressedKey) { var that = this, groupIndex = that._site.groupIndexFromItemIndex(currentItem.index), group = that._groups[groupIndex], adjustedKey = that._adjustedKeyForOrientationAndBars(that._adjustedKeyForRTL(pressedKey), group instanceof Groups.CellSpanningGroup); if (currentItem.type === WinJS.UI.ObjectType.groupHeader) { if (pressedKey === Key.pageUp || pressedKey === Key.pageDown) { // We treat page up and page down keys as if an item had focus currentItem = { type: WinJS.UI.ObjectType.item, index: this._groups[currentItem.index].startIndex }; } else { switch (adjustedKey) { case Key.leftArrow: return { type: WinJS.UI.ObjectType.groupHeader, index: Math.max(0, currentItem.index - 1) }; case Key.rightArrow: return { type: WinJS.UI.ObjectType.groupHeader, index: Math.min(that._groups.length - 1, currentItem.index + 1) }; } return currentItem; } } function handleArrowKeys() { var currentItemInGroup = { type: currentItem.type, index: currentItem.index - group.startIndex }, newItem = group.getAdjacent(currentItemInGroup, adjustedKey); if (newItem === "boundary") { var prevGroup = that._groups[groupIndex - 1], nextGroup = that._groups[groupIndex + 1], lastGroupIndex = that._groups.length - 1; if (adjustedKey === Key.leftArrow) { if (groupIndex === 0) { // We're at the beginning of the first group so stay put return currentItem; } else if (prevGroup instanceof Groups.UniformGroup && group instanceof Groups.UniformGroup) { // Moving between uniform groups so maintain the row/column if possible var coordinates = that._indexToCoordinate(currentItemInGroup.index); var currentSlot = (that._horizontal ? coordinates.row : coordinates.column), indexOfLastBar = Math.floor((prevGroup.count - 1) / that._itemsPerBar), startOfLastBar = indexOfLastBar * that._itemsPerBar; // first cell of last bar return { type: WinJS.UI.ObjectType.item, index: prevGroup.startIndex + Math.min(prevGroup.count - 1, startOfLastBar + currentSlot) }; } else { // Moving to or from a cell spanning group so go to the last item return { type: WinJS.UI.ObjectType.item, index: group.startIndex - 1 }; } } else if (adjustedKey === Key.rightArrow) { if (groupIndex === lastGroupIndex) { // We're at the end of the last group so stay put return currentItem; } else if (group instanceof Groups.UniformGroup && nextGroup instanceof Groups.UniformGroup) { // Moving between uniform groups so maintain the row/column if possible var coordinates = that._indexToCoordinate(currentItemInGroup.index), currentSlot = (that._horizontal ? coordinates.row : coordinates.column); return { type: WinJS.UI.ObjectType.item, index: nextGroup.startIndex + Math.min(nextGroup.count - 1, currentSlot) }; } else { // Moving to or from a cell spanning group so go to the first item return { type: WinJS.UI.ObjectType.item, index: nextGroup.startIndex }; } } else { //#DBG _ASSERT(adjustedKey === Key.downArrow || adjustedKey === Key.upArrow); return currentItem; } } else { newItem.index += group.startIndex; return newItem; } } switch (that._adjustedKeyForRTL(pressedKey)) { case Key.upArrow: case Key.leftArrow: case Key.downArrow: case Key.rightArrow: return handleArrowKeys(); default: return WinJS.UI._LayoutCommon.prototype._getAdjacentForPageKeys.call(that, currentItem, pressedKey); } }, hitTest: function _LayoutCommon_hitTest(x, y) { var sizes = this._sizes, result; // Make the coordinates relative to grid layout's content box x -= sizes.layoutOriginX; y -= sizes.layoutOriginY; var groupIndex = this._groupFromOffset(this._horizontal ? x : y), group = this._groups[groupIndex]; // Make the coordinates relative to the margin box of the group's items container if (this._horizontal) { x -= group.offset; } else { y -= group.offset; } if (this._groupsEnabled) { if (this._groupHeaderPosition === WinJS.UI.HeaderPosition.left) { x -= sizes.headerContainerWidth; } else { // Headers above y -= sizes.headerContainerHeight; } } result = group.hitTest(x, y); result.index += group.startIndex; result.insertAfterIndex += group.startIndex; return result; }, // Animation cycle: // // Edits // --- UpdateTree Realize // | | --- /\/\ // | | | | | | // ------------------------------------------------------- Time // | | | | | | | | // --- | | --- ---/\/\/\/\/\/\/\/\/ // setupAni | | layoutAni endAni (animations) // ---/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ // layout (outside realized range) // // // When there is a modification to the DataSource, the first thing that happens is setupAnimations is // called with the current tree. This allows us to cache the locations of the existing items. // // The next 3 steps have to be completely synchronous otherwise users will see intermediate states and // items will blink or jump between locations. // // ListView modifies the DOM tree. A container is added/removed from the group's itemsContainer for each // item added/removed to the group. The existing itemBoxes are shuffled between the different containers. // The itemBoxes for the removed items will be removed from the containers completely. Since the DOM tree // has been modified we have to apply a transform to position the itemBoxes at their original location. We // compare the new locations with the cached locations to figure out how far to translate the itemBoxes. // Also the removed items need to be placed back in the DOM without affecting layout (by using position // absolute) so that they also do not jump or blink. // // We only tranform and add back removed items for items which were on screen or are now on screen. // // Now the ListView can realize other items asynchronously. The items to realize are items which have been // inserted into the DataSource or items which are in the realization range because a removal has occurred // or the user has scroll slightly. // // During the realization pass the user may scroll. If they scroll to a range outside of the realization // range the items will just appear in the correct location without any animations. If they scroll to a // location within the old realization range we still have the items and they will animate correctly. // // During the realization pass another data source edit can occur. A realization pass is unable to run when // the tree and layout are out of sync. Otherwise it may try to request item at index X and get item at // index X + 1. This means that if another data source edit occurs before endAnimations is called we // restart the whole animation cycle. To group the animations between the two edits we do not reset the // caches of item box locations. We could add to it if there were items outside of the range however they // will only play half of the animation and will probably look just as ugly as not playing the animation at // all. This means setupAnimations will just be a no op in this scenario. // // This also shows that batching data source edits and only changing the data source when in loadingstate // "complete" is still a large performance win. // // Once the realization pass has finished ListView calls executeAnimations. This is where the layout // effectively fades out the removed items (and then removes them from the dom), moves the itemBoxes back // to translate(0,0), and fades in the inserted itemBoxes. ListView waits for the executeAnimations promise // to complete before allowing more data source edits to trigger another animation cycle. // // If a resize occurs during the animation cycle the animations will be canceled and items will jump to // their final positions. setupAnimations: function _LayoutCommon_setupAnimations() { // This function is called after a data source change so that we can cache the locations // of the realized items. if (this._groups.length === 0) { // No animations if we haven't measured before this._resetAnimationCaches(); return; } if (Object.keys(this._cachedItemRecords).length) { // Ignore the second call. return; } this._site._writeProfilerMark("Animation:setupAnimations,StartTM"); var realizationRange = this._getRealizationRange(); var tree = this._site.tree; var itemIndex = 0; var horizontal = (this.orientation === "horizontal"); for (var i = 0, treeLength = tree.length; i < treeLength; i++) { var groupBundle = tree[i]; var groupHasAtleastOneItemRealized = false; var group = this._groups[i]; var groupIsCellSpanning = group instanceof Groups.CellSpanningGroup; var groupOffset = (group ? group.offset : 0); forEachContainer(groupBundle.itemsContainer, function (container, j) { // Don't try to cache something outside of the realization range. if (realizationRange.firstIndex <= itemIndex && realizationRange.lastIndex >= itemIndex) { groupHasAtleastOneItemRealized = true; if (!this._cachedItemRecords[itemIndex]) { var itemPosition = this._getItemPositionForAnimations(itemIndex, i, j); var row = itemPosition.row; var column = itemPosition.column; var left = itemPosition.left; var top = itemPosition.top; // Setting both old and new variables now in case layoutAnimations is called multiple times. this._cachedItemRecords[itemIndex] = { oldRow: row, oldColumn: column, oldLeft: left, oldTop: top, width: itemPosition.width, height: itemPosition.height, element: container, inCellSpanningGroup: groupIsCellSpanning }; } } itemIndex++; }.bind(this)); if (groupHasAtleastOneItemRealized) { var groupIndex = i; if (!this._cachedHeaderRecords[groupIndex]) { var headerPosition = this._getHeaderPositionForAnimations(groupIndex); this._cachedHeaderRecords[groupIndex] = { oldLeft: headerPosition.left, oldTop: headerPosition.top, width: headerPosition.width, height: headerPosition.height, element: groupBundle.header, }; } if (!this._cachedGroupRecords[groupBundle.itemsContainer.element.uniqueID]) { this._cachedGroupRecords[groupBundle.itemsContainer.element.uniqueID] = { oldLeft: horizontal ? groupOffset : 0, left: horizontal ? groupOffset : 0, oldTop: horizontal ? 0 : groupOffset, top: horizontal ? 0 : groupOffset, element: groupBundle.itemsContainer.element, }; } } } this._site._writeProfilerMark("Animation:setupAnimations,StopTM"); }, _layoutAnimations: function _LayoutCommon_layoutAnimations(modifiedItems, modifiedGroups) { // This function is called after the DOM tree has been modified to match the data source. // In this function we update the cached records and apply transforms to hide the modifications // from the user. We will remove the transforms via animations in execute animation. //#DBG _ASSERT(!this._animationsRunning); if (!Object.keys(this._cachedItemRecords).length && !Object.keys(this._cachedGroupRecords).length && !Object.keys(this._cachedHeaderRecords).length) { return; } this._site._writeProfilerMark("Animation:layoutAnimation,StartTM"); this._updateAnimationCache(modifiedItems, modifiedGroups); var realizationRange = this._getRealizationRange(); var tree = this._site.tree; var itemIndex = 0; var horizontal = (this.orientation === "horizontal"); for (var i = 0, treeLength = tree.length; i < treeLength; i++) { var groupBundle = tree[i]; var group = this._groups[i]; var groupIsCellSpanning = group instanceof Groups.CellSpanningGroup; var groupOffset = (group ? group.offset : 0); var groupMovementX = 0; var groupMovementY = 0; var cachedGroupRecord = this._cachedGroupRecords[groupBundle.itemsContainer.element.uniqueID]; if (cachedGroupRecord) { if (horizontal) { groupMovementX = cachedGroupRecord.oldLeft - groupOffset; } else { groupMovementY = cachedGroupRecord.oldTop - groupOffset; } } forEachContainer(groupBundle.itemsContainer, function (container, j) { // Don't try to cache something outside of the realization range. if (realizationRange.firstIndex <= itemIndex && realizationRange.lastIndex >= itemIndex) { var cachedItemRecord = this._cachedItemRecords[itemIndex]; if (cachedItemRecord) { var itemPosition = this._getItemPositionForAnimations(itemIndex, i, j); var row = itemPosition.row; var column = itemPosition.column; var left = itemPosition.left; var top = itemPosition.top; cachedItemRecord.inCellSpanningGroup = cachedItemRecord.inCellSpanningGroup || groupIsCellSpanning; // If the item has moved we need to update the cache and apply a transform to make it // appear like it has not moved yet. if (cachedItemRecord.oldRow !== row || cachedItemRecord.oldColumn !== column || cachedItemRecord.oldTop !== top || cachedItemRecord.oldLeft !== left) { cachedItemRecord.row = row; cachedItemRecord.column = column; cachedItemRecord.left = left; cachedItemRecord.top = top; var xOffset = cachedItemRecord.oldLeft - cachedItemRecord.left - groupMovementX; var yOffset = cachedItemRecord.oldTop - cachedItemRecord.top - groupMovementY; xOffset = (this._site.rtl ? -1 : 1) * xOffset; cachedItemRecord.xOffset = xOffset; cachedItemRecord.yOffset = yOffset; if (xOffset !== 0 || yOffset !== 0) { var element = cachedItemRecord.element; cachedItemRecord.needsToResetTransform = true; element.style.transition = ""; element.style.transform = "translate(" + xOffset + "px," + yOffset + "px)"; } var itemsBlock = container.parentNode; if (WinJS.Utilities.hasClass(itemsBlock, WinJS.UI._itemsBlockClass)) { this._animatingItemsBlocks[itemsBlock.uniqueID] = itemsBlock; } } } else { // Treat items that came from outside of the realization range into the realization range // as a "Move" which means fade it in. this._cachedInsertedItemRecords[itemIndex] = container; container.style.transition = ""; container.style.opacity = 0; } } itemIndex++; }.bind(this)); var groupIndex = i; var cachedHeader = this._cachedHeaderRecords[groupIndex]; if (cachedHeader) { var headerPosition = this._getHeaderPositionForAnimations(groupIndex); // Note: If a group changes width we allow the header to immediately grow/shrink instead of // animating it. However if the header is removed we stick the header to the last known size. cachedHeader.height = headerPosition.height; cachedHeader.width = headerPosition.width; if (cachedHeader.oldLeft !== headerPosition.left || cachedHeader.oldTop !== headerPosition.top) { cachedHeader.left = headerPosition.left; cachedHeader.top = headerPosition.top; var xOffset = cachedHeader.oldLeft - cachedHeader.left; var yOffset = cachedHeader.oldTop - cachedHeader.top; xOffset = (this._site.rtl ? -1 : 1) * xOffset; if (xOffset !== 0 || yOffset !== 0) { cachedHeader.needsToResetTransform = true; var headerContainer = cachedHeader.element; headerContainer.style.transition = ""; headerContainer.style.transform = "translate(" + xOffset + "px," + yOffset + "px)"; } } } if (cachedGroupRecord) { if ((horizontal && cachedGroupRecord.left !== groupOffset) || (!horizontal && cachedGroupRecord.top !== groupOffset)) { var element = cachedGroupRecord.element; if (groupMovementX === 0 && groupMovementY === 0) { if (cachedGroupRecord.needsToResetTransform) { cachedGroupRecord.needsToResetTransform = false; element.style.transform = ""; } } else { var groupOffsetX = (this._site.rtl ? -1 : 1) * groupMovementX, groupOffsetY = groupMovementY; cachedGroupRecord.needsToResetTransform = true; element.style.transition = ""; element.style.transform = "translate(" + groupOffsetX + "px, " + groupOffsetY + "px)"; } } } } if (this._inListMode || this._itemsPerBar === 1) { var itemsBlockKeys = Object.keys(this._animatingItemsBlocks); for (var b = 0, blockKeys = itemsBlockKeys.length; b < blockKeys; b++) { this._animatingItemsBlocks[itemsBlockKeys[b]].style.overflow = 'visible'; } } this._site._writeProfilerMark("Animation:layoutAnimation,StopTM"); }, executeAnimations: function _LayoutCommon_executeAnimations() { // This function is called when we should perform an animation to reveal the true location of the items. // We fade out removed items, fade in added items, and move items which need to be shifted. If they moved // across columns we do a reflow animation. //#DBG _ASSERT(!this._animationsRunning); var animationSignal = new WinJS._Signal(); // Only animate the items on screen. this._filterInsertedElements(); this._filterMovedElements(); this._filterRemovedElements(); if (this._insertedElements.length === 0 && this._removedElements.length === 0 && this._itemMoveRecords.length === 0 && this._moveRecords.length === 0) { // Nothing to animate. this._resetAnimationCaches(true); animationSignal.complete(); return animationSignal.promise; } this._animationsRunning = animationSignal.promise; var slowAnimations = WinJS.UI.Layout._debugAnimations || WinJS.UI.Layout._slowAnimations; var site = this._site; var insertedElements = this._insertedElements; var removedElements = this._removedElements; var itemMoveRecords = this._itemMoveRecords; var moveRecords = this._moveRecords; var removeDelay = 0; var moveDelay = 0; var addDelay = 0; var currentAnimationPromise = null; var pendingTransitionPromises = []; var listenerElement = this._site.surface; var hasMultisizeMove = false; var hasReflow = false; var minOffset = 0; var maxOffset = 0; var itemContainersToExpand = {}; var upOutDist = 0; var downOutDist = 0; var upInDist = 0; var downInDist = 0; var reflowItemRecords = []; var horizontal = (this.orientation === "horizontal"); var oldReflowLayoutProperty = horizontal ? "oldColumn" : "oldRow", reflowLayoutProperty = horizontal ? "column" : "row", oldReflowLayoutPosition = horizontal ? "oldTop" : "oldLeft", reflowLayoutPosition = horizontal ? "top" : "left"; var animatingItemsBlocks = this._animatingItemsBlocks; for (var i = 0, len = itemMoveRecords.length; i < len; i++) { var cachedItemRecord = itemMoveRecords[i]; if (cachedItemRecord.inCellSpanningGroup) { hasMultisizeMove = true; break; } } var that = this; function startAnimations() { removePhase(); if (hasMultisizeMove) { cellSpanningFadeOutMove(); } else { if (that._itemsPerBar > 1) { var maxDistance = that._itemsPerBar * that._sizes.containerCrossSize + that._getHeaderSizeContentAdjustment() + that._sizes.containerMargins[horizontal ? "top" : (site.rtl ? "right" : "left")] + (horizontal ? that._sizes.layoutOriginY : that._sizes.layoutOriginX) for (var i = 0, len = itemMoveRecords.length; i < len; i++) { var cachedItemRecord = itemMoveRecords[i]; if (cachedItemRecord[oldReflowLayoutProperty] > cachedItemRecord[reflowLayoutProperty]) { upOutDist = Math.max(upOutDist, cachedItemRecord[oldReflowLayoutPosition] + cachedItemRecord[horizontal ? "height" : "width"]); upInDist = Math.max(upInDist, maxDistance - cachedItemRecord[reflowLayoutPosition]); hasReflow = true; reflowItemRecords.push(cachedItemRecord); } else if (cachedItemRecord[oldReflowLayoutProperty] < cachedItemRecord[reflowLayoutProperty]) { downOutDist = Math.max(downOutDist, maxDistance - cachedItemRecord[oldReflowLayoutPosition]); downInDist = Math.max(downInDist, cachedItemRecord[reflowLayoutPosition] + cachedItemRecord[horizontal ? "height" : "width"]); reflowItemRecords.push(cachedItemRecord); hasReflow = true; } } } if (site.rtl && !horizontal) { upOutDist *= -1; upInDist *= -1; downOutDist *= -1; downInDist *= -1; } if (hasReflow) { reflowPhase(that._itemsPerBar); } else { directMovePhase(); } } } if (WinJS.UI.Layout._debugAnimations) { requestAnimationFrame(function () { startAnimations() }); } else { startAnimations(); } function waitForNextPhase(nextPhaseCallback) { currentAnimationPromise = WinJS.Promise.join(pendingTransitionPromises); currentAnimationPromise.done(function () { pendingTransitionPromises = []; // The success is called even if the animations are canceled due to the WinJS.UI.executeTransition // API. To deal with that we check the animationSignal variable. If it is null the animations were // canceled so we shouldn't continue. if (animationSignal) { if (WinJS.UI.Layout._debugAnimations) { requestAnimationFrame(function () { nextPhaseCallback(); }) } else { nextPhaseCallback(); } } }); } function removePhase() { if (removedElements.length) { site._writeProfilerMark("Animation:setupRemoveAnimation,StartTM"); moveDelay += 60; addDelay += 60; var removeDuration = 120; if (slowAnimations) { removeDuration *= 10; } pendingTransitionPromises.push(WinJS.UI.executeTransition(removedElements, [{ property: "opacity", delay: removeDelay, duration: removeDuration, timing: "linear", to: 0, skipStylesReset: true }])); site._writeProfilerMark("Animation:setupRemoveAnimation,StopTM"); } } function cellSpanningFadeOutMove() { site._writeProfilerMark("Animation:cellSpanningFadeOutMove,StartTM"); // For multisize items which move we fade out and then fade in (opacity 1->0->1) var moveElements = []; for (var i = 0, len = itemMoveRecords.length; i < len; i++) { var cachedItemRecord = itemMoveRecords[i]; var container = cachedItemRecord.element; moveElements.push(container); } // Including groups and headers. for (var i = 0, len = moveRecords.length; i < len; i++) { var cachedItemRecord = moveRecords[i]; var container = cachedItemRecord.element; moveElements.push(container); } var fadeOutDuration = 120; if (slowAnimations) { fadeOutDuration *= 10; } pendingTransitionPromises.push(WinJS.UI.executeTransition(moveElements, { property: "opacity", delay: removeDelay, duration: fadeOutDuration, timing: "linear", to: 0 })); waitForNextPhase(cellSpanningFadeInMove); site._writeProfilerMark("Animation:cellSpanningFadeOutMove,StopTM"); } function cellSpanningFadeInMove() { site._writeProfilerMark("Animation:cellSpanningFadeInMove,StartTM"); addDelay = 0; var moveElements = []; // Move them to their final location. for (var i = 0, len = itemMoveRecords.length; i < len; i++) { var cachedItemRecord = itemMoveRecords[i]; var container = cachedItemRecord.element; container.style.transform = ""; moveElements.push(container); } // Including groups and headers. for (var i = 0, len = moveRecords.length; i < len; i++) { var cachedItemRecord = moveRecords[i]; var container = cachedItemRecord.element; container.style.transform = ""; moveElements.push(container); } var fadeInDuration = 120; if (slowAnimations) { fadeInDuration *= 10; } // For multisize items which move we fade out and then fade in (opacity 1->0->1) pendingTransitionPromises.push(WinJS.UI.executeTransition(moveElements, { property: "opacity", delay: addDelay, duration: fadeInDuration, timing: "linear", to: 1 })); site._writeProfilerMark("Animation:cellSpanningFadeInMove,StopTM"); addPhase(); } function reflowPhase(itemsPerBar) { site._writeProfilerMark("Animation:setupReflowAnimation,StartTM"); var itemContainersLastBarIndices = {} for (var i = 0, len = reflowItemRecords.length; i < len; i++) { var reflowItemRecord = reflowItemRecords[i]; var xOffset = reflowItemRecord.xOffset; var yOffset = reflowItemRecord.yOffset; if (reflowItemRecord[oldReflowLayoutProperty] > reflowItemRecord[reflowLayoutProperty]) { if (horizontal) { yOffset -= upOutDist; } else { xOffset -= upOutDist; } } else if (reflowItemRecord[oldReflowLayoutProperty] < reflowItemRecord[reflowLayoutProperty]) { if (horizontal) { yOffset += downOutDist; } else { xOffset += downOutDist; } } var container = reflowItemRecord.element; minOffset = Math.min(minOffset, horizontal ? xOffset : yOffset); maxOffset = Math.max(maxOffset, horizontal ? xOffset : yOffset); var itemsContainer = container.parentNode; if (!WinJS.Utilities.hasClass(itemsContainer, "win-itemscontainer")) { itemsContainer = itemsContainer.parentNode } // The itemscontainer element is always overflow:hidden for two reasons: // 1) Better panning performance // 2) When there is margin betweeen the itemscontainer and the surface elements, items that // reflow should not be visible while they travel long distances or overlap with headers. // This introduces an issue when updateTree makes the itemscontainer smaller, but we need its size // to remain the same size during the execution of the animation to avoid having some of the animated // items being clipped. This is only an issue when items from the last column (in horizontal mode) or row // (in vertical mode) of the group will reflow. Therefore, we change the padding so that the contents are larger, // and then use margin to reverse the size change. We don't do this expansion when it is unnecessary because the // layout/formatting caused by these style changes has significant cost when the group has thousands of items. var lastBarIndex = itemContainersLastBarIndices[itemsContainer.uniqueID]; if (!lastBarIndex) { var count = getItemsContainerLength(getItemsContainerTree(itemsContainer, site.tree)); itemContainersLastBarIndices[itemsContainer.uniqueID] = lastBarIndex = Math.ceil(count / itemsPerBar) - 1; } if (reflowItemRecords[i][horizontal ? "column" : "row"] === lastBarIndex) { itemContainersToExpand[itemsContainer.uniqueID] = itemsContainer; } var reflowDuration = 80; if (slowAnimations) { reflowDuration *= 10; } pendingTransitionPromises.push(WinJS.UI.executeTransition(container, { property: "transform", delay: moveDelay, duration: reflowDuration, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "translate(" + xOffset + "px," + yOffset + "px)" })); } var itemContainerKeys = Object.keys(itemContainersToExpand); for (var i = 0, len = itemContainerKeys.length; i < len; i++) { var itemContainer = itemContainersToExpand[itemContainerKeys[i]]; if (site.rtl && horizontal) { itemContainer.style.paddingLeft = (-1 * minOffset) + 'px'; itemContainer.style.marginLeft = minOffset + 'px'; } else { itemContainer.style[horizontal ? "paddingRight" : "paddingBottom"] = maxOffset + 'px'; itemContainer.style[horizontal ? "marginRight" : "marginBottom"] = '-' + maxOffset + 'px'; } } var itemsBlockKeys = Object.keys(animatingItemsBlocks); for (var i = 0, len = itemsBlockKeys.length; i < len; i++) { animatingItemsBlocks[itemsBlockKeys[i]].classList.add(WinJS.UI._clipClass); } waitForNextPhase(afterReflowPhase); site._writeProfilerMark("Animation:setupReflowAnimation,StopTM"); } function cleanupItemsContainers() { // Reset the styles used to obtain overflow-y: hidden overflow-x: visible. var itemContainerKeys = Object.keys(itemContainersToExpand); for (var i = 0, len = itemContainerKeys.length; i < len; i++) { var itemContainer = itemContainersToExpand[itemContainerKeys[i]]; if (site.rtl && horizontal) { itemContainer.style.paddingLeft = ''; itemContainer.style.marginLeft = ''; } else { itemContainer.style[horizontal ? "paddingRight" : "paddingBottom"] = ''; itemContainer.style[horizontal ? "marginRight" : "marginBottom"] = ''; } } itemContainersToExpand = {}; var itemsBlockKeys = Object.keys(animatingItemsBlocks); for (var i = 0, len = itemsBlockKeys.length; i < len; i++) { var itemsBlock = animatingItemsBlocks[itemsBlockKeys[i]]; itemsBlock.style.overflow = ''; itemsBlock.classList.remove(WinJS.UI._clipClass); } } function afterReflowPhase() { site._writeProfilerMark("Animation:prepareReflowedItems,StartTM"); // Position the items at the edge ready to slide in. for (var i = 0, len = reflowItemRecords.length; i < len; i++) { var reflowItemRecord = reflowItemRecords[i]; var xOffset = 0, yOffset = 0; if (reflowItemRecord[oldReflowLayoutProperty] > reflowItemRecord[reflowLayoutProperty]) { if (horizontal) { yOffset = upInDist; } else { xOffset = upInDist; } } else if (reflowItemRecord[oldReflowLayoutProperty] < reflowItemRecord[reflowLayoutProperty]) { if (horizontal) { yOffset = -1 * downInDist; } else { xOffset = -1 * downInDist; } } reflowItemRecord.element.style.transition = ""; reflowItemRecord.element.style.transform = "translate(" + xOffset + "px," + yOffset + "px)"; } site._writeProfilerMark("Animation:prepareReflowedItems,StopTM"); if (WinJS.UI.Layout._debugAnimations) { requestAnimationFrame(function () { directMovePhase(true); }); } else { directMovePhase(true); } } function directMovePhase(fastMode) { // For groups and items which move we transition them from transform: translate(Xpx,Ypx) to translate(0px,0px). var duration = 200; if (fastMode) { duration = 150; moveDelay = 0; addDelay = 0; } if (slowAnimations) { duration *= 10; } if (itemMoveRecords.length > 0 || moveRecords.length > 0) { site._writeProfilerMark("Animation:setupMoveAnimation,StartTM"); var moveElements = []; for (var i = 0, len = moveRecords.length; i < len; i++) { var container = moveRecords[i].element; moveElements.push(container); } for (var i = 0, len = itemMoveRecords.length; i < len; i++) { var container = itemMoveRecords[i].element; moveElements.push(container); } pendingTransitionPromises.push(WinJS.UI.executeTransition(moveElements, { property: "transform", delay: moveDelay, duration: duration, timing: "cubic-bezier(0.1, 0.9, 0.2, 1)", to: "" })); addDelay += 80; site._writeProfilerMark("Animation:setupMoveAnimation,StopTM"); } addPhase(); } function addPhase() { if (insertedElements.length > 0) { site._writeProfilerMark("Animation:setupInsertAnimation,StartTM"); var addDuration = 120; if (slowAnimations) { addDuration *= 10; } pendingTransitionPromises.push(WinJS.UI.executeTransition(insertedElements, [{ property: "opacity", delay: addDelay, duration: addDuration, timing: "linear", to: 1 }])); site._writeProfilerMark("Animation:setupInsertAnimation,StopTM"); } waitForNextPhase(completePhase); } function completePhase() { site._writeProfilerMark("Animation:cleanupAnimations,StartTM"); cleanupItemsContainers(); for (var i = 0, len = removedElements.length; i < len; i++) { var container = removedElements[i]; if (container.parentNode) { WinJS.Utilities._disposeElement(container); container.parentNode.removeChild(container); } } site._writeProfilerMark("Animation:cleanupAnimations,StopTM"); that._animationsRunning = null; animationSignal.complete(); } this._resetAnimationCaches(true); // The PVL animation library completes sucessfully even if you cancel an animation. // If the animation promise passed to layout is canceled we should cancel the PVL animations and // set a marker for them to be ignored. animationSignal.promise.then(null, function () { // Since it was canceled make sure we still clean up the styles. cleanupItemsContainers(); for (var i = 0, len = moveRecords.length; i < len; i++) { var container = moveRecords[i].element; container.style.transform = ''; container.style.opacity = 1; } for (var i = 0, len = itemMoveRecords.length; i < len; i++) { var container = itemMoveRecords[i].element; container.style.transform = ''; container.style.opacity = 1; } for (var i = 0, len = insertedElements.length; i < len; i++) { insertedElements[i].style.opacity = 1; } for (var i = 0, len = removedElements.length; i < len; i++) { var container = removedElements[i]; if (container.parentNode) { WinJS.Utilities._disposeElement(container); container.parentNode.removeChild(container); } } this._animationsRunning = null; animationSignal = null; currentAnimationPromise && currentAnimationPromise.cancel(); }.bind(this)); return animationSignal.promise; }, dragOver: function _LayoutCommon_dragOver(x, y, dragInfo) { // The coordinates passed to dragOver should be in ListView's viewport space. 0,0 should be the top left corner of the viewport's padding. var indicesAffected = this.hitTest(x, y), groupAffected = (this._groups ? this._site.groupIndexFromItemIndex(indicesAffected.index) : 0), itemsContainer = this._site.tree[groupAffected].itemsContainer, itemsCount = getItemsContainerLength(itemsContainer), indexOffset = (this._groups ? this._groups[groupAffected].startIndex : 0), visibleRange = this._getVisibleRange(); indicesAffected.index -= indexOffset; indicesAffected.insertAfterIndex -= indexOffset; visibleRange.firstIndex = Math.max(visibleRange.firstIndex - indexOffset - 1, 0); visibleRange.lastIndex = Math.min(visibleRange.lastIndex - indexOffset + 1, itemsCount); var indexAfter = Math.max(Math.min(itemsCount - 1, indicesAffected.insertAfterIndex), -1), indexBefore = Math.min(indexAfter + 1, itemsCount); if (dragInfo) { for (var i = indexAfter; i >= visibleRange.firstIndex; i--) { if (!dragInfo._isIncluded(i + indexOffset)) { indexAfter = i; break; } else if (i === visibleRange.firstIndex) { indexAfter = -1; } } for (var i = indexBefore; i < visibleRange.lastIndex; i++) { if (!dragInfo._isIncluded(i + indexOffset)) { indexBefore = i; break; } else if (i === (visibleRange.lastIndex - 1)) { indexBefore = itemsCount; } } } var elementBefore = containerFromIndex(itemsContainer, indexBefore), elementAfter = containerFromIndex(itemsContainer, indexAfter); if (this._animatedDragItems) { for (var i = 0, len = this._animatedDragItems.length; i < len; i++) { var item = this._animatedDragItems[i]; if (item) { item.style.transition = this._site.animationsDisabled ? "" : dragBetweenTransition; item.style.transform = ""; } } } this._animatedDragItems = []; var horizontal = this.orientation === "horizontal", inListMode = this._inListMode || this._itemsPerBar === 1; if (this._groups && this._groups[groupAffected] instanceof Groups.CellSpanningGroup) { inListMode = this._groups[groupAffected]._slotsPerColumn === 1; } var horizontalTransform = 0, verticalTransform = 0; // In general, items should slide in the direction perpendicular to the layout's orientation. // In a horizontal layout, items are laid out top to bottom, left to right. For any two neighboring items in this layout, we want to move the first item up and the second down // to denote that any inserted item would go between those two. // Similarily, vertical layout should have the first item move left and the second move right. // List layout is a special case. A horizontal list layout can only lay things out left to right, so it should slide the two items left and right like a vertical grid. // A vertical list can only lay things out top to bottom, so it should slide items up and down like a horizontal grid. // In other words: Apply horizontal transformations if we're a vertical grid or horizontal list, otherwise use vertical transformations. if ((!horizontal && !inListMode) || (horizontal && inListMode)) { horizontalTransform = this._site.rtl ? -dragBetweenDistance : dragBetweenDistance; } else { verticalTransform = dragBetweenDistance; } if (elementBefore) { elementBefore.style.transition = this._site.animationsDisabled ? "" : dragBetweenTransition; elementBefore.style.transform = "translate(" + horizontalTransform + "px, " + verticalTransform + "px)"; this._animatedDragItems.push(elementBefore); } if (elementAfter) { elementAfter.style.transition = this._site.animationsDisabled ? "" : dragBetweenTransition; elementAfter.style.transform = "translate(" + (-horizontalTransform) + "px, -" + verticalTransform + "px)"; this._animatedDragItems.push(elementAfter); } }, dragLeave: function _LayoutCommon_dragLeave() { if (this._animatedDragItems) { for (var i = 0, len = this._animatedDragItems.length; i < len; i++) { this._animatedDragItems[i].style.transition = this._site.animationsDisabled ? "" : dragBetweenTransition; this._animatedDragItems[i].style.transform = ""; } } this._animatedDragItems = []; }, // Private methods _setMaxRowsOrColumns: function _LayoutCommon_setMaxRowsOrColumns(value) { if (value === this._maxRowsOrColumns || this._inListMode) { return; } // If container size is unavailable then we do not need to compute itemsPerBar // as it will be computed along with the container size. if (this._sizes && this._sizes.containerSizeLoaded) { this._itemsPerBar = Math.floor(this._sizes.maxItemsContainerContentSize / this._sizes.containerCrossSize); if (value) { this._itemsPerBar = Math.min(this._itemsPerBar, value); } this._itemsPerBar = Math.max(1, this._itemsPerBar); } this._maxRowsOrColumns = value; this._invalidateLayout(); }, _getItemPosition: function _LayoutCommon_getItemPosition(itemIndex) { if (this._groupsEnabled) { var groupIndex = Math.min(this._groups.length - 1, this._site.groupIndexFromItemIndex(itemIndex)), group = this._groups[groupIndex], itemOfGroupIndex = itemIndex - group.startIndex; return this._getItemPositionForAnimations(itemIndex, groupIndex, itemOfGroupIndex); } else { return this._getItemPositionForAnimations(itemIndex, 0, itemIndex); } }, _getRealizationRange: function _LayoutCommon_getRealizationRange() { var realizedRange = this._site.realizedRange; return { firstIndex: this._firstItemFromRange(realizedRange.firstPixel), lastIndex: this._lastItemFromRange(realizedRange.lastPixel) }; }, _getVisibleRange: function _LayoutCommon_getVisibleRange() { var visibleRange = this._site.visibleRange; return { firstIndex: this._firstItemFromRange(visibleRange.firstPixel), lastIndex: this._lastItemFromRange(visibleRange.lastPixel) }; }, _resetAnimationCaches: function _LayoutCommon_resetAnimationCaches(skipReset) { if (!skipReset) { // Caches with move transforms: this._resetStylesForRecords(this._cachedGroupRecords); this._resetStylesForRecords(this._cachedItemRecords); this._resetStylesForRecords(this._cachedHeaderRecords); // Caches with insert transforms: this._resetStylesForInsertedRecords(this._cachedInsertedItemRecords); this._resetStylesForInsertedRecords(this._cachedInsertedHeaderRecords); // Caches with insert transforms: this._resetStylesForRemovedRecords(this._cachedRemovedItems); this._resetStylesForRemovedRecords(this._cachedRemovedHeaders); var itemsBlockKeys = Object.keys(this._animatingItemsBlocks); for (var i = 0, len = itemsBlockKeys.length; i < len; i++) { var itemsBlock = this._animatingItemsBlocks[itemsBlockKeys[i]]; itemsBlock.style.overflow = ''; itemsBlock.classList.remove(WinJS.UI._clipClass); } } this._cachedGroupRecords = {}; this._cachedItemRecords = {}; this._cachedHeaderRecords = {}; this._cachedInsertedItemRecords = {}; this._cachedInsertedHeaderRecords = {}; this._cachedRemovedItems = []; this._cachedRemovedHeaders = []; this._animatingItemsBlocks = {}; }, _cacheRemovedElements: function _LayoutCommon_cacheRemovedElements(modifiedElements, cachedRecords, cachedInsertedRecords, removedElements, areHeaders) { var containerMargins = this._sizes.containerMargins; var leftStr = "left"; if (this._site.rtl) { leftStr = "right"; } // Offset between the container's content box and its margin box var outerX, outerY; if (areHeaders) { outerX = this._sizes.headerContainerOuterX; outerY = this._sizes.headerContainerOuterY; } else { outerX = this._sizes.containerMargins[leftStr]; outerY = this._sizes.containerMargins.top; } // Cache the removed boxes and place them back in the DOM with position absolute // so that they do not appear like they have moved. for (var i = 0, len = modifiedElements.length; i < len; i++) { var modifiedElementLookup = modifiedElements[i]; if (modifiedElementLookup.newIndex === -1) { var container = modifiedElementLookup.element; var cachedItemRecord = cachedRecords[modifiedElementLookup.oldIndex]; if (cachedItemRecord) { cachedItemRecord.element = container; // This item can no longer be a moved item. delete cachedRecords[modifiedElementLookup.oldIndex]; container.style.position = "absolute"; container.style.transition = ""; container.style.top = cachedItemRecord.oldTop - outerY + "px"; container.style[leftStr] = cachedItemRecord.oldLeft - outerX + "px"; container.style.width = cachedItemRecord.width + "px"; container.style.height = cachedItemRecord.height + "px"; container.style.transform = ""; this._site.surface.appendChild(container); removedElements.push(cachedItemRecord); } if (cachedInsertedRecords[modifiedElementLookup.oldIndex]) { delete cachedInsertedRecords[modifiedElementLookup.oldIndex]; } } } }, _cacheInsertedElements: function _LayoutCommon_cacheInsertedItems(modifiedElements, cachedInsertedRecords, cachedRecords) { var newCachedInsertedRecords = {}; for (var i = 0, len = modifiedElements.length; i < len; i++) { var modifiedElementLookup = modifiedElements[i]; var wasInserted = cachedInsertedRecords[modifiedElementLookup.oldIndex]; if (wasInserted) { delete cachedInsertedRecords[modifiedElementLookup.oldIndex]; } if (wasInserted || modifiedElementLookup.oldIndex === -1 || modifiedElementLookup.moved) { var cachedRecord = cachedRecords[modifiedElementLookup.newIndex]; if (cachedRecord) { delete cachedRecords[modifiedElementLookup.newIndex]; } var modifiedElement = modifiedElementLookup.element; newCachedInsertedRecords[modifiedElementLookup.newIndex] = modifiedElement; modifiedElement.style.transition = ""; modifiedElement.style.transform = ""; modifiedElement.style.opacity = 0; } } var keys = Object.keys(cachedInsertedRecords); for (var i = 0, len = keys.length; i < len; i++) { newCachedInsertedRecords[keys[i]] = cachedInsertedRecords[keys[i]]; } return newCachedInsertedRecords; }, _resetStylesForRecords: function _LayoutCommon_resetStylesForRecords(recordsHash) { var recordKeys = Object.keys(recordsHash); for (var i = 0, len = recordKeys.length; i < len; i++) { var record = recordsHash[recordKeys[i]]; if (record.needsToResetTransform) { record.element.style.transform = ""; record.needsToResetTransform = false; } } }, _resetStylesForInsertedRecords: function _LayoutCommon_resetStylesForInsertedRecords(insertedRecords) { var insertedRecordKeys = Object.keys(insertedRecords); for (var i = 0, len = insertedRecordKeys.length; i < len; i++) { var insertedElement = insertedRecords[insertedRecordKeys[i]] insertedElement.style.opacity = 1; } }, _resetStylesForRemovedRecords: function _LayoutCommon_resetStylesForRemovedRecords(removedElements) { for (var i = 0, len = removedElements.length; i < len; i++) { var container = removedElements[i].element; if (container.parentNode) { WinJS.Utilities._disposeElement(container); container.parentNode.removeChild(container); } } }, _updateAnimationCache: function _LayoutCommon_updateAnimationCache(modifiedItems, modifiedGroups) { // ItemBoxes can change containers so we have to start them back without transforms // and then update them again. ItemsContainers don't need to do this. this._resetStylesForRecords(this._cachedItemRecords); this._resetStylesForRecords(this._cachedHeaderRecords); // Go through all the inserted records and reset their insert transforms. this._resetStylesForInsertedRecords(this._cachedInsertedItemRecords); this._resetStylesForInsertedRecords(this._cachedInsertedHeaderRecords); var existingContainers = {}; var realizationRange = this._getRealizationRange(); var tree = this._site.tree; for (var i = 0, itemIndex = 0, treeLength = tree.length; i < treeLength; i++) { forEachContainer(tree[i].itemsContainer, function (container, j) { if (realizationRange.firstIndex <= itemIndex && realizationRange.lastIndex >= itemIndex) { existingContainers[container.uniqueID] = true; } itemIndex++; }); } // Update the indicies before the insert since insert needs the new containers. function updateIndicies(modifiedElements, cachedRecords) { var updatedCachedRecords = {}; for (var i = 0, len = modifiedElements.length; i < len; i++) { var modifiedElementLookup = modifiedElements[i]; var cachedRecord = cachedRecords[modifiedElementLookup.oldIndex]; if (cachedRecord) { updatedCachedRecords[modifiedElementLookup.newIndex] = cachedRecord; cachedRecord.element = modifiedElementLookup.element; delete cachedRecords[modifiedElementLookup.oldIndex]; } } var cachedRecordKeys = Object.keys(cachedRecords); for (var i = 0, len = cachedRecordKeys.length; i < len; i++) { var key = cachedRecordKeys[i], record = cachedRecords[key]; // We need to filter out containers which were removed from the DOM. If container's item // wasn't realized container can be removed without adding record to modifiedItems. if (!record.element || existingContainers[record.element.uniqueID]) { updatedCachedRecords[key] = record; } } return updatedCachedRecords; } this._cachedItemRecords = updateIndicies(modifiedItems, this._cachedItemRecords); this._cachedHeaderRecords = updateIndicies(modifiedGroups, this._cachedHeaderRecords); this._cachedInsertedItemRecords = this._cacheInsertedElements(modifiedItems, this._cachedInsertedItemRecords, this._cachedItemRecords); this._cachedInsertedHeaderRecords = this._cacheInsertedElements(modifiedGroups, this._cachedInsertedHeaderRecords, this._cachedHeaderRecords); }, _filterRemovedElements: function _LayoutCommon_filterRemovedElements() { this._removedElements = []; if (this._site.animationsDisabled) { this._resetStylesForRemovedRecords(this._cachedRemovedItems); this._resetStylesForRemovedRecords(this._cachedRemovedHeaders); return; } var that = this; var oldLeftStr = this.orientation === "horizontal" ? "oldLeft" : "oldTop"; var widthStr = this.orientation === "horizontal" ? "width" : "height"; var visibleFirstPixel = this._site.scrollbarPos; var visibleLastPixel = visibleFirstPixel + this._site.viewportSize[widthStr] - 1; function filterRemovedElements(removedRecordArray, removedElementsArray) { for (var i = 0, len = removedRecordArray.length; i < len; i++) { var removedItem = removedRecordArray[i]; var container = removedItem.element; if (removedItem[oldLeftStr] + removedItem[widthStr] - 1 < visibleFirstPixel || removedItem[oldLeftStr] > visibleLastPixel || !that._site.viewport.contains(container)) { if (container.parentNode) { WinJS.Utilities._disposeElement(container); container.parentNode.removeChild(container); } } else { removedElementsArray.push(container); } } } filterRemovedElements(this._cachedRemovedItems, this._removedElements); filterRemovedElements(this._cachedRemovedHeaders, this._removedElements); }, _filterInsertedElements: function _LayoutCommon_filterInsertedElements() { this._insertedElements = []; if (this._site.animationsDisabled) { this._resetStylesForInsertedRecords(this._cachedInsertedItemRecords); this._resetStylesForInsertedRecords(this._cachedInsertedHeaderRecords); return; } var that = this; var visibleRange = this._getVisibleRange(); function filterInsertedElements(cachedInsertedRecords, insertedElementsArray) { var recordKeys = Object.keys(cachedInsertedRecords); for (var i = 0, len = recordKeys.length; i < len; i++) { var itemIndex = recordKeys[i]; var insertedRecord = cachedInsertedRecords[itemIndex]; if (itemIndex < visibleRange.firstIndex || itemIndex > visibleRange.lastIndex || that._site.viewport.contains(insertedRecord.element)) { insertedRecord.style.opacity = 1; } else { insertedElementsArray.push(insertedRecord); } } } filterInsertedElements(this._cachedInsertedItemRecords, this._insertedElements); filterInsertedElements(this._cachedInsertedHeaderRecords, this._insertedElements); }, _filterMovedElements: function _LayoutCommon_filterMovedElements() { var that = this; // This filters all the items and groups down which could have moved to just the items on screen. // The items which are not going to animate are immediately shown in their correct final location. var oldLeftStr = this.orientation === "horizontal" ? "oldLeft" : "oldTop"; var leftStr = this.orientation === "horizontal" ? "left" : "top"; var widthStr = this.orientation === "horizontal" ? "width" : "height"; var realizationRange = this._getRealizationRange(); var visibleFirstPixel = this._site.scrollbarPos; var visibleLastPixel = visibleFirstPixel + this._site.viewportSize[widthStr] - 1; // ItemMove can reflow across column or fade in/out due to multisize. this._itemMoveRecords = []; this._moveRecords = []; if (!this._site.animationsDisabled) { var tree = this._site.tree; var itemIndex = 0; for (var i = 0, treeLength = tree.length; i < treeLength; i++) { var groupBundle = tree[i]; var groupHasItemToAnimate = false; forEachContainer(groupBundle.itemsContainer, function (container) { if (realizationRange.firstIndex <= itemIndex && realizationRange.lastIndex >= itemIndex) { var cachedItemRecord = this._cachedItemRecords[itemIndex]; if (cachedItemRecord) { var shouldAnimate = ((cachedItemRecord[oldLeftStr] + cachedItemRecord[widthStr] - 1 >= visibleFirstPixel && cachedItemRecord[oldLeftStr] <= visibleLastPixel) || (cachedItemRecord[leftStr] + cachedItemRecord[widthStr] - 1 >= visibleFirstPixel && cachedItemRecord[leftStr] <= visibleLastPixel)) && that._site.viewport.contains(cachedItemRecord.element); if (shouldAnimate) { groupHasItemToAnimate = true; if (cachedItemRecord.needsToResetTransform) { this._itemMoveRecords.push(cachedItemRecord); delete this._cachedItemRecords[itemIndex]; } } } } itemIndex++; }.bind(this)); var groupIndex = i; var cachedHeaderRecord = this._cachedHeaderRecords[groupIndex]; if (cachedHeaderRecord) { if (groupHasItemToAnimate && cachedHeaderRecord.needsToResetTransform) { this._moveRecords.push(cachedHeaderRecord); delete this._cachedHeaderRecords[groupIndex]; } } var cachedGroupRecord = this._cachedGroupRecords[groupBundle.itemsContainer.element.uniqueID]; if (cachedGroupRecord) { if (groupHasItemToAnimate && cachedGroupRecord.needsToResetTransform) { this._moveRecords.push(cachedGroupRecord); delete this._cachedGroupRecords[groupBundle.itemsContainer.element.uniqueID]; } } } } // Reset transform for groups and items that were never on screen. this._resetStylesForRecords(this._cachedGroupRecords); this._resetStylesForRecords(this._cachedItemRecords); this._resetStylesForRecords(this._cachedHeaderRecords); }, _getItemPositionForAnimations: function _LayoutCommon_getItemPositionForAnimations(itemIndex, groupIndex, itemOfGroupIndex) { // Top/Left are used to know if the item has moved and also used to position the item if removed. // Row/Column are used to know if a reflow animation should occur // Height/Width are used when positioning a removed item without impacting layout. // The returned rectangle refers to the win-container's border/padding/content box. Coordinates // are relative to the viewport. var group = this._groups[groupIndex]; var itemPosition = group.getItemPositionForAnimations(itemOfGroupIndex); var groupOffset = (this._groups[groupIndex] ? this._groups[groupIndex].offset : 0); var headerWidth = (this._groupsEnabled && this._groupHeaderPosition === WinJS.UI.HeaderPosition.left ? this._sizes.headerContainerWidth : 0); var headerHeight = (this._groupsEnabled && this._groupHeaderPosition === WinJS.UI.HeaderPosition.top ? this._sizes.headerContainerHeight : 0); itemPosition.left += this._sizes.layoutOriginX + headerWidth + this._sizes.itemsContainerOuterX; itemPosition.top += this._sizes.layoutOriginY + headerHeight + this._sizes.itemsContainerOuterY; itemPosition[this._horizontal ? "left" : "top"] += groupOffset; return itemPosition; }, _getHeaderPositionForAnimations: function (groupIndex) { // Top/Left are used to know if the item has moved. // Height/Width are used when positioning a removed item without impacting layout. // The returned rectangle refers to the header container's content box. Coordinates // are relative to the viewport. var headerPosition; if (this._groupsEnabled) { var width = this._sizes.headerContainerWidth - this._sizes.headerContainerOuterWidth, height = this._sizes.headerContainerHeight - this._sizes.headerContainerOuterHeight; if (this._groupHeaderPosition === WinJS.UI.HeaderPosition.left && !this._horizontal) { height = this._groups[groupIndex].getItemsContainerSize() - this._sizes.headerContainerOuterHeight; } else if (this._groupHeaderPosition === WinJS.UI.HeaderPosition.top && this._horizontal) { width = this._groups[groupIndex].getItemsContainerSize() - this._sizes.headerContainerOuterWidth; } var offsetX = this._horizontal ? this._groups[groupIndex].offset : 0, offsetY = this._horizontal ? 0 : this._groups[groupIndex].offset; headerPosition = { top: this._sizes.layoutOriginY + offsetY + this._sizes.headerContainerOuterY, left: this._sizes.layoutOriginX + offsetX + this._sizes.headerContainerOuterX, height: height, width: width }; } else { headerPosition = { top: 0, left: 0, height: 0, width: 0 }; } return headerPosition; }, _rangeContainsItems: function _LayoutCommon_rangeContainsItems(firstPixel, lastPixel) { if (this._groups.length === 0) { return false; } else { var lastGroup = this._groups[this._groups.length - 1], lastPixelOfLayout = this._sizes.layoutOrigin + lastGroup.offset + this._getGroupSize(lastGroup) - 1; return lastPixel >= 0 && firstPixel <= lastPixelOfLayout; } }, _itemFromOffset: function _LayoutCommon_itemFromOffset(offset, options) { // supported options are: // - wholeItem: when set to true the fully visible item is returned // - last: if 1 the last item is returned. if 0 the first var that = this; if (this._groups.length === 0) { return 0; } function assignItemMargins(offset) { if (!options.wholeItem) { // This makes it such that if a container's margin is on screen but all of its // content is off screen then we'll treat the container as being off screen. var marginPropLast = (that._horizontal ? (that._site.rtl ? "right" : "left") : "top"), marginPropFirst = (that._horizontal ? (that._site.rtl ? "left" : "right") : "bottom"); if (options.last) { // When looking for the *last* item, treat all container margins // as belonging to the container *before* the margin. return offset - that._sizes.containerMargins[marginPropLast]; } else { // When looking for the *first* item, treat all container margins // as belonging to the container *after* the margin. return offset + that._sizes.containerMargins[marginPropFirst]; } } return offset; } // Assign the headers and margins to the appropriate groups. function assignGroupMarginsAndHeaders(offset) { if (options.last) { // When looking for the *last* group, the *trailing* header and margin belong to the group. return offset - that._getHeaderSizeGroupAdjustment() - that._sizes.itemsContainerOuterStart; } else { // When looking for the *first* group, the *leading* header and margin belong to the group. // No need to make any adjustments to offset because the correct header and margin // already belong to the group. return offset; } } options = options || {}; // Make offset relative to layout's content box offset -= this._sizes.layoutOrigin; offset = assignItemMargins(offset); var groupIndex = this._groupFromOffset(assignGroupMarginsAndHeaders(offset)), group = this._groups[groupIndex]; // Make offset relative to the margin box of the group's items container offset -= group.offset; offset -= this._getHeaderSizeGroupAdjustment(); return group.startIndex + group.itemFromOffset(offset, options); }, _firstItemFromRange: function _LayoutCommon_firstItemFromRange(firstPixel, options) { // supported options are: // - wholeItem: when set to true the first fully visible item is returned options = options || {}; options.last = 0; return this._itemFromOffset(firstPixel, options); }, _lastItemFromRange: function _LayoutCommon_lastItemFromRange(lastPixel, options) { // supported options are: // - wholeItem: when set to true the last fully visible item is returned options = options || {}; options.last = 1; return this._itemFromOffset(lastPixel, options); }, _adjustedKeyForRTL: function _LayoutCommon_adjustedKeyForRTL(key) { if (this._site.rtl) { if (key === Key.leftArrow) { key = Key.rightArrow; } else if (key === Key.rightArrow) { key = Key.leftArrow; } } return key; }, _adjustedKeyForOrientationAndBars: function _LayoutCommon_adjustedKeyForOrientationAndBars(key, cellSpanningGroup) { var newKey = key; // Don't support cell spanning if (cellSpanningGroup) { return key; } // First, convert the key into a virtual form based off of horizontal layouts. // In a horizontal layout, left/right keys switch between columns (AKA "bars"), and // up/down keys switch between rows (AKA "slots"). // In vertical mode, we want up/down to switch between rows (AKA "bars" when vertical), // and left/right to switch between columns (AKA "slots" when vertical). // The first step is to convert keypresses in vertical so that up/down always correspond to moving between slots, // and left/right moving between bars. if (!this._horizontal) { switch (newKey) { case Key.leftArrow: newKey = Key.upArrow; break; case Key.rightArrow: newKey = Key.downArrow; break; case Key.upArrow: newKey = Key.leftArrow; break; case Key.downArrow: newKey = Key.rightArrow; break; } } // Next, if we only have one item per bar, we'll make the change-slots-key the same as the change-bars-key if (this._itemsPerBar === 1) { if (newKey === Key.upArrow) { newKey = Key.leftArrow; } else if (newKey === Key.downArrow) { newKey = Key.rightArrow; } } return newKey; }, _getAdjacentForPageKeys: function _LayoutCommon_getAdjacentForPageKeys(currentItem, pressedKey) { var containerMargins = this._sizes.containerMargins, marginSum = (this.orientation === "horizontal" ? containerMargins.left + containerMargins.right : containerMargins.top + containerMargins.bottom); var viewportLength = this._site.viewportSize[this.orientation === "horizontal" ? "width" : "height"], firstPixel = this._site.scrollbarPos, lastPixel = firstPixel + viewportLength - 1 - containerMargins[(this.orientation === "horizontal" ? "right" : "bottom")], newFocus; // Handles page up by attempting to choose the first fully visible item // on the current page. If that item already has focus, chooses the // first item on the previous page. Page down is handled similarly. var firstIndex = this._firstItemFromRange(firstPixel, { wholeItem: true }), lastIndex = this._lastItemFromRange(lastPixel, { wholeItem: false }), currentItemPosition = this._getItemPosition(currentItem.index); var offscreen = false; if (currentItem.index < firstIndex || currentItem.index > lastIndex) { offscreen = true; if (this.orientation === "horizontal") { firstPixel = currentItemPosition.left - marginSum; } else { firstPixel = currentItemPosition.top - marginSum; } lastPixel = firstPixel + viewportLength - 1; firstIndex = this._firstItemFromRange(firstPixel, { wholeItem: true }); lastIndex = this._lastItemFromRange(lastPixel, { wholeItem: false }); } if (pressedKey === Key.pageUp) { if (!offscreen && firstIndex !== currentItem.index) { return { type: WinJS.UI.ObjectType.item, index: firstIndex }; } var end; if (this.orientation === "horizontal") { end = currentItemPosition.left + currentItemPosition.width + marginSum + containerMargins.left; } else { end = currentItemPosition.top + currentItemPosition.height + marginSum + containerMargins.bottom; } var firstIndexOnPrevPage = this._firstItemFromRange(end - viewportLength, { wholeItem: true }); if (currentItem.index === firstIndexOnPrevPage) { // The current item is so big that it spanned from the previous page, so we want to at least // move to the previous item. newFocus = Math.max(0, currentItem.index - this._itemsPerBar); } else { newFocus = firstIndexOnPrevPage; } } else { if (!offscreen && lastIndex !== currentItem.index) { return { type: WinJS.UI.ObjectType.item, index: lastIndex }; } // We need to subtract twice the marginSum from the item's starting position because we need to // consider that ensureVisible will scroll the viewport to include the new items margin as well // which may push the current item just off screen. var start; if (this.orientation === "horizontal") { start = currentItemPosition.left - marginSum - containerMargins.right; } else { start = currentItemPosition.top - marginSum - containerMargins.bottom; } var lastIndexOnNextPage = Math.max(0, this._lastItemFromRange(start + viewportLength - 1, { wholeItem: true })); if (currentItem.index === lastIndexOnNextPage) { // The current item is so big that it spans across the next page, so we want to at least // move to the next item. It is also ok to blindly increment this index w/o bound checking // since the browse mode clamps the bounds for page keys. This way we do not have to // asynchronoulsy request the count here. newFocus = currentItem.index + this._itemsPerBar; } else { newFocus = lastIndexOnNextPage; } } return { type: WinJS.UI.ObjectType.item, index: newFocus }; }, _isCellSpanning: function _LayoutCommon_isCellSpanning(groupIndex) { var group = this._site.groupFromIndex(groupIndex), groupInfo = this._groupInfo; if (groupInfo) { return !!(typeof groupInfo === "function" ? groupInfo(group) : groupInfo).enableCellSpanning; } else { return false; } }, // Can only be called after measuring has been completed _getGroupInfo: function _LayoutCommon_getGroupInfo(groupIndex) { var group = this._site.groupFromIndex(groupIndex), groupInfo = this._groupInfo, margins = this._sizes.containerMargins, adjustedInfo = { enableCellSpanning: false }; groupInfo = (typeof groupInfo === "function" ? groupInfo(group) : groupInfo); if (groupInfo) { if (groupInfo.enableCellSpanning && (+groupInfo.cellWidth !== groupInfo.cellWidth || +groupInfo.cellHeight !== groupInfo.cellHeight)) { throw new WinJS.ErrorFromName("WinJS.UI.GridLayout.GroupInfoResultIsInvalid", strings.groupInfoResultIsInvalid); } adjustedInfo = { enableCellSpanning: !!groupInfo.enableCellSpanning, cellWidth: groupInfo.cellWidth + margins.left + margins.right, cellHeight: groupInfo.cellHeight + margins.top + margins.bottom }; } return adjustedInfo; }, // itemIndex is optional _getItemInfo: function _LayoutCommon_getItemInfo(itemIndex) { var result; if (!this._itemInfo || typeof this._itemInfo !== "function") { if (this._useDefaultItemInfo) { result = this._defaultItemInfo(itemIndex); } else { throw new WinJS.ErrorFromName("WinJS.UI.GridLayout.ItemInfoIsInvalid", strings.itemInfoIsInvalid); } } else { result = this._itemInfo(itemIndex); } return WinJS.Promise.as(result).then(function (size) { if (!size || +size.width !== size.width || +size.height !== size.height) { throw new WinJS.ErrorFromName("WinJS.UI.GridLayout.ItemInfoIsInvalid", strings.itemInfoIsInvalid); } return size; }); }, _defaultItemInfo: function _LayoutCommon_defaultItemInfo(itemIndex) { var that = this; return this._site.renderItem(this._site.itemFromIndex(itemIndex)).then(function (element) { that._elementsToMeasure[itemIndex] = { element: element }; return that._measureElements(); }).then( function () { var entry = that._elementsToMeasure[itemIndex], size = { width: entry.width, height: entry.height }; delete that._elementsToMeasure[itemIndex]; return size; }, function (error) { delete that._elementsToMeasure[itemIndex]; return WinJS.Promise.wrapError(error); } ); }, _getGroupSize: function _LayoutCommon_getGroupSize(group) { var headerContainerMinSize = 0; if (this._groupsEnabled) { if (this._horizontal && this._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { headerContainerMinSize = this._sizes.headerContainerMinWidth; } else if (!this._horizontal && this._groupHeaderPosition === WinJS.UI.HeaderPosition.left) { headerContainerMinSize = this._sizes.headerContainerMinHeight; } } return Math.max(headerContainerMinSize, group.getItemsContainerSize() + this._getHeaderSizeGroupAdjustment()); }, // offset should be relative to the grid layout's content box _groupFromOffset: function _LayoutCommon_groupFromOffset(offset) { return offset < this._groups[0].offset ? 0 : this._groupFrom(function (group, groupIndex) { //#DBG _ASSERT(group.offset !== undefined); return offset < group.offset; }); }, _groupFromImpl: function _LayoutCommon_groupFromImpl(fromGroup, toGroup, comp) { if (toGroup < fromGroup) { return null; } var center = fromGroup + Math.floor((toGroup - fromGroup) / 2), centerGroup = this._groups[center]; if (comp(centerGroup, center)) { return this._groupFromImpl(fromGroup, center - 1, comp); } else if (center < toGroup && !comp(this._groups[center + 1], center + 1)) { return this._groupFromImpl(center + 1, toGroup, comp); } else { return center; } }, _groupFrom: function _LayoutCommon_groupFrom(comp) { //#DBG _ASSERT(this.assertValid()); if (this._groups.length > 0) { var lastGroupIndex = this._groups.length - 1, lastGroup = this._groups[lastGroupIndex]; if (!comp(lastGroup, lastGroupIndex)) { return lastGroupIndex; } else { return this._groupFromImpl(0, this._groups.length - 1, comp); } } else { return null; } }, _invalidateLayout: function _LayoutCommon_invalidateLayout() { if (this._site) { this._site.invalidateLayout(); } }, _resetMeasurements: function _LayoutCommon_resetMeasurements() { if (this._measuringPromise) { this._measuringPromise.cancel(); this._measuringPromise = null; } if (this._containerSizeClassName) { Utilities.removeClass(this._site.surface, this._containerSizeClassName); deleteDynamicCssRule(this._containerSizeClassName); this._containerSizeClassName = null; } this._sizes = null; this._resetAnimationCaches(); }, _measureElements: function _LayoutCommon_measureElements() { // batching measurements to minimalize number of layout passes if (!this._measuringElements) { var that = this; // Schedule a job so that: // 1. Calls to _measureElements are batched. // 2. that._measuringElements is set before the promise handler is executed // (that._measuringElements is used within the handler). that._measuringElements = Scheduler.schedulePromiseHigh(null, "WinJS.UI.GridLayout._measuringElements").then( function measure() { that._site._writeProfilerMark("_measureElements,StartTM"); var surface = that._createMeasuringSurface(), itemsContainer = document.createElement("div"), site = that._site, measuringElements = that._measuringElements, elementsToMeasure = that._elementsToMeasure, stopMeasuring = false; itemsContainer.className = WinJS.UI._itemsContainerClass + " " + WinJS.UI._laidOutClass; // This code is executed by CellSpanningGroups where styling is configured for –ms-grid. Let's satisfy these assumptions itemsContainer.style.cssText += ";display: -ms-grid" + ";-ms-grid-column: 1" + ";-ms-grid-row: 1"; var keys = Object.keys(elementsToMeasure), len, i; for (i = 0, len = keys.length; i < len; i++) { var element = elementsToMeasure[keys[i]].element; element.style["-ms-grid-column"] = i + 1; element.style["-ms-grid-row"] = i + 1; itemsContainer.appendChild(element); } surface.appendChild(itemsContainer); site.viewport.insertBefore(surface, site.viewport.firstChild); // Reading from the DOM may cause the app's resize handler to // be run synchronously which may invalidate this measuring // operation. When this happens, stop measuring. measuringElements.then(null, function () { stopMeasuring = true; }); for (i = 0, len = keys.length; i < len && !stopMeasuring; i++) { var entry = elementsToMeasure[keys[i]], item = entry.element.querySelector("." + WinJS.UI._itemClass); entry.width = Utilities.getTotalWidth(item); entry.height = Utilities.getTotalHeight(item); } if (surface.parentNode) { surface.parentNode.removeChild(surface); } if (measuringElements === that._measuringElements) { that._measuringElements = null; } site._writeProfilerMark("_measureElements,StopTM"); }, function (error) { that._measuringElements = null; return WinJS.Promise.wrapError(error); } ); } return this._measuringElements; }, _createMeasuringSurface: function _LayoutCommon_createMeasuringSurface() { var surface = document.createElement("div"); surface.style.cssText = "visibility: hidden" + ";-ms-grid-columns: auto" + ";-ms-grid-rows: auto"; surface.className = WinJS.UI._scrollableClass + " " + (this._inListMode ? WinJS.UI._listLayoutClass : WinJS.UI._gridLayoutClass); if (this._groupsEnabled) { if (this._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { Utilities.addClass(surface, WinJS.UI._headerPositionTopClass); } else { //#DBG _ASSERT(this._groupHeaderPosition === WinJS.UI.HeaderPosition.left); Utilities.addClass(surface, WinJS.UI._headerPositionLeftClass); } } return surface; }, // Assumes that the size of the item at the specified index is representative // of the size of all items, measures it, and stores the measurements in // this._sizes. If necessary, also: // - Creates a CSS rule to give the containers a height and width // - Stores the name associated with the rule in this._containerSizeClassName // - Adds the class name associated with the rule to the surface _measureItem: function _LayoutCommon_measureItem(index) { var that = this; var perfId = "Layout:measureItem"; var site = that._site; var measuringPromise = that._measuringPromise; // itemPromise is optional. It is provided when taking a second attempt at measuring. function measureItemImpl(index, itemPromise) { var secondTry = !!itemPromise, elementPromises = {}, itemPromise, left = site.rtl ? "right" : "left", right = site.rtl ? "left" : "right"; return site.itemCount.then(function (count) { if (!count || (that._groupsEnabled && !site.groupCount)) { return WinJS.Promise.cancel; } itemPromise = itemPromise || site.itemFromIndex(index); elementPromises.container = site.renderItem(itemPromise); if (that._groupsEnabled) { elementPromises.headerContainer = site.renderHeader(that._site.groupFromIndex(site.groupIndexFromItemIndex(index))); } return WinJS.Promise.join(elementPromises); }).then(function (elements) { // Reading from the DOM is tricky because each read may trigger a resize handler which // may invalidate this layout object. To make it easier to minimize bugs in this edge case: // 1. All DOM reads for _LayoutCommon_measureItem should be contained within this function. // 2. This function should remain as simple as possible. Stick to DOM reads, avoid putting // logic in here, and cache all needed instance variables at the top of the function. // // Returns null if the measuring operation was invalidated while reading from the DOM. // Otherwise, returns an object containing the measurements. function readMeasurementsFromDOM() { var horizontal = that._horizontal; var groupsEnabled = that._groupsEnabled; var stopMeasuring = false; // Reading from the DOM may cause the app's resize handler to // be run synchronously which may invalidate this measuring // operation. When this happens, stop measuring. measuringPromise.then(null, function () { stopMeasuring = true; }); var firstElementOnSurfaceMargins = WinJS.UI._getMargins(firstElementOnSurface); var firstElementOnSurfaceOffsetX = site.rtl ? (site.viewport.offsetWidth - (firstElementOnSurface.offsetLeft + firstElementOnSurface.offsetWidth)) : firstElementOnSurface.offsetLeft; var firstElementOnSurfaceOffsetY = firstElementOnSurface.offsetTop; var sizes = { // These will be set by _viewportSizeChanged viewportContentSize: 0, surfaceContentSize: 0, maxItemsContainerContentSize: 0, surfaceOuterHeight: getOuterHeight(surface), surfaceOuterWidth: getOuterWidth(surface), // Origin of the grid layout's content in viewport coordinates layoutOriginX: firstElementOnSurfaceOffsetX - firstElementOnSurfaceMargins[left], layoutOriginY: firstElementOnSurfaceOffsetY - firstElementOnSurfaceMargins.top, itemsContainerOuterHeight: getOuterHeight(itemsContainer), itemsContainerOuterWidth: getOuterWidth(itemsContainer), // Amount of space between the items container's margin and its content itemsContainerOuterX: getOuter(site.rtl ? "Right" : "Left", itemsContainer), itemsContainerOuterY: getOuter("Top", itemsContainer), itemBoxOuterHeight: getOuterHeight(itemBox), itemBoxOuterWidth: getOuterWidth(itemBox), containerOuterHeight: getOuterHeight(elements.container), containerOuterWidth: getOuterWidth(elements.container), emptyContainerContentHeight: Utilities.getContentHeight(emptyContainer), emptyContainerContentWidth: Utilities.getContentWidth(emptyContainer), containerMargins: WinJS.UI._getMargins(elements.container), // containerWidth/Height are computed when a uniform group is detected containerWidth: 0, containerHeight: 0, // true when both containerWidth and containerHeight have been measured containerSizeLoaded: false }; if (groupsEnabled) { // Amount of space between the header container's margin and its content sizes.headerContainerOuterX = getOuter(site.rtl ? "Right" : "Left", elements.headerContainer), sizes.headerContainerOuterY = getOuter("Top", elements.headerContainer), sizes.headerContainerOuterWidth = getOuterWidth(elements.headerContainer); sizes.headerContainerOuterHeight = getOuterHeight(elements.headerContainer); sizes.headerContainerWidth = Utilities.getTotalWidth(elements.headerContainer); sizes.headerContainerHeight = Utilities.getTotalHeight(elements.headerContainer); sizes.headerContainerMinWidth = getDimension(elements.headerContainer, "minWidth") + sizes.headerContainerOuterWidth; sizes.headerContainerMinHeight = getDimension(elements.headerContainer, "minHeight") + sizes.headerContainerOuterHeight; } var measurements = { // Measurements which are needed after measureItem has returned. sizes: sizes, // Measurements which are only needed within measureItem. viewportContentWidth: Utilities.getContentWidth(site.viewport), viewportContentHeight: Utilities.getContentHeight(site.viewport), containerContentWidth: Utilities.getContentWidth(elements.container), containerContentHeight: Utilities.getContentHeight(elements.container), containerWidth: Utilities.getTotalWidth(elements.container), containerHeight: Utilities.getTotalHeight(elements.container) }; measurements.viewportCrossSize = measurements[horizontal ? "viewportContentHeight" : "viewportContentWidth"]; site.readyToMeasure(); return stopMeasuring ? null : measurements; } function cleanUp() { if (surface.parentNode) { surface.parentNode.removeChild(surface); } } var surface = that._createMeasuringSurface(), itemsContainer = document.createElement("div"), emptyContainer = document.createElement("div"), itemBox = elements.container.querySelector("." + WinJS.UI._itemBoxClass), groupIndex = site.groupIndexFromItemIndex(index); emptyContainer.className = WinJS.UI._containerClass; itemsContainer.className = WinJS.UI._itemsContainerClass + " " + WinJS.UI._laidOutClass; // Use display=inline-block so that the width sizes to content when not in list mode. // When in grid mode, put items container and header container in different rows and columns so that the size of the items container does not affect the size of the header container and vice versa. // Use the same for list mode when headers are inline with item containers. // When headers are to the left of a vertical list, or above a horizontal list, put the rows/columns they would be in when laid out normally // into the CSS text for measuring. We have to do this because list item containers should take up 100% of the space left over in the surface // once the group's header is laid out. var itemsContainerRow = 1, itemsContainerColumn = 1, headerContainerRow = 2, headerContainerColumn = 2, firstElementOnSurface = itemsContainer; if (that._inListMode && that._groupsEnabled) { if (that._horizontal && that._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { itemsContainerRow = 2; headerContainerColumn = 1; headerContainerRow = 1; firstElementOnSurface = elements.headerContainer; } else if (!that._horizontal && that._groupHeaderPosition === WinJS.UI.HeaderPosition.left) { itemsContainerColumn = 2; headerContainerColumn = 1; headerContainerRow = 1; firstElementOnSurface = elements.headerContainer; } } // ListMode needs to use display block to proprerly measure items in vertical mode, and display flex to properly measure items in horizontal mode itemsContainer.style.cssText += ";display: " + (that._inListMode ? ((that._horizontal ? "flex" : "block") + "; overflow: hidden") : "inline-block") + ";-ms-grid-column: " + itemsContainerColumn + ";-ms-grid-row: " + itemsContainerRow; if (!that._inListMode) { elements.container.style.display = "inline-block"; } if (that._groupsEnabled) { elements.headerContainer.style.cssText += ";display: inline-block" + ";-ms-grid-column: " + headerContainerColumn + ";-ms-grid-row: " + headerContainerRow; WinJS.Utilities.addClass(elements.headerContainer, WinJS.UI._laidOutClass + " " + WinJS.UI._groupLeaderClass); if ((that._groupHeaderPosition === WinJS.UI.HeaderPosition.top && that._horizontal) || (that._groupHeaderPosition === WinJS.UI.HeaderPosition.left && !that._horizontal)) { WinJS.Utilities.addClass(itemsContainer, WinJS.UI._groupLeaderClass); } } itemsContainer.appendChild(elements.container); itemsContainer.appendChild(emptyContainer); surface.appendChild(itemsContainer); if (that._groupsEnabled) { surface.appendChild(elements.headerContainer); } site.viewport.insertBefore(surface, site.viewport.firstChild); var measurements = readMeasurementsFromDOM(); if (!measurements) { // While reading from the DOM, the measuring operation was invalidated. Bail out. cleanUp(); return WinJS.Promise.cancel; } else if ((that._horizontal && measurements.viewportContentHeight === 0) || (!that._horizontal && measurements.viewportContentWidth === 0)) { // ListView is invisible so we can't measure. Return a canceled promise. cleanUp(); return WinJS.Promise.cancel; } else if (!secondTry && !that._isCellSpanning(groupIndex) && (measurements.containerContentWidth === 0 || measurements.containerContentHeight === 0)) { // win-container has no size. For backwards compatibility, wait for the item promise and then try measuring again. cleanUp(); return itemPromise.then(function () { return measureItemImpl(index, itemPromise); }); } else { var sizes = that._sizes = measurements.sizes; // Wrappers for orientation-specific properties. // Sizes prefaced with "cross" refer to the sizes orthogonal to the current layout orientation. Sizes without a preface are in the orientation's direction. Object.defineProperties(sizes, { surfaceOuterCrossSize: { get: function () { return (that._horizontal ? sizes.surfaceOuterHeight : sizes.surfaceOuterWidth); }, enumerable: true }, layoutOrigin: { get: function () { return (that._horizontal ? sizes.layoutOriginX : sizes.layoutOriginY); }, enumerable: true }, itemsContainerOuterSize: { get: function () { return (that._horizontal ? sizes.itemsContainerOuterWidth : sizes.itemsContainerOuterHeight); }, enumerable: true }, itemsContainerOuterCrossSize: { get: function () { return (that._horizontal ? sizes.itemsContainerOuterHeight : sizes.itemsContainerOuterWidth); }, enumerable: true }, itemsContainerOuterStart: { get: function () { return (that._horizontal ? sizes.itemsContainerOuterX : sizes.itemsContainerOuterY); }, enumerable: true }, itemsContainerOuterCrossStart: { get: function () { return (that._horizontal ? sizes.itemsContainerOuterY : sizes.itemsContainerOuterX); }, enumerable: true }, containerCrossSize: { get: function () { return (that._horizontal ? sizes.containerHeight : sizes.containerWidth); }, enumerable: true }, containerSize: { get: function () { return (that._horizontal ? sizes.containerWidth : sizes.containerHeight); }, enumerable: true }, }); // If the measured group is uniform, measure the container height // and width now. Otherwise, compute them thru itemInfo on demand (via _ensureContainerSize). if (!that._isCellSpanning(groupIndex)) { if (that._inListMode) { var itemsContainerContentSize = measurements.viewportCrossSize - sizes.surfaceOuterCrossSize - that._getHeaderSizeContentAdjustment() - sizes.itemsContainerOuterCrossSize; if (that._horizontal) { sizes.containerHeight = itemsContainerContentSize; sizes.containerWidth = measurements.containerWidth; } else { sizes.containerHeight = measurements.containerHeight; sizes.containerWidth = itemsContainerContentSize; } } else { sizes.containerWidth = measurements.containerWidth; sizes.containerHeight = measurements.containerHeight; } sizes.containerSizeLoaded = true; } that._createContainerStyleRule(); that._viewportSizeChanged(measurements.viewportCrossSize); cleanUp(); } }); } if (!measuringPromise) { site._writeProfilerMark(perfId + ",StartTM"); // Use a signal to guarantee that measuringPromise is set before the promise // handler is executed (measuringPromise is referenced within measureItemImpl). var promiseStoredSignal = new WinJS._Signal(); that._measuringPromise = measuringPromise = promiseStoredSignal.promise.then(function () { return measureItemImpl(index); }).then(function () { site._writeProfilerMark(perfId + ":complete,info"); site._writeProfilerMark(perfId + ",StopTM"); }, function (error) { // The purpose of the measuring promise is so that we only // measure once. If measuring fails, clear the promise because // we still need to measure. that._measuringPromise = null; site._writeProfilerMark(perfId + ":canceled,info"); site._writeProfilerMark(perfId + ",StopTM"); return WinJS.Promise.wrapError(error); }); promiseStoredSignal.complete(); } return measuringPromise; }, _getHeaderSizeGroupAdjustment: function () { if (this._groupsEnabled) { if (this._horizontal && this._groupHeaderPosition === WinJS.UI.HeaderPosition.left) { return this._sizes.headerContainerWidth; } else if (!this._horizontal && this._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { return this._sizes.headerContainerHeight; } } return 0; }, _getHeaderSizeContentAdjustment: function () { if (this._groupsEnabled) { if (this._horizontal && this._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { return this._sizes.headerContainerHeight; } else if (!this._horizontal && this._groupHeaderPosition === WinJS.UI.HeaderPosition.left) { return this._sizes.headerContainerWidth; } } return 0; }, // Horizontal layouts lay items out top to bottom, left to right, whereas vertical layouts lay items out left to right, top to bottom. // The viewport size is the size layouts use to determine how many items can be placed in one bar, so it should be cross to the // orientation. _getViewportCrossSize: function () { return this._site.viewportSize[this._horizontal ? "height" : "width"]; }, // viewportContentSize is the new viewport size _viewportSizeChanged: function _LayoutCommon_viewportSizeChanged(viewportContentSize) { var sizes = this._sizes; sizes.viewportContentSize = viewportContentSize; sizes.surfaceContentSize = viewportContentSize - sizes.surfaceOuterCrossSize; sizes.maxItemsContainerContentSize = sizes.surfaceContentSize - sizes.itemsContainerOuterCrossSize - this._getHeaderSizeContentAdjustment(); // This calculation is for uniform layouts if (sizes.containerSizeLoaded && !this._inListMode) { this._itemsPerBar = Math.floor(sizes.maxItemsContainerContentSize / sizes.containerCrossSize); if (this.maximumRowsOrColumns) { this._itemsPerBar = Math.min(this._itemsPerBar, this.maximumRowsOrColumns); } this._itemsPerBar = Math.max(1, this._itemsPerBar); } else { if (this._inListMode) { sizes[this._horizontal ? "containerHeight" : "containerWidth"] = sizes.maxItemsContainerContentSize; } this._itemsPerBar = 1; } // Ignore animations if height changed this._resetAnimationCaches(); }, _createContainerStyleRule: function _LayoutCommon_createContainerStyleRule() { // Adding CSS rules is expensive. Add a rule to provide a // height and width for containers if the app hasn't provided one. var sizes = this._sizes; if (!this._containerSizeClassName && sizes.containerSizeLoaded && (sizes.emptyContainerContentHeight === 0 || sizes.emptyContainerContentWidth === 0)) { var width = sizes.containerWidth - sizes.containerOuterWidth + "px", height = sizes.containerHeight - sizes.containerOuterHeight + "px"; if (this._inListMode) { if (this._horizontal) { height = "calc(100% - " + (sizes.containerMargins.top + sizes.containerMargins.bottom) + "px)"; } else { width = "auto"; } } if (!this._containerSizeClassName) { this._containerSizeClassName = uniqueCssClassName("containersize"); Utilities.addClass(this._site.surface, this._containerSizeClassName); } var ruleSelector = "." + WinJS.UI._containerClass, ruleBody = "width:" + width + ";height:" + height + ";"; addDynamicCssRule(this._containerSizeClassName, this._site, ruleSelector, ruleBody); } }, // Computes container width and height if they haven't been computed yet. This // should happen when the first uniform group is created. _ensureContainerSize: function _LayoutCommon_ensureContainerSize(group) { var sizes = this._sizes; if (!sizes.containerSizeLoaded && !this._ensuringContainerSize) { var promise; if ((!this._itemInfo || typeof this._itemInfo !== "function") && this._useDefaultItemInfo) { var margins = sizes.containerMargins; promise = WinJS.Promise.wrap({ width: group.groupInfo.cellWidth - margins.left - margins.right, height: group.groupInfo.cellHeight - margins.top - margins.bottom }); } else { promise = this._getItemInfo(); } var that = this; this._ensuringContainerSize = promise.then(function (itemSize) { sizes.containerSizeLoaded = true; sizes.containerWidth = itemSize.width + sizes.itemBoxOuterWidth + sizes.containerOuterWidth; sizes.containerHeight = itemSize.height + sizes.itemBoxOuterHeight + sizes.containerOuterHeight; if (!that._inListMode) { that._itemsPerBar = Math.floor(sizes.maxItemsContainerContentSize / sizes.containerCrossSize); if (that.maximumRowsOrColumns) { that._itemsPerBar = Math.min(that._itemsPerBar, that.maximumRowsOrColumns); } that._itemsPerBar = Math.max(1, that._itemsPerBar); } else { that._itemsPerBar = 1; } that._createContainerStyleRule(); }); promise.done( function () { that._ensuringContainerSize = null; }, function () { that._ensuringContainerSize = null; } ); return promise; } else { return this._ensuringContainerSize ? this._ensuringContainerSize : WinJS.Promise.wrap(); } }, _indexToCoordinate: function _LayoutCommon_indexToCoordinate(index, itemsPerBar) { itemsPerBar = itemsPerBar || this._itemsPerBar; var bar = Math.floor(index / itemsPerBar); if (this._horizontal) { return { column: bar, row: index - bar * itemsPerBar }; } else { return { row: bar, column: index - bar * itemsPerBar }; } }, // Empty ranges are represented by null. Non-empty ranges are represented by // an object with 2 properties: firstIndex and lastIndex. _rangeForGroup: function _LayoutCommon_rangeForGroup(group, range) { var first = group.startIndex, last = first + group.count - 1; if (!range || range.firstIndex > last || range.lastIndex < first) { // There isn't any overlap between range and the group's indices return null; } else { return { firstIndex: Math.max(0, range.firstIndex - first), lastIndex: Math.min(group.count - 1, range.lastIndex - first) }; } }, _syncDomWithGroupHeaderPosition: function _LayoutCommon_syncDomWithGroupHeaderPosition(tree) { if (this._groupsEnabled && this._oldGroupHeaderPosition !== this._groupHeaderPosition) { // this._oldGroupHeaderPosition may refer to top, left, or null. It will be null // the first time this function is called which means that no styles have to be // removed. var len = tree.length, i; // Remove styles associated with old group header position if (this._oldGroupHeaderPosition === WinJS.UI.HeaderPosition.top) { Utilities.removeClass(this._site.surface, WinJS.UI._headerPositionTopClass); // maxWidth must be cleared because it is used with headers in the top position but not the left position. // The _groupLeaderClass must be removed from the itemsContainer element because the associated styles // should only be applied to it when headers are in the top position. if (this._horizontal) { for (i = 0; i < len; i++) { tree[i].header.style.maxWidth = ""; WinJS.Utilities.removeClass(tree[i].itemsContainer.element, WinJS.UI._groupLeaderClass); } } else { this._site.surface.style.msGridRows = ""; } } else if (this._oldGroupHeaderPosition === WinJS.UI.HeaderPosition.left) { Utilities.removeClass(this._site.surface, WinJS.UI._headerPositionLeftClass); // msGridColumns is cleared for a similar reason as maxWidth if (!this._horizontal) { for (i = 0; i < len; i++) { tree[i].header.style.maxHeight = ""; WinJS.Utilities.removeClass(tree[i].itemsContainer.element, WinJS.UI._groupLeaderClass); } } this._site.surface.style.msGridColumns = ""; } // Add styles associated with new group header position if (this._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { Utilities.addClass(this._site.surface, WinJS.UI._headerPositionTopClass); if (this._horizontal) { for (i = 0; i < len; i++) { WinJS.Utilities.addClass(tree[i].itemsContainer.element, WinJS.UI._groupLeaderClass); } } } else { //#DBG _ASSERT(this._groupHeaderPosition === WinJS.UI.HeaderPosition.left); Utilities.addClass(this._site.surface, WinJS.UI._headerPositionLeftClass); if (!this._horizontal) { for (i = 0; i < len; i++) { WinJS.Utilities.addClass(tree[i].itemsContainer.element, WinJS.UI._groupLeaderClass); } } } this._oldGroupHeaderPosition = this._groupHeaderPosition; } }, _layoutGroup: function _LayoutCommon_layoutGroup(index) { var group = this._groups[index], groupBundle = this._site.tree[index], headerContainer = groupBundle.header, itemsContainer = groupBundle.itemsContainer.element, sizes = this._sizes; if (this._groupsEnabled) { if (this._horizontal) { if (this._groupHeaderPosition === WinJS.UI.HeaderPosition.top) { var headerContainerMinContentWidth = sizes.headerContainerMinWidth - sizes.headerContainerOuterWidth, itemsContainerContentWidth = group.getItemsContainerSize() - sizes.headerContainerOuterWidth; headerContainer.style.msGridColumn = index + 1; headerContainer.style.maxWidth = Math.max(headerContainerMinContentWidth, itemsContainerContentWidth) + "px"; itemsContainer.style.msGridColumn = index + 1; // itemsContainers only get the _groupLeaderClass when header position is top. Utilities.addClass(itemsContainer, WinJS.UI._groupLeaderClass); } else { //#DBG _ASSERT(this._groupHeaderPosition === WinJS.UI.HeaderPosition.left); headerContainer.style.msGridColumn = index * 2 + 1; itemsContainer.style.msGridColumn = index * 2 + 2; } } else { if (this._groupHeaderPosition === WinJS.UI.HeaderPosition.left) { var headerContainerMinContentHeight = sizes.headerContainerMinHeight - sizes.headerContainerOuterHeight, itemsContainerContentHeight = group.getItemsContainerSize() - sizes.headerContainerOuterHeight; headerContainer.style.msGridRow = index + 1; headerContainer.style.maxHeight = Math.max(headerContainerMinContentHeight, itemsContainerContentHeight) + "px"; itemsContainer.style.msGridRow = index + 1; // itemsContainers only get the _groupLeaderClass when header position is left. Utilities.addClass(itemsContainer, WinJS.UI._groupLeaderClass); } else { //#DBG _ASSERT(this._groupHeaderPosition === WinJS.UI.HeaderPosition.top); headerContainer.style.msGridRow = index * 2 + 1; // It's important to explicitly set the container height in vertical list mode with headers above, since we use flow layout. // When the header's content is taken from the DOM, the headerContainer will shrink unless it has a height set. if (this._inListMode) { headerContainer.style.height = (sizes.headerContainerHeight - sizes.headerContainerOuterHeight) + "px"; } itemsContainer.style.msGridRow = index * 2 + 2; } } // Header containers always get the _groupLeaderClass. Utilities.addClass(headerContainer, WinJS.UI._laidOutClass + " " + WinJS.UI._groupLeaderClass); } Utilities.addClass(itemsContainer, WinJS.UI._laidOutClass); } }, { // The maximum number of rows or columns of win-containers to put into each items block. // A row/column cannot be split across multiple items blocks. win-containers // are grouped into items blocks in order to mitigate the costs of the platform doing // a layout in response to insertions and removals of win-containers. _barsPerItemsBlock: 4 }); }), // // Layouts // _LegacyLayout: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(WinJS.UI._LayoutCommon, null, { /// /// Gets or sets a value that indicates whether the layout should disable the backdrop feature /// which avoids blank areas while panning in a virtualized list. /// /// disableBackdrop is deprecated. Style: .win-listview .win-container.win-backdrop { background-color:transparent; } instead. /// /// disableBackdrop: { get: function _LegacyLayout_disableBackdrop_get() { return this._backdropDisabled || false; }, set: function _LegacyLayout_disableBackdrop_set(value) { Utilities._deprecated(WinJS.UI._strings.disableBackdropIsDeprecated); value = !!value; if (this._backdropDisabled !== value) { this._backdropDisabled = value; if (this._disableBackdropClassName) { deleteDynamicCssRule(this._disableBackdropClassName); this._site && Utilities.removeClass(this._site.surface, this._disableBackdropClassName); this._disableBackdropClassName = null; } this._disableBackdropClassName = uniqueCssClassName("disablebackdrop"); this._site && Utilities.addClass(this._site.surface, this._disableBackdropClassName); if (value) { var ruleSelector = ".win-container.win-backdrop", ruleBody = "background-color:transparent;"; addDynamicCssRule(this._disableBackdropClassName, this._site, ruleSelector, ruleBody); } } } }, /// /// Gets or sets the fill color for the default pattern used for the backdrops. /// The default value is "rgba(155,155,155,0.23)". /// /// backdropColor is deprecated. Style: .win-listview .win-container.win-backdrop { rgba(155,155,155,0.23); } instead. /// /// backdropColor: { get: function _LegacyLayout_backdropColor_get() { return this._backdropColor || "rgba(155,155,155,0.23)"; }, set: function _LegacyLayout_backdropColor_set(value) { Utilities._deprecated(WinJS.UI._strings.backdropColorIsDeprecated); if (value && this._backdropColor !== value) { this._backdropColor = value; if (this._backdropColorClassName) { deleteDynamicCssRule(this._backdropColorClassName); this._site && Utilities.removeClass(this._site.surface, this._backdropColorClassName); this._backdropColorClassName = null; } this._backdropColorClassName = uniqueCssClassName("backdropcolor"); this._site && Utilities.addClass(this._site.surface, this._backdropColorClassName); var ruleSelector = ".win-container.win-backdrop", ruleBody = "background-color:" + value + ";"; addDynamicCssRule(this._backdropColorClassName, this._site, ruleSelector, ruleBody); } } } }); }), GridLayout: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(WinJS.UI._LegacyLayout, function (options) { /// /// /// Creates a new GridLayout. /// /// /// An object that contains one or more property/value pairs to apply to the new control. Each property of the options /// object corresponds to one of the control's properties or events. /// /// /// The new GridLayout. /// /// options = options || {}; // Executing setters to display compatibility warning this.itemInfo = options.itemInfo; this.groupInfo = options.groupInfo; this._maxRowsOrColumns = 0; this._useDefaultItemInfo = true; this._elementsToMeasure = {}; this._groupHeaderPosition = options.groupHeaderPosition || WinJS.UI.HeaderPosition.top; this.orientation = options.orientation || "horizontal"; if (options.maxRows) { this.maxRows = +options.maxRows; } if (options.maximumRowsOrColumns) { this.maximumRowsOrColumns = +options.maximumRowsOrColumns; } }, { // Public /// /// Gets the maximum number of rows or columns, depending on the orientation, that should present before it introduces wrapping to the layout. /// A value of 0 indicates that there is no maximum. The default value is 0. /// maximumRowsOrColumns: { get: function () { return this._maxRowsOrColumns; }, set: function (value) { this._setMaxRowsOrColumns(value); } }, /// /// Gets or sets the maximum number of rows displayed by the ListView. /// /// WinJS.UI.GridLayout.maxRows may be altered or unavailable after the Windows Library for JavaScript 2.0. Instead, use the maximumRowsOrColumns property. /// /// maxRows: { get: function () { return this.maximumRowsOrColumns; }, set: function (maxRows) { Utilities._deprecated(WinJS.UI._strings.maxRowsIsDeprecated); this.maximumRowsOrColumns = maxRows; } }, /// /// Determines the size of the item and whether /// the item should be placed in a new column. /// /// GridLayout.itemInfo may be altered or unavailable in future versions. Instead, use CellSpanningLayout. /// /// itemInfo: { enumerable: true, get: function () { return this._itemInfo; }, set: function (itemInfo) { itemInfo && Utilities._deprecated(WinJS.UI._strings.itemInfoIsDeprecated); this._itemInfo = itemInfo; this._invalidateLayout(); } }, /// /// Indicates whether a group has cell spanning items and specifies the dimensions of the cell. /// /// GridLayout.groupInfo may be altered or unavailable in future versions. Instead, use CellSpanningLayout. /// /// groupInfo: { enumerable: true, get: function () { return this._groupInfo; }, set: function (groupInfo) { groupInfo && Utilities._deprecated(WinJS.UI._strings.groupInfoIsDeprecated); this._groupInfo = groupInfo; this._invalidateLayout(); } } }); }) }); var Groups = WinJS.Namespace.defineWithParent(null, null, { UniformGroupBase: WinJS.Namespace._lazy(function () { return WinJS.Class.define(null, { cleanUp: function UniformGroupBase_cleanUp() { }, itemFromOffset: function UniformGroupBase_itemFromOffset(offset, options) { // supported options are: // - wholeItem: when set to true the fully visible item is returned // - last: if 1 the last item is returned. if 0 the first options = options || {}; var sizes = this._layout._sizes; // Make offset relative to the items container's content box offset -= sizes.itemsContainerOuterStart; if (options.wholeItem) { offset += (options.last ? -1 : 1) * (sizes.containerSize - 1); } var lastIndexOfGroup = this.count - 1, lastBar = Math.floor(lastIndexOfGroup / this._layout._itemsPerBar), bar = clampToRange(0, lastBar, Math.floor(offset / sizes.containerSize)), index = (bar + options.last) * this._layout._itemsPerBar - options.last; return clampToRange(0, this.count - 1, index); }, hitTest: function UniformGroupBase_hitTest(x, y) { var horizontal = this._layout._horizontal, itemsPerBar = this._layout._itemsPerBar, useListSemantics = this._layout._inListMode || itemsPerBar === 1, directionalLocation = horizontal ? x : y, crossLocation = horizontal ? y : x, sizes = this._layout._sizes; directionalLocation -= sizes.itemsContainerOuterStart; crossLocation -= sizes.itemsContainerOuterCrossStart; var bar = Math.floor(directionalLocation / sizes.containerSize); var slotInBar = clampToRange(0, itemsPerBar - 1, Math.floor(crossLocation / sizes.containerCrossSize)); var index = Math.max(-1, bar * itemsPerBar + slotInBar); // insertAfterIndex is determined by which half of the target element the mouse cursor is currently in. // The trouble is that we can cut the element in half horizontally or cut it in half vertically. // Which one we choose depends on the order that elements are laid out in the grid. // A horizontal grid with multiple rows per column will lay items out starting from top to bottom, and move left to right. // A vertical list is just a horizontal grid with an infinite number of rows per column, so it follows the same order. // In both of these cases, each item is cut in half horizontally, since for any item n, n-1 should be above it and n+1 below (ignoring column changes). // A vertical grid lays items out left to right, top to bottom, and a horizontal list left to right (with infinite items per row). // In this case for item n, n-1 is on the left and n+1 on the right, so we cut the item in half vertically. var insertAfterSlot; if ((!horizontal && useListSemantics) || (horizontal && !useListSemantics)) { insertAfterSlot = (y - sizes.containerHeight / 2) / sizes.containerHeight; } else { insertAfterSlot = (x - sizes.containerWidth / 2) / sizes.containerWidth; } if (useListSemantics) { insertAfterSlot = Math.floor(insertAfterSlot); return { index: index, insertAfterIndex: (insertAfterSlot >= 0 && index >= 0 ? insertAfterSlot : -1) }; } insertAfterSlot = clampToRange(-1, itemsPerBar - 1, insertAfterSlot); var insertAfterIndex; if (insertAfterSlot < 0) { insertAfterIndex = bar * itemsPerBar - 1; } else { insertAfterIndex = bar * itemsPerBar + Math.floor(insertAfterSlot); } return { index: clampToRange(-1, this.count - 1, index), insertAfterIndex: clampToRange(-1, this.count - 1, insertAfterIndex) }; }, getAdjacent: function UniformGroupBase_getAdjacent(currentItem, pressedKey) { var index = currentItem.index, currentBar = Math.floor(index / this._layout._itemsPerBar), currentSlot = index % this._layout._itemsPerBar, newFocus; switch (pressedKey) { case Key.upArrow: newFocus = (currentSlot === 0 ? "boundary" : index - 1); break; case Key.downArrow: var isLastIndexOfGroup = (index === this.count - 1), inLastSlot = (this._layout._itemsPerBar > 1 && currentSlot === this._layout._itemsPerBar - 1); newFocus = (isLastIndexOfGroup || inLastSlot ? "boundary" : index + 1); break; case Key.leftArrow: newFocus = (currentBar === 0 && this._layout._itemsPerBar > 1 ? "boundary" : index - this._layout._itemsPerBar); break; case Key.rightArrow: var lastIndexOfGroup = this.count - 1, lastBar = Math.floor(lastIndexOfGroup / this._layout._itemsPerBar); newFocus = (currentBar === lastBar ? "boundary" : Math.min(index + this._layout._itemsPerBar, this.count - 1)); break; } return (newFocus === "boundary" ? newFocus : { type: WinJS.UI.ObjectType.item, index: newFocus }); }, getItemsContainerSize: function UniformGroupBase_getItemsContainerSize() { var sizes = this._layout._sizes, barCount = Math.ceil(this.count / this._layout._itemsPerBar); return barCount * sizes.containerSize + sizes.itemsContainerOuterSize; }, getItemPositionForAnimations: function UniformGroupBase_getItemPositionForAnimations(itemIndex) { // Top/Left are used to know if the item has moved and also used to position the item if removed. // Row/Column are used to know if a reflow animation should occur // Height/Width are used when positioning a removed item without impacting layout. // The returned rectangle refers to the win-container's border/padding/content box. Coordinates // are relative to group's items container. var sizes = this._layout._sizes; var leftStr = this._layout._site.rtl ? "right" : "left"; var containerMargins = this._layout._sizes.containerMargins; var coordinates = this._layout._indexToCoordinate(itemIndex); var itemPosition = { row: coordinates.row, column: coordinates.column, top: containerMargins.top + coordinates.row * sizes.containerHeight, left: containerMargins[leftStr] + coordinates.column * sizes.containerWidth, height: sizes.containerHeight - sizes.containerMargins.top - sizes.containerMargins.bottom, width: sizes.containerWidth - sizes.containerMargins.left - sizes.containerMargins.right }; return itemPosition; } }); }), // // Groups for GridLayout // // Each group implements a 3 function layout interface. The interface is used // whenever GridLayout has to do a layout. The interface consists of: // - prepareLayout/prepareLayoutWithCopyOfTree: Called 1st. Group should update all of its internal // layout state. It should not modify the DOM. Group should implement either prepareLayout or // prepareLayoutWithCopyOfTree. The former is preferable because the latter is expensive as calling // it requires copying the group's tree. Implementing prepareLayoutWithCopyOfTree is necessary when // the group is manually laying out items and is laying out unrealized items asynchronously // (e.g. CellSpanningGroup). This requires a copy of the tree from the previous layout pass. // - layoutRealizedRange: Called 2nd. Group should update the DOM so that // the realized range reflects the internal layout state computed during // prepareLayout. // - layoutUnrealizedRange: Called 3rd. Group should update the DOM for the items // outside of the realized range. This function returns a promise so // it can do its work asynchronously. When the promise completes, layout will // be done. // // The motivation for this interface is perceived performance. If groups had just 1 // layout function, all items would have to be laid out before any animations could // begin. With this interface, animations can begin playing after // layoutRealizedRange is called. // // Each group also implements a cleanUp function which is called when the group is // no longer needed so that it can clean up the DOM and its resources. After cleanUp // is called, the group object cannnot be reused. // UniformGroup: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(Groups.UniformGroupBase, function UniformGroup_ctor(layout, itemsContainer) { this._layout = layout; this._itemsContainer = itemsContainer; Utilities.addClass(this._itemsContainer, layout._inListMode ? WinJS.UI._uniformListLayoutClass : WinJS.UI._uniformGridLayoutClass); }, { cleanUp: function UniformGroup_cleanUp(skipDomCleanUp) { if (!skipDomCleanUp) { Utilities.removeClass(this._itemsContainer, WinJS.UI._uniformGridLayoutClass); Utilities.removeClass(this._itemsContainer, WinJS.UI._uniformListLayoutClass); this._itemsContainer.style.height = this._itemsContainer.style.width = ""; } this._itemsContainer = null; this._layout = null; this.groupInfo = null; this.startIndex = null; this.offset = null; this.count = null; }, prepareLayout: function UniformGroup_prepareLayout(itemsCount, oldChangedRealizedRange, oldState, updatedProperties) { this.groupInfo = updatedProperties.groupInfo; this.startIndex = updatedProperties.startIndex; this.count = itemsCount; return this._layout._ensureContainerSize(this); }, layoutRealizedRange: function UniformGroup_layoutRealizedRange(changedRange, realizedRange) { // Explicitly set the items container size. This is required so that the // surface, which is a grid, will have its width sized to content. var sizes = this._layout._sizes; this._itemsContainer.style[this._layout._horizontal ? "width" : "height"] = this.getItemsContainerSize() - sizes.itemsContainerOuterSize + "px"; this._itemsContainer.style[this._layout._horizontal ? "height" : "width"] = (this._layout._inListMode ? sizes.maxItemsContainerContentSize + "px" : this._layout._itemsPerBar * sizes.containerCrossSize + "px"); }, layoutUnrealizedRange: function UniformGroup_layoutUnrealizedRange(changedRange, realizedRange, beforeRealizedRange) { return WinJS.Promise.wrap(); } }); }), UniformFlowGroup: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(Groups.UniformGroupBase, function UniformFlowGroup_ctor(layout, tree) { this._layout = layout; this._itemsContainer = tree.element; Utilities.addClass(this._itemsContainer, layout._inListMode ? WinJS.UI._uniformListLayoutClass : WinJS.UI._uniformGridLayoutClass); }, { cleanUp: function UniformFlowGroup_cleanUp(skipDomCleanUp) { if (!skipDomCleanUp) { Utilities.removeClass(this._itemsContainer, WinJS.UI._uniformListLayoutClass); Utilities.removeClass(this._itemsContainer, WinJS.UI._uniformGridLayoutClass); this._itemsContainer.style.height = ""; } }, layout: function UniformFlowGroup_layout() { this._layout._site._writeProfilerMark("Layout:_UniformFlowGroup:setItemsContainerHeight,info"); this._itemsContainer.style.height = this.count * this._layout._sizes.containerHeight + "px"; } }) }), CellSpanningGroup: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function CellSpanningGroup_ctor(layout, itemsContainer) { this._layout = layout; this._itemsContainer = itemsContainer; Utilities.addClass(this._itemsContainer, WinJS.UI._cellSpanningGridLayoutClass); this.resetMap(); }, { cleanUp: function CellSpanningGroup_cleanUp(skipDomCleanUp) { if (!skipDomCleanUp) { this._cleanContainers(); Utilities.removeClass(this._itemsContainer, WinJS.UI._cellSpanningGridLayoutClass); this._itemsContainer.style.cssText = ""; } this._itemsContainer = null; if (this._layoutPromise) { this._layoutPromise.cancel(); this._layoutPromise = null; } this.resetMap(); this._slotsPerColumn = null; this._offScreenSlotsPerColumn = null; this._items = null; this._layout = null; this._containersToHide = null; this.groupInfo = null; this.startIndex = null; this.offset = null; this.count = null; }, prepareLayoutWithCopyOfTree: function CellSpanningGroup_prepareLayoutWithCopyOfTree(tree, oldChangedRealizedRange, oldState, updatedProperties) { var that = this; var i; // Remember the items in the old realized item range that changed. // During layoutRealizedRange, they either need to be relaid out or hidden. this._containersToHide = {}; if (oldChangedRealizedRange) { for (i = oldChangedRealizedRange.firstIndex; i <= oldChangedRealizedRange.lastIndex; i++) { this._containersToHide[oldState._items[i].uniqueID] = oldState._items[i]; } } // Update public properties this.groupInfo = updatedProperties.groupInfo; this.startIndex = updatedProperties.startIndex; this.count = tree.items.length; this._items = tree.items; this._slotsPerColumn = Math.floor(this._layout._sizes.maxItemsContainerContentSize / this.groupInfo.cellHeight); if (this._layout.maximumRowsOrColumns) { this._slotsPerColumn = Math.min(this._slotsPerColumn, this._layout.maximumRowsOrColumns); } this._slotsPerColumn = Math.max(this._slotsPerColumn, 1); this.resetMap(); var itemInfoPromises = new Array(this.count); for (i = 0; i < this.count; i++) { itemInfoPromises[i] = this._layout._getItemInfo(this.startIndex + i); } return WinJS.Promise.join(itemInfoPromises).then(function (itemInfos) { itemInfos.forEach(function (itemInfo, index) { that.addItemToMap(index, itemInfo); }); }); }, layoutRealizedRange: function CellSpanningGroup_layoutRealizedRange(firstChangedIndex, realizedRange) { // Lay out the changed items within the realized range if (realizedRange) { var firstChangedRealizedIndex = Math.max(firstChangedIndex, realizedRange.firstIndex), i; for (i = firstChangedRealizedIndex; i <= realizedRange.lastIndex; i++) { this._layoutItem(i); delete this._containersToHide[this._items[i].uniqueID]; } } // Hide the old containers that are in the realized range but weren't relaid out Object.keys(this._containersToHide).forEach(function (id) { WinJS.Utilities.removeClass(this._containersToHide[id], WinJS.UI._laidOutClass); }.bind(this)); this._containersToHide = {}; // Explicitly set the items container height. This is required so that the // surface, which is a grid, will have its width sized to content. this._itemsContainer.style.cssText += ";width:" + (this.getItemsContainerSize() - this._layout._sizes.itemsContainerOuterSize) + "px;height:" + this._layout._sizes.maxItemsContainerContentSize + "px;-ms-grid-columns: (" + this.groupInfo.cellWidth + "px)[" + this.getColumnCount() + "];-ms-grid-rows: (" + this.groupInfo.cellHeight + "px)[" + (this._slotsPerColumn + this._offScreenSlotsPerColumn) + "]"; }, layoutUnrealizedRange: function CellSpanningGroup_layoutUnrealizedRange(firstChangedIndex, realizedRange, beforeRealizedRange) { var that = this; var layoutJob; that._layoutPromise = new WinJS.Promise(function (complete) { function completeLayout() { layoutJob = null; complete(); } function schedule(fn) { return Scheduler.schedule(fn, Scheduler.Priority.normal, null, "WinJS.UI.GridLayout.CellSpanningGroup.LayoutUnrealizedRange"); } // These loops are built to lay out the items that are closest to // the realized range first. if (realizedRange) { var stop = false; // For laying out the changed items that are before the realized range var before = realizedRange.firstIndex - 1; // For laying out the changed items that are after the realized range var after = Math.max(firstChangedIndex, realizedRange.lastIndex + 1); after = Math.max(before + 1, after); // Alternate between laying out items before and after the realized range layoutJob = schedule(function unrealizedRangeWork(info) { while (!stop) { if (info.shouldYield) { info.setWork(unrealizedRangeWork); return; } stop = true; if (before >= firstChangedIndex) { that._layoutItem(before); before--; stop = false; } if (after < that.count) { that._layoutItem(after); after++; stop = false; } } completeLayout(); }); } else if (beforeRealizedRange) { // The items we are laying out come before the realized range. // so lay them out in descending order. var i = that.count - 1; layoutJob = schedule(function beforeRealizedRangeWork(info) { for (; i >= firstChangedIndex; i--) { if (info.shouldYield) { info.setWork(beforeRealizedRangeWork); return; } that._layoutItem(i); } completeLayout(); }); } else { // The items we are laying out come after the realized range // so lay them out in ascending order. var i = firstChangedIndex; layoutJob = schedule(function afterRealizedRangeWork(info) { for (; i < that.count; i++) { if (info.shouldYield) { info.setWork(afterRealizedRangeWork); return; } that._layoutItem(i); } completeLayout(); }); } }, function () { // Cancellation handler for that._layoutPromise layoutJob && layoutJob.cancel(); layoutJob = null; }); return that._layoutPromise; }, itemFromOffset: function CellSpanningGroup_itemFromOffset(offset, options) { // supported options are: // - wholeItem: when set to true the fully visible item is returned // - last: if 1 the last item is returned. if 0 the first options = options || {}; var sizes = this._layout._sizes, margins = sizes.containerMargins; // Make offset relative to the items container's content box offset -= sizes.itemsContainerOuterX; offset -= ((options.last ? 1 : -1) * margins[options.last ? "left" : "right"]); var value = this.indexFromOffset(offset, options.wholeItem, options.last).item; return clampToRange(0, this.count - 1, value); }, getAdjacent: function CellSpanningGroup_getAdjacent(currentItem, pressedKey) { var index, originalIndex; index = originalIndex = currentItem.index; var newIndex, inMap, inMapIndex; if (this.lastAdjacent === index) { inMapIndex = this.lastInMapIndex; } else { inMapIndex = this.findItem(index); } do { var column = Math.floor(inMapIndex / this._slotsPerColumn), row = inMapIndex - column * this._slotsPerColumn, lastColumn = Math.floor((this.occupancyMap.length - 1) / this._slotsPerColumn), entry, c; switch (pressedKey) { case Key.upArrow: if (row > 0) { inMapIndex--; } else { return { type: WinJS.UI.ObjectType.item, index: originalIndex }; } break; case Key.downArrow: if (row + 1 < this._slotsPerColumn) { inMapIndex++; } else { return { type: WinJS.UI.ObjectType.item, index: originalIndex }; } break; case Key.leftArrow: inMapIndex = (column > 0 ? inMapIndex - this._slotsPerColumn : -1); break; case Key.rightArrow: inMapIndex = (column < lastColumn ? inMapIndex + this._slotsPerColumn : this.occupancyMap.length); break; } inMap = inMapIndex >= 0 && inMapIndex < this.occupancyMap.length; if (inMap) { newIndex = this.occupancyMap[inMapIndex] ? this.occupancyMap[inMapIndex].index : undefined; } } while (inMap && (index === newIndex || newIndex === undefined)); this.lastAdjacent = newIndex; this.lastInMapIndex = inMapIndex; return (inMap ? { type: WinJS.UI.ObjectType.item, index: newIndex } : "boundary"); }, hitTest: function CellSpanningGroup_hitTest(x, y) { var sizes = this._layout._sizes, itemIndex = 0; // Make the coordinates relative to the items container's content box x -= sizes.itemsContainerOuterX; y -= sizes.itemsContainerOuterY; if (this.occupancyMap.length > 0) { var result = this.indexFromOffset(x, false, 0); var counter = Math.min(this._slotsPerColumn - 1, Math.floor(y / this.groupInfo.cellHeight)), curr = result.index, lastValidIndex = curr; while (counter-- > 0) { curr++; if (this.occupancyMap[curr]) { lastValidIndex = curr; } } if (!this.occupancyMap[lastValidIndex]) { lastValidIndex--; } itemIndex = this.occupancyMap[lastValidIndex].index; } var itemSize = this.getItemSize(itemIndex), itemLeft = itemSize.column * this.groupInfo.cellWidth, itemTop = itemSize.row * this.groupInfo.cellHeight, useListSemantics = this._slotsPerColumn === 1, insertAfterIndex = itemIndex; if ((useListSemantics && (x < (itemLeft + itemSize.contentWidth / 2))) || (!useListSemantics && (y < (itemTop + itemSize.contentHeight / 2)))) { insertAfterIndex--; } return { type: WinJS.UI.ObjectType.item, index: clampToRange(0, this.count - 1, itemIndex), insertAfterIndex: clampToRange(-1, this.count - 1, insertAfterIndex) }; }, getItemsContainerSize: function CellSpanningGroup_getItemsContainerSize() { var sizes = this._layout._sizes; return this.getColumnCount() * this.groupInfo.cellWidth + sizes.itemsContainerOuterSize; }, getItemPositionForAnimations: function CellSpanningGroup_getItemPositionForAnimations(itemIndex) { // Top/Left are used to know if the item has moved and also used to position the item if removed. // Row/Column are used to know if a reflow animation should occur // Height/Width are used when positioning a removed item without impacting layout. // The returned rectangle refers to the win-container's border/padding/content box. Coordinates // are relative to group's items container. var sizes = this._layout._sizes; var leftStr = this._layout._site.rtl ? "right" : "left"; var containerMargins = this._layout._sizes.containerMargins; var coordinates = this.getItemSize(itemIndex); var groupInfo = this.groupInfo; var itemPosition = { row: coordinates.row, column: coordinates.column, top: containerMargins.top + coordinates.row * groupInfo.cellHeight, left: containerMargins[leftStr] + coordinates.column * groupInfo.cellWidth, height: coordinates.contentHeight, width: coordinates.contentWidth }; return itemPosition; }, _layoutItem: function CellSpanningGroup_layoutItem(index) { var groupInfo = this.groupInfo, margins = this._layout._sizes.containerMargins, entry = this.getItemSize(index); this._items[index].style.cssText += ";-ms-grid-row:" + (entry.row + 1) + ";-ms-grid-column:" + (entry.column + 1) + ";-ms-grid-row-span:" + entry.rows + ";-ms-grid-column-span:" + entry.columns + ";height:" + entry.contentHeight + "px;width:" + entry.contentWidth + "px"; Utilities.addClass(this._items[index], WinJS.UI._laidOutClass); return this._items[index]; }, _cleanContainers: function CellSpanningGroup_cleanContainers() { var items = this._items, len = items.length, i; for (i = 0; i < len; i++) { items[i].style.cssText = ""; Utilities.removeClass(items[i], WinJS.UI._laidOutClass); } }, // Occupancy map getColumnCount: function CellSpanningGroup_getColumnCount() { return Math.ceil(this.occupancyMap.length / this._slotsPerColumn); }, getOccupancyMapItemCount: function CellSpanningGroup_getOccupancyMapItemCount() { var index = -1; // Use forEach as the map may be sparse this.occupancyMap.forEach(function (item) { if (item.index > index) { index = item.index; } }); return index + 1; }, coordinateToIndex: function CellSpanningGroup_coordinateToIndex(c, r) { return c * this._slotsPerColumn + r; }, markSlotAsFull: function CellSpanningGroup_markSlotAsFull(index, itemEntry) { var coordinates = this._layout._indexToCoordinate(index, this._slotsPerColumn), toRow = coordinates.row + itemEntry.rows; for (var r = coordinates.row; r < toRow && r < this._slotsPerColumn; r++) { for (var c = coordinates.column, toColumn = coordinates.column + itemEntry.columns; c < toColumn; c++) { this.occupancyMap[this.coordinateToIndex(c, r)] = itemEntry; } } this._offScreenSlotsPerColumn = Math.max(this._offScreenSlotsPerColumn, toRow - this._slotsPerColumn); }, isSlotEmpty: function CellSpanningGroup_isSlotEmpty(itemSize, row, column) { for (var r = row, toRow = row + itemSize.rows; r < toRow; r++) { for (var c = column, toColumn = column + itemSize.columns; c < toColumn; c++) { if ((r >= this._slotsPerColumn) || (this.occupancyMap[this.coordinateToIndex(c, r)] !== undefined)) { return false; } } } return true; }, findEmptySlot: function CellSpanningGroup_findEmptySlot(startIndex, itemSize, newColumn) { var coordinates = this._layout._indexToCoordinate(startIndex, this._slotsPerColumn), startRow = coordinates.row, lastColumn = Math.floor((this.occupancyMap.length - 1) / this._slotsPerColumn); if (newColumn) { for (var c = coordinates.column + 1; c <= lastColumn; c++) { if (this.isSlotEmpty(itemSize, 0, c)) { return this.coordinateToIndex(c, 0); } } } else { for (var c = coordinates.column; c <= lastColumn; c++) { for (var r = startRow; r < this._slotsPerColumn; r++) { if (this.isSlotEmpty(itemSize, r, c)) { return this.coordinateToIndex(c, r); } } startRow = 0; } } return (lastColumn + 1) * this._slotsPerColumn; }, findItem: function CellSpanningGroup_findItem(index) { for (var inMapIndex = index, len = this.occupancyMap.length; inMapIndex < len; inMapIndex++) { var entry = this.occupancyMap[inMapIndex]; if (entry && entry.index === index) { return inMapIndex; } } return inMapIndex; }, getItemSize: function CellSpanningGroup_getItemSize(index) { var inMapIndex = this.findItem(index), entry = this.occupancyMap[inMapIndex], coords = this._layout._indexToCoordinate(inMapIndex, this._slotsPerColumn); if (index === entry.index) { return { row: coords.row, column: coords.column, contentWidth: entry.contentWidth, contentHeight: entry.contentHeight, columns: entry.columns, rows: entry.rows }; } else { return null; } }, resetMap: function CellSpanningGroup_resetMap() { this.occupancyMap = []; this.lastAdded = 0; this._offScreenSlotsPerColumn = 0; }, addItemToMap: function CellSpanningGroup_addItemToMap(index, itemInfo) { var that = this; function add(mapEntry, newColumn) { var inMapIndex = that.findEmptySlot(that.lastAdded, mapEntry, newColumn); that.lastAdded = inMapIndex; that.markSlotAsFull(inMapIndex, mapEntry); } var groupInfo = that.groupInfo, margins = that._layout._sizes.containerMargins, mapEntry = { index: index, contentWidth: itemInfo.width, contentHeight: itemInfo.height, columns: Math.max(1, Math.ceil((itemInfo.width + margins.left + margins.right) / groupInfo.cellWidth)), rows: Math.max(1, Math.ceil((itemInfo.height + margins.top + margins.bottom) / groupInfo.cellHeight)) }; add(mapEntry, itemInfo.newColumn); }, indexFromOffset: function CellSpanningGroup_indexFromOffset(adjustedOffset, wholeItem, last) { var measuredWidth = 0, lastItem = 0, groupInfo = this.groupInfo, index = 0; if (this.occupancyMap.length > 0) { lastItem = this.getOccupancyMapItemCount() - 1; measuredWidth = Math.ceil((this.occupancyMap.length - 1) / this._slotsPerColumn) * groupInfo.cellWidth; if (adjustedOffset < measuredWidth) { var counter = this._slotsPerColumn, index = (Math.max(0, Math.floor(adjustedOffset / groupInfo.cellWidth)) + last) * this._slotsPerColumn - last; while (!this.occupancyMap[index] && counter-- > 0) { index += (last > 0 ? -1 : 1); } return { index: index, item: this.occupancyMap[index].index } } else { index = this.occupancyMap.length - 1; } } return { index: index, item: lastItem + (Math.max(0, Math.floor((adjustedOffset - measuredWidth) / groupInfo.cellWidth)) + last) * this._slotsPerColumn - last }; } }); }) }); WinJS.Namespace.define("WinJS.UI", { ListLayout: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(WinJS.UI._LegacyLayout, function ListLayout_ctor(options) { /// /// /// Creates a new ListLayout object. /// /// /// An object that contains one or more property/value pairs to apply to the new control. Each property of the options /// object corresponds to one of the object's properties or events. Event names must begin with "on". /// /// /// The new ListLayout object. /// /// options = options || {}; this._itemInfo = {}; this._groupInfo = {}; this._groupHeaderPosition = options.groupHeaderPosition || WinJS.UI.HeaderPosition.top; this._inListMode = true; this.orientation = options.orientation || "vertical"; }, { initialize: function ListLayout_initialize(site, groupsEnabled) { Utilities.addClass(site.surface, WinJS.UI._listLayoutClass); WinJS.UI._LegacyLayout.prototype.initialize.call(this, site, groupsEnabled); }, uninitialize: function ListLayout_uninitialize() { if (this._site) { Utilities.removeClass(this._site.surface, WinJS.UI._listLayoutClass); } WinJS.UI._LegacyLayout.prototype.uninitialize.call(this); }, layout: function ListLayout_layout(tree, changedRange, modifiedItems, modifiedGroups) { if (!this._groupsEnabled && !this._horizontal) { return this._layoutNonGroupedVerticalList(tree, changedRange, modifiedItems, modifiedGroups); } else { return WinJS.UI._LegacyLayout.prototype.layout.call(this, tree, changedRange, modifiedItems, modifiedGroups); } }, _layoutNonGroupedVerticalList: function ListLayout_layoutNonGroupedVerticalList(tree, changedRange, modifiedItems, modifiedGroups) { var that = this; var perfId = "Layout:_layoutNonGroupedVerticalList"; that._site._writeProfilerMark(perfId + ",StartTM"); this._layoutPromise = that._measureItem(0).then(function () { WinJS.Utilities[that._usingStructuralNodes ? "addClass" : "removeClass"](that._site.surface, WinJS.UI._structuralNodesClass); if (that._sizes.viewportContentSize !== that._getViewportCrossSize()) { that._viewportSizeChanged(that._getViewportCrossSize()); } that._cacheRemovedElements(modifiedItems, that._cachedItemRecords, that._cachedInsertedItemRecords, that._cachedRemovedItems, false); that._cacheRemovedElements(modifiedGroups, that._cachedHeaderRecords, that._cachedInsertedHeaderRecords, that._cachedRemovedHeaders, true); var itemsContainer = tree[0].itemsContainer, group = new Groups.UniformFlowGroup(that, itemsContainer); that._groups = [group]; group.groupInfo = { enableCellSpanning: false }; group.startIndex = 0; group.count = getItemsContainerLength(itemsContainer); group.offset = 0; group.layout(); that._site._writeProfilerMark(perfId + ":setSurfaceWidth,info"); that._site.surface.style.width = that._sizes.surfaceContentSize + "px"; that._layoutAnimations(modifiedItems, modifiedGroups); that._site._writeProfilerMark(perfId + ":complete,info"); that._site._writeProfilerMark(perfId + ",StopTM"); }, function (error) { that._site._writeProfilerMark(perfId + ":canceled,info"); that._site._writeProfilerMark(perfId + ",StopTM"); return WinJS.Promise.wrapError(error); }); return { realizedRangeComplete: this._layoutPromise, layoutComplete: this._layoutPromise }; }, numberOfItemsPerItemsBlock: { get: function ListLayout_getNumberOfItemsPerItemsBlock() { // Measure when numberOfItemsPerItemsBlock is called so that we measure before ListView has created the full tree structure // which reduces the trident layout required by measure. this._usingStructuralNodes = WinJS.UI.ListLayout._numberOfItemsPerItemsBlock > 0; return this._measureItem(0).then(function () { return WinJS.UI.ListLayout._numberOfItemsPerItemsBlock; }); } }, }, { // The maximum number of win-containers to put into each items block. win-containers // are grouped into items blocks in order to mitigate the costs of the platform doing // a layout in response to insertions and removals of win-containers. _numberOfItemsPerItemsBlock: 10 }); }), CellSpanningLayout: WinJS.Namespace._lazy(function () { return WinJS.Class.derive(WinJS.UI._LayoutCommon, function CellSpanningLayout_ctor(options) { /// /// /// Creates a new CellSpanningLayout object. /// /// /// An object that contains one or more property/value pairs to apply to the new object. Each property of the options /// object corresponds to one of the object's properties or events. Event names must begin with "on". /// /// /// The new CellSpanningLayout object. /// /// options = options || {}; this._itemInfo = options.itemInfo; this._groupInfo = options.groupInfo; this._groupHeaderPosition = options.groupHeaderPosition || WinJS.UI.HeaderPosition.top; this._horizontal = true; this._cellSpanning = true; }, { /// /// Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. /// A value of 0 indicates that there is no maximum. /// maximumRowsOrColumns: { get: function () { return this._maxRowsOrColumns; }, set: function (value) { this._setMaxRowsOrColumns(value); } }, /// /// Gets or sets a function that returns the width and height of an item, as well as whether /// it should appear in a new column. Setting this function improves performance because /// the ListView can allocate space for an item without having to measure it first. /// The function takes a single parameter: the index of the item to render. /// The function returns an object that has three properties: /// width: The total width of the item. /// height: The total height of the item. /// newColumn: Set to true to create a column break; otherwise, false. /// itemInfo: { enumerable: true, get: function () { return this._itemInfo; }, set: function (itemInfo) { this._itemInfo = itemInfo; this._invalidateLayout(); } }, /// /// Gets or sets a function that enables cell-spanning and establishes base cell dimensions. /// The function returns an object that has these properties: /// enableCellSpanning: Set to true to allow the ListView to contain items of multiple sizes. /// cellWidth: The width of the base cell. /// cellHeight: The height of the base cell. /// groupInfo: { enumerable: true, get: function () { return this._groupInfo; }, set: function (groupInfo) { this._groupInfo = groupInfo; this._invalidateLayout(); } }, /// /// Gets the orientation of the layout. CellSpanning layout only supports horizontal orientation. /// orientation: { enumerable: true, get: function () { return "horizontal"; } } }); }), _LayoutWrapper: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function LayoutWrapper_ctor(layout) { this.defaultAnimations = true; // Initialize and hitTest are required this.initialize = function LayoutWrapper_initialize(site, groupsEnabled) { layout.initialize(site, groupsEnabled); }; this.hitTest = function LayoutWrapper_hitTest(x, y) { return layout.hitTest(x, y); }; // These methods are optional layout.uninitialize && (this.uninitialize = function LayoutWrapper_uninitialize() { layout.uninitialize(); }); if ("numberOfItemsPerItemsBlock" in layout) { Object.defineProperty(this, "numberOfItemsPerItemsBlock", { get: function LayoutWrapper_getNumberOfItemsPerItemsBlock() { return layout.numberOfItemsPerItemsBlock; } }); } layout._getItemPosition && (this._getItemPosition = function LayoutWrapper_getItemPosition(index) { return layout._getItemPosition(index); }); layout.itemsFromRange && (this.itemsFromRange = function LayoutWrapper_itemsFromRange(start, end) { return layout.itemsFromRange(start, end); }); layout.getAdjacent && (this.getAdjacent = function LayoutWrapper_getAdjacent(currentItem, pressedKey) { return layout.getAdjacent(currentItem, pressedKey); }); layout.dragOver && (this.dragOver = function LayoutWrapper_dragOver(x, y, dragInfo) { return layout.dragOver(x, y, dragInfo); }); layout.dragLeave && (this.dragLeave = function LayoutWrapper_dragLeave() { return layout.dragLeave(); }); var propertyDefinition = { enumerable: true, get: function () { return "vertical"; } } if (layout.orientation !== undefined) { propertyDefinition.get = function () { return layout.orientation; } propertyDefinition.set = function (value) { layout.orientation = value; } } Object.defineProperty(this, "orientation", propertyDefinition); if (layout.setupAnimations || layout.executeAnimations) { this.defaultAnimations = false; this.setupAnimations = function LayoutWrapper_setupAnimations() { return layout.setupAnimations(); }; this.executeAnimations = function LayoutWrapper_executeAnimations() { return layout.executeAnimations(); }; } if (layout.layout) { if (this.defaultAnimations) { var that = this; this.layout = function LayoutWrapper_layout(tree, changedRange, modifiedItems, modifiedGroups) { var promises = normalizeLayoutPromises(layout.layout(tree, changedRange, [], [])), synchronous; promises.realizedRangeComplete.then(function () { synchronous = true; }); synchronous && that._layoutAnimations(modifiedItems, modifiedGroups); return promises; }; } else { this.layout = function LayoutWrapper_layout(tree, changedRange, modifiedItems, modifiedGroups) { return normalizeLayoutPromises(layout.layout(tree, changedRange, modifiedItems, modifiedGroups)); }; } } }, { uninitialize: function LayoutWrapper_uninitialize() { }, numberOfItemsPerItemsBlock: { get: function LayoutWrapper_getNumberOfItemsPerItemsBlock() { } }, layout: function LayoutWrapper_layout(tree, changedRange, modifiedItems, modifiedGroups) { if (this.defaultAnimations) { this._layoutAnimations(modifiedItems, modifiedGroups); } return normalizeLayoutPromises(); }, itemsFromRange: function LayoutWrapper_itemsFromRange(start, end) { return { firstIndex: 0, lastIndex: Number.MAX_VALUE }; }, getAdjacent: function LayoutWrapper_getAdjacent(currentItem, pressedKey) { var key = WinJS.Utilities.Key; switch (pressedKey) { case key.pageUp: case key.upArrow: case key.leftArrow: return { type: currentItem.type, index: currentItem.index - 1 }; case key.downArrow: case key.rightArrow: case key.pageDown: return { type: currentItem.type, index: currentItem.index + 1 }; } }, dragOver: function LayoutWrapper_dragOver(x, y) { }, dragLeave: function LayoutWrapper_dragLeaver() { }, setupAnimations: function LayoutWrapper_setupAnimations() { }, executeAnimations: function LayoutWrapper_executeAnimations() { }, _getItemPosition: function LayoutWrapper_getItemPosition() { }, _layoutAnimations: function LayoutWrapper_layoutAnimations(modifiedItems, modifiedGroups) { }, }); }), }); function normalizeLayoutPromises(retVal) { if (WinJS.Promise.is(retVal)) { return { realizedRangeComplete: retVal, layoutComplete: retVal }; } else if (typeof retVal === "object" && retVal && retVal.layoutComplete) { return retVal; } else { return { realizedRangeComplete: WinJS.Promise.wrap(), layoutComplete: WinJS.Promise.wrap() }; } } function getMargins(element) { return { left: getDimension(element, "marginLeft"), right: getDimension(element, "marginRight"), top: getDimension(element, "marginTop"), bottom: getDimension(element, "marginBottom") }; } // Layout, _LayoutCommon, and _LegacyLayout are defined ealier so that their fully // qualified names can be used in WinJS.Class.derive. This is required by Blend. WinJS.Namespace.define("WinJS.UI", { HeaderPosition: { left: "left", top: "top" }, _getMargins: getMargins }); })(this, WinJS); (function listViewImplInit(global, WinJS, undefined) { "use strict"; var DISPOSE_TIMEOUT = 1000; var controlsToDispose = []; var disposeControlTimeout; function disposeControls() { var temp = controlsToDispose; controlsToDispose = []; temp = temp.filter(function (c) { if (c._isZombie()) { c._dispose(); return false; } else { return true; } }); controlsToDispose = controlsToDispose.concat(temp); } function scheduleForDispose(lv) { controlsToDispose.push(lv); disposeControlTimeout && disposeControlTimeout.cancel(); disposeControlTimeout = WinJS.Promise.timeout(DISPOSE_TIMEOUT).then(disposeControls); } function ensureId(element) { if (!element.id) { element.id = element.uniqueID; } } function setFlow(from, to) { WinJS.UI._setAttribute(from, "aria-flowto", to.id); WinJS.UI._setAttribute(to, "x-ms-aria-flowfrom", from.id); } // Only set the attribute if its value has changed function setAttribute(element, attribute, value) { if (element.getAttribute(attribute) !== "" + value) { element.setAttribute(attribute, value); } } function nodeListToArray(nodeList) { return Array.prototype.slice.call(nodeList); } function repeat(markup, count) { return new Array(count + 1).join(markup); } function getOffsetRight(element) { return element.offsetParent ? (element.offsetParent.offsetWidth - element.offsetLeft - element.offsetWidth) : 0; } // Default renderer for Listview var trivialHtmlRenderer = WinJS.UI.simpleItemRenderer(function (item) { if (utilities._isDOMElement(item.data)) { return item.data; } var data = item.data; if (data === undefined) { data = "undefined"; } else if (data === null) { data = "null"; } else if (typeof data === "object") { data = JSON.stringify(data); } var element = document.createElement("span"); element.innerText = data.toString(); return element; }); WinJS.Namespace.define("WinJS.UI", { _trivialHtmlRenderer: trivialHtmlRenderer, _disposeControls: disposeControls, _ensureId: ensureId, _setFlow: setFlow, _setAttribute: setAttribute, _nodeListToArray: nodeListToArray, _repeat: repeat, _ListViewAnimationHelper: { fadeInElement: function (element) { return WinJS.UI.Animation.fadeIn(element); }, fadeOutElement: function (element) { return WinJS.UI.Animation.fadeOut(element); }, animateEntrance: function (canvas, firstEntrance) { return WinJS.UI.Animation.enterContent(canvas, [{ left: firstEntrance ? "100px" : "40px", top: "0px", rtlflip: true }], { mechanism: "transition" }); }, } }); var ScrollToPriority = { uninitialized: 0, low: 1, // used by layoutSite.invalidateLayout, forceLayout, _processReload, _update and _onMSElementResize - operations that preserve the scroll position medium: 2, // used by dataSource change, layout change and etc - operations that reset the scroll position to 0 high: 3 // used by indexOfFirstVisible, ensureVisible, scrollPosition - operations in which the developer explicitly sets the scroll position }; var ViewChange = { rebuild: 0, remeasure: 1, relayout: 2, realize: 3 }; var thisWinUI = WinJS.UI, utilities = WinJS.Utilities, Promise = WinJS.Promise, Scheduler = utilities.Scheduler, AnimationHelper = WinJS.UI._ListViewAnimationHelper; var strings = { get notCompatibleWithSemanticZoom() { return WinJS.Resources._getWinJSString("ui/notCompatibleWithSemanticZoom").value; }, get listViewInvalidItem() { return WinJS.Resources._getWinJSString("ui/listViewInvalidItem").value; }, get listViewViewportAriaLabel() { return WinJS.Resources._getWinJSString("ui/listViewViewportAriaLabel").value; } }; var requireSupportedForProcessing = WinJS.Utilities.requireSupportedForProcessing; // ListView implementation WinJS.Namespace.define("WinJS.UI", { _ScrollToPriority: ScrollToPriority, _ViewChange: ViewChange, /// /// Specifies the type of an IListViewEntity. /// ObjectType: { /// /// This value represents a ListView item. /// item: "item", /// /// This value represents a ListView group header. /// groupHeader: "groupHeader" }, /// /// Specifies the selection mode for a ListView. /// SelectionMode: { /// /// Items cannot be selected. /// none: "none", /// /// A single item may be selected. /// single: "single", /// /// Multiple items may be selected. /// /// multi: "multi" }, /// /// Specifies how an ItemContainer or items in a ListView respond to the tap interaction. /// TapBehavior: { /// /// Tapping the item invokes it and selects it. Navigating to the item with the keyboard changes the /// the selection so that the focused item is the only item that is selected. /// /// directSelect: "directSelect", /// /// Tapping the item invokes it. If the item was selected, tapping it clears the selection. If the item wasn't /// selected, tapping the item selects it. /// Navigating to the item with the keyboard does not select or invoke it. /// toggleSelect: "toggleSelect", /// /// Tapping the item invokes it. Navigating to the item with keyboard does not select it or invoke it. /// invokeOnly: "invokeOnly", /// /// Nothing happens. /// none: "none" }, /// /// Specifies how group headers in a ListView respond to the tap interaction. /// GroupHeaderTapBehavior: { /// /// Tapping the group header invokes it. /// invoke: "invoke", /// /// Nothing happens. /// none: "none" }, /// /// Specifies whether items are selected when the user performs a swipe interaction. /// /// SwipeBehavior: { /// /// The swipe interaction selects the items touched by the swipe. /// /// select: "select", /// /// The swipe interaction does not change which items are selected. /// /// none: "none" }, /// /// Specifies whether the ListView animation is an entrance animation or a transition animation. /// /// ListViewAnimationType: { /// /// The animation plays when the ListView is first displayed. /// /// entrance: "entrance", /// /// The animation plays when the ListView is changing its content. /// /// contentTransition: "contentTransition" }, /// /// Displays items in a customizable list or grid. /// /// /// /// ]]> /// Raised when the ListView is about to play an entrance or a transition animation. /// Raised when the user taps or clicks an item. /// Raised when the user taps or clicks a group header. /// Raised before items are selected or deselected. /// Raised after items are selected or deselected. /// Raised when the loading state changes. /// Raised when the focused item changes. /// Raised when the the user begins dragging ListView items. /// Raised when the user drags into the ListView. /// Raised when a drag operation begun in a ListView ends. /// Raised when the user drags between two ListView items. /// Raised when the user drags outside of the ListView region. /// Raised when the items being dragged are changed due to a datasource modification. /// Raised when the user drops items into the ListView. /// Raised when the accessibility attributes have been added to the ListView items. /// The entire ListView control. /// The viewport of the ListView. /// The scrollable region of the ListView. /// An item in the ListView. /// The background of a selection checkmark. /// A selection checkmark. /// The header of a group. /// The progress indicator of the ListView. /// /// /// ListView: WinJS.Namespace._lazy(function () { var AffectedRange = WinJS.Class.define(function () { this.clear(); }, { // Marks the union of the current affected range and range as requiring layout add: function (range, itemsCount) { range._lastKnownSizeOfData = itemsCount; // store this in order to make unions. if (!this._range) { this._range = range; } else { // Take the union of these two ranges. this._range.start = Math.min(this._range.start, range.start); // To accurately calculate the new unioned range 'end' value, we need to convert the current and new range end // positions into values that represent the remaining number of un-modified items in between the end of the range // and the end of the list of data. var previousUnmodifiedItemsFromEnd = (this._range._lastKnownSizeOfData - this._range.end); var newUnmodifiedItemsFromEnd = (range._lastKnownSizeOfData - range.end); var finalUnmodifiedItemsFromEnd = Math.min(previousUnmodifiedItemsFromEnd, newUnmodifiedItemsFromEnd); this._range._lastKnownSizeOfData = range._lastKnownSizeOfData; // Convert representation of the unioned end position back into a value which matches the above definition of _affecteRange.end this._range.end = this._range._lastKnownSizeOfData - finalUnmodifiedItemsFromEnd; } }, // Marks everything as requiring layout addAll: function () { this.add({ start: 0, end: Number.MAX_VALUE }, Number.MAX_VALUE); }, // Marks nothing as requiring layout clear: function () { this._range = null; }, get: function () { return this._range; } }); var ZoomableView = WinJS.Class.define(function ZoomableView_ctor(listView) { // Constructor this._listView = listView; }, { // Public methods getPanAxis: function () { return this._listView._getPanAxis(); }, configureForZoom: function (isZoomedOut, isCurrentView, triggerZoom, prefetchedPages) { this._listView._configureForZoom(isZoomedOut, isCurrentView, triggerZoom, prefetchedPages); }, setCurrentItem: function (x, y) { this._listView._setCurrentItem(x, y); }, getCurrentItem: function () { return this._listView._getCurrentItem(); }, beginZoom: function () { this._listView._beginZoom(); }, positionItem: function (item, position) { return this._listView._positionItem(item, position); }, endZoom: function (isCurrentView) { this._listView._endZoom(isCurrentView); } }); var ListView = WinJS.Class.define(function ListView_ctor(element, options) { /// /// /// Creates a new ListView. /// /// /// The DOM element that hosts the ListView control. /// /// /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". For example, to provide a handler for the selectionchanged event, /// add a property named "onselectionchanged" to the options object and set its value to the event handler. /// /// /// The new ListView. /// /// element = element || document.createElement("div"); this._id = element.id || ""; this._writeProfilerMark("constructor,StartTM"); options = options || {}; // Attaching JS control to DOM element element.winControl = this; WinJS.Utilities.addClass(element, "win-disposable"); this._affectedRange = new AffectedRange(); this._mutationObserver = new MutationObserver(this._itemPropertyChange.bind(this)); this._versionManager = null; this._insertedItems = {}; this._element = element; this._startProperty = null; this._scrollProperty = null; this._scrollLength = null; this._scrolling = false; this._zooming = false; this._pinching = false; this._itemsManager = null; this._canvas = null; this._cachedCount = WinJS.UI._UNINITIALIZED; this._loadingState = this._LoadingState.complete; this._firstTimeDisplayed = true; this._currentScrollPosition = 0; this._lastScrollPosition = 0; this._notificationHandlers = []; this._itemsBlockExtent = -1; this._viewportWidth = WinJS.UI._UNINITIALIZED; this._viewportHeight = WinJS.UI._UNINITIALIZED; this._manipulationState = MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED; this._maxDeferredItemCleanup = Number.MAX_VALUE; this._groupsToRemove = {}; this._setupInternalTree(); this._isCurrentZoomView = true; this._dragSource = false; this._reorderable = false; this._groupFocusCache = new WinJS.UI._UnsupportedGroupFocusCache(); this._viewChange = ViewChange.rebuild; this._scrollToFunctor = null; this._setScrollbarPosition = false; // The view needs to be initialized after the internal tree is setup, because the view uses the canvas node immediately to insert an element in its constructor this._view = new WinJS.UI._VirtualizeContentsView(this); this._selection = new WinJS.UI._SelectionManager(this); this._createTemplates(); var that = this; this._groupHeaderRenderer = WinJS.UI._trivialHtmlRenderer; this._itemRenderer = WinJS.UI._trivialHtmlRenderer; this._groupHeaderRelease = null; this._itemRelease = null; if (!options.itemDataSource) { var list = new WinJS.Binding.List(); this._dataSource = list.dataSource; } else { this._dataSource = options.itemDataSource; } this._selectionMode = WinJS.UI.SelectionMode.multi; this._tap = WinJS.UI.TapBehavior.invokeOnly; this._groupHeaderTap = WinJS.UI.GroupHeaderTapBehavior.invoke; this._swipeBehavior = WinJS.UI.SwipeBehavior.select; this._mode = new WinJS.UI._SelectionMode(this); // Call after swipeBehavior and modes are set this._setSwipeClass(); this._groups = new WinJS.UI._NoGroups(this); this._updateItemsAriaRoles(); this._updateGroupHeadersAriaRoles(); this._element.setAttribute("aria-multiselectable", this._multiSelection()); this._tabIndex = (this._element.tabIndex !== undefined && this._element.tabIndex >= 0) ? this._element.tabIndex : 0; this._element.tabIndex = -1; this._tabManager.tabIndex = this._tabIndex; if (this._element.style.position !== "absolute" && this._element.style.position !== "relative") { this._element.style.position = "relative"; } this._updateItemsManager(); if (!options.layout) { this._updateLayout(new WinJS.UI.GridLayout()); } this._attachEvents(); this._runningInit = true; WinJS.UI.setOptions(this, options); this._runningInit = false; this._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.medium, 0); this._writeProfilerMark("constructor,StopTM"); }, { // Public properties /// element: { get: function () { return this._element; } }, /// /// Gets or sets an object that controls the layout of the ListView. /// layout: { get: function () { return this._layoutImpl; }, set: function (layoutObject) { this._updateLayout(layoutObject); if (!this._runningInit) { this._view.reset(); this._updateItemsManager(); this._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.medium, 0, true); } } }, /// /// Gets or sets the number of pages to load when the user scrolls beyond the /// threshold specified by the pagesToLoadThreshold property if /// the loadingBehavior property is set to incremental. /// /// pagesToLoad is deprecated. The control will not use this property. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior. /// /// pagesToLoad: { get: function () { return (WinJS.UI._VirtualizeContentsView._pagesToPrefetch * 2) + 1; }, set: function (newValue) { utilities._deprecated(WinJS.UI._strings.pagesToLoadIsDeprecated); } }, /// /// Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is /// within the specified number of pages from the end of the loaded portion of the list, /// and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", /// the ListView initiates an incremental load. /// /// pagesToLoadThreshold is deprecated. The control will not use this property. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior. /// /// pagesToLoadThreshold: { get: function () { return 0; }, set: function (newValue) { utilities._deprecated(WinJS.UI._strings.pagesToLoadThresholdIsDeprecated); } }, /// /// Gets or sets the data source that contains the groups for the items in the itemDataSource. /// groupDataSource: { get: function () { return this._groupDataSource; }, set: function (newValue) { this._writeProfilerMark("set_groupDataSource,info"); var that = this; function groupStatusChanged(eventObject) { if (eventObject.detail === thisWinUI.DataSourceStatus.failure) { that.itemDataSource = null; that.groupDataSource = null; } } if (this._groupDataSource && this._groupDataSource.removeEventListener) { this._groupDataSource.removeEventListener("statuschanged", groupStatusChanged, false); } this._groupDataSource = newValue; this._groupFocusCache = (newValue && this._supportsGroupHeaderKeyboarding) ? new WinJS.UI._GroupFocusCache(this) : new WinJS.UI._UnsupportedGroupFocusCache(); if (this._groupDataSource && this._groupDataSource.addEventListener) { this._groupDataSource.addEventListener("statuschanged", groupStatusChanged, false); } this._createGroupsContainer(); if (!this._runningInit) { this._view.reset(); this._pendingLayoutReset = true; this._pendingGroupWork = true; this._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.medium, 0, true); } else { this._updateGroupWork(); this._resetLayout(); } } }, _updateGroupWork: function () { this._pendingGroupWork = false; if (this._groupDataSource) { utilities.addClass(this._element, WinJS.UI._groupsClass); } else { utilities.removeClass(this._element, WinJS.UI._groupsClass); } this._resetLayout(); }, /// /// Gets or sets a value that indicates whether the next set of pages is automatically loaded /// when the user scrolls beyond the number of pages specified by the /// pagesToLoadThreshold property. /// /// automaticallyLoadPages is deprecated. The control will default this property to false. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior. /// /// automaticallyLoadPages: { get: function () { return false; }, set: function (newValue) { utilities._deprecated(WinJS.UI._strings.automaticallyLoadPagesIsDeprecated); } }, /// /// Gets or sets a value that determines how many data items are loaded into the DOM. /// /// pagesToLoadThreshold is deprecated. The control will default this property to 'randomAccess'. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior. /// /// loadingBehavior: { get: function () { return "randomAccess"; }, set: function (newValue) { utilities._deprecated(WinJS.UI._strings.loadingBehaviorIsDeprecated); } }, /// /// Gets or sets a value that specifies how many ListView items the user can select: "none", "single", or "multi". /// selectionMode: { get: function () { return this._selectionMode; }, set: function (newMode) { if (typeof newMode === "string") { if (newMode.match(/^(none|single|multi)$/)) { this._selectionMode = newMode; this._element.setAttribute("aria-multiselectable", this._multiSelection()); this._updateItemsAriaRoles(); this._setSwipeClass(); return; } } throw new WinJS.ErrorFromName("WinJS.UI.ListView.ModeIsInvalid", WinJS.UI._strings.modeIsInvalid); } }, /// /// Gets or sets how the ListView reacts when the user taps or clicks an item. /// The tap or click can invoke the item, select it and invoke it, or have no /// effect. /// tapBehavior: { get: function () { return this._tap; }, set: function (tap) { this._tap = tap; this._updateItemsAriaRoles(); } }, /// /// Gets or sets how the ListView reacts when the user taps or clicks a group header. /// groupHeaderTapBehavior: { get: function () { return this._groupHeaderTap; }, set: function (tap) { this._groupHeaderTap = tap; this._updateGroupHeadersAriaRoles(); } }, /// /// Gets or sets how the ListView reacts to the swipe interaction. /// The swipe gesture can select the swiped items or it can /// have no effect on the current selection. /// /// swipeBehavior: { get: function () { return this._swipeBehavior; }, set: function (swipeBehavior) { this._swipeBehavior = swipeBehavior; this._setSwipeClass(); } }, /// /// Gets or sets the data source that provides items for the ListView. /// itemDataSource: { get: function () { return this._itemsManager.dataSource; }, set: function (newData) { this._writeProfilerMark("set_itemDataSource,info"); this._dataSource = newData || new WinJS.Binding.List().dataSource; this._groupFocusCache.clear(); if (!this._runningInit) { this._selection._reset(); this._cancelAsyncViewWork(true); this._updateItemsManager(); this._pendingLayoutReset = true; this._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.medium, 0, true); } } }, /// /// Gets or sets the templating function that creates the DOM elements /// for each item in the itemDataSource. Each item can contain multiple /// DOM elements, but we recommend that it have a single root element. /// itemTemplate: { get: function () { return this._itemRenderer; }, set: function (newRenderer) { this._setRenderer(newRenderer, false); if (!this._runningInit) { this._cancelAsyncViewWork(true); this._updateItemsManager(); this._pendingLayoutReset = true; this._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.medium, 0, true); } } }, /// /// Gets or sets the function that is called when the ListView recycles the /// element representation of an item. /// /// resetItem may be altered or unavailable in future versions. Instead, mark the element as disposable using WinJS.Utilities.markDisposable. /// /// resetItem: { get: function () { return this._itemRelease; }, set: function (release) { utilities._deprecated(WinJS.UI._strings.resetItemIsDeprecated); this._itemRelease = release; } }, /// /// Gets or sets the templating function that creates the DOM elements /// for each group header in the groupDataSource. Each group header /// can contain multiple elements, but it must have a single root element. /// groupHeaderTemplate: { get: function () { return this._groupHeaderRenderer; }, set: function (newRenderer) { this._setRenderer(newRenderer, true); if (!this._runningInit) { this._cancelAsyncViewWork(true); this._pendingLayoutReset = true; this._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.medium, 0, true); } } }, /// /// Gets or sets the function that is called when the ListView recycles the DOM element representation /// of a group header. /// /// resetGroupHeader may be altered or unavailable in future versions. Instead, mark the header element as disposable using WinJS.Utilities.markDisposable. /// /// resetGroupHeader: { get: function () { return this._groupHeaderRelease; }, set: function (release) { utilities._deprecated(WinJS.UI._strings.resetGroupHeaderIsDeprecated); this._groupHeaderRelease = release; } }, /// loadingState: { get: function () { return this._loadingState; } }, /// /// Gets an ISelection object that contains the currently selected items. /// selection: { get: function () { return this._selection; } }, /// /// Gets or sets the first visible item. When setting this property, the ListView scrolls so that the /// item with the specified index is at the top of the list. /// indexOfFirstVisible: { get: function () { return this._view.firstIndexDisplayed; }, set: function (itemIndex) { if (itemIndex < 0) { return; } this._writeProfilerMark("set_indexOfFirstVisible(" + itemIndex + "),info"); this._raiseViewLoading(true); var that = this; this._batchViewUpdates(ViewChange.realize, ScrollToPriority.high, function () { var range; return that._entityInRange({ type: WinJS.UI.ObjectType.item, index: itemIndex }).then(function (validated) { if (!validated.inRange) { return { position: 0, direction: "left" }; } else { return that._getItemOffset({ type: WinJS.UI.ObjectType.item, index: validated.index }).then(function (r) { range = r; return that._ensureFirstColumnRange(WinJS.UI.ObjectType.item); }).then(function () { range = that._correctRangeInFirstColumn(range, WinJS.UI.ObjectType.item); range = that._convertFromCanvasCoordinates(range); return that._view.waitForValidScrollPosition(range.begin); }).then(function (begin) { var direction = (begin < that._lastScrollPosition) ? "left" : "right"; var max = that._viewport[that._scrollLength] - that._getViewportLength(); begin = utilities._clamp(begin, 0, max); return { position: begin, direction: direction }; }); } }); }, true); } }, /// /// Gets the index of the last visible item. /// indexOfLastVisible: { get: function () { return this._view.lastIndexDisplayed; } }, /// /// Gets or sets an object that indicates which item should get keyboard focus and its focus status. /// The object has these properties: /// index: the index of the item in the itemDataSource. /// key: the key of the item in the itemDataSource. /// hasFocus: when getting this property, this value is true if the item already has focus; otherwise, it's false. /// When setting this property, set this value to true if the item should get focus immediately; otherwise, set it to /// false and the item will get focus eventually. /// showFocus: true if the item displays the focus rectangle; otherwise, false. /// currentItem: { get: function () { var focused = this._selection._getFocused(); var retVal = { index: focused.index, type: focused.type, key: null, hasFocus: !!this._hasKeyboardFocus, showFocus: false }; if (focused.type === WinJS.UI.ObjectType.groupHeader) { var group = this._groups.group(focused.index); if (group) { retVal.key = group.key; retVal.showFocus = !!(group.header && WinJS.Utilities.hasClass(group.header, WinJS.UI._itemFocusClass)); } } else { var item = this._view.items.itemAt(focused.index); if (item) { var record = this._itemsManager._recordFromElement(item); retVal.key = record.item && record.item.key; retVal.showFocus = !!item.parentNode.querySelector("." + thisWinUI._itemFocusOutlineClass); } } return retVal; }, set: function (data) { this._hasKeyboardFocus = data.hasFocus || this._hasKeyboardFocus; var that = this; function setItemFocused(item, isInTree, entity) { var drawKeyboardFocus = !!data.showFocus && that._hasKeyboardFocus; that._unsetFocusOnItem(isInTree); that._selection._setFocused(entity, drawKeyboardFocus); if (that._hasKeyboardFocus) { that._keyboardFocusInbound = drawKeyboardFocus; that._setFocusOnItem(entity); } else { that._tabManager.childFocus = (isInTree ? item : null); } if (entity.type !== WinJS.UI.ObjectType.groupHeader) { that._updateFocusCache(entity.index); if (that._updater) { that._updater.newSelectionPivot = entity.index; that._updater.oldSelectionPivot = -1; } that._selection._pivot = entity.index; } } if (data.key && ((data.type !== WinJS.UI.ObjectType.groupHeader && this._dataSource.itemFromKey) || (data.type === WinJS.UI.ObjectType.groupHeader && this._groupDataSource && this._groupDataSource.itemFromKey))) { if (this.oldCurrentItemKeyFetch) { this.oldCurrentItemKeyFetch.cancel(); } var dataSource = (data.type === WinJS.UI.ObjectType.groupHeader ? this._groupDataSource : this._dataSource); this.oldCurrentItemKeyFetch = dataSource.itemFromKey(data.key).then(function (item) { that.oldCurrentItemKeyFetch = null; if (item) { var element = (data.type === WinJS.UI.ObjectType.groupHeader ? that._groups.group(item.index).header : that._view.items.itemAt(item.index)); setItemFocused(element, !!element, { type: data.type || WinJS.UI.ObjectType.item, index: item.index }); } }); } else { if (data.index !== undefined) { var element; if (data.type === WinJS.UI.ObjectType.groupHeader) { var group = that._groups.group(data.index); element = group && group.header; } else { element = that._view.items.itemAt(data.index); } setItemFocused(element, !!element, { type: data.type || WinJS.UI.ObjectType.item, index: data.index }); } } } }, /// /// Gets a ZoomableView. This API supports the SemanticZoom infrastructure /// and is not intended to be used directly from your code. /// zoomableView: { get: function () { if (!this._zoomableView) { this._zoomableView = new ZoomableView(this); } return this._zoomableView; } }, /// /// Gets or sets whether the ListView's items can be dragged via drag and drop. /// /// itemsDraggable: { get: function () { return this._dragSource; }, set: function (value) { if (this._dragSource !== value) { this._dragSource = value; this._setSwipeClass(); } } }, /// /// Gets or sets whether the ListView's items can be reordered within itself via drag and drop. When a ListView is marked as reorderable, its items can be dragged about inside itself, but it will not require the itemdrag events it fires to be handled. /// /// itemsReorderable: { get: function () { return this._reorderable; }, set: function (value) { if (this._reorderable !== value) { this._reorderable = value; this._setSwipeClass(); } } }, /// /// Gets or sets the maximum number of realized items. /// maxDeferredItemCleanup: { get: function () { return this._maxDeferredItemCleanup; }, set: function (value) { this._maxDeferredItemCleanup = Math.max(0, +value || 0); } }, // Public methods dispose: function () { /// /// /// Disposes this ListView. /// /// this._dispose(); }, elementFromIndex: function (itemIndex) { /// /// /// Returns the DOM element that represents the item at the specified index. /// /// /// The index of the item. /// /// /// The DOM element that represents the specified item. /// /// return this._view.items.itemAt(itemIndex); }, indexOfElement: function (element) { /// /// /// Returns the index of the item that the specified DOM element displays. /// /// /// The DOM element that displays the item. /// /// /// The index of item that the specified DOM element displays. /// /// return this._view.items.index(element); }, ensureVisible: function ListView_ensureVisible(value) { /// /// /// Makes the specified item visible. The ListView scrolls to the item if needed. /// /// /// The index of the ListView item or IListViewEntity to bring into view. /// /// var type = WinJS.UI.ObjectType.item, itemIndex = value; if (+value !== value) { type = value.type; itemIndex = value.index; } this._writeProfilerMark("ensureVisible(" + type + ": " + itemIndex + "),info"); if (itemIndex < 0) { return; } this._raiseViewLoading(true); var that = this; this._batchViewUpdates(ViewChange.realize, ScrollToPriority.high, function () { var range; return that._entityInRange({ type: type, index: itemIndex }).then(function (validated) { if (!validated.inRange) { return { position: 0, direction: "left" }; } else { return that._getItemOffset({ type: type, index: validated.index }).then(function (r) { range = r; return that._ensureFirstColumnRange(type); }).then(function () { range = that._correctRangeInFirstColumn(range, type); var viewportLength = that._getViewportLength(), left = that._viewportScrollPosition, right = left + viewportLength, newPosition = that._viewportScrollPosition, entityWidth = range.end - range.begin; range = that._convertFromCanvasCoordinates(range); var handled = false; if (type === WinJS.UI.ObjectType.groupHeader && left <= range.begin) { // EnsureVisible on a group where the entire header is fully visible does not // scroll. This prevents tabbing from an item in a very large group to align // the scroll to the header element. var header = that._groups.group(validated.index).header; if (header) { var headerEnd; var margins = WinJS.UI._getMargins(header); if (that._horizontalLayout) { var rtl = that._rtl(); var headerStart = (rtl ? getOffsetRight(header) - margins.right : header.offsetLeft - margins.left); headerEnd = headerStart + header.offsetWidth + (rtl ? margins.left : margins.right); } else { headerEnd = header.offsetTop + header.offsetHeight + margins.top; } handled = headerEnd <= right; } } if (!handled) { if (entityWidth >= right - left) { // This item is larger than the viewport so we will just set // the scroll position to the beginning of the item. newPosition = range.begin; } else { if (range.begin < left) { newPosition = range.begin; } else if (range.end > right) { newPosition = range.end - viewportLength; } } } var direction = (newPosition < that._lastScrollPosition) ? "left" : "right"; var max = that._viewport[that._scrollLength] - viewportLength; newPosition = utilities._clamp(newPosition, 0, max); return { position: newPosition, direction: direction }; }); } }); }, true); }, loadMorePages: function ListView_loadMorePages() { /// /// /// Loads the next set of pages if the ListView object's loadingBehavior is set to incremental. /// /// loadMorePages is deprecated. Invoking this function will not have any effect. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior. /// /// /// utilities._deprecated(WinJS.UI._strings.loadMorePagesIsDeprecated); }, recalculateItemPosition: function ListView_recalculateItemPosition() { /// /// /// Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Use this function or forceLayout when making the ListView visible again after you set its style.display property to "none" or after style changes have been made that affect the size or position of the ListView or its items. Unlike forceLayout, this method doesn’t recreate items and it doesn’t display entrance animation. /// /// this._writeProfilerMark("recalculateItemPosition,info"); this._forceLayoutImpl(ViewChange.relayout); }, forceLayout: function ListView_forceLayout() { /// /// /// Forces the ListView to update its layout. Use this function or relcaculateItemPosition when making the ListView visible again after you set its style.display property to "none” or after style changes have been made that affect the size or position of the ListView or its items. /// after you set its style.display property to "none". /// /// this._writeProfilerMark("forceLayout,info"); this._forceLayoutImpl(ViewChange.remeasure); }, _entityInRange: function ListView_entityInRange(entity) { if (entity.type === WinJS.UI.ObjectType.item) { return this._itemsCount().then(function (itemsCount) { var index = utilities._clamp(entity.index, 0, itemsCount - 1); return { inRange: index >= 0 && index < itemsCount, index: index }; }); } else { var index = utilities._clamp(entity.index, 0, this._groups.length() - 1); return Promise.wrap({ inRange: index >= 0 && index < this._groups.length(), index: index }); } }, _forceLayoutImpl: function ListView_forceLayoutImpl(viewChange) { var that = this; this._versionManager.unlocked.then(function () { that._writeProfilerMark("_forceLayoutImpl viewChange(" + viewChange + "),info"); that._cancelAsyncViewWork(); that._pendingLayoutReset = true; that._resizeViewport(); that._batchViewUpdates(viewChange, ScrollToPriority.low, function () { return { position: that._lastScrollPosition, direction: "right" }; }, true, true); }); }, _supportsGroupHeaderKeyboarding: { get: function () { return this._groupDataSource; } }, _viewportScrollPosition: { get: function () { this._currentScrollPosition = this._viewport[this._scrollProperty]; return this._currentScrollPosition; }, set: function (value) { this._viewport[this._scrollProperty] = value; this._currentScrollPosition = value; } }, _canvasStart: { get: function () { return this._canvasStartValue || 0; }, set: function (value) { var transformX = this._horizontal() ? (this._rtl() ? -value : value) : 0, transformY = this._horizontal() ? 0 : value; if (value !== 0) { this._canvas.style.transform = "translate( " + transformX + "px, " + transformY + "px)"; } else { this._canvas.style.transform = ""; } this._canvasStartValue = value; } }, /// /// Gets or sets the position of the ListView's scrollbar. /// scrollPosition: { get: function () { //#DBG _ASSERT(this._lastScrollPosition >= 0); return this._currentScrollPosition; }, set: function (newPosition) { var that = this; this._batchViewUpdates(ViewChange.realize, ScrollToPriority.high, function () { return that._view.waitForValidScrollPosition(newPosition).then(function () { var max = that._viewport[that._scrollLength] - that._getViewportLength(); newPosition = utilities._clamp(newPosition, 0, max); var direction = (newPosition < that._lastScrollPosition) ? "left" : "right"; return { position: newPosition, direction: direction }; }); }, true); } }, _setRenderer: function ListView_setRenderer(newRenderer, isGroupHeaderRenderer) { var renderer; if (!newRenderer) { if (WinJS.validation) { throw new WinJS.ErrorFromName("WinJS.UI.ListView.invalidTemplate", WinJS.UI._strings.invalidTemplate); } renderer = trivialHtmlRenderer; } else if (typeof newRenderer === "function") { renderer = newRenderer; } else if (typeof newRenderer === "object") { if (WinJS.validation && !newRenderer.renderItem) { throw new WinJS.ErrorFromName("WinJS.UI.ListView.invalidTemplate", WinJS.UI._strings.invalidTemplate); } renderer = newRenderer.renderItem; } if (renderer) { if (isGroupHeaderRenderer) { this._groupHeaderRenderer = renderer; } else { this._itemRenderer = renderer; } } }, _renderWithoutReuse: function ListView_renderWithoutReuse(itemPromise, oldElement) { if (oldElement) { WinJS.Utilities._disposeElement(oldElement); } return this._itemRenderer(itemPromise); }, _isInsertedItem: function ListView_isInsertedItem(itemPromise) { return !!this._insertedItems[itemPromise.handle]; }, _clearInsertedItems: function ListView_clearInsertedItems() { var keys = Object.keys(this._insertedItems); for (var i = 0, len = keys.length; i < len; i++) { this._insertedItems[keys[i]].release(); } this._insertedItems = {}; this._modifiedElements = []; this._countDifference = 0; }, // Private methods _cancelAsyncViewWork: function (stopTreeCreation) { this._view.stopWork(stopTreeCreation); }, _updateView: function ListView_updateView() { if (this._isZombie()) { return; } var that = this; function resetCache() { that._itemsBlockExtent = -1; that._firstItemRange = null; that._firstHeaderRange = null; that._itemMargins = null; that._headerMargins = null; that._canvasMargins = null; that._cachedRTL = null; // Retrieve the values before DOM modifications occur that._rtl(); } var viewChange = this._viewChange; this._viewChange = ViewChange.realize; function functorWrapper() { that._scrollToPriority = ScrollToPriority.uninitialized; var setScrollbarPosition = that._setScrollbarPosition; that._setScrollbarPosition = false; var position = typeof that._scrollToFunctor === "number" ? { position: that._scrollToFunctor } : that._scrollToFunctor(); return Promise.as(position).then( function (scroll) { scroll = scroll || {}; if (setScrollbarPosition && +scroll.position === scroll.position) { that._lastScrollPosition = scroll.position; that._viewportScrollPosition = scroll.position; } return scroll; }, function (error) { that._setScrollbarPosition |= setScrollbarPosition; return Promise.wrapError(error); } ); } if (viewChange === ViewChange.rebuild) { if (this._pendingGroupWork) { this._updateGroupWork(); } if (this._pendingLayoutReset) { this._resetLayout(); } resetCache(); if (!this._firstTimeDisplayed) { this._view.reset(); } this._view.reload(functorWrapper, true); this._setFocusOnItem(this._selection._getFocused()); } else if (viewChange === ViewChange.remeasure) { this._view.resetItems(true); this._resetLayout(); resetCache(); this._view.refresh(functorWrapper); this._setFocusOnItem(this._selection._getFocused()); } else if (viewChange === ViewChange.relayout) { if (this._pendingLayoutReset) { this._resetLayout(); resetCache(); } this._view.refresh(functorWrapper); } else { this._view.onScroll(functorWrapper); } }, _batchViewUpdates: function ListView_batchViewUpdates(viewChange, scrollToPriority, positionFunctor, setScrollbarPosition, skipFadeout) { this._viewChange = Math.min(this._viewChange, viewChange); if (this._scrollToFunctor === null || scrollToPriority >= this._scrollToPriority) { this._scrollToPriority = scrollToPriority; this._scrollToFunctor = positionFunctor; } this._setScrollbarPosition |= !!setScrollbarPosition; if (!this._batchingViewUpdates) { this._raiseViewLoading(); var that = this; this._batchingViewUpdatesSignal = new WinJS._Signal(); this._batchingViewUpdates = Promise.any([this._batchingViewUpdatesSignal.promise, Scheduler.schedulePromiseHigh(null, "WinJS.UI.ListView._updateView")]).then(function () { if (that._isZombie()) { return; } // If we're displaying for the first time, or there were no items visible in the view, we can skip the fade out animation // and go straight to the refresh. _view.items._itemData.length is the most trustworthy way to find how many items are visible. if (that._viewChange === ViewChange.rebuild && !that._firstTimeDisplayed && Object.keys(that._view.items._itemData).length !== 0 && !skipFadeout) { return that._fadeOutViewport(); } }).then( function () { that._batchingViewUpdates = null; that._batchingViewUpdatesSignal = null; that._updateView(); that._firstTimeDisplayed = false; }, function () { that._batchingViewUpdates = null; that._batchingViewUpdatesSignal = null; } ); } return this._batchingViewUpdatesSignal; }, _resetItemCanvas: function () { // The item canvas MUST have style.position = absolute, otherwise clipping will not be done. var tabManagerEl = this._canvas; if (this._tabManager) { this._tabManager.dispose(); } this._tabManager = new WinJS.UI.TabContainer(tabManagerEl); function tabManagerHandler(eventName) { return { name: eventName, handler: function (eventObject) { that["_" + eventName](eventObject); that._mode[eventName](eventObject); }, capture: false }; } var itemCanvasEvents = [ tabManagerHandler("onTabEnter"), tabManagerHandler("onTabExit") ]; var that = this; itemCanvasEvents.forEach(function (itemCanvasEvent) { tabManagerEl.addEventListener(itemCanvasEvent.name, itemCanvasEvent.handler, false); }); this._tabManager.tabIndex = this._tabIndex; }, _resetCanvas: function () { if (this._disposed) { return; } // Layouts do not currently support saving the scroll position when forceLayout() is called. // Layouts need to recreate the canvas because the tabManager is there and you don't want to // construct 2 instances of WinJS.UI.TabContainer for the same element. var newCanvas = document.createElement('div'); newCanvas.className = this._canvas.className; this._viewport.replaceChild(newCanvas, this._canvas); this._canvas = newCanvas; this._groupsToRemove = {}; // We reset the itemCanvas on _resetCanvas in case a ListView client uses two separate custom layouts, and each layout // changes different styles on the itemCanvas without resetting it. this._canvas.appendChild(this._canvasProxy); this._resetItemCanvas(); }, _setupInternalTree: function ListView_setupInternalTree() { utilities.addClass(this._element, WinJS.UI._listViewClass); utilities[this._rtl() ? "addClass" : "removeClass"](this._element, WinJS.UI._rtlListViewClass); this._element.innerHTML = '
' + '
' + // Create a proxy element inside the canvas so that during an MSPointerDown event we can call // msSetPointerCapture on it. This allows hover to not be passed to it which saves a large invalidation. '
' + '
' + '
' + '
' + // The keyboard event helper is a dummy node that allows us to keep getting keyboard events when a virtualized element // gets discarded. It has to be positioned in the center of the viewport, though, otherwise calling .focus() on it // can move our viewport around when we don't want it moved. // The keyboard event helper element will be skipped in the tab order if it doesn't have width+height set on it. ''; this._viewport = this._element.firstElementChild; this._canvas = this._viewport.firstElementChild; this._canvasProxy = this._canvas.firstElementChild; // The deleteWrapper div is used to maintain the scroll width (after delete(s)) until the animation is done this._deleteWrapper = this._canvas.nextElementSibling; this._keyboardEventsHelper = this._viewport.nextElementSibling.firstElementChild; this._tabIndex = this._element.tabIndex !== undefined ? this._element.tabIndex : 0; this._tabEventsHelper = new WinJS.UI.TabContainer(this._keyboardEventsHelper.parentNode); this._tabEventsHelper.tabIndex = this._tabIndex; this._resetItemCanvas(); this._progressBar = document.createElement("progress"); utilities.addClass(this._progressBar, WinJS.UI._progressClass); this._progressBar.style.position = "absolute"; this._progressBar.max = 100; }, _unsetFocusOnItem: function ListView_unsetFocusOnItem(newFocusExists) { if (this._tabManager.childFocus) { this._clearFocusRectangle(this._tabManager.childFocus); } if (this._isZombie()) { return; } if (!newFocusExists) { // _setFocusOnItem may run asynchronously so prepare the keyboardEventsHelper // to receive focus. if (this._tabManager.childFocus) { this._tabManager.childFocus = null; } this._keyboardEventsHelper._shouldHaveFocus = false; this._tabEventsHelper.childFocus = this._keyboardEventsHelper; // If the viewport has focus, leave it there. This will prevent focus from jumping // from the viewport to the keyboardEventsHelper when scrolling with Narrator Touch. if (document.activeElement !== this._viewport && this._hasKeyboardFocus) { this._keyboardEventsHelper._shouldHaveFocus = true; try { this._keyboardEventsHelper.setActive(); } catch (ex) { } } } this._itemFocused = false; }, _setFocusOnItem: function ListView_setFocusOnItem(entity) { this._writeProfilerMark("_setFocusOnItem,info"); if (this._focusRequest) { this._focusRequest.cancel(); } if (this._isZombie()) { return; } var that = this; var setFocusOnItemImpl = function (item) { if (that._isZombie()) { return; } that._tabEventsHelper.childFocus = null; if (that._tabManager.childFocus !== item) { that._tabManager.childFocus = item; } that._focusRequest = null; if (that._hasKeyboardFocus && !that._itemFocused) { if (that._selection._keyboardFocused()) { that._drawFocusRectangle(item); } //#DBG _ASSERT(that._cachedCount !== WinJS.UI._UNINITIALIZED); // The requestItem promise just completed so _cachedCount will // be initialized. that._view.updateAriaForAnnouncement(item, (entity.type === WinJS.UI.ObjectType.groupHeader ? that._groups.length() : that._cachedCount)); // Some consumers of ListView listen for item invoked events and hide the listview when an item is clicked. // Since keyboard interactions rely on async operations, sometimes an invoke event can be received before we get // to item.setActive(), and the listview will be made invisible. If that happens and we call item.setActive(), an exception // is raised for trying to focus on an invisible item. Checking visibility is non-trivial, so it's best // just to catch the exception and ignore it. try { that._itemFocused = true; item.setActive(); } catch (error) { } } }; if (entity.type !== WinJS.UI.ObjectType.groupHeader) { this._focusRequest = this._view.items.requestItem(entity.index).then(setFocusOnItemImpl); } else { this._focusRequest = this._groups.requestHeader(entity.index).then(setFocusOnItemImpl); } }, _attachEvents: function ListView_attachEvents() { var that = this; function listViewHandler(eventName, caseSensitive, capture) { return { name: (caseSensitive ? eventName : eventName.toLowerCase()), handler: function (eventObject) { that["_on" + eventName](eventObject); }, capture: capture }; } function modeHandler(eventName, caseSensitive, capture) { return { capture: capture, name: (caseSensitive ? eventName : eventName.toLowerCase()), handler: function (eventObject) { var currentMode = that._mode, name = "on" + eventName; if (!that._disposed && currentMode[name]) { currentMode[name](eventObject); } } }; } function observerHandler(handlerName, attributesFilter) { return { handler: function (listOfChanges) { that["_on" + handlerName](listOfChanges); }, filter: attributesFilter }; } // Observers for specific element attribute changes var elementObservers = [ observerHandler("PropertyChange", ["dir", "style", "tabindex"]) ]; this._cachedStyleDir = this._element.style.direction; elementObservers.forEach(function (elementObserver) { new MutationObserver(elementObserver.handler).observe(that._element, { attributes: true, attributeFilter: elementObserver.filter }); }); // KeyDown handler needs to be added explicitly via addEventListener instead of using attachEvent. // If it's not added via addEventListener, the eventObject given to us on event does not have the functions stopPropagation() and preventDefault(). var events = [ modeHandler("PointerDown"), modeHandler("click", false), modeHandler("PointerUp"), modeHandler("LostPointerCapture"), modeHandler("MSHoldVisual", true), modeHandler("PointerCancel", true), modeHandler("DragStart"), modeHandler("DragOver"), modeHandler("DragEnter"), modeHandler("DragLeave"), modeHandler("Drop"), modeHandler("ContextMenu"), modeHandler("MSManipulationStateChanged", true, true) ]; events.forEach(function (eventHandler) { that._viewport.addEventListener(eventHandler.name, eventHandler.handler, !!eventHandler.capture); }); // Focus and Blur events need to be handled during the capturing phase, they do not bubble. var elementEvents = [ listViewHandler("Focus", false, true), listViewHandler("Blur", false, true), modeHandler("KeyDown"), modeHandler("KeyUp"), listViewHandler("MSElementResize", false, false) ]; elementEvents.forEach(function (eventHandler) { that._element.addEventListener(eventHandler.name, eventHandler.handler, !!eventHandler.capture); }); var viewportEvents = [ listViewHandler("MSManipulationStateChanged", true), listViewHandler("Scroll") ]; viewportEvents.forEach(function (viewportEvent) { that._viewport.addEventListener(viewportEvent.name, viewportEvent.handler, false); }); this._keyboardEventsHelper.parentNode.addEventListener("onTabEnter", this._onTabEnter.bind(this), false); this._keyboardEventsHelper.parentNode.addEventListener("onTabExit", this._onTabExit.bind(this), false); }, _updateItemsManager: function ListView_updateItemsManager() { var that = this, notificationHandler = { // Following methods are used by ItemsManager beginNotifications: function ListView_beginNotifications() { }, changed: function ListView_changed(newItem, oldItem, oldItemObject) { if (that._ifZombieDispose()) { return; } that._createUpdater(); //#DBG _ASSERT(utilities._isDOMElement(newItem)); var elementInfo = that._updater.elements[oldItem.uniqueID]; if (elementInfo) { var selected = that.selection._isIncluded(elementInfo.index); if (selected) { that._updater.updateDrag = true; } if (oldItem !== newItem) { if (that._tabManager.childFocus === oldItem || that._updater.newFocusedItem === oldItem) { that._updater.newFocusedItem = newItem; that._tabManager.childFocus = null; } if (elementInfo.itemBox) { utilities.addClass(newItem, WinJS.UI._itemClass); that._setupAriaSelectionObserver(newItem); var next = oldItem.nextElementSibling; elementInfo.itemBox.removeChild(oldItem); elementInfo.itemBox.insertBefore(newItem, next); } that._setAriaSelected(newItem, selected); that._view.items.setItemAt(elementInfo.newIndex, { element: newItem, itemBox: elementInfo.itemBox, container: elementInfo.container, itemsManagerRecord: elementInfo.itemsManagerRecord }); delete that._updater.elements[oldItem.uniqueID]; WinJS.Utilities._disposeElement(oldItem); that._updater.elements[newItem.uniqueID] = { item: newItem, container: elementInfo.container, itemBox: elementInfo.itemBox, index: elementInfo.index, newIndex: elementInfo.newIndex, itemsManagerRecord: elementInfo.itemsManagerRecord }; } else if (elementInfo.itemBox && elementInfo.container) { WinJS.UI._ItemEventsHandler.renderSelection(elementInfo.itemBox, newItem, selected, true); utilities[selected ? "addClass" : "removeClass"](elementInfo.container, WinJS.UI._selectedClass); } that._updater.changed = true; } for (var i = 0, len = that._notificationHandlers.length; i < len; i++) { that._notificationHandlers[i].changed(newItem, oldItem); } that._writeProfilerMark("changed,info"); }, removed: function ListView_removed(item, mirage, handle) { if (that._ifZombieDispose()) { return; } that._createUpdater(); function removeFromSelection(index) { that._updater.updateDrag = true; if (that._currentMode()._dragging && that._currentMode()._draggingUnselectedItem && that._currentMode()._dragInfo._isIncluded(index)) { that._updater.newDragInfo = new WinJS.UI._Selection(that, []); } var firstRange = that._updater.selectionFirst[index], lastRange = that._updater.selectionLast[index], range = firstRange || lastRange; if (range) { delete that._updater.selectionFirst[range.oldFirstIndex]; delete that._updater.selectionLast[range.oldLastIndex]; that._updater.selectionChanged = true; } } var insertedItem = that._insertedItems[handle]; if (insertedItem) { delete that._insertedItems[handle]; } var index; if (item) { var elementInfo = that._updater.elements[item.uniqueID], itemObject = that._itemsManager.itemObject(item); if (itemObject) { that._groupFocusCache.deleteItem(itemObject.key); } if (elementInfo) { index = elementInfo.index; // We track removed elements for animation purposes (layout // component consumes this). // if (elementInfo.itemBox) { that._updater.removed.push({ index: index, itemBox: elementInfo.itemBox }); } that._updater.deletesCount++; // The view can't access the data from the itemsManager // anymore, so we need to flag the itemData that it // has been removed. // var itemData = that._view.items.itemDataAt(index); itemData.removed = true; /*#DBG delete elementInfo.itemsManagerRecord.updater; #DBG*/ delete that._updater.elements[item.uniqueID]; } else { index = itemObject && itemObject.index; } if (that._updater.oldFocus.type !== WinJS.UI.ObjectType.groupHeader && that._updater.oldFocus.index === index) { that._updater.newFocus.index = index; // If index is too high, it'll be fixed in endNotifications that._updater.focusedItemRemoved = true; } removeFromSelection(index); } else { index = that._updater.selectionHandles[handle]; if (index === +index) { removeFromSelection(index); } } that._writeProfilerMark("removed(" + index + "),info"); that._updater.changed = true; }, updateAffectedRange: function ListView_updateAffectedRange(newerRange) { that._itemsCount().then(function (count) { // When we receive insertion notifications before all of the containers have // been created and the affected range is beyond the container range, the // affected range indices will not correspond to the indices of the containers // created by updateContainers. In this case, start the affected range at the end // of the containers so that the affected range includes any containers that get // appended due to this batch of notifications. var containerCount = that._view.containers ? that._view.containers.length : 0; newerRange.start = Math.min(newerRange.start, containerCount); that._affectedRange.add(newerRange, count); }); that._createUpdater(); that._updater.changed = true; }, indexChanged: function ListView_indexChanged(item, newIndex, oldIndex) { // We should receive at most one indexChanged notification per oldIndex // per notification cycle. if (that._ifZombieDispose()) { return; } that._createUpdater(); if (item) { var itemObject = that._itemsManager.itemObject(item); if (itemObject) { that._groupFocusCache.updateItemIndex(itemObject.key, newIndex); } var elementInfo = that._updater.elements[item.uniqueID]; if (elementInfo) { elementInfo.newIndex = newIndex; that._updater.changed = true; } that._updater.itemsMoved = true; } if (that._currentMode()._dragging && that._currentMode()._draggingUnselectedItem && that._currentMode()._dragInfo._isIncluded(oldIndex)) { that._updater.newDragInfo = new WinJS.UI._Selection(that, [{ firstIndex: newIndex, lastIndex: newIndex }]); that._updater.updateDrag = true; } if (that._updater.oldFocus.type !== WinJS.UI.ObjectType.groupHeader && that._updater.oldFocus.index === oldIndex) { that._updater.newFocus.index = newIndex; that._updater.changed = true; } if (that._updater.oldSelectionPivot === oldIndex) { that._updater.newSelectionPivot = newIndex; that._updater.changed = true; } var range = that._updater.selectionFirst[oldIndex]; if (range) { range.newFirstIndex = newIndex; that._updater.changed = true; that._updater.updateDrag = true; } range = that._updater.selectionLast[oldIndex]; if (range) { range.newLastIndex = newIndex; that._updater.changed = true; that._updater.updateDrag = true; } }, endNotifications: function ListView_endNotifications() { that._update(); }, inserted: function ListView_inserted(itemPromise) { if (that._ifZombieDispose()) { return; } that._writeProfilerMark("inserted,info"); that._createUpdater(); that._updater.changed = true; itemPromise.retain(); that._updater.insertsCount++; that._insertedItems[itemPromise.handle] = itemPromise; }, moved: function ListView_moved(item, previous, next, itemPromise) { if (that._ifZombieDispose()) { return; } that._createUpdater(); that._updater.movesCount++; if (item) { that._updater.itemsMoved = true; var elementInfo = that._updater.elements[item.uniqueID]; if (elementInfo) { elementInfo.moved = true; } } var index = that._updater.selectionHandles[itemPromise.handle]; if (index === +index) { that._updater.updateDrag = true; var firstRange = that._updater.selectionFirst[index], lastRange = that._updater.selectionLast[index], range = firstRange || lastRange; if (range && range.oldFirstIndex !== range.oldLastIndex) { delete that._updater.selectionFirst[range.oldFirstIndex]; delete that._updater.selectionLast[range.oldLastIndex]; that._updater.selectionChanged = true; that._updater.changed = true; } } that._writeProfilerMark("moved(" + index + "),info"); }, countChanged: function ListView_countChanged(newCount, oldCount) { if (that._ifZombieDispose()) { return; } that._writeProfilerMark("countChanged(" + newCount + "),info"); //#DBG _ASSERT(newCount !== undefined); that._cachedCount = newCount; that._createUpdater(); if ((that._view.lastIndexDisplayed + 1) === oldCount) { that._updater.changed = true; } that._updater.countDifference += newCount - oldCount; }, reload: function ListView_reload() { if (that._ifZombieDispose()) { return; } that._writeProfilerMark("reload,info"); that._processReload(); } }; function statusChanged(eventObject) { if (eventObject.detail === thisWinUI.DataSourceStatus.failure) { that.itemDataSource = null; that.groupDataSource = null; } } if (this._versionManager) { this._versionManager._dispose(); } this._versionManager = new WinJS.UI._VersionManager(); this._updater = null; var ranges = this._selection.getRanges(); this._selection._selected.clear(); if (this._itemsManager) { if (this._itemsManager.dataSource && this._itemsManager.dataSource.removeEventListener) { this._itemsManager.dataSource.removeEventListener("statuschanged", statusChanged, false); } this._clearInsertedItems(); this._itemsManager.release(); } if (this._itemsCountPromise) { this._itemsCountPromise.cancel(); this._itemsCountPromise = null; } this._cachedCount = WinJS.UI._UNINITIALIZED; this._itemsManager = thisWinUI._createItemsManager( this._dataSource, this._renderWithoutReuse.bind(this), notificationHandler, { ownerElement: this._element, versionManager: this._versionManager, indexInView: function (index) { return (index >= that.indexOfFirstVisible && index <= that.indexOfLastVisible); }, viewCallsReady: true, profilerId: this._id }); if (this._dataSource.addEventListener) { this._dataSource.addEventListener("statuschanged", statusChanged, false); } this._selection._selected.set(ranges); }, _processReload: function () { this._affectedRange.addAll(); // Inform scroll view that a realization pass is coming so that it doesn't restart the // realization pass itself. this._cancelAsyncViewWork(true); if (this._currentMode()._dragging) { this._currentMode()._clearDragProperties(); } this._groupFocusCache.clear(); this._selection._reset(); this._updateItemsManager(); this._pendingLayoutReset = true; this._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.low, this.scrollPosition); }, _createUpdater: function ListView_createUpdater() { if (!this._updater) { if (this.itemDataSource instanceof WinJS.UI.VirtualizedDataSource) { // VDS doesn't support the _updateAffectedRange notification so assume // that everything needs to be relaid out. this._affectedRange.addAll(); } this._versionManager.beginUpdating(); // Inform scroll view that a realization pass is coming so that it doesn't restart the // realization pass itself. this._cancelAsyncViewWork(); var updater = { changed: false, elements: {}, selectionFirst: {}, selectionLast: {}, selectionHandles: {}, oldSelectionPivot: { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }, newSelectionPivot: { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }, removed: [], selectionChanged: false, oldFocus: { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }, newFocus: { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }, hadKeyboardFocus: this._hasKeyboardFocus, itemsMoved: false, lastVisible: this.indexOfLastVisible, updateDrag: false, movesCount: 0, insertsCount: 0, deletesCount: 0, countDifference: 0 }; this._view.items.each(function (index, item, itemData) { /*#DBG if (itemData.itemsManagerRecord.released) { throw "ACK! found released data in items collection"; } itemData.itemsManagerRecord.updater = updater; #DBG*/ updater.elements[item.uniqueID] = { item: item, container: itemData.container, itemBox: itemData.itemBox, index: index, newIndex: index, itemsManagerRecord: itemData.itemsManagerRecord, detached: itemData.detached }; }); var selection = this._selection._selected._ranges; for (var i = 0, len = selection.length; i < len; i++) { var range = selection[i]; var newRange = { newFirstIndex: selection[i].firstIndex, oldFirstIndex: selection[i].firstIndex, newLastIndex: selection[i].lastIndex, oldLastIndex: selection[i].lastIndex }; updater.selectionFirst[newRange.oldFirstIndex] = newRange; updater.selectionLast[newRange.oldLastIndex] = newRange; updater.selectionHandles[range.firstPromise.handle] = newRange.oldFirstIndex; updater.selectionHandles[range.lastPromise.handle] = newRange.oldLastIndex; } updater.oldSelectionPivot = this._selection._pivot; updater.newSelectionPivot = updater.oldSelectionPivot; updater.oldFocus = this._selection._getFocused(); updater.newFocus = this._selection._getFocused(); this._updater = updater; } }, _synchronize: function ListView_synchronize() { var updater = this._updater; this._updater = null; var groupsChanged = this._groupsChanged; this._groupsChanged = false; /*#DBG if (updater) { for (i in updater.elements) { if (updater.elements.hasOwnProperty(i)) { var elementInfo = updater.elements[i]; delete elementInfo.itemsManagerRecord.updater; } } } #DBG*/ this._countDifference = this._countDifference || 0; if (updater && updater.changed) { if (updater.itemsMoved) { this._layout.itemsMoved && this._layout.itemsMoved(); } if (updater.removed.length) { this._layout.itemsRemoved && this._layout.itemsRemoved(updater.removed.map(function (node) { return node.itemBox; })); } if (updater.itemsMoved || updater.removed.length || Object.keys(this._insertedItems).length) { this._layout.setupAnimations && this._layout.setupAnimations(); } if (this._currentMode().onDataChanged) { this._currentMode().onDataChanged(); } var newSelection = []; for (var i in updater.selectionFirst) { if (updater.selectionFirst.hasOwnProperty(i)) { var range = updater.selectionFirst[i]; updater.selectionChanged = updater.selectionChanged || ((range.newLastIndex - range.newFirstIndex) != (range.oldLastIndex - range.oldFirstIndex)); if (range.newFirstIndex <= range.newLastIndex) { newSelection.push({ firstIndex: range.newFirstIndex, lastIndex: range.newLastIndex }); } } } if (updater.selectionChanged) { var newSelectionItems = new WinJS.UI._Selection(this, newSelection); // We do not allow listeners to cancel the selection // change because the cancellation would also have to // prevent the deletion. this._selection._fireSelectionChanging(newSelectionItems); this._selection._selected.set(newSelection); this._selection._fireSelectionChanged(); newSelectionItems.clear(); } else { this._selection._selected.set(newSelection); } this._selection._updateCount(this._cachedCount); updater.newSelectionPivot = Math.min(this._cachedCount - 1, updater.newSelectionPivot); this._selection._pivot = (updater.newSelectionPivot >= 0 ? updater.newSelectionPivot : WinJS.UI._INVALID_INDEX); if (updater.newFocus.type !== WinJS.UI.ObjectType.groupHeader) { updater.newFocus.index = Math.max(0, Math.min(this._cachedCount - 1, updater.newFocus.index)); } this._selection._setFocused(updater.newFocus, this._selection._keyboardFocused()); // If there are 2 edits before layoutAnimations runs we need to merge the 2 groups of modified elements. // For example: // If you start with A, B, C and add item Z to the beginning you will have // [ -1 -> 0, 0 -> 1, 1 -> 2, 2 -> 3] // However before layout is called an insert of Y to the beginning also happens you should get // [ -1 -> 0, -1 -> 1, 0 -> 2, 1 -> 3, 2 -> 4] var previousModifiedElements = this._modifiedElements || []; var previousModifiedElementsHash = {}; this._modifiedElements = []; this._countDifference += updater.countDifference; for (i = 0; i < previousModifiedElements.length; i++) { var modifiedElement = previousModifiedElements[i]; if (modifiedElement.newIndex === -1) { this._modifiedElements.push(modifiedElement); } else { previousModifiedElementsHash[modifiedElement.newIndex] = modifiedElement; } } for (i = 0; i < updater.removed.length; i++) { var removed = updater.removed[i]; var modifiedElement = previousModifiedElementsHash[removed.index]; if (modifiedElement) { delete previousModifiedElementsHash[removed.index]; } else { modifiedElement = { oldIndex: removed.index }; } modifiedElement.newIndex = -1; if (!modifiedElement._removalHandled) { modifiedElement._itemBox = removed.itemBox; } this._modifiedElements.push(modifiedElement); } var insertedKeys = Object.keys(this._insertedItems); for (i = 0; i < insertedKeys.length; i++) { this._modifiedElements.push({ oldIndex: -1, newIndex: this._insertedItems[insertedKeys[i]].index }); } this._writeProfilerMark("_synchronize:update_modifiedElements,StartTM"); var newItems = {}; for (i in updater.elements) { if (updater.elements.hasOwnProperty(i)) { var elementInfo = updater.elements[i]; /*#DBG if (elementInfo.itemsManagerRecord.released) { throw "ACK! attempt to put released record into list of items for ScrollView"; } #DBG*/ newItems[elementInfo.newIndex] = { element: elementInfo.item, container: elementInfo.container, itemBox: elementInfo.itemBox, itemsManagerRecord: elementInfo.itemsManagerRecord, detached: elementInfo.detached }; var modifiedElement = previousModifiedElementsHash[elementInfo.index]; if (modifiedElement) { delete previousModifiedElementsHash[elementInfo.index]; modifiedElement.newIndex = elementInfo.newIndex; } else { modifiedElement = { oldIndex: elementInfo.index, newIndex: elementInfo.newIndex }; } modifiedElement.moved = elementInfo.moved; this._modifiedElements.push(modifiedElement); } } this._writeProfilerMark("_synchronize:update_modifiedElements,StopTM"); var previousIndices = Object.keys(previousModifiedElementsHash); for (i = 0; i < previousIndices.length; i++) { var key = previousIndices[i]; var modifiedElement = previousModifiedElementsHash[key]; if (modifiedElement.oldIndex !== -1) { this._modifiedElements.push(modifiedElement); } } this._view.items._itemData = newItems; if (updater.updateDrag && this._currentMode()._dragging) { if (!this._currentMode()._draggingUnselectedItem) { this._currentMode()._dragInfo = this._selection; } else if (updater.newDragInfo) { this._currentMode()._dragInfo = updater.newDragInfo; } this._currentMode().fireDragUpdateEvent(); } // If the focused item is removed, or the item we're trying to focus on has been moved before we can focus on it, // we need to update our focus request to get the item from the appropriate index. if (updater.focusedItemRemoved || (this._focusRequest && (updater.oldFocus.index !== updater.newFocus.index) || (updater.oldFocus.type !== updater.newFocus.type))) { this._itemFocused = false; this._setFocusOnItem(this._selection._getFocused()); } else if (updater.newFocusedItem) { // We need to restore the value of _hasKeyboardFocus because a changed item // gets removed from the DOM at the time of the notification. If the item // had focus at that time, then our value of _hasKeyboardFocus will have changed. this._hasKeyboardFocus = updater.hadKeyboardFocus; this._itemFocused = false; this._setFocusOnItem(this._selection._getFocused()); } var that = this; return this._groups.synchronizeGroups().then(function () { if (updater.newFocus.type === WinJS.UI.ObjectType.groupHeader) { updater.newFocus.index = Math.min(that._groups.length() - 1, updater.newFocus.index); if (updater.newFocus.index < 0) { // An empty listview has currentFocus = item 0 updater.newFocus = { type: WinJS.UI.ObjectType.item, index: 0 }; } that._selection._setFocused(updater.newFocus, that._selection._keyboardFocused()); } that._versionManager.endUpdating(); if (updater.deletesCount > 0) { that._updateDeleteWrapperSize(); } return that._view.updateTree(that._cachedCount, that._countDifference, that._modifiedElements); }).then(function () { return that._lastScrollPosition; }); } else { this._countDifference += updater ? updater.countDifference : 0; var that = this; return this._groups.synchronizeGroups().then(function ListView_synchronizeGroups_success_groupsChanged() { updater && that._versionManager.endUpdating(); return that._view.updateTree(that._cachedCount, that._countDifference, that._modifiedElements); }).then(function () { return that.scrollPosition; }); } }, _updateDeleteWrapperSize: function ListView_updateDeleteWrapperSize(clear) { var sizeProperty = this._horizontal() ? "width" : "height"; this._deleteWrapper.style["min-" + sizeProperty] = (clear ? 0 : this.scrollPosition + this._getViewportSize()[sizeProperty]) + "px"; }, _verifyRealizationNeededForChange: function ListView_skipRealization() { // If the updater indicates that only deletes occurred, and we have not lost a viewport full of items, // we skip realizing all the items and appending new ones until other action causes a full realize (e.g. scrolling). // var skipRealization = false; var totalInViewport = (this._view.lastIndexDisplayed || 0) - (this._view.firstIndexDisplayed || 0); var deletesOnly = this._updater && this._updater.movesCount === 0 && this._updater.insertsCount === 0 && this._updater.deletesCount > 0 && (this._updater.deletesCount === Math.abs(this._updater.countDifference)); if (deletesOnly && this._updater.elements) { // Verify that the indices of the elements in the updater are within the valid range var elementsKeys = Object.keys(this._updater.elements); for (var i = 0, len = elementsKeys.length; i < len; i++) { var element = this._updater.elements[elementsKeys[i]]; var delta = element.index - element.newIndex; if (delta < 0 || delta > this._updater.deletesCount) { deletesOnly = false; break; } } } this._view.deletesWithoutRealize = this._view.deletesWithoutRealize || 0; if (deletesOnly && (this._view.lastIndexDisplayed < this._view.end - totalInViewport) && (this._updater.deletesCount + this._view.deletesWithoutRealize) < totalInViewport) { skipRealization = true; this._view.deletesWithoutRealize += Math.abs(this._updater.countDifference); this._writeProfilerMark("skipping realization on delete,info"); } else { this._view.deletesWithoutRealize = 0; } this._view._setSkipRealizationForChange(skipRealization); }, _update: function ListView_update() { this._writeProfilerMark("update,StartTM"); if (this._ifZombieDispose()) { return; } this._updateJob = null; var that = this; if (this._versionManager.noOutstandingNotifications) { if (this._updater || this._groupsChanged) { this._cancelAsyncViewWork(); this._verifyRealizationNeededForChange(); this._synchronize().then(function (scrollbarPos) { that._writeProfilerMark("update,StopTM"); that._batchViewUpdates(ViewChange.relayout, ScrollToPriority.low, scrollbarPos).complete(); }); } else { // Even if nothing important changed we need to restart aria work if it was canceled. this._batchViewUpdates(ViewChange.relayout, ScrollToPriority.low, this._lastScrollPosition).complete(); } } }, _scheduleUpdate: function ListView_scheduleUpdate() { if (!this._updateJob) { var that = this; // Batch calls to _scheduleUpdate this._updateJob = Scheduler.schedulePromiseHigh(null, "WinJS.UI.ListView._update").then(function () { if (that._updateJob) { that._update(); } }); this._raiseViewLoading(); } }, _createGroupsContainer: function () { if (this._groups) { this._groups.cleanUp(); } if (this._groupDataSource) { this._groups = new WinJS.UI._UnvirtualizedGroupsContainer(this, this._groupDataSource); } else { this._groups = new WinJS.UI._NoGroups(this); } }, _createLayoutSite: function () { var that = this; return Object.create({ invalidateLayout: function () { that._pendingLayoutReset = true; var orientationChanged = (that._layout.orientation === "horizontal") !== that._horizontalLayout; that._affectedRange.addAll(); that._batchViewUpdates(ViewChange.rebuild, ScrollToPriority.low, orientationChanged ? 0 : that.scrollPosition, false, true); }, itemFromIndex: function (itemIndex) { return that._itemsManager._itemPromiseAtIndex(itemIndex); }, groupFromIndex: function (groupIndex) { if (that._groupsEnabled()) { return groupIndex < that._groups.length() ? that._groups.group(groupIndex).userData : null; } else { return { key: "-1" }; } }, groupIndexFromItemIndex: function (itemIndex) { // If itemIndex < 0, returns 0. If itemIndex is larger than the // biggest item index, returns the last group index. itemIndex = Math.max(0, itemIndex); return that._groups.groupFromItem(itemIndex); }, renderItem: function (itemPromise) { return WinJS.Promise._cancelBlocker(that._itemsManager._itemFromItemPromise(itemPromise)).then(function (element) { if (element) { var record = that._itemsManager._recordFromElement(element); if (record.pendingReady) { record.pendingReady(); } element = element.cloneNode(true); utilities.addClass(element, WinJS.UI._itemClass); var itemBox = document.createElement("div"); utilities.addClass(itemBox, thisWinUI._itemBoxClass); itemBox.appendChild(element); var container = document.createElement("div"); utilities.addClass(container, thisWinUI._containerClass); container.appendChild(itemBox); return container; } else { return WinJS.Promise.cancel; } }); }, renderHeader: function (group) { var rendered = WinJS.UI._normalizeRendererReturn(that.groupHeaderTemplate(Promise.wrap(group))); return rendered.then(function (headerRecord) { utilities.addClass(headerRecord.element, thisWinUI._headerClass); var container = document.createElement("div"); utilities.addClass(container, thisWinUI._headerContainerClass); container.appendChild(headerRecord.element); return container; }); }, readyToMeasure: function () { that._getViewportLength(); that._getCanvasMargins(); }, _isZombie: function () { return that._isZombie(); }, _writeProfilerMark: function (text) { that._writeProfilerMark(text); } }, { _itemsManager: { enumerable: true, get: function () { return that._itemsManager; } }, rtl: { enumerable: true, get: function () { return that._rtl(); } }, surface: { enumerable: true, get: function () { return that._canvas; } }, viewport: { enumerable: true, get: function () { return that._viewport; } }, scrollbarPos: { enumerable: true, get: function () { return that.scrollPosition; } }, viewportSize: { enumerable: true, get: function () { return that._getViewportSize(); } }, loadingBehavior: { enumerable: true, get: function () { return that.loadingBehavior; } }, animationsDisabled: { enumerable: true, get: function () { return that._animationsDisabled(); } }, tree: { enumerable: true, get: function () { return that._view.tree; } }, realizedRange: { enumerable: true, get: function () { return { firstPixel: Math.max(0, that.scrollPosition - 2 * that._getViewportLength()), lastPixel: that.scrollPosition + 3 * that._getViewportLength() - 1 } } }, visibleRange: { enumerable: true, get: function () { return { firstPixel: that.scrollPosition, lastPixel: that.scrollPosition + that._getViewportLength() - 1 } } }, itemCount: { enumerable: true, get: function () { return that._itemsCount(); } }, groupCount: { enumerable: true, get: function () { return that._groups.length(); } } }); }, _initializeLayout: function () { this._affectedRange.addAll(); var layoutSite = this._createLayoutSite(); this._layout.initialize(layoutSite, this._groupsEnabled()); return this._layout.orientation === "horizontal"; }, _resetLayoutOrientation: function ListView_resetLayoutOrientation(resetScrollPosition) { if (this._horizontalLayout) { this._startProperty = "left"; this._scrollProperty = "scrollLeft"; this._scrollLength = "scrollWidth"; this._deleteWrapper.style.minHeight = ""; utilities.addClass(this._viewport, WinJS.UI._horizontalClass); utilities.removeClass(this._viewport, WinJS.UI._verticalClass); if (resetScrollPosition) { this._viewport.scrollTop = 0; } } else { this._startProperty = "top"; this._scrollProperty = "scrollTop"; this._scrollLength = "scrollHeight"; this._deleteWrapper.style.minWidth = ""; utilities.addClass(this._viewport, WinJS.UI._verticalClass); utilities.removeClass(this._viewport, WinJS.UI._horizontalClass); if (resetScrollPosition) { this._viewport.scrollLeft = 0; } } }, _resetLayout: function ListView_resetLayout() { this._pendingLayoutReset = false; this._affectedRange.addAll(); if (this._layout) { this._layout.uninitialize(); this._horizontalLayout = this._initializeLayout(); this._resetLayoutOrientation(); } }, _updateLayout: function ListView_updateLayout(layoutObject) { var hadPreviousLayout = false; if (this._layout) { // The old layout is reset here in case it was in the middle of animating when the layout got changed. Reset // will cancel out the animations. this._cancelAsyncViewWork(true); this._layout.uninitialize(); hadPreviousLayout = true; } var layoutImpl; if (layoutObject && typeof layoutObject.type === "function") { var LayoutCtor = requireSupportedForProcessing(layoutObject.type); layoutImpl = new LayoutCtor(layoutObject); } else if (layoutObject && (layoutObject.initialize)) { layoutImpl = layoutObject; } else { layoutImpl = new WinJS.UI.GridLayout(layoutObject); } hadPreviousLayout && this._resetCanvas(); this._layoutImpl = layoutImpl; this._layout = new WinJS.UI._LayoutWrapper(layoutImpl); hadPreviousLayout && this._unsetFocusOnItem(); this._setFocusOnItem({ type: WinJS.UI.ObjectType.item, index: 0 }); this._selection._setFocused({ type: WinJS.UI.ObjectType.item, index: 0 }); this._horizontalLayout = this._initializeLayout(); this._resetLayoutOrientation(hadPreviousLayout); if (hadPreviousLayout) { this._canvas.style.width = this._canvas.style.height = ""; } }, _currentMode: function ListView_currentMode() { return this._mode; }, _setSwipeClass: function ListView_setSwipeClass() { // We apply an -ms-touch-action style to block panning and swiping from occurring at the same time. It is // possible to pan in the margins between items and on lists without the swipe ability. if ((this._currentMode() instanceof WinJS.UI._SelectionMode && this._selectionAllowed() && this._swipeBehavior === WinJS.UI.SwipeBehavior.select) || this._dragSource || this._reorderable) { this._swipeable = true; utilities.addClass(this._element, WinJS.UI._swipeableClass); } else { this._swipeable = false; utilities.removeClass(this._element, WinJS.UI._swipeableClass); } var dragEnabled = (this.itemsDraggable || this.itemsReorderable), swipeSelectEnabled = (this._selectionAllowed() && this._swipeBehavior === WinJS.UI.SwipeBehavior.select), swipeEnabled = this._swipeable; this._view.items.each(function (index, item, itemData) { if (itemData.itemBox) { var dragDisabledOnItem = utilities.hasClass(item, WinJS.UI._nonDraggableClass), selectionDisabledOnItem = utilities.hasClass(item, WinJS.UI._nonSelectableClass), nonSwipeable = utilities.hasClass(itemData.itemBox, WinJS.UI._nonSwipeableClass); itemData.itemBox.draggable = (dragEnabled && !dragDisabledOnItem); if (!swipeEnabled && nonSwipeable) { utilities.removeClass(itemData.itemBox, WinJS.UI._nonSwipeableClass); } else if (swipeEnabled) { var makeNonSwipeable = (dragEnabled && !swipeSelectEnabled && dragDisabledOnItem) || (swipeSelectEnabled && !dragEnabled && selectionDisabledOnItem) || (dragDisabledOnItem && selectionDisabledOnItem); if (makeNonSwipeable && !nonSwipeable) { utilities.addClass(itemData.itemBox, WinJS.UI._nonSwipeableClass); } else if (!makeNonSwipeable && nonSwipeable) { utilities.removeClass(itemData.itemBox, WinJS.UI._nonSwipeableClass); } } } }); }, _resizeViewport: function ListView_resizeViewport() { this._viewportWidth = WinJS.UI._UNINITIALIZED; this._viewportHeight = WinJS.UI._UNINITIALIZED; }, _onMSElementResize: function ListView_onResize() { this._writeProfilerMark("_onMSElementResize,info"); Scheduler.schedule(function () { if (this._isZombie()) { return; } // If these values are uninitialized there is already a realization pass pending. if (this._viewportWidth !== WinJS.UI._UNINITIALIZED && this._viewportHeight !== WinJS.UI._UNINITIALIZED) { var newWidth = this._element.offsetWidth, newHeight = this._element.offsetHeight; if ((this._previousWidth !== newWidth) || (this._previousHeight !== newHeight)) { this._writeProfilerMark("resize (" + this._previousWidth + "x" + this._previousHeight + ") => (" + newWidth + "x" + newHeight + "),info"); this._previousWidth = newWidth; this._previousHeight = newHeight; this._resizeViewport(); var that = this; this._affectedRange.addAll(); this._batchViewUpdates(ViewChange.relayout, ScrollToPriority.low, function () { return { position: that.scrollPosition, direction: "right" }; }); } } }, Scheduler.Priority.max, this, "WinJS.UI.ListView._onMSElementResize"); }, _onFocus: function ListView_onFocus(event) { this._hasKeyboardFocus = true; var that = this; function moveFocusToItem(keyboardFocused) { that._changeFocus(that._selection._getFocused(), true, false, false, keyboardFocused); } // The keyboardEventsHelper object can get focus through three ways: We give it focus explicitly, in which case _shouldHaveFocus will be true, // or the item that should be focused isn't in the viewport, so keyboard focus could only go to our helper. The third way happens when // focus was already on the keyboard helper and someone alt tabbed away from and eventually back to the app. In the second case, we want to navigate // back to the focused item via changeFocus(). In the third case, we don't want to move focus to a real item. We differentiate between cases two and three // by checking if the flag _keyboardFocusInbound is true. It'll be set to true when the tab manager notifies us about the user pressing tab // to move focus into the listview. if (event.srcElement === this._keyboardEventsHelper) { if (!this._keyboardEventsHelper._shouldHaveFocus && this._keyboardFocusInbound) { moveFocusToItem(true); } else { this._keyboardEventsHelper._shouldHaveFocus = false; } } else if (event.srcElement === this._element) { // If someone explicitly calls .focus() on the listview element, we need to route focus to the item that should be focused moveFocusToItem(); } else { if (this._mode.inboundFocusHandled) { this._mode.inboundFocusHandled = false; return }; this._tabEventsHelper.childFocus = null; // In the event that .focus() is explicitly called on an element, we need to figure out what item got focus and set our state appropriately. var items = this._view.items, entity = {}, element = this._groups.headerFrom(event.srcElement), winItem = null; if (element) { entity.type = WinJS.UI.ObjectType.groupHeader; entity.index = this._groups.index(element); } else { entity.index = items.index(event.srcElement); entity.type = WinJS.UI.ObjectType.item; element = items.itemBoxAt(entity.index); winItem = items.itemAt(entity.index); } // In the old layouts, index will be -1 if a group header got focus if (entity.index !== WinJS.UI._INVALID_INDEX) { if (this._keyboardFocusInbound || this._selection._keyboardFocused()) { if ((entity.type === WinJS.UI.ObjectType.groupHeader && event.srcElement === element) || (entity.type === WinJS.UI.ObjectType.item && event.srcElement.parentNode === element)) { // For items we check the parentNode because the srcElement is win-item and element is win-itembox, // for header, they should both be the win-groupheader this._drawFocusRectangle(element); } } if (this._tabManager.childFocus !== element && this._tabManager.childFocus !== winItem) { //#DBG _ASSERT(entity.index !== WinJS.UI._INVALID_INDEX); this._selection._setFocused(entity, this._keyboardFocusInbound || this._selection._keyboardFocused()); this._keyboardFocusInbound = false; element = entity.type === WinJS.UI.ObjectType.groupHeader ? element : items.itemAt(entity.index); this._tabManager.childFocus = element; if (that._updater) { var elementInfo = that._updater.elements[element.uniqueID], focusIndex = entity.index; if (elementInfo && elementInfo.newIndex) { focusIndex = elementInfo.newIndex; } // Note to not set old and new focus to the same object that._updater.oldFocus = { type: entity.type, index: focusIndex }; that._updater.newFocus = { type: entity.type, index: focusIndex }; } } } } }, _onBlur: function ListView_onBlur(event) { this._hasKeyboardFocus = false; this._itemFocused = false; var element = this._view.items.itemBoxFrom(event.srcElement) || this._groups.headerFrom(event.srcElement); if (element) { this._clearFocusRectangle(element); } if (this._focusRequest) { // If we're losing focus and we had an outstanding focus request, that means the focused item isn't realized. To enable the user to tab back // into the listview, we'll make the keyboardEventsHelper tabbable for this scenario. this._tabEventsHelper.childFocus = this._keyboardEventsHelper; } }, _onMSManipulationStateChanged: function ListView_onMSManipulationStateChanged(ev) { var that = this; function done() { that._manipulationEndSignal = null; } this._manipulationState = ev.currentState; that._writeProfilerMark("_onMSManipulationStateChanged state(" + ev.currentState + "),info"); if (this._manipulationState !== MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED && !this._manipulationEndSignal) { this._manipulationEndSignal = new WinJS._Signal(); this._manipulationEndSignal.promise.done(done, done); } if (this._manipulationState === MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED) { this._manipulationEndSignal.complete(); } }, _pendingScroll: false, _onScroll: function ListView_onScroll() { if (!this._zooming && !this._pendingScroll) { this._checkScroller(); } }, _checkScroller: function ListView_checkScroller() { if (this._isZombie()) { return; } var currentScrollPosition = this._viewportScrollPosition; if (currentScrollPosition !== this._lastScrollPosition) { this._pendingScroll = requestAnimationFrame(this._checkScroller.bind(this)); var direction = (currentScrollPosition < this._lastScrollPosition) ? "left" : "right"; currentScrollPosition = Math.max(0, currentScrollPosition); this._lastScrollPosition = currentScrollPosition; this._raiseViewLoading(true); var that = this; this._view.onScroll(function () { return { position: that._lastScrollPosition, direction: direction }; }, this._manipulationEndSignal ? this._manipulationEndSignal.promise : Promise.timeout(WinJS.UI._DEFERRED_SCROLL_END)); } else { this._pendingScroll = null; } }, _onTabEnter: function ListView_onTabEnter() { this._keyboardFocusInbound = true; }, _onTabExit: function ListView_onTabExit() { this._keyboardFocusInbound = false; }, _onPropertyChange: function ListView_onPropertyChange(list) { var that = this; list.forEach(function (record) { var dirChanged = false; if (record.attributeName === "dir") { dirChanged = true; } else if (record.attributeName === "style") { dirChanged = (that._cachedStyleDir != record.target.style.direction); } if (dirChanged) { that._cachedStyleDir = record.target.style.direction; that._cachedRTL = null; utilities[that._rtl() ? "addClass" : "removeClass"](that._element, WinJS.UI._rtlListViewClass); that._lastScrollPosition = 0; that._viewportScrollPosition = 0; that.forceLayout(); } if (record.attributeName === "tabIndex") { var newTabIndex = that._element.tabIndex; if (newTabIndex >= 0) { that._view.items.each(function (index, item, itemData) { item.tabIndex = newTabIndex; }); that._tabIndex = newTabIndex; that._tabManager.tabIndex = newTabIndex; that._tabEventsHelper.tabIndex = newTabIndex; that._element.tabIndex = -1; } } }); }, _getCanvasMargins: function ListView_getCanvasMargins() { if (!this._canvasMargins) { this._canvasMargins = WinJS.UI._getMargins(this._canvas); } return this._canvasMargins; }, // Convert between canvas coordinates and viewport coordinates _convertCoordinatesByCanvasMargins: function ListView_convertCoordinatesByCanvasMargins(coordinates, conversionCallback) { function fix(field, offset) { if (coordinates[field] !== undefined) { coordinates[field] = conversionCallback(coordinates[field], offset); } } var offset; if (this._horizontal()) { offset = this._getCanvasMargins()[this._rtl() ? "right" : "left"]; fix("left", offset); } else { offset = this._getCanvasMargins().top; fix("top", offset); } fix("begin", offset); fix("end", offset); return coordinates; }, _convertFromCanvasCoordinates: function ListView_convertFromCanvasCoordinates(coordinates) { return this._convertCoordinatesByCanvasMargins(coordinates, function (coordinate, canvasMargin) { return coordinate + canvasMargin; }); }, _convertToCanvasCoordinates: function ListView_convertToCanvasCoordinates(coordinates) { return this._convertCoordinatesByCanvasMargins(coordinates, function (coordinate, canvasMargin) { return coordinate - canvasMargin; }); }, // Methods in the site interface used by ScrollView _getViewportSize: function ListView_getViewportSize() { if (this._viewportWidth === WinJS.UI._UNINITIALIZED || this._viewportHeight === WinJS.UI._UNINITIALIZED) { this._viewportWidth = Math.max(0, utilities.getContentWidth(this._element)); this._viewportHeight = Math.max(0, utilities.getContentHeight(this._element)); this._writeProfilerMark("viewportSizeDetected width:" + this._viewportWidth + " height:" + this._viewportHeight); this._previousWidth = this._element.offsetWidth; this._previousHeight = this._element.offsetHeight; } return { width: this._viewportWidth, height: this._viewportHeight }; }, _itemsCount: function ListView_itemsCount() { var that = this; function cleanUp() { that._itemsCountPromise = null; } if (this._cachedCount !== WinJS.UI._UNINITIALIZED) { return Promise.wrap(this._cachedCount); } else { var retVal; if (!this._itemsCountPromise) { retVal = this._itemsCountPromise = this._itemsManager.dataSource.getCount().then( function (count) { if (count === thisWinUI.CountResult.unknown) { count = 0; } that._cachedCount = count; that._selection._updateCount(that._cachedCount); return count; }, function () { return WinJS.Promise.cancel; } ); this._itemsCountPromise.then(cleanUp, cleanUp); } else { retVal = this._itemsCountPromise; } return retVal; } }, _isSelected: function ListView_isSelected(index) { return this._selection._isIncluded(index); }, _LoadingState: { itemsLoading: "itemsLoading", viewPortLoaded: "viewPortLoaded", itemsLoaded: "itemsLoaded", complete: "complete" }, _raiseViewLoading: function ListView_raiseViewLoading(scrolling) { if (this._loadingState !== this._LoadingState.itemsLoading) { this._scrolling = !!scrolling; } this._setViewState(this._LoadingState.itemsLoading); }, _raiseViewComplete: function ListView_raiseViewComplete() { if (!this._disposed && !this._view.animating) { this._setViewState(this._LoadingState.complete); } }, _setViewState: function ListView_setViewState(state) { if (state !== this._loadingState) { var detail = null; // We can go from any state to itemsLoading but the rest of the states transitions must follow this // order: itemsLoading -> viewPortLoaded -> itemsLoaded -> complete. // Recursively set the previous state until you hit the current state or itemsLoading. switch (state) { case this._LoadingState.viewPortLoaded: if (!this._scheduledForDispose) { scheduleForDispose(this); this._scheduledForDispose = true; } this._setViewState(this._LoadingState.itemsLoading); break; case this._LoadingState.itemsLoaded: detail = { scrolling: this._scrolling }; this._setViewState(this._LoadingState.viewPortLoaded); break; case this._LoadingState.complete: this._setViewState(this._LoadingState.itemsLoaded); this._updateDeleteWrapperSize(true); break; } this._writeProfilerMark("loadingStateChanged:" + state + ",info"); this._loadingState = state; var eventObject = document.createEvent("CustomEvent"); eventObject.initCustomEvent("loadingstatechanged", true, false, detail); this._element.dispatchEvent(eventObject); } }, _createTemplates: function ListView_createTemplates() { function createNodeWithClass(className, skipAriaHidden) { var element = document.createElement("div"); element.className = className; if (!skipAriaHidden) { element.setAttribute("aria-hidden", true); } return element; } this._itemBoxTemplate = createNodeWithClass(WinJS.UI._itemBoxClass, true); }, // Methods used by SelectionManager _updateSelection: function ListView_updateSelection() { var indices = this._selection.getIndices(), selectAll = this._selection.isEverything(), selectionMap = {}; if (!selectAll) { for (var i = 0, len = indices.length ; i < len; i++) { var index = indices[i]; selectionMap[index] = true; } } var that = this; this._view.items.each(function (index, element, itemData) { if (itemData.itemBox && !utilities.hasClass(itemData.itemBox, thisWinUI._swipeClass)) { var selected = selectAll || !!selectionMap[index]; WinJS.UI._ItemEventsHandler.renderSelection(itemData.itemBox, element, selected, true); if (itemData.container) { utilities[selected ? "addClass" : "removeClass"](itemData.container, WinJS.UI._selectedClass); } } }); }, _getViewportLength: function ListView_getViewportLength() { return this._getViewportSize()[this._horizontal() ? "width" : "height"]; }, _horizontal: function ListView_horizontal() { return this._horizontalLayout; }, _rtl: function ListView_rtl() { if (typeof this._cachedRTL !== "boolean") { this._cachedRTL = window.getComputedStyle(this._element, null).direction === "rtl"; } return this._cachedRTL; }, _showProgressBar: function ListView_showProgressBar(parent, x, y) { var progressBar = this._progressBar, progressStyle = progressBar.style; if (!progressBar.parentNode) { this._fadingProgressBar = false; if (this._progressIndicatorDelayTimer) { this._progressIndicatorDelayTimer.cancel(); } var that = this; this._progressIndicatorDelayTimer = Promise.timeout(WinJS.UI._LISTVIEW_PROGRESS_DELAY).then(function () { if (!that._isZombie()) { parent.appendChild(progressBar); AnimationHelper.fadeInElement(progressBar); that._progressIndicatorDelayTimer = null; } }); } progressStyle[this._rtl() ? "right" : "left"] = x; progressStyle.top = y; }, _hideProgressBar: function ListView_hideProgressBar() { if (this._progressIndicatorDelayTimer) { this._progressIndicatorDelayTimer.cancel(); this._progressIndicatorDelayTimer = null; } var progressBar = this._progressBar; if (progressBar.parentNode && !this._fadingProgressBar) { this._fadingProgressBar = true; var that = this; AnimationHelper.fadeOutElement(progressBar).then(function () { if (progressBar.parentNode) { progressBar.parentNode.removeChild(progressBar); } that._fadingProgressBar = false; }); } }, _getPanAxis: function () { return this._horizontal() ? "horizontal" : "vertical"; }, _configureForZoom: function (isZoomedOut, isCurrentView, triggerZoom, pagesToPrefetch) { if (WinJS.validation) { if (!this._view.realizePage || typeof this._view.begin !== "number") { throw new WinJS.ErrorFromName("WinJS.UI.ListView.NotCompatibleWithSemanticZoom", strings.notCompatibleWithSemanticZoom); } } this._isZoomedOut = isZoomedOut; this._disableEntranceAnimation = !isCurrentView; this._isCurrentZoomView = isCurrentView; this._triggerZoom = triggerZoom; }, _setCurrentItem: function (x, y) { // First, convert the position into canvas coordinates if (this._rtl()) { x = this._viewportWidth - x; } if (this._horizontal()) { x += this.scrollPosition; } else { y += this.scrollPosition; } var result = this._view.hitTest(x, y), entity = { type: result.type ? result.type : WinJS.UI.ObjectType.item, index: result.index }; if (entity.index >= 0) { if (this._hasKeyboardFocus) { this._changeFocus(entity, true, false, true); } else { this._changeFocusPassively(entity); } } }, _getCurrentItem: function () { var focused = this._selection._getFocused(); if (focused.type === WinJS.UI.ObjectType.groupHeader) { focused = { type: WinJS.UI.ObjectType.item, index: this._groups.group(focused.index).startIndex }; } if (typeof focused.index !== "number") { // Do a hit-test in the viewport center this._setCurrentItem(0.5 * this._viewportWidth, 0.5 * this._viewportHeight); focused = this._selection._getFocused(); } var that = this; var promisePosition = this._getItemOffsetPosition(focused.index). then(function (posCanvas) { var scrollOffset = that._canvasStart; posCanvas[that._startProperty] += scrollOffset; return posCanvas; }); return Promise.join({ item: this._dataSource.itemFromIndex(focused.index), position: promisePosition }); }, _beginZoom: function () { this._zooming = true; // Hide the scrollbar and extend the content beyond the ListView viewport var horizontal = this._horizontal(), scrollOffset = -this.scrollPosition; utilities.addClass(this._viewport, horizontal ? WinJS.UI._zoomingXClass : WinJS.UI._zoomingYClass); this._canvasStart = scrollOffset; utilities.addClass(this._viewport, horizontal ? WinJS.UI._zoomingYClass : WinJS.UI._zoomingXClass); }, _positionItem: function (item, position) { var that = this; function positionItemAtIndex(index) { return that._getItemOffsetPosition(index).then(function positionItemAtIndex_then_ItemOffsetPosition(posCanvas) { var horizontal = that._horizontal(), canvasMargins = that._getCanvasMargins(), canvasSize = that._canvas[horizontal ? "offsetWidth" : "offsetHeight"] + canvasMargins[(horizontal ? (that._rtl() ? "right" : "left") : "top")], viewportSize = (horizontal ? that._viewportWidth : that._viewportHeight), scrollPosition; // Align the leading edge var start = position[that._startProperty], startMax = viewportSize - (horizontal ? posCanvas.width : posCanvas.height); // Ensure the item ends up within the viewport start = Math.max(0, Math.min(startMax, start)); scrollPosition = posCanvas[that._startProperty] - start; // Ensure the scroll position is valid var adjustedScrollPosition = Math.max(0, Math.min(canvasSize - viewportSize, scrollPosition)), scrollAdjustment = adjustedScrollPosition - scrollPosition; scrollPosition = adjustedScrollPosition; // Since a zoom is in progress, adjust the div position var scrollOffset = -scrollPosition; that._canvasStart = scrollOffset; var entity = { type: WinJS.UI.ObjectType.item, index: index } if (that._hasKeyboardFocus) { that._changeFocus(entity, true); } else { that._changeFocusPassively(entity); } that._raiseViewLoading(true); that._view.realizePage(scrollPosition, true); return ( horizontal ? { x: scrollAdjustment, y: 0 } : { x: 0, y: scrollAdjustment } ); }); } var itemIndex = 0; if (item) { itemIndex = (this._isZoomedOut ? item.groupIndexHint : item.firstItemIndexHint); } if (typeof itemIndex === "number") { return positionItemAtIndex(itemIndex); } else { // We'll need to obtain the index from the data source var itemPromise; var key = (this._isZoomedOut ? item.groupKey : item.firstItemKey); if (typeof key === "string" && this._dataSource.itemFromKey) { itemPromise = this._dataSource.itemFromKey(key, (this._isZoomedOut ? { groupMemberKey: item.key, groupMemberIndex: item.index } : null)); } else { var description = (this._isZoomedOut ? item.groupDescription : item.firstItemDescription); if (WinJS.validation) { if (description === undefined) { throw new WinJS.ErrorFromName("WinJS.UI.ListView.InvalidItem", strings.listViewInvalidItem); } } itemPromise = this._dataSource.itemFromDescription(description); } return itemPromise.then(function (item) { return positionItemAtIndex(item.index); }); } }, _endZoom: function (isCurrentView) { if (this._isZombie()) { return; } // Crop the content again and re-enable the scrollbar var horizontal = this._horizontal(), scrollOffset = this._canvasStart; utilities.removeClass(this._viewport, WinJS.UI._zoomingYClass); utilities.removeClass(this._viewport, WinJS.UI._zoomingXClass); this._canvasStart = 0; this._viewportScrollPosition = -scrollOffset; this._disableEntranceAnimation = !isCurrentView; this._isCurrentZoomView = isCurrentView; this._zooming = false; this._view.realizePage(this.scrollPosition, false); }, _getItemOffsetPosition: function (index) { var that = this; return this._getItemOffset({ type: WinJS.UI.ObjectType.item, index: index }).then(function (position) { return that._ensureFirstColumnRange(WinJS.UI.ObjectType.item).then(function () { position = that._correctRangeInFirstColumn(position, WinJS.UI.ObjectType.item); position = that._convertFromCanvasCoordinates(position); if (that._horizontal()) { position.left = position.begin; position.width = position.end - position.begin; position.height = position.totalHeight; } else { position.top = position.begin; position.height = position.end - position.begin; position.width = position.totalWidth; } return position; }); }); }, _groupRemoved: function (key) { this._groupFocusCache.deleteGroup(key); }, _updateFocusCache: function (itemIndex) { if (this._updateFocusCacheItemRequest) { this._updateFocusCacheItemRequest.cancel(); } var that = this; this._updateFocusCacheItemRequest = this._view.items.requestItem(itemIndex).then(function (item) { that._updateFocusCacheItemRequest = null; var itemData = that._view.items.itemDataAt(itemIndex); var groupIndex = that._groups.groupFromItem(itemIndex); var groupKey = that._groups.group(groupIndex).key; if (itemData.itemsManagerRecord.item) { that._groupFocusCache.updateCache(groupKey, itemData.itemsManagerRecord.item.key, itemIndex); } }); }, _changeFocus: function (newFocus, skipSelection, ctrlKeyDown, skipEnsureVisible, keyboardFocused) { //#DBG _ASSERT(newFocus.index !== -1); if (this._isZombie()) { return; } var targetItem; if (newFocus.type !== WinJS.UI.ObjectType.groupHeader) { targetItem = this._view.items.itemAt(newFocus.index); if (!skipSelection && targetItem && utilities.hasClass(targetItem, WinJS.UI._nonSelectableClass)) { skipSelection = true; } this._updateFocusCache(newFocus.index); } else { var group = this._groups.group(newFocus.index); targetItem = group && group.header; } this._unsetFocusOnItem(!!targetItem); this._hasKeyboardFocus = true; this._selection._setFocused(newFocus, keyboardFocused); if (!skipEnsureVisible) { this.ensureVisible(newFocus); } // _selection.set() needs to know which item has focus so we // must call it after _selection._setFocused() has been called. if (!skipSelection && this._selectFocused(ctrlKeyDown)) { this._selection.set(newFocus.index); } this._setFocusOnItem(newFocus); }, // Updates ListView's internal focus state and, if ListView currently has focus, moves // Trident's focus to the item at index newFocus. // Similar to _changeFocus except _changeFocusPassively doesn't: // - ensure the item is selected or visible // - set Trident's focus to newFocus when ListView doesn't have focus _changeFocusPassively: function (newFocus) { //#DBG _ASSERT(newFocus.index !== -1); var targetItem; if (newFocus.type !== WinJS.UI.ObjectType.groupHeader) { targetItem = this._view.items.itemAt(newFocus.index); this._updateFocusCache(newFocus.index); } else { var group = this._groups.group(newFocus.index); targetItem = group && group.header; } this._unsetFocusOnItem(!!targetItem); this._selection._setFocused(newFocus); this._setFocusOnItem(newFocus); }, _drawFocusRectangle: function (item) { if (WinJS.Utilities.hasClass(item, thisWinUI._headerClass)) { WinJS.Utilities.addClass(item, thisWinUI._itemFocusClass); } else { var itemBox = this._view.items.itemBoxFrom(item); //#DBG _ASSERT(utilities.hasClass(itemBox, WinJS.UI._itemBoxClass)); if (itemBox.querySelector("." + thisWinUI._itemFocusOutlineClass)) { return; } utilities.addClass(itemBox, thisWinUI._itemFocusClass); var outline = document.createElement("div"); outline.className = thisWinUI._itemFocusOutlineClass; itemBox.appendChild(outline); } }, _clearFocusRectangle: function (item) { if (!item || this._isZombie()) { return; } var itemBox = this._view.items.itemBoxFrom(item); if (itemBox) { utilities.removeClass(itemBox, thisWinUI._itemFocusClass); //#DBG _ASSERT(utilities.hasClass(itemBox, WinJS.UI._itemBoxClass)); var outline = itemBox.querySelector("." + thisWinUI._itemFocusOutlineClass); if (outline) { outline.parentNode.removeChild(outline); } } else { var header = this._groups.headerFrom(item); if (header) { utilities.removeClass(header, thisWinUI._itemFocusClass); } } }, _defaultInvoke: function (entity) { if (this._isZoomedOut) { this._changeFocusPassively(entity); this._triggerZoom(); } }, _selectionAllowed: function ListView_selectionAllowed(itemIndex) { var item = (itemIndex !== undefined ? this.elementFromIndex(itemIndex) : null), itemSelectable = !(item && utilities.hasClass(item, WinJS.UI._nonSelectableClass)); return itemSelectable && this._selectionMode !== WinJS.UI.SelectionMode.none; }, _multiSelection: function ListView_multiSelection() { return this._selectionMode === WinJS.UI.SelectionMode.multi; }, _selectOnTap: function ListView_selectOnTap() { return this._tap === WinJS.UI.TapBehavior.toggleSelect || this._tap === WinJS.UI.TapBehavior.directSelect; }, _selectFocused: function ListView_selectFocused(ctrlKeyDown) { return this._tap === WinJS.UI.TapBehavior.directSelect && this._selectionMode === WinJS.UI.SelectionMode.multi && !ctrlKeyDown; }, _dispose: function () { if (!this._disposed) { this._disposed = true; var clear = function clear(e) { e && (e.innerText = ""); } this._batchingViewUpdates && this._batchingViewUpdates.cancel(); this._view && this._view._dispose && this._view._dispose(); this._mode && this._mode._dispose && this._mode._dispose(); this._groups && this._groups._dispose && this._groups._dispose(); this._selection && this._selection._dispose && this._selection._dispose(); this._layout && this._layout.uninitialize && this._layout.uninitialize(); this._itemsCountPromise && this._itemsCountPromise.cancel(); this._versionManager && this._versionManager._dispose(); this._clearInsertedItems(); this._itemsManager && this._itemsManager.release(); clear(this._viewport); clear(this._canvas); clear(this._canvasProxy); this._versionManager = null; this._view = null; this._mode = null; this._element = null; this._viewport = null; this._itemsManager = null; this._canvas = null; this._canvasProxy = null; this._itemsCountPromise = null; this._scrollToFunctor = null; var index = controlsToDispose.indexOf(this); if (index >= 0) { controlsToDispose.splice(index, 1); } } }, _isZombie: function () { // determines if this ListView is no longer in the DOM or has been cleared // return this._disposed || !(this.element.firstElementChild && document.body.contains(this.element)); }, _ifZombieDispose: function () { var zombie = this._isZombie(); if (zombie && !this._disposed) { scheduleForDispose(this); } return zombie; }, _animationsDisabled: function () { if (this._viewportWidth === 0 || this._viewportHeight === 0) { return true; } return !WinJS.UI.isAnimationEnabled(); }, _fadeOutViewport: function ListView_fadeOutViewport() { var that = this; return new Promise(function (complete) { if (that._animationsDisabled()) { complete(); return; } if (!that._fadingViewportOut) { if (that._waitingEntranceAnimationPromise) { that._waitingEntranceAnimationPromise.cancel(); that._waitingEntranceAnimationPromise = null; } var eventDetails = that._fireAnimationEvent(WinJS.UI.ListViewAnimationType.contentTransition); that._firedAnimationEvent = true; if (!eventDetails.prevented) { that._fadingViewportOut = true; that._viewport.style["-ms-overflow-style"] = "none"; AnimationHelper.fadeOutElement(that._viewport).then(function () { if (that._isZombie()) { return; } that._fadingViewportOut = false; that._viewport.style.opacity = 1.0; complete(); }); } else { that._disableEntranceAnimation = true; that._viewport.style.opacity = 1.0; complete(); } } }); }, _animateListEntrance: function (firstTime) { var eventDetails = { prevented: false, animationPromise: Promise.wrap() }; var that = this; function resetViewOpacity() { that._canvas.style.opacity = 1; that._viewport.style["-ms-overflow-style"] = ""; } if (this._disableEntranceAnimation || this._animationsDisabled()) { resetViewOpacity(); if (this._waitingEntranceAnimationPromise) { this._waitingEntranceAnimationPromise.cancel(); this._waitingEntranceAnimationPromise = null; } return Promise.wrap(); } if (!this._firedAnimationEvent) { eventDetails = this._fireAnimationEvent(WinJS.UI.ListViewAnimationType.entrance); } else { this._firedAnimationEvent = false; } if (eventDetails.prevented) { resetViewOpacity(); return Promise.wrap(); } else { if (this._waitingEntranceAnimationPromise) { this._waitingEntranceAnimationPromise.cancel(); } this._canvas.style.opacity = 0; this._viewport.style["-ms-overflow-style"] = "none"; this._waitingEntranceAnimationPromise = eventDetails.animationPromise.then(function () { if (!that._isZombie()) { that._canvas.style.opacity = 1; return AnimationHelper.animateEntrance(that._viewport, firstTime).then(function () { if (!that._isZombie()) { that._viewport.style["-ms-overflow-style"] = ""; that._waitingEntranceAnimationPromise = null; } }); } }); return this._waitingEntranceAnimationPromise; } }, _fireAnimationEvent: function (type) { var animationEvent = document.createEvent("CustomEvent"), animationPromise = Promise.wrap(); animationEvent.initCustomEvent("contentanimating", true, true, { type: type }); if (type === WinJS.UI.ListViewAnimationType.entrance) { animationEvent.detail.setPromise = function (delayPromise) { animationPromise = delayPromise; }; } var prevented = !this._element.dispatchEvent(animationEvent); return { prevented: prevented, animationPromise: animationPromise } }, // If they don't yet exist, create the start and end markers which are required // by Narrator's aria-flowto/flowfrom implementation. They mark the start and end // of ListView's set of out-of-order DOM elements and so they must surround the // headers and groups in the DOM. _createAriaMarkers: function ListView_createAriaMarkers() { if (!this._viewport.getAttribute("aria-label")) { this._viewport.setAttribute("aria-label", strings.listViewViewportAriaLabel); } if (!this._ariaStartMarker) { this._ariaStartMarker = document.createElement("div"); this._ariaStartMarker.id = this._ariaStartMarker.uniqueID; this._viewport.insertBefore(this._ariaStartMarker, this._viewport.firstElementChild); } if (!this._ariaEndMarker) { this._ariaEndMarker = document.createElement("div"); this._ariaEndMarker.id = this._ariaEndMarker.uniqueID; this._viewport.appendChild(this._ariaEndMarker); } }, // If the ListView is in static mode, then the roles of the list and items should be "list" and "listitem", respectively. // Otherwise, the roles should be "listbox" and "option." If the ARIA roles are out of sync with the ListView's // static/interactive state, update the role of the ListView and the role of each realized item. _updateItemsAriaRoles: function ListView_updateItemsAriaRoles() { var that = this; var listRole = this._element.getAttribute("role"), expectedListRole, expectedItemRole; if (this._currentMode().staticMode()) { expectedListRole = "list"; expectedItemRole = "listitem"; } else { expectedListRole = "listbox"; expectedItemRole = "option"; } if (listRole !== expectedListRole || this._itemRole !== expectedItemRole) { this._element.setAttribute("role", expectedListRole); this._itemRole = expectedItemRole; this._view.items.each(function (index, itemElement, itemData) { itemElement.setAttribute("role", that._itemRole); }); } }, _updateGroupHeadersAriaRoles: function ListView_updateGroupHeadersAriaRoles() { var that = this, headerRole = (this.groupHeaderTapBehavior === WinJS.UI.GroupHeaderTapBehavior.none ? "separator" : "link"); if (this._headerRole !== headerRole) { this._headerRole = headerRole; for (var i = 0, len = this._groups.length() ; i < len; i++) { var header = this._groups.group(i).header; if (header) { header.setAttribute("role", this._headerRole); } } } }, // Avoids unnecessary UIA selection events by only updating aria-selected if it has changed _setAriaSelected: function ListView_setAriaSelected(itemElement, isSelected) { var ariaSelected = (itemElement.getAttribute("aria-selected") === "true"); if (isSelected !== ariaSelected) { itemElement.setAttribute("aria-selected", isSelected); } }, _setupAriaSelectionObserver: function ListView_setupAriaSelectionObserver(item) { if (!item._mutationObserver) { this._mutationObserver.observe(item, { attributes: true, attributeFilter: ["aria-selected"] }); item._mutationObserver = true; } }, _itemPropertyChange: function ListView_itemPropertyChange(list) { if (this._isZombie()) { return; } var that = this; var singleSelection = that._selectionMode === WinJS.UI.SelectionMode.single; var changedItems = []; var unselectableItems = []; function revertAriaSelected(items) { items.forEach(function (entry) { entry.item.setAttribute("aria-selected", !entry.selected); }); } for (var i = 0, len = list.length; i < len; i++) { var item = list[i].target; var itemBox = that._view.items.itemBoxFrom(item); var selected = item.getAttribute("aria-selected") === "true"; // Only respond to aria-selected changes coming from UIA. This check // relies on the fact that, in renderSelection, we update the selection // visual before aria-selected. if (itemBox && (selected !== WinJS.UI._isSelectionRendered(itemBox))) { var index = that._view.items.index(itemBox); var entry = { index: index, item: item, selected: selected }; (that._selectionAllowed(index) ? changedItems : unselectableItems).push(entry); } } if (changedItems.length > 0) { var signal = new WinJS._Signal(); that.selection._synchronize(signal).then(function () { var newSelection = that.selection._cloneSelection(); changedItems.forEach(function (entry) { if (entry.selected) { newSelection[singleSelection ? "set" : "add"](entry.index); } else { newSelection.remove(entry.index); } }); return that.selection._set(newSelection); }).then(function (approved) { if (!that._isZombie() && !approved) { // A selectionchanging event handler rejected the selection change revertAriaSelected(changedItems); } signal.complete(); }); } revertAriaSelected(unselectableItems); }, _groupsEnabled: function () { return !!this._groups.groupDataSource; }, _getItemPosition: function ListView_getItemPosition(entity, preserveItemsBlocks) { var that = this; return this._view.waitForEntityPosition(entity).then(function () { var container = (entity.type === WinJS.UI.ObjectType.groupHeader ? that._view._getHeaderContainer(entity.index) : that._view.getContainer(entity.index)); if (container) { that._writeProfilerMark("WinJS.UI.ListView:getItemPosition,info"); if (that._view._expandedRange) { var itemsBlockFrom = that._view._expandedRange.first.index, itemsBlockTo = that._view._expandedRange.last.index; } else { preserveItemsBlocks = false; } if (entity.type === WinJS.UI.ObjectType.item) { preserveItemsBlocks = !!preserveItemsBlocks; preserveItemsBlocks &= that._view._ensureContainerInDOM(entity.index); } else { preserveItemsBlocks = false; } var margins = that._getItemMargins(entity.type), position = { left: (that._rtl() ? getOffsetRight(container) - margins.right : container.offsetLeft - margins.left), top: container.offsetTop - margins.top, totalWidth: utilities.getTotalWidth(container), totalHeight: utilities.getTotalHeight(container), contentWidth: utilities.getContentWidth(container), contentHeight: utilities.getContentHeight(container) }; if (preserveItemsBlocks) { that._view._forceItemsBlocksInDOM(itemsBlockFrom, itemsBlockTo + 1); } // When a translation is applied to the surface during zooming, offsetLeft includes the canvas margins, so the left/top position will already be in canvas coordinates. // If we're not zooming, we need to convert the position to canvas coordinates before returning. return (that._zooming && that._canvasStart !== 0 ? position : that._convertToCanvasCoordinates(position)); } else { return WinJS.Promise.cancel; } }); }, _getItemOffset: function ListView_getItemOffset(entity, preserveItemsBlocks) { var that = this; return this._getItemPosition(entity, preserveItemsBlocks).then(function (pos) { // _getItemOffset also includes the right/bottom margin of the previous row/column of items, so that ensureVisible/indexOfFirstVisible will jump such that // the previous row/column is directly offscreen of the target item. var margins = that._getItemMargins(entity.type); if (that._horizontal()) { var rtl = that._rtl(); pos.begin = pos.left - margins[rtl ? "left" : "right"], pos.end = pos.left + pos.totalWidth + margins[rtl ? "right" : "left"] } else { pos.begin = pos.top - margins.bottom, pos.end = pos.top + pos.totalHeight + margins.top } return pos; }); }, _getItemMargins: function ListView_getItemMargins(type) { type = type || WinJS.UI.ObjectType.item; var that = this; var calculateMargins = function (className) { var item = that._canvas.querySelector("." + className), cleanup; if (!item) { item = document.createElement("div"), utilities.addClass(item, className); that._viewport.appendChild(item); cleanup = true; } var margins = WinJS.UI._getMargins(item); if (cleanup) { that._viewport.removeChild(item); } return margins; }; if (type !== WinJS.UI.ObjectType.groupHeader) { return (this._itemMargins ? this._itemMargins : (this._itemMargins = calculateMargins(WinJS.UI._containerClass))); } else { return (this._headerMargins ? this._headerMargins : (this._headerMargins = calculateMargins(WinJS.UI._headerContainerClass))); } }, _fireAccessibilityAnnotationCompleteEvent: function ListView_fireAccessibilityAnnotationCompleteEvent(firstIndex, lastIndex, firstHeaderIndex, lastHeaderIndex) { // This event is fired in these cases: // - When the data source count is 0, it is fired after the aria markers have been // updated. The event detail will be { firstIndex: -1, lastIndex: -1 }. // - When the data source count is non-zero, it is fired after the aria markers // have been updated and the deferred work for the aria properties on the items // has completed. // - When an item gets focus. The event will be { firstIndex: indexOfItem, lastIndex: indexOfItem }. var detail = { firstIndex: firstIndex, lastIndex: lastIndex, firstHeaderIndex: (+firstHeaderIndex) || -1, lastHeaderIndex: (+lastHeaderIndex) || -1 } var eventObject = document.createEvent("CustomEvent"); eventObject.initCustomEvent("accessibilityannotationcomplete", true, false, detail); this._element.dispatchEvent(eventObject); }, _ensureFirstColumnRange: function ListView_ensureFirstColumnRange(type) { var propName = (type === WinJS.UI.ObjectType.item ? "_firstItemRange" : "_firstHeaderRange"); if (!this[propName]) { var that = this; return this._getItemOffset({ type: type, index: 0 }, true).then(function (firstRange) { that[propName] = firstRange; }); } else { return Promise.wrap(); } }, _correctRangeInFirstColumn: function ListView_correctRangeInFirstColumn(range, type) { var firstRange = (type === WinJS.UI.ObjectType.groupHeader ? this._firstHeaderRange : this._firstItemRange); if (firstRange.begin === range.begin) { if (this._horizontal()) { range.begin = -this._getCanvasMargins()[this._rtl() ? "right" : "left"]; } else { range.begin = -this._getCanvasMargins().top; } } return range; }, _updateContainers: function ListView_updateContainers(groups, count, containersDelta, modifiedElements) { var that = this; var maxContainers = this._view.containers.length + (containersDelta > 0 ? containersDelta : 0); var newTree = []; var newKeyToGroupIndex = {}; var newContainers = []; var removedContainers = []; function createContainer() { var element = document.createElement("div"); element.className = WinJS.UI._containerClass; return element; } function updateExistingGroupWithBlocks(groupNode, firstItem, newSize) { if (firstItem + newSize > maxContainers) { newSize = maxContainers - firstItem; } var itemsContainer = groupNode.itemsContainer, blocks = itemsContainer.itemsBlocks, lastBlock = blocks.length ? blocks[blocks.length - 1] : null, currentSize = blocks.length ? (blocks.length - 1) * that._view._blockSize + lastBlock.items.length : 0, delta = newSize - currentSize, oldSize, children; if (delta > 0) { if (lastBlock && lastBlock.items.length < that._view._blockSize) { var toAdd = Math.min(delta, that._view._blockSize - lastBlock.items.length); utilities.insertAdjacentHTMLUnsafe(lastBlock.element, "beforeend", WinJS.UI._repeat("
", toAdd)); oldSize = lastBlock.items.length; children = lastBlock.element.children; for (var j = 0; j < toAdd; j++) { lastBlock.items.push(children[oldSize + j]); } delta -= toAdd; } var blocksCount = Math.floor(delta / that._view._blockSize), lastBlockSize = delta % that._view._blockSize; var blockMarkup = "
" + WinJS.UI._repeat("
", that._view._blockSize) + "
", markup = WinJS.UI._repeat(blockMarkup, blocksCount); if (lastBlockSize) { markup += "
" + WinJS.UI._repeat("
", lastBlockSize) + "
"; blocksCount++; } var blocksTemp = document.createElement("div"); utilities.setInnerHTMLUnsafe(blocksTemp, markup); var children = blocksTemp.children; for (var j = 0; j < blocksCount; j++) { var block = children[j], blockNode = { element: block, items: WinJS.UI._nodeListToArray(block.children) }; itemsContainer.itemsBlocks.push(blockNode); } } else if (delta < 0) { for (var n = delta; n < 0; n++) { var container = lastBlock.items.pop(); if (!that._view._requireFocusRestore && container.contains(document.activeElement)) { that._view._requireFocusRestore = document.activeElement; that._unsetFocusOnItem(); } lastBlock.element.removeChild(container); removedContainers.push(container); if (!lastBlock.items.length) { if (itemsContainer.element === lastBlock.element.parentNode) { itemsContainer.element.removeChild(lastBlock.element); } blocks.pop(); lastBlock = blocks[blocks.length - 1]; } } } for (var j = 0, len = blocks.length; j < len; j++) { var block = blocks[j]; for (var n = 0; n < block.items.length; n++) { newContainers.push(block.items[n]); } } } function addInserted(groupNode, firstItemIndex, newSize) { var added = modifiedElements.filter(function (entry) { return (entry.oldIndex === -1 && entry.newIndex >= firstItemIndex && entry.newIndex < (firstItemIndex + newSize)); }).sort(function (left, right) { return left.newIndex - right.newIndex; }); var itemsContainer = groupNode.itemsContainer; for (var i = 0, len = added.length; i < len; i++) { var entry = added[i], offset = entry.newIndex - firstItemIndex; var container = createContainer(), next = offset < itemsContainer.items.length ? itemsContainer.items[offset] : null; itemsContainer.items.splice(offset, 0, container); itemsContainer.element.insertBefore(container, next); } } function updateExistingGroup(groupNode, firstItem, newSize) { if (firstItem + newSize > maxContainers) { newSize = maxContainers - firstItem; } var itemsContainer = groupNode.itemsContainer, delta = newSize - itemsContainer.items.length; if (delta > 0) { var children = itemsContainer.element.children, oldSize = children.length; utilities.insertAdjacentHTMLUnsafe(itemsContainer.element, "beforeend", WinJS.UI._repeat("
", delta)); for (var n = 0; n < delta; n++) { var container = children[oldSize + n]; itemsContainer.items.push(container); } } for (var n = delta; n < 0; n++) { var container = itemsContainer.items.pop(); itemsContainer.element.removeChild(container); removedContainers.push(container); } for (var n = 0, len = itemsContainer.items.length; n < len; n++) { newContainers.push(itemsContainer.items[n]); } } function addNewGroup(groupInfo, firstItem) { var header = that._view._createHeaderContainer(prevElement); var groupNode = { header: header, itemsContainer: { element: that._view._createItemsContainer(header), } }; groupNode.itemsContainer[that._view._blockSize ? "itemsBlocks" : "items"] = []; if (that._view._blockSize) { updateExistingGroupWithBlocks(groupNode, firstItem, groupInfo.size); } else { updateExistingGroup(groupNode, firstItem, groupInfo.size); } return groupNode; } function shift(groupNode, oldFirstItemIndex, currentFirstItemIndex, newSize) { var currentLast = currentFirstItemIndex + newSize - 1, firstShifted, delta; for (var i = 0, len = modifiedElements.length; i < len; i++) { var entry = modifiedElements[i]; if (entry.newIndex >= currentFirstItemIndex && entry.newIndex <= currentLast && entry.oldIndex !== -1) { if (firstShifted !== +firstShifted || entry.newIndex < firstShifted) { firstShifted = entry.newIndex; delta = entry.newIndex - entry.oldIndex; } } } if (firstShifted === +firstShifted) { var addedBeforeShift = 0; for (i = 0, len = modifiedElements.length; i < len; i++) { var entry = modifiedElements[i]; if (entry.newIndex >= currentFirstItemIndex && entry.newIndex < firstShifted && entry.oldIndex === -1) { addedBeforeShift++; } } var removedBeforeShift = 0, oldFirstShifted = firstShifted - delta; for (i = 0, len = modifiedElements.length; i < len; i++) { var entry = modifiedElements[i]; if (entry.oldIndex >= oldFirstItemIndex && entry.oldIndex < oldFirstShifted && entry.newIndex === -1) { removedBeforeShift++; } } delta += removedBeforeShift; delta -= addedBeforeShift; delta -= currentFirstItemIndex - oldFirstItemIndex; var itemsContainer = groupNode.itemsContainer; if (delta > 0) { var children = itemsContainer.element.children, oldSize = children.length; utilities.insertAdjacentHTMLUnsafe(itemsContainer.element, "afterBegin", WinJS.UI._repeat("
", delta)); for (var n = 0; n < delta; n++) { var container = children[n]; itemsContainer.items.splice(n, 0, container); } } for (var n = delta; n < 0; n++) { var container = itemsContainer.items.shift(); itemsContainer.element.removeChild(container); } if (delta) { // Invalidate the layout of the entire group because we do not know the exact indices which were added/modified since they were before the realization range. that._affectedRange.add({ start: currentFirstItemIndex, end: currentFirstItemIndex + newSize }, count); } } } function flatIndexToGroupIndex(index) { var firstItem = 0; for (var i = 0, len = that._view.tree.length; i < len; i++) { var group = that._view.tree[i], size = group.itemsContainer.items.length, lastItem = firstItem + size - 1; if (index >= firstItem && index <= lastItem) { return { group: i, item: index - firstItem }; } firstItem += size; } } var oldFirstItem = []; var firstItem = 0; if (!that._view._blockSize) { for (var i = 0, len = this._view.tree.length; i < len; i++) { oldFirstItem.push(firstItem); firstItem += this._view.tree[i].itemsContainer.items.length; } } if (!that._view._blockSize) { var removed = modifiedElements.filter(function (entry) { return entry.newIndex === -1 && !entry._removalHandled; }).sort(function (left, right) { return right.oldIndex - left.oldIndex; }); for (var i = 0, len = removed.length; i < len; i++) { var entry = removed[i]; entry._removalHandled = true; var itemBox = entry._itemBox; entry._itemBox = null; var groupIndex = flatIndexToGroupIndex(entry.oldIndex); var group = this._view.tree[groupIndex.group]; var container = group.itemsContainer.items[groupIndex.item]; container.parentNode.removeChild(container); if (utilities.hasClass(itemBox, WinJS.UI._selectedClass)) { utilities.addClass(container, WinJS.UI._selectedClass); } group.itemsContainer.items.splice(groupIndex.item, 1); entry.element = container; } } this._view._modifiedGroups = []; var prevElement = this._canvasProxy; firstItem = 0; // When groups are disabled, loop thru all of the groups (there's only 1). // When groups are enabled, loop until either we exhaust all of the groups in the data source // or we exhaust all of the containers that have been created so far. for (var i = 0, len = groups.length; i < len && (!this._groupsEnabled() || firstItem < maxContainers) ; i++) { var groupInfo = groups[i], existingGroupIndex = this._view.keyToGroupIndex[groupInfo.key], existingGroup = this._view.tree[existingGroupIndex]; if (existingGroup) { if (that._view._blockSize) { updateExistingGroupWithBlocks(existingGroup, firstItem, groupInfo.size); } else { shift(existingGroup, oldFirstItem[existingGroupIndex], firstItem, groupInfo.size); addInserted(existingGroup, firstItem, groupInfo.size); updateExistingGroup(existingGroup, firstItem, groupInfo.size); } newTree.push(existingGroup); newKeyToGroupIndex[groupInfo.key] = newTree.length - 1; delete this._view.keyToGroupIndex[groupInfo.key]; prevElement = existingGroup.itemsContainer.element; this._view._modifiedGroups.push({ oldIndex: existingGroupIndex, newIndex: newTree.length - 1, element: existingGroup.header }); } else { var newGroup = addNewGroup(groupInfo, firstItem); newTree.push(newGroup); newKeyToGroupIndex[groupInfo.key] = newTree.length - 1; this._view._modifiedGroups.push({ oldIndex: -1, newIndex: newTree.length - 1, element: newGroup.header }); prevElement = newGroup.itemsContainer.element; } firstItem += groupInfo.size; } var removedBlocks = [], removedItemsContainers = [], removedHeaders = [], removedGroups = this._view.keyToGroupIndex ? Object.keys(this._view.keyToGroupIndex) : []; for (var i = 0, len = removedGroups.length; i < len; i++) { var groupIndex = this._view.keyToGroupIndex[removedGroups[i]], groupNode = this._view.tree[groupIndex]; removedHeaders.push(groupNode.header); removedItemsContainers.push(groupNode.itemsContainer.element); if (this._view._blockSize) { for (var b = 0; b < groupNode.itemsContainer.itemsBlocks.length; b++) { var block = groupNode.itemsContainer.itemsBlocks[b]; for (var n = 0; n < block.items.length; n++) { removedContainers.push(block.items[n]); } } } else { for (var n = 0; n < groupNode.itemsContainer.items.length; n++) { removedContainers.push(groupNode.itemsContainer.items[n]); } } this._view._modifiedGroups.push({ oldIndex: groupIndex, newIndex: -1, element: groupNode.header }); } for (var i = 0, len = modifiedElements.length; i < len; i++) { if (modifiedElements[i].newIndex === -1 && !modifiedElements[i]._removalHandled) { modifiedElements[i]._removalHandled = true; var itemBox = modifiedElements[i]._itemBox; modifiedElements[i]._itemBox = null; var container; if (removedContainers.length) { container = removedContainers.pop(); utilities.empty(container); } else { container = createContainer(); } if (utilities.hasClass(itemBox, WinJS.UI._selectedClass)) { utilities.addClass(container, WinJS.UI._selectedClass); } container.appendChild(itemBox); modifiedElements[i].element = container; } } this._view.tree = newTree; this._view.keyToGroupIndex = newKeyToGroupIndex; this._view.containers = newContainers; return { removedHeaders: removedHeaders, removedItemsContainers: removedItemsContainers }; }, _writeProfilerMark: function ListView_writeProfilerMark(text) { var message = "WinJS.UI.ListView:" + this._id + ":" + text; msWriteProfilerMark(message); WinJS.log && WinJS.log(message, null, "listviewprofiler"); } }, { // Static members triggerDispose: function () { /// /// /// Triggers the ListView disposal service manually. In normal operation this is triggered /// at ListView instantiation. However in some scenarios it may be appropriate to run /// the disposal service manually. /// /// WinJS.UI._disposeControls(); } }); WinJS.Class.mix(ListView, WinJS.Utilities.createEventProperties( "iteminvoked", "groupheaderinvoked", "selectionchanging", "selectionchanged", "loadingstatechanged", "keyboardnavigating", "contentanimating", "itemdragstart", "itemdragenter", "itemdragend", "itemdragbetween", "itemdragleave", "itemdragchanged", "itemdragdrop", "accessibilityannotationcomplete")); WinJS.Class.mix(ListView, WinJS.UI.DOMEventMixin); return ListView; }), _isSelectionRendered: function ListView_isSelectionRendered(itemBox) { // The tree is changed at pointerDown but _selectedClass is added only when the user drags an item below the selection threshold so checking for _selectedClass is not reliable. return itemBox.querySelectorAll(WinJS.UI._selectionPartsSelector).length > 0; } }); })(this, WinJS); (function repeaterInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Uses templates to generate HTML from a set of data. /// /// /// /// ]]> /// The Repeater control itself /// /// /// Repeater: WinJS.Namespace._lazy(function () { var UI = WinJS.UI; var Utilities = WinJS.Utilities; // Constants var ITEMSLOADED = "itemsloaded", ITEMCHANGING = "itemchanging", ITEMCHANGED = "itemchanged", ITEMINSERTING = "iteminserting", ITEMINSERTED = "iteminserted", ITEMMOVING = "itemmoving", ITEMMOVED = "itemmoved", ITEMREMOVING = "itemremoving", ITEMREMOVED = "itemremoved", ITEMSRELOADING = "itemsreloading", ITEMSRELOADED = "itemsreloaded"; var createEvent = Utilities._createEventProperty; // Class Names var repeaterClass = "win-repeater"; function stringifyItem(dataItem) { // Repeater uses this as its default renderer when no template is provided. var itemElement = document.createElement("div"); itemElement.innerText = JSON.stringify(dataItem); return itemElement; } // Statics var strings = { get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; }, get asynchronousRender() { return WinJS.Resources._getWinJSString("ui/asynchronousRender").value; }, get repeaterReentrancy() { return WinJS.Resources._getWinJSString("ui/repeaterReentrancy").value; }, }; var Repeater = WinJS.Class.define(function Repeater_ctor(element, options) { /// /// /// Creates a new Repeater control. /// /// /// The DOM element that will host the new control. The Repeater will create an element if this value is null. /// /// /// An object that contains one or more property/value pairs to apply to the /// new Repeater. Each property of the options object corresponds to one of the /// object's properties or events. Event names must begin with "on". /// /// /// The new Repeater control. /// /// // Check to make sure we weren't duplicated if (element && element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.Repeater.DuplicateConstruction", strings.duplicateConstruction); } this._element = element || document.createElement("div"); this._id = this._element.id || this._element.uniqueID; this._writeProfilerMark("constructor,StartTM"); options = options || {}; Utilities.addClass(this._element, "win-repeater win-disposable"); this._render = null; this._modifying = false; this._disposed = false; this._element.winControl = this; this._dataListeners = { itemchanged: this._dataItemChangedHandler.bind(this), iteminserted: this._dataItemInsertedHandler.bind(this), itemmoved: this._dataItemMovedHandler.bind(this), itemremoved: this._dataItemRemovedHandler.bind(this), reload: this._dataReloadHandler.bind(this), }; // Consume Repeater innerHTML and return a template. var inlineTemplate = this._extractInlineTemplate(); this._initializing = true; // Use the inlinetemplate if a parameter was not given. // Either way, Repeater's innerHTML has now been consumed. this.template = options.template || inlineTemplate; this.data = options.data; this._initializing = false; UI._setOptions(this, options, true); // Events only this._repeatedDOM = []; this._renderAllItems(); this.dispatchEvent(ITEMSLOADED, {}); this._writeProfilerMark("constructor,StopTM"); }, { /// element: { get: function () { return this._element; } }, /// /// Gets or sets the WinJS.Binding.List that provides the Repeater control with items to display. /// data: { get: function () { return this._data; }, set: function (data) { this._writeProfilerMark("data.set,StartTM"); if (this._data) { this._removeDataListeners(); }; this._data = data || new WinJS.Binding.List(); this._addDataListeners(); if (!this._initializing) { this._reloadRepeater(true); this.dispatchEvent(ITEMSLOADED, {}); } this._writeProfilerMark("data.set,StopTM"); } }, /// /// Gets or sets a Template or custom rendering function that defines the HTML of each item within the Repeater. /// template: { get: function () { return this._template; }, set: function (template) { this._writeProfilerMark("template.set,StartTM"); this._template = (template || stringifyItem); this._render = WinJS.Utilities._syncRenderer(this._template, this.element.tagName); if (!this._initializing) { this._reloadRepeater(true); this.dispatchEvent(ITEMSLOADED, {}); } this._writeProfilerMark("template.set,StopTM"); } }, /// length: { get: function () { return this._repeatedDOM.length; }, }, elementFromIndex: function Repeater_elementFromIndex(index) { /// /// /// Returns the HTML element for the item with the specified index. /// /// /// The index of the item. /// /// /// The DOM element for the specified item. /// /// return this._repeatedDOM[index]; }, dispose: function Repeater_dispose() { /// /// /// Prepare this Repeater for garbage collection. /// /// if (this._disposed) { return; } this._disposed = true; // Mark this control as disposed. this._removeDataListeners(); this._data = null; this._template = null; for (var i = 0, len = this._repeatedDOM.length; i < len; i++) { WinJS.Utilities._disposeElement(this._repeatedDOM[i]); } }, /// /// Raised when the Repeater has finished loading a new set of data. This event is only fired on construction /// or when the Repeater control's data source or template is replaced. /// onitemsloaded: createEvent(ITEMSLOADED), /// /// Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. /// onitemchanging: createEvent(ITEMCHANGING), /// /// Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. /// onitemchanged: createEvent(ITEMCHANGED), /// /// Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. /// oniteminserting: createEvent(ITEMINSERTING), /// /// Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. /// oniteminserted: createEvent(ITEMINSERTED), /// /// Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. /// onitemmoving: createEvent(ITEMMOVING), /// /// Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. /// onitemmoved: createEvent(ITEMMOVED), /// /// Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. /// onitemremoving: createEvent(ITEMREMOVING), /// /// Raised after an item has been removed from one index to another in the Repeater control's data source and after the corresponding DOM element has been removed. /// onitemremoved: createEvent(ITEMREMOVED), /// /// The list has been refreshed and any references to data in the list may be incorrect. /// Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. /// onitemsreloading: createEvent(ITEMSRELOADING), /// /// Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. /// onitemsreloaded: createEvent(ITEMSRELOADED), _extractInlineTemplate: function Repeater_extractInlineTemplate() { // Creates and returns a WinJS.BindingTemplate from the Repeater innerHTML. if (this._element.firstElementChild) { var templateElement = document.createElement(this._element.tagName); while (this._element.firstElementChild) { // Move each child element from the Repeater to the Template Element templateElement.appendChild(this._element.firstElementChild); } return new WinJS.Binding.Template(templateElement, { extractChild: true }); } }, _renderAllItems: function Repeater_renderAllItems() { var fragment = document.createDocumentFragment(); for (var i = 0, len = this._data.length; i < len; i++) { var renderedItem = this._render(this._data.getAt(i)); if (!renderedItem) { throw new WinJS.ErrorFromName("WinJS.UI.Repeater.AsynchronousRender", strings.asynchronousRender); } fragment.appendChild(renderedItem); this._repeatedDOM.push(renderedItem); } this._element.appendChild(fragment); }, _reloadRepeater: function Repeater_reloadRepeater(shouldDisposeElements) { this._unloadRepeatedDOM(shouldDisposeElements); this._repeatedDOM = []; this._renderAllItems(); }, _unloadRepeatedDOM: function Repeater_unloadRepeatedDOM(shouldDisposeElements) { for (var i = 0, len = this._repeatedDOM.length; i < len; i++) { if (!!shouldDisposeElements) { // this_dataReloadHandler uses this to defer disposal until after animations have completed, // at which point it manually disposes each element. WinJS.Utilities._disposeElement(this._repeatedDOM[i]); } this._element.removeChild(this._repeatedDOM[i]); } }, _addDataListeners: function Repeater_addDataListeners() { Object.keys(this._dataListeners).forEach(function (eventName) { this._data.addEventListener(eventName, this._dataListeners[eventName], false); }.bind(this)); }, _beginModification: function Repeater_beginModification() { if (this._modifying) { throw new WinJS.ErrorFromName("WinJS.UI.Repeater.RepeaterModificationReentrancy", strings.repeaterReentrancy); } this._modifying = true; }, _endModification: function Repeater_endModification() { this._modifying = false; }, _removeDataListeners: function Repeater_removeDataListeners() { Object.keys(this._dataListeners).forEach(function (eventName) { this._data.removeEventListener(eventName, this._dataListeners[eventName], false); }.bind(this)); }, _dataItemChangedHandler: function Repeater_dataItemChangedHandler(eventInfo) { // Handles the 'itemchanged' event fired by WinJS.Binding.List this._beginModification(); var animationPromise; var root = this._element; var index = eventInfo.detail.index; var renderedItem = this._render(eventInfo.detail.newValue); if (!renderedItem) { throw new WinJS.ErrorFromName("WinJS.UI.Repeater.AsynchronousRender", strings.asynchronousRender); } // Append to the event object if (this._repeatedDOM[index]) { eventInfo.detail.oldElement = this._repeatedDOM[index]; } eventInfo.detail.newElement = renderedItem; eventInfo.detail.setPromise = function setPromise(delayPromise) { animationPromise = delayPromise; }; this._writeProfilerMark(ITEMCHANGING + ",info"); this.dispatchEvent(ITEMCHANGING, eventInfo.detail); // Make the change var oldItem = null; if (index < this._repeatedDOM.length) { oldItem = this._repeatedDOM[index]; root.replaceChild(renderedItem, oldItem); this._repeatedDOM[index] = renderedItem; } else { root.appendChild(renderedItem); this._repeatedDOM.push(renderedItem); } this._endModification(); this._writeProfilerMark(ITEMCHANGED + ",info"); this.dispatchEvent(ITEMCHANGED, eventInfo.detail); if (oldItem) { // Give the option to delay element disposal. WinJS.Promise.as(animationPromise).done(function () { WinJS.Utilities._disposeElement(oldItem); }.bind(this)); } }, _dataItemInsertedHandler: function Repeater_dataItemInsertedHandler(eventInfo) { // Handles the 'iteminserted' event fired by WinJS.Binding.List this._beginModification(); var index = eventInfo.detail.index; var renderedItem = this._render(eventInfo.detail.value); if (!renderedItem) { throw new WinJS.ErrorFromName("WinJS.UI.Repeater.AsynchronousRender", strings.asynchronousRender); } var root = this._element; eventInfo.detail.affectedElement = renderedItem; this._writeProfilerMark(ITEMINSERTING + ",info"); this.dispatchEvent(ITEMINSERTING, eventInfo.detail); if (index < this._repeatedDOM.length) { var nextSibling = this._repeatedDOM[index]; root.insertBefore(renderedItem, nextSibling); } else { root.appendChild(renderedItem); } // Update collection of rendered elements this._repeatedDOM.splice(index, 0, renderedItem); this._endModification(); this._writeProfilerMark(ITEMINSERTED + ",info"); this.dispatchEvent(ITEMINSERTED, eventInfo.detail); }, _dataItemMovedHandler: function Repeater_dataItemMovedHandler(eventInfo) { // Handles the 'itemmoved' event fired by WinJS.Binding.List this._beginModification(); var movingItem = this._repeatedDOM[eventInfo.detail.oldIndex]; // Fire the event before we start the move. eventInfo.detail.affectedElement = movingItem; this._writeProfilerMark(ITEMMOVING + ",info"); this.dispatchEvent(ITEMMOVING, eventInfo.detail); // Remove this._repeatedDOM.splice(eventInfo.detail.oldIndex, 1)[0]; movingItem.parentNode.removeChild(movingItem); // Insert if (eventInfo.detail.newIndex < (this._data.length) - 1) { var nextSibling = this._repeatedDOM[eventInfo.detail.newIndex]; this._element.insertBefore(movingItem, nextSibling); this._repeatedDOM.splice(eventInfo.detail.newIndex, 0, movingItem); } else { this._repeatedDOM.push(movingItem); this._element.appendChild(movingItem); } this._endModification(); this._writeProfilerMark(ITEMMOVED + ",info"); this.dispatchEvent(ITEMMOVED, eventInfo.detail); }, _dataItemRemovedHandler: function Repeater_dataItemRemoveHandler(eventInfo) { // Handles the 'itemremoved' event fired by WinJS.Binding.List this._beginModification(); var animationPromise; var oldItem = this._repeatedDOM[eventInfo.detail.index]; // Trim 'value' and 'key' from the eventInfo.details that Binding.List gave for the removal case, // since both of those properties already exist inside of eventInfo.details.item. var eventDetail = { affectedElement: oldItem, index: eventInfo.detail.index, item: eventInfo.detail.item }; eventDetail.setPromise = function setPromise(delayPromise) { animationPromise = delayPromise; } this._writeProfilerMark(ITEMREMOVING + ",info"); this.dispatchEvent(ITEMREMOVING, eventDetail); oldItem.parentNode.removeChild(oldItem); this._repeatedDOM.splice(eventInfo.detail.index, 1); this._endModification(); this._writeProfilerMark(ITEMREMOVED + ",info"); this.dispatchEvent(ITEMREMOVED, eventDetail); WinJS.Promise.as(animationPromise).done(function () { WinJS.Utilities._disposeElement(oldItem); }.bind(this)); }, _dataReloadHandler: function Repeater_dataReloadHandler(eventInfo) { // Handles the 'reload' event fired by WinJS.Binding.List whenever it performs operations such as reverse() or sort() this._beginModification(); var animationPromise; var shallowCopyBefore = this._repeatedDOM.slice(0); var eventDetail = { affectedElements: shallowCopyBefore }; eventDetail.setPromise = function (delayPromise) { animationPromise = delayPromise; } this._writeProfilerMark(ITEMSRELOADING + ",info"); this.dispatchEvent(ITEMSRELOADING, eventDetail); this._reloadRepeater(false /*shouldDisposeElements */); var shallowCopyAfter = this._repeatedDOM.slice(0); this._endModification(); this._writeProfilerMark(ITEMSRELOADED + ",info"); this.dispatchEvent(ITEMSRELOADED, { affectedElements: shallowCopyAfter }); WinJS.Promise.as(animationPromise).done(function () { // Gives the option to defer disposal. for (var i = 0, len = shallowCopyBefore.length; i < len; i++) { WinJS.Utilities._disposeElement(shallowCopyBefore[i]); } }.bind(this)); }, _writeProfilerMark: function Repeater_writeProfilerMark(text) { msWriteProfilerMark("WinJS.UI.Repeater:" + this._id + ":" + text); } }, { isDeclarativeControlContainer: true, }); WinJS.Class.mix(Repeater, UI.DOMEventMixin); return Repeater; }) }); })(WinJS); (function selectionManagerInit(global, WinJS, undefined) { "use strict"; var utilities = WinJS.Utilities, Promise = WinJS.Promise; WinJS.Namespace.define("WinJS.UI", { _ItemSet: WinJS.Namespace._lazy(function () { var _ItemSet = WinJS.Class.define(function _ItemSet_ctor(listView, ranges, count) { this._listView = listView; this._ranges = ranges; this._itemsCount = count; }); _ItemSet.prototype = { getRanges: function () { var ranges = []; for (var i = 0, len = this._ranges.length; i < len; i++) { var range = this._ranges[i]; ranges.push({ firstIndex: range.firstIndex, lastIndex: range.lastIndex, firstKey: range.firstKey, lastKey: range.lastKey }); } return ranges; }, getItems: function () { return WinJS.UI.getItemsFromRanges(this._listView._itemsManager.dataSource, this._ranges); }, isEverything: function () { return this.count() === this._itemsCount; }, count: function () { var count = 0; for (var i = 0, len = this._ranges.length; i < len; i++) { var range = this._ranges[i]; count += range.lastIndex - range.firstIndex + 1; } return count; }, getIndices: function () { var indices = []; for (var i = 0, len = this._ranges.length; i < len; i++) { var range = this._ranges[i]; for (var n = range.firstIndex; n <= range.lastIndex; n++) { indices.push(n); } } return indices; } }; return _ItemSet; }), getItemsFromRanges: function (dataSource, ranges) { var listBinding = dataSource.createListBinding(), promises = []; function getIndices() { var indices = []; for (var i = 0, len = ranges.length; i < len; i++) { var range = ranges[i]; for (var j = range.firstIndex; j <= range.lastIndex; j++) { indices.push(j); } } return Promise.wrap(indices); } return getIndices().then(function (indices) { for (var i = 0; i < indices.length; i++) { promises.push(listBinding.fromIndex(indices[i])); } return WinJS.Promise.join(promises).then(function (items) { listBinding.release(); return items; }); }); }, _Selection: WinJS.Namespace._lazy(function () { function isEverythingRange(ranges) { return ranges && ranges.firstIndex === 0 && ranges.lastIndex === Number.MAX_VALUE; } return WinJS.Class.derive(WinJS.UI._ItemSet, function (listView, indexesAndRanges) { this._listView = listView; this._itemsCount = -1; this._ranges = []; if (indexesAndRanges) { this.set(indexesAndRanges); } }, { clear: function () { /// /// /// Clears the selection. /// /// /// A Promise that is fulfilled when the clear operation completes. /// /// this._releaseRanges(this._ranges); this._ranges = []; return Promise.wrap(); }, set: function (items) { /// /// /// Clears the current selection and replaces it with the specified items. /// /// /// The indexes or keys of the items that make up the selection. /// You can provide different types of objects for the items parameter: /// you can specify an index, a key, or a range of indexes. /// It can also be an array that contains one or more of these objects. /// /// /// A Promise that is fulfilled when the operation completes. /// /// // A range with lastIndex set to Number.MAX_VALUE used to mean selectAll. Passing such range to set was equivalent to selectAll. This code preserves this behavior. if (!isEverythingRange(items)) { this._releaseRanges(this._ranges); this._ranges = []; var that = this; return this._execute("_set", items).then(function () { that._ranges.sort(function (left, right) { return left.firstIndex - right.firstIndex; }); return that._ensureKeys(); }).then(function () { return that._ensureCount(); }); } else { return this.selectAll(); } }, add: function (items) { /// /// /// Adds one or more items to the selection. /// /// /// The indexes or keys of the items to add. /// You can provide different types of objects for the items parameter: /// you can specify an index, a key, or a range of indexes. /// It can also be an array that contains one or more of these objects. /// /// /// A Promise that is fulfilled when the operation completes. /// /// if (!isEverythingRange(items)) { var that = this; return this._execute("_add", items).then(function () { return that._ensureKeys(); }).then(function () { return that._ensureCount(); }); } else { return this.selectAll(); } }, remove: function (items) { /// /// /// Removes the specified items from the selection. /// /// /// The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: /// you can specify an index, a key, or a range of indexes. /// It can also be an array that contains one or more of these objects. /// /// /// A Promise that is fulfilled when the operation completes. /// /// var that = this; return this._execute("_remove", items).then(function () { return that._ensureKeys(); }); }, selectAll: function () { /// /// /// Adds all the items in the ListView to the selection. /// /// /// A Promise that is fulfilled when the operation completes. /// /// var that = this; return that._ensureCount().then(function () { if (that._itemsCount) { var range = { firstIndex: 0, lastIndex: that._itemsCount - 1, }; that._retainRange(range); that._releaseRanges(that._ranges); that._ranges = [range]; return that._ensureKeys(); } }); }, /*#DBG _assertValid: function () { for (var i = 0, len = this._ranges.length; i < len; i++) { var range = this._ranges[i]; _ASSERT(range.firstIndex <= range.lastIndex); _ASSERT(!i || this._ranges[i - 1].lastIndex < range.firstIndex); } return true; }, #DBG*/ _execute: function (operation, items) { var that = this, keysSupported = !!that._getListBinding().fromKey, array = Array.isArray(items) ? items : [items], promises = [Promise.wrap()]; function toRange(type, first, last) { var retVal = {}; retVal["first" + type] = first; retVal["last" + type] = last; return retVal; } function handleKeys(range) { var binding = that._getListBinding(); var promise = Promise.join([binding.fromKey(range.firstKey), binding.fromKey(range.lastKey)]).then(function (items) { if (items[0] && items[1]) { range.firstIndex = items[0].index; range.lastIndex = items[1].index; that[operation](range); } return range; }); promises.push(promise); } for (var i = 0, len = array.length; i < len; i++) { var item = array[i]; if (typeof item === "number") { this[operation](toRange("Index", item, item)); } else if (item) { if (keysSupported && item.key !== undefined) { handleKeys(toRange("Key", item.key, item.key)); } else if (keysSupported && item.firstKey !== undefined && item.lastKey !== undefined) { handleKeys(toRange("Key", item.firstKey, item.lastKey)); } else if (item.index !== undefined && typeof item.index === "number") { this[operation](toRange("Index", item.index, item.index)); } else if (item.firstIndex !== undefined && item.lastIndex !== undefined && typeof item.firstIndex === "number" && typeof item.lastIndex === "number") { this[operation](toRange("Index", item.firstIndex, item.lastIndex)); } } } return Promise.join(promises); }, _set: function (range) { this._retainRange(range); this._ranges.push(range); }, _add: function (newRange) { var that = this, prev = null, range, inserted; var merge = function (left, right) { if (right.lastIndex > left.lastIndex) { left.lastIndex = right.lastIndex; left.lastKey = right.lastKey; if (left.lastPromise) { left.lastPromise.release(); } left.lastPromise = that._getListBinding().fromIndex(left.lastIndex).retain(); } } for (var i = 0, len = this._ranges.length; i < len; i++) { range = this._ranges[i]; if (newRange.firstIndex < range.firstIndex) { var mergeWithPrev = prev && newRange.firstIndex < (prev.lastIndex + 1); if (mergeWithPrev) { inserted = i - 1; merge(prev, newRange); } else { this._insertRange(i, newRange); inserted = i; } break; } else if (newRange.firstIndex === range.firstIndex) { merge(range, newRange); inserted = i; break; } prev = range; } if (inserted === undefined) { var last = this._ranges.length ? this._ranges[this._ranges.length - 1] : null, mergeWithLast = last && newRange.firstIndex < (last.lastIndex + 1); if (mergeWithLast) { merge(last, newRange); } else { this._retainRange(newRange); this._ranges.push(newRange); } } else { prev = null; for (i = inserted + 1, len = this._ranges.length; i < len; i++) { range = this._ranges[i]; if (newRange.lastIndex < range.firstIndex) { mergeWithPrev = prev && prev.lastIndex > newRange.lastIndex; if (mergeWithPrev) { merge(this._ranges[inserted], prev); } this._removeRanges(inserted + 1, i - inserted - 1); break; } else if (newRange.lastIndex === range.firstIndex) { merge(this._ranges[inserted], range); this._removeRanges(inserted + 1, i - inserted); break; } prev = range; } if (i >= len) { merge(this._ranges[inserted], this._ranges[len - 1]); this._removeRanges(inserted + 1, len - inserted - 1); } } }, _remove: function (toRemove) { var that = this; function retainPromise(index) { return that._getListBinding().fromIndex(index).retain(); } // This method is called when a range needs to be unselected. It is inspecting every range in the current selection comparing // it to the range which is being unselected and it is building an array of new selected ranges var ranges = []; for (var i = 0, len = this._ranges.length; i < len; i++) { var range = this._ranges[i]; if (range.lastIndex < toRemove.firstIndex || range.firstIndex > toRemove.lastIndex) { // No overlap with the unselected range ranges.push(range); } else if (range.firstIndex < toRemove.firstIndex && range.lastIndex >= toRemove.firstIndex && range.lastIndex <= toRemove.lastIndex) { // The end of this range is being unselected ranges.push({ firstIndex: range.firstIndex, firstKey: range.firstKey, firstPromise: range.firstPromise, lastIndex: toRemove.firstIndex - 1, lastPromise: retainPromise(toRemove.firstIndex - 1) }); range.lastPromise.release(); } else if (range.lastIndex > toRemove.lastIndex && range.firstIndex >= toRemove.firstIndex && range.firstIndex <= toRemove.lastIndex) { // The beginning of this range is being unselected ranges.push({ firstIndex: toRemove.lastIndex + 1, firstPromise: retainPromise(toRemove.lastIndex + 1), lastIndex: range.lastIndex, lastKey: range.lastKey, lastPromise: range.lastPromise }); range.firstPromise.release(); } else if (range.firstIndex < toRemove.firstIndex && range.lastIndex > toRemove.lastIndex) { // The middle part of this range is being unselected ranges.push({ firstIndex: range.firstIndex, firstKey: range.firstKey, firstPromise: range.firstPromise, lastIndex: toRemove.firstIndex - 1, lastPromise: retainPromise(toRemove.firstIndex - 1), }); ranges.push({ firstIndex: toRemove.lastIndex + 1, firstPromise: retainPromise(toRemove.lastIndex + 1), lastIndex: range.lastIndex, lastKey: range.lastKey, lastPromise: range.lastPromise }); } else { // The whole range is being unselected //#DBG _ASSERT(range.firstIndex >= toRemove.firstIndex && range.lastIndex <= toRemove.lastIndex); range.firstPromise.release(); range.lastPromise.release(); } } this._ranges = ranges; }, _ensureKeys: function () { var promises = [Promise.wrap()]; var that = this; var ensureKey = function (which, range) { var keyProperty = which + "Key"; if (!range[keyProperty]) { var promise = range[which + "Promise"]; promise.then(function (item) { if (item) { range[keyProperty] = item.key; } }); return promise; } else { return Promise.wrap(); } } for (var i = 0, len = this._ranges.length; i < len; i++) { var range = this._ranges[i]; promises.push(ensureKey("first", range)); promises.push(ensureKey("last", range)); } Promise.join(promises).then(function () { that._ranges = that._ranges.filter(function (range) { return range.firstKey && range.lastKey; }); }); return Promise.join(promises); }, _mergeRanges: function (target, source) { //#DBG _ASSERT(!target.lastPromise && !source.lastPromise); target.lastIndex = source.lastIndex; target.lastKey = source.lastKey; }, _isIncluded: function (index) { if (this.isEverything()) { return true; } else { for (var i = 0, len = this._ranges.length; i < len; i++) { var range = this._ranges[i]; if (range.firstIndex <= index && index <= range.lastIndex) { return true; } } return false; } }, _ensureCount: function () { var that = this; return this._listView._itemsCount().then(function (count) { that._itemsCount = count; }); }, _insertRange: function (index, newRange) { this._retainRange(newRange); this._ranges.splice(index, 0, newRange); }, _removeRanges: function (index, howMany) { for (var i = 0; i < howMany; i++) { this._releaseRange(this._ranges[index + i]); } this._ranges.splice(index, howMany); }, _retainRange: function (range) { if (!range.firstPromise) { range.firstPromise = this._getListBinding().fromIndex(range.firstIndex).retain(); } if (!range.lastPromise) { range.lastPromise = this._getListBinding().fromIndex(range.lastIndex).retain(); } }, _retainRanges: function () { for (var i = 0, len = this._ranges.length; i < len; i++) { this._retainRange(this._ranges[i]); } }, _releaseRange: function (range) { range.firstPromise.release(); range.lastPromise.release(); }, _releaseRanges: function (ranges) { for (var i = 0, len = ranges.length; i < len; ++i) { this._releaseRange(ranges[i]); } }, _getListBinding: function () { return this._listView._itemsManager._listBinding; } }, { supportedForProcessing: false, }); }), // This component is responsible for holding selection state _SelectionManager: WinJS.Namespace._lazy(function () { var _SelectionManager = function (listView) { this._listView = listView; this._selected = new WinJS.UI._Selection(this._listView); // Don't rename this member. Some apps reference it. this._pivot = WinJS.UI._INVALID_INDEX; this._focused = { type: WinJS.UI.ObjectType.item, index: 0 }; this._pendingChange = Promise.wrap(); }; _SelectionManager.prototype = { count: function () { /// /// /// Returns the number of items in the selection. /// /// /// The number of items in the selection. /// /// return this._selected.count(); }, getIndices: function () { /// /// /// Returns a list of the indexes for the items in the selection. /// /// /// The list of indexes for the items in the selection as an array of Number objects. /// /// return this._selected.getIndices(); }, getItems: function () { /// /// /// Returns an array that contains the items in the selection. /// /// /// A Promise that contains an array of the requested IItem objects. /// /// return this._selected.getItems(); }, getRanges: function () { /// /// /// Gets an array of the index ranges for the selected items. /// /// /// An array that contains an ISelectionRange object for each index range in the selection. /// /// return this._selected.getRanges(); }, isEverything: function () { /// /// /// Returns a value that indicates whether the selection contains every item in the data source. /// /// /// true if the selection contains every item in the data source; otherwise, false. /// /// return this._selected.isEverything(); }, set: function (items) { /// /// /// Clears the current selection and replaces it with the specified items. /// /// /// The indexes or keys of the items that make up the selection. /// You can provide different types of objects for the items parameter: /// you can specify an index, a key, or a range of indexes. /// It can also be an array that contains one or more of these objects. /// /// /// A Promise that is fulfilled when the operation completes. /// /// var that = this, signal = new WinJS._Signal(); return this._synchronize(signal).then(function () { var newSelection = new WinJS.UI._Selection(that._listView); return newSelection.set(items).then( function () { that._set(newSelection); signal.complete(); }, function (error) { newSelection.clear(); signal.complete(); return WinJS.Promise.wrapError(error); } ); }); }, clear: function () { /// /// /// Clears the selection. /// /// /// A Promise that is fulfilled when the clear operation completes. /// /// var that = this, signal = new WinJS._Signal(); return this._synchronize(signal).then(function () { var newSelection = new WinJS.UI._Selection(that._listView); return newSelection.clear().then( function () { that._set(newSelection); signal.complete(); }, function (error) { newSelection.clear(); signal.complete(); return WinJS.Promise.wrapError(error); } ); }); }, add: function (items) { /// /// /// Adds one or more items to the selection. /// /// /// The indexes or keys of the items to add. /// You can provide different types of objects for the items parameter: /// you can specify an index, a key, or a range of indexes. /// It can also be an array that contains one or more of these objects. /// /// /// A Promise that is fulfilled when the operation completes. /// /// var that = this, signal = new WinJS._Signal(); return this._synchronize(signal).then(function () { var newSelection = that._cloneSelection(); return newSelection.add(items).then( function () { that._set(newSelection); signal.complete(); }, function (error) { newSelection.clear(); signal.complete(); return WinJS.Promise.wrapError(error); } ); }); }, remove: function (items) { /// /// /// Removes the specified items from the selection. /// /// /// The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: /// you can specify an index, a key, or a range of indexes. /// It can also be an array that contains one or more of these objects. /// /// /// A Promise that is fulfilled when the operation completes. /// /// var that = this, signal = new WinJS._Signal(); return this._synchronize(signal).then(function () { var newSelection = that._cloneSelection(); return newSelection.remove(items).then( function () { that._set(newSelection); signal.complete(); }, function (error) { newSelection.clear(); signal.complete(); return WinJS.Promise.wrapError(error); } ); }); }, selectAll: function () { /// /// /// Adds all the items in the ListView to the selection. /// /// /// A Promise that is fulfilled when the operation completes. /// /// var that = this, signal = new WinJS._Signal(); return this._synchronize(signal).then(function () { var newSelection = new WinJS.UI._Selection(that._listView); return newSelection.selectAll().then( function () { that._set(newSelection); signal.complete(); }, function (error) { newSelection.clear(); signal.complete(); return WinJS.Promise.wrapError(error); } ); }); }, _synchronize: function (signal) { var that = this; return this._listView._versionManager.unlocked.then(function () { var currentPendingChange = that._pendingChange; that._pendingChange = WinJS.Promise.join([currentPendingChange, signal.promise]).then(function () { }); return currentPendingChange; }); }, _reset: function () { this._pivot = WinJS.UI._INVALID_INDEX; this._setFocused({ type: WinJS.UI.ObjectType.item, index: 0 }, this._keyboardFocused()); this._pendingChange.cancel(); this._pendingChange = Promise.wrap(); this._selected.clear(); this._selected = new WinJS.UI._Selection(this._listView); }, _dispose: function () { this._selected.clear(); this._selected = null; this._listView = null; }, _set: function (newSelection) { var that = this; return this._fireSelectionChanging(newSelection).then(function (approved) { if (approved) { that._selected.clear(); that._selected = newSelection; that._listView._updateSelection(); that._fireSelectionChanged(); } else { newSelection.clear(); } return approved; }); }, _fireSelectionChanging: function (newSelection) { var eventObject = document.createEvent("CustomEvent"), newSelectionUpdated = Promise.wrap(); eventObject.initCustomEvent("selectionchanging", true, true, { newSelection: newSelection, preventTapBehavior: function () { }, setPromise: function (promise) { /// /// /// Used to inform the ListView that asynchronous work is being performed, and that this /// event handler should not be considered complete until the promise completes. /// /// /// The promise to wait for. /// /// newSelectionUpdated = promise; } }); var approved = this._listView._element.dispatchEvent(eventObject); return newSelectionUpdated.then(function () { return approved; }); }, _fireSelectionChanged: function () { var eventObject = document.createEvent("CustomEvent"); eventObject.initCustomEvent("selectionchanged", true, false, null); this._listView._element.dispatchEvent(eventObject); }, _getFocused: function () { return { type: this._focused.type, index: this._focused.index }; }, _setFocused: function (entity, keyboardFocused) { this._focused = { type: entity.type, index: entity.index }; this._focusedByKeyboard = keyboardFocused; }, _keyboardFocused: function () { return this._focusedByKeyboard; }, _updateCount: function (count) { this._selected._itemsCount = count; }, _isIncluded: function (index) { return this._selected._isIncluded(index); }, _cloneSelection: function () { var newSelection = new WinJS.UI._Selection(this._listView); newSelection._ranges = this._selected.getRanges(); newSelection._itemsCount = this._selected._itemsCount; newSelection._retainRanges(); return newSelection; } }; _SelectionManager.supportedForProcessing = false; return _SelectionManager; }) }); })(this, WinJS); (function virtualizeContentsViewInit(global, WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _VirtualizeContentsView: WinJS.Namespace._lazy(function () { var utilities = WinJS.Utilities, Promise = WinJS.Promise, Scheduler = WinJS.Utilities.Scheduler; function cooperativeQueueWorker(info) { var workItems = info.job._workItems; var work; while (workItems.length && !info.shouldYield) { work = workItems.shift(); work(); } info.setWork(cooperativeQueueWorker); if (!workItems.length) { info.job.pause(); } } function scheduleQueueJob(priority, name) { var job = Scheduler.schedule(cooperativeQueueWorker, priority, null, name); job._workItems = []; job.addWork = function (work, head) { if (head) { this._workItems.unshift(work); } else { this._workItems.push(work); } this.resume(); }; job.clearWork = function () { this._workItems.length = 0; }; job.dispose = function () { this.cancel(); this._workItems.length = 0; } return job; } function shouldWaitForSeZo(listView) { return listView._zooming || listView._pinching; } function waitForSeZo(listView, timeout) { // waitForSeZo will block until sezo calls endZoom on listview, or a timeout duration has elapsed to // unblock a potential deadlock between the sezo waiting on container creation, and container creation // waiting on endZoom. if (listView._isZombie()) { return Promise.wrap(); } if (shouldWaitForSeZo(listView)) { if (+timeout !== timeout) { timeout = WinJS.UI._VirtualizeContentsView._waitForSeZoTimeoutDuration; } //To improve SeZo's zoom animation and pinch detection perf, we want to ensure unimportant task //is only run while zooming or pinching is not in progress. return Promise.timeout(WinJS.UI._VirtualizeContentsView._waitForSeZoIntervalDuration).then(function () { timeout -= WinJS.UI._VirtualizeContentsView._waitForSeZoIntervalDuration; if (timeout <= 0) { return true; } return waitForSeZo(listView, timeout); }); } else { return Promise.wrap(); } } function makeFunctor(scrollToFunctor) { if (typeof scrollToFunctor === "number") { var pos = scrollToFunctor; scrollToFunctor = function () { return { position: pos, direction: "right" }; }; } return scrollToFunctor; } var _VirtualizeContentsView = function VirtualizeContentsView_ctor(listView) { this._listView = listView; this._forceRelayout = false; this.items = new WinJS.UI._ItemsContainer(listView); this.firstIndexDisplayed = -1; this.lastIndexDisplayed = -1; this.begin = 0; this.end = 0; this._realizePass = 1; this._firstLayoutPass = true; this._runningAnimations = null; this._renderCompletePromise = Promise.wrap(); this._state = new CreatedState(this); this._createLayoutSignal(); this._createTreeBuildingSignal(); this._layoutWork = null; this._onscreenJob = scheduleQueueJob(Scheduler.Priority.aboveNormal, "on-screen items"); this._frontOffscreenJob = scheduleQueueJob(Scheduler.Priority.normal, "front off-screen items"); this._backOffscreenJob = scheduleQueueJob(Scheduler.Priority.belowNormal, "back off-screen items"); this._scrollbarPos = 0; this._direction = "right"; this._scrollToFunctor = makeFunctor(0); }; _VirtualizeContentsView._pagesToPrefetch = 2; _VirtualizeContentsView._waitForSeZoIntervalDuration = 100; _VirtualizeContentsView._waitForSeZoTimeoutDuration = 500; _VirtualizeContentsView._chunkSize = 500; _VirtualizeContentsView._startupChunkSize = 100; _VirtualizeContentsView._maxTimePerCreateContainers = 5; _VirtualizeContentsView._createContainersJobTimeslice = 15; _VirtualizeContentsView._blocksToRelease = 10; _VirtualizeContentsView._realizationLevel = { skip: "skip", realize: "realize", normal: "normal" }; _VirtualizeContentsView.prototype = { _dispose: function VirtualizeContentsView_dispose() { this.cleanUp(); this.items = null; this._renderCompletePromise && this._renderCompletePromise.cancel(); this._renderCompletePromise = null; this._onscreenJob.dispose(); this._frontOffscreenJob.dispose(); this._backOffscreenJob.dispose(); }, _createItem: function VirtualizeContentsView_createItem(itemIndex, itemPromise, available, unavailable) { this._listView._writeProfilerMark("createItem(" + itemIndex + ") " + this._getBoundingRectString(itemIndex) + ",info"); var that = this; that._listView._itemsManager._itemFromItemPromiseThrottled(itemPromise).done( function (element) { if (element) { available(itemIndex, element, that._listView._itemsManager._recordFromElement(element)); } else { unavailable(itemIndex); } }, function (err) { unavailable(itemIndex); return WinJS.Promise.wrapError(err); } ); }, _addItem: function VirtualizeContentsView_addItem(fragment, itemIndex, element, currentPass) { /*#DBG if (!WinJS.Utilities.data(element).itemsManagerRecord || WinJS.Utilities.data(element).removeElementMapRecord) { throw "ACK! Attempt to add an item to the scrollview which hasn't yet been realized"; } #DBG*/ if (this._realizePass === currentPass) { var record = this._listView._itemsManager._recordFromElement(element); delete this._pendingItemPromises[record.itemPromise.handle]; this.items.setItemAt(itemIndex, { itemBox: null, container: null, element: element, detached: true, itemsManagerRecord: record }); } }, finalItem: function VirtualizeContentsView_finalItem() { return this.containers ? Promise.wrap(this.containers.length - 1) : Promise.cancel; }, _setSkipRealizationForChange: function (skip) { if (skip) { if (this._realizationLevel !== WinJS.UI._VirtualizeContentsView._realizationLevel.realize) { this._realizationLevel = WinJS.UI._VirtualizeContentsView._realizationLevel.skip; } } else { this._realizationLevel = WinJS.UI._VirtualizeContentsView._realizationLevel.realize; } }, _realizeItems: function VirtualizeContentsView_realizeItems(fragment, begin, end, count, currentPass, scrollbarPos, direction, firstInView, lastInView, ignoreGaps) { var perfId = "_realizeItems(" + begin + "-" + (end - 1) + ") visible(" + firstInView + "-" + lastInView + ")"; this._listView._writeProfilerMark(perfId + ",StartTM"); direction = direction || "right"; var counter = end - begin; var inView = lastInView - firstInView + 1, inViewCounter = inView, rightOffscreenCount = end - lastInView - 1, leftOffscreenCount = firstInView - begin; var renderCompletePromises = []; var entranceAnimationSignal = new WinJS._Signal(); var viewportItemsRealized = new WinJS._Signal(); var frontItemsRealized = new WinJS._Signal(); var that = this; function itemIsReady(itemIndex, itemsManagerRecord) { renderCompletePromises.push(WinJS.Promise._cancelBlocker(itemsManagerRecord.renderComplete)); delivered(itemIndex); } function appendItemsToDom(startIndex, endIndex) { that._listView._writeProfilerMark("_realizeItems_appendedItemsToDom,StartTM"); if (that._listView._isZombie()) { return; } function updateSwipeable(itemData, element, itemBox) { if (!itemData.updatedSwipeableAttribute && (that._listView.itemsDraggable || that._listView.itemsReorderable || that._listView._swipeable)) { itemData.itemsManagerRecord.renderComplete.done(function () { if (that._realizePass === currentPass) { var dragDisabledOnItem = utilities.hasClass(element, WinJS.UI._nonDraggableClass), selectionDisabledOnItem = utilities.hasClass(element, WinJS.UI._nonSelectableClass), dragEnabled = (that._listView.itemsDraggable || that._listView.itemsReorderable), swipeSelectEnabled = (that._listView._selectionAllowed() && that._listView._swipeBehavior === WinJS.UI.SwipeBehavior.select); if (dragEnabled && !dragDisabledOnItem) { itemData.itemBox.draggable = true; } if (that._listView._swipeable && ((dragEnabled && !swipeSelectEnabled && dragDisabledOnItem) || (swipeSelectEnabled && !dragEnabled && selectionDisabledOnItem) || (dragDisabledOnItem && selectionDisabledOnItem))) { utilities.addClass(itemData.itemBox, WinJS.UI._nonSwipeableClass); } itemData.updatedSwipeableAttribute = true; } }); } } var itemIndex; var appendItemsCount = 0; var firstIndex = -1; var lastIndex = -1; for (itemIndex = startIndex; itemIndex <= endIndex; itemIndex++) { var itemData = that.items.itemDataAt(itemIndex); if (itemData) { var element = itemData.element, itemBox = itemData.itemBox; if (!itemBox) { itemBox = that._listView._itemBoxTemplate.cloneNode(true); itemData.itemBox = itemBox; itemBox.appendChild(element); utilities.addClass(element, WinJS.UI._itemClass); that._listView._setupAriaSelectionObserver(element); if (that._listView._isSelected(itemIndex)) { WinJS.UI._ItemEventsHandler.renderSelection(itemBox, element, true, true); } that._listView._currentMode().renderDragSourceOnRealizedItem(itemIndex, itemBox); } updateSwipeable(itemData, element, itemBox); var container = that.getContainer(itemIndex); if (itemBox.parentNode !== container) { that._appendAndRestoreFocus(container, itemBox); appendItemsCount++; if (firstIndex < 0) { firstIndex = itemIndex; } lastIndex = itemIndex; itemData.container = container; if (that._listView._isSelected(itemIndex)) { utilities.addClass(container, WinJS.UI._selectedClass); } utilities.removeClass(container, WinJS.UI._backdropClass); // elementAvailable needs to be called after fragment.appendChild. elementAvailable fulfills a promise for items requested // by the keyboard focus handler. That handler will explicitly call .focus() on the element, so in order for // the focus handler to work, the element needs to be in a tree prior to focusing. that.items.elementAvailable(itemIndex); } } } that._listView._writeProfilerMark("_realizeItems_appendedItemsToDom,StopTM"); if (appendItemsCount > 0) { that._listView._writeProfilerMark("_realizeItems_appendedItemsToDom:" + appendItemsCount + " (" + firstIndex + "-" + lastIndex + "),info"); that._reportElementsLevel(direction); } } function removeGaps(first, last, begin, end) { if (ignoreGaps) { return; } // If we realized items 0 through 20 and then scrolled so that items 25 - 30 are on screen when we // append them to the dom we should remove items 0 - 20 from the dom so there are no gaps between the // two realized spots. // Walk backwards from the beginning and if we find an item which is missing remove the rest var foundMissing = false; while (first >= begin) { foundMissing = testGap(first, foundMissing); first--; } // Walk forwards from the end and if we find an item which is missing remove the rest foundMissing = false; while (last <= end) { foundMissing = testGap(last, foundMissing); last++; } function testGap(itemIndex, foundMissing) { // This helper method is called for each index and once an item is missing from the dom // it removes any future one it encounters. var itemData = that.items.itemDataAt(itemIndex); if (itemData) { var itemBox = itemData.itemBox; if (!itemBox || !itemBox.parentNode) { return true; } else if (foundMissing) { utilities.addClass(itemBox.parentNode, WinJS.UI._backdropClass); itemBox.parentNode.removeChild(itemBox); return true; } else { return false; } } else { return true; } } } function scheduleReadySignal(first, last, job, dir, head) { var promises = []; for (var i = first; i <= last; i++) { var itemData = that.items.itemDataAt(i); if (itemData) { promises.push(itemData.itemsManagerRecord.itemPromise); } } function schedule(itemIndex) { var itemData = that.items.itemDataAt(itemIndex); if (itemData) { var record = itemData.itemsManagerRecord; if (!record.readyComplete && that._realizePass === currentPass) { job.addWork(function () { if (that._listView._isZombie()) { return; } if (record.pendingReady && that._realizePass === currentPass) { that._listView._writeProfilerMark("pendingReady(" + itemIndex + "),info"); record.pendingReady(); } }, head); } } } Promise.join(promises).then(function () { if (dir === "right") { for (var i = first; i <= last; i++) { schedule(i); } } else { for (var i = last; i >= first; i--) { schedule(i); } } }); } function delivered(index) { if (that._realizePass !== currentPass) { return; } if (index >= firstInView && index <= lastInView) { if (--inViewCounter === 0) { appendItemsToDom(firstInView, lastInView); removeGaps(firstInView, lastInView, begin, end); if (that._firstLayoutPass) { scheduleReadySignal(firstInView, lastInView, that._frontOffscreenJob, direction === "right" ? "left" : "right", true); var entranceAnimation = Scheduler.schedulePromiseHigh(null, "WinJS.UI.ListView.entranceAnimation").then(function () { if (that._listView._isZombie()) { return; } that._listView._writeProfilerMark("entranceAnimation,StartTM"); var promise = that._listView._animateListEntrance(!that._firstEntranceAnimated); that._firstEntranceAnimated = true; return promise; }); that._runningAnimations = Promise.join([that._runningAnimations, entranceAnimation]); that._runningAnimations.done(function () { that._listView._writeProfilerMark("entranceAnimation,StopTM"); if (that._realizePass === currentPass) { that._runningAnimations = null; entranceAnimationSignal.complete(); } }); that._firstLayoutPass = false; if (that._listView._isCurrentZoomView) { Scheduler.requestDrain(that._onscreenJob.priority); } } else { // during scrolling ready for onscreen items after front off screen items scheduleReadySignal(firstInView, lastInView, that._frontOffscreenJob, direction); entranceAnimationSignal.complete(); } that._updateHeaders(that._listView._canvas, firstInView, lastInView + 1).done(function () { viewportItemsRealized.complete(); }); } } else if (index < firstInView) { --leftOffscreenCount; if (leftOffscreenCount % inView === 0) { appendItemsToDom(begin, firstInView - 1); } if (!leftOffscreenCount) { that._updateHeaders(that._listView._canvas, begin, firstInView).done(function () { if (direction !== "right") { frontItemsRealized.complete(); } }); scheduleReadySignal(begin, firstInView - 1, direction !== "right" ? that._frontOffscreenJob : that._backOffscreenJob, "left"); } } else if (index > lastInView) { --rightOffscreenCount; if (rightOffscreenCount % inView === 0) { appendItemsToDom(lastInView + 1, end - 1); } if (!rightOffscreenCount) { that._updateHeaders(that._listView._canvas, lastInView + 1, end).then(function () { if (direction === "right") { frontItemsRealized.complete(); } }); scheduleReadySignal(lastInView + 1, end - 1, direction === "right" ? that._frontOffscreenJob : that._backOffscreenJob, "right"); } } counter--; if (counter === 0) { that._renderCompletePromise = Promise.join(renderCompletePromises).then(null, function (e) { var error = Array.isArray(e) && e.some(function (item) { return item && !(item instanceof Error && item.name === "Canceled"); }); if (error) { // rethrow return Promise.wrapError(e); } }); (that._headerRenderPromises || Promise.wrap()).done(function () { Scheduler.schedule(function () { if (that._listView._isZombie()) { workCompleteSignal.cancel(); } else { workCompleteSignal.complete(); } }, Math.min(that._onscreenJob.priority, that._backOffscreenJob.priority), null, "WinJS.UI.ListView._allItemsRealized"); }); } } function newItemIsReady(itemIndex, element, itemsManagerRecord) { if (that._realizePass === currentPass) { //#DBG _ASSERT(!itemsManagerRecord.released); var element = itemsManagerRecord.element; that._addItem(fragment, itemIndex, element, currentPass); itemIsReady(itemIndex, itemsManagerRecord); } } if (counter > 0) { var createCount = 0; var updateCount = 0; var cleanCount = 0; //#DBG _ASSERT(lastInView < end); that.firstIndexDisplayed = firstInView; that.lastIndexDisplayed = lastInView; var isCurrentZoomView = that._listView._isCurrentZoomView; if (that._highPriorityRealize && (that._firstLayoutPass || that._hasAnimationInViewportPending)) { // startup or edits that will animate items in the viewport that._highPriorityRealize = false; that._onscreenJob.priority = Scheduler.Priority.high; that._frontOffscreenJob.priority = Scheduler.Priority.normal; that._backOffscreenJob.priority = Scheduler.Priority.belowNormal; } else if (that._highPriorityRealize) { // edits that won't animate items in the viewport that._highPriorityRealize = false; that._onscreenJob.priority = Scheduler.Priority.high; that._frontOffscreenJob.priority = Scheduler.Priority.high - 1; that._backOffscreenJob.priority = Scheduler.Priority.high - 1; } else if (isCurrentZoomView) { // scrolling that._onscreenJob.priority = Scheduler.Priority.aboveNormal; that._frontOffscreenJob.priority = Scheduler.Priority.normal; that._backOffscreenJob.priority = Scheduler.Priority.belowNormal; } else { // hidden ListView in SeZo that._onscreenJob.priority = Scheduler.Priority.belowNormal; that._frontOffscreenJob.priority = Scheduler.Priority.idle; that._backOffscreenJob.priority = Scheduler.Priority.idle; } // Create a promise to wrap the work in the queue. When the queue gets to the last item we can mark // the work promise complete and if the work promise is canceled we cancel the queue. // var workCompleteSignal = new WinJS._Signal(); // If the version manager recieves a notification we clear the work in the work queues // var cancelToken = that._listView._versionManager.cancelOnNotification(workCompleteSignal.promise); var queueStage1AfterStage0 = function (job, record) { if (record.startStage1) { record.stage0.then(function () { if (that._realizePass === currentPass && record.startStage1) { job.addWork(record.startStage1); } }); } }; var queueWork = function (job, itemIndex) { var itemData = that.items.itemDataAt(itemIndex); if (!itemData) { var itemPromise = that._listView._itemsManager._itemPromiseAtIndex(itemIndex); // Remember this pending item promise and avoid canceling it from the previous realization pass. that._pendingItemPromises[itemPromise.handle] = itemPromise; delete that._previousRealizationPendingItemPromises[itemPromise.handle]; job.addWork(function VirtualizeContentsView_realizeItemsWork() { if (that._listView._isZombie()) { return; } createCount++; that._createItem(itemIndex, itemPromise, newItemIsReady, delivered); // _createItem runs user code if (that._listView._isZombie() || that._realizePass !== currentPass) { return; } if (itemPromise.handle) { var record = that._listView._itemsManager._recordFromHandle(itemPromise.handle); queueStage1AfterStage0(job, record); } }); } }; var queueRight = function (job, first, last) { for (var itemIndex = first; itemIndex <= last; itemIndex++) { queueWork(job, itemIndex); } }; var queueLeft = function (job, first, last) { // Always build the left side in the direction away from the center. for (var itemIndex = last; itemIndex >= first; itemIndex--) { queueWork(job, itemIndex); } }; var handleExistingRange = function (job, first, last) { for (var itemIndex = first; itemIndex <= last; itemIndex++) { var itemData = that.items.itemDataAt(itemIndex); if (itemData) { var record = itemData.itemsManagerRecord; itemIsReady(itemIndex, record); updateCount++; queueStage1AfterStage0(job, record); } } }; // PendingItemPromises are the item promises which we have requested from the ItemsManager // which have not returned an element (placeholder or real). Since we only clean up items // which have an element in _unrealizeItems we need to remember these item promises. We cancel // the item promises from the previous realization iteration if those item promises are not // used for the current realization. this._previousRealizationPendingItemPromises = this._pendingItemPromises || {}; this._pendingItemPromises = {}; var emptyFront; if (direction === "left") { queueLeft(that._onscreenJob, firstInView, lastInView); queueLeft(that._frontOffscreenJob, begin, firstInView - 1); emptyFront = begin > (firstInView - 1); } else { queueRight(that._onscreenJob, firstInView, lastInView); queueRight(that._frontOffscreenJob, lastInView + 1, end - 1); emptyFront = lastInView + 1 > (end - 1); } // Anything left in _previousRealizationPendingItemPromises can be canceled here. // Note: we are doing this synchronously. If we didn't do it synchronously we would have had to merge // _previousRealizationPendingItemPromises and _pendingItemPromises together. This also has the great // benefit to cancel item promises in the backOffScreenArea which are much less important. for (var i = 0, handles = Object.keys(this._previousRealizationPendingItemPromises), len = handles.length; i < len; i++) { var handle = handles[i]; that._listView._itemsManager.releaseItemPromise(this._previousRealizationPendingItemPromises[handle]); } this._previousRealizationPendingItemPromises = {}; // Handle existing items in the second pass to make sure that raising ready signal is added to the queues after creating items handleExistingRange(that._onscreenJob, firstInView, lastInView); if (direction === "left") { handleExistingRange(that._frontOffscreenJob, begin, firstInView - 1); } else { handleExistingRange(that._frontOffscreenJob, lastInView + 1, end - 1); } var showProgress = (inViewCounter === lastInView - firstInView + 1); if (that._firstLayoutPass) { that._listView._canvas.style.opacity = 0; } else { if (showProgress) { that._listView._showProgressBar(that._listView._element, "50%", "50%"); } else { that._listView._hideProgressBar(); } } that._frontOffscreenJob.pause(); that._backOffscreenJob.pause(); viewportItemsRealized.promise.done( function () { that._frontOffscreenJob.resume(); if (emptyFront) { frontItemsRealized.complete(); } }, function () { workCompleteSignal.cancel(); } ); frontItemsRealized.promise.done(function () { that._listView._writeProfilerMark("frontItemsRealized,info"); if (direction === "left") { queueRight(that._backOffscreenJob, lastInView + 1, end - 1); handleExistingRange(that._backOffscreenJob, lastInView + 1, end - 1); } else { queueLeft(that._backOffscreenJob, begin, firstInView - 1); handleExistingRange(that._backOffscreenJob, begin, firstInView - 1); } that._backOffscreenJob.resume(); }); workCompleteSignal.promise.done( function () { that._listView._versionManager.clearCancelOnNotification(cancelToken); that._listView._writeProfilerMark(perfId + " complete(created:" + createCount + " updated:" + updateCount + "),info"); }, function (err) { that._listView._versionManager.clearCancelOnNotification(cancelToken); that._onscreenJob.clearWork(); that._frontOffscreenJob.clearWork(); that._backOffscreenJob.clearWork(); entranceAnimationSignal.cancel(); viewportItemsRealized.cancel(); that._listView._writeProfilerMark(perfId + " canceled(created:" + createCount + " updated:" + updateCount + " clean:" + cleanCount + "),info"); return WinJS.Promise.wrapError(err); } ); that._listView._writeProfilerMark(perfId + ",StopTM"); return { viewportItemsRealized: viewportItemsRealized.promise, allItemsRealized: workCompleteSignal.promise, loadingCompleted: Promise.join([workCompleteSignal.promise, entranceAnimationSignal.promise]).then(function () { var promises = []; for (var i = begin; i < end; i++) { var itemData = that.items.itemDataAt(i); if (itemData) { promises.push(itemData.itemsManagerRecord.itemReadyPromise); } } return WinJS.Promise._cancelBlocker(Promise.join(promises)); }) }; } else { that._listView._writeProfilerMark(perfId + ",StopTM"); return { viewportItemsRealized: Promise.wrap(), allItemsRealized: Promise.wrap(), loadingCompleted: Promise.wrap() }; } }, _setAnimationInViewportState: function VirtualizeContentsView_setAnimationInViewportState(modifiedElements) { this._hasAnimationInViewportPending = false; if (modifiedElements && modifiedElements.length > 0) { var viewportLength = this._listView._getViewportLength(), range = this._listView._layout.itemsFromRange(this._scrollbarPos, this._scrollbarPos + viewportLength - 1); for (var i = 0, len = modifiedElements.length; i < len; i++) { var modifiedElement = modifiedElements[i]; if (modifiedElement.newIndex >= range.firstIndex && modifiedElement.newIndex <= range.lastIndex && modifiedElement.newIndex !== modifiedElement.oldIndex) { this._hasAnimationInViewportPending = true; break; } } } }, _addHeader: function VirtualizeContentsView_addHeader(fragment, groupIndex) { var that = this; return this._listView._groups.renderGroup(groupIndex).then(function (header) { if (header) { var placeholder = that._getHeaderContainer(groupIndex); if (header.element.parentNode !== placeholder) { placeholder.appendChild(header.element); utilities.addClass(header.element, WinJS.UI._headerClass); } that._listView._groups.setDomElement(groupIndex, header.element); } }); }, _updateHeaders: function VirtualizeContentsView_updateHeaders(fragment, begin, end) { var that = this; function updateGroup(index) { var group = that._listView._groups.group(index); if (group && !group.header) { var headerPromise = group.headerPromise; if (!headerPromise) { headerPromise = group.headerPromise = that._addHeader(fragment, index); headerPromise.done(function () { group.headerPromise = null; }, function () { group.headerPromise = null; }); } return headerPromise; } return Promise.wrap(); } this._listView._groups.removeElements(); var groupStart = this._listView._groups.groupFromItem(begin), groupIndex = groupStart, groupEnd = this._listView._groups.groupFromItem(end - 1), realizationPromises = []; if (groupIndex !== null) { //#DBG _ASSERT(groupEnd !== null); for (; groupIndex <= groupEnd; groupIndex++) { realizationPromises.push(updateGroup(groupIndex)); } } function done() { that._headerRenderPromises = null; } this._headerRenderPromises = Promise.join(realizationPromises, this._headerRenderPromises).then(done, done); return this._headerRenderPromises || Promise.wrap(); }, _unrealizeItem: function VirtualizeContentsView_unrealizeItem(itemIndex) { var listView = this._listView, focusedItemPurged; this._listView._writeProfilerMark("_unrealizeItem(" + itemIndex + "),info"); var focused = listView._selection._getFocused(); if (focused.type !== WinJS.UI.ObjectType.groupHeader && focused.index === itemIndex) { listView._unsetFocusOnItem(); focusedItemPurged = true; } var itemData = this.items.itemDataAt(itemIndex), item = itemData.element, itemBox = itemData.itemBox; if (itemBox && itemBox.parentNode) { utilities.removeClass(itemBox.parentNode, WinJS.UI._selectedClass); utilities.removeClass(itemBox.parentNode, WinJS.UI._footprintClass); utilities.addClass(itemBox.parentNode, WinJS.UI._backdropClass); itemBox.parentNode.removeChild(itemBox); } itemData.container = null; if (listView._currentMode().itemUnrealized) { listView._currentMode().itemUnrealized(itemIndex, itemBox); } this.items.removeItem(itemIndex); // If this wasn't released by the itemsManager already, then // we remove it. This handles the special case of delete // occuring on an item that is outside of the current view, but // has not been cleaned up yet. // if (!itemData.removed) { listView._itemsManager.releaseItem(item); } WinJS.Utilities._disposeElement(item); if (focusedItemPurged) { // If the focused item was purged, we'll still want to focus on it if it comes into view sometime in the future. // calling _setFocusOnItem once the item is removed from this.items will set up a promise that will be fulfilled // if the item ever gets reloaded listView._setFocusOnItem(listView._selection._getFocused()); } }, _unrealizeGroup: function VirtualizeContentsView_unrealizeGroup(group) { var headerElement = group.header, focusedItemPurged; var focused = this._listView._selection._getFocused(); if (focused.type === WinJS.UI.ObjectType.groupHeader && this._listView._groups.group(focused.index) === group) { this._listView._unsetFocusOnItem(); focusedItemPurged = true; } if (headerElement.parentNode) { headerElement.parentNode.removeChild(headerElement); } WinJS.Utilities._disposeElement(headerElement); group.header = null; group.left = -1; group.top = -1; if (focusedItemPurged) { this._listView._setFocusOnItem(this._listView._selection._getFocused()); } }, _unrealizeItems: function VirtualizeContentsView_unrealizeItems(remove) { var that = this, removedCount = 0; this.items.eachIndex(function (index) { if (index < that.begin || index >= that.end) { that._unrealizeItem(index); return remove && ++removedCount >= remove; } }); var groups = this._listView._groups, beginGroup = groups.groupFromItem(this.begin); if (beginGroup !== null) { var endGroup = groups.groupFromItem(this.end - 1); for (var i = 0, len = groups.length() ; i < len; i++) { var group = groups.group(i); if ((i < beginGroup || i > endGroup) && group.header) { this._unrealizeGroup(group); } } } }, _unrealizeExcessiveItems: function VirtualizeContentsView_unrealizeExcessiveItems() { var realized = this.items.count(), needed = this.end - this.begin, approved = needed + this._listView._maxDeferredItemCleanup; this._listView._writeProfilerMark("_unrealizeExcessiveItems realized(" + realized + ") approved(" + approved + "),info"); if (realized > approved) { this._unrealizeItems(realized - approved); } }, _lazilyUnrealizeItems: function VirtualizeContentsView_lazilyUnrealizeItems() { this._listView._writeProfilerMark("_lazilyUnrealizeItems,StartTM"); var that = this; return waitForSeZo(this._listView).then(function () { function done() { that._listView._writeProfilerMark("_lazilyUnrealizeItems,StopTM"); } if (that._listView._isZombie()) { done(); return; } var itemsToUnrealize = []; that.items.eachIndex(function (index) { if (index < that.begin || index >= that.end) { itemsToUnrealize.push(index); } }); that._listView._writeProfilerMark("_lazilyUnrealizeItems itemsToUnrealize(" + itemsToUnrealize.length + "),info"); var groupsToUnrealize = [], groups = that._listView._groups, beginGroup = groups.groupFromItem(that.begin); if (beginGroup !== null) { var endGroup = groups.groupFromItem(that.end - 1); for (var i = 0, len = groups.length() ; i < len; i++) { var group = groups.group(i); if ((i < beginGroup || i > endGroup) && group.header) { groupsToUnrealize.push(group); } } } if (itemsToUnrealize.length || groupsToUnrealize.length) { var job; var promise = new Promise(function (complete) { function unrealizeWorker(info) { if (that._listView._isZombie()) { return; } var firstIndex = -1, lastIndex = -1, removeCount = 0, zooming = shouldWaitForSeZo(that._listView); while (itemsToUnrealize.length && !zooming && !info.shouldYield) { var itemIndex = itemsToUnrealize.shift(); that._unrealizeItem(itemIndex); removeCount++; if (firstIndex < 0) { firstIndex = itemIndex; } lastIndex = itemIndex; } that._listView._writeProfilerMark("unrealizeWorker removeItems:" + removeCount + " (" + firstIndex + "-" + lastIndex + "),info"); while (groupsToUnrealize.length && !zooming && !info.shouldYield) { that._unrealizeGroup(groupsToUnrealize.shift()); } if (itemsToUnrealize.length || groupsToUnrealize.length) { if (zooming) { info.setPromise(waitForSeZo(that._listView).then(function () { return unrealizeWorker; })); } else { info.setWork(unrealizeWorker); } } else { complete(); } } job = Scheduler.schedule(unrealizeWorker, Scheduler.Priority.belowNormal, null, "WinJS.UI.ListView._lazilyUnrealizeItems"); }); return promise.then(done, function (error) { job.cancel(); that._listView._writeProfilerMark("_lazilyUnrealizeItems canceled,info"); that._listView._writeProfilerMark("_lazilyUnrealizeItems,StopTM"); return Promise.wrapError(error); }); } else { done(); return Promise.wrap(); } }); }, _getBoundingRectString: function VirtualizeContentsView_getBoundingRectString(itemIndex) { var result; if (itemIndex >= 0 && itemIndex < this.containers.length) { var itemPos = this._listView._layout._getItemPosition(itemIndex); if (itemPos) { result = "[" + itemPos.left + "; " + itemPos.top + "; " + itemPos.width + "; " + itemPos.height + " ]"; } } return result || ""; }, _clearDeferTimeout: function VirtualizeContentsView_clearDeferTimeout() { if (this.deferTimeout) { this.deferTimeout.cancel(); this.deferTimeout = null; } if (this.deferredActionCancelToken !== -1) { this._listView._versionManager.clearCancelOnNotification(this.deferredActionCancelToken); this.deferredActionCancelToken = -1; } }, _setupAria: function VirtualizeContentsView_setupAria(timedOut) { if (this._listView._isZombie()) { return; } var that = this; function done() { that._listView._writeProfilerMark("aria work,StopTM"); } function calcLastRealizedIndexInGroup(groupIndex) { var groups = that._listView._groups, nextGroup = groups.group(groupIndex + 1); return (nextGroup ? Math.min(nextGroup.startIndex - 1, that.end - 1) : that.end - 1); } this._listView._createAriaMarkers(); return this._listView._itemsCount().then(function (count) { if (count > 0 && that.firstIndexDisplayed !== -1 && that.lastIndexDisplayed !== -1) { that._listView._writeProfilerMark("aria work,StartTM"); var startMarker = that._listView._ariaStartMarker, endMarker = that._listView._ariaEndMarker, index = that.begin, item = that.items.itemAt(that.begin), job, // These are only used when the ListView is using groups groups, startGroup, currentGroup, group, lastRealizedIndexInGroup; if (item) { WinJS.UI._ensureId(item); if (that._listView._groupsEnabled()) { groups = that._listView._groups; startGroup = currentGroup = groups.groupFromItem(that.begin); group = groups.group(currentGroup); lastRealizedIndexInGroup = calcLastRealizedIndexInGroup(currentGroup); WinJS.UI._ensureId(group.header); WinJS.UI._setAttribute(group.header, "role", that._listView._headerRole); WinJS.UI._setAttribute(group.header, "x-ms-aria-flowfrom", startMarker.id); WinJS.UI._setFlow(group.header, item); WinJS.UI._setAttribute(group.header, "tabindex", that._listView._tabIndex); } else { WinJS.UI._setAttribute(item, "x-ms-aria-flowfrom", startMarker.id); } return new Promise(function (completeJobPromise) { var skipWait = timedOut; job = Scheduler.schedule(function ariaWorker(jobInfo) { if (that._listView._isZombie()) { done(); return; } for (; index < that.end; index++) { if (!skipWait && shouldWaitForSeZo(that._listView)) { jobInfo.setPromise(waitForSeZo(that._listView).then(function (timedOut) { skipWait = timedOut; return ariaWorker; })); return; } else if (jobInfo.shouldYield) { jobInfo.setWork(ariaWorker); return; } item = that.items.itemAt(index); var nextItem = that.items.itemAt(index + 1); if (nextItem) { WinJS.UI._ensureId(nextItem); } WinJS.UI._setAttribute(item, "role", that._listView._itemRole); WinJS.UI._setAttribute(item, "aria-setsize", count); WinJS.UI._setAttribute(item, "aria-posinset", index + 1); WinJS.UI._setAttribute(item, "tabindex", that._listView._tabIndex); if (that._listView._groupsEnabled()) { if (index === lastRealizedIndexInGroup || !nextItem) { var nextGroup = groups.group(currentGroup + 1); // If group is the last realized group, then nextGroup won't exist in the DOM. // When this is the case, nextItem shouldn't exist. //#DBG _ASSERT(nextGroup && nextGroup.header || !nextItem); if (nextGroup && nextGroup.header && nextItem) { WinJS.UI._setAttribute(nextGroup.header, "tabindex", that._listView._tabIndex); WinJS.UI._setAttribute(nextGroup.header, "role", that._listView._headerRole); WinJS.UI._ensureId(nextGroup.header); WinJS.UI._setFlow(item, nextGroup.header); WinJS.UI._setFlow(nextGroup.header, nextItem); } else { // We're at the last group so flow to the end marker WinJS.UI._setAttribute(item, "aria-flowto", endMarker.id); } currentGroup++; group = nextGroup; lastRealizedIndexInGroup = calcLastRealizedIndexInGroup(currentGroup); } else { // This is not the last item in the group so flow to the next item //#DBG _ASSERT(nextItem); WinJS.UI._setFlow(item, nextItem); } } else if (nextItem) { // Groups are disabled so as long as we aren't at the last item, flow to the next one WinJS.UI._setFlow(item, nextItem); } else { // Groups are disabled and we're at the last item, so flow to the end marker WinJS.UI._setAttribute(item, "aria-flowto", endMarker.id); } if (!nextItem) { break; } } that._listView._fireAccessibilityAnnotationCompleteEvent(that.begin, index, startGroup, currentGroup - 1); done(); completeJobPromise(); }, Scheduler.Priority.belowNormal, null, "WinJS.UI.ListView._setupAria"); }, function () { // Cancellation handler for promise returned by setupAria job.cancel(); done(); }); } else { // the first item is null done(); } } else { // The count is 0 return Promise.wrap(); } }); }, _setupDeferredActions: function VirtualizeContentsView_setupDeferredActions() { this._listView._writeProfilerMark("_setupDeferredActions,StartTM"); var that = this; this._clearDeferTimeout(); function cleanUp() { if (that._listView._isZombie()) { return; } that.deferTimeout = null; that._listView._versionManager.clearCancelOnNotification(that.deferredActionCancelToken); that.deferredActionCancelToken = -1; } this.deferTimeout = this._lazilyRemoveRedundantItemsBlocks().then(function() { return WinJS.Promise.timeout(WinJS.UI._DEFERRED_ACTION); }). then(function () { return waitForSeZo(that._listView); }). then(function (timedOut) { return that._setupAria(timedOut); }). then(cleanUp, function (error) { cleanUp(); return Promise.wrapError(error); }); this.deferredActionCancelToken = this._listView._versionManager.cancelOnNotification(this.deferTimeout); this._listView._writeProfilerMark("_setupDeferredActions,StopTM"); }, // Sets aria-flowto on _ariaStartMarker and x-ms-aria-flowfrom on _ariaEndMarker. The former // points to either the first visible group header or the first visible item. The latter points // to the last visible item. _updateAriaMarkers: function VirtualizeContentsView_updateAriaMarkers(listViewIsEmpty, firstIndexDisplayed, lastIndexDisplayed) { var that = this; if (this._listView._isZombie()) { return; } function getFirstVisibleItem() { return that.items.itemAt(firstIndexDisplayed); } // At a certain index, the VDS may return null for all items at that index and // higher. When this is the case, the end marker should point to the last // non-null item in the visible range. function getLastVisibleItem() { for (var i = lastIndexDisplayed; i >= firstIndexDisplayed; i--) { if (that.items.itemAt(i)) { return that.items.itemAt(i); } } return null; } this._listView._createAriaMarkers(); var startMarker = this._listView._ariaStartMarker, endMarker = this._listView._ariaEndMarker, firstVisibleItem, lastVisibleItem; if (firstIndexDisplayed !== -1 && lastIndexDisplayed !== -1 && firstIndexDisplayed <= lastIndexDisplayed) { firstVisibleItem = getFirstVisibleItem(); lastVisibleItem = getLastVisibleItem(); } if (listViewIsEmpty || !firstVisibleItem || !lastVisibleItem) { WinJS.UI._setFlow(startMarker, endMarker); this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1); } else { WinJS.UI._ensureId(firstVisibleItem); WinJS.UI._ensureId(lastVisibleItem); // Set startMarker's flowto if (this._listView._groupsEnabled()) { var groups = this._listView._groups, firstVisibleGroup = groups.group(groups.groupFromItem(firstIndexDisplayed)); if (firstVisibleGroup.header) { WinJS.UI._ensureId(firstVisibleGroup.header); if (firstIndexDisplayed === firstVisibleGroup.startIndex) { WinJS.UI._setAttribute(startMarker, "aria-flowto", firstVisibleGroup.header.id); } else { WinJS.UI._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id); } } } else { WinJS.UI._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id); } // Set endMarker's flowfrom WinJS.UI._setAttribute(endMarker, "x-ms-aria-flowfrom", lastVisibleItem.id); } }, // Update the ARIA attributes on item that are needed so that Narrator can announce it. // item must be in the items container. updateAriaForAnnouncement: function VirtualizeContentsView_updateAriaForAnnouncement(item, count) { var index = -1; var type = WinJS.UI.ObjectType.item; if (WinJS.Utilities.hasClass(item, WinJS.UI._headerClass)) { index = this._listView._groups.index(item); //#DBG _ASSERT(index !== WinJS.UI._INVALID_INDEX); type = WinJS.UI.ObjectType.groupHeader; WinJS.UI._setAttribute(item, "role", this._listView._headerRole); } else { index = this.items.index(item); //#DBG _ASSERT(index !== WinJS.UI._INVALID_INDEX); WinJS.UI._setAttribute(item, "aria-setsize", count); WinJS.UI._setAttribute(item, "aria-posinset", index + 1); WinJS.UI._setAttribute(item, "role", this._listView._itemRole); } if (type === WinJS.UI.ObjectType.groupHeader) { this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1, index, index); } else { this._listView._fireAccessibilityAnnotationCompleteEvent(index, index, -1, -1); } }, _reportElementsLevel: function VirtualizeContentsView_reportElementsLevel(direction) { var items = this.items; function elementsCount(first, last) { var count = 0; for (var itemIndex = first; itemIndex <= last; itemIndex++) { var itemData = items.itemDataAt(itemIndex); if (itemData && itemData.container) { count++; } } return count; } var level; if (direction === "right") { level = Math.floor(100 * elementsCount(this.firstIndexDisplayed, this.end - 1) / (this.end - this.firstIndexDisplayed)); } else { level = Math.floor(100 * elementsCount(this.begin, this.lastIndexDisplayed) / (this.lastIndexDisplayed - this.begin + 1)); } this._listView._writeProfilerMark("elementsLevel level(" + level + "),info"); }, _createHeaderContainer: function VirtualizeContentsView_createHeaderContainer(insertAfter) { return this._createSurfaceChild(WinJS.UI._headerContainerClass, insertAfter); }, _createItemsContainer: function VirtualizeContentsView_createItemsContainer(insertAfter) { var itemsContainer = this._createSurfaceChild(WinJS.UI._itemsContainerClass, insertAfter); var padder = document.createElement("div"); padder.className = WinJS.UI._padderClass; itemsContainer.appendChild(padder); return itemsContainer; }, _ensureContainerInDOM: function VirtualizeContentsView_ensureContainerInDOM(index) { var container = this.containers[index]; if (container && !this._listView._canvas.contains(container)) { this._forceItemsBlocksInDOM(index, index + 1); return true; } return false; }, _ensureItemsBlocksInDOM: function VirtualizeContentsView_ensureItemsBlocksInDOM(begin, end) { if (this._expandedRange) { var oldBegin = this._expandedRange.first.index, oldEnd = this._expandedRange.last.index + 1; if (begin <= oldBegin && end > oldBegin) { end = Math.max(end, oldEnd); } else if (begin < oldEnd && end >= oldEnd) { begin = Math.min(begin, oldBegin); } } this._forceItemsBlocksInDOM(begin, end); }, _removeRedundantItemsBlocks: function VirtualizeContentsView_removeRedundantItemsBlocks() { if (this.begin !== -1 && this.end !== -1) { this._forceItemsBlocksInDOM(this.begin, this.end); } }, _lazilyRemoveRedundantItemsBlocks: function VirtualizeContentsView_lazilyRemoveRedundantItemsBlocks() { this._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks,StartTM"); var that = this; return waitForSeZo(this._listView).then(function () { function done() { that._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks,StopTM"); } if (that._listView._isZombie()) { done(); return; } if (that._expandedRange && that.begin !== -1 && that.end !== -1 && (that._expandedRange.first.index < that.begin || that._expandedRange.last.index + 1 > that.end)) { var job; var promise = new Promise(function (complete) { function blocksCleanupWorker(info) { if (that._listView._isZombie()) { return; } var zooming = shouldWaitForSeZo(that._listView); while (that._expandedRange.first.index < that.begin && !zooming && !info.shouldYield) { var begin = Math.min(that.begin, that._expandedRange.first.index + that._blockSize * WinJS.UI._VirtualizeContentsView._blocksToRelease); that._forceItemsBlocksInDOM(begin, that.end); } while (that._expandedRange.last.index + 1 > that.end && !zooming && !info.shouldYield) { var end = Math.max(that.end, that._expandedRange.last.index - that._blockSize * WinJS.UI._VirtualizeContentsView._blocksToRelease); that._forceItemsBlocksInDOM(that.begin, end); } if (that._expandedRange.first.index < that.begin || that._expandedRange.last.index + 1 > that.end) { if (zooming) { info.setPromise(waitForSeZo(that._listView).then(function () { return blocksCleanupWorker; })); } else { info.setWork(blocksCleanupWorker); } } else { complete(); } } job = Scheduler.schedule(blocksCleanupWorker, Scheduler.Priority.belowNormal, null, "WinJS.UI.ListView._lazilyRemoveRedundantItemsBlocks"); }); return promise.then(done, function (error) { job.cancel(); that._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks canceled,info"); that._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks,StopTM"); return Promise.wrapError(error); }); } else { done(); return Promise.wrap(); } }); }, _forceItemsBlocksInDOM: function VirtualizeContentsView_forceItemsBlocksInDOM(begin, end) { if (!this._blockSize) { return; } var perfId = "_forceItemsBlocksInDOM begin(" + begin + ") end(" + end + "),"; this._listView._writeProfilerMark(perfId + "StartTM"); var that = this, added = 0, removed = 0, paddingProperty = "padding" + (this._listView._horizontal() ? "Left" : "Top"); function setPadder(itemsContainer, padding) { var padder = itemsContainer.element.firstElementChild; padder.style[paddingProperty] = padding; } function forEachBlock(callback) { for (var g = 0; g < that.tree.length; g++) { var itemsContainer = that.tree[g].itemsContainer; for (var b = 0, len = itemsContainer.itemsBlocks.length; b < len; b++) { if (callback(itemsContainer, itemsContainer.itemsBlocks[b])) { return; } } } } function measureItemsBlock(itemsBlock) { that._listView._writeProfilerMark("_itemsBlockExtent,StartTM"); that._listView._itemsBlockExtent = utilities[that._listView._horizontal() ? "getTotalWidth" : "getTotalHeight"](itemsBlock.element); that._listView._writeProfilerMark("_itemsBlockExtent(" + that._listView._itemsBlockExtent + "),info"); that._listView._writeProfilerMark("_itemsBlockExtent,StopTM"); } function getItemsBlockExtent() { if (that._listView._itemsBlockExtent === -1) { // first try blocks already added to the DOM forEachBlock(function (itemsContainer, itemsBlock) { if (itemsBlock.items.length === that._blockSize && itemsBlock.element.parentNode === itemsContainer.element) { measureItemsBlock(itemsBlock); return true; } return false; }); } if (that._listView._itemsBlockExtent === -1) { forEachBlock(function (itemsContainer, itemsBlock) { if (itemsBlock.items.length === that._blockSize) { itemsContainer.element.appendChild(itemsBlock.element); measureItemsBlock(itemsBlock); itemsContainer.element.removeChild(itemsBlock.element); return true; } return false; }); } return that._listView._itemsBlockExtent; } function removeBlocks(itemsContainer, begin, end) { function remove(blockIndex) { var block = itemsContainer.itemsBlocks[blockIndex]; if (block && block.element.parentNode === itemsContainer.element) { itemsContainer.element.removeChild(block.element); removed++; } } if (Array.isArray(begin)) { begin.forEach(remove); } else { for (var i = begin; i < end; i++) { remove(i); } } } function addBlocks(itemsContainer, begin, end) { var padder = itemsContainer.element.firstElementChild, previous = padder; for (var i = begin; i < end; i++) { var block = itemsContainer.itemsBlocks[i]; if (block) { if (block.element.parentNode !== itemsContainer.element) { itemsContainer.element.insertBefore(block.element, previous.nextElementSibling); added++; } previous = block.element; } } } function collapseGroup(groupIndex) { if (groupIndex < that.tree.length) { that._listView._writeProfilerMark("collapseGroup(" + groupIndex + "),info"); var itemsContainer = that.tree[groupIndex].itemsContainer; removeBlocks(itemsContainer, 0, itemsContainer.itemsBlocks.length); setPadder(itemsContainer, ""); } } function expandGroup(groupIndex) { if (groupIndex < that.tree.length) { that._listView._writeProfilerMark("expandGroup(" + groupIndex + "),info"); var itemsContainer = that.tree[groupIndex].itemsContainer; addBlocks(itemsContainer, 0, itemsContainer.itemsBlocks.length); setPadder(itemsContainer, ""); } } function removedFromRange(oldRange, newRange) { function expand(first, last) { var array = []; for (var i = first; i <= last; i++) { array.push(i); } return array; } var newL = newRange[0]; var newR = newRange[1]; var oldL = oldRange[0]; var oldR = oldRange[1]; if (newR < oldL || newL > oldR) { return expand(oldL, oldR); } else if (newL > oldL && newR < oldR) { return expand(oldL, newL - 1).concat(expand(newR + 1, oldR)); } else if (oldL < newL) { return expand(oldL, newL - 1); } else if (oldR > newR) { return expand(newR + 1, oldR); } else { return null; } } var firstGroupIndex = this._listView._groups.groupFromItem(begin), lastGroupIndex = this._listView._groups.groupFromItem(end - 1); var firstGroup = this._listView._groups.group(firstGroupIndex), firstItemsContainer = that.tree[firstGroupIndex].itemsContainer; var firstBlock = Math.floor((begin - firstGroup.startIndex) / this._blockSize); var lastGroup = this._listView._groups.group(lastGroupIndex), lastItemsContainer = that.tree[lastGroupIndex].itemsContainer; var lastBlock = Math.floor((end - 1 - lastGroup.startIndex) / this._blockSize); // if size of structure block is needed try to obtain it before modifying the tree to avoid a layout pass if (firstBlock && that._listView._itemsBlockExtent === -1) { forEachBlock(function (itemsContainer, itemsBlock) { if (itemsBlock.items.length === that._blockSize && itemsBlock.element.parentNode === itemsContainer.element) { measureItemsBlock(itemsBlock); return true; } return false; }); } var groupsToCollapse = this._expandedRange ? removedFromRange([this._expandedRange.first.groupIndex, this._expandedRange.last.groupIndex], [firstGroupIndex, lastGroupIndex]) : null; if (groupsToCollapse) { groupsToCollapse.forEach(collapseGroup); } if (this._expandedRange && this._expandedRange.first.groupKey === firstGroup.key) { var blocksToRemove = removedFromRange([this._expandedRange.first.block, Number.MAX_VALUE], [firstBlock, Number.MAX_VALUE]); if (blocksToRemove) { removeBlocks(firstItemsContainer, blocksToRemove); } } else if (this._expandedRange && firstGroupIndex >= this._expandedRange.first.groupIndex && firstGroupIndex <= this._expandedRange.last.groupIndex) { removeBlocks(firstItemsContainer, 0, firstBlock); } if (firstGroupIndex !== lastGroupIndex) { addBlocks(firstItemsContainer, firstBlock, firstItemsContainer.itemsBlocks.length); addBlocks(lastItemsContainer, 0, lastBlock + 1); } else { addBlocks(firstItemsContainer, firstBlock, lastBlock + 1); } if (this._expandedRange && this._expandedRange.last.groupKey === lastGroup.key) { var blocksToRemove = removedFromRange([0, this._expandedRange.last.block], [0, lastBlock]); if (blocksToRemove) { removeBlocks(lastItemsContainer, blocksToRemove); } } else if (this._expandedRange && lastGroupIndex >= this._expandedRange.first.groupIndex && lastGroupIndex <= this._expandedRange.last.groupIndex) { removeBlocks(lastItemsContainer, lastBlock + 1, lastItemsContainer.itemsBlocks.length); } setPadder(firstItemsContainer, firstBlock ? firstBlock * getItemsBlockExtent() + "px" : ""); if (firstGroupIndex !== lastGroupIndex) { setPadder(lastItemsContainer, ""); } // groups between first and last for (var i = firstGroupIndex + 1; i < lastGroupIndex; i++) { expandGroup(i); } this._expandedRange = { first: { index: begin, groupIndex: firstGroupIndex, groupKey: firstGroup.key, block: firstBlock }, last: { index: end - 1, groupIndex: lastGroupIndex, groupKey: lastGroup.key, block: lastBlock }, }; this._listView._writeProfilerMark("_forceItemsBlocksInDOM groups(" + firstGroupIndex + "-" + lastGroupIndex + ") blocks(" + firstBlock + "-" + lastBlock + ") added(" + added + ") removed(" + removed + "),info"); this._listView._writeProfilerMark(perfId + "StopTM"); }, _realizePageImpl: function VirtualizeContentsView_realizePageImpl() { var that = this; var perfId = "realizePage(scrollPosition:" + this._scrollbarPos + " forceLayout:" + this._forceRelayout + ")"; this._listView._writeProfilerMark(perfId + ",StartTM"); // It's safe to skip realizePage, so we just queue up the last request to run when the version manager // get unlocked. // if (this._listView._versionManager.locked) { this._listView._versionManager.unlocked.done(function () { if (!that._listView._isZombie()) { that._listView._batchViewUpdates(WinJS.UI._ViewChange.realize, WinJS.UI._ScrollToPriority.low, that._listView.scrollPosition); } }); this._listView._writeProfilerMark(perfId + ",StopTM"); return Promise.cancel; } return new Promise(function (c) { var renderingCompleteSignal = new WinJS._Signal(); function complete() { c(); renderingCompleteSignal.complete(); } function viewPortPageRealized() { that._listView._hideProgressBar(); that._state.setLoadingState(that._listView._LoadingState.viewPortLoaded); if (that._executeAnimations) { that._setState(RealizingAnimatingState, renderingCompleteSignal.promise); } } function pageRealized(count) { that._updateAriaMarkers(count === 0, that.firstIndexDisplayed, that.lastIndexDisplayed); that._state.setLoadingState && that._state.setLoadingState(that._listView._LoadingState.itemsLoaded); } function finish(count) { that._listView._clearInsertedItems(); that._listView._groups.removeElements(); viewPortPageRealized(); pageRealized(count); complete(); } that._state.setLoadingState(that._listView._LoadingState.itemsLoading); if (that._firstLayoutPass) { that._listView._showProgressBar(that._listView._element, "50%", "50%"); } var count = that.containers.length; if (count) { // While the zoom animation is played we want to minimize the # of pages // being fetched to improve TtFF for SeZo scenarios var pagesToPrefetch = WinJS.UI._VirtualizeContentsView._pagesToPrefetch; if (that._listView._zooming) { pagesToPrefetch = 0; } var viewportLength = that._listView._getViewportLength(), beginningOffset = Math.max(0, that._scrollbarPos - pagesToPrefetch * viewportLength), endingOffset = that._scrollbarPos + (1 + pagesToPrefetch) * viewportLength; var range = that._listView._layout.itemsFromRange(beginningOffset, endingOffset - 1); if ((range.firstIndex < 0 || range.firstIndex >= count) && (range.lastIndex < 0 || range.lastIndex >= count)) { that.begin = -1; that.end = -1; that.firstIndexDisplayed = -1; that.lastIndexDisplayed = -1; finish(count); } else { var begin = utilities._clamp(range.firstIndex, 0, count - 1), end = utilities._clamp(range.lastIndex + 1, 0, count); var inView = that._listView._layout.itemsFromRange(that._scrollbarPos, that._scrollbarPos + viewportLength - 1), firstInView = utilities._clamp(inView.firstIndex, 0, count - 1), lastInView = utilities._clamp(inView.lastIndex, 0, count - 1); if (that._realizationLevel === WinJS.UI._VirtualizeContentsView._realizationLevel.skip && !that.lastRealizePass && firstInView === that.firstIndexDisplayed && lastInView === that.lastIndexDisplayed) { that.begin = begin; that.end = begin + Object.keys(that.items._itemData).length; that._updateHeaders(that._listView._canvas, that.begin, that.end).done(function () { that.lastRealizePass = null; finish(count); }); } else if ((that._forceRelayout || begin !== that.begin || end !== that.end || firstInView !== that.firstIndexDisplayed || lastInView !== that.lastIndexDisplayed) && (begin < end) && (beginningOffset < endingOffset)) { that._listView._writeProfilerMark("realizePage currentInView(" + firstInView + "-" + lastInView + ") previousInView(" + that.firstIndexDisplayed + "-" + that.lastIndexDisplayed + ") change(" + (firstInView - that.firstIndexDisplayed) + "),info"); that._cancelRealize(); // cancelRealize changes the realizePass and resets begin/end var currentPass = that._realizePass; that.begin = begin; that.end = end; that.firstIndexDisplayed = firstInView; that.lastIndexDisplayed = lastInView; that.deletesWithoutRealize = 0; that._ensureItemsBlocksInDOM(that.begin, that.end); var realizeWork = that._realizeItems( that._listView._itemCanvas, that.begin, that.end, count, currentPass, that._scrollbarPos, that._direction, firstInView, lastInView, that._forceRelayout); that._forceRelayout = false; var realizePassWork = realizeWork.viewportItemsRealized.then(function () { viewPortPageRealized(); return realizeWork.allItemsRealized; }).then(function () { if (that._realizePass === currentPass) { return that._updateHeaders(that._listView._canvas, that.begin, that.end).then(function () { pageRealized(count); }); } }).then(function () { return realizeWork.loadingCompleted; }).then( function () { that._unrealizeExcessiveItems(); that.lastRealizePass = null; complete(); }, function (e) { if (that._realizePass === currentPass) { that.lastRealizePass = null; that.begin = -1; that.end = -1; } return WinJS.Promise.wrapError(e); } ); that.lastRealizePass = Promise.join([realizeWork.viewportItemsRealized, realizeWork.allItemsRealized, realizeWork.loadingCompleted, realizePassWork]); that._unrealizeExcessiveItems(); } else if (!that.lastRealizePass) { // We are currently in the "itemsLoading" state and need to get back to "complete". The // previous realize pass has been completed so proceed to the other states. finish(count); } else { that.lastRealizePass.then(complete); } } } else { that.begin = -1; that.end = -1; that.firstIndexDisplayed = -1; that.lastIndexDisplayed = -1; finish(count); } that._reportElementsLevel(that._direction); that._listView._writeProfilerMark(perfId + ",StopTM"); }); }, realizePage: function VirtualizeContentsView_realizePage(scrollToFunctor, forceRelayout, scrollEndPromise, StateType) { this._scrollToFunctor = makeFunctor(scrollToFunctor); this._forceRelayout = this._forceRelayout || forceRelayout; this._scrollEndPromise = scrollEndPromise; this._listView._writeProfilerMark(this._state.name + "_realizePage,info"); this._state.realizePage(StateType || RealizingState); }, onScroll: function VirtualizeContentsView_onScroll(scrollToFunctor, scrollEndPromise) { this.realizePage(scrollToFunctor, false, scrollEndPromise, ScrollingState); }, reload: function VirtualizeContentsView_reload(scrollToFunctor, highPriority) { if (this._listView._isZombie()) { return; } this._scrollToFunctor = makeFunctor(scrollToFunctor); this._forceRelayout = true; this._highPriorityRealize = !!highPriority; this.stopWork(true); this._listView._writeProfilerMark(this._state.name + "_rebuildTree,info"); this._state.rebuildTree(); }, refresh: function VirtualizeContentsView_refresh(scrollToFunctor) { if (this._listView._isZombie()) { return; } this._scrollToFunctor = makeFunctor(scrollToFunctor); this._forceRelayout = true; this._highPriorityRealize = true; this.stopWork(); this._listView._writeProfilerMark(this._state.name + "_relayout,info"); this._state.relayout(); }, waitForValidScrollPosition: function VirtualizeContentsView_waitForValidScrollPosition(newPosition) { var that = this; var currentMaxScroll = this._listView._viewport[this._listView._scrollLength] - this._listView._getViewportLength(); if (newPosition > currentMaxScroll) { return that._listView._itemsCount().then(function (count) { // Wait until we have laid out enough containers to be able to set the scroll position to newPosition if (that.containers.length < count) { return Promise._cancelBlocker(that._creatingContainersWork && that._creatingContainersWork.promise).then(function () { return that._getLayoutCompleted(); }).then(function () { return newPosition; }); } else { return newPosition; } }); } else { return WinJS.Promise.wrap(newPosition); } }, waitForEntityPosition: function VirtualizeContentsView_waitForEntityPosition(entity) { var that = this; this._listView._writeProfilerMark(this._state.name + "_waitForEntityPosition" + "(" + entity.type + ": " + entity.index + ")" + ",info"); return Promise._cancelBlocker(this._state.waitForEntityPosition(entity).then(function () { if ((entity.type !== WinJS.UI.ObjectType.groupHeader && entity.index >= that.containers.length) || (entity.type === WinJS.UI.ObjectType.groupHeader && that._listView._groups.group(entity.index).startIndex >= that.containers.length)) { return that._creatingContainersWork && that._creatingContainersWork.promise; } }).then(function () { return that._getLayoutCompleted(); })); }, stopWork: function VirtualizeContentsView_stopWork(stopTreeCreation) { this._listView._writeProfilerMark(this._state.name + "_stop,info"); this._state.stop(stopTreeCreation); if (this._layoutWork) { this._layoutWork.cancel(); } if (stopTreeCreation && this._creatingContainersWork) { this._creatingContainersWork.cancel(); } if (stopTreeCreation) { this._state = new CreatedState(this); } }, _cancelRealize: function VirtualizeContentsView_cancelRealize() { this._listView._writeProfilerMark("_cancelRealize,StartTM"); if (this.lastRealizePass || this.deferTimeout) { this._forceRelayout = true; } this._clearDeferTimeout(); this._realizePass++; if (this._headerRenderPromises) { this._headerRenderPromises.cancel(); this._headerRenderPromises = null; } var last = this.lastRealizePass; if (last) { this.lastRealizePass = null; this.begin = -1; this.end = -1; last.cancel(); } this._listView._writeProfilerMark("_cancelRealize,StopTM"); }, resetItems: function VirtualizeContentsView_resetItems(unparent) { if (!this._listView._isZombie()) { this.firstIndexDisplayed = -1; this.lastIndexDisplayed = -1; this._runningAnimations = null; this._executeAnimations = false; var listView = this._listView; this._firstLayoutPass = true; listView._unsetFocusOnItem(); if (listView._currentMode().onDataChanged) { listView._currentMode().onDataChanged(); } this.items.each(function (index, item) { if (unparent && item.parentNode && item.parentNode.parentNode) { item.parentNode.parentNode.removeChild(item.parentNode); } listView._itemsManager.releaseItem(item); WinJS.Utilities._disposeElement(item); }); this.items.removeItems(); this._deferredReparenting = []; if (unparent) { listView._groups.removeElements(); } listView._clearInsertedItems(); } }, reset: function VirtualizeContentsView_reset() { this.stopWork(true); this._state = new CreatedState(this); this.resetItems(); // when in the zombie state, we let disposal cleanup the ScrollView state // if (!this._listView._isZombie()) { var listView = this._listView; listView._groups.resetGroups(); listView._resetCanvas(); this.tree = null; this.keyToGroupIndex = null; this.containers = null; this._expandedRange = null; } }, cleanUp: function VirtualizeContentsView_cleanUp() { this.stopWork(true); this._runningAnimations && this._runningAnimations.cancel(); var itemsManager = this._listView._itemsManager; this.items.each(function (index, item) { itemsManager.releaseItem(item); WinJS.Utilities._disposeElement(item); }); this._listView._unsetFocusOnItem(); this.items.removeItems(); this._deferredReparenting = []; this._listView._groups.resetGroups(); this._listView._resetCanvas(); this.tree = null; this.keyToGroupIndex = null; this.containers = null; this._expandedRange = null; this.destroyed = true; }, getContainer: function VirtualizeContentsView_getContainer(itemIndex) { return this.containers[itemIndex]; }, _getHeaderContainer: function VirtualizeContentsView_getHeaderContainer(groupIndex) { return this.tree[groupIndex].header; }, _getGroups: function VirtualizeContentsView_getGroups(count) { if (this._listView._groupDataSource) { var groupsContainer = this._listView._groups.groups, groups = []; if (count) { for (var i = 0, len = groupsContainer.length; i < len; i++) { var group = groupsContainer[i], nextStartIndex = i + 1 < len ? groupsContainer[i + 1].startIndex : count; groups.push({ key: group.key, size: nextStartIndex - group.startIndex }); } } return groups; } else { return [{ key: "-1", size: count }]; } }, _createChunk: function VirtualizeContentsView_createChunk(groups, count, chunkSize) { var that = this; this._listView._writeProfilerMark("createChunk,StartTM"); function addToGroup(itemsContainer, groupSize) { var children = itemsContainer.element.children, oldSize = children.length, toAdd = Math.min(groupSize - itemsContainer.items.length, chunkSize); utilities.insertAdjacentHTMLUnsafe(itemsContainer.element, "beforeend", WinJS.UI._repeat("
", toAdd)); for (var i = 0; i < toAdd; i++) { var container = children[oldSize + i]; itemsContainer.items.push(container); that.containers.push(container); } } function newGroup(group) { var node = { header: that._listView._groupDataSource ? that._createHeaderContainer() : null, itemsContainer: { element: that._createItemsContainer(), items: [] } }; that.tree.push(node); that.keyToGroupIndex[group.key] = that.tree.length - 1; addToGroup(node.itemsContainer, group.size); } if (this.tree.length && this.tree.length <= groups.length) { var last = this.tree[this.tree.length - 1], finalSize = groups[this.tree.length - 1].size; // check if the last group in the tree already has all items. If not add items to this group if (last.itemsContainer.items.length < finalSize) { addToGroup(last.itemsContainer, finalSize); this._listView._writeProfilerMark("createChunk,StopTM"); return; } } if (this.tree.length < groups.length) { newGroup(groups[this.tree.length]); } this._listView._writeProfilerMark("createChunk,StopTM"); }, _createChunkWithBlocks: function VirtualizeContentsView_createChunkWithBlocks(groups, count, blockSize, chunkSize) { var that = this; this._listView._writeProfilerMark("createChunk,StartTM"); function addToGroup(itemsContainer, toAdd) { var lastExistingBlock = itemsContainer.itemsBlocks.length ? itemsContainer.itemsBlocks[itemsContainer.itemsBlocks.length - 1] : null; if (lastExistingBlock && lastExistingBlock.items.length < blockSize) { var fix = Math.min(toAdd, blockSize - lastExistingBlock.items.length); utilities.insertAdjacentHTMLUnsafe(lastExistingBlock.element, "beforeend", WinJS.UI._repeat("
", fix)); var oldSize = lastExistingBlock.items.length; children = lastExistingBlock.element.children; for (var j = 0; j < fix; j++) { var child = children[oldSize + j]; lastExistingBlock.items.push(child); that.containers.push(child); } toAdd -= fix; } if (toAdd > chunkSize) { toAdd = Math.min(toAdd, Math.max(1, Math.floor(chunkSize / blockSize)) * blockSize); } var blocks = Math.floor(toAdd / blockSize), lastBlockSize = toAdd % blockSize; var blockMarkup = "
" + WinJS.UI._repeat("
", blockSize) + "
", markup = WinJS.UI._repeat(blockMarkup, blocks); if (lastBlockSize) { markup += "
" + WinJS.UI._repeat("
", lastBlockSize) + "
"; blocks++; } var blocksTemp = document.createElement("div"); utilities.setInnerHTMLUnsafe(blocksTemp, markup); var children = blocksTemp.children; for (var i = 0; i < blocks; i++) { var block = children[i], blockNode = { element: block, items: WinJS.UI._nodeListToArray(block.children) }; itemsContainer.itemsBlocks.push(blockNode); for (var n = 0; n < blockNode.items.length; n++) { that.containers.push(blockNode.items[n]); } } } function newGroup(group) { var node = { header: that._listView._groupDataSource ? that._createHeaderContainer() : null, itemsContainer: { element: that._createItemsContainer(), itemsBlocks: [] } }; that.tree.push(node); that.keyToGroupIndex[group.key] = that.tree.length - 1; addToGroup(node.itemsContainer, group.size); } if (this.tree.length && this.tree.length <= groups.length) { var lastContainer = this.tree[this.tree.length - 1].itemsContainer, finalSize = groups[this.tree.length - 1].size, currentSize = 0; if (lastContainer.itemsBlocks.length) { currentSize = (lastContainer.itemsBlocks.length - 1) * blockSize + lastContainer.itemsBlocks[lastContainer.itemsBlocks.length - 1].items.length; } if (currentSize < finalSize) { addToGroup(lastContainer, finalSize - currentSize); this._listView._writeProfilerMark("createChunk,StopTM"); return; } } if (this.tree.length < groups.length) { newGroup(groups[this.tree.length]); } this._listView._writeProfilerMark("createChunk,StopTM"); }, _generateCreateContainersWorker: function VirtualizeContentsView_generateCreateContainersWorker() { var that = this, counter = 0, skipWait = false; return function work(info) { if (!that._listView._versionManager.locked) { that._listView._itemsCount().then(function (count) { var zooming = !skipWait && shouldWaitForSeZo(that._listView); if (!zooming) { if (that._listView._isZombie()) { return; } skipWait = false; var end = performance.now() + _VirtualizeContentsView._createContainersJobTimeslice, groups = that._getGroups(count), startLength = that.containers.length, realizedToEnd = that.end === that.containers.length, chunkSize = WinJS.UI._VirtualizeContentsView._chunkSize; do { that._blockSize ? that._createChunkWithBlocks(groups, count, that._blockSize, chunkSize) : that._createChunk(groups, count, chunkSize); counter++; } while (that.containers.length < count && performance.now() < end); that._listView._writeProfilerMark("createContainers yields containers(" + that.containers.length + "),info"); that._listView._affectedRange.add({ start: startLength, end: that.containers.length }, count); if (realizedToEnd) { that.stopWork(); that._listView._writeProfilerMark(that._state.name + "_relayout,info"); that._state.relayout(); } else { that._listView._writeProfilerMark(that._state.name + "_layoutNewContainers,info"); that._state.layoutNewContainers(); } if (that.containers.length < count) { info.setWork(work); } else { that._listView._writeProfilerMark("createContainers completed steps(" + counter + "),info"); that._creatingContainersWork.complete(); } } else { // Waiting on zooming info.setPromise(waitForSeZo(that._listView).then(function (timedOut) { skipWait = timedOut; return work; })); } }); } else { // Version manager locked info.setPromise(that._listView._versionManager.unlocked.then(function () { return work; })); } }; }, _scheduleLazyTreeCreation: function VirtualizeContentsView_scheduleLazyTreeCreation() { return utilities.Scheduler.schedule(this._generateCreateContainersWorker(), utilities.Scheduler.Priority.idle, this, "WinJS.UI.ListView.LazyTreeCreation"); }, _createContainers: function VirtualizeContentsView_createContainers() { this.tree = null; this.keyToGroupIndex = null; this.containers = null; this._expandedRange = null; var that = this, count; return this._listView._itemsCount().then(function (c) { if (c === 0) { that._listView._hideProgressBar(); } count = c; that._listView._writeProfilerMark("createContainers(" + count + "),StartTM"); if (that._listView._groupDataSource) { return that._listView._groups.initialize(); } }).then(function () { that._listView._writeProfilerMark("numberOfItemsPerItemsBlock,StartTM"); return (count && that._listView._groups.length() ? that._listView._layout.numberOfItemsPerItemsBlock : null); }).then(function (blockSize) { that._listView._writeProfilerMark("numberOfItemsPerItemsBlock(" + blockSize + "),info"); that._listView._writeProfilerMark("numberOfItemsPerItemsBlock,StopTM"); that._listView._resetCanvas(); that.tree = []; that.keyToGroupIndex = {}; that.containers = []; that._blockSize = blockSize; var groups = that._getGroups(count); var end = performance.now() + WinJS.UI._VirtualizeContentsView._maxTimePerCreateContainers, chunkSize = Math.min(WinJS.UI._VirtualizeContentsView._startupChunkSize, WinJS.UI._VirtualizeContentsView._chunkSize); do { var stop = blockSize ? that._createChunkWithBlocks(groups, count, blockSize, chunkSize) : that._createChunk(groups, count, chunkSize); } while (performance.now() < end && that.containers.length < count && !stop); that._listView._writeProfilerMark("createContainers created(" + that.containers.length + "),info"); that._listView._affectedRange.add({ start: 0, end: that.containers.length }, count); if (that.containers.length < count) { var jobNode = that._scheduleLazyTreeCreation(); that._creatingContainersWork.promise.done(null, function () { jobNode.cancel(); }); } else { that._listView._writeProfilerMark("createContainers completed synchronously,info"); that._creatingContainersWork.complete(); } that._listView._writeProfilerMark("createContainers(" + count + "),StopTM"); }); }, _updateItemsBlocks: function VirtualizeContentsView_updateItemsBlocks(blockSize) { var that = this; var usingStructuralNodes = !!blockSize; function createNewBlock() { var element = document.createElement("div"); element.className = WinJS.UI._itemsBlockClass; return element; } function updateGroup(itemsContainer, startIndex) { var blockElements = [], itemsCount = 0, blocks = itemsContainer.itemsBlocks, b; function rebuildItemsContainer() { itemsContainer.itemsBlocks = null; itemsContainer.items = []; for (var i = 0; i < itemsCount; i++) { var container = that.containers[startIndex + i]; itemsContainer.element.appendChild(container); itemsContainer.items.push(container); } } function rebuildItemsContainerWithBlocks() { itemsContainer.itemsBlocks = [{ element: blockElements.length ? blockElements.shift() : createNewBlock(), items: [] }]; var currentBlock = itemsContainer.itemsBlocks[0]; for (var i = 0; i < itemsCount; i++) { if (currentBlock.items.length === blockSize) { var nextBlock = blockElements.length ? blockElements.shift() : createNewBlock(); itemsContainer.itemsBlocks.push({ element: nextBlock, items: [] }); currentBlock = itemsContainer.itemsBlocks[itemsContainer.itemsBlocks.length - 1]; } var container = that.containers[startIndex + i]; currentBlock.element.appendChild(container); currentBlock.items.push(container); } itemsContainer.items = null; } if (blocks) { for (b = 0; b < blocks.length; b++) { itemsCount += blocks[b].items.length; blockElements.push(blocks[b].element); } } else { itemsCount = itemsContainer.items.length; } if (usingStructuralNodes) { rebuildItemsContainerWithBlocks(); } else { rebuildItemsContainer(); } for (b = 0; b < blockElements.length; b++) { var block = blockElements[b]; if (block.parentNode === itemsContainer.element) { itemsContainer.element.removeChild(block); } } return itemsCount; } for (var g = 0, startIndex = 0; g < this.tree.length; g++) { startIndex += updateGroup(this.tree[g].itemsContainer, startIndex); } that._blockSize = blockSize; }, _layoutItems: function VirtualizeContentsView_layoutItems() { var that = this; return this._listView._itemsCount().then(function (count) { return Promise.as(that._listView._layout.numberOfItemsPerItemsBlock).then(function (blockSize) { that._listView._writeProfilerMark("numberOfItemsPerItemsBlock(" + blockSize + "),info"); if (blockSize !== that._blockSize) { that._updateItemsBlocks(blockSize); that._listView._itemsBlockExtent = -1; } var affectedRange = that._listView._affectedRange.get(); var changedRange; // We accumulate all changes that occur between layouts in _affectedRange. If layout is interrupted due to additional // modifications, _affectedRange will become the union of the previous range of changes and the new range of changes // and will be passed to layout again. _affectedRange is reset whenever layout completes. if (affectedRange) { changedRange = { // _affectedRange is stored in the format [start, end), layout expects a range in the form of [firstIndex , lastIndex] // To ensure that layout can successfully use the expected range to find all of the groups which need to be re-laid out // we will pad an extra index at the front end such that layout receives [start - 1, end] in form of [lastIndex, firstIndex]. firstIndex: Math.max(affectedRange.start - 1, 0), lastIndex: Math.min(that.containers.length - 1, affectedRange.end) // Account for any constrained upper limits from lazily loaded win-container's. }; if (changedRange.firstIndex < that.containers.length || that.containers.length === 0) { return that._listView._layout.layout(that.tree, changedRange, that._modifiedElements || [], that._modifiedGroups || []); } } // There is nothing to layout. that._listView._affectedRange.clear(); return { realizedRangeComplete: Promise.wrap(), layoutComplete: Promise.wrap() }; }); }); }, updateTree: function VirtualizeContentsView_updateTree(count, delta, modifiedElements) { this._listView._writeProfilerMark(this._state.name + "_updateTree,info"); return this._state.updateTree(count, delta, modifiedElements); }, _updateTreeImpl: function VirtualizeContentsView_updateTreeImpl(count, delta, modifiedElements, skipUnrealizeItems) { this._executeAnimations = true; this._modifiedElements = modifiedElements; if (modifiedElements.handled) { return; } modifiedElements.handled = true; this._listView._writeProfilerMark("_updateTreeImpl,StartTM"); var that = this, i; if (!skipUnrealizeItems) { // If we skip unrealize items, this work will eventually happen when we reach the UnrealizingState. Sometimes, // it is appropriate to defer the unrealize work in order to optimize scenarios (e.g, edits that happen when we are // in the CompletedState, that way the animation can start sooner). this._unrealizeItems(); } function removeElements(array) { for (var i = 0, len = array.length; i < len; i++) { var itemBox = array[i]; itemBox.parentNode.removeChild(itemBox); } } for (var i = 0, len = modifiedElements.length; i < len; i++) { if (modifiedElements[i]._itemBox && modifiedElements[i]._itemBox.parentNode) { utilities.removeClass(modifiedElements[i]._itemBox.parentNode, WinJS.UI._selectedClass); } } this.items.each(function (index, item, itemData) { itemData.container && utilities.removeClass(itemData.container, WinJS.UI._selectedClass); itemData.container && utilities.addClass(itemData.container, WinJS.UI._backdropClass); }); var removedGroups = this._listView._updateContainers(this._getGroups(count), count, delta, modifiedElements); removeElements(removedGroups.removedHeaders); removeElements(removedGroups.removedItemsContainers); for (var i = 0, len = modifiedElements.length; i < len; i++) { var modifiedElement = modifiedElements[i]; if (modifiedElement.newIndex !== -1) { modifiedElement.element = this.getContainer(modifiedElement.newIndex); if (!modifiedElement.element) { throw "Container missing after updateContainers."; } } else { utilities.removeClass(modifiedElement.element, WinJS.UI._backdropClass); } } // We only need to restore focus if the current focus is within surface var activeElement = document.activeElement; if (this._listView._canvas.contains(activeElement)) { this._requireFocusRestore = activeElement } this._deferredReparenting = []; this.items.each(function (index, item, itemData) { var container = that.getContainer(index), itemBox = itemData.itemBox; if (itemBox && container) { if (itemBox.parentNode !== container) { if (index >= that.firstIndexDisplayed && index <= that.lastIndexDisplayed) { that._appendAndRestoreFocus(container, itemBox); } else { that._deferredReparenting.push({ itemBox: itemBox, container: container }); } } utilities.removeClass(container, WinJS.UI._backdropClass); itemData.container = container; utilities[that._listView.selection._isIncluded(index) ? "addClass" : "removeClass"](container, WinJS.UI._selectedClass); if (!that._listView.selection._isIncluded(index) && utilities.hasClass(itemBox, WinJS.UI._selectedClass)) { WinJS.UI._ItemEventsHandler.renderSelection(itemBox, itemData.element, false, true); } } }); this._listView._writeProfilerMark("_updateTreeImpl,StopTM"); }, _completeUpdateTree: function () { if (this._deferredReparenting) { var deferredCount = this._deferredReparenting.length; if (deferredCount > 0) { var perfId = "_completeReparenting(" + deferredCount + ")"; this._listView._writeProfilerMark(perfId + ",StartTM"); var deferredItem; for (var i = 0; i < deferredCount; i++) { deferredItem = this._deferredReparenting[i]; this._appendAndRestoreFocus(deferredItem.container, deferredItem.itemBox); } this._deferredReparenting = []; this._listView._writeProfilerMark(perfId + ",StopTM"); } } this._requireFocusRestore = null; }, _appendAndRestoreFocus: function VirtualizeContentsView_appendAndRestoreFocus(container, itemBox) { if (itemBox.parentNode !== container) { var activeElement; if (this._requireFocusRestore) { activeElement = document.activeElement; } if (this._requireFocusRestore && this._requireFocusRestore === activeElement && (container.contains(activeElement) || itemBox.contains(activeElement))) { this._listView._unsetFocusOnItem(); activeElement = document.activeElement; } utilities.empty(container); container.appendChild(itemBox); if (this._requireFocusRestore && activeElement === this._listView._keyboardEventsHelper) { var focused = this._listView._selection._getFocused(); if (focused.type === WinJS.UI.ObjectType.item && this.items.itemBoxAt(focused.index) === itemBox) { try { this._requireFocusRestore.setActive(); } catch (e) { } this._requireFocusRestore = null; } } } }, _startAnimations: function VirtualizeContentsView_startAnimations() { this._listView._writeProfilerMark("startAnimations,StartTM"); var that = this; this._hasAnimationInViewportPending = false; var animationPromise = Promise.as(this._listView._layout.executeAnimations()).then(function () { that._listView._writeProfilerMark("startAnimations,StopTM"); }); return animationPromise; }, _setState: function VirtualizeContentsView_setState(NewStateType, arg) { if (!this._listView._isZombie()) { var prevStateName = this._state.name; this._state = new NewStateType(this, arg); this._listView._writeProfilerMark(this._state.name + "_enter from(" + prevStateName + "),info"); this._state.enter(); } }, getAdjacent: function VirtualizeContentsView_getAdjacent(currentFocus, direction) { var that = this; return this.waitForEntityPosition(currentFocus).then(function () { return that._listView._layout.getAdjacent(currentFocus, direction); }); }, hitTest: function VirtualizeContentsView_hitTest(x, y) { if (!this._realizedRangeLaidOut) { var retVal = this._listView._layout.hitTest(x, y); retVal.index = utilities._clamp(retVal.index, -1, this._listView._cachedCount - 1, 0); retVal.insertAfterIndex = utilities._clamp(retVal.insertAfterIndex, -1, this._listView._cachedCount - 1, 0); return retVal; } else { return { index: -1, insertAfterIndex: -1 }; }; }, _createTreeBuildingSignal: function VirtualizeContentsView__createTreeBuildingSignal() { if (!this._creatingContainersWork) { this._creatingContainersWork = new WinJS._Signal(); var that = this; this._creatingContainersWork.promise.done( function () { that._creatingContainersWork = null; }, function (error) { that._creatingContainersWork = null; } ); } }, _createLayoutSignal: function VirtualizeContentsView_createLayoutSignal() { var that = this; if (!this._layoutCompleted) { this._layoutCompleted = new WinJS._Signal(); this._layoutCompleted.promise.done( function () { that._layoutCompleted = null; }, function (error) { that._layoutCompleted = null; } ); } if (!this._realizedRangeLaidOut) { this._realizedRangeLaidOut = new WinJS._Signal(); this._realizedRangeLaidOut.promise.done( function () { that._realizedRangeLaidOut = null; }, function (error) { that._realizedRangeLaidOut = null; } ); } }, _getLayoutCompleted: function VirtualizeContentsView_getLayoutCompleted() { return this._layoutCompleted ? WinJS.Promise._cancelBlocker(this._layoutCompleted.promise) : Promise.wrap(); }, _createSurfaceChild: function VirtualizeContentsView_createSurfaceChild(className, insertAfter) { var element = document.createElement("div"); element.className = className; this._listView._canvas.insertBefore(element, insertAfter ? insertAfter.nextElementSibling : null); return element; }, _executeScrollToFunctor: function VirtualizeContentsView_executeScrollToFunctor() { var that = this; return Promise.as(this._scrollToFunctor ? this._scrollToFunctor() : null).then(function (scroll) { that._scrollToFunctor = null; scroll = scroll || {}; // _scrollbarPos is initialized to 0 in the constructor, and we only set it when a valid integer // value is passed in order to account for cases when there is not a _scrollToFunctor if (+scroll.position === scroll.position) { that._scrollbarPos = scroll.position; } that._direction = scroll.direction || "right"; }); } }; function nop() { } /* View is in this state before reload is called so during startup, after datasource change etc. */ var CreatedState = WinJS.Class.define(function CreatedState_ctor(view) { this.view = view; this.view._createTreeBuildingSignal(); this.view._createLayoutSignal(); }, { name: 'CreatedState', enter: function CreatedState_enter() { this.view._createTreeBuildingSignal(); this.view._createLayoutSignal(); }, stop: nop, realizePage: nop, rebuildTree: function CreatedState_rebuildTree() { this.view._setState(BuildingState); }, relayout: function CreatedState_relayout() { this.view._setState(BuildingState); }, layoutNewContainers: nop, waitForEntityPosition: function CreatedState_waitForEntityPosition(entity) { this.view._setState(BuildingState); return this.view._getLayoutCompleted(); }, updateTree: nop }); /* In this state View is building its DOM tree with win-container element for each item in the data set. To build the tree the view needs to know items count or for grouped case the count of groups and the count of items in each group. The view enters this state when the tree needs to be built during startup or rebuild after data source change and etc. BuildingState => LayingoutState | CreatedState */ var BuildingState = WinJS.Class.define(function BuildingState_ctor(view) { this.view = view; }, { name: 'BuildingState', enter: function BuildingState_enter() { this.canceling = false; this.view._createTreeBuildingSignal(); this.view._createLayoutSignal(); var that = this; // Use a signal to guarantee that this.promise is set before the promise // handler is executed. var promiseStoredSignal = new WinJS._Signal(); this.promise = promiseStoredSignal.promise.then(function () { return that.view._createContainers(); }).then( function () { that.view._setState(LayingoutState); }, function (error) { if (!that.canceling) { // this is coming from layout. ListView is hidden. We need to raise complete and wait in initial state for further actions that.view._setState(CreatedState); that.view._listView._raiseViewComplete(); } return Promise.wrapError(error); } ); promiseStoredSignal.complete(); }, stop: function BuildingState_stop() { this.canceling = true; this.promise.cancel(); this.view._setState(CreatedState); }, realizePage: nop, rebuildTree: function BuildingState_rebuildTree() { this.canceling = true; this.promise.cancel(); this.enter(); }, relayout: nop, layoutNewContainers: nop, waitForEntityPosition: function BuildingState_waitForEntityPosition(entity) { return this.view._getLayoutCompleted(); }, updateTree: nop }); /* In this state View waits for the layout to lay out win-container elements. The view enters this state after edits or resize. LayingoutState => RealizingState | BuildingState | CanceledState | CompletedState | LayoutCanceledState */ var LayingoutState = WinJS.Class.define(function LayingoutState_ctor(view, NextStateType) { this.view = view; this.nextStateType = NextStateType || RealizingState; }, { name: 'LayingoutState', enter: function LayingoutState_enter() { var that = this; this.canceling = false; this.view._createLayoutSignal(); this.view._listView._writeProfilerMark(this.name + "_enter_layoutItems,StartTM"); // Use a signal to guarantee that this.promise is set before the promise // handler is executed. var promiseStoredSignal = new WinJS._Signal(); this.promise = promiseStoredSignal.promise.then(function () { return that.view._layoutItems(); }).then(function (layoutPromises) { // View is taking ownership of this promise and it will cancel it in stopWork that.view._layoutWork = layoutPromises.layoutComplete; return layoutPromises.realizedRangeComplete; }).then( function () { that.view._listView._writeProfilerMark(that.name + "_enter_layoutItems,StopTM"); that.view._listView._clearInsertedItems(); that.view._setAnimationInViewportState(that.view._modifiedElements); that.view._modifiedElements = []; that.view._modifiedGroups = []; that.view._realizedRangeLaidOut.complete(); that.view._layoutWork.then(function () { that.view._listView._writeProfilerMark(that.name + "_enter_layoutCompleted,info"); that.view._listView._affectedRange.clear(); that.view._layoutCompleted.complete(); }); if (!that.canceling) { that.view._setState(that.nextStateType); } }, function (error) { that.view._listView._writeProfilerMark(that.name + "_enter_layoutCanceled,info"); if (!that.canceling) { // Cancel is coming from layout itself so ListView is hidden or empty. In this case we want to raise loadingStateChanged that.view.firstIndexDisplayed = that.view.lastIndexDisplayed = -1; that.view._updateAriaMarkers(true, that.view.firstIndexDisplayed, that.view.lastIndexDisplayed); that.view._setState(CompletedState); } return Promise.wrapError(error); } ); promiseStoredSignal.complete(); if (this.canceling) { this.promise.cancel(); } }, cancelLayout: function LayingoutState_cancelLayout(switchState) { this.view._listView._writeProfilerMark(this.name + "_cancelLayout,info"); this.canceling = true; if (this.promise) { this.promise.cancel(); } if (switchState) { this.view._setState(LayoutCanceledState); } }, stop: function LayingoutState_stop() { this.cancelLayout(true); }, realizePage: nop, rebuildTree: function LayingoutState_rebuildTree() { this.cancelLayout(false); this.view._setState(BuildingState); }, relayout: function LayingoutState_relayout() { this.cancelLayout(false); this.enter(); }, layoutNewContainers: function LayingoutState_layoutNewContainers() { this.relayout(); }, waitForEntityPosition: function LayingoutState_waitForEntityPosition(entity) { return this.view._getLayoutCompleted(); }, updateTree: function LayingoutState_updateTree(count, delta, modifiedElements) { return this.view._updateTreeImpl(count, delta, modifiedElements); } }); /* View enters this state when layout is canceled. LayoutCanceledState => LayingoutState | BuildingState */ var LayoutCanceledState = WinJS.Class.define(function LayoutCanceledState_ctor(view) { this.view = view; }, { name: 'LayoutCanceledState', enter: nop, stop: nop, realizePage: function LayoutCanceledState_realizePage() { this.relayout(); }, rebuildTree: function LayoutCanceledState_rebuildTree() { this.view._setState(BuildingState); }, relayout: function LayoutCanceledState_relayout() { this.view._setState(LayingoutState); }, layoutNewContainers: function LayoutCanceledState_layoutNewContainers() { this.relayout(); }, waitForEntityPosition: function LayoutCanceledState_waitForEntityPosition(entity) { return this.view._getLayoutCompleted(); }, updateTree: function LayoutCanceledState_updateTree(count, delta, modifiedElements) { return this.view._updateTreeImpl(count, delta, modifiedElements); } }); /* Contents of items in the current viewport and prefetch area is realized during this stage. The view enters this state when items needs to be realized for instance during initialization, edits and resize. RealizingState => RealizingAnimatingState | UnrealizingState | LayingoutState | BuildingState | CanceledState */ var RealizingState = WinJS.Class.define(function RealizingState_ctor(view) { this.view = view; this.nextState = UnrealizingState; this.relayoutNewContainers = true; }, { name: 'RealizingState', enter: function RealizingState_enter() { var that = this; var promiseStoredSignal = new WinJS._Signal(); this.promise = promiseStoredSignal.promise.then(function () { return that.view._executeScrollToFunctor(); }).then(function () { that.relayoutNewContainers = false; return Promise._cancelBlocker(that.view._realizePageImpl()); }).then( function () { if (that.view._state === that) { that.view._completeUpdateTree(); that.view._listView._writeProfilerMark("RealizingState_to_UnrealizingState"); that.view._setState(that.nextState); } }, function (error) { if (that.view._state === that && !that.canceling) { that.view._listView._writeProfilerMark("RealizingState_to_CanceledState"); that.view._setState(CanceledState); } return Promise.wrapError(error); } ); promiseStoredSignal.complete(); }, stop: function RealizingState_stop() { this.canceling = true; this.promise.cancel(); this.view._cancelRealize(); this.view._setState(CanceledState); }, realizePage: function RealizingState_realizePage() { this.canceling = true; this.promise.cancel(); this.enter(); }, rebuildTree: function RealizingState_rebuildTree() { this.stop(); this.view._setState(BuildingState); }, relayout: function RealizingState_relayout() { this.stop(); this.view._setState(LayingoutState); }, layoutNewContainers: function RealizingState_layoutNewContainers() { if (this.relayoutNewContainers) { this.relayout(); } else { this.view._createLayoutSignal(); this.view._relayoutInComplete = true; } }, waitForEntityPosition: function RealizingState_waitForEntityPosition(entity) { return this.view._getLayoutCompleted(); }, updateTree: function RealizingState_updateTree(count, delta, modifiedElements) { return this.view._updateTreeImpl(count, delta, modifiedElements); }, setLoadingState: function RealizingState_setLoadingState(state) { this.view._listView._setViewState(state); } }); /* The view enters this state when the realize pass, animations or unrealizing was canceled or after newContainers have been laid out. In this state view waits for the next call from ListViewImpl. It can be scroll, edit etc. CanceledState => RealizingState | ScrollingState | LayingoutState | BuildingState */ var CanceledState = WinJS.Class.define(function CanceledState_ctor(view) { this.view = view; }, { name: 'CanceledState', enter: nop, stop: function CanceledState_stop() { // cancelRealize cancels ariaSetup which can still be in progress this.view._cancelRealize(); }, realizePage: function CanceledState_realizePage(NewStateType) { this.stop(); this.view._setState(NewStateType); }, rebuildTree: function CanceledState_rebuildTree() { this.stop(); this.view._setState(BuildingState); }, relayout: function CanceledState_relayout(NextStateType) { this.stop(); this.view._setState(LayingoutState, NextStateType); }, layoutNewContainers: function CanceledState_layoutNewContainers() { this.relayout(CanceledState); }, waitForEntityPosition: function CanceledState_waitForEntityPosition(entity) { return this.view._getLayoutCompleted(); }, updateTree: function CanceledState_updateTree(count, delta, modifiedElements) { return this.view._updateTreeImpl(count, delta, modifiedElements); } }); /* This state is almost identical with RealizingState. Currently the difference is that in this state loadingStateChanged events aren’t raised and after complete the state is switched to ScrollingPausedState to wait until end of scrolling. ScrollingState => RealizingAnimatingState | ScrollingPausedState | LayingoutState | BuildingState | CanceledState */ var ScrollingState = WinJS.Class.derive(RealizingState, function ScrollingState_ctor(view) { this.view = view; this.nextState = ScrollingPausedState; this.relayoutNewContainers = true; }, { name: 'ScrollingState', setLoadingState: function ScrollingState_setLoadingState(state) { } }); /* The view waits in this state for end of scrolling which for touch is signaled by MSManipulationStateChanged event and for mouse it is timeout. ScrollingPausedState => RealizingAnimatingState | ScrollingPausedState | LayingoutState | BuildingState | CanceledState */ var ScrollingPausedState = WinJS.Class.derive(CanceledState, function ScrollingPausedState_ctor(view) { this.view = view; }, { name: 'ScrollingPausedState', enter: function ScrollingPausedState_enter() { var that = this; this.promise = Promise._cancelBlocker(this.view._scrollEndPromise).then(function () { that.view._setState(UnrealizingState); }); }, stop: function ScrollingPausedState_stop() { this.promise.cancel(); // cancelRealize cancels ariaSetup which can still be in progress this.view._cancelRealize(); }, }); /* In this state, view unrealizes not needed items and then waits for all renderers to complete. UnrealizingState => CompletedState | RealizingState | ScrollingState | LayingoutState | BuildingState | CanceledState */ var UnrealizingState = WinJS.Class.define(function UnrealizingState_ctor(view) { this.view = view; }, { name: 'UnrealizingState', enter: function UnrealizingState_enter() { var that = this; this.promise = this.view._lazilyUnrealizeItems().then(function () { that.view._listView._writeProfilerMark("_renderCompletePromise wait starts,info"); return that.view._renderCompletePromise; }).then(function () { that.view._setState(CompletedState); }); }, stop: function UnrealizingState_stop() { // cancelRealize cancels ariaSetup which can still be in progress this.view._cancelRealize(); this.promise.cancel(); this.view._setState(CanceledState); }, realizePage: function UnrealizingState_realizePage(NewStateType) { this.promise.cancel(); this.view._setState(NewStateType); }, rebuildTree: function UnrealizingState_rebuildTree() { this.view._setState(BuildingState); }, relayout: function UnrealizingState_relayout() { this.view._setState(LayingoutState); }, layoutNewContainers: function UnrealizingState_layoutNewContainers() { this.view._createLayoutSignal(); this.view._relayoutInComplete = true; }, waitForEntityPosition: function UnrealizingState_waitForEntityPosition(entity) { return this.view._getLayoutCompleted(); }, updateTree: function UnrealizingState_updateTree(count, delta, modifiedElements) { return this.view._updateTreeImpl(count, delta, modifiedElements); } }); /* We enter this state, when there are animations to execute, and we have already fired the viewportloaded event RealizingAnimatingState => RealizingState | UnrealizingState | LayingoutState | BuildingState | CanceledState */ var RealizingAnimatingState = WinJS.Class.define(function RealizingStateAnimating_ctor(view, realizePromise) { this.view = view; this.realizePromise = realizePromise; this.realizeId = 1; }, { name: 'RealizingAnimatingState', enter: function RealizingAnimatingState_enter() { var that = this; this.animating = true; this.animatePromise = this.view._startAnimations(); this.animateSignal = new WinJS._Signal(); this.view._executeAnimations = false; this.animatePromise.done( function () { that.animating = false; if (that.modifiedElements) { that.view._updateTreeImpl(that.count, that.delta, that.modifiedElements); that.modifiedElements = null; that.view._setState(CanceledState); } else { that.animateSignal.complete(); } }, function (error) { that.animating = false; return Promise.wrapError(error); } ); this._waitForRealize(); }, _waitForRealize: function RealizingAnimatingState_waitForRealize() { var that = this; this.realizing = true; this.realizePromise.done(function () { that.realizing = false; }); var currentRealizeId = ++this.realizeId; Promise.join([this.realizePromise, this.animateSignal.promise]).done(function () { if (currentRealizeId === that.realizeId) { that.view._completeUpdateTree(); that.view._listView._writeProfilerMark("RealizingAnimatingState_to_UnrealizingState"); that.view._setState(UnrealizingState); } }); }, stop: function RealizingAnimatingState_stop(stopTreeCreation) { // always cancel realization this.realizePromise.cancel(); this.view._cancelRealize(); // animations are canceled only when tree needs to be rebuilt if (stopTreeCreation) { this.animatePromise.cancel(); this.view._setState(CanceledState); } }, realizePage: function RealizingAnimatingState_realizePage() { if (!this.modifiedElements) { var that = this; this.realizePromise = this.view._executeScrollToFunctor().then(function () { return Promise._cancelBlocker(that.view._realizePageImpl()); }); this._waitForRealize(); } }, rebuildTree: function RealizingAnimatingState_rebuildTree() { this.stop(true); this.view._setState(BuildingState); }, relayout: function RealizingAnimatingState_relayout() { // Relayout caused by edits should be stopped by updateTree but relayout can be caused by resize or containers creation and in these cases we should stop animations this.stop(true); // if tree update was waiting for animations we should do it now if (this.modifiedElements) { this.view._updateTreeImpl(this.count, this.delta, this.modifiedElements); this.modifiedElements = null; } this.view._setState(LayingoutState); }, layoutNewContainers: function RealizingAnimatingState_layoutNewContainers() { this.view._createLayoutSignal(); this.view._relayoutInComplete = true; }, waitForEntityPosition: function RealizingAnimatingState_waitForEntityPosition(entity) { return this.view._getLayoutCompleted(); }, updateTree: function RealizingAnimatingState_updateTree(count, delta, modifiedElements) { if (this.animating) { var previousModifiedElements = this.modifiedElements; this.count = count; this.delta = delta; this.modifiedElements = modifiedElements; return previousModifiedElements ? WinJS.Promise.cancel : this.animatePromise; } else { return this.view._updateTreeImpl(count, delta, modifiedElements); } }, setLoadingState: function RealizingAnimatingState_setLoadingState(state) { this.view._listView._setViewState(state); } }); /* The view enters this state when the tree is built, layout and realized after animations have finished. The layout can still laying out items outside of realized view during this stage. CompletedState => RealizingState | ScrollingState | LayingoutState | BuildingState | LayingoutNewContainersState */ var CompletedState = WinJS.Class.derive(CanceledState, function CompletedState_ctor(view) { this.view = view; }, { name: 'CompletedState', enter: function CompletedState_enter() { this._stopped = false; this.view._setupDeferredActions(); this.view._realizationLevel = WinJS.UI._VirtualizeContentsView._realizationLevel.normal; this.view._listView._raiseViewComplete(); // _raiseViewComplete will cause user event listener code to run synchronously. // If any updates are made to the Listview, this state will be stopped by the updater. // We don't want to change state to LayingoutNewContainersState if that happens. if (this.view._state === this && this.view._relayoutInComplete && !this._stopped) { this.view._setState(LayingoutNewContainersState); } }, stop: function CompletedState_stop() { this._stopped = true; // Call base class method. CanceledState.prototype.stop.call(this); }, layoutNewContainers: function CompletedState_layoutNewContainers() { this.view._createLayoutSignal(); this.view._setState(LayingoutNewContainersState); }, updateTree: function CompletedState_updateTree(count, delta, modifiedElements) { return this.view._updateTreeImpl(count, delta, modifiedElements, true); } }); /* The view waits in this state for previous layout pass to finish. LayingoutNewContainersState => RealizingState | ScrollingState | LayingoutState | BuildingState */ var LayingoutNewContainersState = WinJS.Class.derive(CanceledState, function LayingoutNewContainersState(view) { this.view = view; }, { name: 'LayingoutNewContainersState', enter: function LayingoutNewContainersState_enter() { var that = this; // _layoutWork is completed when the previous layout pass is done. _getLayoutCompleted will be completed when these new containers are laid out this.promise = WinJS.Promise.join([this.view.deferTimeout, this.view._layoutWork]); this.promise.then(function () { that.view._relayoutInComplete = false; that.relayout(CanceledState); }); }, stop: function LayingoutNewContainersState_stop() { // cancelRealize cancels ariaSetup which can still be in progress this.promise.cancel(); this.view._cancelRealize(); }, realizePage: function LayingoutNewContainersState_realizePage(NewStateType) { // in this state realizePage needs to run layout before realizing items this.stop(); this.view._setState(LayingoutState, NewStateType); }, layoutNewContainers: function LayingoutNewContainersState_layoutNewContainers() { this.view._createLayoutSignal(); } }); return _VirtualizeContentsView; }) }); })(this, WinJS); (function datePickerInit(WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Allows users to pick a date value. /// /// /// Date Picker /// /// /// ]]> /// Occurs when the current date changes. /// /// /// DatePicker: WinJS.Namespace._lazy(function () { // Constants definition var DEFAULT_DAY_PATTERN = 'day', DEFAULT_MONTH_PATTERN = '{month.full}', DEFAULT_YEAR_PATTERN = 'year.full'; var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/datePicker").value; }, get selectDay() { return WinJS.Resources._getWinJSString("ui/selectDay").value; }, get selectMonth() { return WinJS.Resources._getWinJSString("ui/selectMonth").value; }, get selectYear() { return WinJS.Resources._getWinJSString("ui/selectYear").value; }, }; var yearFormatCache = {}; function newFormatter(pattern, calendar, defaultPattern) { var dtf = Windows.Globalization.DateTimeFormatting; pattern = !pattern ? defaultPattern : pattern; var c = new dtf.DateTimeFormatter(pattern); if (calendar) { return new dtf.DateTimeFormatter(pattern, c.languages, c.geographicRegion, calendar, c.clock); } return c; }; function formatCacheLookup(pattern, calendar, defaultPattern) { var pat = yearFormatCache[pattern]; if (!pat) { pat = yearFormatCache[pattern] = {}; } var cal = pat[calendar]; if (!cal) { cal = pat[calendar] = {}; } var def = cal[defaultPattern]; if (!def) { def = cal[defaultPattern] = {}; def.formatter = newFormatter(pattern, calendar, defaultPattern); def.years = {}; } return def; } function formatYear(pattern, calendar, defaultPattern, datePatterns, order, cal) { var cache = formatCacheLookup(pattern, calendar, defaultPattern); var y = cache.years[cal.year + "-" + cal.era]; if (!y) { y = cache.formatter.format(cal.getDateTime()); cache.years[cal.year + "-" + cal.era] = y; } return y; } function formatMonth(pattern, calendar, defaultPattern, cal) { var cache = formatCacheLookup(pattern, calendar, defaultPattern); // can't cache actual month names because the hebrew calendar varies // the month name depending on religious holidays and leap months. // return cache.formatter.format(cal.getDateTime()); } function formatDay(pattern, calendar, defaultPattern, cal) { var cache = formatCacheLookup(pattern, calendar, defaultPattern); // can't cache actual day names because the format may include the day of the week, // which, of course, varies from month to month. // return cache.formatter.format(cal.getDateTime()); } function newCal(calendar) { var glob = Windows.Globalization; var c = new glob.Calendar(); if (calendar) { return new glob.Calendar(c.languages, calendar, c.getClock()); } return c; }; function yearDiff(start, end) { var yearCount = 0; if (start.era == end.era) { yearCount = end.year - start.year; } else { while (start.era !== end.era || start.year !== end.year) { yearCount++; start.addYears(1); } } return yearCount; } var DatePicker = WinJS.Class.define(function DatePicker_ctor(element, options) { /// /// Creates a new DatePicker control. /// /// The DOM element that will host the DatePicker control. /// /// /// An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds /// to one of the control's properties or events. /// /// A constructed DatePicker control. /// /// // Default to current date this._currentDate = new Date(); // Default to +/- 100 years this._minYear = this._currentDate.getFullYear() - 100; this._maxYear = this._currentDate.getFullYear() + 100; this._datePatterns = { date: null, month: null, year: null }; element = element || document.createElement("div"); WinJS.Utilities.addClass(element, "win-disposable"); element.winControl = this; var label = element.getAttribute("aria-label"); if (!label) { element.setAttribute("aria-label", strings.ariaLabel); } // Options should be set after the element is initialized which is // the same order of operation as imperatively setting options. this._init(element); WinJS.UI.setOptions(this, options); }, { _information: null, _currentDate: null, _calendar: null, _disabled: false, _dateElement: null, _dateControl: null, _monthElement: null, _monthControl: null, _minYear: null, _maxYear: null, _yearElement: null, _yearControl: null, _datePatterns: { date: null, month: null, year: null }, _addAccessibilityAttributes: function () { //see http://www.w3.org/TR/wai-aria/rdf_model.png for details this._domElement.setAttribute("role", "group"); this._dateElement.setAttribute("aria-label", strings.selectDay); this._monthElement.setAttribute("aria-label", strings.selectMonth); this._yearElement.setAttribute("aria-label", strings.selectYear); }, _addControlsInOrder: function () { var e = this._domElement; var u = WinJS.Utilities; var that = this; var orderIndex = 0; // don't use forEach's index, because "era" is in the list that._information.order.forEach(function (s) { switch (s) { case "month": e.appendChild(that._monthElement); u.addClass(that._monthElement, "win-order" + (orderIndex++)); break; case "date": e.appendChild(that._dateElement); u.addClass(that._dateElement, "win-order" + (orderIndex++)); break; case "year": e.appendChild(that._yearElement); u.addClass(that._yearElement, "win-order" + (orderIndex++)); break; } }); }, _createControlElements: function () { this._monthElement = document.createElement("select"); this._monthElement.className = "win-datepicker-month"; this._dateElement = document.createElement("select"); this._dateElement.className = "win-datepicker-date"; this._yearElement = document.createElement("select"); this._yearElement.className = "win-datepicker-year"; }, _createControls: function () { var that = this; var info = this._information; var index = info.getIndex(this.current); if (info.forceLanguage) { this._domElement.setAttribute("lang", info.forceLanguage); this._domElement.setAttribute("dir", info.isRTL ? "rtl" : "ltr"); } this._yearControl = new WinJS.UI._Select(this._yearElement, { dataSource: this._information.years, disabled: this.disabled, index: index.year }); this._monthControl = new WinJS.UI._Select(this._monthElement, { dataSource: this._information.months(index.year), disabled: this.disabled, index: index.month }); this._dateControl = new WinJS.UI._Select(this._dateElement, { dataSource: this._information.dates(index.year, index.month), disabled: this.disabled, index: index.date }); this._wireupEvents(); }, dispose: function () { /// /// /// Disposes this control. /// /// /// }, /// /// Gets or sets the calendar to use. /// /// calendar: { get: function () { return this._calendar; }, set: function (value) { this._calendar = value; this._setElement(this._domElement); } }, /// /// Gets or sets the current date of the DatePicker. /// /// current: { get: function () { var d = this._currentDate; var y = d.getFullYear(); return new Date(Math.max(Math.min(this.maxYear, y), this.minYear), d.getMonth(), d.getDate(), 12, 0, 0, 0); }, set: function (value) { var newDate; if (typeof (value) === "string") { newDate = new Date(Date.parse(value)); newDate.setHours(12, 0, 0, 0); } else { newDate = value; } var oldDate = this._currentDate; if (oldDate != newDate) { this._currentDate = newDate; this._updateDisplay(); } } }, /// /// Gets or sets a value that specifies whether the DatePicker is disabled. A value of true indicates that the DatePicker is disabled. /// /// disabled: { get: function () { return this._disabled; }, set: function (value) { if (this._disabled !== value) { this._disabled = value; // all controls get populated at the same time, so any check is OK // if (this._yearControl) { this._monthControl.setDisabled(value); this._dateControl.setDisabled(value); this._yearControl.setDisabled(value); } } } }, /// /// Gets or sets the display pattern for the date. /// /// datePattern: { get: function () { return this._datePatterns.date; }, set: function (value) { if (this._datePatterns.date !== value) { this._datePatterns.date = value; this._init(); } } }, /// element: { get: function () { return this._domElement; } }, _setElement: function (element) { this._domElement = this._domElement || element; if (!this._domElement) { return; } WinJS.Utilities.empty(this._domElement); WinJS.Utilities.addClass(this._domElement, "win-datepicker"); this._updateInformation(); this._createControlElements(); this._addControlsInOrder(); this._createControls(); this._addAccessibilityAttributes(); }, /// /// Gets or sets the minimum Gregorian year available for picking. /// /// minYear: { get: function () { return this._information.getDate({ year: 0, month: 0, date: 0 }).getFullYear(); }, set: function (value) { if (this._minYear !== value) { this._minYear = value; if (value > this._maxYear) { this._maxYear = value; } this._updateInformation(); if (this._yearControl) { this._yearControl.dataSource = this._information.years; } this._updateDisplay(); } } }, /// /// Gets or sets the maximum Gregorian year available for picking. /// /// maxYear: { get: function () { var index = { year: this._information.years.getLength() - 1 }; index.month = this._information.months(index.year).getLength() - 1; index.date = this._information.dates(index.year, index.month).getLength() - 1; return this._information.getDate(index).getFullYear(); }, set: function (value) { if (this._maxYear !== value) { this._maxYear = value; if (value < this._minYear) { this._minYear = value; } this._updateInformation(); if (this._yearControl) { this._yearControl.dataSource = this._information.years; } this._updateDisplay(); } } }, /// /// Gets or sets the display pattern for the month. /// /// monthPattern: { get: function () { return this._datePatterns.month; }, set: function (value) { if (this._datePatterns.month !== value) { this._datePatterns.month = value; this._init(); } } }, _updateInformation: function () { // since "year" in the date ctor can be two digit (85 == 1985), we need // to force "full year" to capture dates < 100 a.d. // var min = new Date(this._minYear, 0, 1, 12, 0, 0); var max = new Date(this._maxYear, 11, 31, 12, 0, 0); min.setFullYear(this._minYear); max.setFullYear(this._maxYear); this._information = WinJS.UI.DatePicker.getInformation(min, max, this._calendar, this._datePatterns); }, _init: function (element) { this._setElement(element); }, _updateDisplay: function () { if (!this._domElement) return; // all controls get populated at the same time, so any check is OK // if (this._yearControl) { //Render display index based on constraints (minYear and maxYear constraints) //Will not modify current date var index = this._information.getIndex(this.current); this._yearControl.index = index.year; this._monthControl.dataSource = this._information.months(index.year); this._monthControl.index = index.month; this._dateControl.dataSource = this._information.dates(index.year, index.month); this._dateControl.index = index.date; } }, _wireupEvents: function () { var that = this; function changed() { that._currentDate = that._information.getDate({ year: that._yearControl.index, month: that._monthControl.index, date: that._dateControl.index }, that._currentDate); var index = that._information.getIndex(that._currentDate); // Changing the month (or year, if the current date is 2/29) changes the day range, and could have made the day selection invalid that._monthControl.dataSource = that._information.months(index.year) that._monthControl.index = index.month; that._dateControl.dataSource = that._information.dates(index.year, index.month); that._dateControl.index = index.date; } this._dateElement.addEventListener("change", changed, false); this._monthElement.addEventListener("change", changed, false); this._yearElement.addEventListener("change", changed, false); }, /// /// Gets or sets the display pattern for year. /// /// yearPattern: { get: function () { return this._datePatterns.year; }, set: function (value) { if (this._datePatterns.year !== value) { this._datePatterns.year = value; this._init(); } } }, }, { _getInformationWinRT: function (startDate, endDate, calendar, datePatterns) { datePatterns = datePatterns || { date: DEFAULT_DAY_PATTERN, month: DEFAULT_MONTH_PATTERN, year: DEFAULT_YEAR_PATTERN }; var tempCal = newCal(calendar); var monthCal = newCal(calendar); var dayCal = newCal(calendar); tempCal.setToMin(); var minDateTime = tempCal.getDateTime(); tempCal.setToMax(); var maxDateTime = tempCal.getDateTime(); function clamp(date) { return new Date(Math.min(new Date(Math.max(minDateTime, date)), maxDateTime));; } tempCal.hour = 12; startDate = clamp(startDate); endDate = clamp(endDate); tempCal.setDateTime(endDate); var end = { year: tempCal.year, era: tempCal.era }; tempCal.setDateTime(startDate); var minYear = tempCal.year; var yearLen = 0; yearLen = yearDiff(tempCal, end) + 1; // Explicity use a template that's equivalent to a longdate template // as longdate/shortdate can be overriden by the user var dateformat = formatCacheLookup("day month.full year", calendar).formatter; var localdatepattern = dateformat.patterns[0]; var isRTL = localdatepattern.charCodeAt(0) === 8207; var order = ["date", "month", "year"]; var indexes = { month: localdatepattern.indexOf("{month"), date: localdatepattern.indexOf("{day"), year: localdatepattern.indexOf("{year") }; order.sort(function (a, b) { if (indexes[a] < indexes[b]) { return -1; } else if (indexes[a] > indexes[b]) { return 1; } else { return 0; } }); var yearSource = (function () { return { getLength: function () { return yearLen; }, getValue: function (index) { tempCal.setDateTime(startDate); tempCal.addYears(index); return formatYear(datePatterns.year, calendar, DEFAULT_YEAR_PATTERN, datePatterns, order, tempCal); } } })(); var monthSource = function (yearIndex) { monthCal.setDateTime(startDate); monthCal.addYears(yearIndex); return { getLength: function () { return monthCal.numberOfMonthsInThisYear; }, getValue: function (index) { monthCal.month = monthCal.firstMonthInThisYear; monthCal.addMonths(index); return formatMonth(datePatterns.month, calendar, DEFAULT_MONTH_PATTERN, monthCal); } }; }; var dateSource = function (yearIndex, monthIndex) { dayCal.setDateTime(startDate); dayCal.addYears(yearIndex); dayCal.month = dayCal.firstMonthInThisYear; dayCal.addMonths(monthIndex); dayCal.day = dayCal.firstDayInThisMonth; return { getLength: function () { return dayCal.numberOfDaysInThisMonth; }, getValue: function (index) { dayCal.day = dayCal.firstDayInThisMonth; dayCal.addDays(index); return formatDay(datePatterns.date, calendar, DEFAULT_DAY_PATTERN, dayCal); } }; }; return { isRTL: isRTL, forceLanguage: dateformat.resolvedLanguage, order: order, getDate: function (index, lastDate) { var lastCal; if (lastDate) { tempCal.setDateTime(lastDate); lastCal = { year: tempCal.year, month: tempCal.month, day: tempCal.day }; } var c = tempCal; c.setDateTime(startDate); c.addYears(index.year); var guessMonth; if (c.firstMonthInThisYear > c.lastMonthInThisYear) { if (index.month + c.firstMonthInThisYear > c.numberOfMonthsInThisYear) { guessMonth = index.month + c.firstMonthInThisYear - c.numberOfMonthsInThisYear; } else { guessMonth = index.month + c.firstMonthInThisYear; } if (lastCal && lastCal.year !== c.year) { // Year has changed in some transitions in Thai Calendar, this will change the first month, and last month indices of the year. guessMonth = Math.max(Math.min(lastCal.month, c.numberOfMonthsInThisYear), 1); } } else { if (lastCal && lastCal.year !== c.year) { // Year has changed in some transitions in Thai Calendar, this will change the first month, and last month indices of the year. guessMonth = Math.max(Math.min(lastCal.month, c.firstMonthInThisYear + c.numberOfMonthsInThisYear - 1), c.firstMonthInThisYear); } else { guessMonth = Math.max(Math.min(index.month + c.firstMonthInThisYear, c.firstMonthInThisYear + c.numberOfMonthsInThisYear - 1), c.firstMonthInThisYear); } } c.month = guessMonth; var guessDay = Math.max(Math.min(index.date + c.firstDayInThisMonth, c.firstDayInThisMonth + c.numberOfDaysInThisMonth - 1), c.firstDayInThisMonth); if (lastCal && (lastCal.year !== c.year || lastCal.month !== c.month)) { guessDay = Math.max(Math.min(lastCal.day, c.firstDayInThisMonth + c.numberOfDaysInThisMonth - 1), c.firstDayInThisMonth); } c.day = c.firstDayInThisMonth; c.addDays(guessDay - c.firstDayInThisMonth); return c.getDateTime(); }, getIndex: function (date) { var curDate = clamp(date); tempCal.setDateTime(curDate); var cur = { year: tempCal.year, era: tempCal.era }; var yearIndex = 0; tempCal.setDateTime(startDate); tempCal.month = 1; yearIndex = yearDiff(tempCal, cur); tempCal.setDateTime(curDate); var monthIndex = tempCal.month - tempCal.firstMonthInThisYear; if (monthIndex < 0) { // A special case is in some ThaiCalendar years first month // of the year is April, last month is March and month flow is wrap-around // style; April, March .... November, December, January, February, March. So the first index // will be 4 and last index will be 3. We are handling the case to convert this wraparound behavior // into selected index. monthIndex = tempCal.month - tempCal.firstMonthInThisYear + tempCal.numberOfMonthsInThisYear; } var dateIndex = tempCal.day - tempCal.firstDayInThisMonth; var index = { year: yearIndex, month: monthIndex, date: dateIndex }; return index; }, years: yearSource, months: monthSource, dates: dateSource }; }, _getInformationJS: function (startDate, endDate) { var minYear = startDate.getFullYear(); var maxYear = endDate.getFullYear(); var yearSource = { getLength: function () { return Math.max(0, maxYear - minYear + 1); }, getValue: function (index) { return minYear + index; } }; var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var monthSource = function (yearIndex) { return { getLength: function () { return months.length; }, getValue: function (index) { return months[index]; }, getMonthNumber: function (index) { return Math.min(index, months.length - 1); } }; }; var dateSource = function (yearIndex, monthIndex) { var temp = new Date(); var year = yearSource.getValue(yearIndex); // The +1 is needed to make using a day of 0 work correctly var month = monthIndex + 1; // index is always correct, unlike getMonth which changes when the date is invalid temp.setFullYear(year, month, 0); var maxValue = temp.getDate(); return { getLength: function () { return maxValue; }, getValue: function (index) { return "" + (index + 1); }, getDateNumber: function (index) { return Math.min(index + 1, maxValue); } }; }; return { order: ["month", "date", "year"], getDate: function (index) { return new Date( yearSource.getValue(index.year), monthSource(index.year).getMonthNumber(index.month), dateSource(index.year, index.month).getDateNumber(index.date), 12, 0 ); }, getIndex: function (date) { var yearIndex = 0; var year = date.getFullYear(); if (year < minYear) { yearIndex = 0; } else if (year > this.maxYear) { yearIndex = yearSource.getLength() - 1; } else { yearIndex = date.getFullYear() - minYear; } var monthIndex = Math.min(date.getMonth(), monthSource(yearIndex).getLength()); var dateIndex = Math.min(date.getDate() - 1, dateSource(yearIndex, monthIndex).getLength()); return { year: yearIndex, month: monthIndex, date: dateIndex }; }, years: yearSource, months: monthSource, dates: dateSource }; } }); if (WinJS.Utilities.hasWinRT) { DatePicker.getInformation = DatePicker._getInformationWinRT; } else { DatePicker.getInformation = DatePicker._getInformationJS; } WinJS.Class.mix(DatePicker, WinJS.Utilities.createEventProperties("change")); WinJS.Class.mix(DatePicker, WinJS.UI.DOMEventMixin); return DatePicker; }) }); })(WinJS); (function timePickerInit(WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Allows users to select time values. /// /// /// Time Picker /// /// /// ]]> /// Occurs when the time changes. /// /// /// TimePicker: WinJS.Namespace._lazy(function () { // Constants definition var DEFAULT_MINUTE_PATTERN = "{minute.integer(2)}", DEFAULT_HOUR_PATTERN = "{hour.integer(1)}", DEFAULT_PERIOD_PATTERN = "{period.abbreviated(2)}"; var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/timePicker").value; }, get selectHour() { return WinJS.Resources._getWinJSString("ui/selectHour").value; }, get selectMinute() { return WinJS.Resources._getWinJSString("ui/selectMinute").value; }, get selectAMPM() { return WinJS.Resources._getWinJSString("ui/selectAMPM").value; }, }; // date1 and date2 must be Date objects with their date portions set to the // sentinel date. var areTimesEqual = function (date1, date2) { return date1.getHours() === date2.getHours() && date1.getMinutes() === date2.getMinutes(); }; var TimePicker = WinJS.Class.define(function TimePicker_ctor(element, options) { /// /// Initializes a new instance of the TimePicker control /// /// The DOM element associated with the TimePicker control. /// /// /// The set of options to be applied initially to the TimePicker control. /// /// A constructed TimePicker control. /// /// // Default to current time this._currentTime = WinJS.UI.TimePicker._sentinelDate(); element = element || document.createElement("div"); WinJS.Utilities.addClass(element, "win-disposable"); element.winControl = this; var label = element.getAttribute("aria-label"); if (!label) { element.setAttribute("aria-label", strings.ariaLabel); } this._timePatterns = { minute: null, hour: null, period: null }; // Options should be set after the element is initialized which is // the same order of operation as imperatively setting options. this._init(element); WinJS.UI.setOptions(this, options); }, { _currentTime: null, _clock: null, _disabled: false, _hourElement: null, _hourControl: null, _minuteElement: null, _minuteControl: null, _ampmElement: null, _ampmControl: null, _minuteIncrement: 1, _timePatterns: { minute: null, hour: null, period: null }, _information: null, _addAccessibilityAttributes: function () { //see http://www.w3.org/TR/wai-aria/rdf_model.png for details this._domElement.setAttribute("role", "group"); this._hourElement.setAttribute("aria-label", strings.selectHour); this._minuteElement.setAttribute("aria-label", strings.selectMinute); if (this._ampmElement) { this._ampmElement.setAttribute("aria-label", strings.selectAMPM); } }, _addControlsInOrder: function (info) { var that = this; var u = WinJS.Utilities; info.order.forEach(function (s, index) { switch (s) { case "hour": that._domElement.appendChild(that._hourElement); u.addClass(that._hourElement, "win-order" + index); break; case "minute": that._domElement.appendChild(that._minuteElement); u.addClass(that._minuteElement, "win-order" + index); break; case "period": if (that._ampmElement) { that._domElement.appendChild(that._ampmElement); u.addClass(that._ampmElement, "win-order" + index); } break; } }); }, dispose: function () { /// /// /// Disposes this TimePicker. /// /// /// }, /// /// Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. /// /// clock: { get: function () { return this._clock; }, set: function (value) { if (this._clock !== value) { this._clock = value; this._init(); } } }, /// /// Gets or sets the current date (and time) of the TimePicker. /// /// current: { get: function () { var cur = this._currentTime; if (cur) { var time = WinJS.UI.TimePicker._sentinelDate(); time.setHours(cur.getHours()); // accounts for AM/PM time.setMinutes(this._getMinutesIndex(cur) * this.minuteIncrement); time.setSeconds(0); time.setMilliseconds(0); return time; } else { return cur; } }, set: function (value) { var that = this; var newTime; if (typeof (value) === "string") { newTime = WinJS.UI.TimePicker._sentinelDate(); newTime.setTime(Date.parse(newTime.toDateString() + " " + value)); } else { newTime = WinJS.UI.TimePicker._sentinelDate(); newTime.setHours(value.getHours()); newTime.setMinutes(value.getMinutes()); } var oldTime = this._currentTime; if (!areTimesEqual(oldTime, newTime)) { this._currentTime = newTime; this._updateDisplay(); } } }, /// /// Specifies whether the TimePicker is disabled. /// /// disabled: { get: function () { return this._disabled; }, set: function (value) { if (this._disabled !== value) { this._disabled = value; if (this._hourControl) { this._hourControl.setDisabled(value); this._minuteControl.setDisabled(value); } if (this._ampmControl) { this._ampmControl.setDisabled(value); } } } }, /// element: { get: function () { return this._domElement; } }, _init: function (element) { this._setElement(element); this._updateDisplay(); }, /// /// Gets or sets the display pattern for the hour. /// /// hourPattern: { get: function () { return this._timePatterns.hour.pattern; }, set: function (value) { if (this._timePatterns.hour !== value) { this._timePatterns.hour = value; this._init(); } } }, _getHoursAmpm: function (time) { var hours24 = time.getHours(); if (this._ampmElement) { if (hours24 === 0) { return { hours: 12, ampm: 0 }; } else if (hours24 < 12) { return { hours: hours24, ampm: 0 }; } return { hours: hours24 - 12, ampm: 1 }; } return { hours: hours24 }; }, _getHoursIndex: function (hours) { if (this._ampmElement && hours === 12) { return 0; } return hours; }, _getMinutesIndex: function (time) { return parseInt(time.getMinutes() / this.minuteIncrement); }, /// /// Gets or sets the minute increment. For example, "15" specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. /// /// minuteIncrement: { //prevent divide by 0, and leave user's input intact get: function () { return Math.max(1, Math.abs(this._minuteIncrement | 0) % 60); }, set: function (value) { if (this._minuteIncrement != value) { this._minuteIncrement = value; this._init(); } } }, /// /// Gets or sets the display pattern for the minute. /// /// minutePattern: { get: function () { return this._timePatterns.minute.pattern; }, set: function (value) { if (this._timePatterns.minute !== value) { this._timePatterns.minute = value; this._init(); } } }, /// /// Gets or sets the display pattern for the period. /// /// periodPattern: { get: function () { return this._timePatterns.period.pattern; }, set: function (value) { if (this._timePatterns.period !== value) { this._timePatterns.period = value; this._init(); } } }, _setElement: function (element) { this._domElement = this._domElement || element; if (!this._domElement) { return; } var info = WinJS.UI.TimePicker.getInformation(this.clock, this.minuteIncrement, this._timePatterns); this._information = info; if (info.forceLanguage) { this._domElement.setAttribute("lang", info.forceLanguage); this._domElement.setAttribute("dir", info.isRTL ? "rtl" : "ltr"); } WinJS.Utilities.empty(this._domElement); WinJS.Utilities.addClass(this._domElement, "win-timepicker"); this._hourElement = document.createElement("select"); WinJS.Utilities.addClass(this._hourElement, "win-timepicker-hour"); this._minuteElement = document.createElement("select"); WinJS.Utilities.addClass(this._minuteElement, "win-timepicker-minute"); this._ampmElement = null; if (info.clock === "12HourClock") { this._ampmElement = document.createElement("select"); WinJS.Utilities.addClass(this._ampmElement, "win-timepicker-period"); } this._addControlsInOrder(info); var that = this; var hoursAmpm = this._getHoursAmpm(this.current); this._hourControl = new WinJS.UI._Select(this._hourElement, { dataSource: this._getInfoHours(), disabled: this.disabled, index: this._getHoursIndex(hoursAmpm.hours) }); this._minuteControl = new WinJS.UI._Select(this._minuteElement, { dataSource: info.minutes, disabled: this.disabled, index: this._getMinutesIndex(this.current) }); this._ampmControl = null; if (this._ampmElement) { this._ampmControl = new WinJS.UI._Select(this._ampmElement, { dataSource: info.periods, disabled: this.disabled, index: hoursAmpm.ampm }); } this._wireupEvents(); this._updateValues(); this._addAccessibilityAttributes(); }, _getInfoHours: function () { return this._information.hours; }, _updateLayout: function () { if (!this._domElement) return; this._updateValues(); }, _updateValues: function () { if (this._hourControl) { var hoursAmpm = this._getHoursAmpm(this.current); if (this._ampmControl) { this._ampmControl.index = hoursAmpm.ampm; } this._hourControl.index = this._getHoursIndex(hoursAmpm.hours); this._minuteControl.index = this._getMinutesIndex(this.current); } }, _updateDisplay: function () { //Render display index based on constraints (minuteIncrement) //Will not modify current time var hoursAmpm = this._getHoursAmpm(this.current); if (this._ampmControl) { this._ampmControl.index = hoursAmpm.ampm; } if (this._hourControl) { this._hourControl.index = this._getHoursIndex(hoursAmpm.hours); this._minuteControl.index = this._getMinutesIndex(this.current); } }, _wireupEvents: function () { var that = this; var fixupHour = function () { var hour = that._hourControl.index; if (that._ampmElement) { if (that._ampmControl.index === 1) { if (hour !== 12) { hour += 12; } } } return hour; }; var changed = function () { var hour = fixupHour(); that._currentTime.setHours(hour); that._currentTime.setMinutes(that._minuteControl.index * that.minuteIncrement); }; this._hourElement.addEventListener("change", changed, false); this._minuteElement.addEventListener("change", changed, false); if (this._ampmElement) { this._ampmElement.addEventListener("change", changed, false); } } }, { _sentinelDate: function () { // This is July 15th, 2011 as our sentinel date. There are no known // daylight savings transitions that happened on that date. var current = new Date(); return new Date(2011, 6, 15, current.getHours(), current.getMinutes()); }, _getInformationWinRT: function (clock, minuteIncrement, timePatterns) { var newFormatter = function (pattern, defaultPattern) { var dtf = Windows.Globalization.DateTimeFormatting; pattern = !pattern ? defaultPattern : pattern; var formatter = new dtf.DateTimeFormatter(pattern); if (clock) { formatter = dtf.DateTimeFormatter(pattern, formatter.languages, formatter.geographicRegion, formatter.calendar, clock); } return formatter; } var glob = Windows.Globalization; var calendar = new glob.Calendar(); if (clock) { calendar = new glob.Calendar(calendar.languages, calendar.getCalendarSystem(), clock); } calendar.setDateTime(WinJS.UI.TimePicker._sentinelDate()); var computedClock = calendar.getClock(); var numberOfHours = 24; numberOfHours = calendar.numberOfHoursInThisPeriod; var periods = (function () { var periodFormatter = newFormatter(timePatterns.period, DEFAULT_PERIOD_PATTERN); return { getLength: function () { return 2; }, getValue: function (index) { var date = WinJS.UI.TimePicker._sentinelDate(); if (index == 0) { date.setHours(1); var am = periodFormatter.format(date); return am; } if (index == 1) { date.setHours(13); var pm = periodFormatter.format(date); return pm; } return null; } }; })(); // Determine minute format from the DateTimeFormatter var minutes = (function (index) { var minuteFormatter = newFormatter(timePatterns.minute, DEFAULT_MINUTE_PATTERN); var now = WinJS.UI.TimePicker._sentinelDate(); return { getLength: function () { return 60 / minuteIncrement; }, getValue: function (index) { var display = index * minuteIncrement; now.setMinutes(display); return minuteFormatter.format(now); } }; })(); // Determine hour format from the DateTimeFormatter var hours = (function (index) { var hourFormatter = newFormatter(timePatterns.hour, DEFAULT_HOUR_PATTERN); var now = WinJS.UI.TimePicker._sentinelDate(); return { getLength: function () { return numberOfHours }, getValue: function (index) { now.setHours(index); return hourFormatter.format(now); } } })(); // Determine the order of the items from the DateTimeFormatter. // "hour minute" also returns the period (if needed). // var hourMinuteFormatter = newFormatter("hour minute"); var pattern = hourMinuteFormatter.patterns[0]; var order = ["hour", "minute"]; var indexes = { period: pattern.indexOf("{period"), hour: pattern.indexOf("{hour"), minute: pattern.indexOf("{minute") }; if (indexes.period > -1) { order.push("period"); } var DateTimeFormatter = Windows.Globalization.DateTimeFormatting.DateTimeFormatter; var dtf = new DateTimeFormatter("month.full", Windows.Globalization.ApplicationLanguages.languages, "ZZ", "GregorianCalendar", "24HourClock"); var pat = dtf.patterns[0]; var isRTL = pat.charCodeAt(0) === 8207; if (isRTL) { var temp = indexes.hour; indexes.hour = indexes.minute; indexes.minute = temp; } order.sort(function (a, b) { if (indexes[a] < indexes[b]) { return -1; } else if (indexes[a] > indexes[b]) { return 1; } else { return 0; } }); return { minutes: minutes, hours: hours, clock: computedClock, periods: periods, order: order, forceLanguage: hourMinuteFormatter.resolvedLanguage, isRTL: isRTL }; }, _getInformationJS: function (clock, minuteIncrement) { var hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; var minutes = new Object(); minutes.getLength = function () { return 60 / minuteIncrement; } minutes.getValue = function (index) { var display = index * minuteIncrement; if (display < 10) { return "0" + display.toString(); } else { return display.toString(); } }; var order = ["hour", "minute", "period"]; if (clock === "24HourClock") { hours = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]; order = ["hour", "minute"]; } return { minutes: minutes, hours: hours, clock: clock || "12HourClock", periods: ["AM", "PM"], order: order }; } }); if (WinJS.Utilities.hasWinRT) { TimePicker.getInformation = TimePicker._getInformationWinRT; } else { TimePicker.getInformation = TimePicker._getInformationJS; } WinJS.Class.mix(TimePicker, WinJS.Utilities.createEventProperties("change")); WinJS.Class.mix(TimePicker, WinJS.UI.DOMEventMixin); return TimePicker; }) }); })(WinJS); (function selectInit(WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _Select: WinJS.Namespace._lazy(function () { var encodeHtmlRegEx = /[&<>'"]/g; var encodeHtmlEscapeMap = { "&": "&", "<": "<", ">": ">", "'": "'", '"': """ }; var stringDirectionRegEx = /[\u200e\u200f]/g; function encodeHtml(str) { return str.replace(encodeHtmlRegEx, function (m) { return encodeHtmlEscapeMap[m] || ""; }); }; function stripDirectionMarker(str) { return str.replace(stringDirectionRegEx, ""); } function stockGetValue(index) { return this[index]; } function stockGetLength() { return this.length; } function fixDataSource(dataSource) { if (!dataSource.getValue) { dataSource.getValue = stockGetValue } if (!dataSource.getLength) { dataSource.getLength = stockGetLength } return dataSource; } return WinJS.Class.define(function _Select_ctor(element, options) { // This is an implementation detail of the TimePicker and DatePicker, designed // to provide a primitive "data bound" select control. This is not designed to // be used outside of the TimePicker and DatePicker controls. // this._dataSource = fixDataSource(options.dataSource); this._index = options.index || 0; this._domElement = element; // Mark this as a tab stop this._domElement.tabIndex = 0; if (options.disabled) { this.setDisabled(options.disabled); } var that = this; this._domElement.addEventListener("change", function (e) { //Should be set to _index to prevent events from firing twice that._index = that._domElement.selectedIndex; }, false); //update runtime accessibility value after initialization this._createSelectElement(); }, { _index: 0, _dataSource: null, dataSource: { get: function () { return this._dataSource; }, set: function (value) { this._dataSource = fixDataSource(value); //Update layout as data source change if (this._domElement) { this._createSelectElement(); } } }, setDisabled: function (disabled) { if (disabled) { this._domElement.setAttribute("disabled", "disabled"); } else { this._domElement.removeAttribute("disabled"); } }, _createSelectElement: function () { var dataSourceLength = this._dataSource.getLength(); var text = ""; for (var i = 0; i < dataSourceLength; i++) { var value = "" + this._dataSource.getValue(i); var escaped = encodeHtml(value); // WinRT localization often tags the strings with reading direction. We want this // for display text (escaped), but don't want this in the value space, as it // only present for display. // var stripped = stripDirectionMarker(escaped); text += ""; } WinJS.Utilities.setInnerHTMLUnsafe(this._domElement, text); this._domElement.selectedIndex = this._index; }, index: { get: function () { return Math.max(0, Math.min(this._index, this._dataSource.getLength() - 1)); }, set: function (value) { if (this._index !== value) { this._index = value; var d = this._domElement; if (d && d.selectedIndex !== value) { d.selectedIndex = value; } } } }, value: { get: function () { return this._dataSource.getValue(this.index); } } }); }) }) })(WinJS); // Back Button (function backButtonInit(WinJS) { "use strict"; var nav = WinJS.Navigation; // Class Names var navigationBackButtonClass = 'win-navigation-backbutton'; var glyphClass = "win-back"; // CONSTANTS var KEY_LEFT = "Left"; var KEY_BROWSER_BACK = "BrowserBack"; var MOUSE_BACK_BUTTON = 3; // Create Singleton for global event registering/unregistering. This Singleton should only be created once. // Here the function 'returnBackButtonSingelton' is called immediateley and its result is the singleton object. var singleton = (function createBackButtonSingleton() { /* Step 1: Build JavaScript closure */ function hookUpBackButtonGlobalEventHandlers() { // Subscribes to global events on the window object window.addEventListener('keyup', backButtonGlobalKeyUpHandler, false) window.addEventListener('pointerup', backButtonGlobalMSPointerUpHandler, false); } function unHookBackButtonGlobalEventHandlers() { // Unsubscribes from global events on the window object window.removeEventListener('keyup', backButtonGlobalKeyUpHandler, false) window.removeEventListener('pointerup', backButtonGlobalMSPointerUpHandler, false); } function backButtonGlobalKeyUpHandler(event) { // Navigates back when (alt + left) or BrowserBack keys are released. if ((event.key === KEY_LEFT && event.altKey && !event.shiftKey && !event.ctrlKey) || (event.key === KEY_BROWSER_BACK)) { nav.back(); } } function backButtonGlobalMSPointerUpHandler(event) { // Responds to clicks to enable navigation using 'back' mouse buttons. if (event.button === MOUSE_BACK_BUTTON) { nav.back(); } } // Singleton reference count for registering and unregistering global event handlers. var backButtonReferenceCount = 0; // /* Step 2: Return Singleton object literal */ return { addRef: function () { if (backButtonReferenceCount === 0) { hookUpBackButtonGlobalEventHandlers(); } backButtonReferenceCount++; }, release: function () { if (backButtonReferenceCount > 0) { // Ensure count won't become negative. backButtonReferenceCount--; if (backButtonReferenceCount === 0) { unHookBackButtonGlobalEventHandlers(); } } }, getCount: function () { // Return the value of the reference count. Useful for unit testing. return backButtonReferenceCount; } }; }()); // Immediate invoke creates and returns the Singleton WinJS.Namespace.define("WinJS.UI", { /// /// /// Provides backwards navigation functionality. /// /// /// /// /// /// ]]> /// The BackButton control itself /// The Back Arrow glyph /// /// /// BackButton: WinJS.Namespace._lazy(function () { // Statics var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/backbuttonarialabel").value; }, get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; }, get badButtonElement() { return WinJS.Resources._getWinJSString("ui/badButtonElement").value; } }; var BackButton = WinJS.Class.define(function BackButton_ctor(element, options) { /// /// /// Creates a new BackButton control /// /// /// The DOM element that will host the control. If this parameter is null, this constructor creates one for you. /// /// /// An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to /// one of the control's properties or events. /// /// /// A BackButton control. /// /// /// // Check to make sure we weren't duplicated if (element && element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.BackButton.DuplicateConstruction", strings.duplicateConstruction); } this._element = element || document.createElement("button"); options = options || {}; this._initializeButton(); // This will also set the aria-label and tooltip this._disposed = false; // Remember ourselves this._element.winControl = this; WinJS.UI.setOptions(this, options); // Add event handlers for this back button instance this._buttonClickHandler = this._handleBackButtonClick.bind(this); this._element.addEventListener('click', this._buttonClickHandler, false); this._navigatedHandler = this._handleNavigatedEvent.bind(this); nav.addEventListener('navigated', this._navigatedHandler, false); // Increment reference count / manage add global event handlers singleton.addRef(); }, { /// element: { get: function () { return this._element; } }, dispose: function () { /// /// /// Disposes this control. /// /// /// if (this._disposed) { return; } this._disposed = true; // Mark this control as disposed. // Remove 'navigated' eventhandler for this BackButton nav.removeEventListener('navigated', this._navigatedHandler, false); singleton.release(); // Decrement reference count. }, refresh: function () { /// /// /// Sets the 'disabled' attribute to correct the value based on the current navigation history stack. /// /// /// if (nav.canGoBack) { this._element.disabled = false; } else { this._element.disabled = true; } }, _initializeButton: function () { //Final EN-US HTML should be: // //Button will automatically be disabled if WinJS.Navigation.history.canGoBack is false. // Verify the HTML is a button if (this._element.tagName !== "BUTTON") { throw new WinJS.ErrorFromName("WinJS.UI.BackButton.BadButtonElement", strings.badButtonElement); } // Attach our css classes WinJS.Utilities.addClass(this._element, navigationBackButtonClass); // Attach disposable class. WinJS.Utilities.addClass(this._element, "win-disposable"); // Create inner glyph element this._element.innerHTML = ''; // Set the 'disabled' property to the correct value based on the current navigation history stack. this.refresh(); // Set Aria-label and native tooltip to the same localized string equivalent of "Back" this._element.setAttribute("aria-label", strings.ariaLabel); this._element.setAttribute("title", strings.ariaLabel); // Explicitly set type attribute to avoid the default '; this._headerTabStopElement = this._headerElement.firstElementChild; this._headerContentElement = this._headerTabStopElement.firstElementChild; this._headerChevronElement = this._headerTabStopElement.lastElementChild; element.appendChild(this._headerElement); this._winKeyboard = new WinJS.UI._WinKeyboard(this._headerElement); this._contentElement = document.createElement("DIV"); this._contentElement.className = WinJS.UI.HubSection._ClassName.hubSectionContent; this._contentElement.style.visibility = "hidden"; element.appendChild(this._contentElement); // Reparent any existing elements inside the new hub section content element. var elementToMove = this.element.firstChild; while (elementToMove !== this._headerElement) { var nextElement = elementToMove.nextSibling; this._contentElement.appendChild(elementToMove); elementToMove = nextElement; } this._processors = [WinJS.UI.processAll]; WinJS.UI.setOptions(this, options); }, { /// element: { get: function () { return this._element; } }, /// /// Gets or sets a value that specifies whether the header is static. Set this value to true to disable clicks and other interactions. /// /// isHeaderStatic: { get: function () { return this._isHeaderStatic; }, set: function (value) { this._isHeaderStatic = value; if (!this._isHeaderStatic) { this._headerTabStopElement.setAttribute("role", "link"); WinJS.Utilities.addClass(this._headerTabStopElement, WinJS.UI.HubSection._ClassName.hubSectionInteractive); } else { this._headerTabStopElement.setAttribute("role", "heading"); WinJS.Utilities.removeClass(this._headerTabStopElement, WinJS.UI.HubSection._ClassName.hubSectionInteractive); } } }, /// /// Gets the DOM element that hosts the HubSection's content. /// /// contentElement: { get: function () { return this._contentElement; } }, /// /// Get or set the HubSection's header. After you set this property, the Hub renders the header again. /// /// header: { get: function () { return this._header; }, set: function (value) { // Render again even if it is equal to itself. this._header = value; this._renderHeader(); } }, _setHeaderTemplate: function HubSection_setHeaderTemplate(template) { this._template = WinJS.Utilities._syncRenderer(template); this._renderHeader(); }, _renderHeader: function HubSection_renderHeader() { if (this._template) { WinJS.Utilities._disposeElement(this._headerContentElement); WinJS.Utilities.empty(this._headerContentElement); this._template(this, this._headerContentElement); } }, _process: function HubSection_process() { var that = this; this._processed = (this._processors || []).reduce(function (promise, processor) { return promise.then(function () { return processor(that.contentElement); }); }, this._processed || WinJS.Promise.as()); this._processors = null; return this._processed; }, dispose: function HubSection_dispose() { /// /// /// Disposes this control. /// /// /// if (this._disposed) { return; } this._disposed = true; this._processors = null; WinJS.Utilities._disposeElement(this._headerContentElement); WinJS.Utilities.disposeSubTree(this.contentElement); } }, { // Names of classes used by the HubSection. _ClassName: { hubSection: "win-hub-section", hubSectionHeader: "win-hub-section-header", hubSectionHeaderTabStop: "win-hub-section-header-tabstop", hubSectionInteractive: "win-hub-section-header-interactive", hubSectionHeaderContent: "win-hub-section-header-content", hubSectionHeaderChevron: "win-hub-section-header-chevron", hubSectionContent: "win-hub-section-content" }, _Constants: { ellipsisTypeClassName: "win-type-ellipsis", xLargeTypeClassName: "win-type-x-large" }, isDeclarativeControlContainer: WinJS.Utilities.markSupportedForProcessing(function (section, callback) { if (callback === WinJS.UI.processAll) { return; } section._processors = section._processors || []; section._processors.push(callback); // Once processed the first time synchronously queue up new processors as they come in if (section._processed) { section._process(); } }) }); }) }); })(this, WinJS); /// animatable,appbar,appbars,divs,Flyout,Flyouts,iframe,Statics,unfocus,unselectable (function overlayInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _Overlay: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; var utilities = WinJS.Utilities; var createEvent = utilities._createEventProperty; // Class Names var overlayClass = "win-overlay"; var hideFocusClass = "win-hidefocus"; // Prevents the element from showing a focus rect // Event Names var BEFORESHOW = "beforeshow"; var AFTERSHOW = "aftershow"; var BEFOREHIDE = "beforehide"; var AFTERHIDE = "afterhide"; // Helper to get DOM elements from input single object or array or IDs/toolkit/dom elements function _resolveElements(elements) { // No input is just an empty array if (!elements) { return []; } // Make sure it's in array form. if (typeof elements === "string" || !elements || !elements.length) { elements = [elements]; } // Make sure we have a DOM element for each one, (could be string id name or toolkit object) var i, realElements = []; for (i = 0; i < elements.length; i++) { if (elements[i]) { if (typeof elements[i] === "string") { var element = document.getElementById(elements[i]); if (element) { realElements.push(element); } } else if (elements[i].element) { realElements.push(elements[i].element); } else { realElements.push(elements[i]); } } } return realElements; } // Helpers for keyboard showing related events function _allOverlaysCallback(event, command) { var elements = document.querySelectorAll("." + overlayClass); if (elements) { var len = elements.length; for (var i = 0; i < len; i++) { var element = elements[i]; var control = element.winControl; if (!control._disposed) { if (control) { control[command](event); } } } } } function _edgyMayHideFlyouts() { if (!_Overlay._rightMouseMightEdgy) { _Overlay._hideAllFlyouts(); } } var _Overlay = WinJS.Class.define(function _Overlay_ctor(element, options) { /// /// /// Constructs the Overlay control and associates it with the underlying DOM element. /// /// /// The DOM element to be associated with the Overlay control. /// /// /// The set of options to be applied initially to the Overlay control. /// /// A fully constructed Overlay control. /// this._baseOverlayConstructor(element, options); }, { // Functions/properties _baseOverlayConstructor: function _Overlay_baseOverlayConstructor(element, options) { this._disposed = false; // Make sure there's an input element if (!element) { element = document.createElement("div"); } // Check to make sure we weren't duplicated var overlay = element.winControl; if (overlay) { throw new WinJS.ErrorFromName("WinJS.UI._Overlay.DuplicateConstruction", strings.duplicateConstruction); } if (!this._element) { this._element = element; } this._sticky = false; this._doNext = ""; this._element.style.visibility = "hidden"; this._element.style.opacity = 0; // Remember ourselves element.winControl = this; // Attach our css class WinJS.Utilities.addClass(this._element, overlayClass); WinJS.Utilities.addClass(this._element, "win-disposable"); // We don't want to be selectable, set UNSELECTABLE var unselectable = this._element.getAttribute("unselectable"); if (unselectable === null || unselectable === undefined) { this._element.setAttribute("unselectable", "on"); } // Base animation is popIn/popOut this._currentAnimateIn = this._baseAnimateIn; this._currentAnimateOut = this._baseAnimateOut; this._animationPromise = WinJS.Promise.as(); // Command Animations to Queue this._queuedToShow = []; this._queuedToHide = []; this._queuedCommandAnimation = false; if (options) { WinJS.UI.setOptions(this, options); } }, /// element: { get: function () { return this._element; } }, /// Disable an Overlay, setting or getting the HTML disabled attribute. When disabled the Overlay will no longer display with show(), and will hide if currently visible. disabled: { get: function () { // Ensure it's a boolean because we're using the DOM element to keep in-sync return !!this._element.disabled; }, set: function (value) { // Force this check into a boolean because our current state could be a bit confused since we tie to the DOM element value = !!value; var oldValue = !!this._element.disabled; if (oldValue !== value) { this._element.disabled = value; if (!this.hidden && this._element.disabled) { this._hideOrDismiss(); } } } }, /// /// Occurs immediately before the control is shown. /// onbeforeshow: createEvent(BEFORESHOW), /// /// Occurs immediately after the control is shown. /// onaftershow: createEvent(AFTERSHOW), /// /// Occurs immediately before the control is hidden. /// onbeforehide: createEvent(BEFOREHIDE), /// /// Occurs immediately after the control is hidden. /// onafterhide: createEvent(AFTERHIDE), dispose: function () { /// /// /// Disposes this Overlay. /// /// if (this._disposed) { return; } this._disposed = true; this._dispose(); }, _dispose: function _Overlay_dispose() { // To be overridden by subclasses }, show: function () { /// /// /// Shows the Overlay, if hidden, regardless of other state /// /// // call private show to distinguish it from public version this._show(); }, _show: function _Overlay_show() { // We call our base _baseShow because AppBar may need to override show this._baseShow(); }, hide: function () { /// /// /// Hides the Overlay, if visible, regardless of other state /// /// // call private hide to distinguish it from public version this._hide(); }, _hide: function _Overlay_hide() { // We call our base _baseHide because AppBar may need to override hide this._baseHide(); }, // Is the overlay "hidden"? /// hidden: { get: function () { return (this._element.style.visibility === "hidden" || this._element.winAnimating === "hiding" || this._doNext === "hide" || this._fakeHide); } }, addEventListener: function (type, listener, useCapture) { /// /// /// Add an event listener to the DOM element for this Overlay /// /// Required. Event type to add, "beforehide", "afterhide", "beforeshow", or "aftershow" /// Required. The event handler function to associate with this event. /// Optional. True, register for the event capturing phase. False for the event bubbling phase. /// return this._element.addEventListener(type, listener, useCapture); }, removeEventListener: function (type, listener, useCapture) { /// /// /// Remove an event listener to the DOM element for this Overlay /// /// Required. Event type to remove, "beforehide", "afterhide", "beforeshow", or "aftershow" /// Required. The event handler function to associate with this event. /// Optional. True, register for the event capturing phase. False for the event bubbling phase. /// return this._element.removeEventListener(type, listener, useCapture); }, _baseShow: function _Overlay_baseShow() { // If we are already animating, just remember this for later if (this._animating || this._keyboardShowing || this._keyboardHiding) { this._doNext = "show"; return false; } // Each overlay tracks the window width for detecting resizes in the resize handler. this._currentDocumentWidth = this._currentDocumentWidth || document.documentElement.offsetWidth; // "hiding" would need to cancel. if (this._element.style.visibility !== "visible" || this._fakeHide) { // Let us know we're showing. this._element.winAnimating = "showing"; // Hiding, but not none this._element.style.display = ""; if (!this._fakeHide) { this._element.style.visibility = "hidden"; } // In case their event is going to manipulate commands, see if there are // any queued command animations we can handle while we're still hidden. if (this._queuedCommandAnimation) { this._showAndHideFast(this._queuedToShow, this._queuedToHide); this._queuedToShow = []; this._queuedToHide = []; } // Send our "beforeShow" event this._sendEvent(_Overlay.beforeShow); // Need to measure this._findPosition(); // Make sure it's visible, and fully opaque. // Do the popup thing, sending event afterward. var that = this; this._animationPromise = this._currentAnimateIn(). then(function () { that._baseEndShow(); }, function (err) { that._baseEndShow(); }); this._fakeHide = false; return true; } return false; }, // Flyout in particular will need to measure our positioning. _findPosition: function _Overlay_findPosition() { }, _baseEndShow: function _Overlay_baseEndShow() { if (this._disposed) { return; } // Make sure it's visible after showing this._element.setAttribute("aria-hidden", "false"); this._element.winAnimating = ""; // Do our derived classes show stuff this._endShow(); // We're shown now if (this._doNext === "show") { this._doNext = ""; } // After showing, send the after showing event this._sendEvent(_Overlay.afterShow); this._writeProfilerMark("show,StopTM"); // Overlay writes the stop profiler mark for all of its derived classes. // If we had something queued, do that WinJS.Utilities.Scheduler.schedule(this._checkDoNext, WinJS.Utilities.Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); }, _endShow: function _Overlay_endShow() { // Nothing by default }, _baseHide: function _Overlay_baseHide() { // If we are already animating, just remember this for later if (this._animating || this._keyboardShowing) { this._doNext = "hide"; return false; } // In the unlikely event we're between the hiding keyboard and the resize events, just snap it away: if (this._keyboardHiding) { // use the "uninitialized" flag this._element.style.visibility = ""; } // "showing" would need to queue up. if (this._element.style.visibility !== "hidden") { // Let us know we're hiding, accessibility as well. this._element.winAnimating = "hiding"; this._element.setAttribute("aria-hidden", "true"); // Send our "beforeHide" event this._sendEvent(_Overlay.beforeHide); // If our visibility is empty, then this is the first time, just hide it if (this._element.style.visibility === "") { // Initial hiding, just hide it this._element.style.opacity = 0; this._baseEndHide(); } else { // Make sure it's hidden, and fully transparent. var that = this; this._animationPromise = this._currentAnimateOut(). then(function () { that._baseEndHide(); }, function (err) { that._baseEndHide(); }); } return true; } this._fakeHide = false; return false; }, _baseEndHide: function _Overlay_baseEndHide() { if (this._disposed) { return; } // Make sure animation is finished. this._element.style.visibility = "hidden"; this._element.style.display = "none"; this._element.winAnimating = ""; // In case their event is going to manipulate commands, see if there // are any queued command animations we can handle now we're hidden. if (this._queuedCommandAnimation) { this._showAndHideFast(this._queuedToShow, this._queuedToHide); this._queuedToShow = []; this._queuedToHide = []; } // We're hidden now if (this._doNext === "hide") { this._doNext = ""; } // After hiding, send our "afterHide" event this._sendEvent(_Overlay.afterHide); this._writeProfilerMark("hide,StopTM"); // Overlay writes the stop profiler mark for all of its derived classes. // If we had something queued, do that. This has to be after // the afterHide event in case it triggers a show() and they // have something to do in beforeShow that requires afterHide first. WinJS.Utilities.Scheduler.schedule(this._checkDoNext, WinJS.Utilities.Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); }, _checkDoNext: function _Overlay_checkDoNext() { // Do nothing if we're still animating if (this._animating || this._keyboardShowing || this._keyboardHiding || this._disposed) { return; } if (this._doNext === "hide") { // Do hide first because animating commands would be easier this._hide(); this._doNext = ""; } else if (this._queuedCommandAnimation) { // Do queued commands before showing if possible this._showAndHideQueue(); } else if (this._doNext === "show") { // Show last so that we don't unnecessarily animate commands this._show(); this._doNext = ""; } }, // Default animations _baseAnimateIn: function _Overlay_baseAnimateIn() { this._element.style.opacity = 0; this._element.style.visibility = "visible"; // touch opacity so that IE fades from the 0 we just set to 1 window.getComputedStyle(this._element, null).opacity; return WinJS.UI.Animation.fadeIn(this._element); }, _baseAnimateOut: function _Overlay_baseAnimateOut() { this._element.style.opacity = 1; // touch opacity so that IE fades from the 1 we just set to 0 window.getComputedStyle(this._element, null).opacity; return WinJS.UI.Animation.fadeOut(this._element); }, _animating: { get: function _Overlay_animating_get() { // Ensure it's a boolean because we're using the DOM element to keep in-sync return !!this._element.winAnimating; } }, // Send one of our events _sendEvent: function _Overlay_sendEvent(eventName, detail) { if (this._disposed) { return; } var event = document.createEvent("CustomEvent"); event.initEvent(eventName, true, true, (detail || {})); this._element.dispatchEvent(event); }, // Show commands _showCommands: function _Overlay_showCommands(commands, immediate) { var showHide = this._resolveCommands(commands); this._showAndHideCommands(showHide.commands, [], immediate); }, // Hide commands _hideCommands: function _Overlay_hideCommands(commands, immediate) { var showHide = this._resolveCommands(commands); this._showAndHideCommands([], showHide.commands, immediate); }, // Hide commands _showOnlyCommands: function _Overlay_showOnlyCommands(commands, immediate) { var showHide = this._resolveCommands(commands); this._showAndHideCommands(showHide.commands, showHide.others, immediate); }, _showAndHideCommands: function _Overlay_showAndHideCommands(showCommands, hideCommands, immediate) { // Immediate is "easy" if (immediate || (this.hidden && !this._animating)) { // Immediate mode (not animated) this._showAndHideFast(showCommands, hideCommands); // Need to remove them from queues, but others could be queued this._removeFromQueue(showCommands, this._queuedToShow); this._removeFromQueue(hideCommands, this._queuedToHide); } else { // Queue Commands this._updateAnimateQueue(showCommands, this._queuedToShow, this._queuedToHide); this._updateAnimateQueue(hideCommands, this._queuedToHide, this._queuedToShow); } }, _removeFromQueue: function _Overlay_removeFromQueue(commands, queue) { // remove commands from queue. var count; for (count = 0; count < commands.length; count++) { // Remove if it was in queue var countQ; for (countQ = 0; countQ < queue.length; countQ++) { if (queue[countQ] === commands[count]) { queue.splice(countQ, 1); break; } } } }, _updateAnimateQueue: function _Overlay_updateAnimateQueue(addCommands, toQueue, fromQueue) { if (this._disposed) { return; } // Add addCommands to toQueue and remove addCommands from fromQueue. var count; for (count = 0; count < addCommands.length; count++) { // See if it's already in toQueue var countQ; for (countQ = 0; countQ < toQueue.length; countQ++) { if (toQueue[countQ] === addCommands[count]) { break; } } if (countQ === toQueue.length) { // Not found, add it toQueue[countQ] = addCommands[count]; } // Remove if it was in fromQueue for (countQ = 0; countQ < fromQueue.length; countQ++) { if (fromQueue[countQ] === addCommands[count]) { fromQueue.splice(countQ, 1); break; } } } // If we haven't queued the actual animation if (!this._queuedCommandAnimation) { // If not already animating, we'll need to call _checkDoNext if (!this._animating) { WinJS.Utilities.Scheduler.schedule(this._checkDoNext, WinJS.Utilities.Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); } this._queuedCommandAnimation = true; } }, // show/hide commands without doing any animation. _showAndHideFast: function _Overlay_showAndHideFast(showCommands, hideCommands) { var count; var command; for (count = 0; count < showCommands.length; count++) { command = showCommands[count]; if (command && command.style) { command.style.visibility = ""; command.style.display = ""; } } for (count = 0; count < hideCommands.length; count++) { command = hideCommands[count]; if (command && command.style) { command.style.visibility = "hidden"; command.style.display = "none"; } } this._contentChanged(); }, // show and hide the queued commands, perhaps animating if overlay isn't hidden. _showAndHideQueue: function _Overlay_showAndHideQueue() { // Only called if not currently animating. // We'll be done with the queued stuff when we return. this._queuedCommandAnimation = false; // Shortcut if hidden if (this.hidden) { this._showAndHideFast(this._queuedToShow, this._queuedToHide); // Might be something else to do WinJS.Utilities.Scheduler.schedule(this._checkDoNext, WinJS.Utilities.Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); } else { // Animation has 3 parts: "hiding", "showing", and "moving" // PVL has "addToList" and "deleteFromList", both of which allow moving parts. // So we'll set up "add" for showing, and use "delete" for "hiding" + moving, // then trigger both at the same time. var showCommands = this._queuedToShow; var hideCommands = this._queuedToHide; var siblings = this._findSiblings(showCommands.concat(hideCommands)); // Filter out the commands queued for animation that don't need to be animated. var count; for (count = 0; count < showCommands.length; count++) { // If this one's not real or not attached, skip it if (!showCommands[count] || !showCommands[count].style || !document.body.contains(showCommands[count])) { // Not real, skip it showCommands.splice(count, 1); count--; } else if (showCommands[count].style.visibility !== "hidden" && showCommands[count].style.opacity !== "0") { // Don't need to animate showing this one, already visible, so now it's a sibling siblings.push(showCommands[count]); showCommands.splice(count, 1); count--; } } for (count = 0; count < hideCommands.length; count++) { // If this one's not real or not attached, skip it if (!hideCommands[count] || !hideCommands[count].style || !document.body.contains(hideCommands[count]) || hideCommands[count].style.visibility === "hidden" || hideCommands[count].style.opacity === "0") { // Don't need to animate hiding this one, not real, or it's hidden, // so don't even need it as a sibling. hideCommands.splice(count, 1); count--; } } // Start command animations. var commandsAnimationPromise = this._baseBeginAnimateCommands(showCommands, hideCommands, siblings); // Hook end animations var that = this; if (commandsAnimationPromise) { // Needed to animate commandsAnimationPromise.done( function () { that._baseEndAnimateCommands(hideCommands); }, function () { that._baseEndAnimateCommands(hideCommands); } ); } else { // Already positioned correctly WinJS.Utilities.Scheduler.schedule(function () { that._baseEndAnimateCommands([]); }, WinJS.Utilities.Scheduler.Priority.normal, null, "WinJS.UI._Overlay._endAnimateCommandsWithoutAnimation"); } } // Done, clear queues this._queuedToShow = []; this._queuedToHide = []; }, _baseBeginAnimateCommands: function _Overlay_baseBeginAnimateCommands(showCommands, hideCommands, siblings) { // The parameters are 3 mutually exclusive arrays of win-command elements contained in this Overlay. // 1) showCommands[]: All of the HIDDEN win-command elements that ARE scheduled to show. // 2) hideCommands[]: All of the VISIBLE win-command elements that ARE shceduled to hide. // 3) siblings[]: i. All VISIBLE win-command elements that ARE NOT scheduled to hide. // ii. All HIDDEN win-command elements that ARE NOT scheduled to hide OR show. this._beginAnimateCommands(showCommands, hideCommands, this._getVisibleCommands(siblings)); var showAnimated = null, hideAnimated = null; // Hide commands first, with siblings if necessary, // so that the showing commands don't disrupt the hiding commands position. if (hideCommands.length > 0) { hideAnimated = WinJS.UI.Animation.createDeleteFromListAnimation(hideCommands, showCommands.length === 0 ? siblings : undefined); } if (showCommands.length > 0) { showAnimated = WinJS.UI.Animation.createAddToListAnimation(showCommands, siblings); } // Update hiding commands for (var count = 0, len = hideCommands.length; count < len; count++) { // Need to fix our position var rectangle = hideCommands[count].getBoundingClientRect(), style = window.getComputedStyle(hideCommands[count]); // Use the bounding box, adjusting for margins hideCommands[count].style.top = (rectangle.top - parseFloat(style.marginTop)) + "px"; hideCommands[count].style.left = (rectangle.left - parseFloat(style.marginLeft)) + "px"; hideCommands[count].style.opacity = 0; hideCommands[count].style.position = "fixed"; } // Mark as animating this._element.winAnimating = "rearranging"; // Start hiding animations // Hide needs extra cleanup when done var promise = null; if (hideAnimated) { promise = hideAnimated.execute(); } // Update showing commands, // After hiding commands so that the hiding ones fade in the right place. for (count = 0; count < showCommands.length; count++) { showCommands[count].style.visibility = ""; showCommands[count].style.display = ""; showCommands[count].style.opacity = 1; } // Start showing animations if (showAnimated) { var newPromise = showAnimated.execute(); if (promise) { promise = WinJS.Promise.join([promise, newPromise]); } else { promise = newPromise; } } return promise; }, _beginAnimateCommands: function _Overlay_beginAnimateCommands(showCommands, hideCommands, siblings) { // Nothing by default }, _getVisibleCommands: function _Overlay_getVisibleCommands(commandSubSet) { var command, commands = commandSubSet, visibleCommands = []; if (!commands) { // Crawl the inner HTML for the commands. commands = this.element.querySelectorAll(".win-command"); } for (var i = 0, len = commands.length; i < len; i++) { command = commands[i].winControl || commands[i]; if (!command.hidden) { visibleCommands.push(command); } } return visibleCommands; }, // Once animation is complete, ensure that the commands are display:none // and check if there's another animation to start. _baseEndAnimateCommands: function _Overlay_baseEndAnimateCommands(hideCommands) { if (this._disposed) { return; } // Update us var count; for (count = 0; count < hideCommands.length; count++) { // Force us back into our appbar so that we can show again correctly hideCommands[count].style.position = ""; hideCommands[count].getBoundingClientRect(); // Now make us really hidden hideCommands[count].style.visibility = "hidden"; hideCommands[count].style.display = "none"; hideCommands[count].style.opacity = 1; } // Done animating this._element.winAnimating = ""; this._endAnimateCommands(); // Might be something else to do this._checkDoNext(); }, _endAnimateCommands: function _Overlay_endAnimateCommands() { // Nothing by default }, // Resolves our commands _resolveCommands: function _Overlay_resolveCommands(commands) { // First make sure they're all DOM elements. commands = _resolveElements(commands); // Now make sure they're all in this container var result = {}; result.commands = []; result.others = []; var allCommands = this.element.querySelectorAll(".win-command"); var countAll, countIn; for (countAll = 0; countAll < allCommands.length; countAll++) { var found = false; for (countIn = 0; countIn < commands.length; countIn++) { if (commands[countIn] === allCommands[countAll]) { result.commands.push(allCommands[countAll]); commands.splice(countIn, 1); found = true; break; } } if (!found) { result.others.push(allCommands[countAll]); } } return result; }, // Find siblings, all DOM elements now. // Returns all .win-commands in this Overlay that are NOT in the passed in 'commands' array. _findSiblings: function _Overlay_findSiblings(commands) { // Now make sure they're all in this container var siblings = []; var allCommands = this.element.querySelectorAll(".win-command"); var countAll, countIn; for (countAll = 0; countAll < allCommands.length; countAll++) { var found = false; for (countIn = 0; countIn < commands.length; countIn++) { if (commands[countIn] === allCommands[countAll]) { commands.splice(countIn, 1); found = true; break; } } if (!found) { siblings.push(allCommands[countAll]); } } return siblings; }, _baseResize: function _Overlay_baseResize(event) { // Avoid the cost of a resize if the Overlay is hidden. if (this._currentDocumentWidth !== undefined) { if (this._element.style.visibility === "hidden") { this._currentDocumentWidth = undefined; } else { // Overlays can light dismiss on horizontal resize. var newWidth = document.documentElement.offsetWidth; if (this._currentDocumentWidth !== newWidth) { this._currentDocumentWidth = newWidth if (!this._sticky) { this._hideOrDismiss(); } } } } // Call specific resize this._resize(event); }, _hideOrDismiss: function _Overlay_hideOrDismiss() { var element = this._element; if (element && WinJS.Utilities.hasClass(element, "win-settingsflyout")) { this._dismiss(); } else { this.hide(); } }, _resize: function _Overlay_resize(event) { // Nothing by default }, _contentChanged: function _Overlay_contentChanged(needToReMeasure) { // Nothing by default }, _checkScrollPosition: function _Overlay_checkScrollPosition(event) { // Nothing by default }, _showingKeyboard: function _Overlay_showingKeyboard(event) { // Nothing by default }, _hidingKeyboard: function _Overlay_hidingKeyboard(event) { // Nothing by default }, // Verify that this HTML AppBar only has AppBar/MenuCommands. _verifyCommandsOnly: function _Overlay_verifyCommandsOnly(element, type) { var children = element.children; var commands = new Array(children.length); for (var i = 0; i < children.length; i++) { // If constructed they have win-command class, otherwise they have data-win-control if (!WinJS.Utilities.hasClass(children[i], "win-command") && children[i].getAttribute("data-win-control") !== type) { // Wasn't tagged with class or AppBar/MenuCommand, not an AppBar/MenuCommand throw new WinJS.ErrorFromName("WinJS.UI._Overlay.MustContainCommands", strings.mustContainCommands); } else { // Instantiate the commands. WinJS.UI.processAll(children[i]); commands[i] = children[i].winControl; } } return commands; }, // Sets focus on what we think is the last tab stop. If nothing is focusable will // try to set focus on itself. _focusOnLastFocusableElementOrThis: function _Overlay_focusOnLastFocusableElementOrThis() { if (!this._focusOnLastFocusableElement()) { // Nothing is focusable. Set focus to this. _Overlay._trySetActive(this._element); } }, // Sets focus to what we think is the last tab stop. This element must have // a firstDiv with tabIndex equal to the lowest tabIndex in the element // and a finalDiv with tabIndex equal to the highest tabIndex in the element. // Also the firstDiv must be its first child and finalDiv be its last child. // Returns true if successful, false otherwise. _focusOnLastFocusableElement: function _Overlay_focusOnLastFocusableElement() { if (this._element.firstElementChild) { var oldFirstTabIndex = this._element.firstElementChild.tabIndex; var oldLastTabIndex = this._element.lastElementChild.tabIndex; this._element.firstElementChild.tabIndex = -1; this._element.lastElementChild.tabIndex = -1; var tabResult = WinJS.Utilities._focusLastFocusableElement(this._element); if (tabResult) { _Overlay._trySelect(document.activeElement); } this._element.firstElementChild.tabIndex = oldFirstTabIndex; this._element.lastElementChild.tabIndex = oldLastTabIndex; return tabResult; } else { return false; } }, // Sets focus on what we think is the first tab stop. If nothing is focusable will // try to set focus on itself. _focusOnFirstFocusableElementOrThis: function _Overlay_focusOnFirstFocusableElementOrThis() { if (!this._focusOnFirstFocusableElement()) { // Nothing is focusable. Set focus to this. _Overlay._trySetActive(this._element); } }, // Sets focus to what we think is the first tab stop. This element must have // a firstDiv with tabIndex equal to the lowest tabIndex in the element // and a finalDiv with tabIndex equal to the highest tabIndex in the element. // Also the firstDiv must be its first child and finalDiv be its last child. // Returns true if successful, false otherwise. _focusOnFirstFocusableElement: function _Overlay__focusOnFirstFocusableElement() { if (this._element.firstElementChild) { var oldFirstTabIndex = this._element.firstElementChild.tabIndex; var oldLastTabIndex = this._element.lastElementChild.tabIndex; this._element.firstElementChild.tabIndex = -1; this._element.lastElementChild.tabIndex = -1; var tabResult = WinJS.Utilities._focusFirstFocusableElement(this._element); if (tabResult) { _Overlay._trySelect(document.activeElement); } this._element.firstElementChild.tabIndex = oldFirstTabIndex; this._element.lastElementChild.tabIndex = oldLastTabIndex; return tabResult; } else { return false; } }, _addOverlayEventHandlers: function _Overlay_addOverlayEventHandlers(isFlyoutOrSettingsFlyout) { // Set up global event handlers for all overlays if (!_Overlay._flyoutEdgeLightDismissEvent) { // Dismiss on blur & resize window.addEventListener("blur", _Overlay._checkBlur, false); var that = this; // Be careful so it behaves in designer as well. if (WinJS.Utilities.hasWinRT) { // Catch edgy events too var commandUI = Windows.UI.Input.EdgeGesture.getForCurrentView(); commandUI.addEventListener("starting", _Overlay._hideAllFlyouts); commandUI.addEventListener("completed", _edgyMayHideFlyouts); // React to Soft Keyboard events var inputPane = Windows.UI.ViewManagement.InputPane.getForCurrentView(); inputPane.addEventListener("showing", function (event) { that._writeProfilerMark("_showingKeyboard,StartTM"); _allOverlaysCallback(event, "_showingKeyboard"); that._writeProfilerMark("_showingKeyboard,StopTM"); }); inputPane.addEventListener("hiding", function (event) { that._writeProfilerMark("_hidingKeyboard,StartTM"); _allOverlaysCallback(event, "_hidingKeyboard"); that._writeProfilerMark("_hidingKeyboard,StopTM"); }); // Document scroll event document.addEventListener("scroll", function (event) { that._writeProfilerMark("_checkScrollPosition,StartTM"); _allOverlaysCallback(event, "_checkScrollPosition"); that._writeProfilerMark("_checkScrollPosition,StopTM"); }); } // Window resize event window.addEventListener("resize", function (event) { that._writeProfilerMark("_baseResize,StartTM"); _allOverlaysCallback(event, "_baseResize"); that._writeProfilerMark("_baseResize,StopTM"); }); _Overlay._flyoutEdgeLightDismissEvent = true; } // Individual handlers for Flyouts only if (isFlyoutOrSettingsFlyout) { this._handleEventsForFlyoutOrSettingsFlyout(); } }, _handleEventsForFlyoutOrSettingsFlyout: function _Overlay_handleEventsForFlyoutOrSettingsFlyout() { var that = this; // Need to hide ourselves if we lose focus this._element.addEventListener("focusout", function (e) { _Overlay._hideIfLostFocus(that, e); }, false); // Attempt to flag right clicks that may turn into edgy this._element.addEventListener("pointerdown", _Overlay._checkRightClickDown, true); this._element.addEventListener("pointerup", _Overlay._checkRightClickUp, true); }, _writeProfilerMark: function _Overlay_writeProfilerMark(text) { msWriteProfilerMark("WinJS.UI._Overlay:" + this._id + ":" + text); } }); // Statics _Overlay._clickEatingAppBarDiv = false; _Overlay._clickEatingFlyoutDiv = false; _Overlay._flyoutEdgeLightDismissEvent = false; _Overlay._hideFlyouts = function (testElement, notSticky) { var elements = testElement.querySelectorAll(".win-flyout"); var len = elements.length; for (var i = 0; i < len; i++) { var element = elements[i]; if (element.style.visibility !== "hidden") { var flyout = element.winControl; if (flyout && (!notSticky || !flyout._sticky)) { flyout._hideOrDismiss(); } } } }; _Overlay._hideSettingsFlyouts = function (testElement, notSticky) { var elements = testElement.querySelectorAll(".win-settingsflyout"); var len = elements.length; for (var i = 0; i < len; i++) { var element = elements[i]; if (element.style.visibility !== "hidden") { var settingsFlyout = element.winControl; if (settingsFlyout && (!notSticky || !settingsFlyout._sticky)) { settingsFlyout._hideOrDismiss(); } } } }; _Overlay._hideAllFlyouts = function () { _Overlay._hideFlyouts(document, true); _Overlay._hideSettingsFlyouts(document, true) }; _Overlay._createClickEatingDivTemplate = function (divClass, hideClickEatingDivFunction) { var clickEatingDiv = document.createElement("section"); WinJS.Utilities.addClass(clickEatingDiv, divClass); clickEatingDiv.addEventListener("pointerup", function (event) { _Overlay._checkSameClickEatingPointerUp(event, true); }, true); clickEatingDiv.addEventListener("pointerdown", function (event) { _Overlay._checkClickEatingPointerDown(event, true); }, true); clickEatingDiv.addEventListener("click", hideClickEatingDivFunction, true); // Tell Aria that it's clickable clickEatingDiv.setAttribute("role", "menuitem"); clickEatingDiv.setAttribute("aria-label", strings.closeOverlay); // Prevent CED from removing any current selection clickEatingDiv.setAttribute("unselectable", "on"); document.body.appendChild(clickEatingDiv); return clickEatingDiv; }; // Used by AppBar, and Settings Pane _Overlay._createClickEatingDivAppBar = function () { if (!_Overlay._clickEatingAppBarDiv) { _Overlay._clickEatingAppBarDiv = _Overlay._createClickEatingDivTemplate(_Overlay._clickEatingAppBarClass, _Overlay._handleAppBarClickEatingClick); } }; // Used by Flyout and Menu _Overlay._createClickEatingDivFlyout = function () { if (!_Overlay._clickEatingFlyoutDiv) { _Overlay._clickEatingFlyoutDiv = _Overlay._createClickEatingDivTemplate(_Overlay._clickEatingFlyoutClass, _Overlay._handleFlyoutClickEatingClick); } }; // All click-eaters eat "down" clicks so that we can still eat // the "up" click that'll come later. _Overlay._checkClickEatingPointerDown = function (event, stopPropogation) { var target = event.currentTarget; if (target) { try { // Remember pointer id and remember right mouse target._winPointerId = event.pointerId; // Cache right mouse if that was what happened target._winRightMouse = (event.button === 2); } catch (e) { } } if (stopPropogation && !target._winRightMouse) { event.stopPropagation(); event.preventDefault(); } }; // Make sure that if we have an up we had an earlier down of the same kind _Overlay._checkSameClickEatingPointerUp = function (event, stopPropogation) { var result = false, rightMouse = false, target = event.currentTarget; // Same pointer we were watching? try { if (target && target._winPointerId === event.pointerId) { // Same pointer result = true; rightMouse = target._winRightMouse; // For click-eaters, don't count right click the same because edgy will dismiss if (rightMouse && stopPropogation) { result = false; } } } catch (e) { } if (stopPropogation && !rightMouse) { event.stopPropagation(); event.preventDefault(); } return result; }; // If they click on a click eating div, even with a right click, // touch or anything, then we want to light dismiss that layer. _Overlay._handleAppBarClickEatingClick = function (event) { event.stopPropagation(); event.preventDefault(); thisWinUI.AppBar._hideLightDismissAppBars(null, false); _Overlay._hideClickEatingDivAppBar(); _Overlay._hideAllFlyouts(); }; // If they click on a click eating div, even with a right click, // touch or anything, then we want to light dismiss that layer. _Overlay._handleFlyoutClickEatingClick = function (event) { event.stopPropagation(); event.preventDefault(); // Don't light dismiss AppBars because edgy will do that as needed, // so flyouts only. _Overlay._hideClickEatingDivFlyout(); _Overlay._hideFlyouts(document, true); }; _Overlay._checkRightClickDown = function (event) { _Overlay._checkClickEatingPointerDown(event, false); }; _Overlay._checkRightClickUp = function (event) { if (_Overlay._checkSameClickEatingPointerUp(event, false)) { // It was a right click we may want to eat. _Overlay._rightMouseMightEdgy = true; setImmediate(function () { _Overlay._rightMouseMightEdgy = false; }); } }; _Overlay._showClickEatingDivAppBar = function () { WinJS.Utilities.Scheduler.schedule(function () { _Overlay._clickEatingAppBarDiv.style.display = "block"; }, WinJS.Utilities.Scheduler.Priority.high, null, "WinJS.UI._Overlay._showClickEatingDivAppBar"); }; _Overlay._hideClickEatingDivAppBar = function () { WinJS.Utilities.Scheduler.schedule(function () { _Overlay._clickEatingAppBarDiv.style.display = "none"; }, WinJS.Utilities.Scheduler.Priority.high, null, "WinJS.UI._Overlay._hideClickEatingDivAppBar"); }; _Overlay._showClickEatingDivFlyout = function () { WinJS.Utilities.Scheduler.schedule(function () { _Overlay._clickEatingFlyoutDiv.style.display = "block"; }, WinJS.Utilities.Scheduler.Priority.high, null, "WinJS.UI._Overlay._showClickEatingDivFlyout"); }; _Overlay._hideClickEatingDivFlyout = function () { WinJS.Utilities.Scheduler.schedule(function () { _Overlay._clickEatingFlyoutDiv.style.display = "none"; }, WinJS.Utilities.Scheduler.Priority.high, null, "WinJS.UI._Overlay._hideClickEatingDivFlyout"); }; _Overlay._isFlyoutVisible = function () { if (!_Overlay._clickEatingFlyoutDiv) { return false; } return (_Overlay._clickEatingFlyoutDiv.style.display === "block"); }; _Overlay._hideIfLostFocus = function (overlay, focusEvent) { // If we're still showing we haven't really lost focus if (overlay.hidden || overlay.element.winAnimating === "showing" || overlay._sticky) { return; } // If the active thing is within our element, we haven't lost focus var active = document.activeElement; if (overlay._element && overlay._element.contains(active)) { return; } // SettingFlyouts don't dismiss if they spawned a flyout if (WinJS.Utilities.hasClass(overlay._element, "win-settingsflyout")) { var settingsFlyout = overlay; var flyoutControl = _Overlay._getParentControlUsingClassName(active, "win-flyout"); if (flyoutControl && flyoutControl._previousFocus && settingsFlyout.element.contains(flyoutControl._previousFocus)) { flyoutControl.element.addEventListener('focusout', function focusOut(event) { // When the Flyout closes, hide the SetingsFlyout if it didn't regain focus. _Overlay._hideIfLostFocus(settingsFlyout, event); flyoutControl.element.removeEventListener('focusout', focusOut, false); }, false); return; } } // Do not hide focus if focus moved to a CED. Let the click handler on the CED take care of hiding us. if (active && (WinJS.Utilities.hasClass(active, _Overlay._clickEatingFlyoutClass) || WinJS.Utilities.hasClass(active, _Overlay._clickEatingAppBarClass))) { return; } overlay._hideOrDismiss(); }; // Want to hide flyouts on blur. // We get blur if we click off the window, including to an iframe within our window. // Both blurs call this function, but fortunately document.hasFocus is true if either // the document window or our iframe window has focus. _Overlay._checkBlur = function (focusEvent) { if (!document.hasFocus()) { // The document doesn't have focus, so they clicked off the app, so light dismiss. _Overlay._hideAllFlyouts(); thisWinUI.AppBar._hideLightDismissAppBars(null, false); } else { if ((_Overlay._clickEatingFlyoutDiv && _Overlay._clickEatingFlyoutDiv.style.display === "block") || (_Overlay._clickEatingAppBarDiv && _Overlay._clickEatingAppBarDiv.style.display === "block")) { // We were trying to unfocus the window, but document still has focus, // so make sure the iframe that took the focus will check for blur next time. // We don't have to do this if the click eating div is hidden because then // there would be no flyout or appbar needing light dismiss. var active = document.activeElement; if (active && active.tagName === "IFRAME" && !active.msLightDismissBlur) { // This will go away when the IFRAME goes away, and we only create one active.msLightDismissBlur = active.addEventListener("blur", _Overlay._checkBlur, false); } } } }; // Try to set us as active _Overlay._trySetActive = function (element) { if (!element || !element.setActive || !document.body || !document.body.contains(element)) { return false; } try { element.setActive(); } catch (err) { return false; } return (element === document.activeElement); }; // Try to select the text so keyboard can be used. _Overlay._trySelect = function (element) { try { if (element && element.select) { element.select(); } } catch (e) { } }; // Prevent the document.activeElement from showing focus _Overlay._addHideFocusClass = function (element) { if (element) { WinJS.Utilities.addClass(element, hideFocusClass); element.addEventListener("focusout", _Overlay._removeHideFocusClass, false); } }; // Allow the event.target (element that is losing focus) to show focus next time it gains focus _Overlay._removeHideFocusClass = function (event) { // Make sure we really lost focus and was not just an App switch var target = event.target; if (target && target !== document.activeElement) { WinJS.Utilities.removeClass(target, hideFocusClass); event.target.removeEventListener("focusout", _Overlay._removeHideFocusClass, false); } }; _Overlay._getParentControlUsingClassName = function (element, className) { while (element && element !== document.body) { if (WinJS.Utilities.hasClass(element, className)) { return element.winControl; } element = element.parentNode; } return null; }; // Global keyboard hiding offset _Overlay._keyboardInfo = { // Determine if the keyboard is visible or not. get _visible() { try { return (WinJS.Utilities.hasWinRT && Windows.UI.ViewManagement.InputPane.getForCurrentView().occludedRect.height > 0); } catch (e) { return false; } }, // See if we have to reserve extra space for the IHM get _extraOccluded() { var occluded; if (WinJS.Utilities.hasWinRT) { try { occluded = Windows.UI.ViewManagement.InputPane.getForCurrentView().occludedRect.height; } catch (e) { } } // Nothing occluded if not visible. if (occluded && !_Overlay._keyboardInfo._isResized) { // View hasn't been resized, need to return occluded height. return occluded; } // View already has space for keyboard or there's no keyboard return 0; }, // See if the view has been resized to fit a keyboard get _isResized() { // Compare ratios. Very different includes IHM space. var heightRatio = document.documentElement.clientHeight / window.innerHeight, widthRatio = document.documentElement.clientWidth / window.innerWidth; // If they're nearly identical, then the view hasn't been resized for the IHM // Only check one bound because we know the IHM will make it shorter, not skinnier. return (widthRatio / heightRatio < 0.99); }, // Get the top of our visible area in terms of document.documentElement. get _visibleDocTop() { return window.pageYOffset - document.documentElement.scrollTop; }, // Get the bottom of our visible area. get _visibleDocBottom() { return _Overlay._keyboardInfo._visibleDocTop + _Overlay._keyboardInfo._visibleDocHeight; }, // Get the height of the visible document, e.g. the height of the visual viewport minus any IHM occlusion. get _visibleDocHeight() { return _Overlay._keyboardInfo._visualViewportHeight -_Overlay._keyboardInfo._extraOccluded; }, // Get the visual viewport height. window.innerHeight doesn't return floating point values which are present with high DPI. get _visualViewportHeight() { var boundingRect = _Overlay._keyboardInfo._visualViewportSpace; return boundingRect.bottom - boundingRect.top; }, // Get the visual viewport width. window.innerHeight doesn't return floating point values which are present with high DPI. get _visualViewportWidth() { var boundingRect = _Overlay._keyboardInfo._visualViewportSpace; return boundingRect.right - boundingRect.left; }, get _visualViewportSpace() { var className = "win-visualviewport-space" var visualViewportSpace = document.body.querySelector("." + className); if (!visualViewportSpace) { visualViewportSpace = document.createElement("DIV"); visualViewportSpace.className = className; document.body.appendChild(visualViewportSpace); } return visualViewportSpace.getBoundingClientRect(); }, // Get offset of visible window from bottom. get _visibleDocBottomOffset() { // If the view resizes we can return 0 and rely on appbar's -ms-device-fixed css positioning. return (_Overlay._keyboardInfo._isResized) ? 0 : _Overlay._keyboardInfo._extraOccluded; }, // Get total length of the IHM showPanel animation get _animationShowLength() { if (!WinJS.Utilities.hasWinRT) { return 0; } var a = Windows.UI.Core.AnimationMetrics, animationDescription = new a.AnimationDescription(a.AnimationEffect.showPanel, a.AnimationEffectTarget.primary); var animations = animationDescription.animations; var max = 0; for (var i = 0; i < animations.size; i++) { var animation = animations[i]; max = Math.max(max, animation.delay + animation.duration); } return max; } }; // Classes other objects use _Overlay._clickEatingAppBarClass = "win-appbarclickeater"; _Overlay._clickEatingFlyoutClass = "win-flyoutmenuclickeater"; // Padding for IHM timer to allow for first scroll event _Overlay._scrollTimeout = 150; // Events _Overlay.beforeShow = BEFORESHOW; _Overlay.beforeHide = BEFOREHIDE; _Overlay.afterShow = AFTERSHOW; _Overlay.afterHide = AFTERHIDE; _Overlay.commonstrings = { get cannotChangeCommandsWhenVisible() { return WinJS.Resources._getWinJSString("ui/cannotChangeCommandsWhenVisible").value; }, get cannotChangeHiddenProperty() { return WinJS.Resources._getWinJSString("ui/cannotChangeHiddenProperty").value; } }; var strings = { get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; }, get mustContainCommands() { return WinJS.Resources._getWinJSString("ui/mustContainCommands").value; }, get closeOverlay() { return WinJS.Resources._getWinJSString("ui/closeOverlay").value; }, }; WinJS.Class.mix(_Overlay, WinJS.UI.DOMEventMixin); return _Overlay; }) }); })(WinJS); // Glyph Enumeration /// Segoe (function appBarIconInit(WinJS) { "use strict"; var glyphs = ["previous", "next", "play", "pause", "edit", "save", "clear", "delete", "remove", "add", "cancel", "accept", "more", "redo", "undo", "home", "up", "forward", "right", "back", "left", "favorite", "camera", "settings", "video", "sync", "download", "mail", "find", "help", "upload", "emoji", "twopage", "leavechat", "mailforward", "clock", "send", "crop", "rotatecamera", "people", "closepane", "openpane", "world", "flag", "previewlink", "globe", "trim", "attachcamera", "zoomin", "bookmarks", "document", "protecteddocument", "page", "bullets", "comment", "mail2", "contactinfo", "hangup", "viewall", "mappin", "phone", "videochat", "switch", "contact", "rename", "pin", "musicinfo", "go", "keyboard", "dockleft", "dockright", "dockbottom", "remote", "refresh", "rotate", "shuffle", "list", "shop", "selectall", "orientation", "import", "importall", "browsephotos", "webcam", "pictures", "savelocal", "caption", "stop", "showresults", "volume", "repair", "message", "page2", "calendarday", "calendarweek", "calendar", "characters", "mailreplyall", "read", "link", "accounts", "showbcc", "hidebcc", "cut", "attach", "paste", "filter", "copy", "emoji2", "important", "mailreply", "slideshow", "sort", "manage", "allapps", "disconnectdrive", "mapdrive", "newwindow", "openwith", "contactpresence", "priority", "uploadskydrive", "gototoday", "font", "fontcolor", "contact2", "folder", "audio", "placeholder", "view", "setlockscreen", "settile", "cc", "stopslideshow", "permissions", "highlight", "disableupdates", "unfavorite", "unpin", "openlocal", "mute", "italic", "underline", "bold", "movetofolder", "likedislike", "dislike", "like", "alignright", "aligncenter", "alignleft", "zoom", "zoomout", "openfile", "otheruser", "admin", "street", "map", "clearselection", "fontdecrease", "fontincrease", "fontsize", "cellphone", "reshare", "tag", "repeatone", "repeatall", "outlinestar", "solidstar", "calculator", "directions", "target", "library", "phonebook", "memo", "microphone", "postupdate", "backtowindow", "fullscreen", "newfolder", "calendarreply", "unsyncfolder", "reporthacked", "syncfolder", "blockcontact", "switchapps", "addfriend", "touchpointer", "gotostart", "zerobars", "onebar", "twobars", "threebars", "fourbars", "scan", "preview"]; // Provide properties to grab resources for each of the icons /// /// The AppBarIcon enumeration provides a set of glyphs for use with the AppBarCommand icon property. /// WinJS.Namespace.define("WinJS.UI.AppBarIcon", glyphs.reduce(function (fixedIcons, item) { fixedIcons[item] = { get: function () { return WinJS.Resources._getWinJSString("ui/appBarIcons/" + item).value; } }; return fixedIcons; }, {})); })(WinJS); // AppBarCommand /// appbar,appbars,Flyout,Flyouts,onclick,Statics (function appBarCommandInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Represents a command to display in an AppBar. /// /// /// /// ]]> /// The AppBarCommand control itself. /// The AppBarCommand's icon box. /// The AppBarCommand's icon's image formatting. /// The AppBarCommand's icon's ring. /// The AppBarCommand's label /// /// /// AppBarCommand: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; // Class Names var appBarCommandClass = "win-command", appBarCommandGlobalClass = "win-global", appBarCommandSelectionClass = "win-selection", reducedClass = "win-reduced", typeSeparator = "separator", typeButton = "button", typeToggle = "toggle", typeFlyout = "flyout", typeContent = "content", sectionSelection = "selection", sectionGlobal = "global"; function _handleClick(event) { var command = this.winControl; if (command) { if (command._type === typeToggle) { command.selected = !command.selected; } else if (command._type === typeFlyout && command._flyout) { var parentAppBar = thisWinUI._Overlay._getParentControlUsingClassName(this, "win-appbar"); var placement = "top"; if (parentAppBar && parentAppBar.placement === "top") { placement = "bottom"; } var flyout = command._flyout; // Flyout may not have processAll'd, so this may be a DOM object if (typeof flyout === "string") { flyout = document.getElementById(flyout); } if (!flyout.show) { flyout = flyout.winControl; } if (flyout && flyout.show) { flyout.show(this, placement); } } if (command.onclick) { command.onclick(event); } } } var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/appBarCommandAriaLabel").value; }, get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; }, get badClick() { return WinJS.Resources._getWinJSString("ui/badClick").value; }, get badDivElement() { return WinJS.Resources._getWinJSString("ui/badDivElement").value; }, get badHrElement() { return WinJS.Resources._getWinJSString("ui/badHrElement").value; }, get badButtonElement() { return WinJS.Resources._getWinJSString("ui/badButtonElement").value; } }; return WinJS.Class.define(function AppBarCommand_ctor(element, options) { /// /// /// Creates a new AppBarCommand control. /// /// /// The DOM element that will host the control. AppBarCommand will create one if null. /// /// /// The set of properties and values to apply to the new AppBarCommand. /// /// /// The new AppBarCommand control. /// /// // Check to make sure we weren't duplicated if (element && element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.AppBarCommand.DuplicateConstruction", strings.duplicateConstruction); } this._disposed = false; // Don't blow up if they didn't pass options if (!options) { options = {}; } // Need a type before we can create our element if (!options.type) { this._type = typeButton; } // Go ahead and create it, separator and content types look different than buttons // Don't forget to use passed in element if one was provided. this._element = element; if (options.type === typeContent) { this._createContent(); } else if (options.type === typeSeparator) { this._createSeparator(); } else { // This will also set the icon & label this._createButton(); } WinJS.Utilities.addClass(this._element, "win-disposable"); // Remember ourselves this._element.winControl = this; // Attach our css class WinJS.Utilities.addClass(this._element, appBarCommandClass); if (options.onclick) { this.onclick = options.onclick; } // We want to handle some clicks options.onclick = _handleClick; WinJS.UI.setOptions(this, options); if (!options.section) { this._setSection(options.section); } if (this._type === typeToggle && !options.selected) { this.selected = false; } // Set up pointerdown handler and clean up ARIA if needed if (this._type !== typeSeparator) { // Hide the modern focus rect on click or touch var that = this; this._element.addEventListener("pointerdown", function () { thisWinUI._Overlay._addHideFocusClass(that._element); }, false); // Make sure we have an ARIA role var role = this._element.getAttribute("role"); if (role === null || role === "" || role === undefined) { if (this._type === typeToggle) { role = "menuitemcheckbox"; } else if (this._type === typeContent) { role = "group"; } else { role = "menuitem"; } this._element.setAttribute("role", role); if (this._type === typeFlyout) { this._element.setAttribute("aria-haspopup", true); } } // Label should've been set by label, but if it was missed for some reason: var label = this._element.getAttribute("aria-label"); if (label === null || label === "" || label === undefined) { this._element.setAttribute("aria-label", strings.ariaLabel); } } }, { /// /// Gets or sets the ID of the AppBarCommand. /// id: { get: function () { return this._element.id; }, set: function (value) { // we allow setting first time only. otherwise we ignore it. if (value && !this._element.id) { this._element.id = value; } } }, /// /// Gets or sets the type of the AppBarCommand. Possible values are "button", "toggle", "flyout", or "separator". /// type: { get: function () { return this._type; }, set: function (value) { // we allow setting first time only. otherwise we ignore it. if (!this._type) { if (value !== typeContent && value !== typeFlyout && value !== typeToggle && value !== typeSeparator) { this._type = typeButton; } else { this._type = value; } } } }, /// /// Gets or sets the label of the AppBarCommand. /// label: { get: function () { return this._label; }, set: function (value) { this._label = value; if (this._labelSpan) { this._labelSpan.innerText = this.label; } // Ensure that we have a tooltip, by updating already-constructed tooltips. Separators won't have these: if (!this.tooltip && this._tooltipControl) { this._tooltip = this.label; this._tooltipControl.innerHTML = this.label; } // Update aria-label this._element.setAttribute("aria-label", this.label); // Check if we need to suppress the tooltip this._testIdenticalTooltip(); } }, /// /// Gets or sets the icon of the AppBarCommand. /// icon: { get: function () { return this._icon; }, set: function (value) { if (value) { this._icon = (WinJS.UI.AppBarIcon[value] || value); } else { this._icon = value; } if (this._imageSpan) { // If the icon's a single character, presume a glyph if (this._icon && this._icon.length === 1) { // Set the glyph this._imageSpan.innerText = this._icon; this._imageSpan.style.backgroundImage = ""; this._imageSpan.style.msHighContrastAdjust = ""; } else { // Must be an image, set that this._imageSpan.innerText = ""; this._imageSpan.style.backgroundImage = this._icon; this._imageSpan.style.msHighContrastAdjust = "none"; } } } }, /// /// Gets or sets the function to invoke when the command is clicked. /// onclick: { get: function () { return this._onclick; }, set: function (value) { if (value && typeof value !== "function") { throw new WinJS.ErrorFromName("WinJS.UI.AppBarCommand.BadClick", WinJS.Resources._formatString(strings.badClick, "AppBarCommand")); } this._onclick = value; } }, /// /// For flyout-type AppBarCommands, this property returns the WinJS.UI.Flyout that this command invokes. /// When setting this property, you may also use the String ID of the flyout to invoke, the DOM object /// for the flyout, or the WinJS.UI.Flayout object itself. /// flyout: { get: function () { // Resolve it to the flyout var flyout = this._flyout; if (typeof flyout === "string") { flyout = document.getElementById(flyout); } // If it doesn't have a .element, then we need to getControl on it if (flyout && !flyout.element) { flyout = flyout.winControl; } return flyout; }, set: function (value) { // Need to update aria-owns with the new ID. var id = value; if (id && typeof id !== "string") { // Our controls have .element properties if (id.element) { id = id.element; } // Hope it's a DOM element, get ID from DOM element if (id) { if (id.id) { id = id.id; } else { // No id, have to fake one id.id = id.uniqueID; id = id.id; } } } if (typeof id === "string") { this._element.setAttribute("aria-owns", id); } // Remember it this._flyout = value; } }, /// /// Gets or sets the section that the AppBarCommand is in. Possible values are "selection" and "global". /// section: { get: function () { return this._section; }, set: function (value) { // we allow settings section only one time if (!this._section || (window.Windows && Windows.ApplicationModel && Windows.ApplicationModel.DesignMode && Windows.ApplicationModel.DesignMode.designModeEnabled)) { this._setSection(value); } } }, /// Gets or sets the tooltip text of the AppBarCommand. tooltip: { get: function () { return this._tooltip; }, set: function (value) { this._tooltip = value; // Update already-constructed tooltips. Separators and content commands won't have these: if (this._tooltipControl) { this._tooltipControl.innerHTML = this._tooltip; } // Check if we need to suppress the tooltip this._testIdenticalTooltip(); } }, /// Set or get the selected state of a toggle button. selected: { get: function () { // Ensure it's a boolean because we're using the DOM element to keep in-sync return this._element.getAttribute("aria-checked") === "true"; }, set: function (value) { this._element.setAttribute("aria-checked", value); } }, /// element: { get: function () { return this._element; } }, /// /// Gets or sets a value that indicates whether the AppBarCommand is disabled. A value of true disables the AppBarCommand, and a value of false enables it. /// disabled: { get: function () { // Ensure it's a boolean because we're using the DOM element to keep in-sync return !!this._element.disabled; }, set: function (value) { this._element.disabled = value; } }, /// hidden: { get: function () { // Ensure it's a boolean because we're using the DOM element to keep in-sync return this._element.style.visibility === "hidden"; }, set: function (value) { var appbarControl = thisWinUI._Overlay._getParentControlUsingClassName(this._element, "win-appbar"); if (appbarControl && !appbarControl.hidden) { throw new WinJS.ErrorFromName("WinJS.UI.AppBarCommand.CannotChangeHiddenProperty", WinJS.Resources._formatString(thisWinUI._Overlay.commonstrings.cannotChangeHiddenProperty, "AppBar")); } if (value === this.hidden) { // No changes to make. return; } var style = this._element.style; if (value) { style.visibility = "hidden"; style.display = "none"; } else { style.visibility = ""; style.display = "inline-block"; } if (appbarControl) { appbarControl._contentChanged(); } } }, /// /// Gets or sets the HTMLElement within a "content" type AppBarCommand that should receive focus whenever focus moves via Home or the arrow keys, /// from the previous AppBarCommand to the this AppBarCommand. Returns the AppBarCommand object's host element by default. /// firstElementFocus: { get: function () { return this._firstElementFocus || this._lastElementFocus || this._element; }, set: function (element) { // Arguments of null and this.element should treated the same to ensure that this.element is never a tabstop when either focus property has been set. this._firstElementFocus = (element === this.element) ? null : element; this._updateTabStop(); } }, /// /// Gets or sets the HTMLElement within a "content" type AppBarCommand that should receive focus whenever focus would move, via End or arrow keys, /// from the next AppBarCommand to this AppBarCommand. Returns this AppBarCommand object's host element by default. /// lastElementFocus: { get: function () { return this._lastElementFocus || this._firstElementFocus || this._element; }, set: function (element) { // Arguments of null and this.element should treated the same to ensure that this.element is never a tabstop when either focus property has been set. this._lastElementFocus = (element === this.element) ? null : element; this._updateTabStop(); } }, dispose: function () { /// /// /// Disposes this control. /// /// if (this._disposed) { return; } this._disposed = true; if (this._tooltipControl) { this._tooltipControl.dispose(); } if (this._type === typeContent) { WinJS.Utilities.disposeSubTree(this.element); } }, addEventListener: function (type, listener, useCapture) { /// /// /// Registers an event handler for the specified event. /// /// /// Required. The name of the event to register. It must be "beforeshow", "beforehide", "aftershow", or "afterhide". /// /// Required. The event handler function to associate with this event. /// /// Optional. Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. /// /// return this._element.addEventListener(type, listener, useCapture); }, removeEventListener: function (type, listener, useCapture) { /// /// /// Removes an event handler that the addEventListener method registered. /// /// Required. The name of the event to remove. /// Required. The event handler function to remove. /// /// Optional. Set to true to remove the capturing phase event handler; otherwise, set to false to remove the bubbling phase event handler. /// /// return this._element.removeEventListener(type, listener, useCapture); }, /// Adds an extra CSS class during construction. extraClass: { get: function () { return this._extraClass; }, set: function (value) { if (this._extraClass) { WinJS.Utilities.removeClass(this._element, this._extraClass); } this._extraClass = value; WinJS.Utilities.addClass(this._element, this._extraClass); } }, // Private _testIdenticalTooltip: function AppBarCommand_testIdenticalToolTip() { this._hideIfFullSize = (this._label === this._tooltip); }, _createContent: function AppBarCommand_createContent() { // Make sure there's an element if (!this._element) { this._element = document.createElement("div"); } else { // Verify the element was a div if (this._element.tagName !== "DIV") { throw new WinJS.ErrorFromName("WinJS.UI.AppBarCommand.BadDivElement", strings.badDivElement); } } // If a tabIndex isnt set, default to 0; if (parseInt(this._element.getAttribute("tabIndex"), 10) !== this._element.tabIndex) { this._element.tabIndex = 0; } }, _createSeparator: function AppBarCommand_createSeparator() { // Make sure there's an element if (!this._element) { this._element = document.createElement("hr"); } else { // Verify the element was an hr if (this._element.tagName !== "HR") { throw new WinJS.ErrorFromName("WinJS.UI.AppBarCommand.BadHrElement", strings.badHrElement); } } }, _createButton: function AppBarCommand_createButton() { // Make sure there's an element if (!this._element) { this._element = document.createElement("button"); } else { // Verify the element was a button if (this._element.tagName !== "BUTTON") { throw new WinJS.ErrorFromName("WinJS.UI.AppBarCommand.BadButtonElement", strings.badButtonElement); } // Make sure it has a type="button" var type = this._element.getAttribute("type"); if (type === null || type === "" || type === undefined) { this._element.setAttribute("type", "button"); } this._element.innerHTML = ""; } // AppBarCommand buttons need to look like this: //// this._element.type = "button"; this._iconSpan = document.createElement("span"); this._iconSpan.setAttribute("aria-hidden", "true"); this._iconSpan.className = "win-commandicon win-commandring"; this._iconSpan.tabIndex = -1; this._element.appendChild(this._iconSpan); this._imageSpan = document.createElement("span"); this._imageSpan.setAttribute("aria-hidden", "true"); this._imageSpan.className = "win-commandimage"; this._imageSpan.tabIndex = -1; this._iconSpan.appendChild(this._imageSpan); this._labelSpan = document.createElement("span"); this._labelSpan.setAttribute("aria-hidden", "true"); this._labelSpan.className = "win-label"; this._labelSpan.tabIndex = -1; this._element.appendChild(this._labelSpan); // 'win-global' or 'win-selection' are added later by caller. // Label and icon are added later by caller. // Attach a tooltip - Note: we're going to stomp on it's setControl so we don't have to make another DOM element to hang it off of. // This private _tooltipControl attribute is used by other pieces, changing the name could break them. this._tooltipControl = new WinJS.UI.Tooltip(this._element); var that = this; this._tooltipControl.addEventListener("beforeopen", function () { if (that._hideIfFullSize && !thisWinUI._Overlay._getParentControlUsingClassName(that._element.parentElement, reducedClass)) { that._tooltipControl.close(); } }, false); }, _setSection: function AppBarCommand_setSection(section) { if (!section) { section = sectionGlobal; } if (this._section) { // Remove the old section class if (this._section === sectionGlobal) { WinJS.Utilities.removeClass(this._element, appBarCommandGlobalClass); } else if (this.section === sectionSelection) { WinJS.Utilities.removeClass(this._element, appBarCommandSelectionClass); } } // Add the new section class this._section = section; if (section === sectionGlobal) { WinJS.Utilities.addClass(this._element, appBarCommandGlobalClass); } else if (section === sectionSelection) { WinJS.Utilities.addClass(this._element, appBarCommandSelectionClass); } }, _updateTabStop: function AppBarCommand_updateTabStop() { // Whenever the firstElementFocus or lastElementFocus properties are set for content type AppBarCommands, // the containing command element is no longer a tabstop. if (this._firstElementFocus || this._lastElementFocus ) { this.element.tabIndex = -1; } else { this.element.tabIndex = 0; } }, _isFocusable: function AppBarCommand_isFocusable() { return (!this.hidden && this._type !== typeSeparator && !this.element.disabled && (this.firstElementFocus.tabIndex >= 0 || this.lastElementFocus.tabIndex >= 0)) }, }); }) }); })(WinJS); // AppBar /// appbar,appBars,Flyout,Flyouts,iframe,Statics,unfocus,WinJS (function appBarInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Represents an application toolbar for display commands. /// /// /// /// /// /// ]]> /// Raised just before showing the AppBar. /// Raised immediately after the AppBar is fully shown. /// Raised just before hiding the AppBar. /// Raised immediately after the AppBar is fully hidden. /// The AppBar control itself. /// Style for a custom layout AppBar. /// /// /// AppBar: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; // Class Names var commandClass = "win-commandlayout", appBarClass = "win-appbar", reducedClass = "win-reduced", settingsFlyoutClass = "win-settingsflyout", topClass = "win-top", bottomClass = "win-bottom", appBarCommandClass = "win-command"; var firstDivClass = "win-firstdiv", finalDivClass = "win-finaldiv"; // Constants for placement var appBarPlacementTop = "top", appBarPlacementBottom = "bottom"; // Constants for layout var appBarLayoutCustom = "custom", appBarLayoutCommands = "commands"; // Constants for AppBarCommands var typeSeparator = "separator", typeContent = "content", separatorWidth = 60, buttonWidth = 100; // Hook into event var appBarCommandEvent = false; var edgyHappening = null; // Handler for the edgy starting/completed/cancelled events function _completedEdgy(e) { // If we had a right click on a flyout, ignore it. if (thisWinUI._Overlay._rightMouseMightEdgy && e.kind === Windows.UI.Input.EdgeGestureKind.mouse) { return; } if (edgyHappening) { // Edgy was happening, just skip it edgyHappening = null; } else { // Edgy wasn't happening, so toggle var keyboardInvoked = e.kind === Windows.UI.Input.EdgeGestureKind.keyboard; WinJS.UI.AppBar._toggleAppBarEdgy(keyboardInvoked); } } function _startingEdgy() { if (!edgyHappening) { // Edgy wasn't happening, so toggle & start it edgyHappening = WinJS.UI.AppBar._toggleAppBarEdgy(false); } } function _canceledEdgy() { // Shouldn't get here unless edgy was happening. // Undo whatever we were doing. var bars = _getDynamicBarsForEdgy(); if (edgyHappening === "showing") { _hideAllBars(bars, false); } else if (edgyHappening === "hiding") { _showAllBars(bars, false); } edgyHappening = null; } function _allManipulationChanged(event) { var elements = document.querySelectorAll("." + appBarClass); if (elements) { var len = elements.length; for (var i = 0; i < len; i++) { var element = elements[i]; var appbar = element.winControl; if (appbar && !element.disabled) { appbar._manipulationChanged(event); } } } } // Get all the non-sticky bars and return them. // Returns array of AppBar objects. // The array also has _hidden and/or _visible set if ANY are hidden or visible. function _getDynamicBarsForEdgy() { var elements = document.querySelectorAll("." + appBarClass); var len = elements.length; var AppBars = []; AppBars._visible = false; AppBars._hidden = false; for (var i = 0; i < len; i++) { var element = elements[i]; if (element.disabled) { // Skip disabled AppBars continue; } var AppBar = element.winControl; if (AppBar) { AppBars.push(AppBar); // Middle of animation is different than animated if (AppBar._element.winAnimating) { // If animating, look at showing/hiding if (AppBar._element.winAnimating === "hiding") { AppBars._hidden = true; } else { AppBars._visible = true; } } else { // Not animating, so check visibility if (AppBar._element.style.visibility === "hidden") { AppBars._hidden = true; } else { AppBars._visible = true; } } } } return AppBars; } // Show or hide all bars function _hideAllBars(bars, keyboardInvoked) { var len = bars.length; var allBarsAnimationPromises = new Array(len); for (var i = 0; i < len; i++) { bars[i]._keyboardInvoked = keyboardInvoked; bars[i].hide(); allBarsAnimationPromises[i] = bars[i]._animationPromise; } return WinJS.Promise.join(allBarsAnimationPromises); } function _showAllBars(bars, keyboardInvoked) { var len = bars.length; var allBarsAnimationPromises = new Array(len); for (var i = 0; i < len; i++) { bars[i]._keyboardInvoked = keyboardInvoked; bars[i]._doNotFocus = false; bars[i]._show(); allBarsAnimationPromises[i] = bars[i]._animationPromise; } return WinJS.Promise.join(allBarsAnimationPromises); } // Sets focus to the last AppBar in the provided appBars array with given placement. // Returns true if focus was set. False otherwise. function _setFocusToPreviousAppBarHelper(startIndex, appBarPlacement, appBars) { for (var i = startIndex; i >= 0; i--) { if (appBars[i].winControl && appBars[i].winControl.placement === appBarPlacement && !appBars[i].winControl.hidden && appBars[i].winControl._focusOnLastFocusableElement && appBars[i].winControl._focusOnLastFocusableElement()) { return true; } } return false; } // Sets focus to the last AppBar in the provided appBars array with other placement. // Returns true if focus was set. False otherwise. function _setFocusToPreviousAppBarHelperNeither(startIndex, appBars) { for (var i = startIndex; i >= 0; i--) { if (appBars[i].winControl && appBars[i].winControl.placement != appBarPlacementBottom && appBars[i].winControl.placement != appBarPlacementTop && !appBars[i].winControl.hidden && appBars[i].winControl._focusOnLastFocusableElement && appBars[i].winControl._focusOnLastFocusableElement()) { return true; } } return false; } // Sets focus to the last tab stop of the previous AppBar // AppBar tabbing order: // 1) Bottom AppBars // 2) Top AppBars // 3) Other AppBars // DOM order is respected, because an AppBar should not have a defined tabIndex function _setFocusToPreviousAppBar() { var appBars = document.querySelectorAll("." + appBarClass); if (!appBars.length) { return; } var thisAppBarIndex = 0; for (var i = 0; i < appBars.length; i++) { if (appBars[i] === this.parentElement) { thisAppBarIndex = i; break; } } var appBarControl = this.parentElement.winControl; if (appBarControl.placement === appBarPlacementBottom) { // Bottom appBar: Focus order: (1)previous bottom appBars (2)other appBars (3)top appBars (4)bottom appBars if (thisAppBarIndex && _setFocusToPreviousAppBarHelper(thisAppBarIndex - 1, appBarPlacementBottom, appBars)) { return; } if (_setFocusToPreviousAppBarHelperNeither(appBars.length - 1, appBars)) { return; } if (_setFocusToPreviousAppBarHelper(appBars.length - 1, appBarPlacementTop, appBars)) { return; } if (_setFocusToPreviousAppBarHelper(appBars.length - 1, appBarPlacementBottom, appBars)) { return; } } else if (appBarControl.placement === appBarPlacementTop) { // Top appBar: Focus order: (1)previous top appBars (2)bottom appBars (3)other appBars (4)top appBars if (thisAppBarIndex && _setFocusToPreviousAppBarHelper(thisAppBarIndex - 1, appBarPlacementTop, appBars)) { return; } if (_setFocusToPreviousAppBarHelper(appBars.length - 1, appBarPlacementBottom, appBars)) { return; } if (_setFocusToPreviousAppBarHelperNeither(appBars.length - 1, appBars)) { return; } if (_setFocusToPreviousAppBarHelper(appBars.length - 1, appBarPlacementTop, appBars)) { return; } } else { // Other appBar: Focus order: (1)previous other appBars (2)top appBars (3)bottom appBars (4)other appBars if (thisAppBarIndex && _setFocusToPreviousAppBarHelperNeither(thisAppBarIndex - 1, appBars)) { return; } if (_setFocusToPreviousAppBarHelper(appBars.length - 1, appBarPlacementTop, appBars)) { return; } if (_setFocusToPreviousAppBarHelper(appBars.length - 1, appBarPlacementBottom, appBars)) { return; } if (_setFocusToPreviousAppBarHelperNeither(appBars.length - 1, appBars)) { return; } } } // Sets focus to the first AppBar in the provided appBars array with given placement. // Returns true if focus was set. False otherwise. function _setFocusToNextAppBarHelper(startIndex, appBarPlacement, appBars) { for (var i = startIndex; i < appBars.length; i++) { if (appBars[i].winControl && appBars[i].winControl.placement === appBarPlacement && !appBars[i].winControl.hidden && appBars[i].winControl._focusOnFirstFocusableElement && appBars[i].winControl._focusOnFirstFocusableElement()) { return true; } } return false; } // Sets focus to the first AppBar in the provided appBars array with other placement. // Returns true if focus was set. False otherwise. function _setFocusToNextAppBarHelperNeither(startIndex, appBars) { for (var i = startIndex; i < appBars.length; i++) { if (appBars[i].winControl && appBars[i].winControl.placement != appBarPlacementBottom && appBars[i].winControl.placement != appBarPlacementTop && !appBars[i].winControl.hidden && appBars[i].winControl._focusOnFirstFocusableElement && appBars[i].winControl._focusOnFirstFocusableElement()) { return true; } } return false; } // Sets focus to the first tab stop of the next AppBar // AppBar tabbing order: // 1) Bottom AppBars // 2) Top AppBars // 3) Other AppBars // DOM order is respected, because an AppBar should not have a defined tabIndex function _setFocusToNextAppBar() { var appBars = document.querySelectorAll("." + appBarClass); var thisAppBarIndex = 0; for (var i = 0; i < appBars.length; i++) { if (appBars[i] === this.parentElement) { thisAppBarIndex = i; break; } } var appBarControl = this.parentElement.winControl; if (this.parentElement.winControl.placement === appBarPlacementBottom) { // Bottom appBar: Focus order: (1)next bottom appBars (2)top appBars (3)other appBars (4)bottom appBars if (_setFocusToNextAppBarHelper(thisAppBarIndex + 1, appBarPlacementBottom, appBars)) { return; } if (_setFocusToNextAppBarHelper(0, appBarPlacementTop, appBars)) { return; } if (_setFocusToNextAppBarHelperNeither(0, appBars)) { return; } if (_setFocusToNextAppBarHelper(0, appBarPlacementBottom, appBars)) { return; } } else if (this.parentElement.winControl.placement === appBarPlacementTop) { // Top appBar: Focus order: (1)next top appBars (2)other appBars (3)bottom appBars (4)top appBars if (_setFocusToNextAppBarHelper(thisAppBarIndex + 1, appBarPlacementTop, appBars)) { return; } if (_setFocusToNextAppBarHelperNeither(0, appBars)) { return; } if (_setFocusToNextAppBarHelper(0, appBarPlacementBottom, appBars)) { return; } if (_setFocusToNextAppBarHelper(0, appBarPlacementTop, appBars)) { return; } } else { // Other appBar: Focus order: (1)next other appBars (2)bottom appBars (3)top appBars (4)other appBars if (_setFocusToNextAppBarHelperNeither(thisAppBarIndex + 1, appBars)) { return; } if (_setFocusToNextAppBarHelper(0, appBarPlacementBottom, appBars)) { return; } if (_setFocusToNextAppBarHelper(0, appBarPlacementTop, appBars)) { return; } if (_setFocusToNextAppBarHelperNeither(0, appBars)) { return; } } } // Updates the firstDiv & finalDiv of all visible AppBars function _updateAllAppBarsFirstAndFinalDiv() { var appBars = document.querySelectorAll("." + appBarClass); for (var i = 0; i < appBars.length; i++) { if (appBars[i].winControl && !appBars[i].winControl.hidden && appBars[i].winControl._updateFirstAndFinalDiv) { appBars[i].winControl._updateFirstAndFinalDiv(); } } } // Returns true if a visible non-sticky (light dismiss) AppBar is found in the document function _isThereVisibleNonStickyBar() { var appBars = document.querySelectorAll("." + appBarClass); for (var i = 0; i < appBars.length; i++) { var appBarControl = appBars[i].winControl; if (appBarControl && !appBarControl.sticky && (!appBarControl.hidden || appBarControl._element.winAnimating === "showing")) { return true; } } return false; } // Hide all light dismiss AppBars if what has focus is not part of a AppBar or flyout. function _hideIfAllAppBarsLostFocus() { if (!thisWinUI.AppBar._isAppBarOrChild(document.activeElement)) { thisWinUI.AppBar._hideLightDismissAppBars(null, false); // Ensure that sticky appbars clear cached focus after light dismiss are dismissed, which moved focus. thisWinUI.AppBar._ElementWithFocusPreviousToAppBar = null; } } // If the previous focus was not a AppBar or CED, store it in the cache // (_isAppBarOrChild tests CED for us). function _checkStorePreviousFocus(focusEvent) { if (focusEvent.relatedTarget && focusEvent.relatedTarget.focus && !thisWinUI.AppBar._isAppBarOrChild(focusEvent.relatedTarget)) { _storePreviousFocus(focusEvent.relatedTarget); } } // Cache the previous focus information function _storePreviousFocus(element) { if (element) { thisWinUI.AppBar._ElementWithFocusPreviousToAppBar = element; } } // Try to return focus to what had focus before. // If successfully return focus to a textbox, restore the selection too. function _restorePreviousFocus() { thisWinUI._Overlay._trySetActive(thisWinUI.AppBar._ElementWithFocusPreviousToAppBar); } var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/appBarAriaLabel").value; }, get requiresCommands() { return WinJS.Resources._getWinJSString("ui/requiresCommands").value; }, get nullCommand() { return WinJS.Resources._getWinJSString("ui/nullCommand").value; }, get cannotChangePlacementWhenVisible() { return WinJS.Resources._getWinJSString("ui/cannotChangePlacementWhenVisible").value; }, get badLayout() { return WinJS.Resources._getWinJSString("ui/badLayout").value; }, get cannotChangeLayoutWhenVisible() { return WinJS.Resources._getWinJSString("ui/cannotChangeLayoutWhenVisible").value; } }; var AppBar = WinJS.Class.derive(WinJS.UI._Overlay, function AppBar_ctor(element, options) { /// /// /// Creates a new AppBar control. /// /// /// The DOM element that will host the control. /// /// /// The set of properties and values to apply to the new AppBar control. /// /// /// The new AppBar control. /// /// this._initializing = true; // Simplify checking later options = options || {}; // Make sure there's an input element this._element = element || document.createElement("div"); this._id = this._element.id || this._element.uniqueID; this._writeProfilerMark("constructor,StartTM"); // validate that if they didn't set commands, but want command // layout that the HTML only contains commands. Do this first // so that we don't leave partial AppBars in the DOM. if (options.layout !== appBarLayoutCustom && !options.commands && this._element) { // Shallow copy object so we can modify it. options = WinJS.Utilities._shallowCopy(options); options.commands = this._verifyCommandsOnly(this._element, "WinJS.UI.AppBarCommand"); } // Call the base overlay constructor helper this._baseOverlayConstructor(this._element, options); this._initializing = false; // Make a click eating div thisWinUI._Overlay._createClickEatingDivAppBar(); // Attach our css class, WinJS.Utilities.addClass(this._element, appBarClass); // Also may need a command class if not a custom layout appbar if (options.layout !== appBarLayoutCustom) { WinJS.Utilities.addClass(this._element, commandClass); } if (!options.placement) { // Make sure we have default placement this.placement = appBarPlacementBottom; } // Make sure we have an ARIA role var role = this._element.getAttribute("role"); if (!role) { this._element.setAttribute("role", "menubar"); } var label = this._element.getAttribute("aria-label"); if (!label) { this._element.setAttribute("aria-label", strings.ariaLabel); } // Handle key down (esc) and key pressed (left & right) this._element.addEventListener("keydown", this._handleKeyDown.bind(this), false); // Attach event handler if (!appBarCommandEvent) { // We'll trigger on invoking. Could also have invoked or canceled // Eventually we may want click up on invoking and drop back on invoked. // Check for namespace so it'll behave in the designer. if (WinJS.Utilities.hasWinRT) { var commandUI = Windows.UI.Input.EdgeGesture.getForCurrentView(); commandUI.addEventListener("starting", _startingEdgy); commandUI.addEventListener("completed", _completedEdgy); commandUI.addEventListener("canceled", _canceledEdgy); } // Need to know if the IHM is done scrolling document.addEventListener("MSManipulationStateChanged", _allManipulationChanged, false); appBarCommandEvent = true; } // Make sure _Overlay event handlers are hooked up (this aids light dismiss) this._addOverlayEventHandlers(false); // Need to store what had focus before this._element.addEventListener("focusin", function (event) { _checkStorePreviousFocus(event); }, false); // Need to hide ourselves if we lose focus this._element.addEventListener("focusout", function (event) { _hideIfAllAppBarsLostFocus(); }, false); // Commands layout AppBar measures and caches its content synchronously in setOptions through the .commands property setter. // Remove the commands layout AppBar from the layout tree at this point so we don't cause unnecessary layout costs whenever // the window resizes or when CSS changes are applied to the commands layout AppBar's parent element. if (this.layout === appBarLayoutCommands) { this._element.style.display = "none"; } this._writeProfilerMark("constructor,StopTM"); return this; }, { // Public Properties /// The placement of the AppBar on the display. Values are "top" or "bottom". placement: { get: function () { return this._placement; }, set: function (value) { // In designer we may have to move it var wasShown = false; if (window.Windows && Windows.ApplicationModel && Windows.ApplicationModel.DesignMode && Windows.ApplicationModel.DesignMode.designModeEnabled && !this.hidden) { this._hide(); wasShown = true; } if (!this.hidden) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.CannotChangePlacementWhenVisible", strings.cannotChangePlacementWhenVisible); } // Set placement this._placement = value; // Clean up win-top, win-bottom styles if (this._placement === appBarPlacementTop) { WinJS.Utilities.addClass(this._element, topClass); WinJS.Utilities.removeClass(this._element, bottomClass); } else if (this._placement === appBarPlacementBottom) { WinJS.Utilities.removeClass(this._element, topClass); WinJS.Utilities.addClass(this._element, bottomClass); } else { WinJS.Utilities.removeClass(this._element, topClass); WinJS.Utilities.removeClass(this._element, bottomClass); } // Make sure our animations are correct this._assignAnimations(); // Show again if we hid ourselves for the designer if (wasShown) { this._show(); } } }, /// /// Gets or sets the layout of the AppBar contents to either "commands" or "custom". /// layout: { get: function () { // Defaults to commands if not set return this._layout ? this._layout : appBarLayoutCommands; }, set: function (value) { if (value !== appBarLayoutCommands && value !== appBarLayoutCustom) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.BadLayout", strings.badLayout); } // In designer we may have to redraw it var wasShown = false; if (window.Windows && Windows.ApplicationModel && Windows.ApplicationModel.DesignMode && Windows.ApplicationModel.DesignMode.designModeEnabled && !this.hidden) { this._hide(); wasShown = true; } if (!this.hidden) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.CannotChangeLayoutWhenVisible", strings.cannotChangeLayoutWhenVisible); } // Set layout this._layout = value; // Update our classes if (this._layout === appBarLayoutCommands) { // Add the appbar css class back WinJS.Utilities.addClass(this._element, commandClass); } else { // Remove the appbar css class WinJS.Utilities.removeClass(this._element, commandClass); } // Show again if we hid ourselves for the designer if (wasShown) { this._show(); } }, configurable: true }, /// /// Gets or sets value that indicates whether the AppBar is sticky. /// This value is true if the AppBar is sticky; otherwise, it's false. /// sticky: { get: function () { return this._sticky; }, set: function (value) { // If it doesn't change, do nothing if (this._sticky === !!value) { return; } this._sticky = !!value; // Note: caller has to call .show() if they also want it visible // Show or hide the click eating div based on sticky value if (!this.hidden && this._element.style.visibility === "visible") { // May have changed sticky state for keyboard navigation _updateAllAppBarsFirstAndFinalDiv(); // Ensure that the click eating div is in the correct state if (this._sticky) { if (!_isThereVisibleNonStickyBar()) { thisWinUI._Overlay._hideClickEatingDivAppBar(); } } else { thisWinUI._Overlay._showClickEatingDivAppBar(); if (this._shouldStealFocus()) { _storePreviousFocus(document.activeElement); this._setFocusToAppBar(); } } } } }, /// /// Sets the commands for the AppBar. This property accepts an array of AppBarCommand objects. /// commands: { set: function (value) { // Fail if trying to set when visible if (!this.hidden) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.CannotChangeCommandsWhenVisible", WinJS.Resources._formatString(thisWinUI._Overlay.commonstrings.cannotChangeCommandsWhenVisible, "AppBar")); } // Start from scratch if (!this._initializing) { // AppBarCommands defined in markup don't want to be disposed during initialization. this._disposeChildren(); } WinJS.Utilities.empty(this._element); // In case they had only one... if (!Array.isArray(value)) { value = [value]; } // Add commands var len = value.length; for (var i = 0; i < len; i++) { this._addCommand(value[i]); } // Need to measure all content commands after they have been added to the AppBar to make sure we allow // user defined CSS rules based on the ancestor of the content command to take affect. this._needToMeasure = true; // In case this is called from the constructor we wait for the AppBar to get added to the DOM. // It should be added in the synchronous block in which the constructor was called. WinJS.Utilities.Scheduler.schedule(this._layoutCommands, WinJS.Utilities.Scheduler.Priority.idle, this, "WinJS.AppBar._layoutCommands"); } }, getCommandById: function (id) { /// /// /// Retrieves the command with the specified ID from this AppBar. /// If more than one command is found, this method returns them all. /// /// Id of the command to return. /// /// The command found, an array of commands if more than one have the same ID, or null if no command is found. /// /// var commands = this.element.querySelectorAll("#" + id); for (var count = 0; count < commands.length; count++) { // Any elements we generated this should succeed for, // but remove missing ones just to be safe. commands[count] = commands[count].winControl; if (!commands[count]) { commands.splice(count, 1); } } if (commands.length === 1) { return commands[0]; } else if (commands.length === 0) { return null; } return commands; }, showCommands: function (commands) { /// /// /// Show the specified commands of the AppBar. /// /// /// An array of the commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. /// /// if (!commands) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.RequiresCommands", strings.requiresCommands); } this._showCommands(commands); }, hideCommands: function (commands) { /// /// /// Hides the specified commands of the AppBar. /// /// Required. Command or Commands to hide, either String, DOM elements, or WinJS objects. /// if (!commands) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.RequiresCommands", strings.requiresCommands); } this._hideCommands(commands); }, showOnlyCommands: function (commands) { /// /// /// Show the specified commands, hiding all of the others in the AppBar. /// /// /// An array of the commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. /// /// if (!commands) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.RequiresCommands", strings.requiresCommands); } this._showOnlyCommands(commands); }, show: function () { /// /// /// Shows the AppBar, if hidden, regardless of other state /// /// // Just wrap the private one, turning off keyboard invoked flag this._writeProfilerMark("show,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndShow(). this._keyboardInvoked = false; this._doNotFocus = !!this.sticky; this._show(); }, _show: function AppBar_show() { // Don't do anything if disabled if (this.disabled) { return; } // Make sure everything fits before showing this._layoutCommands(); this._scaleAppBar(); // If we're covered by a keyboard we look hidden, so we may have to jump up if (this._keyboardObscured) { // just make us look hidden so that show() gets called. this._fakeHide = true; this._keyboardObscured = false; } // Regardless we're going to be in a CED state if (!this.sticky) { // Need click-eating div to be visible ASAP. thisWinUI._Overlay._showClickEatingDivAppBar(); } // If we are already animating, just remember this for later if (this._element.winAnimating) { this._doNext = "show"; return false; } // We call our base _baseShow because AppBar may need to override show // "hiding" would need to cancel. this._baseShow(); // Clean up tabbing behavior by making sure first and final divs are correct after showing. if (!this.sticky && _isThereVisibleNonStickyBar()) { _updateAllAppBarsFirstAndFinalDiv(); } else { this._updateFirstAndFinalDiv(); } // Check if we should steal focus if (!this._doNotFocus && this._shouldStealFocus()) { // Store what had focus if nothing currently is stored if (!thisWinUI.AppBar._ElementWithFocusPreviousToAppBar) { _storePreviousFocus(document.activeElement); } this._setFocusToAppBar(); } }, hide: function () { /// /// /// Hides the AppBar. /// /// // Just wrap the private one this._writeProfilerMark("hide,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndHide(). this._hide(); }, _hide: function AppBar_hide() { // If we're covered by a keyboard we already look hidden if (this._keyboardObscured && !this._animating) { this._keyboardObscured = false; this._baseEndHide(); } else { // We call our base "_baseHide" because AppBar may need to override hide this._baseHide(); } // Determine if there are any AppBars that are visible. // Set the focus to the next visible AppBar. // If there are none, set the focus to the control stored in the cache, which // is what had focus before the AppBars were given focus. var appBars = document.querySelectorAll("." + appBarClass); var areOtherAppBars = false; var areOtherNonStickyAppBars = false; var i; for (i = 0; i < appBars.length; i++) { var appBarControl = appBars[i].winControl; if (appBarControl && !appBarControl.hidden && (appBarControl !== this)) { areOtherAppBars = true; if (!appBarControl.sticky) { areOtherNonStickyAppBars = true; break; } } } var settingsFlyouts = document.querySelectorAll("." + settingsFlyoutClass); var areVisibleSettingsFlyouts = false; for (i = 0; i < settingsFlyouts.length; i++) { var settingsFlyoutControl = settingsFlyouts[i].winControl; if (settingsFlyoutControl && !settingsFlyoutControl.hidden) { areVisibleSettingsFlyouts = true; break; } } if (!areOtherNonStickyAppBars && !areVisibleSettingsFlyouts) { // Hide the click eating div because there are no other AppBars showing thisWinUI._Overlay._hideClickEatingDivAppBar(); } var that = this; if (!areOtherAppBars) { // Set focus to what had focus before showing the AppBar if (thisWinUI.AppBar._ElementWithFocusPreviousToAppBar && (!document.activeElement || thisWinUI.AppBar._isAppBarOrChild(document.activeElement))) { _restorePreviousFocus(); } // Always clear the previous focus (to prevent temporary leaking of element) thisWinUI.AppBar._ElementWithFocusPreviousToAppBar = null; } else if (thisWinUI.AppBar._isWithinAppBarOrChild(document.activeElement, that.element)) { // Set focus to next visible AppBar in DOM var foundCurrentAppBar = false; for (i = 0; i <= appBars.length; i++) { if (i === appBars.length) { i = 0; } var appBar = appBars[i]; if (appBar === this.element) { foundCurrentAppBar = true; } else if (foundCurrentAppBar && !appBar.winControl.hidden) { appBar.winControl._keyboardInvoked = !!this._keyboardInvoked; appBar.winControl._setFocusToAppBar(); break; } } } // If we are hiding the last lightDismiss AppBar, // then we need to update the tabStops of the other AppBars if (!this.sticky && !_isThereVisibleNonStickyBar()) { _updateAllAppBarsFirstAndFinalDiv(); } // Reset these values this._keyboardInvoked = false; this._doNotFocus = false; }, _dispose: function AppBar_dispose() { WinJS.Utilities.disposeSubTree(this.element); this._hide(); }, _disposeChildren: function AppBar_disposeChildren() { var appBarFirstDiv = this._element.querySelectorAll("." + firstDivClass); appBarFirstDiv = appBarFirstDiv.length >= 1 ? appBarFirstDiv[0] : null; var appBarFinalDiv = this._element.querySelectorAll("." + finalDivClass); appBarFinalDiv = appBarFinalDiv.length >= 1 ? appBarFinalDiv[0] : null; var children = this.element.children; var length = children.length; for (var i = 0; i < length; i++) { var element = children[i]; if (element === appBarFirstDiv || element === appBarFinalDiv) { continue; } if (this.layout === appBarLayoutCommands) { element.winControl.dispose(); } else { WinJS.Utilities.disposeSubTree(element); } } }, _handleKeyDown: function AppBar_handleKeyDown(event) { // On Left/Right arrow keys, moves focus to previous/next AppbarCommand element. // On "Esc" key press hide all flyouts and light dismiss AppBars. // Esc closes light-dismiss AppBars in all layouts but if the user has a text box with an IME // candidate window open, we want to skip the ESC key event since it is handled by the IME. // When the IME handles a key it sets event.keyCode to 229 for an easy check. if (event.key === "Esc" && event.keyCode !== 229) { event.preventDefault(); event.stopPropagation(); thisWinUI._Overlay._hideAllFlyouts(); thisWinUI.AppBar._hideLightDismissAppBars(null, true); } // Commands layout only. if (this.layout === appBarLayoutCommands && !event.altKey) { if (event.srcElement.msMatchesSelector(".win-interactive, .win-interactive *")) { return; //ignore left, right, home & end keys if focused element has win-interactive class. } var rtl = getComputedStyle(this._element).direction === "rtl"; var leftKey = rtl ? "Right" : "Left"; var rightKey = rtl ? "Left" : "Right"; if (event.key === leftKey || event.key == rightKey || event.key === "Home" || event.key === "End") { var focusableCommands = this._getFocusableCommandsInLogicalOrder(); var targetCommand; if (focusableCommands.length) { switch (event.key) { case leftKey: // Arrowing past the last command wraps back around to the first command. var index = Math.max(-1, focusableCommands.focusedIndex - 1) + focusableCommands.length; targetCommand = focusableCommands[index % focusableCommands.length].winControl.lastElementFocus; break; case rightKey: // Arrowing previous to the first command wraps back around to the last command. var index = focusableCommands.focusedIndex + 1 + focusableCommands.length; targetCommand = focusableCommands[index % focusableCommands.length].winControl.firstElementFocus; break; case "Home": var index = 0; targetCommand = focusableCommands[index].winControl.firstElementFocus; break; case "End": var index = focusableCommands.length - 1; targetCommand = focusableCommands[index].winControl.lastElementFocus; break; } } if (targetCommand) { targetCommand.focus(); // Prevent default so that Trident doesn't resolve the keydown event on the newly focused element. event.preventDefault(); } } } }, _getFocusableCommandsInLogicalOrder: function AppBar_getCommandsInLogicalOrder() { // Function returns an array of all the contained AppBarCommands which are reachable by left/right arrows. // if (this.layout === appBarLayoutCommands) { var selectionCommands = [], globalCommands = [], children = this._element.children, globalCommandHasFocus = false, focusedIndex = -1; var categorizeCommand = function (element, isGlobalCommand, containsFocus) { // Helper function to categorize the element by AppBarCommand's section property. The passed in element could be the // AppBarCommand, or the element referenced by a content AppBarCommands's firstElementFocus/lastElementFocus property. // if (isGlobalCommand) { globalCommands.push(element); if (containsFocus) { focusedIndex = globalCommands.length - 1; globalCommandHasFocus = true; } } else { selectionCommands.push(element); if (containsFocus) { focusedIndex = selectionCommands.length - 1; } } } // Separate commands into global and selection arrays. Find the current command with focus. // Skip the first and last indices to avoid "firstDiv" and "finalDiv". for (var i = 1, len = children.length; i < len - 1; i++) { var element = children[i]; if (element && element.winControl) { var containsFocus = element.contains(document.activeElement); // With the inclusion of content type commands, it may be possible to tab to elements in AppBarCommands that are not reachable by arrow keys. // Regardless, when an AppBarCommand contains the element with focus, we just include the whole command so that we can determine which // Commands are adjacent to it when looking for the next focus destination. if (element.winControl._isFocusable() || containsFocus) { var isGlobalCommand = (element.winControl.section === "global"); categorizeCommand(element, isGlobalCommand, containsFocus); } } } var focusableCommands = selectionCommands.concat(globalCommands); focusableCommands.focusedIndex = globalCommandHasFocus ? focusedIndex + selectionCommands.length : focusedIndex; return focusableCommands; } }, _assignAnimations: function AppBar_assignAnimations() { // Make sure the animations are correct for our current placement if (this._placement === appBarPlacementTop || this._placement === appBarPlacementBottom) { // Top or Bottom this._currentAnimateIn = this._animateSlideIn; this._currentAnimateOut = this._animateSlideOut; } else { // Default for in the middle of nowhere this._currentAnimateIn = this._baseAnimateIn; this._currentAnimateOut = this._baseAnimateOut; } }, // AppBar animations _animateSlideIn: function AppBar_animateSlideIn() { var where, height = this._element.offsetHeight; // Get top/bottoms this._checkPosition(); // Get animation direction and clear other value if (this._placement === appBarPlacementTop) { // Top Bar where = { top: "-" + height + "px", left: "0px" }; this._element.style.bottom = "auto"; } else { // Bottom Bar where = { top: height + "px", left: "0px" }; this._element.style.top = "auto"; } this._element.style.opacity = 1; this._element.style.visibility = "visible"; return WinJS.UI.Animation.showEdgeUI(this._element, where, { mechanism: "transition" }); }, _animateSlideOut: function AppBar_animateSlideOut() { var where, height = this._element.offsetHeight; if (this._placement === appBarPlacementTop) { // Top Bar where = { top: "-" + height + "px", left: "0px" }; // Adjust for scrolling or soft keyboard positioning this._element.style.top = (this._getTopOfVisualViewport()) + "px"; } else { // Bottom Bar where = { top: height + "px", left: "0px" }; // Adjust for scrolling or soft keyboard positioning this._element.style.bottom = (this._getAdjustedBottom()) + "px"; } return WinJS.UI.Animation.hideEdgeUI(this._element, where, { mechanism: "transition" }); }, _isABottomAppBarInTheProcessOfShowing: function AppBar_isABottomAppBarInTheProcessOfShowing() { var appbars = document.querySelectorAll("." + appBarClass + "." + bottomClass); for (var i = 0; i < appbars.length; i++) { if (appbars[i].winAnimating === "showing") { return true; } } return false; }, // Returns true if // 1) This is a bottom appbar // 2) No appbar has focus and a bottom appbar is not in the process of showing // 3) What currently has focus is neither a bottom appbar nor a top appbar // AND a bottom appbar is not in the process of showing. // Otherwise Returns false _shouldStealFocus: function AppBar_shouldStealFocus() { var activeElementAppBar = thisWinUI.AppBar._isAppBarOrChild(document.activeElement); if (this._element === activeElementAppBar) { // This appbar already has focus and we don't want to move focus // from where it currently is in this appbar. return false; } if (this._placement === appBarPlacementBottom) { // This is a bottom appbar return true; } var isBottomAppBarShowing = this._isABottomAppBarInTheProcessOfShowing(); if (!activeElementAppBar) { // Currently no appbar has focus. // Return true if a bottom appbar is not in the process of showing. return !isBottomAppBarShowing; } if (!activeElementAppBar.winControl) { // This should not happen, but if it does we want to make sure // that an AppBar ends up with focus. return true; } if ((activeElementAppBar.winControl._placement !== appBarPlacementBottom) && (activeElementAppBar.winControl._placement !== appBarPlacementTop) && !isBottomAppBarShowing) { // What currently has focus is neither a bottom appbar nor a top appbar // -and- // a bottom appbar is not in the process of showing. return true; } return false }, // Set focus to the passed in AppBar _setFocusToAppBar: function AppBar_setFocusToAppBar() { if (this._focusOnFirstFocusableElement()) { // Prevent what is gaining focus from showing that it has focus, // but only in the non-keyboard scenario. if (!this._keyboardInvoked) { thisWinUI._Overlay._addHideFocusClass(document.activeElement); } } else { // No first element, set it to appbar itself thisWinUI._Overlay._trySetActive(this._element); } }, _contentChanged: function AppBar_contentChanged() { this._updateCommandsWidth(); this._scaleAppBar(); }, _scaleAppBar: function AppBar_scaleAppBar() { // For commands layout AppBars only. If the total width of all AppBarCommands is greater than the // width of the AppBar, add the win-reduced class to the AppBar element. if (this.layout === appBarLayoutCommands) { // Measure AppBar's contents width, AppBar offsetWidth and AppBar padding: var widthOfVisibleContent = this._getCommandsWidth(); if (this._appBarTotalKnownWidth !== +this._appBarTotalKnownWidth) { this._appBarTotalKnownWidth = this._scaleAppBarHelper(); } if (widthOfVisibleContent <= this._appBarTotalKnownWidth) { // Full size commands WinJS.Utilities.removeClass(this._element, reducedClass); } else { // Reduced size commands WinJS.Utilities.addClass(this._element, reducedClass); } } }, _scaleAppBarHelper: function AppBar_scaleAppBarHelper() { // This exists as a single line function so that unit tests can // overwrite it since they can't resize the WWA window. return document.documentElement.clientWidth; }, _updateCommandsWidth: function AppBar_updateCommandsWidth(commandSubSet) { // Whenever Commands are hidden/shown in the Commands layout AppBar, this function is called // to update the cached width measurement of all visible AppBarCommands in the AppBar. if (this.layout === appBarLayoutCommands) { var buttonsCount = 0; var separatorsCount = 0; var command; var commands = commandSubSet; this._widthOfAllCommands = 0; if (!commands) { // Crawl the AppBar's inner HTML for the commands. commands = this._getVisibleCommands(); } this._widthOfAllCommands = this._getCommandsWidth(commands); } }, _getCommandsWidth: function AppBar_getCommandsWidth(commandSubSet) { if (!commandSubSet) { // Return the cached width of all previously visible commands in the AppBar. return this._widthOfAllCommands; } else { // Return the width of the specified subset. var separatorsCount = 0; var buttonsCount = 0; var widthOfCommandSubSet = 0; var command; for (var i = 0, len = commandSubSet.length; i < len; i++) { command = commandSubSet[i].winControl || commandSubSet[i]; if (command._type === typeSeparator) { separatorsCount++ } else if (command._type !== typeContent) { // button, toggle, and flyout types all have the same width. buttonsCount++; } else { widthOfCommandSubSet += command._fullSizeWidth; } } } return widthOfCommandSubSet += (separatorsCount * separatorWidth) + (buttonsCount * buttonWidth); }, _beginAnimateCommands: function AppBar_beginAnimateCommands(showCommands, hideCommands, otherVisibleCommands) { // The parameters are 3 mutually exclusive arrays of win-command elements contained in this Overlay. // 1) showCommands[]: All of the HIDDEN win-command elements that ARE scheduled to show. // 2) hideCommands[]: All of the VISIBLE win-command elements that ARE scheduled to hide. // 3) otherVisibleCommands[]: All VISIBLE win-command elements that ARE NOT scheduled to hide. if (this.layout === appBarLayoutCommands) { this._scaleCommandsAfterAnimations = false; // Update our command counts now, to what they will be after we complete the animations. var visibleCommandsAfterAnimations = otherVisibleCommands.concat(showCommands); this._updateCommandsWidth(visibleCommandsAfterAnimations) var changeInWidth = this._getCommandsWidth(showCommands) - this._getCommandsWidth(hideCommands); if (changeInWidth > 0) { // Width of contents is going to increase. If there won't be enough room to fit them all on a single row, // reduce size of commands before the new content appears. this._scaleAppBar(); } else if (changeInWidth < 0) { // Width of contents is going to decrease. Once animations are complete, check if // there is enough available space to make the remaining commands full size. this._scaleCommandsAfterAnimations = true; } } }, _endAnimateCommands: function AppBar_endAnimateCommands() { if (this._scaleCommandsAfterAnimations) { this._scaleAppBar(); } }, _addCommand: function AppBar_addCommand(command) { if (!command) { throw new WinJS.ErrorFromName("WinJS.UI.AppBar.NullCommand", strings.nullCommand); } // See if it's a command already if (!command._element) { // Not a command, so assume it is options for the command's constructor. command = new WinJS.UI.AppBarCommand(null, command); } // If we were attached somewhere else, detach us if (command._element.parentElement) { command._element.parentElement.removeChild(command._element); } // Reattach us this._element.appendChild(command._element); }, _measureContentCommands: function AppBar_measureContentCommands() { // AppBar measures the width of content commands when they are first added // and then caches that value to avoid additional layouts in the future. // Can't measure unless We're in the document body if (document.body.contains(this.element)) { this._needToMeasure = false; // Remove the reducedClass from AppBar to ensure fullsize measurements var hadReducedClass = WinJS.Utilities.hasClass(this.element, reducedClass); WinJS.Utilities.removeClass(this._element, reducedClass); // Make sure AppBar and children have width dimensions. var prevAppBarDisplay = this.element.style.display; var prevCommandDisplay; this.element.style.display = ""; var commandElements = this._element.children; var element; for (var i = 0, len = commandElements.length; i < len; i++) { element = commandElements[i]; if (element.winControl && element.winControl._type === typeContent) { // Make sure command has width dimensions before we measure. prevCommandDisplay = element.style.display; element.style.display = ""; element.winControl._fullSizeWidth = WinJS.Utilities.getTotalWidth(element) || 0; element.style.display = prevCommandDisplay; } } // Restore state to AppBar. this.element.display = prevAppBarDisplay; if (hadReducedClass) { WinJS.Utilities.addClass(this._element, reducedClass); } } }, // Performs any pending measurements on "content" type AppBarCommands and scales the AppBar to fit all AppBarCommand types accordingly. _layoutCommands: function AppBar_layoutCommands() { if (this._needToMeasure && this.layout === appBarLayoutCommands) { this._measureContentCommands(); this._contentChanged(); } }, // Get the top of the top appbars, this is always 0 because appbar uses // -ms-device-fixed positioning. _getTopOfVisualViewport: function AppBar_getTopOfVisualViewPort() { return 0; }, // Get the bottom of the bottom appbars, Bottom is just 0, if there's no IHM. // When the IHM appears, the default behavior is to resize the view. If a resize // happens, we can rely on -ms-device-fixed positioning and leave the bottom // at 0. However if resize doesn't happen, then the keyboard obscures the appbar // and we will need to adjust the bottom of the appbar by distance of the keyboard. _getAdjustedBottom: function AppBar_getAdjustedBottom() { // Need the distance the IHM moved as well. return thisWinUI._Overlay._keyboardInfo._visibleDocBottomOffset; }, _showingKeyboard: function AppBar_showingKeyboard(event) { // Remember keyboard showing state. this._keyboardObscured = false; this._keyboardHiding = false; // If we're already moved, then ignore the whole thing if (thisWinUI._Overlay._keyboardInfo._visible && this._alreadyInPlace()) { return; } this._keyboardShowing = true; // If focus is in the appbar, don't cause scrolling. if (!this.hidden && this._element.contains(document.activeElement)) { event.ensuredFocusedElementInView = true; } // Check if appbar moves or is obscured if (!this.hidden && this._placement !== appBarPlacementTop && thisWinUI._Overlay._isFlyoutVisible()) { // Remember that we're obscured this._keyboardObscured = true; } else { // If not obscured, tag as showing and set timeout to restore us. this._scrollHappened = false; } // Also set timeout regardless, so we can clean up our _keyboardShowing flag. var that = this; setTimeout(function (e) { that._checkKeyboardTimer(e); }, thisWinUI._Overlay._keyboardInfo._animationShowLength + thisWinUI._Overlay._scrollTimeout); }, _hidingKeyboard: function AppBar_hidingKeyboard(event) { // We won't be obscured this._keyboardObscured = false; this._keyboardShowing = false; this._keyboardHiding = true; // We'll either just reveal the current space or resize the window if (!thisWinUI._Overlay._keyboardInfo._isResized) { // If we're visible or only fake hiding under keyboard, or already animating, // then snap us to our final position. if (!this.hidden || this._fakeHide || this._animating) { // Not resized, update our final position immediately this._checkScrollPosition(); this._element.style.display = ""; this._fakeHide = false; } this._keyboardHiding = false; } // Else resize should clear keyboardHiding. }, _resize: function AppBar_resize(event) { // If we're hidden by the keyboard, then hide bottom appbar so it doesn't pop up twice when it scrolls if (this._keyboardShowing) { // Top is allowed to scroll off the top, but we don't want bottom to peek up when // scrolled into view since we'll show it ourselves and don't want a stutter effect. if (!this.hidden) { if (this._placement !== appBarPlacementTop && !this._keyboardObscured) { // If viewport doesn't match window, need to vanish momentarily so it doesn't scroll into view, // however we don't want to toggle the visibility="hidden" hidden flag. this._element.style.display = "none"; } } // else if we're top we stay, and if there's a flyout, stay obscured by the keyboard. } else if (this._keyboardHiding) { this._keyboardHiding = false; if (!this.hidden || this._animating) { // Snap to final position this._checkScrollPosition(); this._element.style.display = ""; this._fakeHide = false; } } // Check for horizontal window resizes. this._appBarTotalKnownWidth = null; if (!this.hidden) { this._scaleAppBar(); } }, _checkKeyboardTimer: function AppBar_checkKeyboardTimer() { if (!this._scrollHappened) { this._mayEdgeBackIn(); } }, _manipulationChanged: function AppBar_manipulationChanged(event) { // See if we're at the not manipulating state, and we had a scroll happen, // which is implicitly after the keyboard animated. if (event.currentState === 0 && this._scrollHappened) { this._mayEdgeBackIn(); } }, _mayEdgeBackIn: function AppBar_mayEdgeBackIn(event) { // May need to react to IHM being resized event if (this._keyboardShowing) { // If not top appbar or viewport isn't still at top, then need to show again this._keyboardShowing = false; // If obscured (flyout showing), don't change. // If hidden, may be because _fakeHide was set in _resize. // If bottom we have to move, or if top scrolled off screen. if (!this._keyboardObscured && (!this.hidden || this._fakeHide) && (this._placement !== appBarPlacementTop || thisWinUI._Overlay._keyboardInfo._visibleDocTop !== 0)) { this._doNotFocus = true; this._fakeHide = true; this._show(); } else { // Ensure any animation dropped during the showing keyboard are caught up. this._checkDoNext(); } } this._scrollHappened = false; }, // _checkPosition repositions the AppBar when the soft keyboard shows up _checkPosition: function AppBar_checkPosition() { // Bottom's the only one needing movement if (this._placement === appBarPlacementBottom) { this._element.style.bottom = this._getAdjustedBottom() + "px"; } else if (this._placement === appBarPlacementTop) { this._element.style.top = this._getTopOfVisualViewport() + "px"; } // else we don't touch custom positions }, _checkScrollPosition: function AppBar_checkScrollPosition(event) { // If keyboard's animating, then remember we may come in if (this._keyboardShowing) { // Tag that it's OK to edge back in. this._scrollHappened = true; return; } // We only need to update if we're visible if (!this.hidden || this._animating) { this._checkPosition(); // Ensure any animation dropped during the showing keyboard are caught up. this._checkDoNext(); } }, _alreadyInPlace: function AppBar_alreadyInPlace() { // See if we're already where we're supposed to be. if (this._placement === appBarPlacementBottom) { if (parseInt(this._element.style.bottom) === this._getAdjustedBottom()) { return true; } } else if (this._placement === appBarPlacementTop) { if (parseInt(this._element.style.top) === this._getTopOfVisualViewport()) { return true; } } // else we don't understand custom positioning return false; }, // If there is a visible non-sticky AppBar then it sets the firstDiv tabIndex to // the minimum tabIndex found in the AppBars and finalDiv to the max found. // Otherwise sets their tabIndex to -1 so they are not tab stops. _updateFirstAndFinalDiv: function AppBar_updateFirstAndFinalDiv() { var appBarFirstDiv = this._element.querySelectorAll("." + firstDivClass); appBarFirstDiv = appBarFirstDiv.length >= 1 ? appBarFirstDiv[0] : null; var appBarFinalDiv = this._element.querySelectorAll("." + finalDivClass); appBarFinalDiv = appBarFinalDiv.length >= 1 ? appBarFinalDiv[0] : null; // Remove the firstDiv & finalDiv if they are not at the appropriate locations if (appBarFirstDiv && (this._element.children[0] != appBarFirstDiv)) { appBarFirstDiv.parentNode.removeChild(appBarFirstDiv); appBarFirstDiv = null; } if (appBarFinalDiv && (this._element.children[this._element.children.length - 1] != appBarFinalDiv)) { appBarFinalDiv.parentNode.removeChild(appBarFinalDiv); appBarFinalDiv = null; } // Create and add the firstDiv & finalDiv if they don't already exist if (!appBarFirstDiv) { // Add a firstDiv that will be the first child of the appBar. // On focus set focus to the previous appBar. // The div should only be focusable if there are visible non-sticky AppBars. appBarFirstDiv = document.createElement("div"); // display: inline is needed so that the div doesn't take up space and cause the page to scroll on focus appBarFirstDiv.style.display = "inline"; appBarFirstDiv.className = firstDivClass; appBarFirstDiv.tabIndex = -1; appBarFirstDiv.setAttribute("aria-hidden", "true"); appBarFirstDiv.addEventListener("focus", _setFocusToPreviousAppBar, true); this._element.insertAdjacentElement("AfterBegin", appBarFirstDiv); } if (!appBarFinalDiv) { // Add a finalDiv that will be the last child of the appBar. // On focus set focus to the next appBar. // The div should only be focusable if there are visible non-sticky AppBars. appBarFinalDiv = document.createElement("div"); // display: inline is needed so that the div doesn't take up space and cause the page to scroll on focus appBarFinalDiv.style.display = "inline"; appBarFinalDiv.className = finalDivClass; appBarFinalDiv.tabIndex = -1; appBarFinalDiv.setAttribute("aria-hidden", "true"); appBarFinalDiv.addEventListener("focus", _setFocusToNextAppBar, true); this._element.appendChild(appBarFinalDiv); } // Update the tabIndex of the firstDiv & finalDiv if (_isThereVisibleNonStickyBar()) { var elms = this._element.getElementsByTagName("*"); if (appBarFirstDiv) { appBarFirstDiv.tabIndex = WinJS.Utilities._getLowestTabIndexInList(elms); } if (appBarFinalDiv) { appBarFinalDiv.tabIndex = WinJS.Utilities._getHighestTabIndexInList(elms); } } else { if (appBarFirstDiv) { appBarFirstDiv.tabIndex = -1; } if (appBarFinalDiv) { appBarFinalDiv.tabIndex = -1; } } }, _writeProfilerMark: function AppBar_writeProfilerMark(text) { msWriteProfilerMark("WinJS.UI.AppBar:" + this._id + ":" + text); } }); // Statics AppBar._ElementWithFocusPreviousToAppBar = null; // Returns appbar element (or CED/sentinal) if the element or what had focus before the element (if a Flyout) is either: // 1) an AppBar, // 2) OR in the subtree of an AppBar, // 3) OR an AppBar click eating div. // Returns null otherwise. AppBar._isAppBarOrChild = function (element) { // If it's null, we can't do this if (!element) { return null; } // click eating divs and sentinals should not have children if (WinJS.Utilities.hasClass(element, thisWinUI._Overlay._clickEatingAppBarClass) || WinJS.Utilities.hasClass(element, thisWinUI._Overlay._clickEatingFlyoutClass) || WinJS.Utilities.hasClass(element, firstDivClass) || WinJS.Utilities.hasClass(element, finalDivClass)) { return element; } while (element && element !== document) { if (WinJS.Utilities.hasClass(element, appBarClass)) { return element; } if (WinJS.Utilities.hasClass(element, "win-flyout") && element != element.winControl._previousFocus) { var flyoutControl = element.winControl; // If _previousFocus was in a light dismissable AppBar, then this Flyout is considered of an extension of it and that AppBar will not close. // Hook up a 'focusout' listener to this Flyout element to make sure that light dismiss AppBars close if focus moves anywhere other than back to an AppBar. var appBarElement = thisWinUI.AppBar._isAppBarOrChild(flyoutControl._previousFocus); if (appBarElement) { flyoutControl.element.addEventListener('focusout', function focusOut(event) { // Hides any open AppBars if the new activeElement is not in an AppBar. _hideIfAllAppBarsLostFocus(); flyoutControl.element.removeEventListener('focusout', focusOut, false); }, false); } return appBarElement; } element = element.parentNode; } return null; }; // Returns true if the element or what had focus before the element (if a Flyout) is either: // 1) the appBar or subtree // 2) OR in a flyout spawned by the appBar // Returns false otherwise. AppBar._isWithinAppBarOrChild = function (element, appBar) { if (!element || !appBar) { return false; } if (appBar.contains(element)) { return true; } var flyout = thisWinUI._Overlay._getParentControlUsingClassName(element, "win-flyout"); return (flyout && appBar.contains(flyout._previousFocus)); }; // Overlay class calls this for global light dismiss events AppBar._hideLightDismissAppBars = function (event, keyboardInvoked) { var elements = document.querySelectorAll("." + appBarClass); var len = elements.length; var AppBars = []; for (var i = 0; i < len; i++) { var AppBar = elements[i].winControl; if (AppBar && !AppBar.sticky && !AppBar.hidden) { AppBars.push(AppBar); } } _hideAllBars(AppBars, keyboardInvoked); }; var appBarSynchronizationPromise = WinJS.Promise.as(); // Callback for AppBar Edgy Event Command AppBar._toggleAppBarEdgy = function (keyboardInvoked) { var bars = _getDynamicBarsForEdgy(); // If they're all visible hide them, otherwise show them all if (bars._visible && !bars._hidden) { appBarSynchronizationPromise = appBarSynchronizationPromise.then(function () { return _hideAllBars(bars, keyboardInvoked); }); return "hiding"; } else { appBarSynchronizationPromise = appBarSynchronizationPromise.then(function () { return _showAllBars(bars, keyboardInvoked); }); return "showing"; } }; return AppBar; }) }); })(WinJS); /// appbar,Flyout,Flyouts,Statics (function flyoutInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// /// Displays lightweight UI that is either informational, or requires user interaction. /// Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. /// /// /// /// Flyout /// /// /// ]]> /// Raised just before showing a flyout. /// Raised immediately after a flyout is fully shown. /// Raised just before hiding a flyout. /// Raised immediately after a flyout is fully hidden. /// The Flyout control itself. /// /// /// Flyout: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; // Class Names var appBarCommandClass = "win-command"; var flyoutClass = "win-flyout"; var flyoutLightClass = "win-ui-light"; var menuClass = "win-menu"; var scrollsClass = "win-scrolls"; var finalDivClass = "win-finaldiv"; var firstDivClass = "win-firstdiv"; function getDimension(element, property) { return parseFloat(element, window.getComputedStyle(element, null)[property]); } var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/flyoutAriaLabel").value; }, get noAnchor() { return WinJS.Resources._getWinJSString("ui/noAnchor").value; }, get badPlacement() { return WinJS.Resources._getWinJSString("ui/badPlacement").value; }, get badAlignment() { return WinJS.Resources._getWinJSString("ui/badAlignment").value; } }; var Flyout = WinJS.Class.derive(WinJS.UI._Overlay, function Flyout_ctor(element, options) { /// /// /// Creates a new Flyout control. /// /// /// The DOM element that hosts the control. /// /// /// The set of properties and values to apply to the new Flyout. /// /// The new Flyout control. /// /// // Simplify checking later options = options || {}; // Make sure there's an input element this._element = element || document.createElement("div"); this._id = this._element.id || this._element.uniqueID; this._writeProfilerMark("constructor,StartTM"); this._baseFlyoutConstructor(this._element, options); var _elms = this._element.getElementsByTagName("*"); var firstDiv = this._addFirstDiv(); firstDiv.tabIndex = WinJS.Utilities._getLowestTabIndexInList(_elms); var finalDiv = this._addFinalDiv(); finalDiv.tabIndex = WinJS.Utilities._getHighestTabIndexInList(_elms); // Handle "esc" & "tab" key presses this._element.addEventListener("keydown", this._handleKeyDown, true); this._writeProfilerMark("constructor,StopTM"); return this; }, { _lastMaxHeight: null, _baseFlyoutConstructor: function Flyout_baseFlyoutContstructor(element, options) { // Flyout constructor // We have some options with defaults this._placement = "auto"; this._alignment = "center"; // Call the base overlay constructor helper this._baseOverlayConstructor(element, options); // Make a click eating div thisWinUI._Overlay._createClickEatingDivFlyout(); // Start flyouts hidden this._element.style.visibilty = "hidden"; this._element.style.display = "none"; // Attach our css class WinJS.Utilities.addClass(this._element, flyoutClass); WinJS.Utilities.addClass(this._element, flyoutLightClass); // Make sure we have an ARIA role var role = this._element.getAttribute("role"); if (role === null || role === "" || role === undefined) { if (WinJS.Utilities.hasClass(this._element, menuClass)) { this._element.setAttribute("role", "menu"); } else { this._element.setAttribute("role", "dialog"); } } var label = this._element.getAttribute("aria-label"); if (label === null || label === "" || label === undefined) { this._element.setAttribute("aria-label", strings.ariaLabel); } // Base animation is popIn, but our flyout has different arguments this._currentAnimateIn = this._flyoutAnimateIn; this._currentAnimateOut = this._flyoutAnimateOut; // Make sure _Overlay event handlers are hooked up this._addOverlayEventHandlers(true); }, /// /// Gets or sets the Flyout control's anchor. The anchor element is the HTML element which the Flyout originates from and is positioned relative to. /// (This setting can be overridden when you call the show method.) /// /// anchor: { get: function () { return this._anchor; }, set: function (value) { this._anchor = value; } }, /// /// Gets or sets the default placement of this Flyout. (This setting can be overridden when you call the show method.) /// /// placement: { get: function () { return this._placement; }, set: function (value) { if (value !== "top" && value !== "bottom" && value !== "left" && value !== "right" && value !== "auto") { // Not a legal placement value throw new WinJS.ErrorFromName("WinJS.UI.Flyout.BadPlacement", strings.badPlacement); } this._placement = value; } }, /// /// Gets or sets the default alignment for this Flyout. (This setting can be overridden when you call the show method.) /// /// alignment: { get: function () { return this._alignment; }, set: function (value) { if (value !== "right" && value !== "left" && value !== "center") { // Not a legal alignment value throw new WinJS.ErrorFromName("WinJS.UI.Flyout.BadAlignment", strings.badAlignment); } this._alignment = value; } }, _dispose: function Flyout_dispose() { WinJS.Utilities.disposeSubTree(this.element); this._hide(); this.anchor = null; }, show: function (anchor, placement, alignment) { /// /// /// Shows the Flyout, if hidden, regardless of other states. /// /// /// The DOM element, or ID of a DOM element to anchor the Flyout, overriding the anchor property for this time only. /// /// /// The placement of the Flyout to the anchor: 'auto' (default), 'top', 'bottom', 'left', or 'right'. This parameter overrides the placement property for this show only. /// /// /// For 'top' or 'bottom' placement, the alignment of the Flyout to the anchor's edge: 'center' (default), 'left', or 'right'. /// This parameter overrides the alignment property for this show only. /// /// /// this._writeProfilerMark("show,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndShow(). // Just call private version to make appbar flags happy this._show(anchor, placement, alignment); }, _show: function Flyout_show(anchor, placement, alignment) { this._baseFlyoutShow(anchor, placement, alignment); }, hide: function () { /// /// /// Hides the Flyout, if visible, regardless of other states. /// /// /// // Just wrap the private one, turning off keyboard invoked flag this._writeProfilerMark("hide,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndHide(). this._keyboardInvoked = false; this._hide(); }, _hide: function Flyout_hide() { if (this._baseHide()) { // Return focus if this or the flyout CED has focus var active = document.activeElement; if (this._previousFocus && active && (this._element.contains(active) || WinJS.Utilities.hasClass(active, thisWinUI._Overlay._clickEatingFlyoutClass)) && this._previousFocus.focus !== undefined) { // _isAppBarOrChild may return a CED or sentinal var appBar = thisWinUI.AppBar._isAppBarOrChild(this._previousFocus); if (!appBar || (appBar.winControl && !appBar.winControl.hidden && !appBar.winAnimating)) { // Don't move focus back to a appBar that is hidden // We cannot rely on element.style.visibility because it will be visible while animating var role = this._previousFocus.getAttribute("role"); var fHideRole = thisWinUI._Overlay._keyboardInfo._visible && !this._keyboardWasUp; if (fHideRole) { // Convince IHM to dismiss because it only came up after the flyout was up. // Change aria role and back to get IHM to dismiss. this._previousFocus.setAttribute("role", ""); } if (this._keyboardInvoked) { this._previousFocus.focus(); } else { thisWinUI._Overlay._trySetActive(this._previousFocus); } active = document.activeElement; if (fHideRole) { // Restore the role so that css is applied correctly var previousFocus = this._previousFocus; if (previousFocus) { setImmediate(function () { previousFocus.setAttribute("role", role); }); } } } // If the anchor gained focus we want to hide the focus in the non-keyboarding scenario if (!this._keyboardInvoked && (this._previousFocus === active) && appBar && active) { thisWinUI._Overlay._addHideFocusClass(active); } } this._previousFocus = null; // Need click-eating div to be hidden if there are no other visible flyouts if (!this._isThereVisibleFlyout()) { thisWinUI._Overlay._hideClickEatingDivFlyout(); } } }, _baseFlyoutShow: function Flyout_baseFlyoutShow(anchor, placement, alignment) { // Don't do anything if disabled if (this.disabled) { return; } // Pick up defaults if (!anchor) { anchor = this._anchor; } if (!placement) { placement = this._placement; } if (!alignment) { alignment = this._alignment; } // Dereference the anchor if necessary if (typeof anchor === "string") { anchor = document.getElementById(anchor); } else if (anchor && anchor.element) { anchor = anchor.element; } // We expect an anchor if (!anchor) { // If we have _nextLeft, etc., then we were continuing an old animation, so that's OK if (!this._retryLast) { throw new WinJS.ErrorFromName("WinJS.UI.Flyout.NoAnchor", strings.noAnchor); } // Last call was incomplete, so use the previous _current values. this._retryLast = null; } else { // Remember the anchor so that if we lose focus we can go back this._currentAnchor = anchor; // Remember current values this._currentPlacement = placement; this._currentAlignment = alignment; } // Need click-eating div to be visible, no matter what if (!this._sticky) { thisWinUI._Overlay._showClickEatingDivFlyout(); } // If we're animating (eg baseShow is going to fail), then don't mess up our current state. // Queue us up to wait for current animation to finish first. if (this._element.winAnimating) { this._doNext = "show"; this._retryLast = true; return; } // We call our base _baseShow to handle the actual animation if (this._baseShow()) { // (_baseShow shouldn't ever fail because we tested winAnimating above). if (!WinJS.Utilities.hasClass(this.element, "win-menu")) { // Verify that the firstDiv is in the correct location. // Move it to the correct location or add it if not. var _elms = this._element.getElementsByTagName("*"); var firstDiv = this.element.querySelectorAll(".win-first"); if (this.element.children.length && !WinJS.Utilities.hasClass(this.element.children[0], firstDivClass)) { if (firstDiv && firstDiv.length > 0) { firstDiv.item(0).parentNode.removeChild(firstDiv.item(0)); } firstDiv = this._addFirstDiv(); } firstDiv.tabIndex = WinJS.Utilities._getLowestTabIndexInList(_elms); // Verify that the finalDiv is in the correct location. // Move it to the correct location or add it if not. var finalDiv = this.element.querySelectorAll(".win-final"); if (!WinJS.Utilities.hasClass(this.element.children[this.element.children.length - 1], finalDivClass)) { if (finalDiv && finalDiv.length > 0) { finalDiv.item(0).parentNode.removeChild(finalDiv.item(0)); } finalDiv = this._addFinalDiv(); } finalDiv.tabIndex = WinJS.Utilities._getHighestTabIndexInList(_elms); } // Hide all other flyouts this._hideAllOtherFlyouts(this); // Store what had focus before showing the Flyout. // This must happen after we hide all other flyouts so that we store the correct element. this._previousFocus = document.activeElement; } }, _endShow: function Flyout_endShow() { // Remember if the IHM was up since we may need to hide it when the flyout hides. // This check needs to happen after the IHM has a chance to hide itself after we force hide // all other visible Flyouts. this._keyboardWasUp = thisWinUI._Overlay._keyboardInfo._visible; if (!WinJS.Utilities.hasClass(this.element, "win-menu")) { // Put focus on the first child in the Flyout this._focusOnFirstFocusableElementOrThis(); // Prevent what is gaining focus from showing that it has focus thisWinUI._Overlay._addHideFocusClass(document.activeElement); } else { // Make sure the menu has focus, but don't show a focus rect thisWinUI._Overlay._trySetActive(this._element); } }, // Find our new flyout position. _findPosition: function Flyout_findPosition() { this._nextHeight = null; this._keyboardMovedUs = false; this._hasScrolls = false; this._keyboardSquishedUs = 0; // Make sure menu toggles behave if (this._checkToggle) { this._checkToggle(); } // Update margins for this alignment and remove old scrolling this._updateAdjustments(this._currentAlignment); // Set up the new position, and prep the offset for showPopup this._getTopLeft(); // Panning top offset is calculated top this._scrollTop = this._nextTop; // Adjust position if (this._nextTop < 0) { // Need to attach to bottom this._element.style.bottom = "0px"; this._element.style.top = "auto"; } else { // Normal, attach to top this._element.style.top = this._nextTop + "px"; this._element.style.bottom = "auto"; } if (this._nextLeft < 0) { // Overran right, attach to right this._element.style.right = "0px"; this._element.style.left = "auto"; } else { // Normal, attach to left this._element.style.left = this._nextLeft + "px"; this._element.style.right = "auto"; } // Adjust height/scrollbar if (this._nextHeight !== null) { WinJS.Utilities.addClass(this._element, scrollsClass); this._lastMaxHeight = this._element.style.maxHeight; this._element.style.maxHeight = this._nextHeight + "px"; this._nextBottom = this._nextTop + this._nextHeight; this._hasScrolls = true; } // May need to adjust if the IHM is showing. if (thisWinUI._Overlay._keyboardInfo._visible) { // Use keyboard logic this._checkKeyboardFit(); if (this._keyboardMovedUs) { this._adjustForKeyboard(); } } }, // This determines our positioning. We have 5 modes, the 1st four are explicit, the last is automatic: // * top - position explicitly on the top of the anchor, shrinking and adding scrollbar as needed. // * bottom - position explicitly below the anchor, shrinking and adding scrollbar as needed. // * left - position left of the anchor, shrinking and adding a vertical scrollbar as needed. // * right - position right of the anchor, shrinking and adding a vertical scroolbar as needed. // * auto - Automatic placement. // Auto tests the height of the anchor and the flyout. For consistency in orientation, we imagine // that the anchor is placed in the vertical center of the display. If the flyout would fit above // that centered anchor, then we will place the flyout vertically in relation to the anchor, otherwise // placement will be horizontal. // Vertical auto placement will be positioned on top of the anchor if room, otherwise below the anchor. // - this is because touch users would be more likely to obscure flyouts below the anchor. // Horizontal auto placement will be positioned to the left of the anchor if room, otherwise to the right. // - this is because right handed users would be more likely to obscure a flyout on the right of the anchor. // Auto placement will add a vertical scrollbar if necessary. _getTopLeft: function Flyout_getTopLeft() { var anchorRawRectangle = this._currentAnchor.getBoundingClientRect(), flyout = {}, anchor = {}; // Adjust for the anchor's margins. anchor.top = anchorRawRectangle.top; anchor.bottom = anchorRawRectangle.bottom; anchor.left = anchorRawRectangle.left; anchor.right = anchorRawRectangle.right; anchor.height = anchor.bottom - anchor.top; anchor.width = anchor.right - anchor.left; // Get our flyout and margins, note that getDimension calls // window.getComputedStyle, which ensures layout is updated. flyout.marginTop = getDimension(this._element, "marginTop"); flyout.marginBottom = getDimension(this._element, "marginBottom"); flyout.marginLeft = getDimension(this._element, "marginLeft"); flyout.marginRight = getDimension(this._element, "marginRight"); flyout.width = WinJS.Utilities.getTotalWidth(this._element); flyout.height = WinJS.Utilities.getTotalHeight(this._element); flyout.innerWidth = WinJS.Utilities.getContentWidth(this._element); flyout.innerHeight = WinJS.Utilities.getContentHeight(this._element); this._nextMarginPadding = (flyout.height - flyout.innerHeight); // Check fit for requested this._currentPlacement, doing fallback if necessary switch (this._currentPlacement) { case "top": if (!this._fitTop(anchor, flyout)) { // Didn't fit, needs scrollbar this._nextTop = 0; this._nextHeight = anchor.top - this._nextMarginPadding; } this._centerHorizontally(anchor, flyout, this._currentAlignment); break; case "bottom": if (!this._fitBottom(anchor, flyout)) { // Didn't fit, needs scrollbar this._nextTop = -1; this._nextHeight = thisWinUI._Overlay._keyboardInfo._visibleDocHeight - anchor.bottom - this._nextMarginPadding; } this._centerHorizontally(anchor, flyout, this._currentAlignment); break; case "left": if (!this._fitLeft(anchor, flyout)) { // Didn't fit, just shove it to edge this._nextLeft = 0; } this._centerVertically(anchor, flyout); break; case "right": if (!this._fitRight(anchor, flyout)) { // Didn't fit,just shove it to edge this._nextLeft = -1; } this._centerVertically(anchor, flyout); break; case "auto": // Auto, if the anchor was in the vertical center of the display would we fit above it? if (this._sometimesFitsAbove(anchor, flyout)) { // It will fit above or below the anchor if (!this._fitTop(anchor, flyout)) { // Didn't fit above (preferred), so go below. this._fitBottom(anchor, flyout); } this._centerHorizontally(anchor, flyout, this._currentAlignment); } else { // Won't fit above or below, try a side if (!this._fitLeft(anchor, flyout) && !this._fitRight(anchor, flyout)) { // Didn't fit left or right either, is top or bottom bigger? if (this._topHasMoreRoom(anchor)) { // Top, won't fit, needs scrollbar this._nextTop = 0; this._nextHeight = anchor.top - this._nextMarginPadding; } else { // Bottom, won't fit, needs scrollbar this._nextTop = -1; this._nextHeight = thisWinUI._Overlay._keyboardInfo._visibleDocHeight - anchor.bottom - this._nextMarginPadding; } this._centerHorizontally(anchor, flyout, this._currentAlignment); } else { this._centerVertically(anchor, flyout); } } break; default: // Not a legal this._currentPlacement value throw new WinJS.ErrorFromName("WinJS.UI.Flyout.BadPlacement", strings.badPlacement); } // Remember "bottom" in case we need to consider keyboard later, only tested for top-pinned bars this._nextBottom = this._nextTop + flyout.height; }, // If the anchor is centered vertically, would the flyout fit above it? _sometimesFitsAbove: function Flyout_sometimesFitsAbove(anchor, flyout) { return ((thisWinUI._Overlay._keyboardInfo._visibleDocHeight - anchor.height) / 2) >= flyout.height; }, _topHasMoreRoom: function Flyout_topHasMoreRoom(anchor) { return anchor.top > thisWinUI._Overlay._keyboardInfo._visibleDocHeight - anchor.bottom; }, // See if we can fit in various places, fitting in the main view, // ignoring viewport changes, like for the IHM. _fitTop: function Flyout_fitTop(anchor, flyout) { this._nextTop = anchor.top - flyout.height; this._nextAnimOffset = { top: "50px", left: "0px", keyframe: "WinJS-showFlyoutTop" }; return (this._nextTop >= 0 && this._nextTop + flyout.height <= thisWinUI._Overlay._keyboardInfo._visibleDocBottom); }, _fitBottom: function Flyout_fitBottom(anchor, flyout) { this._nextTop = anchor.bottom; this._nextAnimOffset = { top: "-50px", left: "0px", keyframe: "WinJS-showFlyoutBottom" }; return (this._nextTop >= 0 && this._nextTop + flyout.height <= thisWinUI._Overlay._keyboardInfo._visibleDocBottom); }, _fitLeft: function Flyout_fitLeft(anchor, flyout) { this._nextLeft = anchor.left - flyout.width; this._nextAnimOffset = { top: "0px", left: "50px", keyframe: "WinJS-showFlyoutLeft" }; return (this._nextLeft >= 0 && this._nextLeft + flyout.width <= thisWinUI._Overlay._keyboardInfo._visualViewportWidth); }, _fitRight: function Flyout_fitRight(anchor, flyout) { this._nextLeft = anchor.right; this._nextAnimOffset = { top: "0px", left: "-50px", keyframe: "WinJS-showFlyoutRight" }; return (this._nextLeft >= 0 && this._nextLeft + flyout.width <= thisWinUI._Overlay._keyboardInfo._visualViewportWidth); }, _centerVertically: function Flyout_centerVertically(anchor, flyout) { this._nextTop = anchor.top + anchor.height / 2 - flyout.height / 2; if (this._nextTop < 0) { this._nextTop = 0; } else if (this._nextTop + flyout.height >= thisWinUI._Overlay._keyboardInfo._visibleDocBottom) { // Flag to put on bottom this._nextTop = -1; } }, _centerHorizontally: function Flyout_centerHorizontally(anchor, flyout, alignment) { if (alignment === "center") { this._nextLeft = anchor.left + anchor.width / 2 - flyout.width / 2; } else if (alignment === "left") { this._nextLeft = anchor.left; } else if (alignment === "right") { this._nextLeft = anchor.right - flyout.width; } else { throw new WinJS.ErrorFromName("WinJS.UI.Flyout.BadAlignment", strings.badAlignment); } if (this._nextLeft < 0) { this._nextLeft = 0; } else if (this._nextLeft + flyout.width >= document.documentElement.clientWidth) { // flag to put on right this._nextLeft = -1; } }, _updateAdjustments: function Flyout_updateAdjustments(alignment) { // Move to 0,0 in case it is off screen, so that it lays out at a reasonable size this._element.style.top = "0px"; this._element.style.bottom = "auto"; this._element.style.left = "0px"; this._element.style.right = "auto"; // Scrolling may not be necessary WinJS.Utilities.removeClass(this._element, scrollsClass); if (this._lastMaxHeight !== null) { this._element.style.maxHeight = this._lastMaxHeight; this._lastMaxHeight = null; } // Alignment if (alignment === "center") { WinJS.Utilities.removeClass(this._element, "win-leftalign"); WinJS.Utilities.removeClass(this._element, "win-rightalign"); } else if (alignment === "left") { WinJS.Utilities.addClass(this._element, "win-leftalign"); WinJS.Utilities.removeClass(this._element, "win-rightalign"); } else if (alignment === "right") { WinJS.Utilities.addClass(this._element, "win-rightalign"); WinJS.Utilities.removeClass(this._element, "win-leftalign"); } }, _showingKeyboard: function Flyout_showingKeyboard(event) { if (this.hidden) { return; } // The only way that we can be showing a keyboard when a flyout is up is because the input was // in the flyout itself, in which case we'll be moving ourselves. There is no practical way // for the application to override this as the focused element is in our flyout. event.ensuredFocusedElementInView = true; // See if the keyboard is going to force us to move this._checkKeyboardFit(); if (this._keyboardMovedUs) { // Pop out immediately, then move to new spot this._element.style.opacity = 0; var that = this; setTimeout(function () { that._adjustForKeyboard(); that._baseAnimateIn(); }, thisWinUI._Overlay._keyboardInfo._animationShowLength); } }, _resize: function Flyout_resize(event) { // If hidden and not busy animating, then nothing to do if (this.hidden && !this._animating) { return; } // This should only happen if the IHM is dismissing, // the only other way is for viewstate changes, which // would dismiss any flyout. if (this._keyboardHiding) { // Hiding keyboard, update our position, giving the anchor a chance to update first. var that = this; setImmediate(function () { that._findPosition(); }); this._keyboardHiding = false; } }, _checkKeyboardFit: function Flyout_checkKeyboardFit() { // Check for moving to fit keyboard: // - Too Tall, above top, or below bottom. var height = WinJS.Utilities.getTotalHeight(this._element); var viewportHeight = thisWinUI._Overlay._keyboardInfo._visibleDocHeight - this._nextMarginPadding; if (height > viewportHeight) { // Too Tall, pin to top with max height this._keyboardMovedUs = true; this._scrollTop = 0; this._keyboardSquishedUs = viewportHeight; } else if (this._nextTop === -1) { // Pinned to bottom counts as moved this._keyboardMovedUs = true; } else if (this._nextTop < 0) { // Above the top of the viewport this._scrollTop = 0; this._keyboardMovedUs = true; } else if (this._nextBottom > thisWinUI._Overlay._keyboardInfo._visibleDocBottom) { // Below the bottom of the viewport this._scrollTop = -1; this._keyboardMovedUs = true; } }, _adjustForKeyboard: function Flyout_adjustForKeyboard() { // Keyboard moved us, update our metrics as needed if (this._keyboardSquishedUs) { // Add scrollbar if we didn't already have scrollsClass if (!this._hasScrolls) { WinJS.Utilities.addClass(this._element, scrollsClass); this._lastMaxHeight = this._element.style.maxHeight; } // Adjust height this._element.style.maxHeight = this._keyboardSquishedUs + "px"; } // Update top/bottom this._checkScrollPosition(true); }, _hidingKeyboard: function Flyout_hidingKeyboard(event) { // If we aren't visible and not animating, or haven't been repositioned, then nothing to do // We don't know if the keyboard moved the anchor, so _keyboardMovedUs doesn't help here if (this.hidden && !this._animating) { return; } // Snap to the final position // We'll either just reveal the current space or resize the window if (thisWinUI._Overlay._keyboardInfo._isResized) { // Flag resize that we'll need an updated position this._keyboardHiding = true; } else { // Not resized, update our final position, giving the anchor a chance to update first. var that = this; setImmediate(function () { that._findPosition(); }); } }, _checkScrollPosition: function Flyout_checkScrollPosition(showing) { if (this.hidden && !showing) { return; } // May need to adjust top by viewport offset if (this._scrollTop < 0) { // Need to attach to bottom this._element.style.bottom = thisWinUI._Overlay._keyboardInfo._visibleDocBottomOffset + "px"; this._element.style.top = "auto"; } else { // Normal, attach to top this._element.style.top = "0px"; this._element.style.bottom = "auto"; } }, // AppBar flyout animations _flyoutAnimateIn: function Flyout_flyoutAnimateIn() { if (this._keyboardMovedUs) { return this._baseAnimateIn(); } else { this._element.style.opacity = 1; this._element.style.visibility = "visible"; return WinJS.UI.Animation.showPopup(this._element, this._nextAnimOffset); } }, _flyoutAnimateOut: function Flyout_flyoutAnimateOut() { if (this._keyboardMovedUs) { return this._baseAnimateOut(); } else { this._element.style.opacity = 0; return WinJS.UI.Animation.hidePopup(this._element, this._nextAnimOffset); } }, // Hide all other flyouts besides this one _hideAllOtherFlyouts: function Flyout_hideAllOtherFlyouts(thisFlyout) { var flyouts = document.querySelectorAll(".win-flyout"); for (var i = 0; i < flyouts.length; i++) { var flyoutControl = flyouts[i].winControl; if (flyoutControl && !flyoutControl.hidden && (flyoutControl !== thisFlyout)) { flyoutControl.hide(); } } }, // Returns true if there is a flyout in the DOM that is not hidden _isThereVisibleFlyout: function Flyout_isThereVisibleFlyout() { var flyouts = document.querySelectorAll(".win-flyout"); for (var i = 0; i < flyouts.length; i++) { var flyoutControl = flyouts[i].winControl; if (flyoutControl && !flyoutControl.hidden) { return true; } } return false; }, _handleKeyDown: function Flyout_handleKeyDown(event) { // Escape closes flyouts but if the user has a text box with an IME candidate // window open, we want to skip the ESC key event since it is handled by the IME. // When the IME handles a key it sets event.keyCode to 229 for an easy check. if (event.key === "Esc" && event.keyCode !== 229) { // Show a focus rect on what we move focus to event.preventDefault(); event.stopPropagation(); this.winControl._keyboardInvoked = true; this.winControl._hide(); } else if ((event.key === "Spacebar" || event.key === "Enter") && (this === document.activeElement)) { event.preventDefault(); event.stopPropagation(); this.winControl.hide(); } else if (event.shiftKey && event.key === "Tab" && this === document.activeElement && !event.altKey && !event.ctrlKey && !event.metaKey) { event.preventDefault(); event.stopPropagation(); this.winControl._focusOnLastFocusableElementOrThis(); } }, // Create and add a new first div as the first child _addFirstDiv: function Flyout_addFirstDiv() { var firstDiv = document.createElement("div"); firstDiv.className = firstDivClass; firstDiv.style.display = "inline"; firstDiv.setAttribute("role", "menuitem"); firstDiv.setAttribute("aria-hidden", "true"); this._element.insertAdjacentElement("AfterBegin", firstDiv); var that = this; firstDiv.addEventListener("focus", function () { that._focusOnLastFocusableElementOrThis(); }, false); return firstDiv; }, // Create and add a new final div as the last child _addFinalDiv: function Flyout_addFinalDiv() { var finalDiv = document.createElement("div"); finalDiv.className = finalDivClass; finalDiv.style.display = "inline"; finalDiv.setAttribute("role", "menuitem"); finalDiv.setAttribute("aria-hidden", "true"); this._element.appendChild(finalDiv); var that = this; finalDiv.addEventListener("focus", function () { that._focusOnFirstFocusableElementOrThis(); }, false); return finalDiv; }, _writeProfilerMark: function Flyout_writeProfilerMark(text) { msWriteProfilerMark("WinJS.UI.Flyout:" + this._id + ":" + text); } }); return Flyout; }) }); })(WinJS); // Menu /// Menu,Menus,Flyout,Flyouts,Statics (function menuInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Represents a menu flyout for displaying commands. /// /// /// Menu /// /// /// /// /// ]]> /// Raised just before showing a menu. /// Raised immediately after a menu is fully shown. /// Raised just before hiding a menu. /// Raised immediately after a menu is fully hidden. /// The Menu control itself /// /// /// Menu: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; // Class Names var menuClass = "win-menu"; var menuToggleClass = "win-menu-toggle"; var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/menuAriaLabel").value; }, get requiresCommands() { return WinJS.Resources._getWinJSString("ui/requiresCommands").value; }, get nullCommand() { return WinJS.Resources._getWinJSString("ui/nullCommand").value; }, }; var Menu = WinJS.Class.derive(WinJS.UI.Flyout, function Menu_ctor(element, options) { /// /// /// Creates a new Menu control. /// /// /// The DOM element that will host the control. /// /// /// The set of properties and values to apply to the control. /// /// The new Menu control. /// /// // We need to be built on top of a Flyout, so stomp on the user's input options = options || {}; // Make sure there's an input element this._element = element || document.createElement("div"); this._id = this._element.id || this._element.uniqueID; this._writeProfilerMark("constructor,StartTM"); // validate that if they didn't set commands, in which // case any HTML only contains commands. Do this first // so that we don't leave partial Menus in the DOM. if (!options.commands && this._element) { // Shallow copy object so we can modify it. options = WinJS.Utilities._shallowCopy(options); options.commands = this._verifyCommandsOnly(this._element, "WinJS.UI.MenuCommand"); } // Remember aria role in case base constructor changes it var role = this._element ? this._element.getAttribute("role") : null; var label = this._element ? this._element.getAttribute("aria-label") : null; // Call the base overlay constructor helper this._baseFlyoutConstructor(this._element, options); // Make sure we have an ARIA role if (role === null || role === "" || role === undefined) { this._element.setAttribute("role", "menu"); } if (label === null || label === "" || label === undefined) { this._element.setAttribute("aria-label", strings.ariaLabel); } // Handle "esc" & "up/down" key presses this._element.addEventListener("keydown", this._handleKeyDown, true); // Attach our css class WinJS.Utilities.addClass(this._element, menuClass); // Need to set our commands, making sure we're hidden first this.hide(); this._writeProfilerMark("constructor,StopTM"); }, { // Public Properties /// /// Sets the MenuCommand objects that appear in the Menu. You can set this to a single MenuCommand or an array of MenuCommand objects. /// /// commands: { set: function (value) { // Fail if trying to set when visible if (!this.hidden) { throw new WinJS.ErrorFromName("WinJS.UI.Menu.CannotChangeCommandsWhenVisible", WinJS.Resources._formatString(thisWinUI._Overlay.commonstrings.cannotChangeCommandsWhenVisible, "Menu")); } // Start from scratch WinJS.Utilities.empty(this._element); // In case they had only one... if (!Array.isArray(value)) { value = [value]; } // Add commands var len = value.length; for (var i = 0; i < len; i++) { this._addCommand(value[i]); } } }, getCommandById: function (id) { /// /// /// Retrieve the command with the specified ID from this Menu. If more than one command is found, all are returned. /// /// The ID of the command to find. /// /// The command found, an array of commands if more than one have the same ID, or null if no command is found. /// /// /// var commands = this.element.querySelectorAll("#" + id); for (var count = 0; count < commands.length; count++) { // Any elements we generated this should succeed for, // but remove missing ones just to be safe. commands[count] = commands[count].winControl; if (!commands[count]) { commands.splice(count, 1); } } if (commands.length === 1) { return commands[0]; } else if (commands.length === 0) { return null; } return commands; }, showCommands: function (commands) { /// /// /// Shows the specified commands of the Menu. /// /// /// The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. /// /// /// if (!commands) { throw new WinJS.ErrorFromName("WinJS.UI.Menu.RequiresCommands", strings.requiresCommands); } this._showCommands(commands, true); }, hideCommands: function (commands) { /// /// /// Hides the Menu. /// /// /// Required. Command or Commands to hide, either String, DOM elements, or WinJS objects. /// /// /// if (!commands) { throw new WinJS.ErrorFromName("WinJS.UI.Menu.RequiresCommands", strings.requiresCommands); } this._hideCommands(commands, true); }, showOnlyCommands: function (commands) { /// /// /// Shows the specified commands of the Menu while hiding all other commands. /// /// /// The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. /// /// /// if (!commands) { throw new WinJS.ErrorFromName("WinJS.UI.Menu.RequiresCommands", strings.requiresCommands); } this._showOnlyCommands(commands, true); }, show: function (anchor, placement, alignment) { /// /// /// Shows the Menu, if hidden, regardless of other states. /// /// /// The DOM element, or ID of a DOM element, to anchor the Menu. This parameter overrides the anchor property for this method call only. /// /// /// The placement of the Menu to the anchor: 'auto' (default), 'top', 'bottom', 'left', or 'right'. This parameter overrides the placement /// property for this method call only. /// /// /// For 'top' or 'bottom' placement, the alignment of the Menu to the anchor's edge: 'center' (default), 'left', or 'right'. This parameter /// overrides the alignment property for this method call only. /// /// /// // Just call private version to make appbar flags happy this._writeProfilerMark("show,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndShow(). this._show(anchor, placement, alignment); }, _show: function Menu_show(anchor, placement, alignment) { // Before we show, we also need to check for children flyouts needing anchors this._checkForFlyoutCommands(); // Call flyout show this._baseFlyoutShow(anchor, placement, alignment); // We need to check for toggles after we send the beforeshow event, // so the developer has a chance to show or hide more commands. // Flyout's _findPosition will make that call. }, _addCommand: function Menu_addCommand(command) { if (!command) { throw new WinJS.ErrorFromName("WinJS.UI.Menu.NullCommand", strings.nullCommand); } // See if it's a command already if (!command._element) { // Not a command, so assume it's options for a command command = new WinJS.UI.MenuCommand(null, command); } // If we were attached somewhere else, detach us if (command._element.parentElement) { command._element.parentElement.removeChild(command._element); } // Reattach us this._element.appendChild(command._element); }, // Called by flyout's _findPosition so that application can update it status // we do the test and we can then fix this last-minute before showing. _checkToggle: function Menu_checkToggle() { var toggles = this._element.querySelectorAll(".win-command[aria-checked]"); var hasToggle = false; if (toggles) { for (var i = 0; i < toggles.length; i++) { if (toggles[i] && toggles[i].winControl && !toggles[i].winControl.hidden) { // Found a visible toggle control hasToggle = true; break; } } } if (hasToggle) { WinJS.Utilities.addClass(this._element, menuToggleClass); } else { WinJS.Utilities.removeClass(this._element, menuToggleClass); } }, _checkForFlyoutCommands: function Menu_checkForFlyoutCommands() { var commands = this._element.querySelectorAll(".win-command"); for (var count = 0; count < commands.length; count++) { if (commands[count].winControl) { // Remember our anchor in case it's a flyout commands[count].winControl._parentFlyout = this; } } }, _handleKeyDown: function Menu_handleKeyDown(event) { if (event.key === "Esc") { // Show a focus rect on what we move focus to this.winControl._keyboardInvoked = true; this.winControl._hide(); } else if ((event.key === "Spacebar" || event.key === "Enter") && (this === document.activeElement)) { event.preventDefault(); this.winControl.hide(); } else if (event.key === "Up") { var that = this; thisWinUI.Menu._focusOnPreviousElement(that); // Prevent the page from scrolling event.preventDefault(); } else if (event.key === "Down") { that = this; thisWinUI.Menu._focusOnNextElement(that); // Prevent the page from scrolling event.preventDefault(); } else if (event.key === "Tab") { event.preventDefault(); } }, _writeProfilerMark: function Menu_writeProfilerMark(text) { msWriteProfilerMark("WinJS.UI.Menu:" + this._id + ":" + text); } }); // Statics // Set focus to next focusable element in the menu (loop if necessary). // Note: The loop works by first setting focus to the menu itself. If the menu is // what had focus before, then we break. Otherwise we try the first child next. // Focus remains on the menu if nothing is focusable. Menu._focusOnNextElement = function (menu) { var _currentElement = document.activeElement; do { if (_currentElement === menu) { _currentElement = _currentElement.firstElementChild; } else { _currentElement = _currentElement.nextElementSibling; } if (_currentElement) { _currentElement.focus(); } else { _currentElement = menu; } } while (_currentElement !== document.activeElement) }; // Set focus to previous focusable element in the menu (loop if necessary). // Note: The loop works by first setting focus to the menu itself. If the menu is // what had focus before, then we break. Otherwise we try the last child next. // Focus remains on the menu if nothing is focusable. Menu._focusOnPreviousElement = function (menu) { var _currentElement = document.activeElement; do { if (_currentElement === menu) { _currentElement = _currentElement.lastElementChild; } else { _currentElement = _currentElement.previousElementSibling; } if (_currentElement) { _currentElement.focus(); } else { _currentElement = menu; } } while (_currentElement !== document.activeElement) }; return Menu; }) }); })(WinJS); // Menu Command /// appbar,appbars,Flyout,Flyouts,onclick,Statics (function menuCommandInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// /// Represents a command to be displayed in a Menu. MenuCommand objects provide button, toggle button, flyout button, /// or separator functionality for Menu controls. /// /// /// /// /// /// ]]> /// The MenuCommand control itself /// /// /// MenuCommand: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; // Class Names var menuCommandClass = "win-command"; var typeSeparator = "separator"; var typeButton = "button"; var typeToggle = "toggle"; var typeFlyout = "flyout"; function _handleMenuClick(event) { var command = this.winControl; if (command) { var hideParent = true; if (command._type === typeToggle) { command.selected = !command.selected; } else if (command._type === typeFlyout && command._flyout) { var flyout = command._flyout; // Flyout may not have processAll'd, so this may be a DOM object if (typeof flyout === "string") { flyout = document.getElementById(flyout); } if (!flyout.show) { flyout = flyout.winControl; } if (flyout && flyout.show) { if (command._parentFlyout) { hideParent = false; flyout.show(command._parentFlyout._currentAnchor, command._parentFlyout._currentPlacement, command._parentFlyout._currentAlignment); } else { flyout.show(this); } } } if (command.onclick) { command.onclick(event); } // Dismiss parent flyout if (hideParent && command._parentFlyout) { command._parentFlyout.hide(); } } } function _handleMouseOver(event) { if (this && this.focus) { this.focus(); this.addEventListener("mousemove", _handleMouseMove, false); } } function _handleMouseMove(event) { if (this && this.focus && this !== document.activeElement) { this.focus(); } } function _handleMouseOut(event) { var that = this; var parentFlyout = _getParentFlyout(that); if (parentFlyout && this === document.activeElement && WinJS.Utilities.hasClass(parentFlyout, "win-menu") && parentFlyout.focus) { // Menu gives focus to the menu itself parentFlyout.focus(); } else if (parentFlyout && this === document.activeElement && parentFlyout.children && parentFlyout.children.length > 0 && parentFlyout.children[0] && WinJS.Utilities.hasClass(parentFlyout.children[0], "win-firstdiv") && parentFlyout.children[0].focus) { // Flyout gives focus to firstDiv parentFlyout.children[0].focus(); } this.removeEventListener("mousemove", _handleMouseMove, false); } function _getParentFlyout(element) { while (element && !WinJS.Utilities.hasClass(element, "win-flyout")) { element = element.parentElement; } return element; } var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/menuCommandAriaLabel").value; }, get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; }, get badClick() { return WinJS.Resources._getWinJSString("ui/badClick").value; }, get badHrElement() { return WinJS.Resources._getWinJSString("ui/badHrElement").value; }, get badButtonElement() { return WinJS.Resources._getWinJSString("ui/badButtonElement").value; } }; return WinJS.Class.define(function MenuCommand_ctor(element, options) { /// /// /// Creates a new MenuCommand object. /// /// /// The DOM element that will host the control. /// /// /// The set of properties and values to apply to the new MenuCommand. /// /// /// A MenuCommand control. /// /// /// // Check to make sure we weren't duplicated if (element && element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.MenuCommand.DuplicateConstruction", strings.duplicateConstruction); } this._disposed = false; // Don't blow up if they didn't pass options if (!options) { options = {}; } // Need a type before we can create our element if (!options.type) { this._type = typeButton; } // Go ahead and create it, separator types look different than buttons // Don't forget to use passed in element if one was provided. this._element = element; if (options.type === typeSeparator) { this._createSeparator(); } else { // This will also set the icon & label this._createButton(); } WinJS.Utilities.addClass(this._element, "win-disposable"); // Remember ourselves this._element.winControl = this; // Attach our css class WinJS.Utilities.addClass(this._element, menuCommandClass); if (!options.selected && options.type === typeToggle) { // Make sure toggle's have selected false for CSS this.selected = false; } if (options.onclick) { this.onclick = options.onclick; } options.onclick = _handleMenuClick; WinJS.UI.setOptions(this, options); // Set our options if (this._type !== typeSeparator) { // Make sure we have an ARIA role var role = this._element.getAttribute("role"); if (role === null || role === "" || role === undefined) { role = "menuitem"; if (this._type === typeToggle) { role = "menuitemcheckbox"; } this._element.setAttribute("role", role); if (this._type === typeFlyout) { this._element.setAttribute("aria-haspopup", true); } } var label = this._element.getAttribute("aria-label"); if (label === null || label === "" || label === undefined) { this._element.setAttribute("aria-label", strings.ariaLabel); } } this._element.addEventListener("mouseover", _handleMouseOver, false); this._element.addEventListener("mouseout", _handleMouseOut, false); }, { /// /// Gets the ID of the MenuCommand. /// /// id: { get: function () { return this._element.id; }, set: function (value) { // we allow setting first time only. otherwise we ignore it. if (!this._element.id) { this._element.id = value; } } }, /// /// Gets the type of the MenuCommand. Possible values are "button", "toggle", "flyout", or "separator". /// /// type: { get: function () { return this._type; }, set: function (value) { // we allow setting first time only. otherwise we ignore it. if (!this._type) { if (value !== typeButton && value !== typeFlyout && value !== typeToggle && value !== typeSeparator) { this._type = typeButton; } else { this._type = value; } } } }, /// /// The label of the MenuCommand /// /// label: { get: function () { return this._label; }, set: function (value) { this._label = value; this._element.innerText = this.label; // Update aria-label this._element.setAttribute("aria-label", this.label); } }, /// /// Gets or sets the function to invoke when the command is clicked. /// /// onclick: { get: function () { return this._onclick; }, set: function (value) { if (value && typeof value !== "function") { throw new WinJS.ErrorFromName("WinJS.UI.MenuCommand.BadClick", WinJS.Resources._formatString(strings.badClick, "MenuCommand")); } this._onclick = value; } }, /// /// For flyout type MenuCommands, this property returns the WinJS.UI.Flyout that this command invokes. When setting this property, you can set /// it to the string ID of the Flyout, the DOM object that hosts the Flyout, or the Flyout object itself. /// /// flyout: { get: function () { // Resolve it to the flyout var flyout = this._flyout; if (typeof flyout === "string") { flyout = document.getElementById(flyout); } // If it doesn't have a .element, then we need to getControl on it if (flyout && !flyout.element) { flyout = flyout.winControl; } return flyout; }, set: function (value) { // Need to update aria-owns with the new ID. var id = value; if (id && typeof id !== "string") { // Our controls have .element properties if (id.element) { id = id.element; } // Hope it's a DOM element, get ID from DOM element if (id) { if (id.id) { id = id.id; } else { // No id, have to fake one id.id = id.uniqueID; id = id.id; } } } if (typeof id === "string") { this._element.setAttribute("aria-owns", id); } // Remember it this._flyout = value; } }, /// /// Gets or sets the selected state of a toggle button. This property is true if the toggle button is selected; otherwise, it's false. /// /// selected: { get: function () { // Ensure it's a boolean because we're using the DOM element to keep in-sync return this._element.getAttribute("aria-checked") === "true"; }, set: function (value) { this._element.setAttribute("aria-checked", !!value); } }, /// element: { get: function () { return this._element; } }, /// /// Gets or sets a value that indicates whether the MenuCommand is disabled. This value is true if the MenuCommand is disabled; otherwise, false. /// /// disabled: { get: function () { // Ensure it's a boolean because we're using the DOM element to keep in-sync return !!this._element.disabled; }, set: function (value) { this._element.disabled = !!value; } }, /// hidden: { get: function () { // Ensure it's a boolean because we're using the DOM element to keep in-sync return this._element.style.visibility === "hidden"; }, set: function (value) { var menuControl = thisWinUI._Overlay._getParentControlUsingClassName(this._element, "win-menu"); if (menuControl && !menuControl.hidden) { throw new WinJS.ErrorFromName("WinJS.UI.MenuCommand.CannotChangeHiddenProperty", WinJS.Resources._formatString(thisWinUI._Overlay.commonstrings.cannotChangeHiddenProperty, "Menu")); } var style = this._element.style; if (value) { style.visibility = "hidden"; style.display = "none"; } else { style.visibility = ""; style.display = "block"; } } }, /// /// Gets or sets the extra CSS class that is applied to the host DOM element. /// /// extraClass: { get: function () { return this._extraClass; }, set: function (value) { if (this._extraClass) { WinJS.Utilities.removeClass(this._element, this._extraClass); } this._extraClass = value; WinJS.Utilities.addClass(this._element, this._extraClass); } }, dispose: function () { /// /// /// Disposes this control. /// /// /// if (this._disposed) { return; } this._disposed = true; if (this._flyout) { this._flyout.dispose(); } }, addEventListener: function (type, listener, useCapture) { /// /// /// Registers an event handler for the specified event. /// /// The name of the event to register. /// The function that handles the event. /// /// Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. /// /// /// return this._element.addEventListener(type, listener, useCapture); }, removeEventListener: function (type, listener, useCapture) { /// /// /// Removes the specified event handler that the addEventListener method registered. /// /// The name of the event to remove. /// The event handler function to remove. /// /// Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. /// /// /// return this._element.removeEventListener(type, listener, useCapture); }, // Private properties _createSeparator: function MenuCommand_createSeparator() { // Make sure there's an input element if (!this._element) { this._element = document.createElement("hr"); } else { // Verify the input was an hr if (this._element.tagName !== "HR") { throw new WinJS.ErrorFromName("WinJS.UI.MenuCommand.BadHrElement", strings.badHrElement); } } }, _createButton: function MenuCommand_createButton() { // Make sure there's an input element if (!this._element) { this._element = document.createElement("button"); } else { // Verify the input was a button if (this._element.tagName !== "BUTTON") { throw new WinJS.ErrorFromName("WinJS.UI.MenuCommand.BadButtonElement", strings.badButtonElement); } this._element.innerHTML = ""; } // MenuCommand buttons need to look like this: //// this._element.type = "button"; // 'innertext' label is added later by caller } }); }) }); })(WinJS); (function searchboxInit(global) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// /// Enables the user to perform search queries and select suggestions. /// /// /// /// /// /// ]]> /// Raised when user or app changes the query text. /// Raised when user clicks on search glyph or presses Enter. /// Raised when user clicks one of the displayed suggestions. /// Raised when the system requests search suggestions from this app. /// /// Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. /// /// Styles the entire Search box control. /// Styles the query input box. /// Styles the search button. /// Styles the result suggestions flyout. /// Styles the result type suggestion. /// Styles the query type suggestion. /// /// Styles the separator type suggestion. /// /// /// Styles the currently selected suggestion. /// /// /// /// SearchBox: WinJS.Namespace._lazy(function () { var utilities = WinJS.Utilities; var createEvent = WinJS.Utilities._createEventProperty; // Enums var ClassName = { searchBox: "win-searchbox", searchBoxInput: "win-searchbox-input", searchBoxButton: "win-searchbox-button", searchBoxFlyout: "win-searchbox-flyout", searchBoxSuggestionResult: "win-searchbox-suggestion-result", searchBoxSuggestionQuery: "win-searchbox-suggestion-query", searchBoxSuggestionSeparator: "win-searchbox-suggestion-separator", searchBoxSuggestionSelected: "win-searchbox-suggestion-selected", searchBoxFlyoutHighlightText: "win-searchbox-flyout-highlighttext", searchBoxButtonInputFocus: "win-searchbox-button-input-focus", searchBoxInputFocus: "win-searchbox-input-focus", searchBoxSuggestionResultText: "win-searchbox-suggestion-result-text", searchBoxSuggestionResultDetailedText: "win-searchbox-suggestion-result-detailed-text", searchboxDisabled: "win-searchbox-disabled", searchboxHitHighlightSpan: "win-searchbox-hithighlight-span", }; var EventName = { querychanged: "querychanged", querysubmitted: "querysubmitted", resultsuggestionchosen: "resultsuggestionchosen", suggestionsrequested: "suggestionsrequested", receivingfocusonkeyboardinput: "receivingfocusonkeyboardinput" }; var SearchSuggestionKind = { Query: 0, Result: 1, Separator: 2 }; var strings = { get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; }, get invalidSearchBoxSuggestionKind() { return WinJS.Resources._getWinJSString("ui/invalidSearchBoxSuggestionKind").value; }, get ariaLabel() { return WinJS.Resources._getWinJSString("ui/searchBoxAriaLabel").value; }, get ariaLabelInputNoPlaceHolder() { return WinJS.Resources._getWinJSString("ui/searchBoxAriaLabelInputNoPlaceHolder").value; }, get ariaLabelInputPlaceHolder() { return WinJS.Resources._getWinJSString("ui/searchBoxAriaLabelInputPlaceHolder").value; }, get ariaLabelButton() { return WinJS.Resources._getWinJSString("ui/searchBoxAriaLabelButton").value; }, get ariaLabelQuery() { return WinJS.Resources._getWinJSString("ui/searchBoxAriaLabelQuery").value; }, get ariaLabelSeparator() { return WinJS.Resources._getWinJSString("ui/searchBoxAriaLabelSeparator").value; }, get ariaLabelResult() { return WinJS.Resources._getWinJSString("ui/searchBoxAriaLabelResult").value; } }; var SearchBox = WinJS.Class.define(function SearchBox_ctor(element, options) { /// /// /// Creates a new SearchBox. /// /// /// The DOM element that hosts the SearchBox. /// /// /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". For example, to provide a handler for the querychanged event, /// add a property named "onquerychanged" to the options object and set its value to the event handler. /// This parameter is optional. /// /// /// The new SearchBox. /// /// /// element = element || document.createElement("div"); if (element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.SearchBox.DuplicateConstruction", strings.duplicateConstruction); } element.winControl = this; // Elements this._domElement = null; this._inputElement = null; this._buttonElement = null; this._flyout = null; this._flyoutDivElement = null; this._repeaterDivElement = null; this._repeater = null; // Variables this._disposed = false; this._focusOnKeyboardInput = false; this._chooseSuggestionOnEnter = false; this._lastKeyPressLanguage = ""; // These are used to eliminate redundant query submitted events this._prevQueryText = ""; this._prevLinguisticDetails = this._createSearchQueryLinguisticDetails([], 0, 0, "", ""); this._prevCompositionStart = 0; this._prevCompositionLength = 0; this._isProcessingDownKey = false; this._isProcessingUpKey = false; this._isProcessingTabKey = false; this._isProcessingEnterKey = false; this._isFlyoutPointerDown = false; this._reflowImeOnPointerRelease = false; // Focus and selection related variables this._currentFocusedIndex = -1; this._currentSelectedIndex = -1; this._suggestionRendererBind = this._suggestionRenderer.bind(this); this._requestingFocusOnKeyboardInputHandlerBind = this._requestingFocusOnKeyboardInputHandler.bind(this); this._suggestionsRequestedHandlerBind = this._suggestionsRequestedHandler.bind(this); this._suggestionsChangedHandlerBind = this._suggestionsChangedHandler.bind(this); // Find out if we are in local compartment and if search APIs are available. this._searchSuggestionManager = null; this._searchSuggestions = null; // Get the search suggestion provider if it is available if ((window.Windows) && (Windows.ApplicationModel) && (Windows.ApplicationModel.Search) && (Windows.ApplicationModel.Search.Core) && (Windows.ApplicationModel.Search.Core.SearchSuggestionManager)) { this._searchSuggestionManager = new Windows.ApplicationModel.Search.Core.SearchSuggestionManager(); this._searchSuggestions = this._searchSuggestionManager.suggestions; } this._hitFinder = null; this._setElement(element); WinJS.UI.setOptions(this, options); this._setAccessibilityProperties(); WinJS.Utilities.addClass(element, "win-disposable"); }, { /// element: { get: function () { return this._domElement; } }, /// /// Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no /// other text in the input box. /// /// placeholderText: { get: function () { return this._inputElement.placeholder; }, set: function (value) { this._inputElement.placeholder = value; this._updateInputElementAriaLabel(); } }, /// /// Gets or sets the query text for the SearchBox. /// /// queryText: { get: function () { return this._inputElement.value; }, set: function (value) { this._inputElement.value = value; } }, /// /// Gets or sets a value that specifies whether search history is disabled for the SearchBox. The default value is false. /// /// searchHistoryDisabled: { get: function () { if (this._searchSuggestionManager) { return !this._searchSuggestionManager.searchHistoryEnabled; } else { return true; } }, set: function (value) { if (this._searchSuggestionManager) { this._searchSuggestionManager.searchHistoryEnabled = !value; } } }, /// /// Gets or sets the search history context for the SearchBox. The search history context string is used as a secondary key for storing search history. /// (The primary key is the AppId.) An app can use the search history context string to store different search histories based on the context of the application. /// If you don't set this property, the system assumes that all searches in your app occur in the same context. /// If you update this property while the search pane is open with suggestions showing, the changes won't take effect until the user enters the next character. /// /// searchHistoryContext: { get: function () { if (this._searchSuggestionManager) { return this._searchSuggestionManager.searchHistoryContext; } else { return ""; } }, set: function (value) { if (this._searchSuggestionManager) { this._searchSuggestionManager.searchHistoryContext = value; } } }, /// /// Enable automatically focusing the search box when the user types into the app window (off by default) While this is enabled, /// input on the current thread will be intercepted and redirected to the search box. Only textual input will trigger the search box to focus. /// The caller will continue to receive non-text keys (such as arrows, tab, etc /// This will also not affect WIN/CTRL/ALT key combinations (except for Ctrl-V for paste). /// If the client needs more to happen than just set focus in the box (make control visible, etc.), they will need to handle the event. /// If enabled, the app must be sure to disable this if the user puts focus in some other edit field. /// /// focusOnKeyboardInput: { get: function () { return this._focusOnKeyboardInput; }, set: function (value) { if (this._focusOnKeyboardInput && !value) { if (this._searchSuggestionManager) { this._searchSuggestionManager.removeEventListener("requestingfocusonkeyboardinput", this._requestingFocusOnKeyboardInputHandlerBind); } } else if (!this._focusOnKeyboardInput && !!value) { if (this._searchSuggestionManager) { this._searchSuggestionManager.addEventListener("requestingfocusonkeyboardinput", this._requestingFocusOnKeyboardInputHandlerBind); } } this._focusOnKeyboardInput = !!value; } }, /// /// Gets or sets whether the first suggestion is chosen when the user presses Enter. /// When set to true, as the user types in the search box, a focus rectangle is drawn on the first search suggestion /// (if present and no IME composition in progress). Pressing enter will behave the same as if clicked on the focused suggestion, /// and the down arrow key press will put real focus to the second suggestion and the up arrow key will remove focus. /// /// chooseSuggestionOnEnter: { get: function () { return this._chooseSuggestionOnEnter; }, set: function (value) { this._chooseSuggestionOnEnter = !!value; this._updateSearchButtonClass(); } }, /// /// Gets or sets a value that specifies whether the SearchBox is disabled. /// /// disabled: { get: function () { return this._inputElement.disabled; }, set: function (value) { if (this._inputElement.disabled === !!value) { return; } if (!value) { // Enable control this._inputElement.disabled = false; this._buttonElement.disabled = false; this._domElement.disabled = false; utilities.removeClass(this.element, ClassName.searchboxDisabled); if (document.activeElement === this.element) { try { this._inputElement.setActive(); } catch (e) { } } } else { // Disable control if (this._isFlyoutShown) { this._hideFlyout(); } utilities.addClass(this.element, ClassName.searchboxDisabled); this._inputElement.disabled = true; this._buttonElement.disabled = true; this._domElement.disabled = true; } } }, // Methods setLocalContentSuggestionSettings: function SearchBox_setLocalContentSuggestionSettings(settings) { /// /// /// Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that /// the system uses to locate and filter these suggestions. /// /// /// The new settings for local content suggestions. /// /// /// if (this._searchSuggestionManager) { this._searchSuggestionManager.setLocalContentSuggestionSettings(settings); } }, dispose: function SearchBox() { /// /// /// Disposes this control. /// /// /// if (this._disposed) { return; } // Cancel pending promises. if (this._flyoutOpenPromise) { this._flyoutOpenPromise.cancel(); } // Detach winrt events. if (this._focusOnKeyboardInput) { if (this._searchSuggestionManager) { this._searchSuggestionManager.removeEventListener("requestingfocusonkeyboardinput", this._requestingFocusOnKeyboardInputHandlerBind); } } if (this._searchSuggestions) { this._searchSuggestions.removeEventListener("vectorchanged", this._suggestionsChangedHandlerBind); } if (this._searchSuggestionManager) { this._searchSuggestionManager.removeEventListener("suggestionsrequested", this._suggestionsRequestedHandlerBind); } this._searchSuggestionManager = null; this._searchSuggestions = null; this._hitFinder = null; this._disposed = true; }, /// /// Raised when user or app changes the query text. /// /// onquerychanged: createEvent(EventName.querychanged), /// /// Raised when user clicks on search glyph or presses enter button. /// /// onquerysubmitted: createEvent(EventName.querysubmitted), /// /// Raised when user clicks on one of the suggestions displayed. /// /// onresultsuggestionchosen: createEvent(EventName.resultsuggestionchosen), /// /// Raised when Windows requests search suggestions from the app. /// /// onsuggestionsrequested: createEvent(EventName.suggestionsrequested), // Private methods _isFlyoutShown: function SearchBox_isFlyoutShown() { return (this._flyoutDivElement.style.display !== "none"); }, _isFlyoutBelow: function SearchBox_isFlyoutBelow() { if (this._flyoutDivElement.getBoundingClientRect().top > this._inputElement.getBoundingClientRect().top) { return true; } return false; }, _getFlyoutTop: function SearchBox_getFlyoutTop() { if (this._isFlyoutBelow()) { return this._inputElement.getBoundingClientRect().bottom; } var popupHeight = this._flyoutDivElement.getBoundingClientRect().bottom - this._flyoutDivElement.getBoundingClientRect().top; return this._inputElement.getBoundingClientRect().top - popupHeight; }, _getFlyoutBottom: function SearchBox_getFlyoutBottom() { if (this._isFlyoutBelow()) { var popupHeight = this._flyoutDivElement.getBoundingClientRect().bottom - this._flyoutDivElement.getBoundingClientRect().top; return this._inputElement.getBoundingClientRect().bottom + popupHeight; } return this._inputElement.getBoundingClientRect().top; }, _updateFlyoutTopAndTouchAction: function SearchBox_updateFlyoutTopAndTouchAction() { var popupHeight = this._flyoutDivElement.getBoundingClientRect().bottom - this._flyoutDivElement.getBoundingClientRect().top; if (!this._isFlyoutBelow()) { this._flyoutDivElement.style.top = "-" + popupHeight + "px"; } // ms-scroll-chaining:none will still chain scroll parent element if child div does // not have a scroll bar. Prevent this by setting and updating touch action if (this._flyoutDivElement.scrollHeight > popupHeight) { this._flyoutDivElement.style.touchAction = "pan-y"; } else { this._flyoutDivElement.style.touchAction = "none"; } }, _showFlyout: function SearchBox_showFlyout() { if (this._isFlyoutShown()) { return; } if (this._suggestionsData.length === 0) { return; } this._flyoutDivElement.style.display = "block"; // Display above vs below var minPopupHeight = this._flyoutDivElement.clientHeight; if (minPopupHeight < WinJS.UI.SearchBox._Constants.MIN_POPUP_HEIGHT) { minPopupHeight = WinJS.UI.SearchBox._Constants.MIN_POPUP_HEIGHT; } var flyoutRect = this._flyoutDivElement.getBoundingClientRect(); var searchBoxRect = this.element.getBoundingClientRect(); var popupHeight = flyoutRect.bottom - flyoutRect.top; var popupWidth = flyoutRect.right - flyoutRect.left; var searchBoxWidth = searchBoxRect.right - searchBoxRect.left; var documentClientHeight = document.documentElement.clientHeight; var documentClientWidth = document.documentElement.clientWidth; var searchBoxClientHeight = this.element.clientHeight; var searchBoxClientLeft = this.element.clientLeft; var flyoutBelowSearchBox = true; if ((searchBoxRect.bottom + minPopupHeight) <= documentClientHeight) { // There is enough space below. Show below this._flyoutDivElement.style.top = searchBoxClientHeight + "px"; } else if ((searchBoxRect.top - minPopupHeight) >= 0) { // There is enough space above. Show above this._flyoutDivElement.style.top = "-" + popupHeight + "px"; flyoutBelowSearchBox = false; } else { // Not enough space above or below. Show below. this._flyoutDivElement.style.top = searchBoxClientHeight + "px"; } // Align left vs right edge var alignRight; if (window.getComputedStyle(this._flyoutDivElement).direction === "rtl") { // RTL: Align to the right edge if there is enough space to the left of the search box's // right edge, or if there is not enough space to fit the flyout aligned to either edge. alignRight = ((searchBoxRect.right - popupWidth) >= 0) || ((searchBoxRect.left + popupWidth) > documentClientWidth); } else { // LTR: Align to the right edge if there isn't enough space to the right of the search box's // left edge, but there is enough space to the left of the search box's right edge. alignRight = ((searchBoxRect.left + popupWidth) > documentClientWidth) && ((searchBoxRect.right - popupWidth) >= 0); } if (alignRight) { this._flyoutDivElement.style.left = (searchBoxWidth - popupWidth - searchBoxClientLeft) + "px"; } else { this._flyoutDivElement.style.left = "-" + searchBoxClientLeft + "px"; } // ms-scroll-chaining:none will still chain scroll parent element if child div does // not have a scroll bar. Prevent this by setting and updating touch action if (this._flyoutDivElement.scrollHeight > popupHeight) { this._flyoutDivElement.style.touchAction = "pan-y"; } else { this._flyoutDivElement.style.touchAction = "none"; } this._addFlyoutIMEPaddingIfRequired(); if (this._flyoutOpenPromise) { this._flyoutOpenPromise.cancel(); this._flyoutOpenPromise = null; } var animationKeyframe = flyoutBelowSearchBox ? "WinJS-flyoutBelowSearchBox-showPopup" : "WinJS-flyoutAboveSearchBox-showPopup"; this._flyoutOpenPromise = WinJS.UI.Animation.showPopup(this._flyoutDivElement, { top: "0px", left: "0px", keyframe: animationKeyframe }); }, _hideFlyout: function SearchBox_hideFlyout() { if (this._isFlyoutShown()) { this._flyoutDivElement.style.display = "none"; this._updateSearchButtonClass(); } }, _addNewSpan: function SearchBox_addNewSpan(element, innerText, insertBefore) { // Adds new span element with specified inner text as child to element, placed before insertBefore var spanElement = document.createElement("span"); spanElement.innerText = innerText; spanElement.setAttribute("aria-hidden", "true"); utilities.addClass(spanElement, ClassName.searchboxHitHighlightSpan); element.insertBefore(spanElement, insertBefore) return spanElement; }, _addHitHighlightedText: function SearchBox_addHitHighlightedText(element, item, text) { if (text) { // Remove any existing hit highlighted text spans utilities.query("." + ClassName.searchboxHitHighlightSpan, element).forEach(function (childElement) { childElement.parentNode.removeChild(childElement); }); // Insert spans at the front of element var firstChild = element.firstChild; var hitsProvided = item.hits; if ((!hitsProvided) && (this._hitFinder !== null) && (item.kind !== SearchSuggestionKind.Separator)) { hitsProvided = this._hitFinder.find(text); } var hits = WinJS.UI.SearchBox._sortAndMergeHits(hitsProvided); var lastPosition = 0; for (var i = 0; i < hits.length; i++) { var hit = hits[i]; // Add previous normal text this._addNewSpan(element, text.substring(lastPosition, hit.startPosition), firstChild); lastPosition = hit.startPosition + hit.length; // Add hit highlighted text var spanHitHighlightedText = this._addNewSpan(element, text.substring(hit.startPosition, lastPosition), firstChild); utilities.addClass(spanHitHighlightedText, ClassName.searchBoxFlyoutHighlightText); } // Add final normal text if (lastPosition < text.length) { this._addNewSpan(element, text.substring(lastPosition), firstChild); } } }, _findSuggestionElementIndex: function SearchBox_findSuggestionElementIndex(curElement) { if (curElement) { for (var i = 0; i < this._suggestionsData.length; i++) { if (this._repeater.elementFromIndex(i) === curElement) { return i; } } } return -1; }, _isSuggestionSelectable: function SearchBox_isSuggestionSelectable(suggestion) { return ((suggestion.kind === SearchSuggestionKind.Query) || (suggestion.kind === SearchSuggestionKind.Result)); }, _findNextSuggestionElementIndex: function SearchBox_findNextSuggestionElementIndex(curIndex) { // Returns -1 if there are no focusable elements after curIndex // Returns first element if curIndex < 0 var startIndex = curIndex + 1; if (startIndex < 0) { startIndex = 0; } for (var i = startIndex; i < this._suggestionsData.length; i++) { if ((this._repeater.elementFromIndex(i)) && (this._isSuggestionSelectable(this._suggestionsData.getAt(i)))) { return i; } } return -1; }, _findPreviousSuggestionElementIndex: function SearchBox_findPreviousSuggestionElementIndex(curIndex) { // Returns -1 if there are no focusable elements before curIndex // Returns last element if curIndex >= suggestionsdata.length var startIndex = curIndex - 1; if (startIndex >= this._suggestionsData.length) { startIndex = this._suggestionsData.length - 1; } for (var i = startIndex; i >= 0; i--) { if ((this._repeater.elementFromIndex(i)) && (this._isSuggestionSelectable(this._suggestionsData.getAt(i)))) { return i; } } return -1; }, _trySetFocusOnSuggestionIndex: function SearchBox_trySetFocusOnSuggestionIndex(index) { try { this._repeater.elementFromIndex(index).focus(); } catch (e) { } }, _updateFakeFocus: function SearchBox_updateFakeFocus() { var firstElementIndex; if (this._isFlyoutShown() && (this._chooseSuggestionOnEnter)) { firstElementIndex = this._findNextSuggestionElementIndex(-1); } else { // This will clear the fake focus. firstElementIndex = -1; } this._selectSuggestionAtIndex(firstElementIndex); }, _updateSearchButtonClass: function SearchBox_updateSearchButtonClass() { if ((this._currentSelectedIndex !== -1) || (document.activeElement !== this._inputElement)) { // Focus is not in input. remove class utilities.removeClass(this._buttonElement, ClassName.searchBoxButtonInputFocus); } else if (document.activeElement === this._inputElement) { utilities.addClass(this._buttonElement, ClassName.searchBoxButtonInputFocus); } }, _selectSuggestionAtIndex: function SearchBox_selectSuggestionAtIndex(indexToSelect) { // Sets focus on the specified element and removes focus from others. // Clears selection if index is outside of suggestiondata index range. var curElement = null; for (var i = 0; i < this._suggestionsData.length; i++) { curElement = this._repeater.elementFromIndex(i); if (i !== indexToSelect) { utilities.removeClass(curElement, ClassName.searchBoxSuggestionSelected); curElement.setAttribute("aria-selected", "false"); } else { utilities.addClass(curElement, ClassName.searchBoxSuggestionSelected); this._scrollToView(curElement); curElement.setAttribute("aria-selected", "true"); } } this._updateSearchButtonClass(); this._currentSelectedIndex = indexToSelect; if (curElement) { this._inputElement.setAttribute("aria-activedescendant", this._repeaterDivElement.id + indexToSelect); } else if (this._inputElement.hasAttribute("aria-activedescendant")) { this._inputElement.removeAttribute("aria-activedescendant"); } }, _scrollToView: function SearchBox_scrollToView(targetElement) { var popupHeight = this._flyoutDivElement.getBoundingClientRect().bottom - this._flyoutDivElement.getBoundingClientRect().top; if ((targetElement.offsetTop + targetElement.offsetHeight) > (this._flyoutDivElement.scrollTop + popupHeight)) { // Element to scroll is below popup visible area var scrollDifference = (targetElement.offsetTop + targetElement.offsetHeight) - (this._flyoutDivElement.scrollTop + popupHeight); this._flyoutDivElement.msZoomTo({ contentX: 0, contentY: (this._flyoutDivElement.scrollTop + scrollDifference), viewportX: 0, viewportY: 0 }); } else if (targetElement.offsetTop < this._flyoutDivElement.scrollTop) { // Element to scroll is above popup visible area this._flyoutDivElement.msZoomTo({ contentX: 0, contentY: targetElement.offsetTop, viewportX: 0, viewportY: 0 }); } }, _querySuggestionRenderer: function SearchBox_querySuggestionRenderer(item) { var root = document.createElement("div"); this._addHitHighlightedText(root, item, item.text); root.title = item.text; utilities.addClass(root, ClassName.searchBoxSuggestionQuery); var that = this; root.addEventListener('click', function (ev) { that._inputElement.focus(); that._processSuggestionChosen(item, ev); }); root.setAttribute("role", "option"); var ariaLabel = WinJS.Resources._formatString(strings.ariaLabelQuery, item.text); root.setAttribute("aria-label", ariaLabel); return root; }, _separatorSuggestionRenderer: function SearchBox_separatorSuggestionRenderer(item) { var root = document.createElement("div"); if (item.text.length > 0) { var textElement = document.createElement("div"); textElement.innerText = item.text; textElement.title = item.text; textElement.setAttribute("aria-hidden", "true"); root.appendChild(textElement); } root.insertAdjacentHTML("beforeend", "
"); utilities.addClass(root, ClassName.searchBoxSuggestionSeparator); root.setAttribute("role", "separator"); var ariaLabel = WinJS.Resources._formatString(strings.ariaLabelSeparator, item.text); root.setAttribute("aria-label", ariaLabel); return root; }, _resultSuggestionRenderer: function SearchBox_resultSuggestionRenderer(item) { var root = document.createElement("div"); var image = new Image; image.style.opacity = 0; var loadImage = function (url) { function onload() { image.removeEventListener("load", onload, false); WinJS.UI.Animation.fadeIn(image); } image.addEventListener("load", onload, false); image.src = url; }; if (item.image !== null) { item.image.openReadAsync().then(function (streamWithContentType) { if (streamWithContentType !== null) { loadImage(URL.createObjectURL(streamWithContentType, { oneTimeOnly: true })); } }); } else if (item.imageUrl != null) { loadImage(item.imageUrl); } image.setAttribute("aria-hidden", "true"); root.appendChild(image); var divElement = document.createElement("div"); utilities.addClass(divElement, ClassName.searchBoxSuggestionResultText); this._addHitHighlightedText(divElement, item, item.text); divElement.title = item.text; divElement.setAttribute("aria-hidden", "true"); root.appendChild(divElement); var brElement = document.createElement("br"); divElement.appendChild(brElement); var divDetailElement = document.createElement("span"); utilities.addClass(divDetailElement, ClassName.searchBoxSuggestionResultDetailedText); this._addHitHighlightedText(divDetailElement, item, item.detailText); divDetailElement.title = item.detailText; divDetailElement.setAttribute("aria-hidden", "true"); divElement.appendChild(divDetailElement); utilities.addClass(root, ClassName.searchBoxSuggestionResult); var that = this; root.addEventListener('click', function (ev) { that._inputElement.focus(); that._processSuggestionChosen(item, ev); }); root.setAttribute("role", "option"); var ariaLabel = WinJS.Resources._formatString(strings.ariaLabelResult, item.text, item.detailText); root.setAttribute("aria-label", ariaLabel); return root; }, _suggestionRenderer: function SearchBox_suggestionRenderer(item) { var root = null; if (!item) { return root; } if (item.kind === SearchSuggestionKind.Query) { root = this._querySuggestionRenderer(item); } else if (item.kind === SearchSuggestionKind.Separator) { root = this._separatorSuggestionRenderer(item); } else if (item.kind === SearchSuggestionKind.Result) { root = this._resultSuggestionRenderer(item); } else { throw new WinJS.ErrorFromName("WinJS.UI.SearchBox.invalidSearchBoxSuggestionKind", strings.invalidSearchBoxSuggestionKind); } return root; }, _setElement: function SearchBox_setElement(element) { this._domElement = element; utilities.addClass(this._domElement, ClassName.searchBox); this._inputElement = document.createElement("input"); this._inputElement.type = "search"; utilities.addClass(this._inputElement, ClassName.searchBoxInput); this._buttonElement = document.createElement("div"); this._buttonElement.tabIndex = -1; utilities.addClass(this._buttonElement, ClassName.searchBoxButton); this._flyoutDivElement = document.createElement('div'); utilities.addClass(this._flyoutDivElement, ClassName.searchBoxFlyout); this._repeaterDivElement = document.createElement('div'); this._suggestionsData = new WinJS.Binding.List(); this._repeater = new WinJS.UI.Repeater(this._repeaterDivElement, { data: this._suggestionsData, template: this._suggestionRendererBind }); this._domElement.appendChild(this._inputElement); this._domElement.appendChild(this._buttonElement); this._domElement.appendChild(this._flyoutDivElement); this._flyoutDivElement.appendChild(this._repeaterDivElement); this._hideFlyout(); this._wireupUserEvents(); this._wireupWinRTEvents(); this._wireupRepeaterEvents(); }, _setAccessibilityProperties: function Searchbox_setAccessibilityProperties() { // Set up accessibility properties var label = this._domElement.getAttribute("aria-label"); if (!label) { this._domElement.setAttribute("aria-label", strings.ariaLabel); } this._domElement.setAttribute("role", "group"); this._updateInputElementAriaLabel(); this._inputElement.setAttribute("role", "textbox"); this._buttonElement.setAttribute("role", "button"); this._buttonElement.setAttribute("aria-label", strings.ariaLabelButton); this._repeaterDivElement.setAttribute("role", "listbox"); WinJS.UI._ensureId(this._repeaterDivElement); this._inputElement.setAttribute("aria-controls", this._repeaterDivElement.id); this._repeaterDivElement.setAttribute("aria-live", "polite"); }, _updateInputElementAriaLabel: function Searchbox_updateInputElementAriaLabel() { var ariaLabel = strings.ariaLabelInputNoPlaceHolder; if (this._inputElement.placeholder && this._inputElement.placeholder) { ariaLabel = WinJS.Resources._formatString(strings.ariaLabelInputPlaceHolder, this._inputElement.placeholder); } this._inputElement.setAttribute("aria-label", ariaLabel); }, _submitQuery: function Searchbox_submitQuery(queryText, fillLinguisticDetails, event) { if (this._disposed) { return; } // get the most up to date value of the input langauge from WinRT if available if ((window.Windows) && (Windows.Globalization) && (Windows.Globalization.Language)) { this._lastKeyPressLanguage = Windows.Globalization.Language.currentInputMethodLanguageTag; } this._fireEvent(WinJS.UI.SearchBox._EventName.querysubmitted, { language: this._lastKeyPressLanguage, linguisticDetails: this._getLinguisticDetails(true /*useCache*/, fillLinguisticDetails), // allow caching, but generate empty linguistic details if suggestion is used queryText: queryText, keyModifiers: WinJS.UI.SearchBox._getKeyModifiers(event) }); if (this._searchSuggestionManager) { this._searchSuggestionManager.addToHistory( this._inputElement.value, this._lastKeyPressLanguage ); } }, _processSuggestionChosen: function Searchbox_processSuggestionChosen(item, event) { this.queryText = item.text; if (item.kind === SearchSuggestionKind.Query) { this._submitQuery(item.text, false /*fillLinguisticDetails*/, event); // force empty linguistic details since explicitly chosen suggestion from list } else if (item.kind === SearchSuggestionKind.Result) { this._fireEvent(WinJS.UI.SearchBox._EventName.resultsuggestionchosen, { tag: item.tag, keyModifiers: WinJS.UI.SearchBox._getKeyModifiers(event), storageFile: null }); } this._hideFlyout(); }, _buttonClickHandler: function SearchBox_buttonClickHandler(event) { this._inputElement.focus(); this._submitQuery(this._inputElement.value, true /*fillLinguisticDetails*/, event); this._hideFlyout(); }, _inputOrImeChangeHandler: function SearchBox_inputImeChangeHandler(event) { var isButtonDown = this._buttonElement.msMatchesSelector(":active"); // swallow the IME change event that gets fired when composition is ended due to keyboarding down to the suggestion list & mouse down on the button if (!this._isProcessingImeFocusLossKey() && !isButtonDown && !this._isFlyoutPointerDown) { var linguisticDetails = this._getLinguisticDetails(false /*useCache*/, true /*createFilled*/); // never cache on explicit user changes var hasLinguisticDetailsChanged = this._hasLinguisticDetailsChanged(linguisticDetails); // updates this._prevLinguisticDetails // Keep the previous composition cache up to date, execpt when composition ended with no text change and alternatives are kept. // In that case, we need to use the cached values to correctly generate the query prefix/suffix for substituting alternatives, but still report to the client that the composition has ended (via start & length of composition of 0) if ((this._inputElement.value !== this._prevQueryText) || (this._prevCompositionLength == 0) || (linguisticDetails.queryTextCompositionLength > 0)) { this._prevCompositionStart = linguisticDetails.queryTextCompositionStart; this._prevCompositionLength = linguisticDetails.queryTextCompositionLength; } if ((this._prevQueryText === this._inputElement.value) && !hasLinguisticDetailsChanged) { // Sometimes the input change is fired even if there is no change in input. // Swallow event in those cases. return; } this._prevQueryText = this._inputElement.value; // get the most up to date value of the input langauge from WinRT if available if ((window.Windows) && (Windows.Globalization) && (Windows.Globalization.Language)) { this._lastKeyPressLanguage = Windows.Globalization.Language.currentInputMethodLanguageTag; } if ((window.Windows) && (Windows.Data) && (Windows.Data.Text) && (Windows.Data.Text.SemanticTextQuery)) { if (this._inputElement.value !== "") { this._hitFinder = new Windows.Data.Text.SemanticTextQuery(this._inputElement.value, this._lastKeyPressLanguage); } else { this._hitFinder = null; } } this._fireEvent(WinJS.UI.SearchBox._EventName.querychanged, { language: this._lastKeyPressLanguage, queryText: this._inputElement.value, linguisticDetails: linguisticDetails }); var queryTextCompositionStart = null; var queryTextCompositionLength = null; var queryTextAlternatives = null; if (this._searchSuggestionManager) { this._searchSuggestionManager.setQuery( this._inputElement.value, this._lastKeyPressLanguage, linguisticDetails ); } } }, _createSearchQueryLinguisticDetails: function SearchBox_createSearchQueryLinguisticDetails(compositionAlternatives, compositionStartOffset, compositionLength, queryTextPrefix, queryTextSuffix) { var linguisticDetails = null; // The linguistic alternatives we receive are only for the composition string being composed. We need to provide the linguistic alternatives // in the form of the full query text with alternatives embedded. var fullCompositionAlternatives = []; for (var i = 0; i < compositionAlternatives.length; i++) { fullCompositionAlternatives[i] = queryTextPrefix + compositionAlternatives[i] + queryTextSuffix; } if ((window.Windows) && (Windows.ApplicationModel) && (Windows.ApplicationModel.Search) && (Windows.ApplicationModel.Search.SearchQueryLinguisticDetails)) { linguisticDetails = new Windows.ApplicationModel.Search.SearchQueryLinguisticDetails(fullCompositionAlternatives, compositionStartOffset, compositionLength); } else { // If we're in web compartment, create a script version of the WinRT SearchQueryLinguisticDetails object linguisticDetails = { queryTextAlternatives: fullCompositionAlternatives, queryTextCompositionStart: compositionStartOffset, queryTextCompositionLength: compositionLength }; } return linguisticDetails; }, _getLinguisticDetails: function SearchBox_getLinguisticDetails(useCache, createFilled) { // createFilled=false always creates an empty linguistic details object, otherwise generate it or use the cache var linguisticDetails = null; if ((this._inputElement.value === this._prevQueryText) && useCache && this._prevLinguisticDetails && createFilled) { linguisticDetails = this._prevLinguisticDetails; } else { var compositionAlternatives = []; var compositionStartOffset = 0; var compositionLength = 0; var queryTextPrefix = ""; var queryTextSuffix = ""; if (createFilled && this._inputElement.msGetInputContext && this._inputElement.msGetInputContext().getCompositionAlternatives) { var context = this._inputElement.msGetInputContext(); compositionAlternatives = context.getCompositionAlternatives(); compositionStartOffset = context.compositionStartOffset; compositionLength = context.compositionEndOffset - context.compositionStartOffset; if ((this._inputElement.value !== this._prevQueryText) || (this._prevCompositionLength == 0) || (compositionLength > 0)) { queryTextPrefix = this._inputElement.value.substring(0, compositionStartOffset); queryTextSuffix = this._inputElement.value.substring(compositionStartOffset + compositionLength); } else { // composition ended, but alternatives have been kept, need to reuse the previous query prefix/suffix, but still report to the client that the composition has ended (start & length of composition of 0) queryTextPrefix = this._inputElement.value.substring(0, this._prevCompositionStart); queryTextSuffix = this._inputElement.value.substring(this._prevCompositionStart + this._prevCompositionLength); } } linguisticDetails = this._createSearchQueryLinguisticDetails(compositionAlternatives, compositionStartOffset, compositionLength, queryTextPrefix, queryTextSuffix); } return linguisticDetails; }, _handleTabKeyDown: function SearchBox_handleTabKeyDown(event) { var closeFlyout = true; if (event.shiftKey) { // If focus is not in input if (this._currentFocusedIndex !== -1) { // Remove selection. this._currentFocusedIndex = -1; this._selectSuggestionAtIndex(this._currentFocusedIndex); this._updateSearchButtonClass(); event.preventDefault(); event.stopPropagation(); closeFlyout = false; } } else if (this._currentFocusedIndex === -1) { if (this._isFlyoutBelow()) { // Move to first element this._currentFocusedIndex = this._findNextSuggestionElementIndex(this._currentFocusedIndex); } else { // Move to last element this._currentFocusedIndex = this._findPreviousSuggestionElementIndex(this._suggestionsData.length); } if (this._currentFocusedIndex != -1) { this._selectSuggestionAtIndex(this._currentFocusedIndex); this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); this._updateSearchButtonClass(); event.preventDefault(); event.stopPropagation(); closeFlyout = false; } } if (closeFlyout) { this._hideFlyout(); } }, _keyDownHandler: function SearchBox_keyDownHandler(event) { this._lastKeyPressLanguage = event.locale; if (event.key === "Tab") { this._isProcessingTabKey = true; } else if (event.key === "Up") { this._isProcessingUpKey = true; } else if (event.key === "Down") { this._isProcessingDownKey = true; } else if ((event.key === "Enter") && (event.locale === "ko")) { this._isProcessingEnterKey = true; } // Ignore keys handled by ime. if (event.keyCode !== WinJS.UI.SearchBox._Constants.IME_HANDLED_KEYCODE) { if (event.key === "Tab") { this._handleTabKeyDown(event); } else if (event.key === "Esc") { // If focus is not in input if (this._currentFocusedIndex !== -1) { this.queryText = this._prevQueryText; this._currentFocusedIndex = -1; this._selectSuggestionAtIndex(this._currentFocusedIndex); this._updateSearchButtonClass(); event.preventDefault(); event.stopPropagation(); } else if (this.queryText !== "") { this.queryText = ""; this._inputOrImeChangeHandler(null); this._updateSearchButtonClass(); event.preventDefault(); event.stopPropagation(); } } else if (event.key === "Up") { var prevIndex; if (this._currentSelectedIndex !== -1) { prevIndex = this._findPreviousSuggestionElementIndex(this._currentSelectedIndex); // Restore user entered query when user navigates back to input. if (prevIndex === -1) { this.queryText = this._prevQueryText; } } else { prevIndex = this._findPreviousSuggestionElementIndex(this._suggestionsData.length); } this._currentFocusedIndex = prevIndex; this._selectSuggestionAtIndex(prevIndex); this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); this._updateSearchButtonClass(); event.preventDefault(); event.stopPropagation(); } else if (event.key === "Down") { var nextIndex = this._findNextSuggestionElementIndex(this._currentSelectedIndex); // Restore user entered query when user navigates back to input. if ((this._currentSelectedIndex !== -1) && (nextIndex === -1)) { this.queryText = this._prevQueryText; } this._currentFocusedIndex = nextIndex; this._selectSuggestionAtIndex(nextIndex); this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); this._updateSearchButtonClass(); event.preventDefault(); event.stopPropagation(); } else if (event.key === "Enter") { if (this._currentSelectedIndex === -1) { this._submitQuery(this._inputElement.value, true /*fillLinguisticDetails*/, event); } else { this._processSuggestionChosen(this._suggestionsData.getAt(this._currentSelectedIndex), event); } this._hideFlyout(); } else if (WinJS.UI.SearchBox._isTypeToSearchKey(event)) { // Type to search on suggestions scenario. if (this._currentFocusedIndex !== -1) { this._currentFocusedIndex = -1; this._selectSuggestionAtIndex(-1); this._updateFakeFocus(); } } } }, _keyPressHandler: function SearchBox_keyPressHandler(event) { this._lastKeyPressLanguage = event.locale; }, _keyUpHandler: function SearchBox_keyUpHandler(event) { if (event.key === "Tab") { this._isProcessingTabKey = false; } else if (event.key === "Up") { this._isProcessingUpKey = false; } else if (event.key === "Down") { this._isProcessingDownKey = false; } else if (event.key === "Enter") { this._isProcessingEnterKey = false; } }, _searchBoxFocusInHandler: function SearchBox__searchBoxFocusInHandler(event) { // Refresh hit highlighting if text has changed since focus was present // This can happen if the user committed a suggestion previously. if (this._inputElement.value !== this._prevQueryText) { if ((window.Windows) && (Windows.Data) && (Windows.Data.Text) && (Windows.Data.Text.SemanticTextQuery)) { if (this._inputElement.value !== "") { this._hitFinder = new Windows.Data.Text.SemanticTextQuery(this._inputElement.value, this._inputElement.lang); } else { this._hitFinder = null; } } } // If focus is returning to the input box from outside the search control, show the flyout and refresh the suggestions if ((event.target === this._inputElement) && !this._isElementInSearchControl(event.relatedTarget)) { this._showFlyout(); // If focus is not in input if (this._currentFocusedIndex !== -1) { this._selectSuggestionAtIndex(this._currentFocusedIndex); } else { this._updateFakeFocus(); } if (this._searchSuggestionManager) { this._searchSuggestionManager.setQuery( this._inputElement.value, this._lastKeyPressLanguage, this._getLinguisticDetails(true /*useCache*/, true /*createFilled*/) ); } } utilities.addClass(this.element, ClassName.searchBoxInputFocus); this._updateSearchButtonClass(); }, _searchBoxFocusOutHandler: function SearchBox_searchBoxFocusOutHandler(event) { this._hideFlyoutIfLeavingSearchControl(event.relatedTarget); utilities.removeClass(this.element, ClassName.searchBoxInputFocus); this._updateSearchButtonClass(); this._isProcessingDownKey = false; this._isProcessingUpKey = false; this._isProcessingTabKey = false; this._isProcessingEnterKey = false; }, _isIMEOccludingFlyout: function SearchBox_isIMEOccludingFlyout(imeRect) { var flyoutTop = this._getFlyoutTop(); var flyoutBottom = this._getFlyoutBottom(); if (((imeRect.top >= flyoutTop) && (imeRect.top <= flyoutBottom)) || ((imeRect.bottom >= flyoutTop) && (imeRect.bottom <= flyoutBottom))) { return true; } return false; }, _addFlyoutIMEPaddingIfRequired: function SearchBox_addFlyoutIMEPaddingIfRequired() { if (this._isFlyoutShown() && this._isFlyoutBelow() && this._inputElement.msGetInputContext && this._inputElement.msGetInputContext()) { var context = this._inputElement.msGetInputContext(); var rect = context.getCandidateWindowClientRect(); if (this._isIMEOccludingFlyout(rect)) { var animation = WinJS.UI.Animation.createRepositionAnimation(this._flyoutDivElement.children); this._flyoutDivElement.style.paddingTop = (rect.bottom - rect.top) + "px"; animation.execute(); } } }, _msCandidateWindowShowHandler: function SearchBox_msCandidateWindowShowHandler(event) { this._addFlyoutIMEPaddingIfRequired(); this._reflowImeOnPointerRelease = false; }, _msCandidateWindowHideHandler: function SearchBox_msCandidateWindowHideHandler(event) { if (!this._isFlyoutPointerDown) { var animation = WinJS.UI.Animation.createRepositionAnimation(this._flyoutDivElement.children); this._flyoutDivElement.style.paddingTop = ""; animation.execute(); } else { this._reflowImeOnPointerRelease = true; } }, _wireupUserEvents: function SearchBox_wireupUserEvents() { var inputOrImeChangeHandler = this._inputOrImeChangeHandler.bind(this); this._buttonElement.addEventListener("click", this._buttonClickHandler.bind(this)); this._inputElement.addEventListener("input", inputOrImeChangeHandler); this._inputElement.addEventListener("keydown", this._keyDownHandler.bind(this)); this._inputElement.addEventListener("keypress", this._keyPressHandler.bind(this)); this._inputElement.addEventListener("keyup", this._keyUpHandler.bind(this)); this._inputElement.addEventListener("pointerdown", this._inputPointerDownHandler.bind(this)); this._flyoutDivElement.addEventListener("pointerdown", this._flyoutPointerDownHandler.bind(this)); this._flyoutDivElement.addEventListener("pointerup", this._flyoutPointerReleasedHandler.bind(this)); this._flyoutDivElement.addEventListener("pointercancel", this._flyoutPointerReleasedHandler.bind(this)); this._flyoutDivElement.addEventListener("pointerout", this._flyoutPointerReleasedHandler.bind(this)); this.element.addEventListener("focusin", this._searchBoxFocusInHandler.bind(this)); this.element.addEventListener("focusout", this._searchBoxFocusOutHandler.bind(this)); this._inputElement.addEventListener("compositionstart", inputOrImeChangeHandler); this._inputElement.addEventListener("compositionupdate", inputOrImeChangeHandler); this._inputElement.addEventListener("compositionend", inputOrImeChangeHandler); if (this._inputElement.msGetInputContext && this._inputElement.msGetInputContext()) { var context = this._inputElement.msGetInputContext(); context.addEventListener("MSCandidateWindowShow", this._msCandidateWindowShowHandler.bind(this)); context.addEventListener("MSCandidateWindowHide", this._msCandidateWindowHideHandler.bind(this)); } }, _repeaterChangedHandler: function SearchBox_repeaterChangedHandler(ev) { this._updateFlyoutTopAndTouchAction(); if (this._isFlyoutShown()) { this._repeaterDivElement.style.display = "none"; this._repeaterDivElement.style.display = "block"; } }, _wireupRepeaterEvents: function SearchBox_wireupRepeaterEvents() { var repeaterChangeHandler = this._repeaterChangedHandler.bind(this); this._repeater.addEventListener("itemchanged", repeaterChangeHandler); this._repeater.addEventListener("iteminserted", repeaterChangeHandler); this._repeater.addEventListener("itemremoved", repeaterChangeHandler); this._repeater.addEventListener("itemsreloaded", repeaterChangeHandler); }, _inputPointerDownHandler: function SearchBox_inputPointerDownHandler(ev) { if ((document.activeElement === this._inputElement) && (this._currentSelectedIndex !== -1)) { this._currentFocusedIndex = -1; this._selectSuggestionAtIndex(this._currentFocusedIndex); } }, _flyoutPointerDownHandler: function SearchBox_flyoutPointerDownHandler(ev) { this._isFlyoutPointerDown = true; var srcElement = ev.srcElement; while (srcElement && (srcElement.parentNode !== this._repeaterDivElement)) { srcElement = srcElement.parentNode; } var index = this._findSuggestionElementIndex(srcElement); if ((index >= 0) && (index < this._suggestionsData.length) && (this._currentFocusedIndex !== index)) { if (this._isSuggestionSelectable(this._suggestionsData.getAt(index))) { this._currentFocusedIndex = index; this._selectSuggestionAtIndex(index); this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); } } // Prevent default so focus does not leave input element. ev.preventDefault(); }, _flyoutPointerReleasedHandler: function SearchBox_flyoutPointerReleasedHandler(ev) { this._isFlyoutPointerDown = false; if (this._reflowImeOnPointerRelease) { this._reflowImeOnPointerRelease = false; var animation = WinJS.UI.Animation.createRepositionAnimation(this._flyoutDivElement.children); this._flyoutDivElement.style.paddingTop = ""; animation.execute(); } }, _isElementInSearchControl: function SearchBox_isElementInSearchControl(targetElement) { return this.element.contains(targetElement) || (this.element === targetElement); }, _hideFlyoutIfLeavingSearchControl: function SearchBox__hideFlyoutIfLeavingSearchControl(targetElement) { if (!this._isFlyoutShown()) { return; } if (!this._isElementInSearchControl(targetElement)) { this._hideFlyout(); } }, _wireupWinRTEvents: function SearchBox_wireupWinRTEvents() { if (this._searchSuggestions) { this._searchSuggestions.addEventListener("vectorchanged", this._suggestionsChangedHandlerBind); } if (this._searchSuggestionManager) { this._searchSuggestionManager.addEventListener("suggestionsrequested", this._suggestionsRequestedHandlerBind); } }, _suggestionsChangedHandler: function SearchBox_suggestionsChangedHandler(event) { var collectionChange = event.collectionChange; if (collectionChange === Windows.Foundation.Collections.CollectionChange.reset) { if (this._isFlyoutShown()) { this._hideFlyout(); } this._suggestionsData.splice(0, this._suggestionsData.length); } else if (collectionChange === Windows.Foundation.Collections.CollectionChange.itemInserted) { var index = event.index; var suggestion = this._searchSuggestions[index]; this._suggestionsData.splice(index, 0, suggestion); this._showFlyout(); } else if (collectionChange === Windows.Foundation.Collections.CollectionChange.itemRemoved) { if ((this._suggestionsData.length === 1)) { try { this._inputElement.setActive(); } catch (e) { } this._hideFlyout(); } var index = event.index; this._suggestionsData.splice(index, 1); } else if (collectionChange === Windows.Foundation.Collections.CollectionChange.itemChanged) { var index = event.index; var suggestion = this._searchSuggestions[index]; if (suggestion !== this._suggestionsData.getAt(index)) { this._suggestionsData.setAt(index, suggestion); } else { // If the suggestions manager gives us an identical item, it means that only the hit highlighted text has changed. var existingElement = this._repeater.elementFromIndex(index); if (utilities.hasClass(existingElement, ClassName.searchBoxSuggestionQuery)) { this._addHitHighlightedText(existingElement, suggestion, suggestion.text); } else { var resultSuggestionDiv = existingElement.querySelector("." + ClassName.searchBoxSuggestionResultText); if (resultSuggestionDiv) { this._addHitHighlightedText(resultSuggestionDiv, suggestion, suggestion.text); var resultSuggestionDetailDiv = existingElement.querySelector("." + ClassName.searchBoxSuggestionResultDetailedText); if (resultSuggestionDetailDiv) { this._addHitHighlightedText(resultSuggestionDetailDiv, suggestion, suggestion.detailText); } } } } } if (document.activeElement === this._inputElement) { this._updateFakeFocus(); } }, _suggestionsRequestedHandler: function SearchBox_suggestionsRequestedHandler(event) { // get the most up to date value of the input langauge from WinRT if available if ((window.Windows) && (Windows.Globalization) && (Windows.Globalization.Language)) { this._lastKeyPressLanguage = Windows.Globalization.Language.currentInputMethodLanguageTag; } var suggestionsRequestedEventDetail = event; var deferral; this._fireEvent(WinJS.UI.SearchBox._EventName.suggestionsrequested, { setPromise: function (promise) { deferral = suggestionsRequestedEventDetail.request.getDeferral(); promise.then(function () { deferral.complete(); }); }, searchSuggestionCollection: suggestionsRequestedEventDetail.request.searchSuggestionCollection, language: this._lastKeyPressLanguage, linguisticDetails: this._getLinguisticDetails(true /*useCache*/, true /*createFilled*/), queryText: this._inputElement.value }); }, _fireEvent: function SearchBox_fireEvent(type, detail) { // Returns true if ev.preventDefault() was not called var event = document.createEvent("CustomEvent"); event.initCustomEvent(type, true, true, detail); return this.element.dispatchEvent(event); }, _requestingFocusOnKeyboardInputHandler: function SearchBox_requestingFocusOnKeyboardInputHandler(event) { this._fireEvent(WinJS.UI.SearchBox._EventName.receivingfocusonkeyboardinput, null); if (document.activeElement !== this._inputElement) { try { this._inputElement.focus(); } catch (e) { } } }, _hasLinguisticDetailsChanged: function SearchBox_hasLinguisticDetailsChanged(newLinguisticDetails) { var hasLinguisticDetailsChanged = false; if ((this._prevLinguisticDetails.queryTextCompositionStart !== newLinguisticDetails.queryTextCompositionStart) || (this._prevLinguisticDetails.queryTextCompositionLength !== newLinguisticDetails.queryTextCompositionLength) || (this._prevLinguisticDetails.queryTextAlternatives.length !== newLinguisticDetails.queryTextAlternatives.length)) { hasLinguisticDetailsChanged = true; } this._prevLinguisticDetails = newLinguisticDetails; return hasLinguisticDetailsChanged; }, _isProcessingImeFocusLossKey: function SearchBox_isProcessingImeFocusLossKey() { return this._isProcessingDownKey || this._isProcessingUpKey || this._isProcessingTabKey || this._isProcessingEnterKey; }, _updateQueryTextWithSuggestionText: function SearchBox_updateQueryTextWithSuggestionText(suggestionIndex) { if ((suggestionIndex >= 0) && (suggestionIndex < this._suggestionsData.length)) { this.queryText = this._suggestionsData.getAt(suggestionIndex).text; } } }, { _EventName: { querychanged: EventName.querychanged, querysubmitted: EventName.querysubmitted, resultsuggestionchosen: EventName.resultsuggestionchosen, suggestionsrequested: EventName.suggestionsrequested, receivingfocusonkeyboardinput: EventName.receivingfocusonkeyboardinput }, _Constants: { MIN_POPUP_HEIGHT: 152, IME_HANDLED_KEYCODE: 229 }, _getKeyModifiers: function SearchBox_getKeyModifiers(ev) { // Returns the same value as http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.system.virtualkeymodifiers var VirtualKeys = { ctrlKey: 1, altKey: 2, shiftKey: 4 }; var keyModifiers = 0; if (ev.ctrlKey) { keyModifiers |= VirtualKeys.ctrlKey; } if (ev.altKey) { keyModifiers |= VirtualKeys.altKey; } if (ev.shiftKey) { keyModifiers |= VirtualKeys.shiftKey; } return keyModifiers; }, _sortAndMergeHits: function searchBox_sortAndMergeHits(hitsProvided) { var reducedHits = []; if (hitsProvided) { // Copy hitsprovided array as winrt objects are immutable. var hits = new Array(hitsProvided.length); for (var i = 0; i < hitsProvided.length; i++) { hits.push({ startPosition: hitsProvided[i].startPosition, length: hitsProvided[i].length }); } hits.sort(WinJS.UI.SearchBox._hitStartPositionAscendingSorter); hits.reduce(WinJS.UI.SearchBox._hitIntersectionReducer, reducedHits); } return reducedHits; }, _hitStartPositionAscendingSorter: function searchBox_hitStartPositionAscendingSorter(firstHit, secondHit) { var returnValue = 0; if (firstHit.startPosition < secondHit.startPosition) { returnValue = -1; } else if (firstHit.startPosition > secondHit.startPosition) { returnValue = 1; } return returnValue; }, _hitIntersectionReducer: function searchBox_hitIntersectionReducer(reducedHits, nextHit, currentIndex, originalList) { if (currentIndex === 0) { reducedHits.push(nextHit); } else { var curHit = reducedHits[reducedHits.length - 1]; var curHitEndPosition = curHit.startPosition + curHit.length; //#DBG _ASSERT(nextHit.startPosition >= curHit.startPosition); if (nextHit.startPosition <= curHitEndPosition) { // The next hit intersects or is next to current hit. Merge it. var nextHitEndPosition = nextHit.startPosition + nextHit.length; if (nextHitEndPosition > curHitEndPosition) { curHit.length = nextHitEndPosition - curHit.startPosition; } } else { // No intersection, simply add to reduced list. reducedHits.push(nextHit); } } return reducedHits; }, _isTypeToSearchKey: function searchBox__isTypeToSearchKey(event) { if (event.shiftKey || event.ctrlKey || event.altKey) { return false; } return true; } }); WinJS.Class.mix(SearchBox, WinJS.UI.DOMEventMixin); return SearchBox; }) }); })(this, WinJS); /// appbar,Flyout,Flyouts,registeredforsettings,SettingsFlyout,Statics,Syriac (function settingsFlyoutInit(WinJS) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Provides users with fast, in-context access to settings that affect the current app. /// /// /// Settings Flyout /// /// /// ///
/// ///
Custom Settings
///
///
/// {Your Content Here} ///
/// ]]>
/// Raised just before showing a SettingsFlyout. /// Raised immediately after a SettingsFlyout is fully shown. /// Raised just before hiding a SettingsFlyout. /// Raised immediately after a SettingsFlyout is fully hidden. /// The SettingsFlyout control itself. /// /// /// SettingsFlyout: WinJS.Namespace._lazy(function () { var thisWinUI = WinJS.UI; var focusHasHitSettingsPaneOnce; // Class Names var settingsFlyoutClass = "win-settingsflyout", fullSettingsFlyoutClassName = "." + settingsFlyoutClass, settingsFlyoutLightClass = "win-ui-light", narrowClass = "win-narrow", wideClass = "win-wide"; var firstDivClass = "win-firstdiv"; var finalDivClass = "win-finaldiv"; // Constants for width var settingsNarrow = "narrow", settingsWide = "wide"; // Determine if the settings pane (system language) is RTL or not. function _shouldAnimateFromLeft() { if (WinJS.Utilities.hasWinRT && Windows.UI.ApplicationSettings.SettingsEdgeLocation) { var appSettings = Windows.UI.ApplicationSettings; return (appSettings.SettingsPane.edge === appSettings.SettingsEdgeLocation.left); } else { return false; } }; // Get the settings control by matching the settingsCommandId // if no match we'll try to match element id function _getChildSettingsControl(parentElement, id) { var settingElements = parentElement.querySelectorAll(fullSettingsFlyoutClassName); var retValue, control; for (var i = 0; i < settingElements.length; i++) { control = settingElements[i].winControl; if (control) { if (control.settingsCommandId === id) { retValue = control; break; } if (settingElements[i].id === id) { retValue = retValue || control; } } } return retValue; } var SettingsFlyout = WinJS.Class.derive(WinJS.UI._Overlay, function SettingsFlyout_ctor(element, options) { /// /// Creates a new SettingsFlyout control. /// /// The DOM element that will host the control. /// /// /// The set of properties and values to apply to the new SettingsFlyout. /// /// The new SettingsFlyout control. /// /// // Make sure there's an input element this._element = element || document.createElement("div"); this._id = this._element.id || this._element.uniqueID; this._writeProfilerMark("constructor,StartTM"); // Call the base overlay constructor helper this._baseOverlayConstructor(this._element, options); this._addFirstDiv(); this._addFinalDiv(); // Handle "esc" & "tab" key presses this._element.addEventListener("keydown", this._handleKeyDown, true); // Make a click eating div thisWinUI._Overlay._createClickEatingDivAppBar(); // Start settings hidden this._element.style.visibilty = "hidden"; this._element.style.display = "none"; // Attach our css class WinJS.Utilities.addClass(this._element, settingsFlyoutClass); // apply the light theme styling to the win-content elements inside the SettingsFlyout WinJS.Utilities.query("div.win-content", this._element). forEach(function (e) { if (!e.msMatchesSelector('.win-ui-dark, .win-ui-dark *')) { WinJS.Utilities.addClass(e, settingsFlyoutLightClass); } }); // Make sure we have an ARIA role var role = this._element.getAttribute("role"); if (role === null || role === "" || role === undefined) { this._element.setAttribute("role", "dialog"); } var label = this._element.getAttribute("aria-label"); if (label === null || label === "" || label === undefined) { this._element.setAttribute("aria-label", strings.ariaLabel); } // Make sure _Overlay event handlers are hooked up this._addOverlayEventHandlers(true); // Make sure animations are hooked up this._currentAnimateIn = this._animateSlideIn; this._currentAnimateOut = this._animateSlideOut; this._writeProfilerMark("constructor,StopTM"); }, { // Public Properties /// /// Width of the SettingsFlyout, "narrow", or "wide". /// /// SettingsFlyout.width may be altered or unavailable in future versions. Instead, style the CSS width property on elements with the .win-settingsflyout class. /// /// /// width: { get: function () { return this._width; }, set: function (value) { WinJS.Utilities._deprecated(strings.widthDeprecationMessage); if (value === this._width) { return; } // Get rid of old class if (this._width === settingsNarrow) { WinJS.Utilities.removeClass(this._element, narrowClass); } else if (this._width === settingsWide) { WinJS.Utilities.removeClass(this._element, wideClass); } this._width = value; // Attach our new css class if (this._width === settingsNarrow) { WinJS.Utilities.addClass(this._element, narrowClass); } else if (this._width === settingsWide) { WinJS.Utilities.addClass(this._element, wideClass); } } }, /// /// Define the settings command Id for the SettingsFlyout control. /// /// settingsCommandId: { get: function () { return this._settingsCommandId; }, set: function (value) { this._settingsCommandId = value; } }, show: function () { /// /// /// Shows the SettingsFlyout, if hidden. /// /// /// // Just call private version to make appbar flags happy // Don't do anything if disabled if (this.disabled) { return; } this._writeProfilerMark("show,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndShow(). this._show(); }, _dispose: function SettingsFlyout_dispose() { WinJS.Utilities.disposeSubTree(this.element); this._dismiss(); }, _show: function SettingsFlyout_show() { // We call our base "_baseShow" because SettingsFlyout overrides show this._baseShow(); // Need click-eating div to be visible, // (even if now hiding, we'll show and need click eater) thisWinUI._Overlay._showClickEatingDivAppBar(); }, _endShow: function SettingsFlyout_endShow() { // Clean up after showing this._initAfterAnimation(); }, _initAfterAnimation: function SettingsFlyout_initAfterAnimation() { focusHasHitSettingsPaneOnce = 0; // Verify that the firstDiv and finalDiv are in the correct location. // Move them to the correct location or add them if they are not. if (!WinJS.Utilities.hasClass(this.element.children[0], firstDivClass)) { var firstDiv = this.element.querySelectorAll(".win-first"); if (firstDiv && firstDiv.length > 0) { firstDiv.item(0).parentNode.removeChild(firstDiv.item(0)); } this._addFirstDiv(); } // Set focus to the firstDiv if (this.element.children[0]) { this.element.children[0].addEventListener("focusout", function () { focusHasHitSettingsPaneOnce = 1; }, false); this.element.children[0].focus(); } if (!WinJS.Utilities.hasClass(this.element.children[this.element.children.length - 1], finalDivClass)) { var finalDiv = this.element.querySelectorAll(".win-final"); if (finalDiv && finalDiv.length > 0) { finalDiv.item(0).parentNode.removeChild(finalDiv.item(0)); } this._addFinalDiv(); } this._setBackButtonsAriaLabel(); }, _setBackButtonsAriaLabel: function SettingsFlyout_setBackButtonsAriaLabel() { var backbuttons = this.element.querySelectorAll(".win-backbutton"); var label; for (var i = 0; i < backbuttons.length; i++) { label = backbuttons[i].getAttribute("aria-label"); if (label === null || label === "" || label === undefined) { backbuttons[i].setAttribute("aria-label", strings.backbuttonAriaLabel); } } }, hide: function () { /// /// /// Hides the SettingsFlyout, if visible, regardless of other state. /// /// /// // Just call private version to make appbar flags happy this._writeProfilerMark("hide,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndHide(). this._hide(); }, _hide: function SettingsFlyout_hide() { if (this._baseHide()) { // Need click-eating div to be hidden thisWinUI._Overlay._hideClickEatingDivAppBar(); } }, // SettingsFlyout animations _animateSlideIn: function SettingsFlyout_animateSlideIn() { var animateFromLeft = _shouldAnimateFromLeft(); var offset = animateFromLeft ? "-100px" : "100px"; WinJS.Utilities.query("div.win-content", this._element). forEach(function (e) { WinJS.UI.Animation.enterPage(e, { left: offset }) }); var where, width = this._element.offsetWidth; // Slide in from right side or left side? if (animateFromLeft) { // RTL where = { top: "0px", left: "-" + width + "px" }; this._element.style.right = "auto"; this._element.style.left = "0px"; } else { // From right side where = { top: "0px", left: width + "px" }; this._element.style.right = "0px"; this._element.style.left = "auto"; } this._element.style.opacity = 1; this._element.style.visibility = "visible"; return WinJS.UI.Animation.showPanel(this._element, where); }, _animateSlideOut: function SettingsFlyout_animateSlideOut() { var where, width = this._element.offsetWidth; if (_shouldAnimateFromLeft()) { // RTL where = { top: "0px", left: width + "px" }; this._element.style.right = "auto"; this._element.style.left = "-" + width + "px"; } else { // From right side where = { top: "0px", left: "-" + width + "px" }; this._element.style.right = "-" + width + "px"; this._element.style.left = "auto"; } return WinJS.UI.Animation.showPanel(this._element, where); }, _fragmentDiv: { get: function SettingsFlyout_fragmentDiv_get() { return this._fragDiv; }, set: function SettingsFlyout_fragmentDiv_set(value) { this._fragDiv = value; } }, _unloadPage: function SettingsFlyout_unloadPage(event) { var settingsControl = event.currentTarget.winControl; settingsControl.removeEventListener(thisWinUI._Overlay.afterHide, this._unloadPage, false); WinJS.Promise.as().then(function () { if (settingsControl._fragmentDiv) { document.body.removeChild(settingsControl._fragmentDiv); settingsControl._fragmentDiv = null; } }); }, _dismiss: function SettingsFlyout_dismiss() { this.addEventListener(thisWinUI._Overlay.afterHide, this._unloadPage, false); this._hide(); }, _handleKeyDown: function SettingsFlyout_handleKeyDown(event) { if (event.key === "Esc") { event.preventDefault(); event.stopPropagation(); this.winControl._dismiss(); } else if ((event.key === "Spacebar" || event.key === "Enter") && (this.children[0] === document.activeElement)) { event.preventDefault(); event.stopPropagation(); this.winControl._dismiss(); } else if (event.shiftKey && event.key === "Tab" && this.children[0] === document.activeElement) { event.preventDefault(); event.stopPropagation(); var _elms = this.getElementsByTagName("*"); for (var i = _elms.length - 2; i >= 0; i--) { _elms[i].focus(); if (_elms[i] === document.activeElement) { break; } } } }, _focusOnLastFocusableElementFromParent: function SettingsFlyout_focusOnLastFocusableElementFromParent() { var active = document.activeElement; if (!focusHasHitSettingsPaneOnce || !active || !WinJS.Utilities.hasClass(active, firstDivClass)) { return; } var _elms = this.parentElement.getElementsByTagName("*"); // There should be at least 1 element in addition to the firstDiv & finalDiv if (_elms.length <= 2) { return; } // Get the tabIndex set to the finalDiv (which is the highest) var _highestTabIndex = _elms[_elms.length - 1].tabIndex; // If there are positive tabIndices, set focus to the element with the highest tabIndex. // Otherwise set focus to the last focusable element in DOM order. if (_highestTabIndex) { for (var i = _elms.length - 2; i > 0; i--) { if (_elms[i].tabIndex === _highestTabIndex) { _elms[i].focus(); break; } } } else { for (i = _elms.length - 2; i > 0; i--) { // Skip
with undefined tabIndex (To work around Win8 bug #622245) if ((_elms[i].tagName !== "DIV") || (_elms[i].getAttribute("tabIndex") !== null)) { _elms[i].focus(); if (_elms[i] === document.activeElement) { break; } } } } }, _focusOnFirstFocusableElementFromParent: function SettingsFlyout_focusOnFirstFocusableElementFromParent() { var active = document.activeElement; if (!active || !WinJS.Utilities.hasClass(active, finalDivClass)) { return; } var _elms = this.parentElement.getElementsByTagName("*"); // There should be at least 1 element in addition to the firstDiv & finalDiv if (_elms.length <= 2) { return; } // Get the tabIndex set to the firstDiv (which is the lowest) var _lowestTabIndex = _elms[0].tabIndex; // If there are positive tabIndices, set focus to the element with the lowest tabIndex. // Otherwise set focus to the first focusable element in DOM order. if (_lowestTabIndex) { for (var i = 1; i < _elms.length - 1; i++) { if (_elms[i].tabIndex === _lowestTabIndex) { _elms[i].focus(); break; } } } else { for (i = 1; i < _elms.length - 1; i++) { // Skip
with undefined tabIndex (To work around Win8 bug #622245) if ((_elms[i].tagName !== "DIV") || (_elms[i].getAttribute("tabIndex") !== null)) { _elms[i].focus(); if (_elms[i] === document.activeElement) { break; } } } } }, // Create and add a new first div to the beginning of the list _addFirstDiv: function SettingsFlyout_addFirstDiv() { var _elms = this._element.getElementsByTagName("*"); var _minTab = 0; for (var i = 0; i < _elms.length; i++) { if ((0 < _elms[i].tabIndex) && (_minTab === 0 || _elms[i].tabIndex < _minTab)) { _minTab = _elms[i].tabIndex; } } var firstDiv = document.createElement("div"); firstDiv.className = firstDivClass; firstDiv.style.display = "inline"; firstDiv.setAttribute("role", "menuitem"); firstDiv.setAttribute("aria-hidden", "true"); firstDiv.tabIndex = _minTab; firstDiv.addEventListener("focus", this._focusOnLastFocusableElementFromParent, false); this._element.insertAdjacentElement("AfterBegin", firstDiv); }, // Create and add a new final div to the end of the list _addFinalDiv: function SettingsFlyout_addFinalDiv() { var _elms = this._element.getElementsByTagName("*"); var _maxTab = 0; for (var i = 0; i < _elms.length; i++) { if (_elms[i].tabIndex > _maxTab) { _maxTab = _elms[i].tabIndex; } } var finalDiv = document.createElement("div"); finalDiv.className = finalDivClass; finalDiv.style.display = "inline"; finalDiv.setAttribute("role", "menuitem"); finalDiv.setAttribute("aria-hidden", "true"); finalDiv.tabIndex = _maxTab; finalDiv.addEventListener("focus", this._focusOnFirstFocusableElementFromParent, false); this._element.appendChild(finalDiv); }, _writeProfilerMark: function SettingsFlyout_writeProfilerMark(text) { msWriteProfilerMark("WinJS.UI.SettingsFlyout:" + this._id + ":" + text); } }); // Statics SettingsFlyout.show = function () { /// /// /// Shows the SettingsPane UI, if hidden, regardless of other states. /// /// /// if (WinJS.Utilities.hasWinRT) { Windows.UI.ApplicationSettings.SettingsPane.show(); } // And hide the WWA one var elements = document.querySelectorAll('div[data-win-control="WinJS.UI.SettingsFlyout"]'); var len = elements.length; for (var i = 0; i < len; i++) { var settingsFlyout = elements[i].winControl; if (settingsFlyout) { settingsFlyout._dismiss(); } } }; var _settingsEvent = { event: undefined }; SettingsFlyout.populateSettings = function (e) { /// /// /// Loads a portion of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. /// /// /// An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains /// the applicationcommands sub-property that you set to an array of settings commands. /// /// /// _settingsEvent.event = e.detail; if (_settingsEvent.event.applicationcommands) { var n = Windows.UI.ApplicationSettings; Object.keys(_settingsEvent.event.applicationcommands).forEach(function (name) { var setting = _settingsEvent.event.applicationcommands[name]; if (!setting.title) { setting.title = name; } var command = new n.SettingsCommand(name, setting.title, thisWinUI.SettingsFlyout._onSettingsCommand); _settingsEvent.event.e.request.applicationCommands.append(command); }); } }; SettingsFlyout._onSettingsCommand = function (command) { var id = command.id; if (_settingsEvent.event.applicationcommands && _settingsEvent.event.applicationcommands[id]) { thisWinUI.SettingsFlyout.showSettings(id, _settingsEvent.event.applicationcommands[id].href); } }; SettingsFlyout.showSettings = function (id, path) { /// /// /// Show the SettingsFlyout using the settings element identifier (ID) and the path of the page that contains the settings element. /// /// /// The ID of the settings element. /// /// /// The path of the page that contains the settings element. /// /// /// var control = _getChildSettingsControl(document, id); if (control) { control.show(); } else if (path) { var divElement = document.createElement("div"); divElement = document.body.appendChild(divElement); WinJS.UI.Pages.render(path, divElement).then(function () { control = _getChildSettingsControl(divElement, id); if (control) { control._fragmentDiv = divElement; control.show(); } else { document.body.removeChild(divElement); } }); } else { throw new WinJS.ErrorFromName("WinJS.UI.SettingsFlyout.BadReference", strings.badReference); } }; var strings = { get ariaLabel() { return WinJS.Resources._getWinJSString("ui/settingsFlyoutAriaLabel").value; }, get badReference() { return WinJS.Resources._getWinJSString("ui/badReference").value; }, get backbuttonAriaLabel() { return WinJS.Resources._getWinJSString("ui/backbuttonarialabel").value; }, get widthDeprecationMessage() { return WinJS.Resources._getWinJSString("ui/settingsFlyoutWidthIsDeprecated").value; }, }; return SettingsFlyout; }) }); })(WinJS); (function itemContainerInit(global, WinJS, undefined) { "use strict"; var utilities = WinJS.Utilities; var createEvent = utilities._createEventProperty; var eventNames = { invoked: "invoked", selectionchanging: "selectionchanging", selectionchanged: "selectionchanged" }; WinJS.Namespace.define("WinJS.UI", { /// /// Defines an item that can be pressed, swiped, and dragged. /// /// /// /// HTML content
/// ]]> /// Raised when the user taps or clicks the item. /// Raised before the item is selected or deselected. /// Raised after the item is selected or deselected. /// Main container for the selection item control. /// The background of a selection checkmark. /// A selection checkmark. /// Used to display an outline when the main container has keyboard focus. /// /// /// ItemContainer: WinJS.Namespace._lazy(function () { var strings = { get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; } }; var ItemContainer = WinJS.Class.define(function ItemContainer_ctor(element, options) { /// /// /// Creates a new ItemContainer control. /// /// /// The DOM element that hosts the ItemContainer control. /// /// /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". For example, to provide a handler for the selectionchanging event, /// add a property named "onselectionchanging" to the options object and set its value to the event handler. /// /// /// The new ItemContainer control. /// /// element = element || document.createElement("DIV"); this._id = element.id || element.uniqueID; this._writeProfilerMark("constructor,StartTM"); options = options || {}; if (element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.ItemContainer.DuplicateConstruction", strings.duplicateConstruction); } // Attaching JS control to DOM element element.winControl = this; this._element = element; WinJS.Utilities.addClass(element, "win-disposable"); this._selectionMode = WinJS.UI.SelectionMode.single; this._draggable = false; this._pressedEntity = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }; this.tapBehavior = WinJS.UI.TapBehavior.invokeOnly; this.swipeOrientation = WinJS.UI.Orientation.vertical; this.swipeBehavior = WinJS.UI.SwipeBehavior.select; WinJS.Utilities.addClass(this.element, WinJS.UI.ItemContainer._ClassName.itemContainer + " " + WinJS.UI._containerClass); this._setupInternalTree(); this._selection = new WinJS.UI._SingleItemSelectionManager(element, this._itemBox); this._setTabIndex(); WinJS.UI.setOptions(this, options); this._mutationObserver = new MutationObserver(this._itemPropertyChange.bind(this)); this._mutationObserver.observe(element, { attributes: true, attributeFilter: ["aria-selected"] }); this._setAriaRole(); var that = this; if (!this.selectionDisabled) { setImmediate(function () { that._setDirectionClass(); }); } this._itemEventsHandler = new WinJS.UI._ItemEventsHandler(Object.create({ containerFromElement: function (element) { return that.element; }, indexForItemElement: function (element) { return that.element.uniqueID; }, indexForHeaderElement: function () { return WinJS.UI._INVALID_INDEX; }, itemBoxAtIndex: function (index) { return that._itemBox; }, itemAtIndex: function (index) { return that.element; }, headerAtIndex: function (index) { return null; }, containerAtIndex: function (index) { return that.element; }, isZombie: function () { return this._disposed; }, getItemPosition: function (index) { return that._getItemPosition(); }, rtl: function () { return that._rtl(); }, fireInvokeEvent: function (itemIndex, itemElement) { that._fireInvokeEvent(); }, verifySelectionAllowed: function (index) { return that._verifySelectionAllowed(); }, changeFocus: function (newFocus, skipSelection, ctrlKeyDown, skipEnsureVisible, keyboardFocused) { }, selectRange: function (firstIndex, lastIndex, additive) { return that._selection.set({ firstIndex: firstIndex, lastIndex: lastIndex }); } }, { pressedEntity: { get: function () { return that._pressedEntity; }, set: function (value) { that._pressedEntity = value; } }, pressedElement: { enumerable: true, set: function (value) { that._pressedElement = value; } }, eventHandlerRoot: { enumerable: true, get: function () { return that.element; } }, swipeBehavior: { enumerable: true, get: function () { return that._swipeBehavior; } }, selectionMode: { enumerable: true, get: function () { return that._selectionMode; } }, accessibleItemClass: { enumerable: true, get: function () { // CSS class of the element with the aria role return WinJS.UI._containerClass; } }, canvasProxy: { enumerable: true, get: function () { return that._captureProxy; } }, tapBehavior: { enumerable: true, get: function () { return that._tapBehavior; } }, draggable: { enumerable: true, get: function () { return that._draggable; } }, selection: { enumerable: true, get: function () { return that._selection; } }, horizontal: { enumerable: true, get: function () { return that._swipeOrientation === WinJS.UI.Orientation.vertical; } }, customFootprintParent: { enumerable: true, get: function () { // Use the main container as the footprint return null; } }, skipPreventDefaultOnPointerDown: { enumerable: true, get: function () { return true; } } })); function eventHandler(eventName, caseSensitive, capture) { return { name: (caseSensitive ? eventName : eventName.toLowerCase()), handler: function (eventObject) { that["_on" + eventName](eventObject); }, capture: capture }; } var events = [ eventHandler("MSManipulationStateChanged", true, true), eventHandler("PointerDown"), eventHandler("Click"), eventHandler("PointerUp"), eventHandler("PointerCancel"), eventHandler("LostPointerCapture"), eventHandler("ContextMenu"), eventHandler("MSHoldVisual", true), eventHandler("Focus"), eventHandler("Blur"), eventHandler("DragStart"), eventHandler("DragEnd"), eventHandler("KeyDown") ]; events.forEach(function (eventHandler) { that.element.addEventListener(eventHandler.name, eventHandler.handler, !!eventHandler.capture); }); this._writeProfilerMark("constructor,StopTM"); }, { /// element: { get: function () { return this._element; } }, /// /// Gets or sets a value that specifies whether the item can be dragged. The default value is false. /// /// draggable: { get: function () { return this._draggable; }, set: function (value) { if (this._draggable !== value) { this._draggable = value; this._updateDraggableAttribute(); } } }, /// /// Gets or sets a value that specifies whether the item is selected. /// selected: { get: function () { return this._selection.selected; }, set: function (value) { if (this._selection.selected !== value) { this._selection.selected = value; } } }, /// /// Gets or sets the swipe orientation of the ItemContainer control. /// The default value is "vertical". /// swipeOrientation: { get: function () { return this._swipeOrientation; }, set: function (value) { if (value === WinJS.UI.Orientation.vertical) { WinJS.Utilities.removeClass(this.element, WinJS.UI.ItemContainer._ClassName.horizontal); WinJS.Utilities.addClass(this.element, WinJS.UI.ItemContainer._ClassName.vertical); } else { value = WinJS.UI.Orientation.horizontal; WinJS.Utilities.removeClass(this.element, WinJS.UI.ItemContainer._ClassName.vertical); WinJS.Utilities.addClass(this.element, WinJS.UI.ItemContainer._ClassName.horizontal); } this._swipeOrientation = value; } }, /// /// Gets or sets how the ItemContainer control reacts when the user taps or clicks an item. /// The tap or click can invoke the item, select it and invoke it, or have no effect. /// Possible values: "toggleSelect", "invokeOnly", and "none". The default value is "invokeOnly". /// tapBehavior: { get: function () { return this._tapBehavior; }, set: function (value) { this._tapBehavior = value; this._setAriaRole(); } }, /// /// Gets or sets how the ItemContainer control reacts to the swipe interaction. /// The swipe gesture can select the item or it can have no effect on the current selection. /// Possible values: "select", "none". The default value is: "select". /// /// swipeBehavior: { get: function () { return this._swipeBehavior; }, set: function (value) { this._swipeBehavior = value; this._setSwipeClass(); } }, /// /// Gets or sets whether the item selection is disabled. The default value is false. /// selectionDisabled: { get: function () { return this._selectionMode === WinJS.UI.SelectionMode.none; }, set: function (value) { if (value) { this._selectionMode = WinJS.UI.SelectionMode.none; } else { this._setDirectionClass(); this._selectionMode = WinJS.UI.SelectionMode.single; } this._setSwipeClass(); this._setAriaRole(); } }, /// /// Raised when the item is invoked. You can use the tapBehavior property to specify whether taps and clicks invoke the item. /// oninvoked: createEvent(eventNames.invoked), /// /// Raised just before the item is selected or deselected. /// onselectionchanging: createEvent(eventNames.selectionchanging), /// /// Raised after the item is selected or deselected. /// onselectionchanged: createEvent(eventNames.selectionchanged), forceLayout: function () { /// /// /// Forces the ItemContainer control to update its layout. /// Use this function when the reading direction of the app changes after the control has been initialized. /// /// this._forceLayout(); }, dispose: function () { /// /// /// Disposes this control. /// /// if (this._disposed) { return; } this._disposed = true; this._itemEventsHandler.dispose(); WinJS.Utilities.disposeSubTree(this.element); }, _onMSManipulationStateChanged: function ItemContainer_onMSManipulationStateChanged(eventObject) { this._itemEventsHandler.onMSManipulationStateChanged(eventObject); }, _onPointerDown: function ItemContainer_onPointerDown(eventObject) { this._itemEventsHandler.onPointerDown(eventObject); }, _onClick: function ItemContainer_onClick(eventObject) { this._itemEventsHandler.onClick(eventObject); }, _onPointerUp: function ItemContainer_onPointerUp(eventObject) { if (utilities.hasClass(this._itemBox, WinJS.UI._itemFocusClass)) { this._onBlur(eventObject); } this._itemEventsHandler.onPointerUp(eventObject); }, _onPointerCancel: function ItemContainer_onPointerCancel(eventObject) { this._itemEventsHandler.onPointerCancel(eventObject); }, _onLostPointerCapture: function ItemContainer_onLostPointerCapture(eventObject) { this._itemEventsHandler.onLostPointerCapture(eventObject); }, _onContextMenu: function ItemContainer_onContextMenu(eventObject) { this._itemEventsHandler.onContextMenu(eventObject); }, _onMSHoldVisual: function ItemContainer_onMSHoldVisual(eventObject) { this._itemEventsHandler.onMSHoldVisual(eventObject); }, _onFocus: function ItemContainer_onFocus(eventObject) { if (this._itemBox.querySelector("." + WinJS.UI._itemFocusOutlineClass) || !WinJS.UI._keyboardSeenLast) { return; } utilities.addClass(this._itemBox, WinJS.UI._itemFocusClass); var outline = document.createElement("div"); outline.className = WinJS.UI._itemFocusOutlineClass; this._itemBox.appendChild(outline); }, _onBlur: function ItemContainer_onBlur(eventObject) { utilities.removeClass(this._itemBox, WinJS.UI._itemFocusClass); var outline = this._itemBox.querySelector("." + WinJS.UI._itemFocusOutlineClass); if (outline) { outline.parentNode.removeChild(outline); } }, _onDragStart: function ItemContainer_onDragStart(eventObject) { // Drag shouldn't be initiated when the user holds down the mouse on a win-interactive element and moves. // The problem is that the dragstart event's srcElement+target will both be an itembox (which has draggable=true), so we can't check for win-interactive in the dragstart event handler. // The itemEventsHandler sets our _pressedElement field on PointerDown, so we use that instead when checking for interactive. if (this._pressedElement && this._itemEventsHandler._isInteractive(this._pressedElement)) { eventObject.preventDefault(); } else { this._dragging = true; var that = this; // We delay setting the win-dragsource CSS class so that IE has time to create a thumbnail before me make it opaque setImmediate(function () { if (that._dragging) { utilities.addClass(that._itemBox, WinJS.UI._dragSourceClass); } }); } }, _onDragEnd: function ItemContainer_onDragEnd(eventObject) { this._dragging = false; utilities.removeClass(this._itemBox, WinJS.UI._dragSourceClass); this._itemEventsHandler.resetPointerDownState(); }, _onKeyDown: function ItemContainer_onKeyDown(eventObject) { if (!this._itemEventsHandler._isInteractive(eventObject.srcElement)) { var Key = utilities.Key, keyCode = eventObject.keyCode, swipeEnabled = this._swipeBehavior === WinJS.UI.SwipeBehavior.select; var handled = false; if (!eventObject.ctrlKey && keyCode === Key.enter) { var allowed = this._verifySelectionAllowed(); if (allowed.canTapSelect) { this.selected = !this.selected; } this._fireInvokeEvent(); handled = true; } else if (eventObject.ctrlKey && keyCode === Key.enter || (swipeEnabled && eventObject.shiftKey && keyCode === Key.F10) || (swipeEnabled && keyCode === Key.menu) || keyCode === Key.space) { if (!this.selectionDisabled) { this.selected = !this.selected; try { this.element.setActive(); } catch (e) { } handled = true; } } else if (keyCode === Key.escape && this.selected) { this.selected = false; handled = true; } if (handled) { eventObject.stopPropagation(); eventObject.preventDefault(); } } }, _setTabIndex: function ItemContainer_setTabIndex() { var currentTabIndex = this.element.getAttribute("tabindex"); if (!currentTabIndex) { // Set the tabindex to 0 only if the application did not already // provide a tabindex this.element.setAttribute("tabindex", "0") } }, _rtl: function ItemContainer_rtl() { if (typeof this._cachedRTL !== "boolean") { this._cachedRTL = window.getComputedStyle(this.element, null).direction === "rtl"; } return this._cachedRTL; }, _setDirectionClass: function ItemContainer_setDirectionClass() { utilities[this._rtl() ? "addClass" : "removeClass"](this.element, WinJS.UI._rtlListViewClass); }, _forceLayout: function ItemContainer_forceLayout() { this._cachedRTL = window.getComputedStyle(this.element, null).direction === "rtl"; this._setDirectionClass(); }, _getItemPosition: function ItemContainer_getItemPosition() { var container = this.element; if (container) { return WinJS.Promise.wrap({ left: (this._rtl() ? container.offsetParent.offsetWidth - container.offsetLeft - container.offsetWidth : container.offsetLeft), top: container.offsetTop, totalWidth: utilities.getTotalWidth(container), totalHeight: utilities.getTotalHeight(container), contentWidth: utilities.getContentWidth(container), contentHeight: utilities.getContentHeight(container) }); } else { return WinJS.Promise.cancel; } }, _itemPropertyChange: function ItemContainer_itemPropertyChange(list) { if (this._disposed) { return; } var container = list[0].target; var ariaSelected = container.getAttribute("aria-selected") === "true"; // Only respond to aria-selected changes coming from UIA. This check // relies on the fact that, in renderSelection, we update the selection // visual before aria-selected. if (ariaSelected !== WinJS.UI._isSelectionRendered(this._itemBox)) { if (this.selectionDisabled) { // Revert the change made by UIA since the control has selection disabled WinJS.UI._setAttribute(container, "aria-selected", !ariaSelected); } else { this.selected = ariaSelected; // Revert the change because the update was prevented on the selectionchanging event if (ariaSelected !== this.selected) { WinJS.UI._setAttribute(container, "aria-selected", !ariaSelected); } } } }, _setSwipeClass: function ItemContainer_setSwipeClass() { // We apply an -ms-touch-action style to block panning and swiping from occurring at the same time. if ((this._swipeBehavior === WinJS.UI.SwipeBehavior.select && this._selectionMode !== WinJS.UI.SelectionMode.none) || this._draggable) { utilities.addClass(this._element, WinJS.UI._swipeableClass); } else { utilities.removeClass(this._element, WinJS.UI._swipeableClass); } }, _updateDraggableAttribute: function ItemContainer_setSwipeClass() { this._setSwipeClass(); this._itemBox.setAttribute("draggable", this._draggable); }, _verifySelectionAllowed: function ItemContainer_verifySelectionAllowed() { if (this._selectionMode !== WinJS.UI.SelectionMode.none && (this._tapBehavior === WinJS.UI.TapBehavior.toggleSelect || this._swipeBehavior === WinJS.UI.SwipeBehavior.select)) { var canSelect = this._selection.fireSelectionChanging(); return { canSelect: canSelect, canTapSelect: canSelect && this._tapBehavior === WinJS.UI.TapBehavior.toggleSelect }; } else { return { canSelect: false, canTapSelect: false }; } }, _setupInternalTree: function ItemContainer_setupInternalTree() { var item = document.createElement("div"); item.className = WinJS.UI._itemClass; this._captureProxy = document.createElement("div"); this._itemBox = document.createElement("div"); this._itemBox.className = WinJS.UI._itemBoxClass; var child = this.element.firstChild; while (child) { var sibling = child.nextSibling; item.appendChild(child); child = sibling; } this.element.appendChild(this._itemBox); this._itemBox.appendChild(item); this.element.appendChild(this._captureProxy); }, _fireInvokeEvent: function ItemContainer_fireInvokeEvent() { if (this.tapBehavior !== WinJS.UI.TapBehavior.none) { var eventObject = document.createEvent("CustomEvent"); eventObject.initCustomEvent(eventNames.invoked, true, false, {}); this.element.dispatchEvent(eventObject); } }, _setAriaRole: function ItemContainer_setAriaRole() { if (!this.element.getAttribute("role") || this._usingDefaultItemRole) { this._usingDefaultItemRole = true; var defaultItemRole; if (this.tapBehavior === WinJS.UI.TapBehavior.none && this.selectionDisabled) { defaultItemRole = "listitem"; } else { defaultItemRole = "option"; } WinJS.UI._setAttribute(this.element, "role", defaultItemRole); } }, _writeProfilerMark: function ItemContainer_writeProfilerMark(text) { var message = "WinJS.UI.ItemContainer:" + this._id + ":" + text; msWriteProfilerMark(message); WinJS.log && WinJS.log(message, null, "itemcontainerprofiler"); } }, { // Names of classes used by the ItemContainer. _ClassName: { itemContainer: "win-itemcontainer", vertical: "win-vertical", horizontal: "win-horizontal", } }); WinJS.Class.mix(ItemContainer, WinJS.UI.DOMEventMixin); return ItemContainer; }), _SingleItemSelectionManager: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function SingleItemSelectionManager_ctor(element, itemBox) { this._selected = false; this._element = element; this._itemBox = itemBox; }, { selected: { get: function () { return this._selected; }, set: function (value) { value = !!value; if (this._selected !== value) { if (this.fireSelectionChanging()) { this._selected = value; WinJS.UI._ItemEventsHandler.renderSelection(this._itemBox, this._element, value, true, this._element); this.fireSelectionChanged(); } } } }, count: function SingleItemSelectionManager_count() { return this._selected ? 1 : 0; }, getIndices: function SingleItemSelectionManager_getIndices() { // not used }, getItems: function SingleItemSelectionManager_getItems() { // not used }, getRanges: function SingleItemSelectionManager_getRanges() { // not used }, isEverything: function SingleItemSelectionManager_isEverything() { return false; }, set: function SingleItemSelectionManager_set(items) { this.selected = true; }, clear: function SingleItemSelectionManager_clear() { this.selected = false; }, add: function SingleItemSelectionManager_add(items) { this.selected = true; }, remove: function SingleItemSelectionManager_remove(items) { this.selected = false; }, selectAll: function SingleItemSelectionManager_selectAll() { // not used }, fireSelectionChanging: function SingleItemSelectionManager_fireSelectionChanging() { var eventObject = document.createEvent("CustomEvent"); eventObject.initCustomEvent(eventNames.selectionchanging, true, true, {}); return this._element.dispatchEvent(eventObject); }, fireSelectionChanged: function ItemContainer_fireSelectionChanged() { var eventObject = document.createEvent("CustomEvent"); eventObject.initCustomEvent(eventNames.selectionchanged, true, false, {}); this._element.dispatchEvent(eventObject); }, _isIncluded: function SingleItemSelectionManager_isIncluded(index) { return this._selected; }, _getFocused: function SingleItemSelectionManager_getFocused(index) { return { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX }; } }) }) }); })(this, WinJS); (function KeyboardBehaviorInit(global, WinJS, undefined) { "use strict"; // not supported in WebWorker if (!global.document) { return; } WinJS.UI._keyboardSeenLast = false; window.addEventListener("pointerdown", function (ev) { if (WinJS.UI._keyboardSeenLast) { WinJS.UI._keyboardSeenLast = false; } }, true); window.addEventListener("keydown", function (ev) { if (!WinJS.UI._keyboardSeenLast) { WinJS.UI._keyboardSeenLast = true; } }, true); WinJS.Namespace.define("WinJS.UI", { _WinKeyboard: function (element) { // Win Keyboard behavior is a solution that would be similar to -ms-keyboard-focus. // It monitors the last input (keyboard/mouse) and adds/removes a win-keyboard class // so that you can style .foo.win-keyboard:focus vs .foo:focus to add a keyboard rect // on an item only when the last input method was keyboard. // Reminder: Touch edgy does not count as an input method. element.addEventListener("pointerdown", function (ev) { // In case pointer down came on the active element. WinJS.Utilities.removeClass(ev.srcElement, "win-keyboard"); }, true); element.addEventListener("keydown", function (ev) { WinJS.Utilities.addClass(ev.srcElement, "win-keyboard"); }, true); element.addEventListener("focusin", function (ev) { WinJS.UI._keyboardSeenLast && WinJS.Utilities.addClass(ev.srcElement, "win-keyboard"); }, true); element.addEventListener("focusout", function (ev) { WinJS.Utilities.removeClass(ev.srcElement, "win-keyboard"); }, true); }, _KeyboardBehavior: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function KeyboardBehavior_ctor(element, options) { // KeyboardBehavior allows you to easily convert a bunch of tabable elements into a single tab stop with // navigation replaced by keyboard arrow (Up/Down/Left/Right) + Home + End + Custom keys. // // Example use cases: // // 1 Dimensional list: FixedDirection = height and FixedSize = 1; // [1] [ 2 ] [ 3 ] [4] [ 5 ]... // // 2 Dimensional list: FixedDirection = height and FixedSize = 2; // [1] [3] [5] [7] ... // [2] [4] [6] [8] // // 1 Dimensional list: FixedDirection = width and FixedSize = 1; // [ 1 ] // - - // | | // | 2 | // | | // - - // [ 3 ] // [ 4 ] // ... // // 2 Dimensional list: FixedDirection = width and FixedSize = 2; // [1][2] // [3][4] // [5][6] // ... // // Currently it is a "behavior" instead of a "control" so it can be attached to the same element as a // winControl. The main scenario for this would be to attach it to the same element as a repeater. // // It also blocks "Portaling" where you go off the end of one column and wrap around to the other // column. It also blocks "Carousel" where you go from the end of the list to the beginning. // // Keyboarding behavior supports nesting. It supports your tab stops having sub tab stops. If you want // an interactive element within the tab stop you need to use the win-interactive classname or during the // keydown event stop propogation so that the event is skipped. // // If you have custom keyboarding the getAdjacent API is provided. This can be used to enable keyboarding // in multisize 2d lists or custom keyboard commands. PageDown and PageUp are the most common since this // behavior does not detect scrollers. // // It also allows developers to show/hide keyboard focus rectangles themselves. // // It has an API called currentIndex so that Tab (or Shift+Tab) or a developer imitating Tab will result in // the correct item having focus. // // It also allows an element to be represented as 2 arrow stops (commonly used for a split button) by calling // the _getFocusInto API on the child element's winControl if it exists. element = element || document.createElement("DIV"); options = options || {}; element._keyboardBehavior = this; this._element = element; this._fixedDirection = WinJS.UI._KeyboardBehavior.FixedDirection.width; this._fixedSize = 1; this._currentIndex = 0; WinJS.UI.setOptions(this, options); this._element.addEventListener('keydown', this._keyDownHandler.bind(this)); this._element.addEventListener('pointerdown', this._MSPointerDownHandler.bind(this)); this._element.addEventListener("beforeactivate", this._beforeActivateHandler.bind(this)); }, { element: { get: function () { return this._element; } }, fixedDirection: { get: function () { return this._fixedDirection; }, set: function (value) { this._fixedDirection = value; } }, fixedSize: { get: function () { return this._fixedSize; }, set: function (value) { if (+value === value) { value = Math.max(1, value); this._fixedSize = value; } } }, currentIndex: { get: function () { if (this._element.children.length > 0) { return this._currentIndex; } return -1; }, set: function (value) { if (+value === value) { var length = this._element.children.length; value = Math.max(0, Math.min(length - 1, value)); this._currentIndex = value; } } }, getAdjacent: { get: function () { return this._getAdjacent }, set: function (value) { this._getAdjacent = value; } }, _keyDownHandler: function _KeyboardBehavior_keyDownHandler(ev) { if (!ev.altKey) { if (ev.srcElement.msMatchesSelector(".win-interactive, .win-interactive *")) { return; } var blockScrolling = false; var newIndex = this.currentIndex; var maxIndex = this._element.children.length - 1; var minIndex = 0; var rtl = getComputedStyle(this._element).direction === "rtl"; var leftStr = rtl ? "Right" : "Left"; var rightStr = rtl ? "Left" : "Right"; var targetIndex = this.getAdjacent && this.getAdjacent(newIndex, ev.key); if (+targetIndex === targetIndex) { blockScrolling = true; newIndex = targetIndex; } else { var modFixedSize = newIndex % this.fixedSize; if (ev.key === leftStr) { blockScrolling = true; if (this.fixedDirection === WinJS.UI._KeyboardBehavior.FixedDirection.width) { if (modFixedSize !== 0) { newIndex--; } } else { if (newIndex >= this.fixedSize) { newIndex -= this.fixedSize; } } } else if (ev.key === rightStr) { blockScrolling = true; if (this.fixedDirection === WinJS.UI._KeyboardBehavior.FixedDirection.width) { if (modFixedSize !== this.fixedSize - 1) { newIndex++; } } else { if (newIndex + this.fixedSize - modFixedSize <= maxIndex) { newIndex += this.fixedSize; } } } else if (ev.key === "Up") { blockScrolling = true; if (this.fixedDirection === WinJS.UI._KeyboardBehavior.FixedDirection.height) { if (modFixedSize !== 0) { newIndex--; } } else { if (newIndex >= this.fixedSize) { newIndex -= this.fixedSize; } } } else if (ev.key === "Down") { blockScrolling = true; if (this.fixedDirection === WinJS.UI._KeyboardBehavior.FixedDirection.height) { if (modFixedSize !== this.fixedSize - 1) { newIndex++; } } else { if (newIndex + this.fixedSize - modFixedSize <= maxIndex) { newIndex += this.fixedSize; } } } else if (ev.key === "Home") { blockScrolling = true; newIndex = 0; } else if (ev.key === "End") { blockScrolling = true; newIndex = this._element.children.length - 1; } else if (ev.key === "PageUp") { blockScrolling = true; } else if (ev.key === "PageDown") { blockScrolling = true; } } newIndex = Math.max(0, Math.min(this._element.children.length - 1, newIndex)); if (newIndex !== this.currentIndex) { this._focus(newIndex, ev.key); // Allow KeyboardBehavior to be nested if (ev.key === leftStr || ev.key === rightStr || ev.key === "Up" || ev.key === "Down") { ev.stopPropagation(); } } if (blockScrolling) { ev.preventDefault(); } } }, _focus: function _KeyboardBehavior_focus(index, key) { index = (+index === index) ? index : this.currentIndex; var elementToFocus = this._element.children[index]; if (elementToFocus) { if (elementToFocus.winControl && elementToFocus.winControl._getFocusInto) { elementToFocus = elementToFocus.winControl._getFocusInto(key); } this.currentIndex = index; try { elementToFocus.setActive(); } catch (e) { } } }, _MSPointerDownHandler: function _KeyboardBehavior_MSPointerDownHandler(ev) { var srcElement = ev.srcElement; if (srcElement === this.element) { return; } while (srcElement.parentNode !== this.element) { srcElement = srcElement.parentNode; } var index = -1; while (srcElement) { index++; srcElement = srcElement.previousElementSibling; } this.currentIndex = index; }, _beforeActivateHandler: function _KeyboardBehavior_beforeActivateHandler(ev) { var allowActivate = false; if (this._element.children.length) { var currentItem = this._element.children[this.currentIndex]; if (currentItem === ev.srcElement || currentItem.contains(ev.srcElement)) { allowActivate = true; } } if (!allowActivate) { ev.stopPropagation(); ev.preventDefault(); } } }, { FixedDirection: { height: "height", width: "width" } }) }) }); })(this, WinJS); (function NavBarInit(global, WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// /// Displays navigation commands in a toolbar that the user can show or hide. /// /// /// /// /// /// ///
///
///
///
]]> /// Raised just before showing the NavBar. /// Raised immediately after an NavBar is fully shown. /// Raised just before hiding the NavBar. /// Raised immediately after the NavBar is fully hidden. /// Fired when children of NavBar control have been processed from a WinJS.UI.processAll call. /// Styles the entire NavBar. /// /// /// NavBar: WinJS.Namespace._lazy(function () { var childrenProcessedEventName = "childrenprocessed"; var createEvent = WinJS.Utilities._createEventProperty; return WinJS.Class.derive(WinJS.UI.AppBar, function NavBar_ctor(element, options) { /// /// /// Creates a new NavBar. /// /// /// The DOM element that will host the new NavBar control. /// /// /// An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's /// properties or events. /// /// /// The new NavBar control. /// /// /// options = options || {}; // Shallow copy object so we can modify it. options = WinJS.Utilities._shallowCopy(options); // Default to Placement = Top and Layout = Custom options.placement = options.placement || "top"; options.layout = "custom"; WinJS.UI.AppBar.call(this, element, options); this._element.addEventListener("beforeshow", this._handleBeforeShow.bind(this)); WinJS.Utilities.addClass(this.element, WinJS.UI.NavBar._ClassName.navbar); if (window.Windows && Windows.ApplicationModel && Windows.ApplicationModel.DesignMode && Windows.ApplicationModel.DesignMode.designModeEnabled) { this._processChildren(); } else { WinJS.Utilities.Scheduler.schedule(this._processChildren.bind(this), WinJS.Utilities.Scheduler.Priority.idle, null, "WinJS.UI.NavBar.processChildren"); } }, { // Block others from setting the layout property. /// /// The layout of the NavBar contents. /// /// layout: { value: "custom", writable: false }, /// /// Raised when children of NavBar control have been processed by a WinJS.UI.processAll call. /// /// onchildrenprocessed: createEvent(childrenProcessedEventName), _processChildren: function NavBar_processChildren() { // The NavBar control schedules processAll on its children at idle priority to avoid hurting startup // performance. If the NavBar is shown before the scheduler gets to the idle job, the NavBar will // immediately call processAll on its children. If your app needs the children to be processed before // the scheduled job executes, you may call processChildren to force the processAll call. if (!this._processed) { this._processed = true; this._writeProfilerMark("processChildren,StartTM"); var that = this; var processed = WinJS.Promise.as(); if (this._processors) { this._processors.forEach(function (processAll) { for (var i = 0, len = that.element.children.length; i < len; i++) { (function (child) { processed = processed.then(function () { processAll(child); }); }(that.element.children[i])); } }); } return processed.then( function () { that._writeProfilerMark("processChildren,StopTM"); that._fireEvent(WinJS.UI.NavBar._EventName.childrenProcessed); }, function () { that._writeProfilerMark("processChildren,StopTM"); that._fireEvent(WinJS.UI.NavBar._EventName.childrenProcessed); } ); } return WinJS.Promise.wrap(); }, _show: function NavBar_show() { // Override _show to call processChildren first. // if (this.disabled) { return; } var that = this; this._processChildren().then(function () { WinJS.UI.AppBar.prototype._show.call(that); }); }, _handleBeforeShow: function NavBar_handleBeforeShow() { // Navbar needs to ensure its elements to have their correct height and width after AppBar changes display="none" // to display="" and AppBar needs the elements to have their final height before it measures its own element height // to do the slide in animation over the correct amount of pixels. if (this._disposed) { return; } var navbarcontainerEls = this.element.querySelectorAll('.win-navbarcontainer'); for (var i = 0; i < navbarcontainerEls.length; i++) { navbarcontainerEls[i].winControl.forceLayout(); } }, _fireEvent: function NavBar_fireEvent(type, detail) { var event = document.createEvent("CustomEvent"); event.initCustomEvent(type, true, false, detail || {}); this.element.dispatchEvent(event); }, _writeProfilerMark: function NavBar_writeProfilerMark(text) { msWriteProfilerMark("WinJS.UI.NavBar:" + this._id + ":" + text); } }, { _ClassName: { navbar: "win-navbar" }, _EventName: { childrenProcessed: childrenProcessedEventName }, isDeclarativeControlContainer: WinJS.Utilities.markSupportedForProcessing(function (navbar, callback) { if (navbar._processed) { for (var i = 0, len = navbar.element.children.length; i < len; i++) { callback(navbar.element.children[i]); } } else { navbar._processors = navbar._processors || []; navbar._processors.push(callback); } }) }); }) }); })(this, WinJS); (function NavBarContainerInit(global, WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// /// Contains a group of NavBarCommand objects in a NavBar. /// /// /// /// /// /// ///
/// ]]>
/// Raised when a NavBarCommand is invoked. /// Raised when the split button on a NavBarCommand is toggled. /// Styles the entire NavBarContainer control. /// /// Styles the page indication for the NavBarContainer. /// /// Styles the page indication for each page. /// /// Styles the indication of the current page. /// /// Styles the area that contains items for the NavBarContainer. /// Styles left and right navigation arrows. /// Styles the left navigation arrow. /// Styles the right navigation arrow. /// /// /// NavBarContainer: WinJS.Namespace._lazy(function () { var buttonFadeDelay = 3000; var PT_TOUCH = MSPointerEvent.MSPOINTER_TYPE_TOUCH || "touch"; var MS_MANIPULATION_STATE_STOPPED = 0; var createEvent = WinJS.Utilities._createEventProperty; var eventNames = { invoked: "invoked", splittoggle: "splittoggle" }; var strings = { get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; }, get navBarContainerViewportAriaLabel() { return WinJS.Resources._getWinJSString("ui/navBarContainerViewportAriaLabel").value; } }; var NavBarContainer = WinJS.Class.define(function NavBarContainer_ctor(element, options) { /// /// /// Creates a new NavBarContainer. /// /// /// The DOM element that will host the NavBarContainer control. /// /// /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". /// /// /// The new NavBarContainer. /// /// /// element = element || document.createElement("DIV"); this._id = element.id || element.uniqueID; this._writeProfilerMark("constructor,StartTM"); options = options || {}; if (element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.NavBarContainer.DuplicateConstruction", strings.duplicateConstruction); } // Attaching JS control to DOM element element.winControl = this; this._element = element; WinJS.Utilities.addClass(this.element, WinJS.UI.NavBarContainer._ClassName.navbarcontainer); WinJS.Utilities.addClass(this.element, "win-disposable"); this._currentManipulationState = MS_MANIPULATION_STATE_STOPPED; this._fixedSize = false; this._maxRows = 1; this._sizes = {}; this._setupTree(); this._duringConstructor = true; this._dataChangingBound = this._dataChanging.bind(this); this._dataChangedBound = this._dataChanged.bind(this); this._navigatedBound = this._navigated.bind(this); WinJS.Navigation.addEventListener('navigated', this._navigatedBound); // Don't use set options for the properties so we can control the ordering to avoid rendering multiple times. this.layout = options.layout || WinJS.UI.Orientation.horizontal; if (options.maxRows) { this.maxRows = options.maxRows; } if (options.template) { this.template = options.template; } if (options.data) { this.data = options.data; } if (options.fixedSize) { this.fixedSize = options.fixedSize; } // Events only WinJS.UI._setOptions(this, options, true); this._duringConstructor = false; if (options.currentIndex) { this.currentIndex = options.currentIndex; } this._updatePageUI(); this._writeProfilerMark("constructor,StopTM"); }, { /// element: { get: function () { return this._element; } }, /// /// Gets or sets a Template or custom rendering function that defines the HTML of each item within the NavBarContainer. /// /// template: { get: function () { return this._template; }, set: function (value) { this._template = value; if (this._repeater) { var hadFocus = this.element.contains(document.activeElement); if (!this._duringConstructor) { this._closeSplitIfOpen(); } // the repeater's template is wired up to this._render() so just resetting it will rebuild the tree. this._repeater.template = this._repeater.template; if (!this._duringConstructor) { this._measured = false; this._sizes.itemMeasured = false; this._reset(); if (hadFocus) { this._keyboardBehavior._focus(0); } } } } }, _render: function NavBarContainer_render(item, wrapperElement) { var navbarCommandEl = document.createElement('div'); var template = this._template; if (template) { if (template.render) { template.render(item, navbarCommandEl); } else if (template.winControl && template.winControl.render) { template.winControl.render(item, navbarCommandEl); } else { navbarCommandEl.appendChild(template(item)); } } // Create the NavBarCommand after calling render so that the reparenting in navbarCommand works. var navbarCommand = new WinJS.UI.NavBarCommand(navbarCommandEl, item); return navbarCommandEl; }, /// /// Gets or sets the WinJS.Binding.List that provides the NavBarContainer with items to display. /// /// data: { get: function () { return this._repeater && this._repeater.data; }, set: function (value) { if (!value) { value = new WinJS.Binding.List(); } if (!this._duringConstructor) { this._closeSplitIfOpen(); } this._removeDataChangingEvents(); this._removeDataChangedEvents(); var hadFocus = this.element.contains(document.activeElement); if (!this._repeater) { this._surfaceEl.innerHTML = ""; this._repeater = new WinJS.UI.Repeater(this._surfaceEl, { template: this._render.bind(this) }); } this._addDataChangingEvents(value); this._repeater.data = value; this._addDataChangedEvents(value); if (!this._duringConstructor) { this._measured = false; this._sizes.itemMeasured = false; this._reset(); if (hadFocus) { this._keyboardBehavior._focus(0); } } } }, /// /// Gets or sets the number of rows allowed to be used before items are placed on additional pages. /// /// maxRows: { get: function () { return this._maxRows; }, set: function (value) { value = (+value === value) ? value : 1; this._maxRows = Math.max(1, value); if (!this._duringConstructor) { this._closeSplitIfOpen(); this._measured = false; this._reset(); } } }, /// /// Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. The default is "horizontal". /// /// layout: { get: function () { return this._layout; }, set: function (value) { if (value === WinJS.UI.Orientation.vertical) { this._layout = WinJS.UI.Orientation.vertical; WinJS.Utilities.removeClass(this.element, WinJS.UI.NavBarContainer._ClassName.horizontal); WinJS.Utilities.addClass(this.element, WinJS.UI.NavBarContainer._ClassName.vertical); } else { this._layout = WinJS.UI.Orientation.horizontal; WinJS.Utilities.removeClass(this.element, WinJS.UI.NavBarContainer._ClassName.vertical); WinJS.Utilities.addClass(this.element, WinJS.UI.NavBarContainer._ClassName.horizontal); } this._viewportEl.style.msScrollSnapType = ""; this._zooming = false; if (!this._duringConstructor) { this._measured = false; this._sizes.itemMeasured = false; this._ensureVisible(this._keyboardBehavior.currentIndex, true); this._updatePageUI(); this._closeSplitIfOpen(); } } }, /// currentIndex: { get: function () { return this._keyboardBehavior.currentIndex; }, set: function (value) { if (value === +value) { var hadFocus = this.element.contains(document.activeElement); this._keyboardBehavior.currentIndex = value; if (this._surfaceEl.children.length > 0) { this._surfaceEl.children[this._keyboardBehavior.currentIndex].winControl._splitButtonActive = false; } this._ensureVisible(this._keyboardBehavior.currentIndex, true); if (hadFocus) { this._keyboardBehavior._focus(); } } } }, /// /// Gets or sets a value that specifies whether child NavBarCommand objects should be a fixed width when there are multiple pages. A value of true indicates /// that the NavBarCommand objects use a fixed width; a value of false indicates that they use a dynamic width. /// /// fixedSize: { get: function () { return this._fixedSize; }, set: function (value) { this._fixedSize = !!value; if (!this._duringConstructor) { this._closeSplitIfOpen(); if (!this._measured) { this._measure(); } else if (this._surfaceEl.children.length > 0) { this._updateGridStyles(); } } } }, /// /// Raised when a NavBarCommand has been invoked. /// /// oninvoked: createEvent(eventNames.invoked), /// /// Raised when the split button on a NavBarCommand is toggled. /// /// onsplittoggle: createEvent(eventNames.splittoggle), forceLayout: function NavBarContainer_forceLayout() { /// /// /// Forces the NavBarContainer to update scroll positions and if there are internal pending measurements, it will also re-measure. /// Use this function when making the NavBarContainer visible again after you set its style.display property to "none". /// /// /// if (this._measured) { if (this.layout === WinJS.UI.Orientation.horizontal) { this._scrollPosition = this._viewportEl.scrollLeft; } else { this._scrollPosition = this._viewportEl.scrollTop; } } this._duringForceLayout = true; this._ensureVisible(this._keyboardBehavior.currentIndex, true); this._updatePageUI(); this._duringForceLayout = false; }, _navigated: function NavBarContainer_navigated() { this._closeSplitIfOpen(); this._reset(); }, _dataChanging: function NavBarContainer_dataChanging(ev) { // Store the element that was active so that we can detect // if the focus went away because of the data change. this._elementHadFocus = document.activeElement; if (this._currentSplitNavItem && this._currentSplitNavItem.splitOpened) { if (ev.type === "itemremoved") { if (this._surfaceEl.children[ev.detail.index].winControl === this._currentSplitNavItem) { this._closeSplitIfOpen(); } } else if (ev.type === "itemchanged") { if (this._surfaceEl.children[ev.detail.index].winControl === this._currentSplitNavItem) { this._closeSplitIfOpen(); } } else if (ev.type === "itemmoved") { if (this._surfaceEl.children[ev.detail.oldIndex].winControl === this._currentSplitNavItem) { this._closeSplitIfOpen(); } } else if (ev.type === "reload") { this._closeSplitIfOpen(); } } }, _dataChanged: function NavBarContainer_dataChanged(ev) { this._measured = false; if (ev.type === "itemremoved") { if (ev.detail.index < this._keyboardBehavior.currentIndex) { this._keyboardBehavior.currentIndex--; } else if (ev.detail.index === this._keyboardBehavior.currentIndex) { // This clamps if the item being removed was the last item in the list this._keyboardBehavior.currentIndex = this._keyboardBehavior.currentIndex; if (document.activeElement === null && this._elementHadFocus) { this._keyboardBehavior._focus(); } } } else if (ev.type === "itemchanged") { if (ev.detail.index === this._keyboardBehavior.currentIndex) { if (document.activeElement === null && this._elementHadFocus) { this._keyboardBehavior._focus(); } } } else if (ev.type === "iteminserted") { if (ev.detail.index <= this._keyboardBehavior.currentIndex) { this._keyboardBehavior.currentIndex++; } } else if (ev.type === "itemmoved") { if (ev.detail.oldIndex === this._keyboardBehavior.currentIndex) { this._keyboardBehavior.currentIndex = ev.detail.newIndex; if (document.activeElement === null && this._elementHadFocus) { this._keyboardBehavior._focus(); } } } else if (ev.type === "reload") { this._keyboardBehavior.currentIndex = 0; if (document.activeElement === null && this._elementHadFocus) { this._keyboardBehavior._focus(); } } this._ensureVisible(this._keyboardBehavior.currentIndex, true); this._updatePageUI(); }, _reset: function NavBarContainer_reset() { this._keyboardBehavior.currentIndex = 0; if (this._surfaceEl.children.length > 0) { this._surfaceEl.children[this._keyboardBehavior.currentIndex].winControl._splitButtonActive = false; } if (this.element.contains(document.activeElement)) { this._keyboardBehavior._focus(0); } this._viewportEl.style.msScrollSnapType = ""; this._zooming = false; this._ensureVisible(0, true); this._updatePageUI(); }, _removeDataChangedEvents: function NavBarContainer_removeDataChangedEvents() { if (this._repeater) { this._repeater.data.removeEventListener("itemchanged", this._dataChangedBound); this._repeater.data.removeEventListener("iteminserted", this._dataChangedBound); this._repeater.data.removeEventListener("itemmoved", this._dataChangedBound); this._repeater.data.removeEventListener("itemremoved", this._dataChangedBound); this._repeater.data.removeEventListener("reload", this._dataChangedBound); } }, _addDataChangedEvents: function NavBarContainer_addDataChangedEvents(bindingList) { if (this._repeater) { this._repeater.data.addEventListener("itemchanged", this._dataChangedBound); this._repeater.data.addEventListener("iteminserted", this._dataChangedBound); this._repeater.data.addEventListener("itemmoved", this._dataChangedBound); this._repeater.data.addEventListener("itemremoved", this._dataChangedBound); this._repeater.data.addEventListener("reload", this._dataChangedBound); } }, _removeDataChangingEvents: function NavBarContainer_removeDataChangingEvents() { if (this._repeater) { this._repeater.data.removeEventListener("itemchanged", this._dataChangingBound); this._repeater.data.removeEventListener("iteminserted", this._dataChangingBound); this._repeater.data.removeEventListener("itemmoved", this._dataChangingBound); this._repeater.data.removeEventListener("itemremoved", this._dataChangingBound); this._repeater.data.removeEventListener("reload", this._dataChangingBound); } }, _addDataChangingEvents: function NavBarContainer_addDataChangingEvents(bindingList) { bindingList.addEventListener("itemchanged", this._dataChangingBound); bindingList.addEventListener("iteminserted", this._dataChangingBound); bindingList.addEventListener("itemmoved", this._dataChangingBound); bindingList.addEventListener("itemremoved", this._dataChangingBound); bindingList.addEventListener("reload", this._dataChangingBound); }, _mouseleave: function NavBarContainer_mouseleave(ev) { if (this._mouseInViewport) { this._mouseInViewport = false; this._updateArrows(); } }, _MSPointerDown: function NavBarContainer_MSPointerDown(ev) { if (ev.pointerType === PT_TOUCH) { if (this._mouseInViewport) { this._mouseInViewport = false; this._updateArrows(); } } }, _MSPointerMove: function NavBarContainer_MSPointerMove(ev) { if (ev.pointerType !== PT_TOUCH) { if (!this._mouseInViewport) { this._mouseInViewport = true; this._updateArrows(); } } }, _setupTree: function NavBarContainer_setupTree() { this._animateNextPreviousButtons = WinJS.Promise.wrap(); this._element.addEventListener('mouseleave', this._mouseleave.bind(this)); this._element.addEventListener('pointerdown', this._MSPointerDown.bind(this)); this._element.addEventListener('pointermove', this._MSPointerMove.bind(this)); this._element.addEventListener("focus", this._focusHandler.bind(this), true); this._pageindicatorsEl = document.createElement('div'); WinJS.Utilities.addClass(this._pageindicatorsEl, WinJS.UI.NavBarContainer._ClassName.pageindicators); this._element.appendChild(this._pageindicatorsEl); this._ariaStartMarker = document.createElement("div"); this._element.appendChild(this._ariaStartMarker); this._viewportEl = document.createElement('div'); WinJS.Utilities.addClass(this._viewportEl, WinJS.UI.NavBarContainer._ClassName.viewport); this._element.appendChild(this._viewportEl); this._viewportEl.setAttribute("role", "group"); this._viewportEl.setAttribute("aria-label", strings.navBarContainerViewportAriaLabel); this._boundResizeHandler = this._resizeHandler.bind(this); window.addEventListener("resize", this._boundResizeHandler); this._viewportEl.addEventListener("mselementresize", this._resizeHandler.bind(this)); this._viewportEl.addEventListener("scroll", this._scrollHandler.bind(this)); this._viewportEl.addEventListener("MSManipulationStateChanged", this._MSManipulationStateChangedHandler.bind(this)); this._ariaEndMarker = document.createElement("div"); this._element.appendChild(this._ariaEndMarker); this._surfaceEl = document.createElement('div'); WinJS.Utilities.addClass(this._surfaceEl, WinJS.UI.NavBarContainer._ClassName.surface); this._viewportEl.appendChild(this._surfaceEl); this._surfaceEl.addEventListener("_invoked", this._navbarCommandInvokedHandler.bind(this)); this._surfaceEl.addEventListener("_splittoggle", this._navbarCommandSplitToggleHandler.bind(this)); this._surfaceEl.addEventListener("focus", this._itemsFocusHandler.bind(this), true); this._surfaceEl.addEventListener("keydown", this._keyDownHandler.bind(this)); // Reparent NavBarCommands which were in declarative markup var tempEl = this.element.firstElementChild; while (tempEl !== this._pageindicatorsEl) { this._surfaceEl.appendChild(tempEl); WinJS.UI.process(tempEl); tempEl = this.element.firstElementChild; } this._leftArrowEl = document.createElement('div'); WinJS.Utilities.addClass(this._leftArrowEl, WinJS.UI.NavBarContainer._ClassName.navleftarrow); WinJS.Utilities.addClass(this._leftArrowEl, WinJS.UI.NavBarContainer._ClassName.navarrow); this._element.appendChild(this._leftArrowEl); this._leftArrowEl.addEventListener('click', this._goLeft.bind(this)); this._leftArrowEl.style.opacity = 0; this._leftArrowEl.style.visibility = 'hidden'; this._leftArrowFadeOut = WinJS.Promise.wrap(); this._rightArrowEl = document.createElement('div'); WinJS.Utilities.addClass(this._rightArrowEl, WinJS.UI.NavBarContainer._ClassName.navrightarrow); WinJS.Utilities.addClass(this._rightArrowEl, WinJS.UI.NavBarContainer._ClassName.navarrow); this._element.appendChild(this._rightArrowEl); this._rightArrowEl.addEventListener('click', this._goRight.bind(this)); this._rightArrowEl.style.opacity = 0; this._rightArrowEl.style.visibility = 'hidden'; this._rightArrowFadeOut = WinJS.Promise.wrap(); this._keyboardBehavior = new WinJS.UI._KeyboardBehavior(this._surfaceEl); this._winKeyboard = new WinJS.UI._WinKeyboard(this._surfaceEl); }, _goRight: function NavBarContainer_goRight() { if (this._sizes.rtl) { this._goPrev(); } else { this._goNext(); } }, _goLeft: function NavBarContainer_goLeft() { if (this._sizes.rtl) { this._goNext(); } else { this._goPrev(); } }, _goNext: function NavBarContainer_goNext() { this._measure(); var itemsPerPage = this._sizes.rowsPerPage * this._sizes.columnsPerPage; var targetPage = Math.min(Math.floor(this._keyboardBehavior.currentIndex / itemsPerPage) + 1, this._sizes.pages - 1); this._keyboardBehavior.currentIndex = Math.min(itemsPerPage * targetPage, this._surfaceEl.children.length); this._keyboardBehavior._focus(); }, _goPrev: function NavBarContainer_goPrev() { this._measure(); var itemsPerPage = this._sizes.rowsPerPage * this._sizes.columnsPerPage; var targetPage = Math.max(0, Math.floor(this._keyboardBehavior.currentIndex / itemsPerPage) - 1); this._keyboardBehavior.currentIndex = Math.max(itemsPerPage * targetPage, 0); this._keyboardBehavior._focus(); }, _currentPage: { get: function () { if (this.layout === WinJS.UI.Orientation.horizontal) { this._measure(); if (this._sizes.viewportOffsetWidth > 0) { return Math.min(this._sizes.pages - 1, Math.round(this._scrollPosition / this._sizes.viewportOffsetWidth)); } } return 0; } }, _resizeHandler: function NavBarContainer_resizeHandler() { if (this._disposed) { return; } if (this._measured) { this._measured = false; if (!this._pendingResize) { this._pendingResize = true; this._resizeImplBound = this._resizeImplBound || this._resizeImpl.bind(this); if (!this._appBarEl || !this._appBarEl.contains(this.element)) { if (this._appBarEl) { this._appBarEl.removeEventListener('beforeshow', this._resizeImplBound); } var appBarEl = this.element.parentNode; while (appBarEl && !WinJS.Utilities.hasClass(appBarEl, 'win-appbar')) { appBarEl = appBarEl.parentNode; } this._appBarEl = appBarEl; } if (this._appBarEl && this._appBarEl.winControl && this._appBarEl.winControl.hidden) { // Do resize lazily. WinJS.Utilities.Scheduler.schedule(this._resizeImplBound, WinJS.Utilities.Scheduler.Priority.idle, null, "WinJS.UI.NavBarContainer._resizeImpl"); this._appBarEl.addEventListener('beforeshow', this._resizeImplBound); } else { // Do resize now this._resizeImpl(); } } } }, _resizeImpl: function NavBarContainer_resizeImpl() { if (!this._disposed && this._pendingResize) { this._pendingResize = false; if (this._appBarEl) { this._appBarEl.removeEventListener('beforeshow', this._resizeImplBound); } this._keyboardBehavior.currentIndex = 0; if (this._surfaceEl.children.length > 0) { this._surfaceEl.children[0].winControl._splitButtonActive = false; } if (this.element.contains(document.activeElement)) { this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex); } this._closeSplitIfOpen(); this._ensureVisible(this._keyboardBehavior.currentIndex, true); this._updatePageUI(); } }, _keyDownHandler: function NavBarContainer_keyDownHandler(ev) { var key = ev.key if (!ev.altKey && (key === "PageUp" || key === "PageDown")) { var srcElement = ev.srcElement; if (srcElement.msMatchesSelector(".win-interactive, .win-interactive *")) { return; } var index = this._keyboardBehavior.currentIndex; this._measure(); var sizes = this._sizes; var page = Math.floor(index / (sizes.columnsPerPage * sizes.rowsPerPage)); var scrollPositionTarget = null; if (key === "PageUp") { if (this.layout === WinJS.UI.Orientation.horizontal) { var indexOfFirstItemOnPage = page * sizes.columnsPerPage * sizes.rowsPerPage; if (index === indexOfFirstItemOnPage && this._surfaceEl.children[index].winControl._buttonEl === document.activeElement) { // First item on page so go back 1 page. index = index - sizes.columnsPerPage * sizes.rowsPerPage; } else { // Not first item on page so go to the first item on page. index = indexOfFirstItemOnPage; } } else { var currentItem = this._surfaceEl.children[index]; var top = currentItem.offsetTop; var bottom = top + currentItem.offsetHeight; var scrollPosition = this._zooming ? this._zoomPosition : this._scrollPosition; if (top >= scrollPosition && bottom < scrollPosition + sizes.viewportOffsetHeight) { // current item is fully on screen. while (index > 0 && this._surfaceEl.children[index - 1].offsetTop > scrollPosition) { index--; } } if (this._keyboardBehavior.currentIndex === index) { var scrollPositionForOnePageAboveItem = bottom - sizes.viewportOffsetHeight; index = Math.max(0, index - 1); while (index > 0 && this._surfaceEl.children[index - 1].offsetTop > scrollPositionForOnePageAboveItem) { index--; } if (index > 0) { scrollPositionTarget = this._surfaceEl.children[index].offsetTop - this._sizes.itemMarginTop; } else { scrollPositionTarget = 0; } } } index = Math.max(index, 0); this._keyboardBehavior.currentIndex = index; var element = this._surfaceEl.children[index].winControl._buttonEl; this._surfaceEl.children[index].winControl._splitButtonActive = false; if (scrollPositionTarget !== null) { this._scrollTo(scrollPositionTarget); } try { element.setActive(); } catch (e) { } } else { if (this.layout === WinJS.UI.Orientation.horizontal) { var indexOfLastItemOnPage = (page + 1) * sizes.columnsPerPage * sizes.rowsPerPage - 1; if (index === indexOfLastItemOnPage) { // Last item on page so go forward 1 page. index = index + sizes.columnsPerPage * sizes.rowsPerPage; } else { // Not Last item on page so go to last item on page. index = indexOfLastItemOnPage; } } else { var currentItem = this._surfaceEl.children[this._keyboardBehavior.currentIndex]; var top = currentItem.offsetTop; var bottom = top + currentItem.offsetHeight; var scrollPosition = this._zooming ? this._zoomPosition : this._scrollPosition; if (top >= scrollPosition && bottom < scrollPosition + sizes.viewportOffsetHeight) { // current item is fully on screen. while (index < this._surfaceEl.children.length - 1 && this._surfaceEl.children[index + 1].offsetTop + this._surfaceEl.children[index + 1].offsetHeight < scrollPosition + sizes.viewportOffsetHeight) { index++; } } if (index === this._keyboardBehavior.currentIndex) { var scrollPositionForOnePageBelowItem = top + sizes.viewportOffsetHeight; index = Math.min(this._surfaceEl.children.length - 1, index + 1); while (index < this._surfaceEl.children.length - 1 && this._surfaceEl.children[index + 1].offsetTop + this._surfaceEl.children[index + 1].offsetHeight < scrollPositionForOnePageBelowItem) { index++; } if (index < this._surfaceEl.children.length - 1) { scrollPositionTarget = this._surfaceEl.children[index + 1].offsetTop - this._sizes.viewportOffsetHeight; } else { scrollPositionTarget = this._scrollLength - this._sizes.viewportOffsetHeight; } } } index = Math.min(index, this._surfaceEl.children.length - 1); this._keyboardBehavior.currentIndex = index; var element = this._surfaceEl.children[index].winControl._buttonEl; this._surfaceEl.children[index].winControl._splitButtonActive = false; if (scrollPositionTarget !== null) { this._scrollTo(scrollPositionTarget); } try { element.setActive(); } catch (e) { } } } }, _focusHandler: function NavBarContainer_focusHandler(ev) { var srcElement = ev.srcElement; if (!this._surfaceEl.contains(srcElement)) { // Forward focus from NavBarContainer, viewport or surface to the currentIndex. this._skipEnsureVisible = true; this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex); } }, _itemsFocusHandler: function NavBarContainer_itemsFocusHandler(ev) { // Find the item which is being focused and scroll it to view. var srcElement = ev.srcElement; if (srcElement === this._surfaceEl) { return; } while (srcElement.parentNode !== this._surfaceEl) { srcElement = srcElement.parentNode; } var index = -1; while (srcElement) { index++; srcElement = srcElement.previousSibling; } if (this._skipEnsureVisible) { this._skipEnsureVisible = false; } else { this._ensureVisible(index); } }, _ensureVisible: function NavBarContainer_ensureVisible(index, withoutAnimation) { this._measure(); if (this.layout === WinJS.UI.Orientation.horizontal) { var page = Math.floor(index / (this._sizes.rowsPerPage * this._sizes.columnsPerPage)); this._scrollTo(page * this._sizes.viewportOffsetWidth, withoutAnimation); } else { var element = this._surfaceEl.children[index]; var maxScrollPosition; if (index > 0) { maxScrollPosition = element.offsetTop - this._sizes.itemMarginTop; } else { maxScrollPosition = 0; } var minScrollPosition; if (index < this._surfaceEl.children.length - 1) { minScrollPosition = this._surfaceEl.children[index + 1].offsetTop - this._sizes.viewportOffsetHeight; } else { minScrollPosition = this._scrollLength - this._sizes.viewportOffsetHeight; } var newScrollPosition = this._zooming ? this._zoomPosition : this._scrollPosition; newScrollPosition = Math.max(newScrollPosition, minScrollPosition); newScrollPosition = Math.min(newScrollPosition, maxScrollPosition); this._scrollTo(newScrollPosition, withoutAnimation); } }, _scrollTo: function NavBarContainer_scrollTo(targetScrollPosition, withoutAnimation) { this._measure(); if (this.layout === WinJS.UI.Orientation.horizontal) { targetScrollPosition = Math.max(0, Math.min(this._scrollLength - this._sizes.viewportOffsetWidth, targetScrollPosition)); } else { targetScrollPosition = Math.max(0, Math.min(this._scrollLength - this._sizes.viewportOffsetHeight, targetScrollPosition)); } if (withoutAnimation) { if (Math.abs(this._scrollPosition - targetScrollPosition) > 1) { this._zooming = false; this._scrollPosition = targetScrollPosition; this._updatePageUI(); if (!this._duringForceLayout) { this._closeSplitIfOpen(); } if (this.layout === WinJS.UI.Orientation.horizontal) { this._viewportEl.scrollLeft = targetScrollPosition; } else { this._viewportEl.scrollTop = targetScrollPosition; } } } else { if ((!this._zooming && Math.abs(this._scrollPosition - targetScrollPosition) > 1) || (this._zooming && Math.abs(this._zoomPosition - targetScrollPosition) > 1)) { this._zoomPosition = targetScrollPosition; this._zooming = true; if (this.layout === WinJS.UI.Orientation.horizontal) { this._viewportEl.style.msScrollSnapType = "none"; this._viewportEl.msZoomTo({ contentX: targetScrollPosition, contentY: 0, viewportX: 0, viewportY: 0 }); } else { this._viewportEl.msZoomTo({ contentX: 0, contentY: targetScrollPosition, viewportX: 0, viewportY: 0 }); } this._closeSplitIfOpen(); } } }, _MSManipulationStateChangedHandler: function NavBarContainer_MSManipulationStateChangedHandler(e) { this._currentManipulationState = e.currentState; if (e.currentState === e.MS_MANIPULATION_STATE_ACTIVE) { this._viewportEl.style.msScrollSnapType = ""; this._zooming = false; } clearTimeout(this._manipulationStateTimeoutId); // The extra stop event is firing when an msZoomTo is called during another msZoomTo and // also the first msZoomTo after a resize. if (e.currentState === e.MS_MANIPULATION_STATE_STOPPED) { this._manipulationStateTimeoutId = setTimeout(function () { this._viewportEl.style.msScrollSnapType = ""; this._zooming = false; this._updateCurrentIndexIfPageChanged(); }.bind(this), 100); } }, _scrollHandler: function NavBarContainer_scrollHandler() { this._measured = false; if (!this._checkingScroll) { var that = this; this._checkingScroll = requestAnimationFrame(function () { that._checkingScroll = null; var newScrollPosition; if (that.layout === WinJS.UI.Orientation.horizontal) { newScrollPosition = that._viewportEl.scrollLeft; } else { newScrollPosition = that._viewportEl.scrollTop; } if (newScrollPosition !== that._scrollPosition) { that._scrollPosition = newScrollPosition; that._closeSplitIfOpen(); } that._updatePageUI(); if (!that._zooming && this._currentManipulationState === MS_MANIPULATION_STATE_STOPPED) { that._updateCurrentIndexIfPageChanged(); } }); } }, _updateCurrentIndexIfPageChanged: function NavBarContainer_updateCurrentIndexIfPageChanged() { // If you change pages via pagination arrows, mouse wheel, or panning we need to update the current // item to be the first item on the new page. if (this.layout === WinJS.UI.Orientation.horizontal) { this._measure(); var currentPage = this._currentPage; var firstIndexOnPage = currentPage * this._sizes.rowsPerPage * this._sizes.columnsPerPage; var lastIndexOnPage = (currentPage + 1) * this._sizes.rowsPerPage * this._sizes.columnsPerPage - 1; if (this._keyboardBehavior.currentIndex < firstIndexOnPage || this._keyboardBehavior.currentIndex > lastIndexOnPage) { // Page change occurred. this._keyboardBehavior.currentIndex = firstIndexOnPage; if (this._surfaceEl.children.length > 0) { this._surfaceEl.children[this._keyboardBehavior.currentIndex].winControl._splitButtonActive = false; } if (this.element.contains(document.activeElement)) { this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex); } } } }, _measure: function NavBarContainer_measure() { if (!this._measured) { this._resizeImpl(); this._writeProfilerMark("measure,StartTM"); var sizes = this._sizes; sizes.rtl = getComputedStyle(this._element).direction === "rtl"; var itemCount = this._surfaceEl.children.length; if (itemCount > 0) { if (!this._sizes.itemMeasured) { this._writeProfilerMark("measureItem,StartTM"); var elementToMeasure = this._surfaceEl.firstElementChild; // Clear inline margins set by NavBarContainer before measuring. elementToMeasure.style.margin = ""; elementToMeasure.style.width = ""; var elementComputedStyle = getComputedStyle(elementToMeasure); sizes.itemOffsetWidth = parseFloat(getComputedStyle(elementToMeasure).width); if (elementToMeasure.offsetWidth === 0) { sizes.itemOffsetWidth = 0; } sizes.itemMarginLeft = parseFloat(elementComputedStyle.marginLeft); sizes.itemMarginRight = parseFloat(elementComputedStyle.marginRight); sizes.itemWidth = sizes.itemOffsetWidth + sizes.itemMarginLeft + sizes.itemMarginRight; sizes.itemOffsetHeight = parseFloat(getComputedStyle(elementToMeasure).height); if (elementToMeasure.offsetHeight === 0) { sizes.itemOffsetHeight = 0; } sizes.itemMarginTop = parseFloat(elementComputedStyle.marginTop); sizes.itemMarginBottom = parseFloat(elementComputedStyle.marginBottom); sizes.itemHeight = sizes.itemOffsetHeight + sizes.itemMarginTop + sizes.itemMarginBottom; if (sizes.itemOffsetWidth > 0 && sizes.itemOffsetHeight > 0) { sizes.itemMeasured = true; } this._writeProfilerMark("measureItem,StopTM"); } sizes.viewportOffsetWidth = parseFloat(getComputedStyle(this._viewportEl).width); if (this._viewportEl.offsetWidth === 0) { sizes.viewportOffsetWidth = 0; } sizes.viewportOffsetHeight = parseFloat(getComputedStyle(this._viewportEl).height); if (this._viewportEl.offsetHeight === 0) { sizes.viewportOffsetHeight = 0; } if (sizes.viewportOffsetWidth === 0 || sizes.itemOffsetHeight === 0) { this._measured = false; } else { this._measured = true; } if (this.layout === WinJS.UI.Orientation.horizontal) { this._scrollPosition = this._viewportEl.scrollLeft; sizes.leadingEdge = this._leftArrowEl.offsetWidth + parseInt(getComputedStyle(this._leftArrowEl).marginLeft) + parseInt(getComputedStyle(this._leftArrowEl).marginRight); var usableSpace = sizes.viewportOffsetWidth - sizes.leadingEdge * 2; sizes.maxColumns = sizes.itemWidth ? Math.max(1, Math.floor(usableSpace / sizes.itemWidth)) : 1; sizes.rowsPerPage = Math.min(this.maxRows, Math.ceil(itemCount / sizes.maxColumns)); sizes.columnsPerPage = Math.min(sizes.maxColumns, itemCount); sizes.pages = Math.ceil(itemCount / (sizes.columnsPerPage * sizes.rowsPerPage)); sizes.trailingEdge = sizes.leadingEdge; sizes.extraSpace = usableSpace - (sizes.columnsPerPage * sizes.itemWidth); this._scrollLength = sizes.viewportOffsetWidth * sizes.pages; this._keyboardBehavior.fixedSize = sizes.rowsPerPage; this._keyboardBehavior.fixedDirection = WinJS.UI._KeyboardBehavior.FixedDirection.height; this._surfaceEl.style.height = (sizes.itemHeight * sizes.rowsPerPage) + "px"; this._surfaceEl.style.width = this._scrollLength + "px"; } else { this._scrollPosition = this._viewportEl.scrollTop; sizes.leadingEdge = 0; sizes.rowsPerPage = itemCount; sizes.columnsPerPage = 1; sizes.pages = 1; sizes.trailingEdge = 0; // Reminder there is margin collapsing so just use scrollHeight instead of itemHeight * itemCount this._scrollLength = this._viewportEl.scrollHeight; this._keyboardBehavior.fixedSize = sizes.columnsPerPage; this._keyboardBehavior.fixedDirection = WinJS.UI._KeyboardBehavior.FixedDirection.width; this._surfaceEl.style.height = ""; this._surfaceEl.style.width = ""; } this._updateGridStyles(); } else { sizes.pages = 1; this._hasPreviousContent = false; this._hasNextContent = false; this._surfaceEl.style.height = ""; this._surfaceEl.style.width = ""; } this._writeProfilerMark("measure,StopTM"); } }, _updateGridStyles: function NavBarContainer_updateGridStyles() { var sizes = this._sizes; var itemCount = this._surfaceEl.children.length; for (var index = 0; index < itemCount; index++) { var itemEl = this._surfaceEl.children[index]; var marginRight; var marginLeft; var cssRow; var cssColumn; var width = ""; if (this.layout === WinJS.UI.Orientation.horizontal) { var row = Math.floor(index % sizes.rowsPerPage); var column = Math.floor(index / sizes.rowsPerPage); var isFirstColumnOnPage = column % sizes.columnsPerPage === 0; var isLastColumnOnPage = column % sizes.columnsPerPage === sizes.columnsPerPage - 1; var extraTrailingMargin = sizes.trailingEdge; if (this.fixedSize) { extraTrailingMargin += sizes.extraSpace; } else { var spaceToDistribute = sizes.extraSpace - (sizes.maxColumns - sizes.columnsPerPage) * sizes.itemWidth; width = (sizes.itemOffsetWidth + (spaceToDistribute / sizes.maxColumns)) + "px"; } cssRow = row + 1; cssColumn = column + 1; var extraMarginRight; var extraMarginLeft; if (sizes.rtl) { extraMarginRight = (isFirstColumnOnPage ? sizes.leadingEdge : 0); extraMarginLeft = (isLastColumnOnPage ? extraTrailingMargin : 0); } else { extraMarginRight = (isLastColumnOnPage ? extraTrailingMargin : 0); extraMarginLeft = (isFirstColumnOnPage ? sizes.leadingEdge : 0); } marginRight = extraMarginRight + sizes.itemMarginRight + "px"; marginLeft = extraMarginLeft + sizes.itemMarginLeft + "px"; } else { cssRow = ""; cssColumn = ""; marginRight = ""; marginLeft = ""; } if (itemEl.style.msGridRow !== cssRow) { itemEl.style.msGridRow = cssRow; } if (itemEl.style.msGridColumn !== cssColumn) { itemEl.style.msGridColumn = cssColumn; } if (itemEl.style.marginRight !== marginRight) { itemEl.style.marginRight = marginRight; } if (itemEl.style.marginLeft !== marginLeft) { itemEl.style.marginLeft = marginLeft; } if (itemEl.style.width !== width) { itemEl.style.width = width; } } }, _updatePageUI: function NavBarContainer_updatePageUI() { this._measure(); var currentPage = this._currentPage; this._hasPreviousContent = (currentPage !== 0); this._hasNextContent = (currentPage < this._sizes.pages - 1); this._updateArrows(); // Always output the pagination indicators so they reserves up space. if (this._indicatorCount !== this._sizes.pages) { this._indicatorCount = this._sizes.pages; this._pageindicatorsEl.innerHTML = new Array(this._sizes.pages + 1).join(''); } for (var i = 0; i < this._pageindicatorsEl.children.length; i++) { if (i === currentPage) { WinJS.Utilities.addClass(this._pageindicatorsEl.children[i], WinJS.UI.NavBarContainer._ClassName.currentindicator); } else { WinJS.Utilities.removeClass(this._pageindicatorsEl.children[i], WinJS.UI.NavBarContainer._ClassName.currentindicator); } } if (this._sizes.pages > 1) { this._viewportEl.style.overflowX = ""; this._pageindicatorsEl.style.visibility = ""; } else { this._viewportEl.style.overflowX = "hidden"; this._pageindicatorsEl.style.visibility = "hidden"; } if (this._sizes.pages <= 1 || this._layout !== WinJS.UI.Orientation.horizontal) { this._ariaStartMarker.removeAttribute("aria-flowto"); this._ariaEndMarker.removeAttribute("x-ms-aria-flowfrom"); } else { var firstIndexOnCurrentPage = currentPage * this._sizes.rowsPerPage * this._sizes.columnsPerPage; var firstItem = this._surfaceEl.children[firstIndexOnCurrentPage].winControl._buttonEl; WinJS.UI._ensureId(firstItem); this._ariaStartMarker.setAttribute("aria-flowto", firstItem.id); var lastIndexOnCurrentPage = Math.min(this._surfaceEl.children.length - 1, (currentPage + 1) * this._sizes.rowsPerPage * this._sizes.columnsPerPage - 1); var lastItem = this._surfaceEl.children[lastIndexOnCurrentPage].winControl._buttonEl; WinJS.UI._ensureId(lastItem); this._ariaEndMarker.setAttribute("x-ms-aria-flowfrom", lastItem.id); } }, _closeSplitIfOpen: function NavBarContainer_closeSplitIfOpen() { if (this._currentSplitNavItem) { if (this._currentSplitNavItem.splitOpened) { this._currentSplitNavItem._toggleSplit(); } this._currentSplitNavItem = null; } }, _updateArrows: function NavBarContainer_updateArrows() { var hasLeftContent = this._sizes.rtl ? this._hasNextContent : this._hasPreviousContent; var hasRightContent = this._sizes.rtl ? this._hasPreviousContent : this._hasNextContent; var that = this; // Previous and next are the arrows, not states. On mouse hover the arrows fade in immediately. If you // mouse out the arrows fade out after a delay. When you reach the last/first page, the corresponding // arrow fades out immediately as well. if (this._mouseInViewport && hasLeftContent) { this._leftArrowWaitingToFadeOut && this._leftArrowWaitingToFadeOut.cancel(); this._leftArrowWaitingToFadeOut = null; this._leftArrowFadeOut && this._leftArrowFadeOut.cancel(); this._leftArrowFadeOut = null; this._leftArrowEl.style.visibility = ''; this._leftArrowFadeIn = this._leftArrowFadeIn || WinJS.UI.Animation.fadeIn(this._leftArrowEl); } else { if (hasLeftContent) { // If we need a delayed fade out and we are already running a delayed fade out just use that one, don't extend it. // Otherwise create a delayed fade out. this._leftArrowWaitingToFadeOut = this._leftArrowWaitingToFadeOut || WinJS.Promise.timeout(buttonFadeDelay); } else { // If we need a immediate fade out and already have a delayed fade out cancel that one and create an immediate one. this._leftArrowWaitingToFadeOut && this._leftArrowWaitingToFadeOut.cancel(); this._leftArrowWaitingToFadeOut = WinJS.Promise.wrap(); } this._leftArrowWaitingToFadeOut.then(function () { // After the delay cancel any fade in if running. If we already were fading out continue it otherwise start the fade out. this._leftArrowFadeIn && this._leftArrowFadeIn.cancel(); this._leftArrowFadeIn = null; this._leftArrowFadeOut = this._leftArrowFadeOut || WinJS.UI.Animation.fadeOut(this._leftArrowEl).then(function () { that._leftArrowEl.style.visibility = 'hidden'; }); }.bind(this)); } // Same pattern for Next arrow. if (this._mouseInViewport && hasRightContent) { this._rightArrowWaitingToFadeOut && this._rightArrowWaitingToFadeOut.cancel(); this._rightArrowWaitingToFadeOut = null; this._rightArrowFadeOut && this._rightArrowFadeOut.cancel(); this._rightArrowFadeOut = null; this._rightArrowEl.style.visibility = ''; this._rightArrowFadeIn = this._rightArrowFadeIn || WinJS.UI.Animation.fadeIn(this._rightArrowEl); } else { if (hasRightContent) { this._rightArrowWaitingToFadeOut = this._rightArrowWaitingToFadeOut || WinJS.Promise.timeout(buttonFadeDelay); } else { this._rightArrowWaitingToFadeOut && this._rightArrowWaitingToFadeOut.cancel(); this._rightArrowWaitingToFadeOut = WinJS.Promise.wrap(); } this._rightArrowWaitingToFadeOut.then(function () { this._rightArrowFadeIn && this._rightArrowFadeIn.cancel(); this._rightArrowFadeIn = null; this._rightArrowFadeOut = this._rightArrowFadeOut || WinJS.UI.Animation.fadeOut(this._rightArrowEl).then(function () { that._rightArrowEl.style.visibility = 'hidden'; }); }.bind(this)); } }, _navbarCommandInvokedHandler: function NavBarContainer_navbarCommandInvokedHandler(ev) { var srcElement = ev.srcElement; var index = -1; while (srcElement) { index++; srcElement = srcElement.previousSibling; } this._fireEvent(WinJS.UI.NavBarContainer._EventName.invoked, { index: index, navbarCommand: ev.srcElement.winControl, data: this._repeater ? this._repeater.data.getAt(index) : null }); }, _navbarCommandSplitToggleHandler: function NavBarContainer_navbarCommandSplitToggleHandler(ev) { var srcElement = ev.srcElement; var index = -1; while (srcElement) { index++; srcElement = srcElement.previousSibling; } var navbarCommand = ev.srcElement.winControl; this._closeSplitIfOpen(); if (navbarCommand.splitOpened) { this._currentSplitNavItem = navbarCommand; } this._fireEvent(WinJS.UI.NavBarContainer._EventName.splitToggle, { opened: navbarCommand.splitOpened, index: index, navbarCommand: navbarCommand, data: this._repeater ? this._repeater.data.getAt(index) : null }); }, _fireEvent: function NavBarContainer_fireEvent(type, detail) { var event = document.createEvent("CustomEvent"); event.initCustomEvent(type, true, false, detail); this.element.dispatchEvent(event); }, _writeProfilerMark: function NavBarContainer_writeProfilerMark(text) { var message = "WinJS.UI.NavBarContainer:" + this._id + ":" + text; msWriteProfilerMark(message); WinJS.log && WinJS.log(message, null, "navbarcontainerprofiler"); }, dispose: function NavBarContainer_dispose() { /// /// /// Disposes this control. /// /// /// if (this._disposed) { return; } this._disposed = true; if (this._appBarEl) { this._appBarEl.removeEventListener('beforeshow', this._resizeImplBound); } WinJS.Navigation.removeEventListener('navigated', this._navigatedBound); this._leftArrowWaitingToFadeOut && this._leftArrowWaitingToFadeOut.cancel(); this._leftArrowFadeOut && this._leftArrowFadeOut.cancel(); this._leftArrowFadeIn && this._leftArrowFadeIn.cancel(); this._rightArrowWaitingToFadeOut && this._rightArrowWaitingToFadeOut.cancel(); this._rightArrowFadeOut && this._rightArrowFadeOut.cancel(); this._rightArrowFadeIn && this._rightArrowFadeIn.cancel(); window.removeEventListener("resize", this._boundResizeHandler); this._removeDataChangingEvents(); this._removeDataChangedEvents(); } }, { // Names of classes used by the NavBarContainer. _ClassName: { navbarcontainer: "win-navbarcontainer", pageindicators: "win-navbarcontainer-pageindicator-box", indicator: "win-navbarcontainer-pageindicator", currentindicator: "win-navbarcontainer-pageindicator-current", vertical: "win-navbarcontainer-vertical", horizontal: "win-navbarcontainer-horizontal", viewport: "win-navbarcontainer-viewport", surface: "win-navbarcontainer-surface", navarrow: "win-navbarcontainer-navarrow", navleftarrow: "win-navbarcontainer-navleft", navrightarrow: "win-navbarcontainer-navright" }, _EventName: { invoked: eventNames.invoked, splitToggle: eventNames.splittoggle } }); WinJS.Class.mix(NavBarContainer, WinJS.UI.DOMEventMixin); return NavBarContainer; }) }); })(this, WinJS); (function NavBarCommandInit(global, WinJS, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { _WinPressed: WinJS.Namespace._lazy(function () { return WinJS.Class.define(function _WinPressed_ctor(element) { // WinPressed is the combination of :hover:active // :hover is delayed by trident for touch by 300ms so if you want :hover:active to work quickly you need to // use this behavior. // :active does not bubble to its parent like :hover does so this is also useful for that scenario. this._element = element; this._element.addEventListener("pointerdown", this._MSPointerDownButtonHandler.bind(this)); }, { _MSPointerDownButtonHandler: function _WinPressed_MSPointerDownButtonHandler(ev) { if (!this._pointerUpBound) { this._pointerUpBound = this._MSPointerUpHandler.bind(this); this._pointerCancelBound = this._MSPointerCancelHandler.bind(this); this._pointerOverBound = this._MSPointerOverHandler.bind(this); this._pointerOutBound = this._MSPointerOutHandler.bind(this); } if (ev.isPrimary) { if (this._pointerId) { this._resetPointer(); } if (!ev.srcElement.msMatchesSelector(".win-interactive, .win-interactive *")) { this._pointerId = ev.pointerId; window.addEventListener("pointerup", this._pointerUpBound, true); window.addEventListener("pointercancel", this._pointerCancelBound), true; this._element.addEventListener("pointerover", this._pointerOverBound, true); this._element.addEventListener("pointerout", this._pointerOutBound, true); WinJS.Utilities.addClass(this._element, WinJS.UI._WinPressed.winPressed); } } }, _MSPointerOverHandler: function _WinPressed_MSPointerOverHandler(ev) { if (this._pointerId === ev.pointerId) { WinJS.Utilities.addClass(this._element, WinJS.UI._WinPressed.winPressed); } }, _MSPointerOutHandler: function _WinPressed_MSPointerOutHandler(ev) { if (this._pointerId === ev.pointerId) { WinJS.Utilities.removeClass(this._element, WinJS.UI._WinPressed.winPressed); } }, _MSPointerCancelHandler: function _WinPressed_MSPointerCancelHandler(ev) { if (this._pointerId === ev.pointerId) { this._resetPointer(); } }, _MSPointerUpHandler: function _WinPressed_MSPointerUpHandler(ev) { if (this._pointerId === ev.pointerId) { this._resetPointer(); } }, _resetPointer: function _WinPressed_resetPointer() { this._pointerId = null; window.removeEventListener("pointerup", this._pointerUpBound, true); window.removeEventListener("pointercancel", this._pointerCancelBound, true); this._element.removeEventListener("pointerover", this._pointerOverBound, true); this._element.removeEventListener("pointerout", this._pointerOutBound, true); WinJS.Utilities.removeClass(this._element, WinJS.UI._WinPressed.winPressed); }, dispose: function _WinPressed_dispose() { if (this._disposed) { return; } this._disposed = true; this._resetPointer(); } }, { winPressed: "win-pressed" }) }), /// /// /// Represents a navigation command in an NavBarContainer. /// /// /// /// /// /// ]]> /// Styles the entire NavBarCommand control. /// Styles the main button in a NavBarCommand. /// Styles the split button in a NavBarCommand /// Styles the icon in the main button of a NavBarCommand. /// Styles the label in the main button of a NavBarCommand. /// /// /// NavBarCommand: WinJS.Namespace._lazy(function () { var strings = { get duplicateConstruction() { return WinJS.Resources._getWinJSString("ui/duplicateConstruction").value; } }; var NavBarCommand = WinJS.Class.define(function NavBarCommand_ctor(element, options) { /// /// /// Creates a new NavBarCommand. /// /// /// The DOM element that will host the new NavBarCommand control. /// /// /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". /// /// /// The new NavBarCommand. /// /// /// element = element || document.createElement("DIV"); options = options || {}; if (element.winControl) { throw new WinJS.ErrorFromName("WinJS.UI.NavBarCommand.DuplicateConstruction", strings.duplicateConstruction); } // Attaching JS control to DOM element element.winControl = this; this._element = element; WinJS.Utilities.addClass(this.element, WinJS.UI.NavBarCommand._ClassName.navbarcommand); WinJS.Utilities.addClass(this.element, "win-disposable"); this._tooltip = null; this._splitOpened = false; this._buildDom(); element.addEventListener('keydown', this._keydownHandler.bind(this)); WinJS.UI.setOptions(this, options); }, { /// element: { get: function () { return this._element; } }, /// /// Gets or sets the label of the NavBarCommand. /// /// label: { get: function () { return this._label; }, set: function (value) { this._label = value; this._labelEl.textContent = value; } }, /// /// Gets or sets the tooltip of the NavBarCommand. /// /// tooltip: { get: function () { return this._tooltip; }, set: function (value) { this._tooltip = value; if (this._tooltip || this._tooltip === "") { this._element.setAttribute('title', this._tooltip); } else { this._element.removeAttribute('title'); } } }, /// /// Gets or sets the icon of the NavBarCommand. This value is either one of the values of the AppBarIcon enumeration or the path of a custom PNG file. /// /// icon: { get: function () { return this._icon; }, set: function (value) { this._icon = (WinJS.UI.AppBarIcon[value] || value); // If the icon's a single character, presume a glyph if (this._icon && this._icon.length === 1) { // Set the glyph this._imageSpan.innerText = this._icon; this._imageSpan.style.backgroundImage = ""; this._imageSpan.style.msHighContrastAdjust = ""; this._imageSpan.style.display = ""; } else if (this._icon && this._icon.length > 1) { // Must be an image, set that this._imageSpan.innerText = ""; this._imageSpan.style.backgroundImage = this._icon; this._imageSpan.style.msHighContrastAdjust = "none"; this._imageSpan.style.display = ""; } else { this._imageSpan.innerText = ""; this._imageSpan.style.backgroundImage = ""; this._imageSpan.style.msHighContrastAdjust = ""; this._imageSpan.style.display = "none"; } } }, /// /// Gets or sets the command's target location. /// /// location: { get: function () { return this._location; }, set: function (value) { this._location = value; } }, /// /// Gets or sets the state value used for navigation. The command passes this object to the WinJS.Navigation.navigate function. /// /// state: { get: function () { return this._state; }, set: function (value) { this._state = value; } }, /// /// Gets or sets a value that specifies whether the NavBarCommand has a split button. /// /// splitButton: { get: function () { return this._split; }, set: function (value) { this._split = value; if (this._split) { this._splitButtonEl.style.display = "flex"; } else { this._splitButtonEl.style.display = "none"; } } }, /// splitOpened: { get: function () { return this._splitOpened; }, set: function (value) { if (this._splitOpened !== !!value) { this._toggleSplit(); } } }, _toggleSplit: function NavBarCommand_toggleSplit() { this._splitOpened = !this._splitOpened; if (this._splitOpened) { WinJS.Utilities.addClass(this._splitButtonEl, WinJS.UI.NavBarCommand._ClassName.navbarcommandsplitbuttonopened); this._splitButtonEl.setAttribute("aria-expanded", "true"); } else { WinJS.Utilities.removeClass(this._splitButtonEl, WinJS.UI.NavBarCommand._ClassName.navbarcommandsplitbuttonopened); this._splitButtonEl.setAttribute("aria-expanded", "false"); } this._fireEvent(WinJS.UI.NavBarCommand._EventName._splitToggle); }, _rtl: { get: function () { return window.getComputedStyle(this.element).direction === "rtl"; } }, _keydownHandler: function NavBarCommand_keydownHandler(ev) { if (ev.srcElement.msMatchesSelector(".win-interactive, .win-interactive *")) { return; } var leftStr = this._rtl ? "Right" : "Left"; var rightStr = this._rtl ? "Left" : "Right"; if (!ev.altKey && (ev.key === leftStr || ev.key === "Home" || ev.key === "End") && ev.srcElement === this._splitButtonEl) { this._splitButtonActive = false; try { this._buttonEl.setActive(); } catch (e) { } if (ev.key === leftStr) { ev.stopPropagation(); } ev.preventDefault(); } else if (!ev.altKey && ev.key === rightStr && this.splitButton && (ev.srcElement === this._buttonEl || this._buttonEl.contains(ev.srcElement))) { this._splitButtonActive = true; try { this._splitButtonEl.setActive(); } catch (e) { } if (ev.key === rightStr) { ev.stopPropagation(); } ev.preventDefault(); } else if ((ev.key === "Spacebar" || ev.key === "Enter") && (ev.srcElement === this._buttonEl || this._buttonEl.contains(ev.srcElement))) { if (this.location) { WinJS.Navigation.navigate(this.location, this.state); } this._fireEvent(WinJS.UI.NavBarCommand._EventName._invoked); } else if ((ev.key === "Spacebar" || ev.key === "Enter") && ev.srcElement === this._splitButtonEl) { this._toggleSplit(); } }, _getFocusInto: function NavBarCommand_getFocusInto(key) { var leftStr = this._rtl ? "Right" : "Left"; if ((key === leftStr) && this.splitButton) { this._splitButtonActive = true; return this._splitButtonEl; } else { this._splitButtonActive = false; return this._buttonEl; } }, _buildDom: function NavBarCommand_buildDom() { var markup = '
' + '
' + '
' + '
' + '
' + '
' + ''; this.element.insertAdjacentHTML("afterBegin", markup); this._buttonEl = this.element.firstElementChild; this._buttonPressedBehavior = new WinJS.UI._WinPressed(this._buttonEl); this._contentEl = this._buttonEl.firstElementChild; this._imageSpan = this._contentEl.firstElementChild; this._imageSpan.style.display = "none"; this._labelEl = this._imageSpan.nextElementSibling; this._splitButtonEl = this._buttonEl.nextElementSibling; this._splitButtonPressedBehavior = new WinJS.UI._WinPressed(this._splitButtonEl); this._splitButtonEl.style.display = "none"; WinJS.UI._ensureId(this._buttonEl); this._splitButtonEl.setAttribute("aria-labelledby", this._buttonEl.id); this._buttonEl.addEventListener("click", this._handleButtonClick.bind(this)); this._buttonEl.addEventListener("beforeactivate", this._beforeactivateButtonHandler.bind(this)); this._buttonEl.addEventListener("pointerdown", this._MSPointerDownButtonHandler.bind(this)); var mutationObserver = new MutationObserver(this._splitButtonAriaExpandedPropertyChangeHandler.bind(this)); mutationObserver.observe(this._splitButtonEl, { attributes: true, attributeFilter: ["aria-expanded"] }); this._splitButtonEl.addEventListener("click", this._handleSplitButtonClick.bind(this)); this._splitButtonEl.addEventListener("beforeactivate", this._beforeactivateSplitButtonHandler.bind(this)); this._splitButtonEl.addEventListener("pointerdown", this._MSPointerDownSplitButtonHandler.bind(this)); // reparent any other elements. var tempEl = this._splitButtonEl.nextSibling; while (tempEl) { this._buttonEl.insertBefore(tempEl, this._contentEl); if (tempEl.nodeName !== "#text") { WinJS.UI.processAll(tempEl); } tempEl = this._splitButtonEl.nextSibling; } }, _MSPointerDownButtonHandler: function NavBarCommand_MSPointerDownButtonHandler(ev) { this._splitButtonActive = false; }, _MSPointerDownSplitButtonHandler: function NavBarCommand_MSPointerDownSplitButtonHandler(ev) { this._splitButtonActive = true; }, _handleButtonClick: function NavBarCommand_handleButtonClick(ev) { var srcElement = ev.srcElement; if (!srcElement.msMatchesSelector(".win-interactive, .win-interactive *")) { if (this.location) { WinJS.Navigation.navigate(this.location, this.state); } this._fireEvent(WinJS.UI.NavBarCommand._EventName._invoked); } }, _splitButtonAriaExpandedPropertyChangeHandler: function NavBarCommand_splitButtonAriaExpandedPropertyChangeHandler() { if ((this._splitButtonEl.getAttribute("aria-expanded") === "true") !== this._splitOpened) { this._toggleSplit(); } }, _handleSplitButtonClick: function NavBarCommand_handleSplitButtonClick(ev) { this._toggleSplit(); }, _beforeactivateSplitButtonHandler: function NavBarCommand_beforeactivateSplitButtonHandler(ev) { if (!this._splitButtonActive) { ev.stopPropagation(); ev.preventDefault(); } }, _beforeactivateButtonHandler: function NavBarCommand_beforeactivateButtonHandler(ev) { if (this._splitButtonActive) { ev.stopPropagation(); ev.preventDefault(); } }, _fireEvent: function NavBarCommand_fireEvent(type, detail) { var event = document.createEvent("CustomEvent"); event.initCustomEvent(type, true, false, detail); this.element.dispatchEvent(event); }, dispose: function NavBarCommand_dispose() { /// /// /// Disposes this control. /// /// /// if (this._disposed) { return; } this._disposed = true; this._buttonPressedBehavior.dispose(); this._splitButtonPressedBehavior.dispose(); } }, { _ClassName: { navbarcommand: "win-navbarcommand", navbarcommandbutton: "win-navbarcommand-button", navbarcommandbuttoncontent: "win-navbarcommand-button-content", navbarcommandsplitbutton: "win-navbarcommand-splitbutton", navbarcommandsplitbuttonopened: "win-navbarcommand-splitbutton-opened", navbarcommandicon: "win-navbarcommand-icon", navbarcommandlabel: "win-navbarcommand-label" }, _EventName: { _invoked: "_invoked", _splitToggle: "_splittoggle" } }); WinJS.Class.mix(NavBarCommand, WinJS.UI.DOMEventMixin); return NavBarCommand; }) }); })(this, WinJS); (function tooltipInit(global) { "use strict"; // Tooltip control implementation WinJS.Namespace.define("WinJS.UI", { /// /// /// Displays a tooltip that can contain images and formatting. /// /// /// /// /// /// ]]> /// Raised when the tooltip is about to appear. /// Raised when the tooltip is showing. /// Raised when the tooltip is about to become hidden. /// Raised when the tooltip is hidden. /// The entire Tooltip control. /// /// /// Tooltip: WinJS.Namespace._lazy(function () { var lastCloseTime = 0; var utilities = WinJS.Utilities; var animation = WinJS.UI.Animation; // Constants definition var DEFAULT_PLACEMENT = "top"; var DELAY_INITIAL_TOUCH_SHORT = 400; var DELAY_INITIAL_TOUCH_LONG = 1200; var DEFAULT_MOUSE_HOVER_TIME = 400; // 0.4 second var DEFAULT_MESSAGE_DURATION = 5000; // 5 secs var DELAY_RESHOW_NONINFOTIP_TOUCH = 0; var DELAY_RESHOW_NONINFOTIP_NONTOUCH = 600; var DELAY_RESHOW_INFOTIP_TOUCH = 400; var DELAY_RESHOW_INFOTIP_NONTOUCH = 600; var RESHOW_THRESHOLD = 200; var HIDE_DELAY_MAX = 300000; // 5 mins var OFFSET_KEYBOARD = 12; var OFFSET_MOUSE = 20; var OFFSET_TOUCH = 45; var OFFSET_PROGRAMMATIC_TOUCH = 20; var OFFSET_PROGRAMMATIC_NONTOUCH = 12; var SAFETY_NET_GAP = 1; // We set a 1-pixel gap between the right or bottom edge of the tooltip and the viewport to avoid possible re-layout var PT_TOUCH = MSPointerEvent.MSPOINTER_TYPE_TOUCH || "touch"; // pointer type to indicate a touch event var EVENTS_INVOKE = { "keyup": "", "pointerover": "" }, EVENTS_UPDATE = { "pointermove": "" }, EVENTS_DISMISS = { "pointerdown": "", "keydown": "", "blur": "", "pointerout": "", "pointercancel": "", "pointerup": "" }, EVENTS_BY_CHILD = { "pointerover": "", "pointerout": "" }; // CSS class names var msTooltip = "win-tooltip", msTooltipPhantom = "win-tooltip-phantom"; // Global attributes var mouseHoverTime = DEFAULT_MOUSE_HOVER_TIME, nonInfoTooltipNonTouchShowDelay = 2 * mouseHoverTime, infoTooltipNonTouchShowDelay = 2.5 * mouseHoverTime, messageDuration = DEFAULT_MESSAGE_DURATION, isLeftHanded = false; var hasInitWinRTSettings = false; var createEvent = WinJS.Utilities._createEventProperty; return WinJS.Class.define(function Tooltip_ctor(anchorElement, options) { /// /// /// Creates a new Tooltip. /// /// /// The DOM element that hosts the Tooltip. /// /// /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". For example, to provide a handler for the opened event, /// add a property named "onopened" to the options object and set its value to the event handler. /// This parameter is optional. /// /// /// The new Tooltip. /// /// /// anchorElement = anchorElement || document.createElement("div"); var tooltip = utilities.data(anchorElement).tooltip; if (tooltip) { return tooltip; } // Set system attributes if it is in WWA, otherwise, use the default values if (!hasInitWinRTSettings && WinJS.Utilities.hasWinRT) { // in WWA var uiSettings = new Windows.UI.ViewManagement.UISettings(); mouseHoverTime = uiSettings.mouseHoverTime; nonInfoTooltipNonTouchShowDelay = 2 * mouseHoverTime; infoTooltipNonTouchShowDelay = 2.5 * mouseHoverTime; messageDuration = uiSettings.messageDuration * 1000; // uiSettings.messageDuration is in seconds. var handedness = uiSettings.handPreference; isLeftHanded = (handedness == Windows.UI.ViewManagement.HandPreference.leftHanded); } hasInitWinRTSettings = true; // Need to initialize properties this._disposed = false; this._placement = DEFAULT_PLACEMENT; this._infotip = false; this._innerHTML = null; this._contentElement = null; this._extraClass = null; this._lastContentType = "html"; this._anchorElement = anchorElement; this._domElement = null; this._phantomDiv = null; this._triggerByOpen = false; this._eventListenerRemoveStack = []; // To handle keyboard navigation this._lastKeyOrBlurEvent = null; this._currentKeyOrBlurEvent = null; // Remember ourselves anchorElement.winControl = this; WinJS.Utilities.addClass(anchorElement, "win-disposable"); // If anchor element's title is defined, set as the default tooltip content if (anchorElement.title) { this._innerHTML = this._anchorElement.title; this._anchorElement.removeAttribute("title"); } WinJS.UI.setOptions(this, options); this._events(); utilities.data(anchorElement).tooltip = this; }, { /// /// Gets or sets the HTML content of the Tooltip. /// /// innerHTML: { get: function () { return this._innerHTML; }, set: function (value) { this._innerHTML = value; if (this._domElement) { // If we set the innerHTML to null or "" while tooltip is up, we should close it if (!this._innerHTML || this._innerHTML === "") { this._onDismiss(); return; } this._domElement.innerHTML = value; this._position(); } this._lastContentType = "html"; } }, /// element: { get: function () { return this._anchorElement; } }, /// /// Gets or sets the DOM element that is the content for the ToolTip. /// /// contentElement: { get: function () { return this._contentElement; }, set: function (value) { this._contentElement = value; if (this._domElement) { // If we set the contentElement to null while tooltip is up, we should close it if (!this._contentElement) { this._onDismiss(); return; } this._domElement.innerHTML = ""; this._domElement.appendChild(this._contentElement); this._position(); } this._lastContentType = "element"; } }, /// /// Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. /// /// placement: { get: function () { return this._placement; }, set: function (value) { if (value !== "top" && value !== "bottom" && value !== "left" && value !== "right") { value = DEFAULT_PLACEMENT; } this._placement = value; if (this._domElement) { this._position(); } } }, /// /// Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains /// a lot of info and should be displayed for longer than a typical Tooltip. /// The default value is false. /// /// infotip: { get: function () { return this._infotip; }, set: function (value) { this._infotip = !!value; //convert the value to boolean } }, /// /// Gets or sets additional CSS classes to apply to the Tooltip control's host element. /// /// extraClass: { get: function () { return this._extraClass; }, set: function (value) { this._extraClass = value; } }, /// /// Raised just before the Tooltip appears. /// /// onbeforeopen: createEvent("beforeopen"), /// /// Raised when the Tooltip is shown. /// /// onopened: createEvent("opened"), /// /// Raised just before the Tooltip is hidden. /// /// onbeforeclose: createEvent("beforeclose"), /// /// Raised when the Tooltip is no longer displayed. /// /// onclosed: createEvent("closed"), dispose: function () { /// /// /// Disposes this Tooltip. /// /// /// if (this._disposed) { return; } this._disposed = true; WinJS.Utilities.disposeSubTree(this.element); for (var i = 0, len = this._eventListenerRemoveStack.length; i < len; i++) { this._eventListenerRemoveStack[i](); } this._onDismiss(); var data = utilities.data(this._anchorElement); if (data) { delete data.tooltip; } }, addEventListener: function (eventName, eventCallBack, capture) { /// /// /// Registers an event handler for the specified event. /// /// The name of the event. /// The event handler function to associate with this event. /// Set to true to register the event handler for the capturing phase; set to false to register for the bubbling phase. /// /// if (this._anchorElement) { this._anchorElement.addEventListener(eventName, eventCallBack, capture); var that = this; this._eventListenerRemoveStack.push(function () { that._anchorElement.removeEventListener(eventName, eventCallBack, capture); }); } }, removeEventListener: function (eventName, eventCallBack, capture) { /// /// /// Unregisters an event handler for the specified event. /// /// The name of the event. /// The event handler function to remove. /// Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. /// /// if (this._anchorElement) { this._anchorElement.removeEventListener(eventName, eventCallBack, capture); } }, open: function (type) { /// /// /// Shows the Tooltip. /// /// The type of tooltip to show: "touch", "mouseover", "mousedown", or "keyboard". The default value is "mousedown". /// /// // Open takes precedence over other triggering events // Once tooltip is opened using open(), it can only be closed by time out(mouseover or keyboard) or explicitly by close(). this._triggerByOpen = true; if (type !== "touch" && type !== "mouseover" && type !== "mousedown" && type !== "keyboard") { type = "default"; } switch (type) { case "touch": this._onInvoke("touch", "never"); break; case "mouseover": this._onInvoke("mouse", "auto"); break; case "keyboard": this._onInvoke("keyboard", "auto"); break; case "mousedown": case "default": this._onInvoke("nodelay", "never"); break; } }, close: function () { /// /// /// Hids the Tooltip. /// /// /// this._onDismiss(); }, _cleanUpDOM: function () { if (this._domElement) { WinJS.Utilities.disposeSubTree(this._domElement); document.body.removeChild(this._domElement); this._domElement = null; document.body.removeChild(this._phantomDiv); this._phantomDiv = null; } }, _createTooltipDOM: function () { this._cleanUpDOM(); this._domElement = document.createElement("div"); var id = this._domElement.uniqueID; this._domElement.setAttribute("id", id); // Set the direction of tooltip according to anchor element's var computedStyle = document.defaultView.getComputedStyle(this._anchorElement, null); var elemStyle = this._domElement.style; elemStyle.direction = computedStyle.direction; elemStyle.writingMode = computedStyle["writing-mode"]; // must use CSS name, not JS name // Make the tooltip non-focusable this._domElement.setAttribute("tabindex", -1); // Set the aria tags for accessibility this._domElement.setAttribute("role", "tooltip"); this._anchorElement.setAttribute("aria-describedby", id); // Set the tooltip content if (this._lastContentType === "element") { // Last update through contentElement option this._domElement.appendChild(this._contentElement); } else { // Last update through innerHTML option this._domElement.innerHTML = this._innerHTML; } document.body.appendChild(this._domElement); utilities.addClass(this._domElement, msTooltip); // In the event of user-assigned classes, add those too if (this._extraClass) { utilities.addClass(this._domElement, this._extraClass); } // Create a phantom div on top of the tooltip div to block all interactions this._phantomDiv = document.createElement("div"); this._phantomDiv.setAttribute("tabindex", -1); document.body.appendChild(this._phantomDiv); utilities.addClass(this._phantomDiv, msTooltipPhantom); var zIndex = document.defaultView.getComputedStyle(this._domElement, null).zIndex + 1; this._phantomDiv.style.zIndex = zIndex; }, _raiseEvent: function (type, eventProperties) { if (this._anchorElement) { var customEvent = document.createEvent("CustomEvent"); customEvent.initCustomEvent(type, false, false, eventProperties); this._anchorElement.dispatchEvent(customEvent); } }, // Support for keyboard navigation _captureLastKeyBlurOrPointerOverEvent: function (event, listener) { listener._lastKeyOrBlurEvent = listener._currentKeyOrBlurEvent; switch (event.type) { case "keyup": if (event.key === "Shift") { listener._currentKeyOrBlurEvent = null; } else { listener._currentKeyOrBlurEvent = "keyboard"; } break; case "blur": //anchor elment no longer in focus, clear up the stack listener._currentKeyOrBlurEvent = null; break; default: break; } }, _registerEventToListener: function (element, eventType, listener) { var handler = function (event) { listener._captureLastKeyBlurOrPointerOverEvent(event, listener); listener._handleEvent(event); }; element.addEventListener(eventType, handler, false); this._eventListenerRemoveStack.push(function () { element.removeEventListener(eventType, handler, false); }); }, _events: function () { for (var eventType in EVENTS_INVOKE) { this._registerEventToListener(this._anchorElement, eventType, this); } for (var eventType in EVENTS_UPDATE) { this._registerEventToListener(this._anchorElement, eventType, this); } for (eventType in EVENTS_DISMISS) { this._registerEventToListener(this._anchorElement, eventType, this); } }, _handleEvent: function (event) { var eventType = event.type; if (!this._triggerByOpen) { // If the anchor element has children, we should ignore events that are caused within the anchor element // Please note that we are not using event.target here as in bubbling phases from the child, the event target // is usually the child if (eventType in EVENTS_BY_CHILD) { var elem = event.relatedTarget; while (elem && elem !== this._anchorElement && elem !== document.body) { try { elem = elem.parentNode; } catch (e) { if (e instanceof Error && e.message === 'Permission denied') { //Permission denied error, if we can't access the node's //information, we should not handle the event //Put this guard prior Bug 484666 is fixed return; } else { throw e; } } } if (elem === this._anchorElement) { return; } } if (eventType in EVENTS_INVOKE) { if (event.pointerType == PT_TOUCH) { this._onInvoke("touch", "never", event); this._showTrigger = "touch"; } else { var type = eventType.substring(0, 3) === "key" ? "keyboard" : "mouse"; this._onInvoke(type, "auto", event); this._showTrigger = type; } } else if (eventType in EVENTS_UPDATE) { this._contactPoint = { x: event.clientX, y: event.clientY }; } else if (eventType in EVENTS_DISMISS) { var eventTrigger; if (event.pointerType == PT_TOUCH) { if (eventType == "pointerdown") { return; } eventTrigger = "touch"; } else { eventTrigger = eventType.substring(0, 3) === "key" ? "keyboard" : "mouse"; } if (eventType != "blur" && eventTrigger != this._showTrigger) { return; } this._onDismiss(); } } }, _onShowAnimationEnd: function () { if (this._shouldDismiss || this._disposed) { return; } this._raiseEvent("opened"); if (this._domElement) { if (this._hideDelay !== "never") { var that = this; var delay = this._infotip ? Math.min(3 * messageDuration, HIDE_DELAY_MAX) : messageDuration; this._hideDelayTimer = setTimeout(function () { that._onDismiss(); }, delay); } } }, _onHideAnimationEnd: function () { document.body.removeEventListener("DOMNodeRemoved", this._removeTooltip, false); this._cleanUpDOM(); // Once we remove the tooltip from the DOM, we should remove the aria tag from the anchor if (this._anchorElement) { this._anchorElement.removeAttribute("aria-describedby"); } lastCloseTime = (new Date()).getTime(); this._triggerByOpen = false; if (!this._disposed) { this._raiseEvent("closed"); } }, _decideOnDelay: function (type) { var value; this._useAnimation = true; if (type == "nodelay") { value = 0; this._useAnimation = false; } else { var curTime = (new Date()).getTime(); // If the mouse is moved immediately from another anchor that has // tooltip open, we should use a shorter delay if (curTime - lastCloseTime <= RESHOW_THRESHOLD) { if (type == "touch") { value = this._infotip ? DELAY_RESHOW_INFOTIP_TOUCH : DELAY_RESHOW_NONINFOTIP_TOUCH; } else { value = this._infotip ? DELAY_RESHOW_INFOTIP_NONTOUCH : DELAY_RESHOW_NONINFOTIP_NONTOUCH; } this._useAnimation = false; } else if (type == "touch") { value = this._infotip ? DELAY_INITIAL_TOUCH_LONG : DELAY_INITIAL_TOUCH_SHORT; } else { value = this._infotip ? infoTooltipNonTouchShowDelay : nonInfoTooltipNonTouchShowDelay; } } return value; }, // This function returns the anchor element's position in the Window coordinates. _getAnchorPositionFromElementWindowCoord: function () { var rect = this._anchorElement.getBoundingClientRect(); return { x: rect.left, y: rect.top, width: rect.width, height: rect.height }; }, _getAnchorPositionFromPointerWindowCoord: function (contactPoint) { return { x: contactPoint.x, y: contactPoint.y, width: 1, height: 1 }; }, _canPositionOnSide: function (placement, viewport, anchor, tip) { var availWidth = 0, availHeight = 0; switch (placement) { case "top": availWidth = tip.width + this._offset; availHeight = anchor.y; break; case "bottom": availWidth = tip.width + this._offset; availHeight = viewport.height - anchor.y - anchor.height; break; case "left": availWidth = anchor.x; availHeight = tip.height + this._offset; break; case "right": availWidth = viewport.width - anchor.x - anchor.width; availHeight = tip.height + this._offset; break; } return ((availWidth >= tip.width + this._offset) && (availHeight >= tip.height + this._offset)); }, _positionOnSide: function (placement, viewport, anchor, tip) { var left = 0, top = 0; switch (placement) { case "top": case "bottom": // Align the tooltip to the anchor's center horizontally left = anchor.x + anchor.width / 2 - tip.width / 2; // If the left boundary is outside the window, set it to 0 // If the right boundary is outside the window, set it to align with the window right boundary left = Math.min(Math.max(left, 0), viewport.width - tip.width - SAFETY_NET_GAP); top = (placement == "top") ? anchor.y - tip.height - this._offset : anchor.y + anchor.height + this._offset; break; case "left": case "right": // Align the tooltip to the anchor's center vertically top = anchor.y + anchor.height / 2 - tip.height / 2; // If the top boundary is outside the window, set it to 0 // If the bottom boundary is outside the window, set it to align with the window bottom boundary top = Math.min(Math.max(top, 0), viewport.height - tip.height - SAFETY_NET_GAP); left = (placement == "left") ? anchor.x - tip.width - this._offset : anchor.x + anchor.width + this._offset; break; } // Actually set the position this._domElement.style.left = left + "px"; this._domElement.style.top = top + "px"; // Set the phantom's position and size this._phantomDiv.style.left = left + "px"; this._phantomDiv.style.top = top + "px"; this._phantomDiv.style.width = tip.width + "px"; this._phantomDiv.style.height = tip.height + "px"; }, _position: function (contactType) { var viewport = { width: 0, height: 0 }; var anchor = { x: 0, y: 0, width: 0, height: 0 }; var tip = { width: 0, height: 0 }; viewport.width = document.documentElement.clientWidth; viewport.height = document.documentElement.clientHeight; if (document.defaultView.getComputedStyle(document.body, null)["writing-mode"] === "tb-rl") { viewport.width = document.documentElement.clientHeight; viewport.height = document.documentElement.clientWidth; } if (this._contactPoint && (contactType === "touch" || contactType === "mouse")) { anchor = this._getAnchorPositionFromPointerWindowCoord(this._contactPoint); } else { // keyboard or programmatic is relative to element anchor = this._getAnchorPositionFromElementWindowCoord(); } tip.width = this._domElement.offsetWidth; tip.height = this._domElement.offsetHeight; var fallback_order = { "top": ["top", "bottom", "left", "right"], "bottom": ["bottom", "top", "left", "right"], "left": ["left", "right", "top", "bottom"], "right": ["right", "left", "top", "bottom"] }; if (isLeftHanded) { fallback_order.top[2] = "right"; fallback_order.top[3] = "left"; fallback_order.bottom[2] = "right"; fallback_order.bottom[3] = "left"; } // Try to position the tooltip according to the placement preference // We use this order: // 1. Try the preferred placement // 2. Try the opposite placement // 3. If the preferred placement is top or bottom, we should try left // and right (or right and left if left handed) // If the preferred placement is left or right, we should try top and bottom var order = fallback_order[this._placement]; var length = order.length; for (var i = 0; i < length; i++) { if (i == length - 1 || this._canPositionOnSide(order[i], viewport, anchor, tip)) { this._positionOnSide(order[i], viewport, anchor, tip); break; } } return order[i]; }, _showTooltip: function (contactType) { // Give a chance to dismiss the tooltip before it starts to show if (this._shouldDismiss) { return; } this._isShown = true; this._raiseEvent("beforeopen"); // If the anchor is not in the DOM tree, we don't create the tooltip if (!document.body.contains(this._anchorElement)) { return; } if (this._shouldDismiss) { return; } // If the contentElement is set to null or innerHTML set to null or "", we should NOT show the tooltip if (this._lastContentType === "element") { // Last update through contentElement option if (!this._contentElement) { this._isShown = false; return; } } else { // Last update through innerHTML option if (!this._innerHTML || this._innerHTML === "") { this._isShown = false; return; } } var that = this; this._removeTooltip = function (event) { var current = that._anchorElement; while (current) { if (event.target == current) { document.body.removeEventListener("DOMNodeRemoved", that._removeTooltip, false); that._cleanUpDOM(); break; } current = current.parentNode; } }; document.body.addEventListener("DOMNodeRemoved", this._removeTooltip, false); this._createTooltipDOM(); var pos = this._position(contactType); var that = this; if (this._useAnimation) { animation.fadeIn(this._domElement) .then(this._onShowAnimationEnd.bind(this)); } else { this._onShowAnimationEnd(); } }, _onInvoke: function (type, hide, event) { // Reset the dismiss flag this._shouldDismiss = false; // If the tooltip is already shown, ignore the current event if (this._isShown) { return; } // To handle keyboard support, we only want to display tooltip on the first tab key event only if (event && event.type === "keyup") { if (this._lastKeyOrBlurEvent == "keyboard" || !this._lastKeyOrBlurEvent && event.key !== "Tab") { return; } } // Set the hide delay, this._hideDelay = hide; this._contactPoint = null; if (event) { // Open through interaction this._contactPoint = { x: event.clientX, y: event.clientY }; // Tooltip display offset differently for touch events and non-touch events if (type == "touch") { this._offset = OFFSET_TOUCH; } else if (type === "keyboard") { this._offset = OFFSET_KEYBOARD; } else { this._offset = OFFSET_MOUSE; } } else { // Open Programmatically if (type == "touch") { this._offset = OFFSET_PROGRAMMATIC_TOUCH; } else { this._offset = OFFSET_PROGRAMMATIC_NONTOUCH; } } clearTimeout(this._delayTimer); clearTimeout(this._hideDelayTimer); // Set the delay time var delay = this._decideOnDelay(type); if (delay > 0) { var that = this; this._delayTimer = setTimeout(function () { that._showTooltip(type); }, delay); } else { this._showTooltip(type); } }, _onDismiss: function () { // Set the dismiss flag so that we don't miss dismiss events this._shouldDismiss = true; // If the tooltip is already dismissed, ignore the current event if (!this._isShown) { return; } this._isShown = false; // Reset tooltip state this._showTrigger = "mouse"; if (this._domElement) { this._raiseEvent("beforeclose"); if (this._useAnimation) { animation.fadeOut(this._domElement) .then(this._onHideAnimationEnd.bind(this)); } else { this._onHideAnimationEnd(); } } else { this._raiseEvent("beforeclose"); this._raiseEvent("closed"); } } }); }) }); })(this, WinJS); // ViewBox control (function viewboxInit(global, undefined) { "use strict"; WinJS.Namespace.define("WinJS.UI", { /// /// Scales a single child element to fill the available space without /// resizing it. This control reacts to changes in the size of the container as well as /// changes in size of the child element. For example, a media query may result in /// a change in aspect ratio. /// /// View Box /// /// ///
ViewBox
]]>
/// /// /// ViewBox: WinJS.Namespace._lazy(function () { var Scheduler = WinJS.Utilities.Scheduler; var strings = { get invalidViewBoxChildren() { return WinJS.Resources._getWinJSString("ui/invalidViewBoxChildren").value; }, }; function onresize(control) { if (control && !control._resizing) { control._resizing = control._resizing || 0; control._resizing++; try { control._updateLayout(); } finally { control._resizing--; } } } function onresizeBox(ev) { if (ev.srcElement) { onresize(ev.srcElement.winControl); } } function onresizeSizer(ev) { if (ev.srcElement) { onresize(ev.srcElement.parentElement.winControl); } } var ViewBox = WinJS.Class.define(function ViewBox_ctor(element, options) { /// /// Initializes a new instance of the ViewBox control /// /// The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. /// /// /// The set of options to be applied initially to the ViewBox control. /// /// A constructed ViewBox control. /// this._disposed = false; this._element = element || document.createElement("div"); var box = this.element; box.winControl = this; WinJS.Utilities.addClass(box, "win-disposable"); WinJS.Utilities.addClass(box, "win-viewbox"); this.forceLayout(); }, { _sizer: null, _element: null, /// element: { get: function () { return this._element; } }, _rtl: { get: function () { return window.getComputedStyle(this.element).direction === "rtl"; } }, _initialize: function () { var box = this.element; if (box.firstElementChild !== this._sizer) { if (WinJS.validation) { if (box.childElementCount != 1) { throw new WinJS.ErrorFromName("WinJS.UI.ViewBox.InvalidChildren", strings.invalidViewBoxChildren); } } if (this._sizer) { this._sizer.onresize = null; } var sizer = box.firstElementChild; this._sizer = sizer; if (sizer) { box.addEventListener("mselementresize", onresizeBox); sizer.addEventListener("mselementresize", onresizeSizer); } if (box.clientWidth === 0 && box.clientHeight === 0) { var that = this; // Wait for the viewbox to get added to the DOM. It should be added // in the synchronous block in which _initialize was called. Scheduler.schedule(function () { that._updateLayout(); }, Scheduler.Priority.normal, null, "WinJS.UI.ViewBox._updateLayout") } } }, _updateLayout: function () { var sizer = this._sizer; if (sizer) { var box = this.element; var w = sizer.clientWidth; var h = sizer.clientHeight; var bw = box.clientWidth; var bh = box.clientHeight; var wRatio = bw / w; var hRatio = bh / h; var mRatio = Math.min(wRatio, hRatio); var transX = Math.abs(bw - (w * mRatio)) / 2; var transY = Math.abs(bh - (h * mRatio)) / 2; var rtl = this._rtl; this._sizer.style["transform"] = "translate(" + (rtl ? "-" : "") + transX + "px," + transY + "px) scale(" + mRatio + ")"; this._sizer.style["transform-origin"] = rtl ? "top right" : "top left"; } }, dispose: function () { /// /// /// Disposes this ViewBox. /// /// if (this._disposed) { return; } this._disposed = true; WinJS.Utilities.disposeSubTree(this._element); }, forceLayout: function () { this._initialize(); this._updateLayout(); } }); WinJS.Class.mix(ViewBox, WinJS.UI.DOMEventMixin); return ViewBox; }) }); }(this)); msWriteProfilerMark("Microsoft.WinJS.2.0 1.0.9600.17018.winblue_gdr.140204-1946 ui.js,StopTM");