<commit_before>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */

/**
 * @class
 *
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Control/MouseDefaults.js
 */
OpenLayers.Control.MouseToolbar = OpenLayers.Class.create();
OpenLayers.Control.MouseToolbar.X = 6;
OpenLayers.Control.MouseToolbar.Y = 300;
OpenLayers.Control.MouseToolbar.prototype =
  OpenLayers.Class.inherit( OpenLayers.Control,
                            OpenLayers.Control.MouseDefaults, {

    mode: null,

    buttons: null,

    direction: "vertical",

    /** @type String */
    buttonClicked: null,

    initialize: function(position, direction) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.position = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,
                                             OpenLayers.Control.MouseToolbar.Y);
        if (position) {
            this.position = position;
        }
        if (direction) {
            this.direction = direction;
        }
        this.measureDivs = [];
    },

    draw: function() {
        OpenLayers.Control.prototype.draw.apply(this, arguments);
        OpenLayers.Control.MouseDefaults.prototype.draw.apply(this, arguments);
        this.buttons = new Object();
        var sz = new OpenLayers.Size(28,28);
        var centered = this.position;
        this._addButton("zoombox", "drag-rectangle-off.png", "drag-rectangle-on.png", centered, sz, "Shift->Drag to zoom to area");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this._addButton("pan", "panning-hand-off.png", "panning-hand-on.png", centered, sz, "Drag the map to pan.");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this.switchModeTo("pan");
        return this.div;

    },

    _addButton:function(id, img, activeImg, xy, sz, title) {
        var imgLocation = OpenLayers.Util.getImagesLocation() + img;
        var activeImgLocation = OpenLayers.Util.getImagesLocation() + activeImg;
        // var btn = new ol.AlphaImage("_"+id, imgLocation, xy, sz);
        var btn = OpenLayers.Util.createAlphaImageDiv(
                                    "OpenLayers_Control_MouseToolbar_" + id,
                                    xy, sz, imgLocation, "absolute");

        //we want to add the outer div
        this.div.appendChild(btn);
        btn.imgLocation = imgLocation;
        btn.activeImgLocation = activeImgLocation;

        btn.events = new OpenLayers.Events(this, btn, null, true);
        btn.events.register("mousedown", this, this.buttonDown);
        btn.events.register("mouseup", this, this.buttonUp);
        btn.events.register("dblclick", this, OpenLayers.Event.stop);
        btn.action = id;
        btn.title = title;
        btn.alt = title;
        btn.map = this.map;

        //we want to remember/reference the outer div
        this.buttons[id] = btn;
        return btn;
    },

    /**
     * @param {Event} evt
     */
    buttonDown: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.buttonClicked = evt.element.action;
        OpenLayers.Event.stop(evt);
    },

    /**
     * @param {Event} evt
     */
    buttonUp: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        if (this.buttonClicked != null) {
            if (this.buttonClicked == evt.element.action) {
                this.switchModeTo(evt.element.action);
            }
            OpenLayers.Event.stop(evt);
            this.buttonClicked = null;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultDblClick: function (evt) {
        this.switchModeTo("pan");
        this.performedDrag = false;
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
        OpenLayers.Event.stop(evt);
        return false;
    },

    /**
    * @param {Event} evt
    */
    defaultMouseDown: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.mouseDragStart = evt.xy.clone();
        this.performedDrag = false;
        this.startViaKeyboard = false;
        if (evt.shiftKey && this.mode !="zoombox") {
            this.switchModeTo("zoombox");
            this.startViaKeyboard = true;
        } else if (evt.altKey && this.mode !="measure") {
            this.switchModeTo("measure");
        } else if (!this.mode) {
            this.switchModeTo("pan");
        }

        switch (this.mode) {
            case "zoombox":
                this.map.div.style.cursor = "crosshair";
                this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
                                                         this.mouseDragStart,
                                                         null,
                                                         null,
                                                         "absolute",
                                                         "2px solid red");
                this.zoomBox.style.backgroundColor = "white";
                this.zoomBox.style.filter = "alpha(opacity=50)"; // IE
                this.zoomBox.style.opacity = "0.50";
                this.zoomBox.style.fontSize = "1px";
                this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.viewPortDiv.appendChild(this.zoomBox);
                this.performedDrag = true;
                break;
            case "measure":
                var distance = "";
                if (this.measureStart) {
                    measureEnd = this.map.getLonLatFromViewPortPx(this.mouseDragStart);
                    distance = OpenLayers.Util.distVincenty(this.measureStart, measureEnd);
                    distance = Math.round(distance * 100) / 100;
                    distance = distance + "km";
                    this.measureStartBox = this.measureBox;
                }
                this.measureStart = this.map.getLonLatFromViewPortPx(this.mouseDragStart);;
                this.measureBox = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           -2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");
                this.measureBox.style.width="4px";
                this.measureBox.style.height="4px";
                this.measureBox.style.fontSize = "1px";
                this.measureBox.style.backgroundColor="red";
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                if (distance) {
                    this.measureBoxDistance = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");

                    this.measureBoxDistance.innerHTML = distance;
                    this.measureBoxDistance.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                    this.map.layerContainerDiv.appendChild(this.measureBoxDistance);
                    this.measureDivs.push(this.measureBoxDistance);
                }
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                this.measureDivs.push(this.measureBox);
                break;
            default:
                this.map.div.style.cursor = "move";
                break;
        }
        document.onselectstart = function() { return false; }
        OpenLayers.Event.stop(evt);
    },

    switchModeTo: function(mode) {
        if (mode != this.mode) {

            if (this.mode && this.buttons[this.mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[this.mode], null, null, null, this.buttons[this.mode].imgLocation);
            }
            if (this.mode == "measure" && mode != "measure") {
                for(var i = 0; i < this.measureDivs.length; i++) {
                    if (this.measureDivs[i]) {
                        this.map.layerContainerDiv.removeChild(this.measureDivs[i]);
                    }
                }
                this.measureDivs = [];
                this.measureStart = null;
            }
            this.mode = mode;
            if (this.buttons[mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[mode], null, null, null, this.buttons[mode].activeImgLocation);
            }
            switch (this.mode) {
                case "zoombox":
                    this.map.div.style.cursor = "crosshair";
                    break;
                default:
                    this.map.div.style.cursor = "default";
                    break;
            }

        }
    },

    leaveMode: function() {
        this.switchModeTo("pan");
    },

    /**
    * @param {Event} evt
    */
    defaultMouseMove: function (evt) {
        if (this.mouseDragStart != null) {
            switch (this.mode) {
                case "zoombox":
                    var deltaX = Math.abs(this.mouseDragStart.x - evt.xy.x);
                    var deltaY = Math.abs(this.mouseDragStart.y - evt.xy.y);
                    this.zoomBox.style.width = Math.max(1, deltaX) + "px";
                    this.zoomBox.style.height = Math.max(1, deltaY) + "px";
                    if (evt.xy.x < this.mouseDragStart.x) {
                        this.zoomBox.style.left = evt.xy.x+"px";
                    }
                    if (evt.xy.y < this.mouseDragStart.y) {
                        this.zoomBox.style.top = evt.xy.y+"px";
                    }
                    break;
                default:
                    var deltaX = this.mouseDragStart.x - evt.xy.x;
                    var deltaY = this.mouseDragStart.y - evt.xy.y;
                    var size = this.map.getSize();
                    var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
                                                     size.h / 2 + deltaY);
                    var newCenter = this.map.getLonLatFromViewPortPx( newXY );
                    this.map.setCenter(newCenter, null, true);
                    this.mouseDragStart = evt.xy.clone();
            }
            this.performedDrag = true;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultMouseUp: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        switch (this.mode) {
            case "zoombox":
                this.zoomBoxEnd(evt);
                if (this.startViaKeyboard) this.leaveMode();
                break;
            case "pan":
                if (this.performedDrag) {
                    this.map.setCenter(this.map.center);
                }
        }
        document.onselectstart = null;
        this.mouseDragStart = null;
        this.map.div.style.cursor = "default";
    },

    /**
    * @param {Event} evt
    */
    defaultMouseOut: function (evt) {
        if (this.mouseDragStart != null
            && OpenLayers.Util.mouseLeft(evt, this.map.div)) {
            if (this.zoomBox) {
                this.removeZoomBox();
                if (this.startViaKeyboard) this.leaveMode();
            }
            this.mouseDragStart = null;
            this.map.div.style.cursor = "default";
        }
    },

    defaultClick: function (evt) {
        if (this.performedDrag)  {
            this.performedDrag = false;
            return false;
        }
    }
});

<commit_msg>Committing erik's patch on #362 .<commit_after>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */

/**
 * @class
 *
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Control/MouseDefaults.js
 */
