<commit_before>/* global console, Image, WSE */
/*
    Copyright (c) 2012, 2013 The WebStory Engine Contributors
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name WebStory Engine nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* global document, Image, console, WSE */

(function (out)
{
    "use strict";

    /**
     * Constructor function for ImagePacks.
     *
     * @param asset [DOM Element] The asset definition.
     * @param interpreter [WSE.Interpreter] The interpreter object.
     */
    out.assets.Imagepack = function (asset, interpreter)
    {
        var element, images, children, i, len, current, name;
        var src, image, self, triggerDecreaseFn, width, height;

        this.stage = interpreter.stage;
        this.bus = interpreter.bus;
        this.name = asset.getAttribute("name");
        this.id = out.tools.getUniqueId();
        this.cssid = asset.getAttribute("cssid") || "wse_imagepack_" + this.name;
        this.interpreter = interpreter;
        out.tools.applyAssetUnits(this, asset);

        self = this;
        images = {};
        element = document.createElement("div");
        width = asset.getAttribute('width');
        height = asset.getAttribute('height');

        element.style.opacity = 0;
        element.draggable = false;

        element.setAttribute("class", "imagepack");
        element.setAttribute("id", this.cssid);

        element.setAttribute("data-wse-asset-name", this.name);

        children = asset.getElementsByTagName("image");

        triggerDecreaseFn = function ()
        {
            self.bus.trigger("wse.assets.loading.decrease");
        };

        for (i = 0, len = children.length; i < len; i += 1)
        {
            current = children[i];
            name = current.getAttribute("name");
            src = current.getAttribute("src");

            if (name === null)
            {
                this.bus.trigger(
                    "wse.interpreter.warning",
                    {
                        element: asset,
                        message: "Image without name in imagepack '" +
                            this.name + "'."
                    }
                );
                continue;
            }

            if (src === null)
            {
                this.bus.trigger(
                    "wse.interpreter.warning",
                    {
                        element: asset,
                        message: "Image without src in imagepack '" +
                            this.name + "'."
                    }
                );
                continue;
            }

            image = new Image();

            this.bus.trigger("wse.assets.loading.increase");
            out.tools.attachEventListener(image, 'load', triggerDecreaseFn);

            image.src = src;
            image.style.opacity = 0;
            image.style.position = "absolute";
            image.draggable = false;

            image.setAttribute("data-wse-asset-image-name", name);

            if (width !== null)
            {
                image.setAttribute('width', width);
            }

            if (height !== null)
            {
                image.setAttribute('height', height);
            }

            images[name] = this.cssid + "_" + name;
            image.setAttribute("id", images[name]);
            element.appendChild(image);
        }

        element.style.position = "absolute";
        element.style.left = asset.getAttribute("x") || 0;
        element.style.top = asset.getAttribute("y") || 0;
        element.style.zIndex = asset.getAttribute("z") || 0;

        this.images = images;
        this.current = null;

        this.stage.appendChild(element);

        this.bus.trigger("wse.assets.imagepack.constructor", this);
    };

    out.tools.mixin(out.assets.mixins.displayable, out.assets.Imagepack.prototype);

    out.assets.Imagepack.prototype.set = function (command, args)
    {
        var image, name, self, old, duration, isAnimation, bus = this.bus, element;

        args = args || {};
        self = this;
        name = command.getAttribute("image");
        duration = command.getAttribute("duration") || 400;
        isAnimation = args.animation === true ? true : false;

        if (name === null)
        {
            bus.trigger(
                "wse.interpreter.warning",
                {
                    element: command,
                    message: "Missing attribute 'image' on 'do' element " +
                        "referencing imagepack '" + this.name + "'."
                }
            );

            return {
                doNext: true
            };
        }

        try {
            image = document.getElementById(this.images[name]);
        }
        catch (e) {
            console.error("DOM Element for Image " + name + " on Imagepack " + this.name + " not found!", e);
        }

        if (typeof image === "undefined" || image === null)
        {
            bus.trigger(
                "wse.interpreter.warning",
                {
                    element: command,
                    message: "Unknown image name on 'do' element referencing " +
                        "imagepack '" + this.name + "'."
                }
            );

            return {
                doNext: true
            };
        }

        old = this.current;

        for (var key in this.images)
        {
            if (this.images.hasOwnProperty(key))
            {
                if (key !== name)
                {
                    continue;
                }

                if (key === old)
                {
                    bus.trigger(
                        "wse.interpreter.warning",
                        {
                            element: command,
                            message: "Trying to set the image that is " +
                                "already set on imagepack '" + this.name + "'."
                        }
                    );

                    return {
                        doNext: true
                    };
                }
            }
        }

        if (!isAnimation)
        {
            self.interpreter.waitCounter += 1;
        }

        element = document.getElementById(this.cssid);
        element.style.width = image.offsetWidth + "px";
        element.style.height = image.offsetHeight + "px";

        (function ()
        {
            var valFn, finishFn, options;

            valFn = function (v)
            {
                image.style.opacity = v;
            };

            finishFn = function ()
            {
                if (!isAnimation)
                {
                    self.interpreter.waitCounter -= 1;
                }
            };

            options = {
                duration: duration,
                easing: out.fx.easing.easeOutCubic,
                onFinish: finishFn
            };

            out.fx.transform(valFn, 0, 1, options);
        }());

        if (this.current !== null)
        {
            if (!isAnimation)
            {
                self.interpreter.waitCounter += 1;
            }

            (function ()
            {
                var timeoutFn;

                timeoutFn = function()
                {
                    var oldEl, valFn, finishFn, options;

                    oldEl = document.getElementById(self.images[old]);

                    valFn = function (v)
                    {
                        oldEl.style.opacity = v;
                    };

                    finishFn = function ()
                    {
                        if (!isAnimation)
                        {
                            self.interpreter.waitCounter -= 1;
                        }
                    };

                    options = {
                        duration: duration,
                        easing: out.fx.easing.easeInCubic,
                        onFinish: finishFn
                    };

                    out.fx.transform(valFn, 1, 0, options);
                };

                timeoutFn();
            }());
        }

        this.current = name;

        return {
            doNext: true
        };
    };

    out.assets.Imagepack.prototype.save = function ()
    {
        var cur, key, images, name, obj;

        images = this.images;
        cur = this.current || null;
        name = null;

        for (key in images)
        {
            if (images.hasOwnProperty(key))
            {
                if (images[key] === cur)
                {
                    name = key;
                }
            }
        }

        obj = {
            assetType: "Imagepack",
            current: cur,
            cssid: this.cssid,
            images: images,
            z: this.z
        };

        this.bus.trigger(
            "wse.assets.imagepack.save",
            {
                subject: this,
                saves: obj
            }
        );

        return obj;
    };

    out.assets.Imagepack.prototype.restore = function (save)
    {
        var name;

        name = save.current;
        this.cssid = save.cssid;
        this.z = save.z;

        document.getElementById(this.cssid).style.zIndex = this.z;

        if (name !== null)
        {
            this.current = name;
        }

        this.bus.trigger(
            "wse.assets.imagepack.restore",
            {
                subject: this,
                saves: save
            }
        );
    };
}(WSE));<commit_msg>Fixed: Saving an unset imagepack resulted in an error during restoring the savegame when the current image of the imagepack before loading the savegame was the same as the one set on the imagepack after loading.<commit_after>/* global console, Image, WSE */
/*
    Copyright (c) 2012, 2013 The WebStory Engine Contributors
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name WebStory Engine nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* global document, Image, console, WSE */

