<commit_before>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.View}
 * @param {!WebInspector.PopoverHelper=} popoverHelper
 */
WebInspector.Popover = function(popoverHelper)
{
    WebInspector.View.call(this);
    this.markAsRoot();
    this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll"; // Override

    this._popupArrowElement = document.createElement("div");
    this._popupArrowElement.className = "arrow";
    this.element.appendChild(this._popupArrowElement);

    this._contentDiv = document.createElement("div");
    this._contentDiv.className = "content";
    this.element.appendChild(this._contentDiv);

    this._popoverHelper = popoverHelper;
}

WebInspector.Popover.prototype = {
    /**
     * @param {!Element} element
     * @param {!Element|!AnchorBox} anchor
     * @param {?number=} preferredWidth
     * @param {?number=} preferredHeight
     * @param {?WebInspector.Popover.Orientation=} arrowDirection
     */
    show: function(element, anchor, preferredWidth, preferredHeight, arrowDirection)
    {
        this._innerShow(null, element, anchor, preferredWidth, preferredHeight, arrowDirection);
    },

    /**
     * @param {!WebInspector.View} view
     * @param {!Element|!AnchorBox} anchor
     * @param {?number=} preferredWidth
     * @param {?number=} preferredHeight
     */
    showView: function(view, anchor, preferredWidth, preferredHeight)
    {
        this._innerShow(view, view.element, anchor, preferredWidth, preferredHeight);
    },

    /**
     * @param {?WebInspector.View} view
     * @param {!Element} contentElement
     * @param {!Element|!AnchorBox} anchor
     * @param {?number=} preferredWidth
     * @param {?number=} preferredHeight
     * @param {?WebInspector.Popover.Orientation=} arrowDirection
     */
    _innerShow: function(view, contentElement, anchor, preferredWidth, preferredHeight, arrowDirection)
    {
        if (this._disposed)
            return;
        this.contentElement = contentElement;

        // This should not happen, but we hide previous popup to be on the safe side.
        if (WebInspector.Popover._popover)
            WebInspector.Popover._popover.detach();
        WebInspector.Popover._popover = this;

        // Temporarily attach in order to measure preferred dimensions.
        var preferredSize = view ? view.measurePreferredSize() : this.contentElement.measurePreferredSize();
        preferredWidth = preferredWidth || preferredSize.width;
        preferredHeight = preferredHeight || preferredSize.height;

        WebInspector.View.prototype.show.call(this, document.body);

        if (view)
            view.show(this._contentDiv);
        else
            this._contentDiv.appendChild(this.contentElement);

        this._positionElement(anchor, preferredWidth, preferredHeight, arrowDirection);

        if (this._popoverHelper) {
            this._contentDiv.addEventListener("mousemove", this._popoverHelper._killHidePopoverTimer.bind(this._popoverHelper), true);
            this.element.addEventListener("mouseout", this._popoverHelper._popoverMouseOut.bind(this._popoverHelper), true);
        }
    },

    hide: function()
    {
        this.detach();
        delete WebInspector.Popover._popover;
    },

    get disposed()
    {
        return this._disposed;
    },

    dispose: function()
    {
        if (this.isShowing())
            this.hide();
        this._disposed = true;
    },

    setCanShrink: function(canShrink)
    {
        this._hasFixedHeight = !canShrink;
        this._contentDiv.classList.add("fixed-height");
    },

    /**
     * @param {!Element|!AnchorBox} anchorElement
     * @param {number} preferredWidth
     * @param {number} preferredHeight
     * @param {?WebInspector.Popover.Orientation=} arrowDirection
     */
    _positionElement: function(anchorElement, preferredWidth, preferredHeight, arrowDirection)
    {
        const borderWidth = 25;
        const scrollerWidth = this._hasFixedHeight ? 0 : 11;
        const arrowHeight = 15;
        const arrowOffset = 10;
        const borderRadius = 10;

        // Skinny tooltips are not pretty, their arrow location is not nice.
        preferredWidth = Math.max(preferredWidth, 50);
        // Position relative to main DevTools element.
        const container = WebInspector.Dialog.modalHostView().element;
        const totalWidth = container.offsetWidth;
        const totalHeight = container.offsetHeight;

        var anchorBox = anchorElement instanceof AnchorBox ? anchorElement : anchorElement.boxInWindow(window);
        anchorBox = anchorBox.relativeToElement(container);
        var newElementPosition = { x: 0, y: 0, width: preferredWidth + scrollerWidth, height: preferredHeight };

        var verticalAlignment;
        var roomAbove = anchorBox.y;
        var roomBelow = totalHeight - anchorBox.y - anchorBox.height;

        if ((roomAbove > roomBelow) || (arrowDirection === WebInspector.Popover.Orientation.Bottom)) {
            // Positioning above the anchor.
            if ((anchorBox.y > newElementPosition.height + arrowHeight + borderRadius) || (arrowDirection === WebInspector.Popover.Orientation.Bottom))
                newElementPosition.y = anchorBox.y - newElementPosition.height - arrowHeight;
            else {
                newElementPosition.y = borderRadius;
                newElementPosition.height = anchorBox.y - borderRadius * 2 - arrowHeight;
                if (this._hasFixedHeight && newElementPosition.height < preferredHeight) {
                    newElementPosition.y = borderRadius;
                    newElementPosition.height = preferredHeight;
                }
            }
            verticalAlignment = WebInspector.Popover.Orientation.Bottom;
        } else {
            // Positioning below the anchor.
            newElementPosition.y = anchorBox.y + anchorBox.height + arrowHeight;
            if ((newElementPosition.y + newElementPosition.height + arrowHeight - borderWidth >= totalHeight) && (arrowDirection !== WebInspector.Popover.Orientation.Top)) {
                newElementPosition.height = totalHeight - anchorBox.y - anchorBox.height - borderRadius * 2 - arrowHeight;
                if (this._hasFixedHeight && newElementPosition.height < preferredHeight) {
                    newElementPosition.y = totalHeight - preferredHeight - borderRadius;
                    newElementPosition.height = preferredHeight;
                }
            }
            // Align arrow.
            verticalAlignment = WebInspector.Popover.Orientation.Top;
        }

        var horizontalAlignment;
        if (anchorBox.x + newElementPosition.width < totalWidth) {
            newElementPosition.x = Math.max(borderRadius, anchorBox.x - borderRadius - arrowOffset);
            horizontalAlignment = "left";
        } else if (newElementPosition.width + borderRadius * 2 < totalWidth) {
            newElementPosition.x = totalWidth - newElementPosition.width - borderRadius;
            horizontalAlignment = "right";
            // Position arrow accurately.
            var arrowRightPosition = Math.max(0, totalWidth - anchorBox.x - anchorBox.width - borderRadius - arrowOffset);
            arrowRightPosition += anchorBox.width / 2;
            arrowRightPosition = Math.min(arrowRightPosition, newElementPosition.width - borderRadius - arrowOffset);
            this._popupArrowElement.style.right = arrowRightPosition + "px";
        } else {
            newElementPosition.x = borderRadius;
            newElementPosition.width = totalWidth - borderRadius * 2;
            newElementPosition.height += scrollerWidth;
            horizontalAlignment = "left";
            if (verticalAlignment === WebInspector.Popover.Orientation.Bottom)
                newElementPosition.y -= scrollerWidth;
            // Position arrow accurately.
            this._popupArrowElement.style.left = Math.max(0, anchorBox.x - borderRadius * 2 - arrowOffset) + "px";
            this._popupArrowElement.style.left += anchorBox.width / 2;
        }

        this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll " + verticalAlignment + "-" + horizontalAlignment + "-arrow";
        this.element.positionAt(newElementPosition.x - borderWidth, newElementPosition.y - borderWidth, container);
        this.element.style.width = newElementPosition.width + borderWidth * 2 + "px";
        this.element.style.height = newElementPosition.height + borderWidth * 2 + "px";
    },

    __proto__: WebInspector.View.prototype
}

/**
 * @constructor
 * @param {!Element} panelElement
 * @param {function(!Element, !Event):(!Element|!AnchorBox)|undefined} getAnchor
 * @param {function(!Element, !WebInspector.Popover):undefined} showPopover
 * @param {function()=} onHide
 * @param {boolean=} disableOnClick
 */
WebInspector.PopoverHelper = function(panelElement, getAnchor, showPopover, onHide, disableOnClick)
{
    this._panelElement = panelElement;
    this._getAnchor = getAnchor;
    this._showPopover = showPopover;
    this._onHide = onHide;
    this._disableOnClick = !!disableOnClick;
    panelElement.addEventListener("mousedown", this._mouseDown.bind(this), false);
    panelElement.addEventListener("mousemove", this._mouseMove.bind(this), false);
    panelElement.addEventListener("mouseout", this._mouseOut.bind(this), false);
    this.setTimeout(1000);
}