OpenLayers.Control.MouseToolbar = OpenLayers.Class.create();
OpenLayers.Control.MouseToolbar.X = 6;
OpenLayers.Control.MouseToolbar.Y = 300;
OpenLayers.Control.MouseToolbar.prototype =
  OpenLayers.Class.inherit( OpenLayers.Control.MouseDefaults, {

    mode: null,

    buttons: null,

    direction: "vertical",

    /** @type String */
    buttonClicked: null,

    initialize: function(position, direction) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.position = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,
                                             OpenLayers.Control.MouseToolbar.Y);
        if (position) {
            this.position = position;
        }
        if (direction) {
            this.direction = direction;
        }
        this.measureDivs = [];
    },

    draw: function() {
        OpenLayers.Control.prototype.draw.apply(this, arguments);
        OpenLayers.Control.MouseDefaults.prototype.draw.apply(this, arguments);
        this.buttons = new Object();
        var sz = new OpenLayers.Size(28,28);
        var centered = this.position;
        this._addButton("zoombox", "drag-rectangle-off.png", "drag-rectangle-on.png", centered, sz, "Shift->Drag to zoom to area");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this._addButton("pan", "panning-hand-off.png", "panning-hand-on.png", centered, sz, "Drag the map to pan.");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this.switchModeTo("pan");
        return this.div;

    },

    _addButton:function(id, img, activeImg, xy, sz, title) {
        var imgLocation = OpenLayers.Util.getImagesLocation() + img;
        var activeImgLocation = OpenLayers.Util.getImagesLocation() + activeImg;
        // var btn = new ol.AlphaImage("_"+id, imgLocation, xy, sz);
        var btn = OpenLayers.Util.createAlphaImageDiv(
                                    "OpenLayers_Control_MouseToolbar_" + id,
                                    xy, sz, imgLocation, "absolute");

        //we want to add the outer div
        this.div.appendChild(btn);
        btn.imgLocation = imgLocation;
        btn.activeImgLocation = activeImgLocation;

        btn.events = new OpenLayers.Events(this, btn, null, true);
        btn.events.register("mousedown", this, this.buttonDown);
        btn.events.register("mouseup", this, this.buttonUp);
        btn.events.register("dblclick", this, OpenLayers.Event.stop);
        btn.action = id;
        btn.title = title;
        btn.alt = title;
        btn.map = this.map;

        //we want to remember/reference the outer div
        this.buttons[id] = btn;
        return btn;
    },

    /**
     * @param {Event} evt
     */
    buttonDown: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.buttonClicked = evt.element.action;
        OpenLayers.Event.stop(evt);
    },

    /**
     * @param {Event} evt
     */
    buttonUp: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        if (this.buttonClicked != null) {
            if (this.buttonClicked == evt.element.action) {
                this.switchModeTo(evt.element.action);
            }
            OpenLayers.Event.stop(evt);
            this.buttonClicked = null;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultDblClick: function (evt) {
        this.switchModeTo("pan");
        this.performedDrag = false;
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
        OpenLayers.Event.stop(evt);
        return false;
    },

    /**
    * @param {Event} evt
    */
    defaultMouseDown: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.mouseDragStart = evt.xy.clone();
        this.performedDrag = false;
        this.startViaKeyboard = false;
        if (evt.shiftKey && this.mode !="zoombox") {
            this.switchModeTo("zoombox");
            this.startViaKeyboard = true;
        } else if (evt.altKey && this.mode !="measure") {
            this.switchModeTo("measure");
        } else if (!this.mode) {
            this.switchModeTo("pan");
        }

        switch (this.mode) {
            case "zoombox":
                this.map.div.style.cursor = "crosshair";
                this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
                                                         this.mouseDragStart,
                                                         null,
                                                         null,
                                                         "absolute",
                                                         "2px solid red");
                this.zoomBox.style.backgroundColor = "white";
                this.zoomBox.style.filter = "alpha(opacity=50)"; // IE
                this.zoomBox.style.opacity = "0.50";
                this.zoomBox.style.fontSize = "1px";
                this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.viewPortDiv.appendChild(this.zoomBox);
                this.performedDrag = true;
                break;
            case "measure":
                var distance = "";
                if (this.measureStart) {
                    measureEnd = this.map.getLonLatFromViewPortPx(this.mouseDragStart);
                    distance = OpenLayers.Util.distVincenty(this.measureStart, measureEnd);
                    distance = Math.round(distance * 100) / 100;
                    distance = distance + "km";
                    this.measureStartBox = this.measureBox;
                }
                this.measureStart = this.map.getLonLatFromViewPortPx(this.mouseDragStart);;
                this.measureBox = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           -2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");
                this.measureBox.style.width="4px";
                this.measureBox.style.height="4px";
                this.measureBox.style.fontSize = "1px";
                this.measureBox.style.backgroundColor="red";
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                if (distance) {
                    this.measureBoxDistance = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");

                    this.measureBoxDistance.innerHTML = distance;
                    this.measureBoxDistance.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                    this.map.layerContainerDiv.appendChild(this.measureBoxDistance);
                    this.measureDivs.push(this.measureBoxDistance);
                }
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                this.measureDivs.push(this.measureBox);
                break;
            default:
                this.map.div.style.cursor = "move";
                break;
        }
        document.onselectstart = function() { return false; }
        OpenLayers.Event.stop(evt);
    },

    switchModeTo: function(mode) {
        if (mode != this.mode) {

            if (this.mode && this.buttons[this.mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[this.mode], null, null, null, this.buttons[this.mode].imgLocation);
            }
            if (this.mode == "measure" && mode != "measure") {
                for(var i = 0; i < this.measureDivs.length; i++) {
                    if (this.measureDivs[i]) {
                        this.map.layerContainerDiv.removeChild(this.measureDivs[i]);
                    }
                }
                this.measureDivs = [];
                this.measureStart = null;
            }
            this.mode = mode;
            if (this.buttons[mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[mode], null, null, null, this.buttons[mode].activeImgLocation);
            }
            switch (this.mode) {
                case "zoombox":
                    this.map.div.style.cursor = "crosshair";
                    break;
                default:
                    this.map.div.style.cursor = "default";
                    break;
            }

        }
    },

    leaveMode: function() {
        this.switchModeTo("pan");
    },

    /**
    * @param {Event} evt
    */
    defaultMouseMove: function (evt) {
        if (this.mouseDragStart != null) {
            switch (this.mode) {
                case "zoombox":
                    var deltaX = Math.abs(this.mouseDragStart.x - evt.xy.x);
                    var deltaY = Math.abs(this.mouseDragStart.y - evt.xy.y);
                    this.zoomBox.style.width = Math.max(1, deltaX) + "px";
                    this.zoomBox.style.height = Math.max(1, deltaY) + "px";
                    if (evt.xy.x < this.mouseDragStart.x) {
                        this.zoomBox.style.left = evt.xy.x+"px";
                    }
                    if (evt.xy.y < this.mouseDragStart.y) {
                        this.zoomBox.style.top = evt.xy.y+"px";
                    }
                    break;
                default:
                    var deltaX = this.mouseDragStart.x - evt.xy.x;
                    var deltaY = this.mouseDragStart.y - evt.xy.y;
                    var size = this.map.getSize();
                    var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
                                                     size.h / 2 + deltaY);
                    var newCenter = this.map.getLonLatFromViewPortPx( newXY );
                    this.map.setCenter(newCenter, null, true);
                    this.mouseDragStart = evt.xy.clone();
            }
            this.performedDrag = true;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultMouseUp: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        switch (this.mode) {
            case "zoombox":
                this.zoomBoxEnd(evt);
                if (this.startViaKeyboard) this.leaveMode();
                break;
            case "pan":
                if (this.performedDrag) {
                    this.map.setCenter(this.map.center);
                }
        }
        document.onselectstart = null;
        this.mouseDragStart = null;
        this.map.div.style.cursor = "default";
    },

    /**
    * @param {Event} evt
    */
    defaultMouseOut: function (evt) {
        if (this.mouseDragStart != null
            && OpenLayers.Util.mouseLeft(evt, this.map.div)) {
            if (this.zoomBox) {
                this.removeZoomBox();
                if (this.startViaKeyboard) this.leaveMode();
            }
            this.mouseDragStart = null;
            this.map.div.style.cursor = "default";
        }
    },

    defaultClick: function (evt) {
        if (this.performedDrag)  {
            this.performedDrag = false;
            return false;
        }
    }
});

<|endoftext|>


<commit_before>/*
 * ${copyright}
 */

// Provides TablePersoProvider
sap.ui.define(['sap/ui/base/ManagedObject', "sap/base/Log"],
	function(ManagedObject, Log) {
	"use strict";

	/**
	 * This is an abstract TablePersoProvider, describing the interface for a real
	 * TablePersoProvider.
	 *
	 * @public
	 *
	 * @class Table Personalization Provider
	 * @extends sap.ui.base.ManagedObject
	 * @abstract
	 * @author SAP
	 * @version ${version}
	 * @alias sap.m.TablePersoProvider
	 */
	var TablePersoProvider = ManagedObject.extend("sap.m.TablePersoProvider", /** @lends sap.m.TablePersoProvider */

	{
		constructor: function(sId, mSettings) {

			ManagedObject.apply(this, arguments);

		},

		metadata: {
			"abstract": true,
			library: "sap.m"
		}

	});

	/**
	 * Initializes the TablePersoProvider instance after creation.
	 *
	 * @protected
	 */
	TablePersoProvider.prototype.init = function() {

		Log.warning("This is the abstract base class for a TablePersoProvider. Do not create instances of this class, but use a concrete sub class instead.");
		Log.debug("TablePersoProvider init");

	};

	/**
	 * Retrieves the personalization bundle.

	 * This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	 * @public
	 */
	TablePersoProvider.prototype.getPersData = function() {

		Log.debug("TablePersoProvider getPersData");

	};

	/**
	 * Stores the personalization bundle, overwriting any previous bundle completely.

	 * This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	 * @param {object} oBundle
	 * @public
	 */
	TablePersoProvider.prototype.setPersData = function(oBundle) {

		Log.debug("TablePersoProvider setPersData");

	};

	/**
	 * Removes the personalization bundle.

	 * This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	 * @public
	 */
	TablePersoProvider.prototype.delPersData = function() {

		Log.debug("TablePersoProvider delPersData");

	};

	/**
	 * Callback function which can be used to determine the title of a given column
	 * within the TablePersoDialog. As a default, the column header controls are
	 * asked for their 'text' or 'title' property. This works in most cases, for example
	 * if the header control is an sap.m.Label (has 'text' property) or an sap.m.ObjectListItem
	 * (has 'title' property).
	 *
	 * If the header control used in a column has neither 'text' nor 'title' property, or if you would like to
	 * display a modified column name for a certain column, this callback function can be used.
	 *
	 * If the callback delivers null for a column (which is the default implementation), the default
	 * texts described above are displayed for that column in the TablePersoDialog.
	 *
	 * In case neither the callback delivers null and neither 'text' nor ' title' property are at hand,
	 * the TablePersoDialog will display the column id and a warning message is logged.
	 *
	 * @param {sap.m.Column} oColumn column whose caption shall be determined
	 * @public
	 */
	TablePersoProvider.prototype.getCaption = function(oColumn) {
		return null;
	};

	/**
	 * Callback function which can be used to determine the group of a given column
	 * within the TablePersoDialog. As a default, the columns are not assigned to a group.
	 *
	 * This information is used to group the columns within the TablePersoDialog if the TablePersoController's
	 * 'group' flag is set, otherwise, the groups are ignored.
	 *
	 * @param {sap.m.Column} oColumn column whose group shall be determined
	 * @public
	 */
	TablePersoProvider.prototype.getGroup = function(oColumn) {
		return null;
	};

	/**
	* Resets user’s personalization for a given table so that ‘getPersData’ will
	* deliver its initial state. If no table is specified, all personalizations
	* of the currently logged on user are reset.

	*
	* This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	* @public
	*/
	TablePersoProvider.prototype.resetPersData = function() {

		Log.debug("TablePersoProvider resetPersData");

	};

	/**
	 * Retrieves the desired reset state.
	 * This getter is used by the TablePersoController if the resetAllMode is ServiceReset.

	 *
	 * This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	 * @public
	 * @since 1.88
	 */
	TablePersoProvider.prototype.getResetPersData = function() {

		Log.debug("TablePersoProvider getPersData");

	};

	return TablePersoProvider;

});<commit_msg>[INTERNAL]TablePersoProvider: enhance 'getPersoData' jsdoc<commit_after>/*
 * ${copyright}
 */