(function (out)
{
    "use strict";

    /**
     * Constructor function for ImagePacks.
     *
     * @param asset [DOM Element] The asset definition.
     * @param interpreter [WSE.Interpreter] The interpreter object.
     */
    out.assets.Imagepack = function (asset, interpreter)
    {
        var element, images, children, i, len, current, name;
        var src, image, self, triggerDecreaseFn, width, height;

        this.stage = interpreter.stage;
        this.bus = interpreter.bus;
        this.name = asset.getAttribute("name");
        this.id = out.tools.getUniqueId();
        this.cssid = asset.getAttribute("cssid") || "wse_imagepack_" + this.name;
        this.interpreter = interpreter;
        out.tools.applyAssetUnits(this, asset);

        self = this;
        images = {};
        element = document.createElement("div");
        width = asset.getAttribute('width');
        height = asset.getAttribute('height');

        element.style.opacity = 0;
        element.draggable = false;

        element.setAttribute("class", "imagepack");
        element.setAttribute("id", this.cssid);

        element.setAttribute("data-wse-asset-name", this.name);

        children = asset.getElementsByTagName("image");

        triggerDecreaseFn = function ()
        {
            self.bus.trigger("wse.assets.loading.decrease");
        };

        for (i = 0, len = children.length; i < len; i += 1)
        {
            current = children[i];
            name = current.getAttribute("name");
            src = current.getAttribute("src");

            if (name === null)
            {
                this.bus.trigger(
                    "wse.interpreter.warning",
                    {
                        element: asset,
                        message: "Image without name in imagepack '" +
                            this.name + "'."
                    }
                );
                continue;
            }

            if (src === null)
            {
                this.bus.trigger(
                    "wse.interpreter.warning",
                    {
                        element: asset,
                        message: "Image without src in imagepack '" +
                            this.name + "'."
                    }
                );
                continue;
            }

            image = new Image();

            this.bus.trigger("wse.assets.loading.increase");
            out.tools.attachEventListener(image, 'load', triggerDecreaseFn);

            image.src = src;
            image.style.opacity = 0;
            image.style.position = "absolute";
            image.draggable = false;

            image.setAttribute("data-wse-asset-image-name", name);

            if (width !== null)
            {
                image.setAttribute('width', width);
            }

            if (height !== null)
            {
                image.setAttribute('height', height);
            }

            images[name] = this.cssid + "_" + name;
            image.setAttribute("id", images[name]);
            element.appendChild(image);
        }

        element.style.position = "absolute";
        element.style.left = asset.getAttribute("x") || 0;
        element.style.top = asset.getAttribute("y") || 0;
        element.style.zIndex = asset.getAttribute("z") || 0;

        this.images = images;
        this.current = null;

        this.stage.appendChild(element);

        this.bus.trigger("wse.assets.imagepack.constructor", this);
    };

    out.tools.mixin(out.assets.mixins.displayable, out.assets.Imagepack.prototype);

    out.assets.Imagepack.prototype.set = function (command, args)
    {
        var image, name, self, old, duration, isAnimation, bus = this.bus, element;

        args = args || {};
        self = this;
        name = command.getAttribute("image");
        duration = command.getAttribute("duration") || 400;
        isAnimation = args.animation === true ? true : false;

        if (name === null)
        {
            bus.trigger(
                "wse.interpreter.warning",
                {
                    element: command,
                    message: "Missing attribute 'image' on 'do' element " +
                        "referencing imagepack '" + this.name + "'."
                }
            );

            return {
                doNext: true
            };
        }

        try {
            image = document.getElementById(this.images[name]);
        }
        catch (e) {
            console.error("DOM Element for Image " + name + " on Imagepack " + this.name + " not found!", e);
        }

        if (typeof image === "undefined" || image === null)
        {
            bus.trigger(
                "wse.interpreter.warning",
                {
                    element: command,
                    message: "Unknown image name on 'do' element referencing " +
                        "imagepack '" + this.name + "'."
                }
            );

            return {
                doNext: true
            };
        }

        old = this.current;

        for (var key in this.images)
        {
            if (this.images.hasOwnProperty(key))
            {
                if (key !== name)
                {
                    continue;
                }

                if (key === old)
                {
                    bus.trigger(
                        "wse.interpreter.warning",
                        {
                            element: command,
                            message: "Trying to set the image that is " +
                                "already set on imagepack '" + this.name + "'."
                        }
                    );

                    return {
                        doNext: true
                    };
                }
            }
        }

        if (!isAnimation)
        {
            self.interpreter.waitCounter += 1;
        }

        element = document.getElementById(this.cssid);
        element.style.width = image.offsetWidth + "px";
        element.style.height = image.offsetHeight + "px";

        (function ()
        {
            var valFn, finishFn, options;

            valFn = function (v)
            {
                image.style.opacity = v;
            };

            finishFn = function ()
            {
                if (!isAnimation)
                {
                    self.interpreter.waitCounter -= 1;
                }
            };

            options = {
                duration: duration,
                easing: out.fx.easing.easeOutCubic,
                onFinish: finishFn
            };

            out.fx.transform(valFn, 0, 1, options);
        }());

        if (this.current !== null)
        {
            if (!isAnimation)
            {
                self.interpreter.waitCounter += 1;
            }

            (function ()
            {
                var timeoutFn;

                timeoutFn = function()
                {
                    var oldEl, valFn, finishFn, options;

                    oldEl = document.getElementById(self.images[old]);

                    valFn = function (v)
                    {
                        oldEl.style.opacity = v;
                    };

                    finishFn = function ()
                    {
                        if (!isAnimation)
                        {
                            self.interpreter.waitCounter -= 1;
                        }
                    };

                    options = {
                        duration: duration,
                        easing: out.fx.easing.easeInCubic,
                        onFinish: finishFn
                    };

                    out.fx.transform(valFn, 1, 0, options);
                };

                timeoutFn();
            }());
        }

        this.current = name;

        return {
            doNext: true
        };
    };

    out.assets.Imagepack.prototype.save = function ()
    {
        var cur, key, images, name, obj;

        images = this.images;
        cur = this.current || null;
        name = null;

        for (key in images)
        {
            if (images.hasOwnProperty(key))
            {
                if (images[key] === cur)
                {
                    name = key;
                }
            }
        }

        obj = {
            assetType: "Imagepack",
            current: cur,
            cssid: this.cssid,
            images: images,
            z: this.z
        };

        this.bus.trigger(
            "wse.assets.imagepack.save",
            {
                subject: this,
                saves: obj
            }
        );

        return obj;
    };

    out.assets.Imagepack.prototype.restore = function (save)
    {
        var name;

        name = save.current;
        this.cssid = save.cssid;
        this.z = save.z;
        this.current = name;

        document.getElementById(this.cssid).style.zIndex = this.z;

        this.bus.trigger(
            "wse.assets.imagepack.restore",
            {
                subject: this,
                saves: save
            }
        );
    };
}(WSE));<|endoftext|>


<commit_before>var todoList = {
  todos: [],
  addTodo: function(todoText) {
    this.todos.push({
      todoText: todoText,
      completed: false
    });
  },
  changeTodo: function(position, todoText) {
    this.todos[position].todoText = todoText;
  },
  deleteTodo: function(position) {
    this.todos.splice(position, 1);
  },
  toggleCompleted: function(position) {
    var todo = this.todos[position];
    todo.completed = !todo.completed;
  },
  toggleAll: function() {
    var totalTodos = this.todos.length;
    var completedTodos = 0;

    // Get number of completed todos.
    for (var i = 0; i < totalTodos; i++) {
      if (this.todos[i].completed === true) {
        completedTodos++;
      }
    }

    // Case 1: If everything’s true, make everything false.
    if (completedTodos === totalTodos) {
      for (var i = 0; i < totalTodos; i++) {
        this.todos[i].completed = false;
      }
    // Case 2: Otherwise, make everything true.
    } else {
      for (var i = 0; i < totalTodos; i++) {
        this.todos[i].completed = true;
      }
    }
  }
};

var handlers = {
  addTodo: function() {
    var addTodoTextInput = document.getElementById('addTodoTextInput');
    todoList.addTodo(addTodoTextInput.value);
    addTodoTextInput.value = '';
    view.displayTodos();
  },
  changeTodo: function() {
    var changeTodoPositionInput = document.getElementById('changeTodoPositionInput');
    var changeTodoTextInput = document.getElementById('changeTodoTextInput');
    todoList.changeTodo(changeTodoPositionInput.valueAsNumber, changeTodoTextInput.value);
    changeTodoPositionInput.value = '';
    changeTodoTextInput.value = '';
    view.displayTodos();
  },
  deleteTodo: function(position) {
    todoList.deleteTodo(position);
    view.displayTodos();
  },
  toggleCompleted: function() {
    var toggleCompletedPositionInput = document.getElementById('toggleCompletedPositionInput');
    todoList.toggleCompleted(toggleCompletedPositionInput.valueAsNumber);
    toggleCompletedPositionInput.value = '';
    view.displayTodos();
  },
  toggleAll: function() {
    todoList.toggleAll();
    view.displayTodos();
  }
};

var view = {
  displayTodos: function() {
    var todosUl = document.querySelector('ul');
    todosUl.innerHTML = '';
    for (var i = 0; i < todoList.todos.length; i++) {
      var todoLi = document.createElement('li');
      var todo = todoList.todos[i];
      var todoTextWithCompletion = '';

      if (todo.completed === true) {
        todoTextWithCompletion = '(x) ' + todo.todoText;
      } else {
        todoTextWithCompletion = '( ) ' + todo.todoText;
      }

      todoLi.id = i;
      todoLi.textContent = todoTextWithCompletion;
      todoLi.appendChild(this.createDeleteButton());
      todosUl.appendChild(todoLi);
    }
  },
  createDeleteButton: function() {
    var deleteButton = document.createElement('button');

    deleteButton.textContent = 'Delete';
    deleteButton.className = 'deleteButton';
    return deleteButton;
  },
  setupEventListeners: function() {
    var todosUl = document.querySelector('ul');

    todosUl.addEventListener('click', function(event) {
      var elementClicked = event.target;

      if (elementClicked.className === 'deleteButton') {
        handlers.deleteTodo(parseInt(elementClicked.parentNode.id));
      }
    });
  }
};

view.setupEventListeners();
<commit_msg>🚴🐏 Updated with Glitch<commit_after>var todoList = {
  todos: [],
  addTodo: function(todoText) {
    this.todos.push({
      todoText: todoText,
      completed: false
    });
  },
  changeTodo: function(position, todoText) {
    this.todos[position].todoText = todoText;
  },
  deleteTodo: function(position) {
    this.todos.splice(position, 1);
  },
  toggleCompleted: function(position) {
    var todo = this.todos[position];
    todo.completed = !todo.completed;
  },
  toggleAll: function() {
    var totalTodos = this.todos.length;
    var completedTodos = 0;

    // Get number of completed todos.
    this.todos.forEach(function(todo) {
      if (todo.completed === true) {
        completedTodos++
      }
    });

    this.todos.forEach(function(todo) {
      if (completedTodos === totalTodos) {
        // Case 1: If everything’s true, make everything false.
        todo.completed = false;
      } else {
        // Case 2: Otherwise, make everything true.
        todo.completed = true;
      }
    });
  }
};