WebInspector.PopoverHelper.prototype = {
    setTimeout: function(timeout)
    {
        this._timeout = timeout;
    },

    /**
     * @param {!MouseEvent} event
     * @return {boolean}
     */
    _eventInHoverElement: function(event)
    {
        if (!this._hoverElement)
            return false;
        var box = this._hoverElement instanceof AnchorBox ? this._hoverElement : this._hoverElement.boxInWindow();
        return (box.x <= event.clientX && event.clientX <= box.x + box.width &&
            box.y <= event.clientY && event.clientY <= box.y + box.height);
    },

    _mouseDown: function(event)
    {
        if (this._disableOnClick || !this._eventInHoverElement(event))
            this.hidePopover();
        else {
            this._killHidePopoverTimer();
            this._handleMouseAction(event, true);
        }
    },

    _mouseMove: function(event)
    {
        // Pretend that nothing has happened.
        if (this._eventInHoverElement(event))
            return;

        this._startHidePopoverTimer();
        this._handleMouseAction(event, false);
    },

    _popoverMouseOut: function(event)
    {
        if (!this.isPopoverVisible())
            return;
        if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this._popover._contentDiv))
            this._startHidePopoverTimer();
    },

    _mouseOut: function(event)
    {
        if (!this.isPopoverVisible())
            return;
        if (!this._eventInHoverElement(event))
            this._startHidePopoverTimer();
    },

    _startHidePopoverTimer: function()
    {
        // User has 500ms (this._timeout / 2) to reach the popup.
        if (!this._popover || this._hidePopoverTimer)
            return;

        /**
         * @this {WebInspector.PopoverHelper}
         */
        function doHide()
        {
            this._hidePopover();
            delete this._hidePopoverTimer;
        }
        this._hidePopoverTimer = setTimeout(doHide.bind(this), this._timeout / 2);
    },

    _handleMouseAction: function(event, isMouseDown)
    {
        this._resetHoverTimer();
        if (event.which && this._disableOnClick)
            return;
        this._hoverElement = this._getAnchor(event.target, event);
        if (!this._hoverElement)
            return;
        const toolTipDelay = isMouseDown ? 0 : (this._popup ? this._timeout * 0.6 : this._timeout);
        this._hoverTimer = setTimeout(this._mouseHover.bind(this, this._hoverElement), toolTipDelay);
    },

    _resetHoverTimer: function()
    {
        if (this._hoverTimer) {
            clearTimeout(this._hoverTimer);
            delete this._hoverTimer;
        }
    },

    /**
     * @return {boolean}
     */
    isPopoverVisible: function()
    {
        return !!this._popover;
    },

    hidePopover: function()
    {
        this._resetHoverTimer();
        this._hidePopover();
    },

    _hidePopover: function()
    {
        if (!this._popover)
            return;

        if (this._onHide)
            this._onHide();

        this._popover.dispose();
        delete this._popover;
        this._hoverElement = null;
    },

    _mouseHover: function(element)
    {
        delete this._hoverTimer;

        this._hidePopover();
        this._popover = new WebInspector.Popover(this);
        this._showPopover(element, this._popover);
    },

    _killHidePopoverTimer: function()
    {
        if (this._hidePopoverTimer) {
            clearTimeout(this._hidePopoverTimer);
            delete this._hidePopoverTimer;

            // We know that we reached the popup, but we might have moved over other elements.
            // Discard pending command.
            this._resetHoverTimer();
        }
    }
}

/** @enum {string} */
WebInspector.Popover.Orientation = {
    Top: "top",
    Bottom: "bottom"
}
<commit_msg>[DevTools] Minor tweak in popover positioning.<commit_after>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.View}
 * @param {!WebInspector.PopoverHelper=} popoverHelper
 */
WebInspector.Popover = function(popoverHelper)
{
    WebInspector.View.call(this);
    this.markAsRoot();
    this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll"; // Override

    this._popupArrowElement = document.createElement("div");
    this._popupArrowElement.className = "arrow";
    this.element.appendChild(this._popupArrowElement);

    this._contentDiv = document.createElement("div");
    this._contentDiv.className = "content";
    this.element.appendChild(this._contentDiv);

    this._popoverHelper = popoverHelper;
}

WebInspector.Popover.prototype = {
    /**
     * @param {!Element} element
     * @param {!Element|!AnchorBox} anchor
     * @param {?number=} preferredWidth
     * @param {?number=} preferredHeight
     * @param {?WebInspector.Popover.Orientation=} arrowDirection
     */
    show: function(element, anchor, preferredWidth, preferredHeight, arrowDirection)
    {
        this._innerShow(null, element, anchor, preferredWidth, preferredHeight, arrowDirection);
    },

    /**
     * @param {!WebInspector.View} view
     * @param {!Element|!AnchorBox} anchor
     * @param {?number=} preferredWidth
     * @param {?number=} preferredHeight
     */
    showView: function(view, anchor, preferredWidth, preferredHeight)
    {
        this._innerShow(view, view.element, anchor, preferredWidth, preferredHeight);
    },

    /**
     * @param {?WebInspector.View} view
     * @param {!Element} contentElement
     * @param {!Element|!AnchorBox} anchor
     * @param {?number=} preferredWidth
     * @param {?number=} preferredHeight
     * @param {?WebInspector.Popover.Orientation=} arrowDirection
     */
    _innerShow: function(view, contentElement, anchor, preferredWidth, preferredHeight, arrowDirection)
    {
        if (this._disposed)
            return;
        this.contentElement = contentElement;

        // This should not happen, but we hide previous popup to be on the safe side.
        if (WebInspector.Popover._popover)
            WebInspector.Popover._popover.detach();
        WebInspector.Popover._popover = this;

        // Temporarily attach in order to measure preferred dimensions.
        var preferredSize = view ? view.measurePreferredSize() : this.contentElement.measurePreferredSize();
        preferredWidth = preferredWidth || preferredSize.width;
        preferredHeight = preferredHeight || preferredSize.height;

        WebInspector.View.prototype.show.call(this, document.body);

        if (view)
            view.show(this._contentDiv);
        else
            this._contentDiv.appendChild(this.contentElement);

        this._positionElement(anchor, preferredWidth, preferredHeight, arrowDirection);

        if (this._popoverHelper) {
            this._contentDiv.addEventListener("mousemove", this._popoverHelper._killHidePopoverTimer.bind(this._popoverHelper), true);
            this.element.addEventListener("mouseout", this._popoverHelper._popoverMouseOut.bind(this._popoverHelper), true);
        }
    },

    hide: function()
    {
        this.detach();
        delete WebInspector.Popover._popover;
    },

    get disposed()
    {
        return this._disposed;
    },

    dispose: function()
    {
        if (this.isShowing())
            this.hide();
        this._disposed = true;
    },

    setCanShrink: function(canShrink)
    {
        this._hasFixedHeight = !canShrink;
        this._contentDiv.classList.add("fixed-height");
    },

    /**
     * @param {!Element|!AnchorBox} anchorElement
     * @param {number} preferredWidth
     * @param {number} preferredHeight
     * @param {?WebInspector.Popover.Orientation=} arrowDirection
     */
    _positionElement: function(anchorElement, preferredWidth, preferredHeight, arrowDirection)
    {
        const borderWidth = 25;
        const scrollerWidth = this._hasFixedHeight ? 0 : 11;
        const arrowHeight = 15;
        const arrowOffset = 10;
        const borderRadius = 10;

        // Skinny tooltips are not pretty, their arrow location is not nice.
        preferredWidth = Math.max(preferredWidth, 50);
        // Position relative to main DevTools element.
        const container = WebInspector.Dialog.modalHostView().element;
        const totalWidth = container.offsetWidth;
        const totalHeight = container.offsetHeight;

        var anchorBox = anchorElement instanceof AnchorBox ? anchorElement : anchorElement.boxInWindow(window);
        anchorBox = anchorBox.relativeToElement(container);
        var newElementPosition = { x: 0, y: 0, width: preferredWidth + scrollerWidth, height: preferredHeight };

        var verticalAlignment;
        var roomAbove = anchorBox.y;
        var roomBelow = totalHeight - anchorBox.y - anchorBox.height;

        if ((roomAbove > roomBelow) || (arrowDirection === WebInspector.Popover.Orientation.Bottom)) {
            // Positioning above the anchor.
            if ((anchorBox.y > newElementPosition.height + arrowHeight + borderRadius) || (arrowDirection === WebInspector.Popover.Orientation.Bottom))
                newElementPosition.y = anchorBox.y - newElementPosition.height - arrowHeight;
            else {
                newElementPosition.y = borderRadius;
                newElementPosition.height = anchorBox.y - borderRadius * 2 - arrowHeight;
                if (this._hasFixedHeight && newElementPosition.height < preferredHeight) {
                    newElementPosition.y = borderRadius;
                    newElementPosition.height = preferredHeight;
                }
            }
            verticalAlignment = WebInspector.Popover.Orientation.Bottom;
        } else {
            // Positioning below the anchor.
            newElementPosition.y = anchorBox.y + anchorBox.height + arrowHeight;
            if ((newElementPosition.y + newElementPosition.height + borderRadius >= totalHeight) && (arrowDirection !== WebInspector.Popover.Orientation.Top)) {
                newElementPosition.height = totalHeight - borderRadius - newElementPosition.y;
                if (this._hasFixedHeight && newElementPosition.height < preferredHeight) {
                    newElementPosition.y = totalHeight - preferredHeight - borderRadius;
                    newElementPosition.height = preferredHeight;
                }
            }
            // Align arrow.
            verticalAlignment = WebInspector.Popover.Orientation.Top;
        }

        var horizontalAlignment;
        if (anchorBox.x + newElementPosition.width < totalWidth) {
            newElementPosition.x = Math.max(borderRadius, anchorBox.x - borderRadius - arrowOffset);
            horizontalAlignment = "left";
        } else if (newElementPosition.width + borderRadius * 2 < totalWidth) {
            newElementPosition.x = totalWidth - newElementPosition.width - borderRadius;
            horizontalAlignment = "right";
            // Position arrow accurately.
            var arrowRightPosition = Math.max(0, totalWidth - anchorBox.x - anchorBox.width - borderRadius - arrowOffset);
            arrowRightPosition += anchorBox.width / 2;
            arrowRightPosition = Math.min(arrowRightPosition, newElementPosition.width - borderRadius - arrowOffset);
            this._popupArrowElement.style.right = arrowRightPosition + "px";
        } else {
            newElementPosition.x = borderRadius;
            newElementPosition.width = totalWidth - borderRadius * 2;
            newElementPosition.height += scrollerWidth;
            horizontalAlignment = "left";
            if (verticalAlignment === WebInspector.Popover.Orientation.Bottom)
                newElementPosition.y -= scrollerWidth;
            // Position arrow accurately.
            this._popupArrowElement.style.left = Math.max(0, anchorBox.x - borderRadius * 2 - arrowOffset) + "px";
            this._popupArrowElement.style.left += anchorBox.width / 2;
        }

        this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll " + verticalAlignment + "-" + horizontalAlignment + "-arrow";
        this.element.positionAt(newElementPosition.x - borderWidth, newElementPosition.y - borderWidth, container);
        this.element.style.width = newElementPosition.width + borderWidth * 2 + "px";
        this.element.style.height = newElementPosition.height + borderWidth * 2 + "px";
    },

    __proto__: WebInspector.View.prototype
}