// Provides TablePersoProvider
sap.ui.define(['sap/ui/base/ManagedObject', "sap/base/Log"],
	function(ManagedObject, Log) {
	"use strict";

	/**
	 * This is an abstract TablePersoProvider, describing the interface for a real
	 * TablePersoProvider.
	 *
	 * @public
	 *
	 * @class Table Personalization Provider
	 * @extends sap.ui.base.ManagedObject
	 * @abstract
	 * @author SAP
	 * @version ${version}
	 * @alias sap.m.TablePersoProvider
	 */
	var TablePersoProvider = ManagedObject.extend("sap.m.TablePersoProvider", /** @lends sap.m.TablePersoProvider */

	{
		constructor: function(sId, mSettings) {

			ManagedObject.apply(this, arguments);

		},

		metadata: {
			"abstract": true,
			library: "sap.m"
		}

	});

	/**
	 * Initializes the TablePersoProvider instance after creation.
	 *
	 * @protected
	 */
	TablePersoProvider.prototype.init = function() {

		Log.warning("This is the abstract base class for a TablePersoProvider. Do not create instances of this class, but use a concrete sub class instead.");
		Log.debug("TablePersoProvider init");

	};

	/**
	 * Retrieves the personalization bundle.

	 * This must return a {@link http://api.jquery.com/promise/ jQuery Promise},
	 * which resolves in the desired table state.
	 *
	 * @example [
	 *		{
	 *			id: "demoApp-productsTable-productCol",
	 *			order: 2,
	 *			text: "Product",
	 *			visible: true
	 *		},
	 *		{
	 *			id: "demoApp-productsTable-supplierCol",
	 *			order: 1,
	 *			text: "Supplier",
	 *			visible: true
	 *		},
	 *		{
	 *			id: "demoApp-productsTable-dimensionsCol",
	 *			order: 0,
	 *			text: "Dimensions",
	 *			visible: false
	 *		}
	 *	]
	 *
	 * @public
	 */
	TablePersoProvider.prototype.getPersData = function() {

		Log.debug("TablePersoProvider getPersData");

	};

	/**
	 * Stores the personalization bundle, overwriting any previous bundle completely.

	 * This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	 * @param {object} oBundle
	 * @public
	 */
	TablePersoProvider.prototype.setPersData = function(oBundle) {

		Log.debug("TablePersoProvider setPersData");

	};

	/**
	 * Removes the personalization bundle.

	 * This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	 * @public
	 */
	TablePersoProvider.prototype.delPersData = function() {

		Log.debug("TablePersoProvider delPersData");

	};

	/**
	 * Callback function which can be used to determine the title of a given column
	 * within the TablePersoDialog. As a default, the column header controls are
	 * asked for their 'text' or 'title' property. This works in most cases, for example
	 * if the header control is an sap.m.Label (has 'text' property) or an sap.m.ObjectListItem
	 * (has 'title' property).
	 *
	 * If the header control used in a column has neither 'text' nor 'title' property, or if you would like to
	 * display a modified column name for a certain column, this callback function can be used.
	 *
	 * If the callback delivers null for a column (which is the default implementation), the default
	 * texts described above are displayed for that column in the TablePersoDialog.
	 *
	 * In case neither the callback delivers null and neither 'text' nor ' title' property are at hand,
	 * the TablePersoDialog will display the column id and a warning message is logged.
	 *
	 * @param {sap.m.Column} oColumn column whose caption shall be determined
	 * @public
	 */
	TablePersoProvider.prototype.getCaption = function(oColumn) {
		return null;
	};

	/**
	 * Callback function which can be used to determine the group of a given column
	 * within the TablePersoDialog. As a default, the columns are not assigned to a group.
	 *
	 * This information is used to group the columns within the TablePersoDialog if the TablePersoController's
	 * 'group' flag is set, otherwise, the groups are ignored.
	 *
	 * @param {sap.m.Column} oColumn column whose group shall be determined
	 * @public
	 */
	TablePersoProvider.prototype.getGroup = function(oColumn) {
		return null;
	};

	/**
	* Resets user’s personalization for a given table so that ‘getPersData’ will
	* deliver its initial state. If no table is specified, all personalizations
	* of the currently logged on user are reset.

	*
	* This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	* @public
	*/
	TablePersoProvider.prototype.resetPersData = function() {

		Log.debug("TablePersoProvider resetPersData");

	};

	/**
	 * Retrieves the desired reset state.
	 * This getter is used by the TablePersoController if the resetAllMode is ServiceReset.

	 *
	 * This must return a {@link http://api.jquery.com/promise/ jQuery promise}.
	 * @public
	 * @since 1.88
	 */
	TablePersoProvider.prototype.getResetPersData = function() {

		Log.debug("TablePersoProvider getPersData");

	};

	return TablePersoProvider;

});<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides control sap.t.SideNavigation.
sap.ui.define([
    'jquery.sap.global',
    './library',
    'sap/ui/core/Control',
    'sap/ui/core/ResizeHandler',
    'sap/ui/core/Icon',
    'sap/ui/core/delegate/ScrollEnablement',
    "./SideNavigationRenderer"
],
	function(
	    jQuery,
		library,
		Control,
		ResizeHandler,
		Icon,
		ScrollEnablement,
		SideNavigationRenderer
	) {
		'use strict';

		/**
		 * Constructor for a new SideNavigation.
		 *
		 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
		 * @param {object} [mSettings] Initial settings for the new control
		 *
		 * @class
		 * The SideNavigation control is a container, which consists of flexible and fixed parts on top of each other.
		 *
Responsive Behavior

		 *

		 *
The flexible part adapts its size to the fixed one.

		 *
The flexible part has a scrollbar when the content is larger than the available space.

		 *

		 *Note: In order for the SideNavigation to stretch properly, its parent layout control should only be the sap.tnt.ToolPage.
		 * @extends sap.ui.core.Control
		 *
		 * @author SAP SE
		 * @version ${version}
		 *
		 * @constructor
		 * @public
		 * @since 1.34
		 * @alias sap.tnt.SideNavigation
		 * @see {@link fiori:https://experience.sap.com/fiori-design-web/side-navigation/ Side Navigation}
		 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
		 */
		var SideNavigation = Control.extend('sap.tnt.SideNavigation', /** @lends sap.t.SideNavigation.prototype */ {
			metadata: {
				library: 'sap.tnt',
				properties: {
					/**
					 * Specifies if the control is expanded.
					 */
					expanded: {type: 'boolean', group: 'Misc', defaultValue: true}
				},
				defaultAggregation: "item",
				aggregations: {
					/**
					 * Defines the content inside the flexible part.
					 */
					item: {type: 'sap.tnt.NavigationList', multiple: false, bindable: "bindable"},
					/**
					 * Defines the content inside the fixed part.
					 */
					fixedItem: {type: 'sap.tnt.NavigationList', multiple: false},
					/**
					 * Defines the content inside the footer.
					 */
					footer: {type: 'sap.tnt.NavigationList', multiple: false},
					/**
					 * The top arrow, used for scrolling throw items when SideNavigation is collapsed.
					 */
					_topArrowControl: {type: "sap.ui.core.Icon", multiple: false, visibility: "hidden"},
					/**
					 * The bottom arrow, used for scrolling throw items when SideNavigation is collapsed.
					 */
					_bottomArrowControl: {type: "sap.ui.core.Icon", multiple: false, visibility: "hidden"}
				},
				associations : {
					/**
					 * The selected NavigationListItem.
					 *
					 * @since 1.52.0
					 */
					selectedItem: {type: "sap.tnt.NavigationListItem", multiple: false}
				},
				events: {
					/**
					 * Fired when an item is selected.
					 */
					itemSelect: {
						parameters: {
							/**
							 * The selected item.
							 */
							item: {type: 'sap.ui.core.Item'}
						}
					}
				}
			}
		});

		SideNavigation.prototype.init = function () {

			this._scroller = new ScrollEnablement(this, this.getId() + "-Flexible-Content", {
				horizontal: false,
				vertical: true
			});

			// Define group for F6 handling
			this.data('sap-ui-fastnavgroup', 'true', true);
		};

		SideNavigation.prototype.setAggregation = function (aggregationName, object, suppressInvalidate) {
			if (object && object.attachItemSelect) {
				object.attachItemSelect(this._itemSelectionHandler.bind(this));
			}

			return sap.ui.base.ManagedObject.prototype.setAggregation.apply(this, arguments);
		};

		/**
		 * Sets if the control is in expanded or collapsed mode.
		 *
		 * @public
		 * @param {boolean} isExpanded Indication if the SideNavigation is expanded.
		 * @returns {sap.tnt.SideNavigation} this SideNavigation reference for chaining.
		 */
		SideNavigation.prototype.setExpanded = function (isExpanded) {

			if (this.getExpanded() === isExpanded) {
				return this;
			}

			this.setProperty('expanded', isExpanded, true);

			if (!this.getDomRef()) {
				return this;
			}

			var that = this,
				$this = this.$(),
				width;

			if (that._hasActiveAnimation) {
				that._finishAnimation(!isExpanded);
				$this.stop();
			}

			if (isExpanded) {
				that.$().toggleClass('sapTntSideNavigationNotExpanded', !isExpanded);

				if (that.getAggregation('item')) {
					that.getAggregation('item').setExpanded(isExpanded);
				}

				if (that.getAggregation('fixedItem')) {
					that.getAggregation('fixedItem').setExpanded(isExpanded);
				}
			}

			that._hasActiveAnimation = true;
			width = isExpanded ? '15rem' : '3rem';

			$this.animate({
					width: width
				},
				{
					duration: 300,
					complete: function () {
						var isExpanded = that.getExpanded();
						that._finishAnimation(isExpanded);
					}
				});

			return this;
		};

		/**
		 * @private
		 */
		SideNavigation.prototype._finishAnimation = function (isExpanded) {
			if (!this._hasActiveAnimation || !this.getDomRef()) {
				return;
			}

			this.$().toggleClass('sapTntSideNavigationNotExpandedWidth', !isExpanded);

			if (!isExpanded) {
				this.$().toggleClass('sapTntSideNavigationNotExpanded', !isExpanded);

				if (this.getAggregation('item')) {
					this.getAggregation('item').setExpanded(isExpanded);
				}

				if (this.getAggregation('fixedItem')) {
					this.getAggregation('fixedItem').setExpanded(isExpanded);
				}
			}

			this.$().css('width', '');
			this._hasActiveAnimation = false;

			this._toggleArrows();
		};

		/**
		 * @private
		 */
		SideNavigation.prototype.onBeforeRendering = function () {
			var selectedItem = this.getSelectedItem();

			if (selectedItem) {
			    this.setSelectedItem(selectedItem, true);
			}

			this._deregisterControl();
		};

		/**
		 * @private
		 */
		SideNavigation.prototype.onAfterRendering = function () {
			this._ResizeHandler = ResizeHandler.register(this.getDomRef(), this._toggleArrows.bind(this));
			this._toggleArrows();
		};

		/**
		 * Sets the association for selectedItem
		 * @public
		 * @param {string|sap.tnt.NavigationListItem} selectedItem The control to be set as selected
		 * @param {boolean} suppressInvalidate If true, the managed object's invalidate method is not called
		 * @return {sap.tnt.SideNavigation|null} The selectedItem association
		 */
		SideNavigation.prototype.setSelectedItem = function (selectedItem, suppressInvalidate) {
			var navigationList = this.getAggregation('item');
			var fixedNavigationList = this.getAggregation('fixedItem');
			var listItemToSelect;

			if (!selectedItem) {
				if (navigationList.setSelectedItem) {
					navigationList.setSelectedItem(null, true);
				}
				if (fixedNavigationList.setSelectedItem) {
					fixedNavigationList.setSelectedItem(null, true);
				}
			}

			if (typeof selectedItem === 'string') {
				listItemToSelect = sap.ui.getCore().byId(selectedItem);
			} else {
				listItemToSelect = selectedItem;
			}

			var selectedInFlexibleList = listItemToSelect && listItemToSelect.getNavigationList && listItemToSelect.getNavigationList() === navigationList;
			var selectedInFixedList = listItemToSelect && listItemToSelect.getNavigationList && listItemToSelect.getNavigationList() === fixedNavigationList;

			if (selectedInFlexibleList) {
				navigationList.setSelectedItem(listItemToSelect, suppressInvalidate);
				if (fixedNavigationList) {
					fixedNavigationList.setSelectedItem(null, true);
				}
			}

			if (selectedInFixedList) {
				fixedNavigationList.setSelectedItem(listItemToSelect, suppressInvalidate);
				navigationList.setSelectedItem(null, true);
			}

			return sap.ui.core.Control.prototype.setAssociation.call(this, 'selectedItem', listItemToSelect, true);
		};

		/**
		 * @private
		 */
		SideNavigation.prototype.exit = function () {

			if (this._scroller) {
				this._scroller.destroy();
				this._scroller = null;
			}

			this._deregisterControl();
		};

		/**
		 *
		 * @param event
		 * @private
		 */
		SideNavigation.prototype._itemSelectionHandler = function (event) {
			var listId = event.getSource().getId();
			var itemAggregation = this.getAggregation('item');
			var fixedItemAggregation = this.getAggregation('fixedItem');
			var item = event.getParameter('item');

			if (itemAggregation && fixedItemAggregation && listId === itemAggregation.getId()) {
				fixedItemAggregation.setSelectedItem(null);
			}

			if (itemAggregation && fixedItemAggregation && listId === fixedItemAggregation.getId()) {
				itemAggregation.setSelectedItem(null);
			}

			sap.ui.core.Control.prototype.setAssociation.call(this, 'selectedItem', item, true);

			this.fireItemSelect({
				item: item
			});
		};

		/**
		 * @private
		 */
		SideNavigation.prototype._deregisterControl = function () {
			if (this._ResizeHandler) {
				ResizeHandler.deregister(this._ResizeHandler);
				this._ResizeHandler = null;
			}
		};

		/**
		 * Returns the sap.ui.core.Icon control used to display the group icon.
		 * @returns {sap.ui.core.Icon}
		 * @private
		 */
		SideNavigation.prototype._getTopArrowControl = function () {
			var iconControl = this.getAggregation('_topArrowControl');
			var that = this;

			if (!iconControl) {
				iconControl = new Icon({
					src: 'sap-icon://navigation-up-arrow',
					noTabStop: true,
					useIconTooltip: false,
					tooltip: '',
					press: this._arrowPress.bind(that)
				}).addStyleClass('sapTntSideNavigationScrollIcon sapTntSideNavigationScrollIconUp');
				this.setAggregation("_topArrowControl", iconControl, true);
			}

			return iconControl;
		};

		/**
		 * Returns the sap.ui.core.Icon control used to display the group icon.
		 * @returns {sap.ui.core.Icon}
		 * @private
		 */
		SideNavigation.prototype._getBottomArrowControl = function () {
			var iconControl = this.getAggregation('_bottomArrowControl');
			var that = this;

			if (!iconControl) {
				iconControl = new Icon({
					src: 'sap-icon://navigation-down-arrow',
					noTabStop: true,
					useIconTooltip: false,
					tooltip: '',
					press: this._arrowPress.bind(that)
				}).addStyleClass('sapTntSideNavigationScrollIcon sapTntSideNavigationScrollIconDown');

				this.setAggregation("_bottomArrowControl", iconControl, true);
			}

			return iconControl;
		};

		SideNavigation.prototype._toggleArrows = function () {
			var domRef = this.getDomRef();

			if (!domRef) {
				return;
			}

			var scrollContainerWrapper = this.$('Flexible')[0];
			var scrollContainerContent = this.$('Flexible-Content')[0];
			var isAsideExpanded = this.getExpanded();

			if (this._hasActiveAnimation) {
				domRef.querySelector('.sapTntSideNavigationScrollIconUp').style.display = 'none';
				domRef.querySelector('.sapTntSideNavigationScrollIconDown').style.display = 'none';
				return;
			}

			if ((scrollContainerContent.offsetHeight > scrollContainerWrapper.offsetHeight) && !isAsideExpanded) {
				domRef.querySelector('.sapTntSideNavigationScrollIconUp').style.display = 'block';
				domRef.querySelector('.sapTntSideNavigationScrollIconDown').style.display = 'block';

				domRef.querySelector('.sapTntSideNavigationScrollIconDown').classList.remove('sapTntSideNavigationScrollIconDisabled');
			} else {
				domRef.querySelector('.sapTntSideNavigationScrollIconUp').style.display = 'none';
				domRef.querySelector('.sapTntSideNavigationScrollIconDown').style.display = 'none';
			}
		};

		SideNavigation.prototype._arrowPress = function (event) {
			event.preventDefault();

			var source = document.getElementById(event.oSource.sId);
			var isDirectionForward = source.classList.contains('sapTntSideNavigationScrollIconDown') ? true : false;

			var $container = this.$('Flexible');

			var step = isDirectionForward ? 40 : -40;
			$container[0].scrollTop += step;
		};

		return SideNavigation;

	}, /* bExport= */ true
);
<commit_msg>[FIX] sap.tnt.SideNavigation: Expand/collapse animation visual glitches solved<commit_after>/*!
 * ${copyright}
 */