var handlers = {
  addTodo: function() {
    var addTodoTextInput = document.getElementById('addTodoTextInput');
    todoList.addTodo(addTodoTextInput.value);
    addTodoTextInput.value = '';
    view.displayTodos();
  },
  changeTodo: function() {
    var changeTodoPositionInput = document.getElementById('changeTodoPositionInput');
    var changeTodoTextInput = document.getElementById('changeTodoTextInput');
    todoList.changeTodo(changeTodoPositionInput.valueAsNumber, changeTodoTextInput.value);
    changeTodoPositionInput.value = '';
    changeTodoTextInput.value = '';
    view.displayTodos();
  },
  deleteTodo: function(position) {
    todoList.deleteTodo(position);
    view.displayTodos();
  },
  toggleCompleted: function() {
    var toggleCompletedPositionInput = document.getElementById('toggleCompletedPositionInput');
    todoList.toggleCompleted(toggleCompletedPositionInput.valueAsNumber);
    toggleCompletedPositionInput.value = '';
    view.displayTodos();
  },
  toggleAll: function() {
    todoList.toggleAll();
    view.displayTodos();
  }
};

var view = {
  displayTodos: function() {
    var todosUl = document.querySelector('ul');
    todosUl.innerHTML = '';
    todoList.todos.forEach(function(todo, position) {
      var todoLi = document.createElement('li');
      var todoTextWithCompletion = '';

      if (todo.completed === true) {
        todoTextWithCompletion = '(x) ' + todo.todoText;
      } else {
        todoTextWithCompletion = '( ) ' + todo.todoText;
      }

      todoLi.id = position;
      todoLi.textContent = todoTextWithCompletion;
      todoLi.appendChild(this.createDeleteButton());
      todosUl.appendChild(todoLi);
    }, this);
  },
  createDeleteButton: function() {
    var deleteButton = document.createElement('button');

    deleteButton.textContent = 'Delete';
    deleteButton.className = 'deleteButton';
    return deleteButton;
  },
  setupEventListeners: function() {
    var todosUl = document.querySelector('ul');

    todosUl.addEventListener('click', function(event) {
      var elementClicked = event.target;

      if (elementClicked.className === 'deleteButton') {
        handlers.deleteTodo(parseInt(elementClicked.parentNode.id));
      }
    });
  }
};

view.setupEventListeners();
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var $ = require('jquery');

var AdminView = Backbone.View.extend({
	el: $("#linksf-admin"),
	template: require('templates/login'),
	render: function() {
		$(this.el).html(this.template({ name: 'arf arf arf' }));
		return this;
	}
});

module.exports = AdminView;
<commit_msg>cleanup<commit_after>var Backbone = require('backbone'),
    $ = require('jquery');

var AdminView = Backbone.View.extend({
	el: $("#linksf-admin"),
	template: require('templates/login'),
	render: function() {
		$(this.el).html(this.template({ name: 'arf arf arf' }));
		return this;
	}
});

module.exports = AdminView;
<|endoftext|>


<commit_before>var width   = 1200;
var height  = 600;
var imageWidth = 30;
var imageHeight = 50;
var img= new Image();
var view_radius = 130;
var view_angle = Math.PI * 0.33;
img.src = "https://image.ibb.co/bKH1ak/turlte4real.png";

function draw_circle(context, x, y) {
    context.beginPath();
    context.arc(x, y, 10, 0, 2 * Math.PI, false);
    context.closePath();
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();
}

function draw_turtle(context, x, y, angle) {
  context.save();

  //Set the origin to the center of the image
  context.translate(x, y);
  //Rotate the canvas around the origin
  context.rotate(angle);
  //draw the image
  context.drawImage(img,imageWidth / 2 * (-1),imageHeight / 2 * (-1),imageWidth,imageHeight);

  context.restore();
}

function transpose_point(x, y, originX, originY, theta) {
    x = x - originX;
    y = y - originY;
    var newX = (Math.cos(theta) * x) - (Math.sin(theta) * y);
    var newY = (Math.sin(theta) * x) + (Math.cos(theta) * y);
    return {x: newX + originX, y: newY + originY};
}

function point_in_range(character, x, y) {
    var xDistance = x - character.pos.x;
    var yDistance = y - character.pos.y;
    var distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);

    var character_direction = characterAngle(character);
    var point_angle = pointToAngle(x, y, character.pos.x, character.pos.y);

    var facing_player = (point_angle >= (character_direction - view_angle));
    facing_player &= (point_angle <= (character_direction + view_angle));

    return (distance <= view_radius) && facing_player;
}

function draw_view(canvas, character) {
    canvas.globalCompositeOperation = "destination-out";
    var mouseX = character.move_to.x;
    var mouseY = character.move_to.y;
    var character_direction = characterAngle(character);

    var w = mouseX - character.pos.x;
    var h = mouseY - character.pos.y;
    var hypo = Math.sqrt((w * w) + (h * h));

    var xratio = w / hypo;
    var yratio = h / hypo;

    var arcCenterX = character.pos.x + (xratio * view_radius);
    var arcCenterY = character.pos.y + (yratio * view_radius);

    var arcS = character_direction - view_angle;
    var arcE = character_direction + view_angle;

    var left = transpose_point(arcCenterX, arcCenterY, character.pos.x, character.pos.y, view_angle);
    var right = transpose_point(arcCenterX, arcCenterY, character.pos.x, character.pos.y, -view_angle);
    canvas.beginPath();
    canvas.arc(character.pos.x, character.pos.y, view_radius, arcS, arcE, false);
    canvas.moveTo(character.pos.x, character.pos.y);
    canvas.lineTo(left.x, left.y);
    canvas.lineTo(right.x, right.y);
    canvas.lineTo(character.pos.x, character.pos.y)
    canvas.closePath();
    canvas.fillStyle = 'black';
    canvas.fill();
    canvas.lineWidth = 1;
    canvas.strokeStyle = '#000000';
    canvas.stroke();

    canvas.globalCompositeOperation = "source-over";
}

function move_character(character, new_x, new_y) {
    if (new_x >= width) {
        character.pos.x = width;
    } else if (new_x <= -100) {
        character.pos.x = 0;
    } else {
        character.pos.x = new_x;
    }

    if (new_y >= height) {
        character.pos.y = height;
    } else if (new_y <= -100) {
        character.pos.y = 0;
    } else {
        character.pos.y = new_y;
    }
}

function move_character_towards_cursor(character, mouseX, mouseY){
   character.pos.angle = pointToAngle(mouseX, mouseY, character.pos.x, character.pos.y) + 1.5708
   character.move_to.x = mouseX;
   character.move_to.y = mouseY;
   var xDistance = mouseX - character.pos.x;
   var yDistance = mouseY - character.pos.y;
   var distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);
   if (distance > 1) {
        var new_pos_x = character.pos.x + xDistance * 0.015;
        var new_pos_y = character.pos.y + yDistance * 0.015;
        move_character(character, new_pos_x, new_pos_y);
   }

}

function pointToAngle(x, y, originX, originY) {
    var dx = x - originX;
    var dy = y - originY;
    var theta = Math.atan2(dy, dx);
    if (theta < 0) {
        theta += (2 * Math.PI);
    }
    return theta;
}

function characterAngle(character) {
    var mouseX = character.move_to.x;
    var mouseY = character.move_to.y;
    return pointToAngle(mouseX, mouseY, character.pos.x, character.pos.y);
}

document.addEventListener("DOMContentLoaded", function() {
    // get canvas element and create context
    var canvas  = document.getElementById('game');
    var scoreBoard  = document.getElementById('score');
    var context = canvas.getContext('2d');
    var socket  = io.connect();

    // set canvas to full browser width/height
    canvas.width = width;
    canvas.height = height;

    var character = {
        move_to:{x:0,y:0},
        move: false,
        id: false,
        pos: {x:0, y:0, angle: 0}
    };

    canvas.onmousemove = function(e) {
        var rect = document.getElementById('game').getBoundingClientRect();
        var mouseX = e.clientX - rect.left;
        var mouseY = e.clientY - rect.top;
        move_character_towards_cursor(character, mouseX, mouseY);
        character.move = true;
    };

    canvas.onmousedown = function(e) {
        var rect = document.getElementById('game').getBoundingClientRect();

        var mouseX = e.clientX - rect.left;
        var mouseY = e.clientY - rect.top;
        var attack_radius = 80.0;
        var w = mouseX - character.pos.x;
        var h = mouseY - character.pos.y;
        var hypo = Math.sqrt((w * w) + (h * h));

        var xratio = w / hypo;
        var yratio = h / hypo;

        var attackX = character.pos.x + (xratio * attack_radius);
        var attackY = character.pos.y + (yratio * attack_radius);

        var attack_position = {x: attackX, y: attackY};

        var attack = {id: character.id, attack: attack_position, type: 'A'};
        socket.emit('attack', attack);
    };

    // draw line received from server
    socket.on('update_characters', function (all_characters) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = 'black';
        context.fill();
        context.strokeStyle = '#000000';
        context.stroke();

        draw_view(context, character);
        // Draw myself.
        draw_turtle(context, character.pos.x, character.pos.y, character.pos.angle);
        for (var i in all_characters) {
            other = all_characters[i];
            if (i != character.id && point_in_range(character, other.x, other.y)) {
                draw_turtle(context, other.x, other.y, other.angle);
            }
            if (i == character.id) {
              scoreBoard.innerHTML = all_characters[i].score.toString();
            }
            console.log("id: " + i + " // angle: " + all_characters[i].angle.toString());
        }
    });

    socket.on('character_died', function () {
        window.location = 'https://yourwaifuisshit.com';
    });

    // main loop, running every 25ms
    function mainLoop() {
        if (character.move) {
            move_character_towards_cursor(character,character.move_to.x,character.move_to.y);
        }

        if (character.id) {
            socket.emit('move_character', character);
        }

        setTimeout(mainLoop, 25);
    }

    socket.on('init_character', function(data) {
        character.id = data.id;
        character.pos.x = data.pos.x;
        character.pos.y = data.pos.y;
        character.pos.angle = data.pos.angle;
        mainLoop();
    });
});
<commit_msg>the holy viewport algorithm<commit_after>var width   = 1200;
var height  = 600;
var imageWidth = 30;
var imageHeight = 50;
var img= new Image();
var view_radius = 130;
var view_angle = Math.PI * 0.33;
img.src = "https://image.ibb.co/bKH1ak/turlte4real.png";