/**
 * @constructor
 * @param {!Element} panelElement
 * @param {function(!Element, !Event):(!Element|!AnchorBox)|undefined} getAnchor
 * @param {function(!Element, !WebInspector.Popover):undefined} showPopover
 * @param {function()=} onHide
 * @param {boolean=} disableOnClick
 */
WebInspector.PopoverHelper = function(panelElement, getAnchor, showPopover, onHide, disableOnClick)
{
    this._panelElement = panelElement;
    this._getAnchor = getAnchor;
    this._showPopover = showPopover;
    this._onHide = onHide;
    this._disableOnClick = !!disableOnClick;
    panelElement.addEventListener("mousedown", this._mouseDown.bind(this), false);
    panelElement.addEventListener("mousemove", this._mouseMove.bind(this), false);
    panelElement.addEventListener("mouseout", this._mouseOut.bind(this), false);
    this.setTimeout(1000);
}

WebInspector.PopoverHelper.prototype = {
    setTimeout: function(timeout)
    {
        this._timeout = timeout;
    },

    /**
     * @param {!MouseEvent} event
     * @return {boolean}
     */
    _eventInHoverElement: function(event)
    {
        if (!this._hoverElement)
            return false;
        var box = this._hoverElement instanceof AnchorBox ? this._hoverElement : this._hoverElement.boxInWindow();
        return (box.x <= event.clientX && event.clientX <= box.x + box.width &&
            box.y <= event.clientY && event.clientY <= box.y + box.height);
    },

    _mouseDown: function(event)
    {
        if (this._disableOnClick || !this._eventInHoverElement(event))
            this.hidePopover();
        else {
            this._killHidePopoverTimer();
            this._handleMouseAction(event, true);
        }
    },

    _mouseMove: function(event)
    {
        // Pretend that nothing has happened.
        if (this._eventInHoverElement(event))
            return;

        this._startHidePopoverTimer();
        this._handleMouseAction(event, false);
    },

    _popoverMouseOut: function(event)
    {
        if (!this.isPopoverVisible())
            return;
        if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this._popover._contentDiv))
            this._startHidePopoverTimer();
    },

    _mouseOut: function(event)
    {
        if (!this.isPopoverVisible())
            return;
        if (!this._eventInHoverElement(event))
            this._startHidePopoverTimer();
    },

    _startHidePopoverTimer: function()
    {
        // User has 500ms (this._timeout / 2) to reach the popup.
        if (!this._popover || this._hidePopoverTimer)
            return;

        /**
         * @this {WebInspector.PopoverHelper}
         */
        function doHide()
        {
            this._hidePopover();
            delete this._hidePopoverTimer;
        }
        this._hidePopoverTimer = setTimeout(doHide.bind(this), this._timeout / 2);
    },

    _handleMouseAction: function(event, isMouseDown)
    {
        this._resetHoverTimer();
        if (event.which && this._disableOnClick)
            return;
        this._hoverElement = this._getAnchor(event.target, event);
        if (!this._hoverElement)
            return;
        const toolTipDelay = isMouseDown ? 0 : (this._popup ? this._timeout * 0.6 : this._timeout);
        this._hoverTimer = setTimeout(this._mouseHover.bind(this, this._hoverElement), toolTipDelay);
    },

    _resetHoverTimer: function()
    {
        if (this._hoverTimer) {
            clearTimeout(this._hoverTimer);
            delete this._hoverTimer;
        }
    },

    /**
     * @return {boolean}
     */
    isPopoverVisible: function()
    {
        return !!this._popover;
    },

    hidePopover: function()
    {
        this._resetHoverTimer();
        this._hidePopover();
    },

    _hidePopover: function()
    {
        if (!this._popover)
            return;

        if (this._onHide)
            this._onHide();

        this._popover.dispose();
        delete this._popover;
        this._hoverElement = null;
    },

    _mouseHover: function(element)
    {
        delete this._hoverTimer;

        this._hidePopover();
        this._popover = new WebInspector.Popover(this);
        this._showPopover(element, this._popover);
    },

    _killHidePopoverTimer: function()
    {
        if (this._hidePopoverTimer) {
            clearTimeout(this._hidePopoverTimer);
            delete this._hidePopoverTimer;

            // We know that we reached the popup, but we might have moved over other elements.
            // Discard pending command.
            this._resetHoverTimer();
        }
    }
}

/** @enum {string} */
WebInspector.Popover.Orientation = {
    Top: "top",
    Bottom: "bottom"
}
<|endoftext|>


<commit_before>// ECMAScript 5 strict mode
"use strict";

assert2(cr, "cr namespace not created");
assert2(cr.behaviors, "cr.behaviors not created");

cr.behaviors.RubberBand = function(runtime)
{
    this.runtime = runtime;
};