// Provides control sap.t.SideNavigation.
sap.ui.define([
    'jquery.sap.global',
    './library',
    'sap/ui/core/Control',
    'sap/ui/core/ResizeHandler',
    'sap/ui/core/Icon',
    'sap/ui/core/delegate/ScrollEnablement',
    "./SideNavigationRenderer"
],
	function(
	    jQuery,
		library,
		Control,
		ResizeHandler,
		Icon,
		ScrollEnablement,
		SideNavigationRenderer
	) {
		'use strict';

		/**
		 * Constructor for a new SideNavigation.
		 *
		 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
		 * @param {object} [mSettings] Initial settings for the new control
		 *
		 * @class
		 * The SideNavigation control is a container, which consists of flexible and fixed parts on top of each other.
		 *
Responsive Behavior

		 *

		 *
The flexible part adapts its size to the fixed one.

		 *
The flexible part has a scrollbar when the content is larger than the available space.

		 *

		 *Note: In order for the SideNavigation to stretch properly, its parent layout control should only be the sap.tnt.ToolPage.
		 * @extends sap.ui.core.Control
		 *
		 * @author SAP SE
		 * @version ${version}
		 *
		 * @constructor
		 * @public
		 * @since 1.34
		 * @alias sap.tnt.SideNavigation
		 * @see {@link fiori:https://experience.sap.com/fiori-design-web/side-navigation/ Side Navigation}
		 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
		 */
		var SideNavigation = Control.extend('sap.tnt.SideNavigation', /** @lends sap.t.SideNavigation.prototype */ {
			metadata: {
				library: 'sap.tnt',
				properties: {
					/**
					 * Specifies if the control is expanded.
					 */
					expanded: {type: 'boolean', group: 'Misc', defaultValue: true}
				},
				defaultAggregation: "item",
				aggregations: {
					/**
					 * Defines the content inside the flexible part.
					 */
					item: {type: 'sap.tnt.NavigationList', multiple: false, bindable: "bindable"},
					/**
					 * Defines the content inside the fixed part.
					 */
					fixedItem: {type: 'sap.tnt.NavigationList', multiple: false},
					/**
					 * Defines the content inside the footer.
					 */
					footer: {type: 'sap.tnt.NavigationList', multiple: false},
					/**
					 * The top arrow, used for scrolling throw items when SideNavigation is collapsed.
					 */
					_topArrowControl: {type: "sap.ui.core.Icon", multiple: false, visibility: "hidden"},
					/**
					 * The bottom arrow, used for scrolling throw items when SideNavigation is collapsed.
					 */
					_bottomArrowControl: {type: "sap.ui.core.Icon", multiple: false, visibility: "hidden"}
				},
				associations : {
					/**
					 * The selected NavigationListItem.
					 *
					 * @since 1.52.0
					 */
					selectedItem: {type: "sap.tnt.NavigationListItem", multiple: false}
				},
				events: {
					/**
					 * Fired when an item is selected.
					 */
					itemSelect: {
						parameters: {
							/**
							 * The selected item.
							 */
							item: {type: 'sap.ui.core.Item'}
						}
					}
				}
			}
		});

		SideNavigation.prototype.init = function () {

			this._scroller = new ScrollEnablement(this, this.getId() + "-Flexible-Content", {
				horizontal: false,
				vertical: true
			});

			// Define group for F6 handling
			this.data('sap-ui-fastnavgroup', 'true', true);
		};

		SideNavigation.prototype.setAggregation = function (aggregationName, object, suppressInvalidate) {
			if (object && object.attachItemSelect) {
				object.attachItemSelect(this._itemSelectionHandler.bind(this));
			}

			return sap.ui.base.ManagedObject.prototype.setAggregation.apply(this, arguments);
		};

		/**
		 * Sets if the control is in expanded or collapsed mode.
		 *
		 * @public
		 * @param {boolean} isExpanded Indication if the SideNavigation is expanded.
		 * @returns {sap.tnt.SideNavigation} this SideNavigation reference for chaining.
		 */
		SideNavigation.prototype.setExpanded = function (isExpanded) {

			if (this.getExpanded() === isExpanded) {
				return this;
			}

			this.setProperty('expanded', isExpanded, true);

			if (!this.getDomRef()) {
				return this;
			}

			var that = this,
				$this = this.$(),
				width;

			if (that._hasActiveAnimation) {
				that._finishAnimation(!isExpanded);
				$this.stop();
			}

			if (isExpanded) {
				that.$().toggleClass('sapTntSideNavigationNotExpanded', !isExpanded);

				if (that.getAggregation('item')) {
					that.getAggregation('item').setExpanded(isExpanded);
				}

				if (that.getAggregation('fixedItem')) {
					that.getAggregation('fixedItem').setExpanded(isExpanded);
				}
			} else {
				// hide scroller during collapsing animation
				this._scroller.setVertical(false);
			}

			that._hasActiveAnimation = true;
			width = isExpanded ? '15rem' : '3rem';

			$this.animate({
					width: width
				},
				{
					duration: 300,
					complete: function () {
						var isExpanded = that.getExpanded();
						that._finishAnimation(isExpanded);
					}
				});

			return this;
		};

		/**
		 * @private
		 */
		SideNavigation.prototype._finishAnimation = function (isExpanded) {
			if (!this._hasActiveAnimation || !this.getDomRef()) {
				return;
			}

			this.$().toggleClass('sapTntSideNavigationNotExpandedWidth', !isExpanded);

			if (!isExpanded) {
				this.$().toggleClass('sapTntSideNavigationNotExpanded', !isExpanded);

				if (this.getAggregation('item')) {
					this.getAggregation('item').setExpanded(isExpanded);
				}

				if (this.getAggregation('fixedItem')) {
					this.getAggregation('fixedItem').setExpanded(isExpanded);
				}

				// enable back the scroller after collapsing animation
				this._scroller.setVertical(true);
			}

			this.$().css('width', '');
			this._hasActiveAnimation = false;

			// wait for any re-rendering after the animation, before calling toggle arrows
			jQuery.sap.delayedCall(0, this, this._toggleArrows);
		};

		/**
		 * @private
		 */
		SideNavigation.prototype.onBeforeRendering = function () {
			var selectedItem = this.getSelectedItem();

			if (selectedItem) {
			    this.setSelectedItem(selectedItem, true);
			}

			this._deregisterControl();
		};

		/**
		 * @private
		 */
		SideNavigation.prototype.onAfterRendering = function () {
			this._ResizeHandler = ResizeHandler.register(this.getDomRef(), this._toggleArrows.bind(this));
			this._toggleArrows();
		};

		/**
		 * Sets the association for selectedItem
		 * @public
		 * @param {string|sap.tnt.NavigationListItem} selectedItem The control to be set as selected
		 * @param {boolean} suppressInvalidate If true, the managed object's invalidate method is not called
		 * @return {sap.tnt.SideNavigation|null} The selectedItem association
		 */
		SideNavigation.prototype.setSelectedItem = function (selectedItem, suppressInvalidate) {
			var navigationList = this.getAggregation('item');
			var fixedNavigationList = this.getAggregation('fixedItem');
			var listItemToSelect;

			if (!selectedItem) {
				if (navigationList.setSelectedItem) {
					navigationList.setSelectedItem(null, true);
				}
				if (fixedNavigationList.setSelectedItem) {
					fixedNavigationList.setSelectedItem(null, true);
				}
			}

			if (typeof selectedItem === 'string') {
				listItemToSelect = sap.ui.getCore().byId(selectedItem);
			} else {
				listItemToSelect = selectedItem;
			}

			var selectedInFlexibleList = listItemToSelect && listItemToSelect.getNavigationList && listItemToSelect.getNavigationList() === navigationList;
			var selectedInFixedList = listItemToSelect && listItemToSelect.getNavigationList && listItemToSelect.getNavigationList() === fixedNavigationList;

			if (selectedInFlexibleList) {
				navigationList.setSelectedItem(listItemToSelect, suppressInvalidate);
				if (fixedNavigationList) {
					fixedNavigationList.setSelectedItem(null, true);
				}
			}

			if (selectedInFixedList) {
				fixedNavigationList.setSelectedItem(listItemToSelect, suppressInvalidate);
				navigationList.setSelectedItem(null, true);
			}

			return sap.ui.core.Control.prototype.setAssociation.call(this, 'selectedItem', listItemToSelect, true);
		};

		/**
		 * @private
		 */
		SideNavigation.prototype.exit = function () {

			if (this._scroller) {
				this._scroller.destroy();
				this._scroller = null;
			}

			this._deregisterControl();
		};

		/**
		 *
		 * @param event
		 * @private
		 */
		SideNavigation.prototype._itemSelectionHandler = function (event) {
			var listId = event.getSource().getId();
			var itemAggregation = this.getAggregation('item');
			var fixedItemAggregation = this.getAggregation('fixedItem');
			var item = event.getParameter('item');

			if (itemAggregation && fixedItemAggregation && listId === itemAggregation.getId()) {
				fixedItemAggregation.setSelectedItem(null);
			}

			if (itemAggregation && fixedItemAggregation && listId === fixedItemAggregation.getId()) {
				itemAggregation.setSelectedItem(null);
			}

			sap.ui.core.Control.prototype.setAssociation.call(this, 'selectedItem', item, true);

			this.fireItemSelect({
				item: item
			});
		};

		/**
		 * @private
		 */
		SideNavigation.prototype._deregisterControl = function () {
			if (this._ResizeHandler) {
				ResizeHandler.deregister(this._ResizeHandler);
				this._ResizeHandler = null;
			}
		};

		/**
		 * Returns the sap.ui.core.Icon control used to display the group icon.
		 * @returns {sap.ui.core.Icon}
		 * @private
		 */
		SideNavigation.prototype._getTopArrowControl = function () {
			var iconControl = this.getAggregation('_topArrowControl');
			var that = this;

			if (!iconControl) {
				iconControl = new Icon({
					src: 'sap-icon://navigation-up-arrow',
					noTabStop: true,
					useIconTooltip: false,
					tooltip: '',
					press: this._arrowPress.bind(that)
				}).addStyleClass('sapTntSideNavigationScrollIcon sapTntSideNavigationScrollIconUp');
				this.setAggregation("_topArrowControl", iconControl, true);
			}

			return iconControl;
		};

		/**
		 * Returns the sap.ui.core.Icon control used to display the group icon.
		 * @returns {sap.ui.core.Icon}
		 * @private
		 */
		SideNavigation.prototype._getBottomArrowControl = function () {
			var iconControl = this.getAggregation('_bottomArrowControl');
			var that = this;

			if (!iconControl) {
				iconControl = new Icon({
					src: 'sap-icon://navigation-down-arrow',
					noTabStop: true,
					useIconTooltip: false,
					tooltip: '',
					press: this._arrowPress.bind(that)
				}).addStyleClass('sapTntSideNavigationScrollIcon sapTntSideNavigationScrollIconDown');

				this.setAggregation("_bottomArrowControl", iconControl, true);
			}

			return iconControl;
		};

		SideNavigation.prototype._toggleArrows = function () {
			var domRef = this.getDomRef();

			if (!domRef) {
				return;
			}

			var scrollContainerWrapper = this.$('Flexible')[0];
			var scrollContainerContent = this.$('Flexible-Content')[0];
			var isAsideExpanded = this.getExpanded();

			if (this._hasActiveAnimation) {
				domRef.querySelector('.sapTntSideNavigationScrollIconUp').style.display = 'none';
				domRef.querySelector('.sapTntSideNavigationScrollIconDown').style.display = 'none';
				return;
			}

			if ((scrollContainerContent.offsetHeight > scrollContainerWrapper.offsetHeight) && !isAsideExpanded) {
				domRef.querySelector('.sapTntSideNavigationScrollIconUp').style.display = 'block';
				domRef.querySelector('.sapTntSideNavigationScrollIconDown').style.display = 'block';

				domRef.querySelector('.sapTntSideNavigationScrollIconDown').classList.remove('sapTntSideNavigationScrollIconDisabled');
			} else {
				domRef.querySelector('.sapTntSideNavigationScrollIconUp').style.display = 'none';
				domRef.querySelector('.sapTntSideNavigationScrollIconDown').style.display = 'none';
			}
		};

		SideNavigation.prototype._arrowPress = function (event) {
			event.preventDefault();

			var source = document.getElementById(event.oSource.sId);
			var isDirectionForward = source.classList.contains('sapTntSideNavigationScrollIconDown') ? true : false;

			var $container = this.$('Flexible');

			var step = isDirectionForward ? 40 : -40;
			$container[0].scrollTop += step;
		};

		return SideNavigation;

	}, /* bExport= */ true
);
<|endoftext|>