function draw_circle(context, x, y) {
    context.beginPath();
    context.arc(x, y, 10, 0, 2 * Math.PI, false);
    context.closePath();
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();
}

function draw_turtle(context, x, y, angle) {
  context.save();

  //Set the origin to the center of the image
  context.translate(x, y);
  //Rotate the canvas around the origin
  context.rotate(angle);
  //draw the image
  context.drawImage(img,imageWidth / 2 * (-1),imageHeight / 2 * (-1),imageWidth,imageHeight);

  context.restore();
}

function transpose_point(x, y, originX, originY, theta) {
    x = x - originX;
    y = y - originY;
    var newX = (Math.cos(theta) * x) - (Math.sin(theta) * y);
    var newY = (Math.sin(theta) * x) + (Math.cos(theta) * y);
    return {x: newX + originX, y: newY + originY};
}

function point_in_range(character, x, y) {
    var xDistance = x - character.pos.x;
    var yDistance = y - character.pos.y;
    var distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);

    var character_direction = characterAngle(character);
    var point_angle = pointToAngle(x, y, character.pos.x, character.pos.y);

    var facing_player = (point_angle >= (character_direction - view_angle));
    facing_player &= (point_angle <= (character_direction + view_angle));

    return (distance <= view_radius) && facing_player;
}

function draw_view(canvas, character) {
    canvas.globalCompositeOperation = "destination-out";
    var mouseX = character.move_to.x;
    var mouseY = character.move_to.y;
    var character_direction = characterAngle(character);

    var w = mouseX - character.pos.x;
    var h = mouseY - character.pos.y;
    var hypo = Math.sqrt((w * w) + (h * h));

    var xratio = w / hypo;
    var yratio = h / hypo;

    var arcCenterX = character.pos.x + (xratio * view_radius);
    var arcCenterY = character.pos.y + (yratio * view_radius);

    var arcS = character_direction - view_angle;
    var arcE = character_direction + view_angle;

    var left = transpose_point(arcCenterX, arcCenterY, character.pos.x, character.pos.y, view_angle);
    var right = transpose_point(arcCenterX, arcCenterY, character.pos.x, character.pos.y, -view_angle);
    canvas.beginPath();
    canvas.arc(character.pos.x, character.pos.y, view_radius, arcS, arcE, false);
    canvas.moveTo(character.pos.x, character.pos.y);
    canvas.lineTo(left.x, left.y);
    canvas.lineTo(right.x, right.y);
    canvas.lineTo(character.pos.x, character.pos.y)
    canvas.closePath();
    canvas.fillStyle = 'black';
    canvas.fill();
    canvas.lineWidth = 1;
    canvas.strokeStyle = '#000000';
    canvas.stroke();

    canvas.globalCompositeOperation = "source-over";
}

function move_character(character, new_x, new_y, viewOrigin) {
    console.log("new_x: " + viewOrigin.left.toString() + " new_y: " + viewOrigin.top.toString());
    // X
    if ((new_x < 1000) && (new_x > 200)) {
        character.pos.x = new_x;
    }
    else if ((new_x >= 1000) && ((viewOrigin.left + 1200) + (new_x - character.pos.x) < 2400)) {
        character.pos.x = 1000;
        viewOrigin.left += new_x - character.pos.x;
    }
    else if ((new_x <= 200) && (viewOrigin.left - (new_x - character.pos.x) > 0)) {
        character.pos.x = 200;
        viewOrigin.left -= character.pos.x - new_x;
    }
    else if ((new_x >= 1000) && ((viewOrigin.left + 1200) + (new_x - character.pos.x) >= 2400)) {
        character.pos.x = new_x - (1200 - viewOrigin.left);
        viewOrigin.left = 1200;
    }
    else if ((new_x <= 200) && (viewOrigin.left - (new_x - character.pos.x) <= 0)) {
        character.pos.x = new_x - viewOrigin.left ;
        viewOrigin.left = 0;
    }

    // Y
    if ((new_y < 400) && (new_y > 200)) {
        character.pos.y = new_y;
    }
    else if ((new_y >= 400) && ((viewOrigin.top + 600) + (new_y - character.pos.y) < 1200)) {
        character.pos.y = 400;
        viewOrigin.top += new_y - character.pos.y;
    }
    else if ((new_y <= 200) && (viewOrigin.top - (new_y - character.pos.y) > 0)) {
        character.pos.y = 200;
        viewOrigin.top -= character.pos.y - new_y;
    }
    else if ((new_y >= 400) && ((viewOrigin.top + 600) + (new_y - character.pos.y) >= 1200)) {
        character.pos.y = new_y - (600 - viewOrigin.top);
        viewOrigin.top = 1200;
    }
    else if ((new_y <= 200) && (viewOrigin.top - (new_y - character.pos.y) <= 0)) {
        character.pos.y = new_y - viewOrigin.top ;
        viewOrigin.top = 0;
    }

    //
    // if (new_x >= width) {
    //     character.pos.x = width;
    // } else if (new_x <= -100) {
    //     character.pos.x = 0;
    // } else {
    //     character.pos.x = new_x;
    // }
    //
    //
    // // Y
    // if (new_y >= height) {
    //     character.pos.y = height;
    // } else if (new_y <= -100) {
    //     character.pos.y = 0;
    // } else {
    //     character.pos.y = new_y;
    // }
}

function move_character_towards_cursor(character, mouseX, mouseY, viewOrigin){
   character.pos.angle = pointToAngle(mouseX, mouseY, character.pos.x, character.pos.y) + 1.5708
   character.move_to.x = mouseX;
   character.move_to.y = mouseY;
   var xDistance = mouseX - character.pos.x;
   var yDistance = mouseY - character.pos.y;
   var distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);
   if (distance > 1) {
        var new_pos_x = character.pos.x + xDistance * 0.015;
        var new_pos_y = character.pos.y + yDistance * 0.015;
        move_character(character, new_pos_x, new_pos_y, viewOrigin);
   }

}

function pointToAngle(x, y, originX, originY) {
    var dx = x - originX;
    var dy = y - originY;
    var theta = Math.atan2(dy, dx);
    if (theta < 0) {
        theta += (2 * Math.PI);
    }
    return theta;
}

function characterAngle(character) {
    var mouseX = character.move_to.x;
    var mouseY = character.move_to.y;
    return pointToAngle(mouseX, mouseY, character.pos.x, character.pos.y);
}

document.addEventListener("DOMContentLoaded", function() {
    // get canvas element and create context
    var canvas  = document.getElementById('game');
    var scoreBoard  = document.getElementById('score');
    var context = canvas.getContext('2d');
    var socket  = io.connect();

    // set canvas to full browser width/height
    canvas.width = width;
    canvas.height = height;

    var character = {
        move_to:{x:0,y:0},
        move: false,
        id: false,
        pos: {x:0, y:0, angle: 0}
    };

    var viewOrigin = {
        top:0,
        left:0
    }

    canvas.onmousemove = function(e) {
        var rect = document.getElementById('game').getBoundingClientRect();
        var mouseX = e.clientX - rect.left;
        var mouseY = e.clientY - rect.top;
        move_character_towards_cursor(character, mouseX, mouseY, viewOrigin);
        character.move = true;
    };

    canvas.onmousedown = function(e) {
        var rect = document.getElementById('game').getBoundingClientRect();

        var mouseX = e.clientX - rect.left;
        var mouseY = e.clientY - rect.top;
        var attack_radius = 80.0;
        var w = mouseX - character.pos.x;
        var h = mouseY - character.pos.y;
        var hypo = Math.sqrt((w * w) + (h * h));

        var xratio = w / hypo;
        var yratio = h / hypo;

        var attackX = character.pos.x + (xratio * attack_radius);
        var attackY = character.pos.y + (yratio * attack_radius);

        var attack_position = {x: attackX+viewOrigin.left, y: attackY+viewOrigin.top};

        var attack = {id: character.id, attack: attack_position, type: 'A'};
        socket.emit('attack', attack);
    };

    // draw line received from server
    socket.on('update_characters', function (all_characters) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = 'black';
        context.fill();
        context.strokeStyle = '#000000';
        context.stroke();

        draw_view(context, character);
        // Draw myself.
        draw_turtle(context, character.pos.x - viewOrigin.left, character.pos.y - viewOrigin.top, character.pos.angle);
        for (var i in all_characters) {
            other = all_characters[i];
            other.x -= viewOrigin.left;
            other.y -= viewOrigin.top;
            if (i != character.id && point_in_range(character, other.x, other.y)) {
                draw_turtle(context, other.x, other.y, other.angle);
            }
            if (i == character.id) {
              scoreBoard.innerHTML = all_characters[i].score.toString();
            }
        }
    });

    socket.on('character_died', function () {
        window.location = 'https://yourwaifuisshit.com';
    });

    // main loop, running every 25ms
    function mainLoop() {
        if (character.move) {
            move_character_towards_cursor(character,character.move_to.x,character.move_to.y, viewOrigin);
        }

        if (character.id) {
            var correctedCharacter = character;
            correctedCharacter.pos.x += viewOrigin.left;
            correctedCharacter.pos.y += viewOrigin.top;
            socket.emit('move_character', correctedCharacter);
        }

        setTimeout(mainLoop, 25);
    }

    socket.on('init_character', function(data) {
        character.id = data.id;
        character.pos.x = data.pos.x;
        character.pos.y = data.pos.y;
        character.pos.angle = data.pos.angle;
        mainLoop();
    });
});
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();

    fetchProjectStructure();

    $(".savePageBtn").click(function(){

    });
}