(function ()
{
    var behaviorProto = cr.behaviors.RubberBand.prototype;

    behaviorProto.Type = function(behavior, objtype)
    {
        this.behavior = behavior;
        this.objtype = objtype;
        this.runtime = behavior.runtime;
    };

    var behtypeProto = behaviorProto.Type.prototype;

    behtypeProto.onCreate = function()
    {
    };

    behaviorProto.Instance = function(type, inst)
    {
        this.type = type;
        this.behavior = type.behavior;
        this.inst = inst;
        this.runtime = type.runtime;
    };

    var behinstProto = behaviorProto.Instance.prototype;

    behinstProto.onCreate = function()
    {
        this.relaxedLength = this.properties[0];
        this.stiffness = this.properties[1]*0.1; // for nicer default config values
        this.gravity = this.properties[2]*100;
        this.drag = this.properties[3]*0.01;
        this.enabled = this.properties[4]; // 0=disabled, 1=enabled

        this.fixture = null;
        this.fixtureUid = -1;
        this.dx = 0;
        this.dy = 0;
        this.isStretched = false;
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    };

    behinstProto.onDestroy = function ()
    {
        this.fixture = null;
    };

    behinstProto.saveToJSON = function ()
    {
        return {
            "fixtureUid": this.fixture ? this.fixture.uid : -1,
            "relaxedLength": this.relaxedLength,
            "stiffness": this.stiffness,
            "gravity": this.gravity,
            "enabled": this.enabled,
            "drag": this.drag,
            "dx": this.dx,
            "dy": this.dy
        };
    };

    behinstProto.loadFromJSON = function (o)
    {
        this.fixtureUid = o["fixtureUid"];
        this.relaxedLength = o["relaxedLength"];
        this.stiffness = o["stiffness"];
        this.gravity = o["gravity"];
        this.enabled = o["enabled"];
        this.drag = o["drag"];
        this.dx = o["dx"];
        this.dy = o["dy"];

        this.isStretched = (this.calculateStretch().displacement > 0);
    };

    behinstProto.afterLoad = function ()
    {
        if (this.fixtureUid === -1)
        {
            this.fixture = null;
        }
        else
        {
            this.fixture = this.runtime.getObjectByUID(this.fixtureUid);
            assert2(this.fixture, "Failed to find fixture object by UID");
        }

        this.fixtureUid = -1;
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    };

    behinstProto.tick = function ()
    {
        this.pickupExternalImpulse();
        if (this.enabled)
        {
            this.applyBandMovement();
        }
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    }

    behinstProto.applyBandMovement = function ()
    {
        var accelX = 0,
            accelY = 0,
            dt = this.runtime.getDt(this.inst),
            delta = this.getDeltaVector(),
            stretch = this.calculateStretch();
        if (this.fixture)
        {
            this.isStretched = (stretch.displacement > 0);
            if (this.isStretched)
            {
                var accel = stretch.displacement*this.stiffness;
                accelX = accel*delta.x*stretch.ratio;
                accelY = accel*delta.y*stretch.ratio;
                this.dx += dt*accelX;
                this.dy += dt*accelY;
            }
        }
        if (this.gravity)
        {
            this.dy += dt*this.gravity;
        }
        if (this.drag)
        {
            this.dx -= (this.drag*this.dx);
            this.dy -= (this.drag*this.dy);
        }
        {
            this.inst.x += (this.dx + 0.5*(accelX)*dt)*dt;
            this.inst.y += (this.dy + 0.5*(accelY + this.gravity)*dt)*dt;
            this.inst.set_bbox_changed();
        }
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    };

    behinstProto.pickupExternalImpulse = function ()
    {
        if (this.lastX !== this.inst.x || this.lastY !== this.inst.y)
        {
            var dt = this.runtime.getDt(this.inst),
                deltaX = this.inst.x - this.lastX,
                deltaY = this.inst.y - this.lastY;
            if (Math.abs(deltaX) > 0.001)
            {
                this.dx = (this.dx + deltaX/dt)/2;
            }
            if (Math.abs(deltaY) > 0.001)
            {
                this.dy = (this.dy + deltaY/dt)/2;
            }
        }
    }

    behinstProto.calculateStretch = function ()
    {
        if (!this.fixture)
        {
            return 0;
        }
        var distance = cr.distanceTo(this.fixture.x, this.fixture.y, this.inst.x, this.inst.y),
            displacement = Math.max(distance - this.relaxedLength, 0),
            result = {};
        result.ratio = displacement/distance;
        result.displacement = displacement;
        return result;
    }

    behinstProto.getDeltaVector = function ()
    {
        var result = {};
        if (!this.fixture)
        {
            result.x = 0;
            result.y = 0;
            return result;
        }
        result.x = this.fixture.x - this.inst.x;
        result.y = this.fixture.y - this.inst.y;
        return result;
    }

    /**BEGIN-PREVIEWONLY**/
    behinstProto.getDebuggerValues = function (propsections)
    {
        propsections.push({
            "title": this.type.name,
            "properties": [
                {"name": "fixtureName/UID", "value": this.fixture ? this.fixture.type.name+"/"+this.fixture.uid : "-/-", "readonly": true},
                {"name": "Tiedness", "value": !! this.fixture, "readonly": true},
                {"name": "Stretchedness", "value": this.isStretched, "readonly": true},
                {"name": "Velocity.x", "value": this.dx, "readonly": true},
                {"name": "Velocity.y", "value": this.dy, "readonly": true},
                {"name": "Relaxed Length", "value": this.relaxedLength},
                {"name": "Spring Rate", "value": this.stiffness},
                {"name": "Gravity", "value": this.gravity},
                {"name": "Drag", "value": this.drag},
                {"name": "Enabled", "value": !! this.enabled}
            ]
        });
    };

    behinstProto.onDebugValueEdited = function (header, name, value)
    {
        if (name === "Relaxed Length")
            this.relaxedLength = value;
        if (name === "Spring Rate")
            this.stiffness = value;
        if (name === "Gravity")
            this.gravity = value;
        if (name === "Drag")
            this.drag = value;
        if (name === "Enabled")
            this.enabled = value;
    };
    /**END-PREVIEWONLY**/

    function Cnds() {};

    Cnds.prototype.IsStretched = function () { return this.isStretched }
    Cnds.prototype.IsTied = function () { return !! this.fixture }
    Cnds.prototype.IsEnabled = function () { return this.enabled }

    behaviorProto.cnds = new Cnds();

    function Acts() {};

    Acts.prototype.tie = function (obj)
    {
        if (!obj)
        {
            return;
        }
        var otherinst = obj.getFirstPicked(this.inst);
        if (!otherinst)
        {
            return;
        }
        this.fixture = otherinst;
    };

    Acts.prototype.cut = function (obj)
    {
        this.fixture = null;
        this.isStretched = false;
    }

    Acts.prototype.SetEnabled = function (en)
    {
        this.enabled = (en === 1);
        if (!this.enabled)
        {
            this.dx = 0;
            this.dy = 0;
        }
    };

    behaviorProto.acts = new Acts();

    function Exps() {};

    behaviorProto.exps = new Exps();

}());
<commit_msg>Trying to minimize jumping/artifacts of jumps in framerate<commit_after>// ECMAScript 5 strict mode
"use strict";

assert2(cr, "cr namespace not created");
assert2(cr.behaviors, "cr.behaviors not created");

cr.behaviors.RubberBand = function(runtime)
{
    this.runtime = runtime;
};

(function ()
{
    var behaviorProto = cr.behaviors.RubberBand.prototype;

    behaviorProto.Type = function(behavior, objtype)
    {
        this.behavior = behavior;
        this.objtype = objtype;
        this.runtime = behavior.runtime;
    };

    var behtypeProto = behaviorProto.Type.prototype;

    behtypeProto.onCreate = function()
    {
    };

    behaviorProto.Instance = function(type, inst)
    {
        this.type = type;
        this.behavior = type.behavior;
        this.inst = inst;
        this.runtime = type.runtime;
    };

    var behinstProto = behaviorProto.Instance.prototype;

    behinstProto.onCreate = function()
    {
        this.relaxedLength = this.properties[0];
        this.stiffness = this.properties[1]*0.1; // for nicer default config values
        this.gravity = this.properties[2]*100;
        this.drag = this.properties[3]*0.01;
        this.enabled = this.properties[4]; // 0=disabled, 1=enabled

        this.fixture = null;
        this.fixtureUid = -1;
        this.dx = 0;
        this.dy = 0;
        this.isStretched = false;
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    };

    behinstProto.onDestroy = function ()
    {
        this.fixture = null;
    };

    behinstProto.saveToJSON = function ()
    {
        return {
            "fixtureUid": this.fixture ? this.fixture.uid : -1,
            "relaxedLength": this.relaxedLength,
            "stiffness": this.stiffness,
            "gravity": this.gravity,
            "enabled": this.enabled,
            "drag": this.drag,
            "dx": this.dx,
            "dy": this.dy,
            "lastX": this.lastX,
            "lastY": this.lastY
        };
    };

    behinstProto.loadFromJSON = function (o)
    {
        this.fixtureUid = o["fixtureUid"];
        this.relaxedLength = o["relaxedLength"];
        this.stiffness = o["stiffness"];
        this.gravity = o["gravity"];
        this.enabled = o["enabled"];
        this.drag = o["drag"];
        this.dx = o["dx"];
        this.dy = o["dy"];
        this.lastX = o["lastX"];
        this.lastY = o["lastY"];

        this.isStretched = (this.calculateStretch().displacement > 0);
    };

    behinstProto.afterLoad = function ()
    {
        if (this.fixtureUid === -1)
        {
            this.fixture = null;
        }
        else
        {
            this.fixture = this.runtime.getObjectByUID(this.fixtureUid);
            assert2(this.fixture, "Failed to find fixture object by UID");
        }

        this.fixtureUid = -1;
    };

    behinstProto.tick = function ()
    {
        this.pickupExternalImpulse();
        if (this.enabled)
        {
            this.applyBandMovement();
        }
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    }

    behinstProto.applyBandMovement = function ()
    {
        var accelX = 0,
            accelY = 0,
            dt = this.runtime.getDt(this.inst),
            delta = this.getDeltaVector(),
            stretch = this.calculateStretch();
        if (this.fixture)
        {
            this.isStretched = (stretch.displacement > 0);
            if (this.isStretched)
            {
                var accel = stretch.displacement*this.stiffness;
                accelX = accel*delta.x*stretch.ratio;
                accelY = accel*delta.y*stretch.ratio;
                this.dx += dt*accelX;
                this.dy += dt*accelY;
            }
        }
        if (this.gravity)
        {
            this.dy += dt*this.gravity;
        }
        if (this.drag)
        {
            this.dx -= (this.drag*this.dx);
            this.dy -= (this.drag*this.dy);
        }
        {
            this.inst.x += (this.dx + 0.5*(accelX)*dt)*dt;
            this.inst.y += (this.dy + 0.5*(accelY + this.gravity)*dt)*dt;
            this.inst.set_bbox_changed();
        }
    };

    behinstProto.pickupExternalImpulse = function ()
    {
        if (this.lastX !== this.inst.x || this.lastY !== this.inst.y)
        {
            var dt = this.runtime.getDt(this.inst),
                deltaX = this.inst.x - this.lastX,
                deltaY = this.inst.y - this.lastY;
            if (dt <= 0.005) { return } // avoid jumps after pausing/when tabbing
            this.dx = (this.dx + deltaX/dt)/2;
            this.dy = (this.dy + deltaY/dt)/2;
        }
    }

    behinstProto.calculateStretch = function ()
    {
        if (!this.fixture)
        {
            return 0;
        }
        var distance = cr.distanceTo(this.fixture.x, this.fixture.y, this.inst.x, this.inst.y),
            displacement = Math.max(distance - this.relaxedLength, 0),
            result = {};
        result.ratio = displacement/distance;
        result.displacement = displacement;
        return result;
    }

    behinstProto.getDeltaVector = function ()
    {
        var result = {};
        if (!this.fixture)
        {
            result.x = 0;
            result.y = 0;
            return result;
        }
        result.x = this.fixture.x - this.inst.x;
        result.y = this.fixture.y - this.inst.y;
        return result;
    }

    /**BEGIN-PREVIEWONLY**/
    behinstProto.getDebuggerValues = function (propsections)
    {
        propsections.push({
            "title": this.type.name,
            "properties": [
                {"name": "fixtureName/UID", "value": this.fixture ? this.fixture.type.name+"/"+this.fixture.uid : "-/-", "readonly": true},
                {"name": "Tiedness", "value": !! this.fixture, "readonly": true},
                {"name": "Stretchedness", "value": this.isStretched, "readonly": true},
                {"name": "Velocity.x", "value": this.dx, "readonly": true},
                {"name": "Velocity.y", "value": this.dy, "readonly": true},
                {"name": "Relaxed Length", "value": this.relaxedLength},
                {"name": "Spring Rate", "value": this.stiffness},
                {"name": "Gravity", "value": this.gravity},
                {"name": "Drag", "value": this.drag},
                {"name": "Enabled", "value": !! this.enabled}
            ]
        });
    };

    behinstProto.onDebugValueEdited = function (header, name, value)
    {
        if (name === "Relaxed Length")
            this.relaxedLength = value;
        if (name === "Spring Rate")
            this.stiffness = value;
        if (name === "Gravity")
            this.gravity = value;
        if (name === "Drag")
            this.drag = value;
        if (name === "Enabled")
            this.enabled = value;
    };
    /**END-PREVIEWONLY**/

    function Cnds() {};

    Cnds.prototype.IsStretched = function () { return this.isStretched }
    Cnds.prototype.IsTied = function () { return !! this.fixture }
    Cnds.prototype.IsEnabled = function () { return this.enabled }

    behaviorProto.cnds = new Cnds();

    function Acts() {};

    Acts.prototype.tie = function (obj)
    {
        if (!obj)
        {
            return;
        }
        var otherinst = obj.getFirstPicked(this.inst);
        if (!otherinst)
        {
            return;
        }
        this.fixture = otherinst;
    };

    Acts.prototype.cut = function (obj)
    {
        this.fixture = null;
        this.isStretched = false;
    }

    Acts.prototype.SetEnabled = function (en)
    {
        this.enabled = (en === 1);
        if (!this.enabled)
        {
            this.dx = 0;
            this.dy = 0;
        }
    };

    behaviorProto.acts = new Acts();

    function Exps() {};

    behaviorProto.exps = new Exps();

}());
<|endoftext|>