<commit_before>'use strict';

// Libs
let bodyparser = require('body-parser');

// Classes
let ApiController = require('./ApiController');

// Constants
const SUBMISSION_TIMEOUT_MS = 1000;

// Private vars
let lastSubmission = Date.now();
let lastIp = '';

class FormsController extends ApiController {
    /**
     * Initialises this controller
     */
    static init(app) {
        app.get('/api/:project/:environment/forms/', this.middleware(), this.getAllForms);
        app.get('/api/:project/:environment/forms/:id', this.middleware(), this.getForm);
        app.get('/api/:project/:environment/forms/:id/entries', this.middleware(), this.getAllEntries);

        app.post('/api/:project/:environment/forms/new', this.middleware(), this.postNew);
        app.post('/api/:project/:environment/forms/:id', this.middleware(), this.postForm);
        app.post('/api/:project/:environment/forms/:id/submit', this.middleware({ authenticate: false, allowCORS: this.checkCORS }), bodyparser.urlencoded({extended: true}), this.postSubmit);
        app.post('/api/:project/:environment/forms/pull/:id', this.middleware(), this.pullForm);
        app.post('/api/:project/:environment/forms/push/:id', this.middleware(), this.pushForm);
        app.post('/api/:project/:environment/forms/clear/:id', this.middleware(), this.postClearAllEntries);

        app.delete('/api/:project/:environment/forms/:id', this.middleware(), this.deleteForm);

        // Init spam prevention timer
        lastSubmission = Date.now();
    }