function fetchProjectScore()
{
    $.getJSON("/api/projectscore/" + projectid + "/" + studentid + "/currentuser", function(data)
    {
        console.log(data);
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description, 0));
                });
            });
        })
    });

    fetchProjectScore();
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, score) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        score: ko.observable(score)
    };
}<commit_msg>save/get project score<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();

    fetchProjectStructure()
    fetchProjectScore();

    $(".savePageBtn").click(function(){

    });
}

function fetchProjectScore()
{
    $.getJSON("/api/projectscore/" + projectid + "/" + studentid + "/currentuser", function(data)
    {
        console.log(data);
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description, 0));
                });
            });
        })
    });
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, score) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        score: ko.observable(score)
    };
}<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
/**
 * Defines support rules related to the view.
 */
sap.ui.define(["jquery.sap.global", "sap/ui/support/library"],
	function(jQuery, SupportLib) {
	"use strict";

	// shortcuts
	var Categories = SupportLib.Categories; // Accessibility, Performance, Memory, ...
	var Severity = SupportLib.Severity; // Hint, Warning, Error
	var Audiences = SupportLib.Audiences; // Control, Internal, Application

	//**********************************************************
	// Rule Definitions
	//**********************************************************

	/**
	 * Checks for wrongly configured view namespace
	 */
	var oXMLViewWrongNamespace = {
		id: "XMLViewWrongNamespace",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		title: "XML View is not configured with namespace 'sap.ui.core.mvc'",
		description: "For consistency and proper resource loading, the root node of an XML view must be configured with the namespace 'mvc'",
		resolution: "Define the XML view as '<core:View ...>' and configure the XML namepspace as 'xmlns:mvc=\"sap.ui.core.mvc\"'",
		resolutionurls: [{
			text: "Documentation: Namespaces in XML Views",
			href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });
			aXMLViews.forEach(function (oXMLView) {
				if (oXMLView._xContent.namespaceURI !== "sap.ui.core.mvc") {
					var sViewName = oXMLView.getViewName().split("\.").pop();
					oIssueManager.addIssue({
						severity: Severity.Medium,
						details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") is configured with namespace '" + oXMLView._xContent.namespaceURI + "' instead of 'sap.ui.core.mvc'",
						context: {
							id: oXMLView.getId()
						}
					});
				}
			});
		}
	};

	/**
	 * Checks if a default namespaces is set in an XML view
	 */
	var oXMLViewDefaultNamespace = {
		id: "XMLViewDefaultNamespace",
		audiences: [Audiences.Control, Audiences.Application],
		categories: [Categories.Performance],
		enabled: true,
		title: "Default namespace missing in XML view",
		description: "If the default namespace is missing, the code is less readable and parsing performance may be slow",
		resolution: "Set the namespace of the control library that holds most of the controls you use as default namespace (e.g. xmlns=\"sap.m\")",
		resolutionurls: [{
			text: "Documentation: Namespaces in XML Views",
			href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

			aXMLViews.forEach(function (oXMLView) {
				if (!oXMLView._xContent.attributes.getNamedItem("xmlns")) {
					var sViewName = oXMLView.getViewName().split("\.").pop();
					oIssueManager.addIssue({
						severity: Severity.Low,
						details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") does not contain a default namespace",
						context: {
							id: oXMLView.getId()
						}
					});
				}
			});
		}
	};

	var oXMLViewLowerCaseControl = {
		id: "XMLViewLowerCaseControl",
		audiences: ["Control","Application"],
		categories: ["Performance"],
		enabled: true,
		title: "Control tag in XML view starts with lower case",
		description: "Control tags with lower case cannot be loaded in Linux-based systems",
		resolution: "Start the Control tag with upper case",
		resolutionurls: [],
		check: function (oIssueManager, oCoreFacade, oScope) {

			//get all aggregations of each element
			var aAggregationsOfElements = oScope.getElements().map(
					function (oElement) {
						return Object.keys(oElement.getMetadata().getAllAggregations());
					}
			);
			//flatten array of arrays and filter duplicates
			var aAggregations = aAggregationsOfElements.reduce(
				function(a, b) {
					return a.concat(b);
				}).filter(
					function (x, i, a) {
						return a.indexOf(x) === i;
					});

			var aXMLViews = oScope.getElements().filter(function (oControl) {
				return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView";
			});

			aXMLViews.forEach(function (oXMLView) {
				var aLocalName = [];
				var _getTags = function (oXcontent) {
					aLocalName.push(oXcontent.localName);
					for (var i = 0; i < oXcontent.children.length; i++) {
						_getTags(oXcontent.children[i]);
					}
				};

				_getTags(oXMLView._xContent);
				aLocalName = jQuery.uniqueSort(aLocalName);

				aLocalName.forEach(function (sTag) 	{
					var sFirstLetter = sTag.charAt(0);
					// check for lowercase, aggregations are excluded
					if ((sFirstLetter.toLowerCase() === sFirstLetter) && !aAggregations.includes(sTag)) {
						var sViewName = oXMLView.getViewName().split("\.").pop();
						oIssueManager.addIssue({
							severity: Severity.High,
							details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains a Control tag that starts with lower case '" + sTag + "'",
							context: {
								id: oXMLView.getId()
							}
						});
					}
				});
			});
		}
	};

	/**
	 * Checks for unused namespaces inside an XML view
	 */
	var oXMLViewUnusedNamespaces = {
		id: "XMLViewUnusedNamespaces",
		audiences: [Audiences.Control, Audiences.Application],
		categories: [Categories.Performance],
		enabled: true,
		title: "Unused namespaces in XML view",
		description: "Namespaces that are declared but not used have a negative impact on performance (and may confuse readers of the code)",
		resolution: "Remove the unused namespaces from the view definition",
		resolutionurls: [{
			text: "Documentation: Namespaces in XML Views",
			href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

			aXMLViews.forEach(function (oXMLView) {
				for (var i = 0; i < oXMLView._xContent.attributes.length; i++) {
					var sName = oXMLView._xContent.attributes.item(i).name;
					var sLocalName = oXMLView._xContent.attributes.item(i).localName;
					var sFullName = oXMLView._xContent.attributes.item(i).value;

					// check all explicit namespaces except for the injected support namespace
					// and the mvc, because the use of mvc is checked in other rule
					if (sName.match("xmlns:")
						&& sLocalName !== "xmlns:support"
						&& sLocalName !== "mvc") {
						for (var j = 0; j < oXMLView._xContent.children.length; j++) {
							var sContent = oXMLView._xContent.children[j].outerHTML;

							// check if there is a reference of this namespace inside the view
							if (!sContent.match("<" + sLocalName + ":")) {
								var sViewName = oXMLView.getViewName().split("\.").pop();
								oIssueManager.addIssue({
									severity: Severity.Error,
									details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains an unused XML namespace '" + sLocalName + "' referencing library '" + sFullName + "'",
									context: {
										id: oXMLView.getId()
									}
								});
							}
						}
					}
				}
			});
		}
	};

	/**
	 * Checks for deprecated properties
	 */
	var oDeprecatedPropertyRule = {
		id: "deprecatedProperty",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated property",
		description: "Using deprecated properties should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which property should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mProperties = oMetadata.getAllProperties();

					for (var sProperty in mProperties) {
						// if property is deprecated and it is set to a different from the default value
						// Checks only the deprecated properties with defaultValue property is not null
						if (mProperties[sProperty].deprecated
							&& mProperties[sProperty].defaultValue != oElement.getProperty(sProperty)
							&& mProperties[sProperty].defaultValue !== null) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated property '" + sProperty + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	/**
	 * Checks for deprecated aggregations
	 */
	var oDeprecatedAggregationRule = {
		id: "deprecatedAggregation",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated aggregation",
		description: "Using deprecated aggregation should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which aggregation should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mAggregations = oMetadata.getAllAggregations();

					for (var sAggregation in mAggregations) {
						// if aggregation is deprecated and contains elements
						if (mAggregations[sAggregation].deprecated
							&& !jQuery.isEmptyObject(oElement.getAggregation(sAggregation))) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated aggregation '" + sAggregation + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	/**
	 * Checks for deprecated associations
	 */
	var oDeprecatedAssociationRule = {
		id: "deprecatedAssociation",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated association",
		description: "Using deprecated association should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which association should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mAssociations = oMetadata.getAllAssociations();

					for (var sAssociation in mAssociations) {
						// if association is deprecated and set by developer
						if (mAssociations[sAssociation].deprecated
							&& !jQuery.isEmptyObject(oElement.getAssociation(sAssociation))) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated association '" + sAssociation + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	/**
	 * Checks for deprecated events
	 */
	var oDeprecatedEventRule = {
		id: "deprecatedEvent",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated event",
		description: "Using deprecated event should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which event should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mEvents = oMetadata.getAllEvents();

					for (var sEvent in mEvents) {
						// if event is deprecated and developer added event handler
						if (mEvents[sEvent].deprecated
							&& oElement.mEventRegistry[sEvent] && oElement.mEventRegistry[sEvent].length > 0) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated event '" + sEvent + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	return [
		oXMLViewWrongNamespace,
		oXMLViewDefaultNamespace,
		oXMLViewLowerCaseControl,
		oXMLViewUnusedNamespaces,
		oDeprecatedPropertyRule,
		oDeprecatedAggregationRule,
		oDeprecatedAssociationRule,
		oDeprecatedEventRule
	];
}, true);
<commit_msg>[INTERNAL] sap.ui.support: xmlViewWrongNamespace rule has been changed<commit_after>/*!
 * ${copyright}
 */
/**
 * Defines support rules related to the view.
 */
sap.ui.define(["jquery.sap.global", "sap/ui/support/library"],
	function(jQuery, SupportLib) {
	"use strict";

	// shortcuts
	var Categories = SupportLib.Categories; // Accessibility, Performance, Memory, ...
	var Severity = SupportLib.Severity; // Hint, Warning, Error
	var Audiences = SupportLib.Audiences; // Control, Internal, Application

	//**********************************************************
	// Rule Definitions
	//**********************************************************

	/**
	 * Checks for wrongly configured view namespace
	 */
	var oXMLViewWrongNamespace = {
		id: "xmlViewWrongNamespace",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "-",
		title: "XML View is not configured with namespace 'sap.ui.core.mvc'",
		description: "For consistency and proper resource loading, the root node of an XML view must be configured with the namespace 'mvc'",
		resolution: "Define the XML view as '<core:View ...>' and configure the XML namepspace as 'xmlns:mvc=\"sap.ui.core.mvc\"'",
		resolutionurls: [{
			text: "Documentation: Namespaces in XML Views",
			href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });
			aXMLViews.forEach(function (oXMLView) {
				if (oXMLView._xContent.namespaceURI !== "sap.ui.core.mvc") {
					var sViewName = oXMLView.getViewName().split("\.").pop();
					oIssueManager.addIssue({
						severity: Severity.Medium,
						details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") is configured with namespace '" + oXMLView._xContent.namespaceURI + "' instead of 'sap.ui.core.mvc'",
						context: {
							id: oXMLView.getId()
						}
					});
				}
			});
		}
	};

	/**
	 * Checks if a default namespaces is set in an XML view
	 */
	var oXMLViewDefaultNamespace = {
		id: "XMLViewDefaultNamespace",
		audiences: [Audiences.Control, Audiences.Application],
		categories: [Categories.Performance],
		enabled: true,
		title: "Default namespace missing in XML view",
		description: "If the default namespace is missing, the code is less readable and parsing performance may be slow",
		resolution: "Set the namespace of the control library that holds most of the controls you use as default namespace (e.g. xmlns=\"sap.m\")",
		resolutionurls: [{
			text: "Documentation: Namespaces in XML Views",
			href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

			aXMLViews.forEach(function (oXMLView) {
				if (!oXMLView._xContent.attributes.getNamedItem("xmlns")) {
					var sViewName = oXMLView.getViewName().split("\.").pop();
					oIssueManager.addIssue({
						severity: Severity.Low,
						details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") does not contain a default namespace",
						context: {
							id: oXMLView.getId()
						}
					});
				}
			});
		}
	};

	var oXMLViewLowerCaseControl = {
		id: "XMLViewLowerCaseControl",
		audiences: ["Control","Application"],
		categories: ["Performance"],
		enabled: true,
		title: "Control tag in XML view starts with lower case",
		description: "Control tags with lower case cannot be loaded in Linux-based systems",
		resolution: "Start the Control tag with upper case",
		resolutionurls: [],
		check: function (oIssueManager, oCoreFacade, oScope) {

			//get all aggregations of each element
			var aAggregationsOfElements = oScope.getElements().map(
					function (oElement) {
						return Object.keys(oElement.getMetadata().getAllAggregations());
					}
			);
			//flatten array of arrays and filter duplicates
			var aAggregations = aAggregationsOfElements.reduce(
				function(a, b) {
					return a.concat(b);
				}).filter(
					function (x, i, a) {
						return a.indexOf(x) === i;
					});

			var aXMLViews = oScope.getElements().filter(function (oControl) {
				return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView";
			});

			aXMLViews.forEach(function (oXMLView) {
				var aLocalName = [];
				var _getTags = function (oXcontent) {
					aLocalName.push(oXcontent.localName);
					for (var i = 0; i < oXcontent.children.length; i++) {
						_getTags(oXcontent.children[i]);
					}
				};

				_getTags(oXMLView._xContent);
				aLocalName = jQuery.uniqueSort(aLocalName);

				aLocalName.forEach(function (sTag) 	{
					var sFirstLetter = sTag.charAt(0);
					// check for lowercase, aggregations are excluded
					if ((sFirstLetter.toLowerCase() === sFirstLetter) && !aAggregations.includes(sTag)) {
						var sViewName = oXMLView.getViewName().split("\.").pop();
						oIssueManager.addIssue({
							severity: Severity.High,
							details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains a Control tag that starts with lower case '" + sTag + "'",
							context: {
								id: oXMLView.getId()
							}
						});
					}
				});
			});
		}
	};

	/**
	 * Checks for unused namespaces inside an XML view
	 */
	var oXMLViewUnusedNamespaces = {
		id: "XMLViewUnusedNamespaces",
		audiences: [Audiences.Control, Audiences.Application],
		categories: [Categories.Performance],
		enabled: true,
		title: "Unused namespaces in XML view",
		description: "Namespaces that are declared but not used have a negative impact on performance (and may confuse readers of the code)",
		resolution: "Remove the unused namespaces from the view definition",
		resolutionurls: [{
			text: "Documentation: Namespaces in XML Views",
			href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

			aXMLViews.forEach(function (oXMLView) {
				for (var i = 0; i < oXMLView._xContent.attributes.length; i++) {
					var sName = oXMLView._xContent.attributes.item(i).name;
					var sLocalName = oXMLView._xContent.attributes.item(i).localName;
					var sFullName = oXMLView._xContent.attributes.item(i).value;

					// check all explicit namespaces except for the injected support namespace
					// and the mvc, because the use of mvc is checked in other rule
					if (sName.match("xmlns:")
						&& sLocalName !== "xmlns:support"
						&& sLocalName !== "mvc") {
						for (var j = 0; j < oXMLView._xContent.children.length; j++) {
							var sContent = oXMLView._xContent.children[j].outerHTML;

							// check if there is a reference of this namespace inside the view
							if (!sContent.match("<" + sLocalName + ":")) {
								var sViewName = oXMLView.getViewName().split("\.").pop();
								oIssueManager.addIssue({
									severity: Severity.Error,
									details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains an unused XML namespace '" + sLocalName + "' referencing library '" + sFullName + "'",
									context: {
										id: oXMLView.getId()
									}
								});
							}
						}
					}
				}
			});
		}
	};

	/**
	 * Checks for deprecated properties
	 */
	var oDeprecatedPropertyRule = {
		id: "deprecatedProperty",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated property",
		description: "Using deprecated properties should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which property should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mProperties = oMetadata.getAllProperties();

					for (var sProperty in mProperties) {
						// if property is deprecated and it is set to a different from the default value
						// Checks only the deprecated properties with defaultValue property is not null
						if (mProperties[sProperty].deprecated
							&& mProperties[sProperty].defaultValue != oElement.getProperty(sProperty)
							&& mProperties[sProperty].defaultValue !== null) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated property '" + sProperty + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	/**
	 * Checks for deprecated aggregations
	 */
	var oDeprecatedAggregationRule = {
		id: "deprecatedAggregation",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated aggregation",
		description: "Using deprecated aggregation should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which aggregation should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mAggregations = oMetadata.getAllAggregations();

					for (var sAggregation in mAggregations) {
						// if aggregation is deprecated and contains elements
						if (mAggregations[sAggregation].deprecated
							&& !jQuery.isEmptyObject(oElement.getAggregation(sAggregation))) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated aggregation '" + sAggregation + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	/**
	 * Checks for deprecated associations
	 */
	var oDeprecatedAssociationRule = {
		id: "deprecatedAssociation",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated association",
		description: "Using deprecated association should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which association should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mAssociations = oMetadata.getAllAssociations();

					for (var sAssociation in mAssociations) {
						// if association is deprecated and set by developer
						if (mAssociations[sAssociation].deprecated
							&& !jQuery.isEmptyObject(oElement.getAssociation(sAssociation))) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated association '" + sAssociation + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	/**
	 * Checks for deprecated events
	 */
	var oDeprecatedEventRule = {
		id: "deprecatedEvent",
		audiences: [Audiences.Application],
		categories: [Categories.Functionality],
		enabled: true,
		minversion: "1.38",
		title: "Control is using deprecated event",
		description: "Using deprecated event should be avoided, because they are not maintained anymore",
		resolution: "Refer to the API of the element which event should be used instead.",
		resolutionurls: [{
			text: "API Reference",
			href: "https://sapui5.hana.ondemand.com/#/api/deprecated"
		}],
		check: function(oIssueManager, oCoreFacade, oScope) {
			oScope.getElementsByClassName(sap.ui.core.Element)
				.forEach(function(oElement) {

					var oMetadata = oElement.getMetadata(),
						mEvents = oMetadata.getAllEvents();

					for (var sEvent in mEvents) {
						// if event is deprecated and developer added event handler
						if (mEvents[sEvent].deprecated
							&& oElement.mEventRegistry[sEvent] && oElement.mEventRegistry[sEvent].length > 0) {

							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "Deprecated event '" + sEvent + "' is used for element '" + oElement.getId() + "'.",
								context: {
									id: oElement.getId()
								}
							});
						}
					}
				});
		}
	};

	return [
		oXMLViewWrongNamespace,
		oXMLViewDefaultNamespace,
		oXMLViewLowerCaseControl,
		oXMLViewUnusedNamespaces,
		oDeprecatedPropertyRule,
		oDeprecatedAggregationRule,
		oDeprecatedAssociationRule,
		oDeprecatedEventRule
	];
}, true);
<|endoftext|>


<commit_before>// TODO: switch to requireJS or AMD modules
// TODO: convert to backbone?

$(function(){
	mf.init()
	mf.load()
})

var mf = {}

mf.init = function() {
	// put in constructor
	mf.nav.skip    = new mf.controllers.button('#skip')
	mf.nav.discard = new mf.controllers.button('#discard')
	mf.nav.publish = new mf.controllers.button('#publish')
	mf.nav.inspect = new mf.controllers.button('#inspect')
	mf.nav.undo    = new mf.controllers.button('#undo')

	mf.nav.skip.bind('right').bind('j').bind('s')
	mf.nav.discard.bind('x').bind('d').bind('space')
	mf.nav.publish.bind('w').bind('p')
	mf.nav.inspect.bind('i').bind('return')
	mf.nav.undo.bind('u').bind('ctrl+z')
	mf.nav.undo.disable()

	mf.display = new mf.controllers.display('article')
	mf.display.wait()

	mf.pending = new mf.controllers.counter('#pending')
	mf.pending.change(function(count){
		if (count)
			mf.nav.enable()
		else
			mf.nav.disable()
	}())

	mf.nav.skip.action(mf.skip)
	mf.nav.discard.action(mf.discard)
	mf.nav.publish.action(mf.publish)
	mf.nav.inspect.action(mf.inspect)
	//mf.nav.undo.action(mf.undo)
}

mf.updatePending = function(count) {
	$('#pending').text(count)
}

// render the next article from cache and begin to use the
mf.next = function() {}

mf.controllers = {}

mf.controllers.display = function(selector) {
	var ele = $(selector)

	// render a given node-feedparser article to the page
	this.render = function(article) {
		$('#error').hide()
		$('#loading').hide()
		ele.css('visibility','visible')
		$('section.description',ele).html(article.description)
		$('> h1 a',ele).text(article.title).attr('href',article.origlink)
		$('time',ele).attr('datetime',article.pubdate)
		$('.note',ele).html(article.author).prepend(' by ')
		return this
	}

	var hide = this.hide = function() {
		ele.css('visibility','hidden')
		return this
	}

	// show loading animation
	this.wait = function(){
		$('#loading').show()
		hide()
		$('#error').hide()
		return this
	}

	// show 'error' message
	this.error = function(msg) {
		$('#loading').hide()
		hide()
		$('#error').show().text(msg)
		return this
	}
}

// positive article counter
mf.controllers.counter = function(selector) {
	ele = $(selector)
	var value = 0

	// callback for when number changes
	var change = function(value) {}
	this.change = function(fn) {
		action = fn
	}

	this.set = function(number) {
		ele.text(number)
		value = number
		change(value)
		return this
	}

	// initialise
	this.set(value)

	this.get = function() {
		return value
	}

	this.decrement = function() {
		if (value > 0)
			ele.text(--value)

		return this
	}
}

// navigation buttons (sort of like a view controller)
mf.controllers.button = function(selector){
	var ele = $(selector)
	var enabled = true;

	// callback for when button is clicked or key is pressed
	var action = function() {}
	this.action = function(fn) {
		action = fn
	}

	ele.click(function() {
		if (enabled)
			action()
	})

	this.enable = function() {
		enabled = true
		ele.removeClass('disabled')
		return this
	}

	this.disable = function() {
		enabled = false
		ele.addClass('disabled')
		return this
	}

	// bind a key
	this.bind = function(key) {

		// press
		$(document).bind('keydown',key,function() {
			if (!enabled) return false

			ele.addClass('depressed')
			return false
		})
		// release
		$(document).bind('keyup',key,function() {
			if (!enabled) return false

			ele.removeClass('depressed')
			action()
			return false
		})
		return this
	}
}

// -------model?

// current article
mf.article = null

// download and display the next article (or current on first load)
mf.load = mf.skip = function() {
	mf.display.wait()
	mf.nav.disable()
	$.ajax({
		url: mf.article?'/next':'/current',
		type:'GET',
		error:function() {
			mf.display.error('No more articles')
		},
		success:function(article) {
			if (!article.pending) {
				mf.display.error('None left in queue')
				ml.article = null
			} else {
				mf.article = article
				mf.display.render(article)
				mf.nav.enable()
			}

			mf.pending.set(article.pending)
		}

	})
}

mf.publish = function() {
	mf.pending.decrement()
	$.ajax({
		url:'/publish/'+mf.article.id,
		type:'GET',
		error:function() {
			mf.display.error("None left!")
		},
		success:function() {
			console.log('Published article')
		}

	})
	mf.load()
}

mf.discard = function() {
	mf.pending.decrement()
	$.ajax({
		url:'/'+mf.article.id,
		type:'DELETE',
		error:function() {
			mf.display.error("That's it!")
		},
		success:function() {
			console.log('Deleted article')
		}

	})
	mf.load()
}

mf.inspect = function() {
	window.open(mf.article.link)
}

mf.nav = {}
mf.nav.enable = function() {
	mf.nav.skip.enable()
	mf.nav.discard.enable()
	mf.nav.publish.enable()
	mf.nav.inspect.enable()
}

mf.nav.disable = function() {
	mf.nav.skip.disable()
	mf.nav.discard.disable()
	mf.nav.publish.disable()
	mf.nav.inspect.disable()
}
<commit_msg>check pending 5 secs<commit_after>// TODO: switch to requireJS or AMD modules
// TODO: convert to backbone?

$(function(){
	mf.init()
	mf.load()
})

var mf = {}

mf.init = function() {
	// put in constructor
	mf.nav.skip    = new mf.controllers.button('#skip')
	mf.nav.discard = new mf.controllers.button('#discard')
	mf.nav.publish = new mf.controllers.button('#publish')
	mf.nav.inspect = new mf.controllers.button('#inspect')
	mf.nav.undo    = new mf.controllers.button('#undo')

	mf.nav.skip.bind('right').bind('j').bind('s')
	mf.nav.discard.bind('x').bind('d').bind('space')
	mf.nav.publish.bind('w').bind('p')
	mf.nav.inspect.bind('i').bind('return')
	mf.nav.undo.bind('u').bind('ctrl+z')
	mf.nav.undo.disable()

	mf.display = new mf.controllers.display('article')
	mf.display.wait()

	mf.pending = new mf.controllers.counter('#pending')
	mf.pending.change(function(count){
		if (count)
			mf.nav.enable()
		else
			mf.nav.disable()
	}())

	mf.nav.skip.action(mf.skip)
	mf.nav.discard.action(mf.discard)
	mf.nav.publish.action(mf.publish)
	mf.nav.inspect.action(mf.inspect)
	//mf.nav.undo.action(mf.undo)

	setInterval(mf.check_pending,5000)
}

mf.updatePending = function(count) {
	$('#pending').text(count)
}

// render the next article from cache and begin to use the
mf.next = function() {}

mf.controllers = {}

mf.controllers.display = function(selector) {
	var ele = $(selector)

	// render a given node-feedparser article to the page
	this.render = function(article) {
		$('#error').hide()
		$('#loading').hide()
		ele.css('visibility','visible')
		$('section.description',ele).html(article.description)
		$('> h1 a',ele).text(article.title).attr('href',article.origlink)
		$('time',ele).attr('datetime',article.pubdate)
		$('.note',ele).html(article.author).prepend(' by ')
		return this
	}

	var hide = this.hide = function() {
		ele.css('visibility','hidden')
		return this
	}

	// show loading animation
	this.wait = function(){
		$('#loading').show()
		hide()
		$('#error').hide()
		return this
	}

	// show 'error' message
	this.error = function(msg) {
		$('#loading').hide()
		hide()
		$('#error').show().text(msg)
		return this
	}
}

// positive article counter
mf.controllers.counter = function(selector) {
	ele = $(selector)
	var value = 0

	// callback for when number changes
	var change = function(value) {}
	this.change = function(fn) {
		action = fn
	}

	this.set = function(number) {
		ele.text(number)
		value = number
		change(value)
		return this
	}

	// initialise
	this.set(value)

	this.get = function() {
		return value
	}

	this.decrement = function() {
		if (value > 0)
			ele.text(--value)

		return this
	}
}

// navigation buttons (sort of like a view controller)
mf.controllers.button = function(selector){
	var ele = $(selector)
	var enabled = true;

	// callback for when button is clicked or key is pressed
	var action = function() {}
	this.action = function(fn) {
		action = fn
	}

	ele.click(function() {
		if (enabled)
			action()
	})

	this.enable = function() {
		enabled = true
		ele.removeClass('disabled')
		return this
	}

	this.disable = function() {
		enabled = false
		ele.addClass('disabled')
		return this
	}

	// bind a key
	this.bind = function(key) {

		// press
		$(document).bind('keydown',key,function() {
			if (!enabled) return false

			ele.addClass('depressed')
			return false
		})
		// release
		$(document).bind('keyup',key,function() {
			if (!enabled) return false

			ele.removeClass('depressed')
			action()
			return false
		})
		return this
	}
}

// -------model?

// current article
mf.article = null

// download and display the next article (or current on first load)
mf.load = mf.skip = function() {
	mf.display.wait()
	mf.nav.disable()
	$.ajax({
		url: mf.article?'/next':'/current',
		type:'GET',
		error:function() {
			mf.display.error('No more articles')
		},
		success:function(article) {
			if (!article.pending) {
				mf.display.error('None left in queue')
				ml.article = null
			} else {
				mf.article = article
				mf.display.render(article)
				mf.nav.enable()
			}

			mf.pending.set(article.pending)
		}

	})
}

mf.publish = function() {
	mf.pending.decrement()
	$.ajax({
		url:'/publish/'+mf.article.id,
		type:'GET',
		error:function() {
			mf.display.error("None left!")
		},
		success:function() {
			console.log('Published article')
		}

	})
	mf.load()
}

mf.discard = function() {
	mf.pending.decrement()
	$.ajax({
		url:'/'+mf.article.id,
		type:'DELETE',
		error:function() {
			mf.display.error("That's it!")
		},
		success:function() {
			console.log('Deleted article')
		}

	})
	mf.load()
}

mf.inspect = function() {
	window.open(mf.article.link)
}

mf.nav = {}
mf.nav.enable = function() {
	mf.nav.skip.enable()
	mf.nav.discard.enable()
	mf.nav.publish.enable()
	mf.nav.inspect.enable()
}

mf.nav.disable = function() {
	mf.nav.skip.disable()
	mf.nav.discard.disable()
	mf.nav.publish.disable()
	mf.nav.inspect.disable()
}

mf.check_pending = function () {
	$({
		url: '/pending',
		success: function(d) {
			mf.pending.set(d.pending)
		}
	})
}
<|endoftext|>


<commit_before>const $ = require('jquery');

const elrAccordion = function(params) {
    const self = {};
    const spec = params || {};
    const containerClass = spec.containerClass || 'elr-accordion';
    const labelClass = spec.labelClass || 'elr-accordion-label';
    const contentHolderClass = spec.contentHolderClass || 'elr-accordion-inner';
    const showButtons = (typeof spec.showButtons === 'undefined') ? true : spec.showButtons;
    const speed = spec.speed || 300;
    const expandIconClass = spec.expandIconClass  || 'fa-plus';
    const collapseIconClass = spec.collapseIconClass  || 'fa-minus';
    const iconClass = spec.iconClass || 'elr-accordion-icon';
    const $container = $(`.${containerClass}`);

    const showDefaultContent = function($expandedContent, $content) {
        $content.hide();
        $expandedContent.show();
    };

    const toggle = function(speed, $openContent) {
        const $that = $(this);
        const $nextContent = $that.next();

        $openContent.slideUp(speed);

        if ( $($nextContent).is(':hidden') ) {
            $nextContent.slideDown(speed);
        } else {
            $nextContent.slideUp(speed);
        }
    };

    const replaceIcons = function($openContent, iconClass, expandIconClass, collapseIconClass) {
        const $that = $(this);
        const $icon = $that.find(`.${iconClass}`);
        const $openContentIcons = $openContent.prev().find(`.${iconClass}`);

        if ( $icon.hasClass(expandIconClass) ) {
            $icon.removeClass(expandIconClass).addClass(collapseIconClass);
        } else {
            $icon.removeClass(collapseIconClass).addClass(expandIconClass);
        }

        $openContentIcons.removeClass(collapseIconClass).addClass(expandIconClass);
    };

    const createButton = function(button, message, className, $container) {
        return $('<button></button>', {text: message, 'class': className}).prependTo($container);
    };

    const addButtons = function($container) {
        return {
            'showButton': createButton('showButton', 'Show All', 'elr-show-all elr-button elr-button-primary', $container),
            'hideButton': createButton('hideButton', 'Hide All', 'elr-hide-all elr-button elr-button-primary', $container),
        };
    };

    const showAll = function(speed, $content) {
        $content.slideDown(speed);
    };

    const hideAll = function(speed, $content) {
        $content.slideUp(speed);
    };

    if ( $container.length ) {
        const $label = $container.find(`.${labelClass}`);
        const $content = $container.find(`.${contentHolderClass}`);
        const $icons = $label.find(`.${iconClass}`);
        const $expandedContent = $container.find(`.${contentHolderClass}[data-state=expanded]`);
        // const $buttons;

        if ( showButtons ) {
            const $buttons = addButtons($container);

            $buttons.showButton.on('click', function() {
                showAll(speed, $content);
                $icons.removeClass(expandIconClass).addClass(collapseIconClass);
            });

            $buttons.hideButton.on('click', function() {
                hideAll(speed, $content);
                $icons.removeClass(collapseIconClass).addClass(expandIconClass);
            });
        }

        showDefaultContent($expandedContent, $content);

        $label.on('click', function(e) {
            const $openContent = $($content).not(':hidden');

            replaceIcons.call(this, $openContent, iconClass, expandIconClass, collapseIconClass);
            toggle.call(this, speed, $openContent);
            e.stopPropagation();
        });
    }

    return self;
};

export default elrAccordion;<commit_msg>remove unnecessary variable declaration<commit_after>const $ = require('jquery');

const elrAccordion = function(params) {
    const self = {};
    const spec = params || {};
    const containerClass = spec.containerClass || 'elr-accordion';
    const labelClass = spec.labelClass || 'elr-accordion-label';
    const contentHolderClass = spec.contentHolderClass || 'elr-accordion-inner';
    const showButtons = (typeof spec.showButtons === 'undefined') ? true : spec.showButtons;
    const speed = spec.speed || 300;
    const expandIconClass = spec.expandIconClass  || 'fa-plus';
    const collapseIconClass = spec.collapseIconClass  || 'fa-minus';
    const iconClass = spec.iconClass || 'elr-accordion-icon';
    const $container = $(`.${containerClass}`);

    const showDefaultContent = function($expandedContent, $content) {
        $content.hide();
        $expandedContent.show();
    };

    const toggle = function(speed, $openContent) {
        const $that = $(this);
        const $nextContent = $that.next();

        $openContent.slideUp(speed);

        if ( $($nextContent).is(':hidden') ) {
            $nextContent.slideDown(speed);
        } else {
            $nextContent.slideUp(speed);
        }
    };

    const replaceIcons = function($openContent, iconClass, expandIconClass, collapseIconClass) {
        const $that = $(this);
        const $icon = $that.find(`.${iconClass}`);
        const $openContentIcons = $openContent.prev().find(`.${iconClass}`);

        if ( $icon.hasClass(expandIconClass) ) {
            $icon.removeClass(expandIconClass).addClass(collapseIconClass);
        } else {
            $icon.removeClass(collapseIconClass).addClass(expandIconClass);
        }

        $openContentIcons.removeClass(collapseIconClass).addClass(expandIconClass);
    };

    const createButton = function(button, message, className, $container) {
        return $('<button></button>', {text: message, 'class': className}).prependTo($container);
    };

    const addButtons = function($container) {
        return {
            'showButton': createButton('showButton', 'Show All', 'elr-show-all elr-button elr-button-primary', $container),
            'hideButton': createButton('hideButton', 'Hide All', 'elr-hide-all elr-button elr-button-primary', $container),
        };
    };

    const showAll = function(speed, $content) {
        $content.slideDown(speed);
    };

    const hideAll = function(speed, $content) {
        $content.slideUp(speed);
    };

    if ( $container.length ) {
        const $label = $container.find(`.${labelClass}`);
        const $content = $container.find(`.${contentHolderClass}`);
        const $icons = $label.find(`.${iconClass}`);
        const $expandedContent = $container.find(`.${contentHolderClass}[data-state=expanded]`);

        if ( showButtons ) {
            const $buttons = addButtons($container);

            $buttons.showButton.on('click', function() {
                showAll(speed, $content);
                $icons.removeClass(expandIconClass).addClass(collapseIconClass);
            });

            $buttons.hideButton.on('click', function() {
                hideAll(speed, $content);
                $icons.removeClass(collapseIconClass).addClass(expandIconClass);
            });
        }

        showDefaultContent($expandedContent, $content);

        $label.on('click', function(e) {
            const $openContent = $($content).not(':hidden');

            replaceIcons.call(this, $openContent, iconClass, expandIconClass, collapseIconClass);
            toggle.call(this, speed, $openContent);
            e.stopPropagation();
        });
    }

    return self;
};

export default elrAccordion;<|endoftext|>