<commit_before>describe("the options panel", function() {

  var visitOptions = function() {
    return Tests.visit("options")
    .then(function () {
      return Tests.importRules();
    })
    .then(function () {
      return $(".extension-options-url a").click();
    }).then(function () {
      return browser.driver.sleep(500);
    });
  };

  it("is available", function(){
    visitOptions().then(function () {
      expect(browser.driver.getTitle()).to.become("Form-O-Fill Options");
    });
  });

  it("is contains all essential parts", function(){
    visitOptions().then(function () {
      // Current tab
      expect($("li.tab.current input").getAttribute("value")).to.become("dummy");

      // More tab
      expect($("li.tab.more").isPresent()).to.become(true);

      // Quickump menu
      expect($("#rules-overview").isPresent()).to.become(true);

      // Action buttons
      expect($(".menu button.save").isPresent()).to.become(true);
      expect($(".menu button.reload").isPresent()).to.become(true);
      expect($(".menu button.format").isPresent()).to.become(true);
      expect($(".menu button.export").isPresent()).to.become(true);
      expect($(".menu button.import").isPresent()).to.become(true);

      // Editor window
      $("#ruleeditor-ace").getSize().then(function (size) {
        expect(size.height).to.be.above(200);
        expect(size.width).to.be.above(200);
      });

      // Navigation links
      expect($$(".navigation .menu li").getText()).to.become(["Rule Editor", "Help", "About", "Changelog", "Logs"]);
    });
  });

});
<commit_msg>i really dig promises. even simpler now<commit_after>describe("the options panel", function() {

  var visitOptions = function() {
    return Tests.visit("options")
    .then(Tests.importRules)
    .then($(".extension-options-url a").click)
    .then(function () {
      return browser.driver.sleep(1000);
    });
  };

  it("is available", function(){
    visitOptions().then(function () {
      expect(browser.driver.getTitle()).to.become("Form-O-Fill Options");
    });
  });

  it("is contains all essential parts", function(){
    visitOptions().then(function () {
      // Current tab
      expect($("li.tab.current input").getAttribute("value")).to.become("dummy");

      // More tab
      expect($("li.tab.more").isPresent()).to.become(true);

      // Quickump menu
      expect($("#rules-overview").isPresent()).to.become(true);

      // Action buttons
      expect($(".menu button.save").isPresent()).to.become(true);
      expect($(".menu button.reload").isPresent()).to.become(true);
      expect($(".menu button.format").isPresent()).to.become(true);
      expect($(".menu button.export").isPresent()).to.become(true);
      expect($(".menu button.import").isPresent()).to.become(true);

      // Editor window
      $("#ruleeditor-ace").getSize().then(function (size) {
        expect(size.height).to.be.above(200);
        expect(size.width).to.be.above(200);
      });

      // Navigation links
      expect($$(".navigation .menu li").getText()).to.become(["Rule Editor", "Help", "About", "Changelog", "Logs"]);
    });
  });

});
<|endoftext|>


<commit_before>/* global vm, Promise */
const {Chromeless} = require('chromeless');
const test = require('tap').test;
const path = require('path');
const fs = require('fs');
const chromeless = new Chromeless();

const indexHTML = path.resolve(__dirname, 'index.html');
const testDir = (...args) => path.resolve(__dirname, 'scratch-tests', ...args);

const testFile = file => test(file, async t => {
    // start each test by going to the index.html, and loading the scratch file
    const says = await chromeless.goto(`file://${indexHTML}`)
        .setFileInput('#file', testDir(file))
        // the index.html handler for file input will add a #loaded element when it
        // finishes.
        .wait('#loaded')
        .evaluate(() => {
            // This function is run INSIDE the integration chrome browser via some
            // injection and .toString() magic.  We can return some "simple data"
            // back across as a promise, so we will just log all the says that happen
            // for parsing after.

            // this becomes the `says` in the outer scope
            const messages = [];
            const TIMEOUT = 5000;

            vm.runtime.on('SAY', (_, __, message) => {
                messages.push(message);
            });

            vm.greenFlag();
            const startTime = Date.now();

            return Promise.resolve()
                .then(async () => {
                    // waiting for all threads to complete, then we return
                    while (vm.runtime.threads.length > 0) {
                        if ((Date.now() - startTime) >= TIMEOUT) {
                            messages.push(`fail Threads still running after ${TIMEOUT}ms`);
                            break;
                        }

                        await new Promise(resolve => setTimeout(resolve, 50));
                    }

                    return messages;
                });
        });

    // Map string messages to tap reporting methods. This will be used
    // with events from scratch's runtime emitted on block instructions.
    let didPlan = false;
    let didEnd = false;
    const reporters = {
        comment (message) {
            t.comment(message);
        },
        pass (reason) {
            t.pass(reason);
        },
        fail (reason) {
            t.fail(reason);
        },
        plan (count) {
            didPlan = true;
            t.plan(Number(count));
        },
        end () {
            didEnd = true;
            t.end();
        }
    };

    // loop over each "SAY" we caught from the VM and use the reporters
    says.forEach(text => {
        // first word of the say is going to be a "command"
        const command = text.split(/\s+/, 1)[0].toLowerCase();
        if (reporters[command]) {
            return reporters[command](text.substring(command.length).trim());
        }

        // Default to a comment with the full text if we didn't match
        // any command prefix
        return reporters.comment(text);
    });

    if (!didPlan) {
        t.comment('did not say "plan NUMBER_OF_TESTS"');
    }

    // End must be called so that tap knows the test is done. If
    // the test has a SAY "end" block but that block did not
    // execute, this explicit failure will raise that issue so
    // it can be resolved.
    if (!didEnd) {
        t.fail('did not say "end"');
        t.end();
    }
});

// immediately invoked async function to let us wait for each test to finish before starting the next.
(async () => {
    const files = fs.readdirSync(testDir())
        .filter(uri => uri.endsWith('.sb2') || uri.endsWidth('.sb3'));

    for (const file of files) {
        await testFile(file);
    }

    // close the browser window we used
    await chromeless.end();
})();
<commit_msg>Fix a thread status check in integration tests to allow "done" threads<commit_after>/* global vm, Promise */
const {Chromeless} = require('chromeless');
const test = require('tap').test;
const path = require('path');
const fs = require('fs');
const chromeless = new Chromeless();

const indexHTML = path.resolve(__dirname, 'index.html');
const testDir = (...args) => path.resolve(__dirname, 'scratch-tests', ...args);