    /**
     * Check CORS
     *
     * @returns {Promise} Result
     */
    static checkCORS(req, res) {
        return FormHelper.getForm(req.params.project, req.params.environment, req.params.id)
        .then((form) => {
            return Promise.resolve(form.allowedOrigin || '*');
        });
    }

    /**
     * Gets all forms
     */
    static getAllForms(req, res) {
        FormHelper.getAllForms(req.project, req.environment)
        .then((forms) => {
            res.status(200).send(forms);
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Deletes a single Form by id
     */
    static deleteForm(req, res) {
        FormHelper.deleteForm(req.project, req.environment, req.params.id)
        .then(() => {
            res.status(200).send('OK');
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Pulls Form by id
     */
    static pullForm(req, res) {
        let id = req.params.id;

        SyncHelper.getResourceItem(req.project, req.environment, 'forms', id)
        .then((resourceItem) => {
            if(!resourceItem) { return Promise.reject(new Error('Couldn\'t find remote Form "' + id + '"')); }

            return FormHelper.setForm(req.project, req.environment, id, resourceItem)
            .then(() => {
                res.status(200).send(resourceItem);
            });
        })
        .catch((e) => {
            res.status(404).send(FormController.printError(e));
        });
    }

    /**
     * Pushes Form by id
     */
    static pushForm(req, res) {
        let id = req.params.id;

        FormHelper.getForm(req.project, req.environment, id)
        .then((localForm) => {
            return SyncHelper.setResourceItem(req.project, req.environment, 'forms', id, localForm);
        })
        .then(() => {
            return FormHelper.deleteForm(req.project, req.environment, id);
        })
        .then(() => {
            res.status(200).send(id);
        })
        .catch((e) => {
            res.status(404).send(FormController.printError(e));
        });
    }

    /**
     * Gets a single form by id
     */
    static getForm(req, res) {
        FormHelper.getForm(req.project, req.environment, req.params.id)
        .then((form) => {
            res.status(200).send(form.getObject());
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Gets all entries from a Form as CSV
     */
    static getAllEntries(req, res) {
        FormHelper.getForm(req.project, req.environment, req.params.id)
        .then((form) => {
            let csv = '';

            for(let inputKey in form.inputs) {
                csv += '"' + inputKey + '",';
            }

            // Remove last comma
            csv = csv.slice(0, -1);
            csv += '\r\n';

            for(let entry of form.entries) {
                for(let inputKey in form.inputs) {
                    csv += '"' + (entry[inputKey] || ' ') + '",';
                }

                // Remove last comma
                csv = csv.slice(0, -1);
                csv += '\r\n';
            }

            res.attachment('entries-' + form.id + '.csv');

            res.status(200).send(csv);
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Sets a single form by id
     */
    static postForm(req, res) {
        FormHelper.setForm(req.project, req.environment, req.params.id, req.body)
        .then((form) => {
            res.status(200).send(form.getObject());
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Creates a form
     */
    static postNew(req, res) {
        FormHelper.createForm(req.project, req.environment)
        .then((form) => {
            res.status(200).send(form.id);
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Submits a form
     */
    static postSubmit(req, res) {
        // Prevent spam
        if(
            lastIp != req.connection.remoteAddress || // This IP is not the same as the previous one
            Date.now() - lastSubmission >= SUBMISSION_TIMEOUT_MS // Timeout has been reached
        ) {
            lastSubmission = Date.now();
            lastIp = req.connection.remoteAddress;

            FormHelper.addEntry(req.project, req.environment, req.params.id, req.body)
            .then((form) => {
                if(form.redirect) {
                    let redirectUrl = form.redirect;

                    if(form.appendRedirect) {
                        if(!req.headers.referer) {
                            return Promise.reject(new Error('Request header has no referer'));
                        }

                        redirectUrl = req.headers.referer + redirectUrl;
                    }

                    res.status(302).redirect(redirectUrl);

                } else {
                    res.sendStatus(200);

                }
            })
            .catch((e) => {
                res.status(400).send(FormsController.printError(e));
            });

        } else {
            res.status(400).send(ApiController.printError(new Error('Spam prevention triggered. Please try again later.')));

        }
    }

    /**
     * Clears all form entries
     */
    static postClearAllEntries(req, res) {
        FormHelper.clearAllEntries(req.project, req.environment, req.params.id)
        .then(() => {
            res.sendStatus(200);
        })
        .catch((e) => {
            res.status(502).send(ApiController.printError(e));
        });
    }
}

module.exports = FormsController;
<commit_msg>token in origin<commit_after>'use strict';

// Libs
let bodyparser = require('body-parser');

// Classes
let ApiController = require('./ApiController');

// Constants
const SUBMISSION_TIMEOUT_MS = 1000;

// Private vars
let lastSubmission = Date.now();
let lastIp = '';

class FormsController extends ApiController {
    /**
     * Initialises this controller
     */
    static init(app) {
        app.get('/api/:project/:environment/forms/', this.middleware(), this.getAllForms);
        app.get('/api/:project/:environment/forms/:id', this.middleware(), this.getForm);
        app.get('/api/:project/:environment/forms/:id/entries', this.middleware(), this.getAllEntries);

        app.post('/api/:project/:environment/forms/new', this.middleware(), this.postNew);
        app.post('/api/:project/:environment/forms/:id', this.middleware(), this.postForm);
        app.post('/api/:project/:environment/forms/:id/submit', this.middleware({ authenticate: false, allowCORS: this.checkCORS }), bodyparser.urlencoded({extended: true}), this.postSubmit);
        app.post('/api/:project/:environment/forms/pull/:id', this.middleware(), this.pullForm);
        app.post('/api/:project/:environment/forms/push/:id', this.middleware(), this.pushForm);
        app.post('/api/:project/:environment/forms/clear/:id', this.middleware(), this.postClearAllEntries);

        app.delete('/api/:project/:environment/forms/:id', this.middleware(), this.deleteForm);

        // Init spam prevention timer
        lastSubmission = Date.now();
    }

    /**
     * Check CORS
     *
     * @returns {Promise} Result
     */
    static checkCORS(req, res) {
        return FormHelper.getForm(req.params.project, req.params.environment, req.params.id)
        .then((form) => {
            return Promise.resolve(form.allowedOrigin || '*');
        });
    }

    /**
     * Gets all forms
     */
    static getAllForms(req, res) {
        FormHelper.getAllForms(req.project, req.environment)
        .then((forms) => {
            res.status(200).send(forms);
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Deletes a single Form by id
     */
    static deleteForm(req, res) {
        FormHelper.deleteForm(req.project, req.environment, req.params.id)
        .then(() => {
            res.status(200).send('OK');
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Pulls Form by id
     */
    static pullForm(req, res) {
        let id = req.params.id;

        SyncHelper.getResourceItem(req.project, req.environment, 'forms', id)
        .then((resourceItem) => {
            if(!resourceItem) { return Promise.reject(new Error('Couldn\'t find remote Form "' + id + '"')); }

            return FormHelper.setForm(req.project, req.environment, id, resourceItem)
            .then(() => {
                res.status(200).send(resourceItem);
            });
        })
        .catch((e) => {
            res.status(404).send(FormController.printError(e));
        });
    }

    /**
     * Pushes Form by id
     */
    static pushForm(req, res) {
        let id = req.params.id;

        FormHelper.getForm(req.project, req.environment, id)
        .then((localForm) => {
            return SyncHelper.setResourceItem(req.project, req.environment, 'forms', id, localForm);
        })
        .then(() => {
            return FormHelper.deleteForm(req.project, req.environment, id);
        })
        .then(() => {
            res.status(200).send(id);
        })
        .catch((e) => {
            res.status(404).send(FormController.printError(e));
        });
    }

    /**
     * Gets a single form by id
     */
    static getForm(req, res) {
        FormHelper.getForm(req.project, req.environment, req.params.id)
        .then((form) => {
            res.status(200).send(form.getObject());
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Gets all entries from a Form as CSV
     */
    static getAllEntries(req, res) {
        FormHelper.getForm(req.project, req.environment, req.params.id)
        .then((form) => {
            let csv = '';

            for(let inputKey in form.inputs) {
                csv += '"' + inputKey + '",';
            }

            // Remove last comma
            csv = csv.slice(0, -1);
            csv += '\r\n';

            for(let entry of form.entries) {
                for(let inputKey in form.inputs) {
                    csv += '"' + (entry[inputKey] || ' ') + '",';
                }

                // Remove last comma
                csv = csv.slice(0, -1);
                csv += '\r\n';
            }

            res.attachment('entries-' + form.id + '.csv');

            res.status(200).send(csv);
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Sets a single form by id
     */
    static postForm(req, res) {
        FormHelper.setForm(req.project, req.environment, req.params.id, req.body)
        .then((form) => {
            res.status(200).send(form.getObject());
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Creates a form
     */
    static postNew(req, res) {
        FormHelper.createForm(req.project, req.environment)
        .then((form) => {
            res.status(200).send(form.id);
        })
        .catch((e) => {
            res.status(502).send(FormsController.printError(e));
        });
    }

    /**
     * Submits a form
     */
    static postSubmit(req, res) {
        // Prevent spam
        if(
            lastIp != req.connection.remoteAddress || // This IP is not the same as the previous one
            Date.now() - lastSubmission >= SUBMISSION_TIMEOUT_MS // Timeout has been reached
        ) {
            lastSubmission = Date.now();
            lastIp = req.connection.remoteAddress;

            FormHelper.addEntry(req.project, req.environment, req.params.id, req.body)
            .then((form) => {
                if(form.redirect) {
                    let redirectUrl = form.redirect;

                    if(form.appendRedirect && req.headers.referer) {
                        redirectUrl = req.headers.referer + redirectUrl;
                    }

                    res.status(302).redirect(redirectUrl);

                } else {
                    res.sendStatus(200);

                }
            })
            .catch((e) => {
                res.status(400).send(FormsController.printError(e));
            });

        } else {
            res.status(400).send(ApiController.printError(new Error('Spam prevention triggered. Please try again later.')));

        }
    }

    /**
     * Clears all form entries
     */
    static postClearAllEntries(req, res) {
        FormHelper.clearAllEntries(req.project, req.environment, req.params.id)
        .then(() => {
            res.sendStatus(200);
        })
        .catch((e) => {
            res.status(502).send(ApiController.printError(e));
        });
    }
}

module.exports = FormsController;
<|endoftext|>


<commit_before>'use strict';

const WebSocket = require('ws');
require('./ext-arrays.js');

class PSConnection {
	constructor() {
		this.handlers = {};
		this.battles = {};
		this.monitors = {};
	}

	on(event, cb) {
		this.handlers[event] = this.handlers[event] || [];
		this.handlers[event].push(cb);
	}

	remove(event, cb) {
		for (var i in this.handlers[event])
			if (this.handlers[event][i] == cb) {
				delete this.handlers[event][i];
				break;
			}
	}

	send(data) {
		this.ws.send(JSON.stringify(data));
	}

	addBattleListener(battle) {
		this.monitors[battle.room] = battle;
	}

	removeBattleListener(battle) {
		delete this.monitors[battle.room];
	}

	start() {
		try {
			this.ws = new WebSocket('wss://sim2.psim.us/showdown/926/3jbvr0y1/websocket');
			this.ws.on('open', () => {
			});

			this.ws.on('close', () => {
				console.log('CONNECTION CLOSED');
				this.start();
			});

			this.ws.on('message', (data) => {
				if (data == 'o')
					return;
				data = JSON.parse(data.substr(1))[0];
				data = data.split('\n')
					.filter(line => line != '');
				if (data[0][0] == '>') {
					let room = data[0].substr(1);
					data = data.filter(line => line[0] != '>');
					if (this.monitors[room]) {
						for(let e of data) {
							// Have to check everytime because certain events might destroy the room
							if (!this.monitors[room])
								break;
							let event = e.split('|')[1];
							if (this.monitors[room][event]) {
								this.monitors[room][event](e, e.split('|').filter(d => d != ''));
							}
						}
					}
				}
				else {
					data.filter(line => line[0] != '>')
						.map(e => [e.split('|')[1], e.split('|'), e])
						.filter(event => this.handlers[event[0]])
						.map(event => [this.handlers[event[0]], ...event])
						.forEach(e => e[0](e[3], e[2].filter(d => d != '')));
				}
			});
		} catch(e) {
			console.log('Something horribly wrong happened, disabled websocket');
		}
	}
};

module.exports = new PSConnection();
<commit_msg>Fix "typo"<commit_after>'use strict';

const WebSocket = require('ws');

class PSConnection {
	constructor() {
		this.handlers = {};
		this.battles = {};
		this.monitors = {};
	}

	on(event, cb) {
		this.handlers[event] = this.handlers[event] || [];
		this.handlers[event].push(cb);
	}

	remove(event, cb) {
		for (var i in this.handlers[event])
			if (this.handlers[event][i] == cb) {
				delete this.handlers[event][i];
				break;
			}
	}

	send(data) {
		this.ws.send(JSON.stringify(data));
	}

	addBattleListener(battle) {
		this.monitors[battle.room] = battle;
	}

	removeBattleListener(battle) {
		delete this.monitors[battle.room];
	}

	start() {
		try {
			this.ws = new WebSocket('wss://sim2.psim.us/showdown/926/3jbvr0y1/websocket');
			this.ws.on('open', () => {
			});

			this.ws.on('close', () => {
				console.log('CONNECTION CLOSED');
				this.start();
			});

			this.ws.on('message', (data) => {
				if (data == 'o')
					return;
				data = JSON.parse(data.substr(1))[0];
				data = data.split('\n')
					.filter(line => line != '');
				if (data[0][0] == '>') {
					let room = data[0].substr(1);
					data = data.filter(line => line[0] != '>');
					if (this.monitors[room]) {
						for(let e of data) {
							// Have to check everytime because certain events might destroy the room
							if (!this.monitors[room])
								break;
							let event = e.split('|')[1];
							if (this.monitors[room][event]) {
								this.monitors[room][event](e, e.split('|').filter(d => d != ''));
							}
						}
					}
				}
				else {
					data.filter(line => line[0] != '>')
						.map(e => [e.split('|')[1], e.split('|'), e])
						.filter(event => this.handlers[event[0]])
						.map(event => [this.handlers[event[0]], ...event])
						.forEach(e => e[0].forEach(e[3], e[2].filter(d => d != '')));
				}
			});
		} catch(e) {
			console.log('Something horribly wrong happened, disabled websocket');
		}
	}
};

module.exports = new PSConnection();
<|endoftext|>


<commit_before>// alguns métodos não devem ser herdados por todos, como check e uncheck. Ver como isso seria resolvido sem comprometimento do padrão builder

var
    // mudar para APIece ("apaiês")
    esPhinx,
    Iterable,
    Extensor,
    SearchContext,
    Search;

// IIFE
(function($module) {
    "use strict";

    const
        name = "esPhinx";

    var
        selectInBreadth = function(iterable, callback) {
            var
                returned,
                strategy,
                selected = [];

            if (iterable instanceof window.Node) {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Element
                                                   .new(iterable));
            } else {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Object
                                                   .new(iterable));
            }

            strategy.research(function(value, key, trace) {
                if (value instanceof window.Node) {
                    returned = callback.call(iterable, value, key);
                } else {
                    returned = callback.call(iterable, value, key, trace);
                }

                if (returned) {
                    selected.push(value);
                }
            });

            return selected;
        },

        resolveContext = function(context) {
            if (typeof context == "object") {
                if (context instanceof esPhinx ||
                    context instanceof Element) {
                    return context;
                }
            } else if (typeof context == "string") {
                // recursivity
                return esPhinx(context);
            }

            return window.document;
        };

    try {
        Object.defineProperties($module, {

            esPhinx: {

                // ver por que o nome na função está sendo necessário para alguns casos
                value: function esPhinx(selector, context) {
                // value: (function esPhinx(selector, context) {

                    var
                        self = esPhinx,
                        mainReference = this,
                        collection = [],

                        hasElement = function(iterable) {
                            for (var i in iterable) {
                                if (iterable.hasOwnProperty(i)) {
                                    return iterable[i] instanceof window.Element;
                                }
                            }
                        };

                    if (!(mainReference instanceof self)) {
                        return new self(selector, context);
                    }

                    context = resolveContext(context);

                    if (selector) {
                        // recognize a tagName
                        // ([^<][^ >]+)
                        // to get attributes?
                        // selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
                        // get children "".match(/(>)(<.(?=(<\/)))/)[0]
                        if (selector instanceof self) {
                            return selector;
                        } else if (typeof selector == "function") {
                            return window.document
                                .addEventListener("DOMContentLoaded", function(e) {
                                selector.call(self, e);
                            });
                        // add support to XPath
                        } else if (typeof selector == "string") {
                            collection = Array.from((new window.DOMParser())
                                .parseFromString(selector, "text/html").body
                                .childNodes);

                            if (!hasElement(collection)) {
                                collection = [];
                                if (Iterable.isIterable(context)) {
                                    Array.from(context).forEach(function(node) {
                                        collection = collection.concat(Array
                                            .from(node.querySelectorAll(selector)))
                                            .flatten();
                                    });
                                } else {
                                    try {
                                        collection = Array.from(context
                                            .querySelectorAll(selector));
                                    } catch (e) {}
                                }
                            }
                        } else if (selector instanceof window.Node) {
                            collection = [selector];
                        } else if (selector instanceof Object) {
                            collection = Array.from(selector);

                            if (selector.constructor != window.HTMLCollection &&
                                collection.length) {
                                mainReference[0] = selector;

                                if (selector == window) {
                                    collection = [];
                                }
                            }
                        }

                        Object.assign(mainReference, collection);
                    }

                    Object.defineProperties(mainReference, {
                        splice: {
                            value: Array.prototype.splice
                        },

                        toString: {
                            value: function() {
                                return name;
                            }
                        }
                    });
                    Iterable.toIterable(mainReference);

                    return mainReference;
                }

            }

        });
    } catch(e) {};

    Object.defineProperties(esPhinx, {
        Extensor: {
            value: {},
            enumerable: true
        }
    });

    Extensor.new(esPhinx.Extensor, true, {
        new: function(object, final, structure) {
            Extensor.new(object, final, structure);
        }
    });

    esPhinx.Extensor.new(esPhinx, true, {
        extend: function() {
            // debugger
            this.Extensor.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.Extensor.new(esPhinx.prototype, true, {
        extend: function() {
            // debugger
            esPhinx.Extensor.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.extend(true, {

        selectByText: function(text, context) {
            var
                collection = [];

            this.select(this(resolveContext(context)), function(element) {
                collection = collection.concat(document.evaluate(
                    "descendant-or-self::*[normalize-space(text())='" +
                    text.trim() + "']", element).elements()).flatten();
            });

            return esPhinx(collection);
        },

        isIterable: function(object) {
            return isIterable(object);
        },

        selectInBreadth: function(collection, callback) {
            return selectInBreadth(collection, callback);
        },

        each: function(collection, startIndex, callback) {
            var
                keys = Object.keys(collection),
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function" ) {
                callback = startIndex;
            }

            iterator.each(startIndex, function(item) {
                callback.call(this, item, keys[this.index()]);
            });
        },

        reverseEach: function(collection, startIndex, callback) {
            var
                keys = Object.keys(collection),
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function") {
                callback = startIndex;
            }

            iterator.reverseEach(startIndex, function(item) {
                callback.call(this, item, keys[this.index()]);
            });
        },

        select: function(collection, callback) {
            var
                returned,
                selected = [],
                keys = Object.keys(collection),
                iterator = Iterable.Proxy.new(collection);

            iterator.each(function(item) {
                returned = callback.call(this, item,
                                         keys[this.index()]);
                if (returned) {
                    selected.push(item);
                }
            });

            // esPhinx.each(collection, 0, function(item, i) {
            //     returned = callback.call(collection, item, i);

            //     if (returned) {
            //         selected.push(item);
            //     }
            // });

            if (selected.length) {
                return selected;
            }
        }

    });

})(window);

// element_pattern = /([\n ]*<(([a-zA-Z]+( +(\w+-*)* *(= *((" *((\w+-*)|(((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+))) *;? *)|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *")|(' *((\w+-*)|((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+)))|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *')|(\\" *((\w+-*)|((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+)))|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *\\")|(\\' *((\w+-*)|((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+)))|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *\\')))?)* *(\/|(>(\n|.)*<\/[a-zA-Z]+)))|(!--(\n|.)*--))>[\n ]*)+$/g;

// recognize a Element
// selector_pattern = /( *(([a-zA-Z]+)|([.#](\w+-*)+)|(:(\w+-*)+(\([a-zA-Z0-9]+\))?)|(:{2}(\w+-*)+)|(\*)|(\w*\[ *(\w+-*)+ *([\^$|~*]?= *(((\\?["'])?((\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))(;(\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))*;?(\\?["'])?)|((\\?["']) *((\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))( *; *(\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))* *;? *(\\?["'])))) *\]))(( *([,~>+] *)?(([.#](\w+-*)+)|(:(\w+-*)+(\([a-zA-Z0-9]+\))?)|(:{2}(\w+-*)+)|(\w*\[ *(\w+-*)+ *([\^$|~*]?= *(((\\?["'])?((\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))(;(\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))*;?(\\?["'])?)|((\\?["']) *((\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))( *; *(\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))* *;? *(\\?["']))))? *(\\?["'])? *\])))|((( *[,~>+] *)| +)(([a-zA-Z]+)|\*)))* *(?!.))/;

// element_pattern = /<(([a-zA-Z]+.*\/?)|(!--(\n|.)*--))>/;

// if (RegExp.prototype.hasOwnProperty("sticky")) {
//     element_pattern = new RegExp(element_pattern, "gy");
//     // selector_pattern = new RegExp(selector_pattern, "gy");
// } else {
//     element_pattern = new RegExp(element_pattern, "g");
//     // selector_pattern = new RegExp(selector_pattern, "g");
// }
<commit_msg>improves main when pass a function as parameter<commit_after>// alguns métodos não devem ser herdados por todos, como check e uncheck. Ver como isso seria resolvido sem comprometimento do padrão builder

var
    // mudar para APIece ("apaiês")
    esPhinx,
    Iterable,
    Extensor,
    SearchContext,
    Search;

// IIFE
(function($module) {
    "use strict";

    const
        name = "esPhinx";

    var
        selectInBreadth = function(iterable, callback) {
            var
                returned,
                strategy,
                selected = [];

            if (iterable instanceof window.Node) {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Element
                                                   .new(iterable));
            } else {
                strategy = SearchContext.Proxy.new(Search.Graphs.BFS.Object
                                                   .new(iterable));
            }

            strategy.research(function(value, key, trace) {
                if (value instanceof window.Node) {
                    returned = callback.call(iterable, value, key);
                } else {
                    returned = callback.call(iterable, value, key, trace);
                }

                if (returned) {
                    selected.push(value);
                }
            });

            return selected;
        },

        resolveContext = function(context) {
            if (typeof context == "object") {
                if (context instanceof esPhinx ||
                    context instanceof Element) {
                    return context;
                }
            } else if (typeof context == "string") {
                // recursivity
                return esPhinx(context);
            }

            return window.document;
        };

    try {
        Object.defineProperties($module, {

            esPhinx: {

                // ver por que o nome na função está sendo necessário para alguns casos
                value: function esPhinx(selector, context) {
                // value: (function esPhinx(selector, context) {

                    var
                        self = esPhinx,
                        mainReference = this,
                        collection = [],

                        hasElement = function(iterable) {
                            for (var i in iterable) {
                                if (iterable.hasOwnProperty(i)) {
                                    return iterable[i] instanceof
                                    window.Element;
                                }
                            }
                        };

                    if (!(mainReference instanceof self)) {
                        return new self(selector, context);
                    }

                    context = resolveContext(context);

                    if (selector) {
                        // recognize a tagName
                        // ([^<][^ >]+)
                        // to get attributes?
                        // selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
                        // get children "".match(/(>)(<.(?=(<\/)))/)[0]
                        if (selector instanceof self) {
                            return selector;
                        } else if (typeof selector == "function") {
                            // don't never pass a autoexecutable function as parameter
                            return window.document
                                .addEventListener("DOMContentLoaded",
                                                  function(e) {
                                selector.call(self, self, e);
                            });
                        // add support to XPath
                        } else if (typeof selector == "string") {
                            collection = Array.from((new window.DOMParser())
                                .parseFromString(selector, "text/html").body
                                .childNodes);

                            if (!hasElement(collection)) {
                                collection = [];
                                if (Iterable.isIterable(context)) {
                                    Array.from(context).forEach(function(node) {
                                        collection = collection.concat(Array
                                            .from(node
                                                  .querySelectorAll(selector)))
                                        .flatten();
                                    });
                                } else {
                                    try {
                                        collection = Array.from(context
                                            .querySelectorAll(selector));
                                    } catch (e) {}
                                }
                            }
                        } else if (selector instanceof window.Node) {
                            collection = [selector];
                        } else if (selector instanceof Object) {
                            collection = Array.from(selector);

                            if (selector.constructor != window.HTMLCollection &&
                                collection.length) {
                                mainReference[0] = selector;

                                if (selector == window) {
                                    collection = [];
                                }
                            }
                        }

                        Object.assign(mainReference, collection);
                    }

                    Object.defineProperties(mainReference, {
                        splice: {
                            value: Array.prototype.splice
                        },

                        toString: {
                            value: function() {
                                return name;
                            }
                        }
                    });
                    Iterable.toIterable(mainReference);

                    return mainReference;
                }

            }

        });
    } catch(e) {};

    Object.defineProperties(esPhinx, {
        Extensor: {
            value: {},
            enumerable: true
        }
    });

    Extensor.new(esPhinx.Extensor, true, {
        new: function(object, final, structure) {
            Extensor.new(object, final, structure);
        }
    });

    esPhinx.Extensor.new(esPhinx, true, {
        extend: function() {
            // debugger
            this.Extensor.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.Extensor.new(esPhinx.prototype, true, {
        extend: function() {
            // debugger
            esPhinx.Extensor.new(this, arguments[0], arguments[1]);
        }
    });

    esPhinx.extend(true, {

        selectByText: function(text, context) {
            var
                collection = [];

            this.select(this(resolveContext(context)), function(element) {
                collection = collection.concat(document.evaluate(
                    "descendant-or-self::*[normalize-space(text())='" +
                    text.trim() + "']", element).elements()).flatten();
            });

            return esPhinx(collection);
        },

        isIterable: function(object) {
            return isIterable(object);
        },

        selectInBreadth: function(collection, callback) {
            return selectInBreadth(collection, callback);
        },

        each: function(collection, startIndex, callback) {
            var
                keys = Object.keys(collection),
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function" ) {
                callback = startIndex;
            }

            iterator.each(startIndex, function(item) {
                callback.call(this, item, keys[this.index()]);
            });
        },

        reverseEach: function(collection, startIndex, callback) {
            var
                keys = Object.keys(collection),
                iterator = Iterable.Proxy.new(collection);

            if (typeof startIndex == "function") {
                callback = startIndex;
            }

            iterator.reverseEach(startIndex, function(item) {
                callback.call(this, item, keys[this.index()]);
            });
        },

        select: function(collection, callback) {
            var
                returned,
                selected = [],
                keys = Object.keys(collection),
                iterator = Iterable.Proxy.new(collection);

            iterator.each(function(item) {
                returned = callback.call(this, item,
                                         keys[this.index()]);
                if (returned) {
                    selected.push(item);
                }
            });

            // esPhinx.each(collection, 0, function(item, i) {
            //     returned = callback.call(collection, item, i);

            //     if (returned) {
            //         selected.push(item);
            //     }
            // });

            if (selected.length) {
                return selected;
            }
        }

    });

})(window);

// element_pattern = /([\n ]*<(([a-zA-Z]+( +(\w+-*)* *(= *((" *((\w+-*)|(((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+))) *;? *)|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *")|(' *((\w+-*)|((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+)))|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *')|(\\" *((\w+-*)|((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+)))|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *\\")|(\\' *((\w+-*)|((\w+-*)+ *: *((\w+-*)+|((\/?(\w+-*))*(\w+-*)+\.\w+)))|((\/?(\w+-*))*(\w+-*)+\.\w+))+ *\\')))?)* *(\/|(>(\n|.)*<\/[a-zA-Z]+)))|(!--(\n|.)*--))>[\n ]*)+$/g;

// recognize a Element
// selector_pattern = /( *(([a-zA-Z]+)|([.#](\w+-*)+)|(:(\w+-*)+(\([a-zA-Z0-9]+\))?)|(:{2}(\w+-*)+)|(\*)|(\w*\[ *(\w+-*)+ *([\^$|~*]?= *(((\\?["'])?((\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))(;(\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))*;?(\\?["'])?)|((\\?["']) *((\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))( *; *(\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))* *;? *(\\?["'])))) *\]))(( *([,~>+] *)?(([.#](\w+-*)+)|(:(\w+-*)+(\([a-zA-Z0-9]+\))?)|(:{2}(\w+-*)+)|(\w*\[ *(\w+-*)+ *([\^$|~*]?= *(((\\?["'])?((\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))(;(\w+-*)+:((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))*;?(\\?["'])?)|((\\?["']) *((\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))( *; *(\w+-*)+ *: *((\w+-*)+|((\\?["'])?(\/?(\w+-*))*(\w+-*)+\.\w+)))* *;? *(\\?["']))))? *(\\?["'])? *\])))|((( *[,~>+] *)| +)(([a-zA-Z]+)|\*)))* *(?!.))/;

// element_pattern = /<(([a-zA-Z]+.*\/?)|(!--(\n|.)*--))>/;

// if (RegExp.prototype.hasOwnProperty("sticky")) {
//     element_pattern = new RegExp(element_pattern, "gy");
//     // selector_pattern = new RegExp(selector_pattern, "gy");
// } else {
//     element_pattern = new RegExp(element_pattern, "g");
//     // selector_pattern = new RegExp(selector_pattern, "g");
// }
<|endoftext|>