const testFile = file => test(file, async t => {
    // start each test by going to the index.html, and loading the scratch file
    const says = await chromeless.goto(`file://${indexHTML}`)
        .setFileInput('#file', testDir(file))
        // the index.html handler for file input will add a #loaded element when it
        // finishes.
        .wait('#loaded')
        .evaluate(() => {
            // This function is run INSIDE the integration chrome browser via some
            // injection and .toString() magic.  We can return some "simple data"
            // back across as a promise, so we will just log all the says that happen
            // for parsing after.

            // this becomes the `says` in the outer scope
            const messages = [];
            const TIMEOUT = 5000;

            vm.runtime.on('SAY', (_, __, message) => {
                messages.push(message);
            });

            vm.greenFlag();
            const startTime = Date.now();

            return Promise.resolve()
                .then(async () => {
                    // waiting for all threads to complete, then we return

                    while (vm.runtime.threads.filter(thread => vm.runtime.isActiveThread(thread)).length > 0) {
                        if ((Date.now() - startTime) >= TIMEOUT) {
                            // if we push the message after end, the failure from tap is not very useful:
                            // "not ok test after end() was called"
                            messages.unshift(`fail Threads still running after ${TIMEOUT}ms`);
                            break;
                        }

                        await new Promise(resolve => setTimeout(resolve, 50));
                    }

                    return messages;
                });
        });

    // Map string messages to tap reporting methods. This will be used
    // with events from scratch's runtime emitted on block instructions.
    let didPlan = false;
    let didEnd = false;
    const reporters = {
        comment (message) {
            t.comment(message);
        },
        pass (reason) {
            t.pass(reason);
        },
        fail (reason) {
            t.fail(reason);
        },
        plan (count) {
            didPlan = true;
            t.plan(Number(count));
        },
        end () {
            didEnd = true;
            t.end();
        }
    };

    // loop over each "SAY" we caught from the VM and use the reporters
    says.forEach(text => {
        // first word of the say is going to be a "command"
        const command = text.split(/\s+/, 1)[0].toLowerCase();
        if (reporters[command]) {
            return reporters[command](text.substring(command.length).trim());
        }

        // Default to a comment with the full text if we didn't match
        // any command prefix
        return reporters.comment(text);
    });

    if (!didPlan) {
        t.comment('did not say "plan NUMBER_OF_TESTS"');
    }

    // End must be called so that tap knows the test is done. If
    // the test has a SAY "end" block but that block did not
    // execute, this explicit failure will raise that issue so
    // it can be resolved.
    if (!didEnd) {
        t.fail('did not say "end"');
        t.end();
    }
});

// immediately invoked async function to let us wait for each test to finish before starting the next.
(async () => {
    const files = fs.readdirSync(testDir())
        .filter(uri => uri.endsWith('.sb2') || uri.endsWidth('.sb3'));

    for (const file of files) {
        await testFile(file);
    }

    // close the browser window we used
    await chromeless.end();
})();
<|endoftext|>


<commit_before>const showSlides = require('../../src/commons/showSlides');

describe('the showSlides module', async () => {
  it('does nothing when id is not found', async () => {
    const doc = {
      getElementById() {
        return null;
      }
    };
    let res;
    document.body.innerHTML = '';
    try {
      res = await showSlides.showSlides(['booya'], doc);
      expect(res).toBe(1);
    } catch (e) {
      throw e;
    }
  });
});
<commit_msg>jest lint error fixes<commit_after>const showSlides = require('../../src/commons/showSlides');

describe('the showSlides module', () => {
  it('does nothing when id is not found', async () => {
    const doc = {
      getElementById() {
        return null;
      }
    };
    let res;
    document.body.innerHTML = '';
    try {
      res = await showSlides.showSlides(['booya'], doc);
      expect(res).toBe(1);
    } catch (e) {
      throw e;
    }
  });
});
<|endoftext|>


<commit_before>// @flow weak

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import RaisedButton from 'material-ui/RaisedButton';
import withWidth, { LARGE } from 'material-ui/utils/withWidth';
import spacing from 'material-ui/styles/spacing';
import typography from 'material-ui/styles/typography';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import FullWidthSection from '../components/FullWidthSection';

class HomePage extends Component {
  static propTypes = {
    width: PropTypes.number.isRequired,
  };

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  homePageHero() {
    const styles = {
      root: {
        overflow: 'hidden',
      },
      tagline: {
        margin: '16px auto 0 auto',
        textAlign: 'center',
        maxWidth: 575,
      },
      label: {
        color: lightBaseTheme.palette.primary1Color,
      },
      h1: {
        fontWeight: typography.fontWeightLight,
      },
      h2: {
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 19,
        marginBottom: 13,
        letterSpacing: 0,
      },
      nowrap: {
        whiteSpace: 'nowrap',
      },
      taglineWhenLarge: {
        marginTop: 32,
      },
      h1WhenLarge: {
        fontSize: 56,
      },
      h2WhenLarge: {
        fontSize: 24,
        lineHeight: '32px',
        paddingTop: 16,
        marginBottom: 12,
      },
    };

    styles.h2 = Object.assign({}, styles.h1, styles.h2);

    if (this.props.width === LARGE) {
    //   styles.tagline = Object.assign({}, styles.tagline, styles.taglineWhenLarge);
    //   styles.h1 = Object.assign({}, styles.h1, styles.h1WhenLarge);
    //   styles.h2 = Object.assign({}, styles.h2, styles.h2WhenLarge);
    }

    return (
      <FullWidthSection style={styles.root}>

Resonance

      </FullWidthSection>
    );
  }

  homeContribute() {
    const styles = {
      root: {
        textAlign: 'center',
      },
      h3: {
        margin: 0,
        padding: 0,
        fontWeight: typography.fontWeightLight,
        fontSize: 22,
      },
      button: {
        marginTop: 32,
      },
    };

    return (
      <FullWidthSection useContent style={styles.root}>
        <RaisedButton
          label="GitHub"
          primary
          href="https://github.com/sghall/resonance"
          style={styles.button}
        />
        <RaisedButton
          label="Examples"
          onTouchTap={this.handleTouchTapDemo}
          style={styles.button}
        />
      </FullWidthSection>
    );
  }

  handleTouchTapDemo = () => {
    this.context.router.push('/examples/states-by-age');
  };

  render() {
    const style = {
      paddingTop: spacing.desktopKeylineIncrement,
    };

    return (

        {this.homePageHero()}
        {this.homeContribute()}

    );
  }
}

export default withWidth()(HomePage);
<commit_msg>update link<commit_after>// @flow weak

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import RaisedButton from 'material-ui/RaisedButton';
import withWidth, { LARGE } from 'material-ui/utils/withWidth';
import spacing from 'material-ui/styles/spacing';
import typography from 'material-ui/styles/typography';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import FullWidthSection from '../components/FullWidthSection';

class HomePage extends Component {
  static propTypes = {
    width: PropTypes.number.isRequired,
  };

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  homePageHero() {
    const styles = {
      root: {
        overflow: 'hidden',
      },
      tagline: {
        margin: '16px auto 0 auto',
        textAlign: 'center',
        maxWidth: 575,
      },
      label: {
        color: lightBaseTheme.palette.primary1Color,
      },
      h1: {
        fontWeight: typography.fontWeightLight,
      },
      h2: {
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 19,
        marginBottom: 13,
        letterSpacing: 0,
      },
      nowrap: {
        whiteSpace: 'nowrap',
      },
      taglineWhenLarge: {
        marginTop: 32,
      },
      h1WhenLarge: {
        fontSize: 56,
      },
      h2WhenLarge: {
        fontSize: 24,
        lineHeight: '32px',
        paddingTop: 16,
        marginBottom: 12,
      },
    };

    styles.h2 = Object.assign({}, styles.h1, styles.h2);

    if (this.props.width === LARGE) {
    //   styles.tagline = Object.assign({}, styles.tagline, styles.taglineWhenLarge);
    //   styles.h1 = Object.assign({}, styles.h1, styles.h1WhenLarge);
    //   styles.h2 = Object.assign({}, styles.h2, styles.h2WhenLarge);
    }

    return (
      <FullWidthSection style={styles.root}>

Resonance

      </FullWidthSection>
    );
  }

  homeContribute() {
    const styles = {
      root: {
        textAlign: 'center',
      },
      h3: {
        margin: 0,
        padding: 0,
        fontWeight: typography.fontWeightLight,
        fontSize: 22,
      },
      button: {
        marginTop: 32,
      },
    };

    return (
      <FullWidthSection useContent style={styles.root}>
        <RaisedButton
          label="GitHub"
          primary
          href="https://github.com/sghall/resonance"
          style={styles.button}
        />
        <RaisedButton
          label="Examples"
          onTouchTap={this.handleTouchTapDemo}
          style={styles.button}
        />
      </FullWidthSection>
    );
  }

  handleTouchTapDemo = () => {
    this.context.router.push('/redux-examples/states-by-age');
  };

  render() {
    const style = {
      paddingTop: spacing.desktopKeylineIncrement,
    };

    return (

        {this.homePageHero()}
        {this.homeContribute()}

    );
  }
}

export default withWidth()(HomePage);
<|endoftext|>


<commit_before>import StyleManager from 'style_manager';
import Models from './model/Models';
import SectorView from './view/SectorView';
import SectorsView from './view/SectorsView';
import PropertyView from './view/PropertyView';
import PropertySelectView from './view/PropertySelectView';
import PropertyRadioView from './view/PropertyRadioView';
import PropertyIntegerView from './view/PropertyIntegerView';
import PropertyColorView from './view/PropertyColorView';
import PropertyCompositeView from './view/PropertyCompositeView';
import PropertyStackView from './view/PropertyStackView';
import LayerView from './view/LayerView';

describe('StyleManager', () => {
  describe('Main', () => {
    var obj;

    beforeEach(() => {
      obj = new StyleManager().init({
        sectors: []
      });
    });

    afterEach(() => {
      obj = null;
    });

    test('Object exists', () => {
      expect(obj).toBeTruthy();
    });

    test('No sectors', () => {
      expect(obj.getSectors().length).toEqual(0);
    });

    test('Add sector', () => {
      obj.addSector('test', {
        name: 'Test name'
      });
      var sector = obj.getSectors().at(0);
      expect(obj.getSectors().length).toEqual(1);
      expect(sector.get('id')).toEqual('test');
      expect(sector.get('name')).toEqual('Test name');
    });

    test('Add sectors', () => {
      obj.addSector('test', {});
      obj.addSector('test2', {});
      expect(obj.getSectors().length).toEqual(2);
    });

    test("Can't create more than one sector with the same id", () => {
      var sect1 = obj.addSector('test', {});
      var sect2 = obj.addSector('test', {});
      expect(obj.getSectors().length).toEqual(1);
      expect(sect1).toEqual(sect2);
    });

    test('Get inexistent sector', () => {
      expect(obj.getSector('test')).toBeFalsy();
    });

    test('Get sector', () => {
      var sect1 = obj.addSector('test', { name: 'Test' });
      var sect2 = obj.getSector('test');
      expect(sect1).toEqual(sect2);
    });

    test('Add property to inexistent sector', () => {
      expect(obj.addProperty('test', {})).toEqual(null);
    });

    test('Add property', () => {
      obj.addSector('test', {});
      expect(obj.addProperty('test', {})).toBeTruthy();
      expect(obj.getProperties('test').length).toEqual(1);
    });

    test('Check added property', () => {
      obj.addSector('test', {});
      var prop = obj.addProperty('test', {
        name: 'test'
      });
      expect(prop.get('name')).toEqual('test');
    });

    test('Add properties', () => {
      obj.addSector('test', {});
      obj.addProperty('test', [{}, {}]);
      expect(obj.getProperties('test').length).toEqual(2);
    });

    test('Get property from inexistent sector', () => {
      expect(obj.getProperty('test', 'test-prop')).toEqual(null);
    });

    test("Can't get properties without proper name", () => {
      obj.addSector('test', {});
      obj.addProperty('test', [{}, {}]);
      expect(obj.getProperty('test', 'test-prop')).toEqual(null);
    });

    test('Get property with proper name', () => {
      obj.addSector('test', {});
      var prop1 = obj.addProperty('test', { property: 'test-prop' });
      var prop2 = obj.getProperty('test', 'test-prop');
      expect(prop1).toEqual(prop2);
    });

    test('Get properties with proper name', () => {
      obj.addSector('test', {});
      obj.addProperty('test', [
        { property: 'test-prop' },
        { property: 'test-prop' }
      ]);
      expect(obj.getProperty('test', 'test-prop')).toBeTruthy();
    });

    test('Get inexistent properties', () => {
      expect(obj.getProperties('test')).toEqual(null);
      expect(obj.getProperties()).toEqual(null);
    });

    test('Renders correctly', () => {
      expect(obj.render()).toBeTruthy();
    });

    describe('Init with configuration', () => {
      beforeEach(() => {
        obj = new StyleManager().init({
          sectors: [
            {
              id: 'dim',
              name: 'Dimension',
              properties: [
                {
                  name: 'Width',
                  property: 'width'
                },
                {
                  name: 'Height',
                  property: 'height'
                }
              ]
            },
            {
              id: 'pos',
              name: 'position',
              properties: [
                {
                  name: 'Width',
                  property: 'width'
                }
              ]
            }
          ]
        });
        obj.onLoad();
      });

      afterEach(() => {
        obj = null;
      });

      test('Sectors added', () => {
        expect(obj.getSectors().length).toEqual(2);
        var sect1 = obj.getSector('dim');
        expect(sect1.get('name')).toEqual('Dimension');
      });

      test('Properties added', () => {
        var sect1 = obj.getSector('dim');
        var sect2 = obj.getSector('pos');
        expect(sect1.get('properties').length).toEqual(2);
        expect(sect2.get('properties').length).toEqual(1);
      });

      test('Property is correct', () => {
        var prop1 = obj.getProperty('dim', 'width');
        expect(prop1.get('name')).toEqual('Width');
      });
    });
  });
});
<commit_msg>Fix StyleManager tests<commit_after>import Editor from 'editor/model/Editor';

describe('StyleManager', () => {
  describe('Main', () => {
    let obj;
    let em;

    beforeEach(() => {
      em = new Editor({});
      obj = em.get('StyleManager');
    });

    afterEach(() => {
      obj = null;
      em.destroy();
    });

    test('Object exists', () => {
      expect(obj).toBeTruthy();
    });

    test('No sectors', () => {
      expect(obj.getSectors().length).toEqual(0);
    });

    test('Add sector', () => {
      obj.addSector('test', {
        name: 'Test name'
      });
      var sector = obj.getSectors()[0];
      expect(obj.getSectors().length).toEqual(1);
      expect(sector.get('id')).toEqual('test');
      expect(sector.get('name')).toEqual('Test name');
    });

    test('Add sectors', () => {
      obj.addSector('test', {});
      obj.addSector('test2', {});
      expect(obj.getSectors().length).toEqual(2);
    });

    test("Can't create more than one sector with the same id", () => {
      var sect1 = obj.addSector('test', {});
      var sect2 = obj.addSector('test', {});
      expect(obj.getSectors().length).toEqual(1);
      expect(sect1).toEqual(sect2);
    });

    test('Get inexistent sector', () => {
      expect(obj.getSector('test')).toBeFalsy();
    });

    test('Get sector', () => {
      var sect1 = obj.addSector('test', { name: 'Test' });
      var sect2 = obj.getSector('test');
      expect(sect1).toEqual(sect2);
    });

    test('Add property to inexistent sector', () => {
      expect(obj.addProperty('test', {})).toEqual(null);
    });

    test('Add property', () => {
      obj.addSector('test', {});
      expect(obj.addProperty('test', {})).toBeTruthy();
      expect(obj.getProperties('test').length).toEqual(1);
    });

    test('Check added property', () => {
      obj.addSector('test', {});
      var prop = obj.addProperty('test', {
        name: 'test'
      });
      expect(prop.get('name')).toEqual('test');
    });

    test('Add properties', () => {
      obj.addSector('test', {});
      obj.addProperty('test', [{}, {}]);
      expect(obj.getProperties('test').length).toEqual(2);
    });

    test('Get property from inexistent sector', () => {
      expect(obj.getProperty('test', 'test-prop')).toEqual(null);
    });

    test("Can't get properties without proper name", () => {
      obj.addSector('test', {});
      obj.addProperty('test', [{}, {}]);
      expect(obj.getProperty('test', 'test-prop')).toEqual(null);
    });

    test('Get property with proper name', () => {
      obj.addSector('test', {});
      var prop1 = obj.addProperty('test', { property: 'test-prop' });
      var prop2 = obj.getProperty('test', 'test-prop');
      expect(prop1).toEqual(prop2);
    });

    test('Get properties with proper name', () => {
      obj.addSector('test', {});
      obj.addProperty('test', [
        { property: 'test-prop' },
        { property: 'test-prop' }
      ]);
      expect(obj.getProperty('test', 'test-prop')).toBeTruthy();
    });

    test('Get inexistent properties', () => {
      expect(obj.getProperties('test')).toEqual(null);
      expect(obj.getProperties()).toEqual(null);
    });

    test('Renders correctly', () => {
      expect(obj.render()).toBeTruthy();
    });

    describe('Init with configuration', () => {
      beforeEach(() => {
        em = new Editor({
          StyleManager: {
            sectors: [
              {
                id: 'dim',
                name: 'Dimension',
                properties: [
                  {
                    name: 'Width',
                    property: 'width'
                  },
                  {
                    name: 'Height',
                    property: 'height'
                  }
                ]
              },
              {
                id: 'pos',
                name: 'position',
                properties: [
                  {
                    name: 'Width',
                    property: 'width'
                  }
                ]
              }
            ]
          }
        });
        obj = em.get('StyleManager');
        obj.onLoad();
      });

      afterEach(() => {
        obj = null;
        em.destroy();
      });

      test('Sectors added', () => {
        expect(obj.getSectors().length).toEqual(2);
        var sect1 = obj.getSector('dim');
        expect(sect1.get('name')).toEqual('Dimension');
      });

      test('Properties added', () => {
        var sect1 = obj.getSector('dim');
        var sect2 = obj.getSector('pos');
        expect(sect1.get('properties').length).toEqual(2);
        expect(sect2.get('properties').length).toEqual(1);
      });

      test('Property is correct', () => {
        var prop1 = obj.getProperty('dim', 'width');
        expect(prop1.get('name')).toEqual('Width');
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var helper   = require('../../helpers/angularity-test'),
    matchers = require('../../helpers/jasmine-matchers');

var fastIt = helper.jasmineFactory({
  before: 0,
  after : 500
});

var slowIt = helper.jasmineFactory({
  before: 500,
  after : 1000
});

var FLAGS = [ 'project', 'external', 'codestyle', 'templates', 'launch' ];

describe('The Angularity webstorm task', function () {

  beforeEach(matchers.addMatchers);

  beforeEach(customMatchers);

  beforeEach(helper.getTimeoutSwitch(60000));

  afterEach(helper.getTimeoutSwitch());

  afterEach(helper.cleanUp);

 // TODO @bholloway appveyor fails command with exitcode 1 and nothing on stdout or stderr
 var platform = require('../../../lib/config/platform');
 if (!platform.isAppveyor()) {
  describe('should display help when requested', function (done) {
    helper.runner.create()
      .addInvocation('webstorm --help')
      .addInvocation('webstorm -h')
      .forEach(fastIt(expectations))
      .finally(done);

    function expectations(testCase) {
      expect(testCase.stderr).toBeBuildHelpWithError(false);
    }
  });
}

  describe('should fail where angularity.json is not present', function(done) {
    helper.runner.create()
      .addSource('minimal-es5')
      .withSourceFilter(function removeBuildFiles(value) {
        return !(/angularity.json$/.test(value));
      })
      .addInvocation('webstorm', FLAGS.map(composeOption(false)))
      .forEach(slowIt(expectations))
      .finally(done);

    function expectations(testCase) {
      expect(testCase.stderr).toBeBuildHelpWithError(true);
    }
  });

  describe('should operate with all flags false', function(done) {
    helper.runner.create()
      .addSource('minimal-es5')
      .addInvocation('webstorm', FLAGS.map(composeOption(false)))
      .forEach(slowIt(expectations))
      .finally(done);

    function expectations(testCase) {
      expect(testCase.stdout).toBeTask('webstorm');
    }
  });

  // TODO @bholloway more test coverage on webstorm task
});

function composeOption(boolean) {
  return function optionToInvocation(option) {
    return ((option.length > 1) ? '--' : '-') + option + ' ' + boolean;
  };
}

function customMatchers() {
  jasmine.addMatchers({
    toBeBuildHelpWithError: matchers.getHelpMatcher(/^\s*The "webstorm" task/)
  });
}<commit_msg>gate all webstorm tests on appveyor<commit_after>'use strict';

var helper   = require('../../helpers/angularity-test'),
    matchers = require('../../helpers/jasmine-matchers'),
    platform = require('../../../lib/config/platform');

var fastIt = helper.jasmineFactory({
  before: 0,
  after : 500
});

var slowIt = helper.jasmineFactory({
  before: 500,
  after : 1000
});

var FLAGS = [ 'project', 'external', 'codestyle', 'templates', 'launch' ];

// TODO @bholloway appveyor fails any webstorm command with exitcode 1 and nothing on stdout or stderr
if (!platform.isAppveyor()) {

  describe('The Angularity webstorm task', function () {

    beforeEach(matchers.addMatchers);

    beforeEach(customMatchers);

    beforeEach(helper.getTimeoutSwitch(60000));

    afterEach(helper.getTimeoutSwitch());

    afterEach(helper.cleanUp);

    describe('should display help when requested', function (done) {
      helper.runner.create()
        .addInvocation('webstorm --help')
        .addInvocation('webstorm -h')
        .forEach(fastIt(expectations))
        .finally(done);

      function expectations(testCase) {
        expect(testCase.stderr).toBeBuildHelpWithError(false);
      }
    });

    describe('should fail where angularity.json is not present', function (done) {
      helper.runner.create()
        .addSource('minimal-es5')
        .withSourceFilter(function removeBuildFiles(value) {
          return !(/angularity.json$/.test(value));
        })
        .addInvocation('webstorm', FLAGS.map(composeOption(false)))
        .forEach(slowIt(expectations))
        .finally(done);

      function expectations(testCase) {
        expect(testCase.stderr).toBeBuildHelpWithError(true);
      }
    });

    describe('should operate with all flags false', function (done) {
      helper.runner.create()
        .addSource('minimal-es5')
        .addInvocation('webstorm', FLAGS.map(composeOption(false)))
        .forEach(slowIt(expectations))
        .finally(done);

      function expectations(testCase) {
        expect(testCase.stdout).toBeTask('webstorm');
      }
    });

    // TODO @bholloway more test coverage on webstorm task
  });
}

function composeOption(boolean) {
  return function optionToInvocation(option) {
    return ((option.length > 1) ? '--' : '-') + option + ' ' + boolean;
  };
}

function customMatchers() {
  jasmine.addMatchers({
    toBeBuildHelpWithError: matchers.getHelpMatcher(/^\s*The "webstorm" task/)
  });
}<|endoftext|>


<commit_before>// create table view data object
var data = [
	{title:'Local', hasChild:true, test:'../examples/sound_local.js'},
	{title:'Local with File', hasChild:true, test:'../examples/sound_file.js'},
	{title:'Local with File URL', hasChild:true, test:'../examples/sound_file_url.js'},
	{title:'Remote URL', hasChild:true, test:'../examples/sound_remote_url.js'}
];

if (Titanium.Platform.name == 'iPhone OS')
{
	data.push({title:'Remote Streaming', hasChild:true, test:'../examples/sound_remote.js'});
	data.push({title:'Record', hasChild:true, test:'../examples/sound_record.js'});
}

// create table view
var tableview = Titanium.UI.createTableView({
	data:data
});

// create table view event listener
tableview.addEventListener('click', function(e)
{
	if (e.rowData.test)
	{
		var win = Titanium.UI.createWindow({
			url:e.rowData.test,
			title:e.rowData.title
		});
		Titanium.UI.currentTab.open(win,{animated:true});
	}
});

// add table view to the window
Titanium.UI.currentWindow.add(tableview);
<commit_msg>KitchenSink: enable remote audio stream test for Android thx to new media player<commit_after>// create table view data object
var data = [
	{title:'Local', hasChild:true, test:'../examples/sound_local.js'},
	{title:'Local with File', hasChild:true, test:'../examples/sound_file.js'},
	{title:'Local with File URL', hasChild:true, test:'../examples/sound_file_url.js'},
	{title:'Remote URL', hasChild:true, test:'../examples/sound_remote_url.js'},
	{title:'Remote Streaming', hasChild:true, test:'../examples/sound_remote.js'}
];

if (Titanium.Platform.name == 'iPhone OS')
{
	data.push({title:'Record', hasChild:true, test:'../examples/sound_record.js'});
}

// create table view
var tableview = Titanium.UI.createTableView({
	data:data
});

// create table view event listener
tableview.addEventListener('click', function(e)
{
	if (e.rowData.test)
	{
		var win = Titanium.UI.createWindow({
			url:e.rowData.test,
			title:e.rowData.title
		});
		Titanium.UI.currentTab.open(win,{animated:true});
	}
});

// add table view to the window
Titanium.UI.currentWindow.add(tableview);
<|endoftext|>


<commit_before>// var ConvertLib = artifacts.require("./ConvertLib.sol");
// var MetaCoin = artifacts.require("./MetaCoin.sol");
var ERC20Interface = artifacts.require("./ERC20Interface.sol");
var FixedSupplyToken = artifacts.require("./FixedSupplyToken.sol");

module.exports = function(deployer) {
  // deployer.deploy(ConvertLib);
  // deployer.link(ConvertLib, MetaCoin);
  // deployer.deploy(MetaCoin);
  deployer.deploy(ERC20Interface);
  deployer.deploy(FixedSupplyToken);
};
<commit_msg>ERC20 token fix<commit_after>// var ConvertLib = artifacts.require("./ConvertLib.sol");
// var MetaCoin = artifacts.require("./MetaCoin.sol");
var ERC20Interface = artifacts.require("./ERC20Interface.sol");
var FixedSupplyToken = artifacts.require("./FixedSupplyToken.sol");

module.exports = function(deployer) {
  // deployer.deploy(ConvertLib);
  // deployer.link(ConvertLib, MetaCoin);
  // deployer.deploy(MetaCoin);
  deployer.deploy(FixedSupplyToken);
};
<|endoftext|>


<commit_before>import panic from './panic';

let match=function(value,patterns){
	let rusted=value.__rusted&&'__data' in value,
		non_exhaustive_pattern='non-exhaustive patterns: `_` not covered',
		name=rusted?value.__name:value,
		data=rusted?value.__data:value;

	if((!rusted)&&!('_' in patterns)){
		panic(non_exhaustive_pattern);
	}

	let buf=(name in patterns)
			? patterns[name]
		: ('_' in patterns)
			? patterns._
			: panic(non_exhaustive_pattern);

	return typeof buf==='function'?buf(data):buf;
};

export default match;
<commit_msg>Refactor<commit_after>import panic from './panic';

const non_exhaustive_pattern='non-exhaustive patterns: `_` not covered';

let select_arm=function(value,pattern){
	return (value in pattern)
			? pattern[value]
		: ('_' in pattern)
			? pattern._
			: panic(non_exhaustive_pattern) ;
};

let match=function(value,patterns){
	let rusted=value.__rusted&&'__data' in value,
		name=rusted?value.__name:value,
		data=rusted?value.__data:value;

	if((!rusted)&&!('_' in patterns)){
		panic(non_exhaustive_pattern);
	}

	let buf=select_arm(name,patterns);

	return typeof buf==='function'
		? buf(data)
		: buf;
};

export default match;
<|endoftext|>