<commit_before>(function () {

    me.CanvasRenderer = (function () {
        var api = {},
        canvas = null,
        context = null,
        doubleBuffering = null,
        backBufferCanvas = null,
        backBufferContext2D = null,
        gameHeightZoom = 0,
        gameWidthZoom = 0;

        api.init = function (c, db) {
            canvas = c;
            context = this.getContext2d(canvas);
            doubleBuffering = db;

            // create the back buffer if we use double buffering
            if (doubleBuffering) {
                backBufferCanvas = me.video.createCanvas(canvas.width, canvas.height, false);
                backBufferContext2D = this.getContext2d(backBufferCanvas);
            }
            else {
                backBufferCanvas = canvas;
                backBufferContext2D = context;
            }

            return this;
        };

        api.applyRGBFilter = function (object, effect, option) {
            //create a output canvas using the given canvas or image size
            var _context = api.getContext2d(me.video.createCanvas(object.width, object.height, false));
            // get the pixels array of the give parameter
            var imgpix = me.utils.getPixels(object);
            // pointer to the pixels data
            var pix = imgpix.data;

            // apply selected effect
            var i, n;
            switch (effect) {
                case "b&w":
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        var grayscale = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) >>> 3;
                        pix[i] = grayscale; // red
                        pix[i + 1] = grayscale; // green
                        pix[i + 2] = grayscale; // blue
                    }
                    break;

                case "brightness":
                    // make sure it's between 0.0 and 1.0
                    var brightness = Math.abs(option).clamp(0.0, 1.0);
                    for (i = 0, n = pix.length; i < n; i += 4) {

                        pix[i] *= brightness; // red
                        pix[i + 1] *= brightness; // green
                        pix[i + 2] *= brightness; // blue
                    }
                    break;

                case "transparent":
                    var refColor = me.pool.pull("me.Color").parseHex(option);
                    var pixel = me.pool.pull("me.Color");
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        pixel.setColor(pix[i], pix[i + 1], pix[i + 2]);
                        if (pixel.equals(refColor)) {
                            pix[i + 3] = 0;
                        }
                    }
                    me.pool.push(refColor);
                    me.pool.push(pixel);

                    break;

                default:
                    return null;
            }

            // put our modified image back in the new filtered canvas
            _context.putImageData(imgpix, 0, 0);

            // return it
            return _context;
        };

        /**
         * render the main framebuffer on screen
         * @name blitSurface
         * @memberOf me.video
         * @function
         */
        api.blitSurface = function () {
            if (doubleBuffering) {
                /** @ignore */
                api.blitSurface = function () {
                    //FPS.update();
                    context.drawImage(
                        backBufferCanvas, 0, 0,
                        backBufferCanvas.width, backBufferCanvas.height, 0,
                        0, gameWidthZoom, gameHeightZoom
                    );

                };
            }
            else {
                // "empty" function, as we directly render stuff on "context2D"
                /** @ignore */
                api.blitSurface = function () {
                };
            }
            api.blitSurface();
        };

        /**
         * Clear the specified context with the given color
         * @name clearSurface
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} canvas contest. Optional, will default to system context.
         * @param {String} color a CSS color string
         */
        api.clearSurface = function (ctx, col) {
            if (ctx === null) {
                ctx = context;
            }
            var _canvas = ctx.canvas;
            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.fillStyle = col;
            ctx.fillRect(0, 0, _canvas.width, _canvas.height);
            ctx.restore();
        };

        /**
         * Draw an image using the canvas api
         * @name drawImage
         * @memberOf me.CanvasRenderer
         * @function
         * @param {image} an html image element
         * @param {Number} offsetX value, from the source image.
         * @param {Number} offsetY value, from the source image.
         * @param {Number} imageWidth the width of the image to be drawn
         * @param {Number} imageHeight the height of the image to be drawn
         * @param {Number} destX the x position to draw the image at on the screen
         * @param {Number} destY the y position to draw the image at on the screen
         * @param {Number} destW the width value to draw the image at on the screen
         * @param {Number} destH the height value to draw the image at on the screen
         */
        api.drawImage = function (image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH) {
            context.drawImage(image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH);
        };

        /**
         * return a reference to the screen canvas corresponding 2d Context

         * (will return buffered context if double buffering is enabled, or a reference to the Screen Context)
         * @name getScreenContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getScreenContext = function () {
            return context;
        };

        /**
         * Returns the 2D Context object of the given Canvas
         * `getContext2d` will also enable/disable antialiasing features based on global settings.
         * @name getContext2D
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Canvas}
         * @return {Context2d}
         */
        api.getContext2d = function (canvas) {
            var _context;
            if (navigator.isCocoonJS) {
                // cocoonJS specific extension
                _context = canvas.getContext("2d", {
                    "antialias" : me.sys.scalingInterpolation
                });
            }
            else {
                _context = canvas.getContext("2d");
            }
            if (!_context.canvas) {
                _context.canvas = canvas;
            }
            this.setImageSmoothing(_context, me.sys.scalingInterpolation);
            return _context;
        };

        /**
         * return a reference to the system canvas
         * @name getSystemCanvas
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Canvas}
         */
        api.getSystemCanvas = function () {
            return backBufferCanvas;
        };

        /**
         * return a reference to the system 2d Context
         * @name getSystemContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getSystemContext = function () {
            return backBufferContext2D;
        };

        /**
         * return the current global alpha
         * @name globalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Number}
         */
        api.globalAlpha = function () {
            return context.globalAlpha;
        };

        /**
         * resets the canvas transform to identity
         * @name resetTransform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.resetTransform = function () {
            context.setTransform(1, 0, 0, 1, 0, 0);
        };

        api.resize = function (scaleX, scaleY) {
            gameWidthZoom = backBufferCanvas.width * scaleX;
            gameHeightZoom = backBufferCanvas.height * scaleY;
            canvas.width = gameWidthZoom;
            canvas.height = gameHeightZoom;

            // adjust CSS style for High-DPI devices
            if (me.device.getPixelRatio() > 1) {
                canvas.style.width = (canvas.width / me.device.getPixelRatio()) + "px";
                canvas.style.height = (canvas.height / me.device.getPixelRatio()) + "px";
            }
            this.setImageSmoothing(context, me.sys.scalingInterpolation);
            this.blitSurface();
        };

        /**
         * restores the canvas context
         * @name restore
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.restore = function () {
            context.restore();
        };

        /**
         * rotates the canvas context
         * @name rotate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} angle in radians
         */
        api.rotate = function (angle) {
            context.rotate(angle);
        };

        /**
         * save the canvas context
         * @name save
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.save = function () {
            context.save();
        };

        /**
         * scales the canvas context
         * @name scale
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.scale = function (x, y) {
            context.scale(x, y);
        };

        api.setAlpha = function (enable) {
            context.globalCompositeOperation = enable ? "source-over" : "copy";
        };

        /**
         * Sets the global alpha on the canvas context
         * @name setGlobalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} alpha value. 0.0 to 1.0 values accepted.
         */
        api.setGlobalAlpha = function (a) {
            context.globalAlpha = a;
        };

        /**
         * enable/disable image smoothing (scaling interpolation) for the specified 2d Context

         * (!) this might not be supported by all browsers

         * @name setImageSmoothing
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} context
         * @param {Boolean} [enable=false]
         */
        api.setImageSmoothing = function (context, enable) {
            me.agent.setPrefixed("imageSmoothingEnabled", enable === true, context);
        };

        /**
         * transforms the context. Accepts any number of integer arguments
         * @name transform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.transform = function () {
            context.transform(arguments);
        };

        /**
         * Translates the context to the given position
         * @name translate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.translate = function (x, y) {
            context.translate(x, y);
        };

        return api;
    })();

})();<commit_msg>fixed an error with the transform<commit_after>(function () {

    me.CanvasRenderer = (function () {
        var api = {},
        canvas = null,
        context = null,
        doubleBuffering = null,
        backBufferCanvas = null,
        backBufferContext2D = null,
        gameHeightZoom = 0,
        gameWidthZoom = 0;

        api.init = function (c, db) {
            canvas = c;
            context = this.getContext2d(canvas);
            doubleBuffering = db;

            // create the back buffer if we use double buffering
            if (doubleBuffering) {
                backBufferCanvas = me.video.createCanvas(canvas.width, canvas.height, false);
                backBufferContext2D = this.getContext2d(backBufferCanvas);
            }
            else {
                backBufferCanvas = canvas;
                backBufferContext2D = context;
            }

            return this;
        };

        api.applyRGBFilter = function (object, effect, option) {
            //create a output canvas using the given canvas or image size
            var _context = api.getContext2d(me.video.createCanvas(object.width, object.height, false));
            // get the pixels array of the give parameter
            var imgpix = me.utils.getPixels(object);
            // pointer to the pixels data
            var pix = imgpix.data;

            // apply selected effect
            var i, n;
            switch (effect) {
                case "b&w":
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        var grayscale = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) >>> 3;
                        pix[i] = grayscale; // red
                        pix[i + 1] = grayscale; // green
                        pix[i + 2] = grayscale; // blue
                    }
                    break;

                case "brightness":
                    // make sure it's between 0.0 and 1.0
                    var brightness = Math.abs(option).clamp(0.0, 1.0);
                    for (i = 0, n = pix.length; i < n; i += 4) {

                        pix[i] *= brightness; // red
                        pix[i + 1] *= brightness; // green
                        pix[i + 2] *= brightness; // blue
                    }
                    break;

                case "transparent":
                    var refColor = me.pool.pull("me.Color").parseHex(option);
                    var pixel = me.pool.pull("me.Color");
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        pixel.setColor(pix[i], pix[i + 1], pix[i + 2]);
                        if (pixel.equals(refColor)) {
                            pix[i + 3] = 0;
                        }
                    }
                    me.pool.push(refColor);
                    me.pool.push(pixel);

                    break;

                default:
                    return null;
            }

            // put our modified image back in the new filtered canvas
            _context.putImageData(imgpix, 0, 0);

            // return it
            return _context;
        };

        /**
         * render the main framebuffer on screen
         * @name blitSurface
         * @memberOf me.video
         * @function
         */
        api.blitSurface = function () {
            if (doubleBuffering) {
                /** @ignore */
                api.blitSurface = function () {
                    //FPS.update();
                    context.drawImage(
                        backBufferCanvas, 0, 0,
                        backBufferCanvas.width, backBufferCanvas.height, 0,
                        0, gameWidthZoom, gameHeightZoom
                    );

                };
            }
            else {
                // "empty" function, as we directly render stuff on "context2D"
                /** @ignore */
                api.blitSurface = function () {
                };
            }
            api.blitSurface();
        };

        /**
         * Clear the specified context with the given color
         * @name clearSurface
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} canvas contest. Optional, will default to system context.
         * @param {String} color a CSS color string
         */
        api.clearSurface = function (ctx, col) {
            if (ctx === null) {
                ctx = context;
            }
            var _canvas = ctx.canvas;
            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.fillStyle = col;
            ctx.fillRect(0, 0, _canvas.width, _canvas.height);
            ctx.restore();
        };

        /**
         * Draw an image using the canvas api
         * @name drawImage
         * @memberOf me.CanvasRenderer
         * @function
         * @param {image} an html image element
         * @param {Number} offsetX value, from the source image.
         * @param {Number} offsetY value, from the source image.
         * @param {Number} imageWidth the width of the image to be drawn
         * @param {Number} imageHeight the height of the image to be drawn
         * @param {Number} destX the x position to draw the image at on the screen
         * @param {Number} destY the y position to draw the image at on the screen
         * @param {Number} destW the width value to draw the image at on the screen
         * @param {Number} destH the height value to draw the image at on the screen
         */
        api.drawImage = function (image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH) {
            context.drawImage(image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH);
        };

        /**
         * return a reference to the screen canvas corresponding 2d Context

         * (will return buffered context if double buffering is enabled, or a reference to the Screen Context)
         * @name getScreenContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getScreenContext = function () {
            return context;
        };

        /**
         * Returns the 2D Context object of the given Canvas
         * `getContext2d` will also enable/disable antialiasing features based on global settings.
         * @name getContext2D
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Canvas}
         * @return {Context2d}
         */
        api.getContext2d = function (canvas) {
            var _context;
            if (navigator.isCocoonJS) {
                // cocoonJS specific extension
                _context = canvas.getContext("2d", {
                    "antialias" : me.sys.scalingInterpolation
                });
            }
            else {
                _context = canvas.getContext("2d");
            }
            if (!_context.canvas) {
                _context.canvas = canvas;
            }
            this.setImageSmoothing(_context, me.sys.scalingInterpolation);
            return _context;
        };

        /**
         * return a reference to the system canvas
         * @name getSystemCanvas
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Canvas}
         */
        api.getSystemCanvas = function () {
            return backBufferCanvas;
        };

        /**
         * return a reference to the system 2d Context
         * @name getSystemContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getSystemContext = function () {
            return backBufferContext2D;
        };

        /**
         * return the current global alpha
         * @name globalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Number}
         */
        api.globalAlpha = function () {
            return context.globalAlpha;
        };

        /**
         * resets the canvas transform to identity
         * @name resetTransform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.resetTransform = function () {
            context.setTransform(1, 0, 0, 1, 0, 0);
        };

        api.resize = function (scaleX, scaleY) {
            gameWidthZoom = backBufferCanvas.width * scaleX;
            gameHeightZoom = backBufferCanvas.height * scaleY;
            canvas.width = gameWidthZoom;
            canvas.height = gameHeightZoom;

            // adjust CSS style for High-DPI devices
            if (me.device.getPixelRatio() > 1) {
                canvas.style.width = (canvas.width / me.device.getPixelRatio()) + "px";
                canvas.style.height = (canvas.height / me.device.getPixelRatio()) + "px";
            }
            this.setImageSmoothing(context, me.sys.scalingInterpolation);
            this.blitSurface();
        };

        /**
         * restores the canvas context
         * @name restore
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.restore = function () {
            context.restore();
        };

        /**
         * rotates the canvas context
         * @name rotate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} angle in radians
         */
        api.rotate = function (angle) {
            context.rotate(angle);
        };

        /**
         * save the canvas context
         * @name save
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.save = function () {
            context.save();
        };

        /**
         * scales the canvas context
         * @name scale
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.scale = function (x, y) {
            context.scale(x, y);
        };

        api.setAlpha = function (enable) {
            context.globalCompositeOperation = enable ? "source-over" : "copy";
        };

        /**
         * Sets the global alpha on the canvas context
         * @name setGlobalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} alpha value. 0.0 to 1.0 values accepted.
         */
        api.setGlobalAlpha = function (a) {
            context.globalAlpha = a;
        };

        /**
         * enable/disable image smoothing (scaling interpolation) for the specified 2d Context

         * (!) this might not be supported by all browsers

         * @name setImageSmoothing
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} context
         * @param {Boolean} [enable=false]
         */
        api.setImageSmoothing = function (context, enable) {
            me.agent.setPrefixed("imageSmoothingEnabled", enable === true, context);
        };

        /**
         * transforms the context. Accepts any number of integer arguments
         * @name transform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.transform = function () {
            context.transform.apply(context, arguments);
        };

        /**
         * Translates the context to the given position
         * @name translate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.translate = function (x, y) {
            context.translate(x, y);
        };

        return api;
    })();

})();<|endoftext|>


<commit_before>let timerId
export let tndWidgets = {
  searchBox: {
    queryHook(query, refine) {
      clearTimeout(timerId);
      timerId = setTimeout(() => refine(query), 500);
    },
  },
  hits: {
    transformItems(items) {
      return items.map(item => ({
        ...item,
        type: item.type.toUpperCase(),
      }));
    },
  },
  refinementBase: {
    templates: {
      item: `{{label}} ({{count}})
      `,
      sortBy: ["name:asc", "count:desc"],
    },
  }
}<commit_msg>Set operator to 'and' for refinementLists<commit_after>let timerId
export let tndWidgets = {
  searchBox: {
    queryHook(query, refine) {
      clearTimeout(timerId);
      timerId = setTimeout(() => refine(query), 500);
    },
  },
  hits: {
    transformItems(items) {
      return items.map(item => ({
        ...item,
        type: item.type.toUpperCase(),
      }));
    },
  },
  refinementBase: {
    templates: {
      item: `{{label}} ({{count}})
      `,
      sortBy: ["name:asc", "count:desc"],
      operator: 'and'
    },
  }
}<|endoftext|>


<commit_before>/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var Firebase = require('firebase');
var env = require('./env');
var ref = new Firebase(env.get('firebase.database.url'));

function touch(context) {
  ref.auth(env.get('firebase.database.token'), function(error) {
    if (error) {
      context.done(error);
    } else {
      console.log('Authenticated successfully with admin rights');
      ref.child('lastmodified').set(Firebase.ServerValue.TIMESTAMP);
      context.done();
    }
  });
}

module.exports = {
  touch: touch
}<commit_msg>Update to the lastmodified-tracking sample.<commit_after>/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var Firebase = require('firebase');
var env = require('./env');
var ref = new Firebase(env.get('firebase.database.url'), 'admin');
ref.auth(env.get('firebase.database.token'));

exports.touch = function(context) {
  console.log('Authenticated successfully with admin rights');
  ref.child('lastmodified').set(Firebase.ServerValue.TIMESTAMP, context.done);
};<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

suite('customElements', function() {
  var work;
  var assert = chai.assert;

  setup(function() {
    work = document.createElement('div');
    document.body.appendChild(work);
  });

  teardown(function() {
    document.body.removeChild(work);
  });

  test('document.register create via new', function() {
    // register x-foo
    var XFoo = document.register('x-foo', {prototype: HTMLElement.prototype});
    // create an instance via new
    var xfoo = new XFoo();
    // test localName
    assert.equal(xfoo.localName, 'x-foo');
    // attach content
    work.appendChild(xfoo).textContent = '[x-foo]';
    // reacquire
    var xfoo = work.querySelector('x-foo');
    // test textContent
    assert.equal(xfoo.textContent, '[x-foo]');
  });

  test('document.register create via createElement', function() {
    // register x-foo
    var XFoo = document.register('x-foo', {prototype: HTMLElement.prototype});
    // create an instance via createElement
    var xfoo = document.createElement('x-foo');
    // test localName
    assert.equal(xfoo.localName, 'x-foo');
    // attach content
    xfoo.textContent = '[x-foo2]';
    // test textContent
    assert.equal(xfoo.textContent, '[x-foo2]');
  });

  test('document.register create multiple instances', function() {
    var XFooPrototype = Object.create(HTMLElement.prototype);
    XFooPrototype.bluate = function() {
      this.color = 'lightblue';
    };
    var XFoo = document.register('x-foo', {
      prototype: XFooPrototype
    });
    // create an instance
    var xfoo1 = new XFoo();
    // create another instance
    var xfoo2 = new XFoo();
    // test textContent
    xfoo1.textContent = '[x-foo1]';
    xfoo2.textContent = '[x-foo2]';
    assert.equal(xfoo1.textContent, '[x-foo1]');
    assert.equal(xfoo2.textContent, '[x-foo2]');
    // test bluate
    xfoo1.bluate();
    assert.equal(xfoo1.color, 'lightblue');
    assert.isUndefined(xfoo2.color);
  });

  test('document.register extend native element', function() {
    // test native element extension
    var XBarPrototype = Object.create(HTMLButtonElement.prototype);
    var XBar = document.register('x-bar', {
      prototype: XBarPrototype,
      extends: 'button'
    });
    var xbar = new XBar();
    work.appendChild(xbar).textContent = 'x-bar';
    xbar = work.querySelector('button[is=x-bar]');
    assert(xbar);
    assert.equal(xbar.textContent, 'x-bar');
    // test extension of native element extension
    var XBarBarPrototype = Object.create(XBarPrototype);
    var XBarBar = document.register('x-barbar', {
      prototype: XBarBarPrototype,
      extends: 'x-bar'
    });
    var xbarbar = new XBarBar();
    work.appendChild(xbarbar).textContent = 'x-barbar';
    xbarbar = work.querySelector('button[is=x-barbar]');
    assert(xbarbar);
    assert.equal(xbarbar.textContent, 'x-barbar');
    // test extension^3
    var XBarBarBarPrototype = Object.create(XBarBarPrototype);
    var XBarBarBar = document.register('x-barbarbar', {
      prototype: XBarBarBarPrototype,
      extends: 'x-barbar'
    });
    var xbarbarbar = new XBarBarBar();
    work.appendChild(xbarbarbar).textContent = 'x-barbarbar';
    xbarbarbar = work.querySelector('button[is=x-barbarbar]');
    assert(xbarbarbar);
    assert.equal(xbarbarbar.textContent, 'x-barbarbar');
  });

  test('document.register readyCallback in prototype', function() {
    var XBooPrototype = Object.create(HTMLElement.prototype);
    XBooPrototype.readyCallback = function() {
      this.style.fontStyle = 'italic';
    }
    var XBoo = document.register('x-boo', {
      prototype: XBooPrototype
    });
    var xboo = new XBoo();
    assert.equal(xboo.style.fontStyle, 'italic');
    //
    var XBooBooPrototype = Object.create(XBooPrototype);
    XBooBooPrototype.readyCallback = function() {
      XBoo.prototype.readyCallback.call(this);
      this.style.fontSize = '32pt';
    };
    var XBooBoo = document.register('x-booboo', {
      prototype: XBooBooPrototype,
      extends: 'x-boo'
    });
    var xbooboo = new XBooBoo();
    assert.equal(xbooboo.style.fontStyle, 'italic');
    assert.equal(xbooboo.style.fontSize, '32pt');
  });

  test('document.register [ready|inserted|removed]Callbacks in prototype', function(done) {
    var ready, inserted, removed;
    var XBooPrototype = Object.create(HTMLElement.prototype);
    XBooPrototype.readyCallback = function() {
      ready = true;
    }
    XBooPrototype.insertedCallback = function() {
      inserted = true;
    }
    XBooPrototype.removedCallback = function() {
      removed = true;
    }
    var XBoo = document.register('x-boo-ir', {
      prototype: XBooPrototype
    });
    var xboo = new XBoo();
    assert(ready, 'ready must be true [XBoo]');
    assert(!inserted, 'inserted must be false [XBoo]');
    assert(!removed, 'removed must be false [XBoo]');
    work.appendChild(xboo);
    setTimeout(function() {
      assert(inserted, 'inserted must be true [XBoo]');
      work.removeChild(xboo);
      setTimeout(function() {
        assert(removed, 'removed must be true [XBoo]');
        //
        ready = inserted = removed = false;
        var XBooBooPrototype = Object.create(XBooPrototype);
        XBooBooPrototype.readyCallback = function() {
          XBoo.prototype.readyCallback.call(this);
        };
        XBooBooPrototype.insertedCallback = function() {
          XBoo.prototype.insertedCallback.call(this);
        };
        XBooBooPrototype.removedCallback = function() {
          XBoo.prototype.removedCallback.call(this);
        };
        var XBooBoo = document.register('x-booboo-ir', {
          prototype: XBooBooPrototype,
          extends: 'x-boo-ir'
        });
        var xbooboo = new XBooBoo();
        assert(ready, 'ready must be true [XBooBoo]');
        assert(!inserted, 'inserted must be false [XBooBoo]');
        assert(!removed, 'removed must be false [XBooBoo]');
        work.appendChild(xbooboo);
        setTimeout(function() {
          assert(inserted, 'inserted must be true [XBooBoo]');
          work.removeChild(xbooboo);
          setTimeout(function() {
            assert(removed, 'removed must be true [XBooBoo]');
            done();
          }, 0);
        }, 0);
       }, 0);
     }, 0);
  });

  test('document.register attributeChangedCallback in prototype', function(done) {
    var XBooPrototype = Object.create(HTMLElement.prototype);
    XBooPrototype.attributeChangedCallback = function(inName, inOldValue) {
      if (inName == 'foo' && inOldValue=='bar'
          && this.attributes.foo.value == 'zot') {
        done();
      }
    }
    var XBoo = document.register('x-boo-acp', {
      prototype: XBooPrototype
    });
    var xboo = new XBoo();
    xboo.setAttribute('foo', 'bar');
    xboo.setAttribute('foo', 'zot');
  });
});<commit_msg>begin updating tests for spec compliance<commit_after>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

suite('customElements', function() {
  var work;
  var assert = chai.assert;

  setup(function() {
    work = document.createElement('div');
    document.body.appendChild(work);
  });

  teardown(function() {
    document.body.removeChild(work);
  });

  test('document.register create via new', function() {
    // register x-foo
    var XFoo = document.register('x-foo', {prototype: Object.create(HTMLElement.prototype)});
    // create an instance via new
    var xfoo = new XFoo();
    // test localName
    assert.equal(xfoo.localName, 'x-foo');
    // attach content
    work.appendChild(xfoo).textContent = '[x-foo]';
    // reacquire
    var xfoo = work.querySelector('x-foo');
    // test textContent
    assert.equal(xfoo.textContent, '[x-foo]');
  });

  test('document.register create via createElement', function() {
    // register x-foo
    var XFoo = document.register('x-foo2', {prototype:  Object.create(HTMLElement.prototype)});
    // create an instance via createElement
    var xfoo = document.createElement('x-foo2');
    // test localName
    assert.equal(xfoo.localName, 'x-foo2');
    // attach content
    xfoo.textContent = '[x-foo2]';
    // test textContent
    assert.equal(xfoo.textContent, '[x-foo2]');
  });

  test('document.register create multiple instances', function() {
    var XFooPrototype = Object.create(HTMLElement.prototype);
    XFooPrototype.bluate = function() {
      this.color = 'lightblue';
    };
    var XFoo = document.register('x-foo3', {
      prototype: XFooPrototype
    });
    // create an instance
    var xfoo1 = new XFoo();
    // create another instance
    var xfoo2 = new XFoo();
    // test textContent
    xfoo1.textContent = '[x-foo1]';
    xfoo2.textContent = '[x-foo2]';
    assert.equal(xfoo1.textContent, '[x-foo1]');
    assert.equal(xfoo2.textContent, '[x-foo2]');
    // test bluate
    xfoo1.bluate();
    assert.equal(xfoo1.color, 'lightblue');
    assert.isUndefined(xfoo2.color);
  });

  test('document.register extend native element', function() {
    // test native element extension
    var XBarPrototype = Object.create(HTMLButtonElement.prototype);
    var XBar = document.register('x-bar', {
      prototype: XBarPrototype,
      extends: 'button'
    });
    var xbar = new XBar();
    work.appendChild(xbar).textContent = 'x-bar';
    xbar = work.querySelector('button[is=x-bar]');
    assert(xbar);
    assert.equal(xbar.textContent, 'x-bar');
    // test extension of native element extension
    var XBarBarPrototype = Object.create(XBarPrototype);
    var XBarBar = document.register('x-barbar', {
      prototype: XBarBarPrototype,
      extends: 'x-bar'
    });
    var xbarbar = new XBarBar();
    work.appendChild(xbarbar).textContent = 'x-barbar';
    xbarbar = work.querySelector('button[is=x-barbar]');
    assert(xbarbar);
    assert.equal(xbarbar.textContent, 'x-barbar');
    // test extension^3
    var XBarBarBarPrototype = Object.create(XBarBarPrototype);
    var XBarBarBar = document.register('x-barbarbar', {
      prototype: XBarBarBarPrototype,
      extends: 'x-barbar'
    });
    var xbarbarbar = new XBarBarBar();
    work.appendChild(xbarbarbar).textContent = 'x-barbarbar';
    xbarbarbar = work.querySelector('button[is=x-barbarbar]');
    assert(xbarbarbar);
    assert.equal(xbarbarbar.textContent, 'x-barbarbar');
  });

  test('document.register readyCallback in prototype', function() {
    var XBooPrototype = Object.create(HTMLElement.prototype);
    XBooPrototype.readyCallback = function() {
      this.style.fontStyle = 'italic';
    }
    var XBoo = document.register('x-boo', {
      prototype: XBooPrototype
    });
    var xboo = new XBoo();
    assert.equal(xboo.style.fontStyle, 'italic');
    //
    var XBooBooPrototype = Object.create(XBooPrototype);
    XBooBooPrototype.readyCallback = function() {
      XBoo.prototype.readyCallback.call(this);
      this.style.fontSize = '32pt';
    };
    var XBooBoo = document.register('x-booboo', {
      prototype: XBooBooPrototype,
      extends: 'x-boo'
    });
    var xbooboo = new XBooBoo();
    assert.equal(xbooboo.style.fontStyle, 'italic');
    assert.equal(xbooboo.style.fontSize, '32pt');
  });

  test('document.register [ready|inserted|removed]Callbacks in prototype', function(done) {
    var ready, inserted, removed;
    var XBooPrototype = Object.create(HTMLElement.prototype);
    XBooPrototype.readyCallback = function() {
      ready = true;
    }
    XBooPrototype.insertedCallback = function() {
      inserted = true;
    }
    XBooPrototype.removedCallback = function() {
      removed = true;
    }
    var XBoo = document.register('x-boo-ir', {
      prototype: XBooPrototype
    });
    var xboo = new XBoo();
    assert(ready, 'ready must be true [XBoo]');
    assert(!inserted, 'inserted must be false [XBoo]');
    assert(!removed, 'removed must be false [XBoo]');
    work.appendChild(xboo);
    setTimeout(function() {
      assert(inserted, 'inserted must be true [XBoo]');
      work.removeChild(xboo);
      setTimeout(function() {
        assert(removed, 'removed must be true [XBoo]');
        //
        ready = inserted = removed = false;
        var XBooBooPrototype = Object.create(XBooPrototype);
        XBooBooPrototype.readyCallback = function() {
          XBoo.prototype.readyCallback.call(this);
        };
        XBooBooPrototype.insertedCallback = function() {
          XBoo.prototype.insertedCallback.call(this);
        };
        XBooBooPrototype.removedCallback = function() {
          XBoo.prototype.removedCallback.call(this);
        };
        var XBooBoo = document.register('x-booboo-ir', {
          prototype: XBooBooPrototype,
          extends: 'x-boo-ir'
        });
        var xbooboo = new XBooBoo();
        assert(ready, 'ready must be true [XBooBoo]');
        assert(!inserted, 'inserted must be false [XBooBoo]');
        assert(!removed, 'removed must be false [XBooBoo]');
        work.appendChild(xbooboo);
        setTimeout(function() {
          assert(inserted, 'inserted must be true [XBooBoo]');
          work.removeChild(xbooboo);
          setTimeout(function() {
            assert(removed, 'removed must be true [XBooBoo]');
            done();
          }, 0);
        }, 0);
       }, 0);
     }, 0);
  });

  test('document.register attributeChangedCallback in prototype', function(done) {
    var XBooPrototype = Object.create(HTMLElement.prototype);
    XBooPrototype.attributeChangedCallback = function(inName, inOldValue) {
      if (inName == 'foo' && inOldValue=='bar'
          && this.attributes.foo.value == 'zot') {
        done();
      }
    }
    var XBoo = document.register('x-boo-acp', {
      prototype: XBooPrototype
    });
    var xboo = new XBoo();
    xboo.setAttribute('foo', 'bar');
    xboo.setAttribute('foo', 'zot');
  });
});<|endoftext|>


<commit_before>/*globals describe,it,before,after*/
var DockerizeManager = require('../src/DockerizeManager'),
    BaseManager = require('../src/BaseManager'),
    Logger = require('../src/Logger'),
    fs = require('fs'),
    path = require('path'),
    assert = require('assert'),
    _ = require('lodash'),
    rm_rf = require('rimraf'),
    exists = require('exists-file'),
    utils = require(__dirname + '/res/utils'),
    srcUtils = require('../src/utils'),
    nop = function () {
    };

var logger = new Logger(),
    manager = new DockerizeManager(logger),
    baseManager = new BaseManager(logger);

var WebGMEConfig = 'config.webgme.js',
    SETUP_CONFIG = 'webgme-setup.json';

var PROJECT_DIR,
    TMP_DIR = path.join(__dirname, '..', 'test-tmp');

describe('DockerizeManager', function () {
    'use strict';

    before(function (done) {
        if (!fs.existsSync(TMP_DIR)) {
            fs.mkdir(TMP_DIR, function () {
                process.chdir(TMP_DIR);
                done();
            });
        } else {
            rm_rf(TMP_DIR, function () {
                fs.mkdir(TMP_DIR, function () {
                    process.chdir(TMP_DIR);
                    done();
                });
            });
        }
    });

    // Creating a new item from boilerplate
    describe('dockerize', function () {
        let cnt = 0;

        beforeEach(function (done) {
            PROJECT_DIR = path.join(TMP_DIR, 'DockerizeProj' + cnt);
            fs.mkdirSync(PROJECT_DIR);
            process.chdir(PROJECT_DIR);
            baseManager.init({}, function () {
                var configPath = path.join(PROJECT_DIR, SETUP_CONFIG);
                assert(fs.existsSync(configPath));
                done();
            });
        });

        afterEach(function (done) {
            if (fs.existsSync(PROJECT_DIR)) {
                //rm_rf(PROJECT_DIR, done);
                done();
            } else {
                done();
            }

            cnt += 1;
        });

        it('should update package json with webgme-docker-worker-manager', function () {
            manager.dockerize({});
            var packageJSON = srcUtils.getPackageJSON(PROJECT_DIR);
            assert(typeof packageJSON.dependencies['webgme-docker-worker-manager'] === 'string',
                'Did not update package.json');
        });

        it('should generate the default file when no options given', function () {
            manager.dockerize({});
            [
                'Dockerfile',
                'DockerfilePluginWorker',
                './config/config.docker.js',
                'docker-compose.yml',
            ].forEach((fName) => assert(exists(path.join(PROJECT_DIR, fName)), `Did not generate ${fName}`));
        });

        it('should additionally generate prod files when --production is given', function () {
            manager.dockerize({production: true});
            [
                'Dockerfile',
                'DockerfilePluginWorker',
                './config/config.docker.js',
                'docker-compose.yml',
                // production
                'DockerfileNginx',
                './config/config.dockerprod.js',
                'docker-compose-prod.yml',
            ].forEach((fName) => assert(exists(path.join(PROJECT_DIR, fName)), `Did not generate ${fName}`));
        });

        it.only('should not overwrite existing files', function () {
            const fPath = path.join(PROJECT_DIR, 'Dockerfile');
            const dummyContent = 'Already here!';
            fs.writeFileSync(fPath, dummyContent);
            manager.dockerize({});
            assert(fs.readFileSync(fPath, 'utf-8') === dummyContent, 'Overwrote file!');
        });

        it.only('should overwrite existing files', function () {
            const fPath = path.join(PROJECT_DIR, 'Dockerfile');
            const dummyContent = 'Already here!';
            fs.writeFileSync(fPath, dummyContent);
            manager.dockerize({forceUpdate: true});
            assert(fs.readFileSync(fPath, 'utf-8') !== dummyContent, 'Did not overwrite file!');
        });
    });
});
<commit_msg>WIP Remove left out only<commit_after>/*globals describe,it,before,after*/
var DockerizeManager = require('../src/DockerizeManager'),
    BaseManager = require('../src/BaseManager'),
    Logger = require('../src/Logger'),
    fs = require('fs'),
    path = require('path'),
    assert = require('assert'),
    _ = require('lodash'),
    rm_rf = require('rimraf'),
    exists = require('exists-file'),
    utils = require(__dirname + '/res/utils'),
    srcUtils = require('../src/utils'),
    nop = function () {
    };

var logger = new Logger(),
    manager = new DockerizeManager(logger),
    baseManager = new BaseManager(logger);

var WebGMEConfig = 'config.webgme.js',
    SETUP_CONFIG = 'webgme-setup.json';

var PROJECT_DIR,
    TMP_DIR = path.join(__dirname, '..', 'test-tmp');

describe('DockerizeManager', function () {
    'use strict';

    before(function (done) {
        if (!fs.existsSync(TMP_DIR)) {
            fs.mkdir(TMP_DIR, function () {
                process.chdir(TMP_DIR);
                done();
            });
        } else {
            rm_rf(TMP_DIR, function () {
                fs.mkdir(TMP_DIR, function () {
                    process.chdir(TMP_DIR);
                    done();
                });
            });
        }
    });

    // Creating a new item from boilerplate
    describe('dockerize', function () {
        let cnt = 0;

        beforeEach(function (done) {
            PROJECT_DIR = path.join(TMP_DIR, 'DockerizeProj' + cnt);
            fs.mkdirSync(PROJECT_DIR);
            process.chdir(PROJECT_DIR);
            baseManager.init({}, function () {
                var configPath = path.join(PROJECT_DIR, SETUP_CONFIG);
                assert(fs.existsSync(configPath));
                done();
            });
        });

        afterEach(function (done) {
            if (fs.existsSync(PROJECT_DIR)) {
                //rm_rf(PROJECT_DIR, done);
                done();
            } else {
                done();
            }

            cnt += 1;
        });

        it('should update package json with webgme-docker-worker-manager', function () {
            manager.dockerize({});
            var packageJSON = srcUtils.getPackageJSON(PROJECT_DIR);
            assert(typeof packageJSON.dependencies['webgme-docker-worker-manager'] === 'string',
                'Did not update package.json');
        });

        it('should generate the default file when no options given', function () {
            manager.dockerize({});
            [
                'Dockerfile',
                'DockerfilePluginWorker',
                './config/config.docker.js',
                'docker-compose.yml',
            ].forEach((fName) => assert(exists(path.join(PROJECT_DIR, fName)), `Did not generate ${fName}`));
        });

        it('should additionally generate prod files when --production is given', function () {
            manager.dockerize({production: true});
            [
                'Dockerfile',
                'DockerfilePluginWorker',
                './config/config.docker.js',
                'docker-compose.yml',
                // production
                'DockerfileNginx',
                './config/config.dockerprod.js',
                'docker-compose-prod.yml',
            ].forEach((fName) => assert(exists(path.join(PROJECT_DIR, fName)), `Did not generate ${fName}`));
        });

        it('should not overwrite existing files', function () {
            const fPath = path.join(PROJECT_DIR, 'Dockerfile');
            const dummyContent = 'Already here!';
            fs.writeFileSync(fPath, dummyContent);
            manager.dockerize({});
            assert(fs.readFileSync(fPath, 'utf-8') === dummyContent, 'Overwrote file!');
        });

        it('should overwrite existing files', function () {
            const fPath = path.join(PROJECT_DIR, 'Dockerfile');
            const dummyContent = 'Already here!';
            fs.writeFileSync(fPath, dummyContent);
            manager.dockerize({forceUpdate: true});
            assert(fs.readFileSync(fPath, 'utf-8') !== dummyContent, 'Did not overwrite file!');
        });
    });
});
<|endoftext|>


<commit_before>$(document).ready(function() {
  "use strict";

  var BackRss = new Marionette.Application();

  BackRss.AppLayoutView = Marionette.LayoutView.extend({
    template: "#layout-view-template",

    regions: {
      menu: "#menu",
      content: "#content"
    }
  });

  BackRss.mainLayout = new BackRss.AppLayoutView();

  BackRss.Site = Backbone.Model.extend({
    urlRoot: '/api/sites',
    idAttribute: '_id',

    defaults: {
      title: '',
      url: '',
      count: 0
    }
  });

  BackRss.SitesCollection = Backbone.Collection.extend({
    model: BackRss.Site,
    url: '/api/sites',

    comparator: function(model1, model2) {
      if (model1.get('title') > model2.get('title') && model1.get('_id') != null) {
        return 1;
      } else {
        return -1;
      }
    },

    parse: function(response) {
      return response.data;
    }
  });

  BackRss.Feed = Backbone.Model.extend({
    url: '/api/feeds',
    idAttribute: '_id'
  });

  BackRss.FeedsCollection = Backbone.Collection.extend({
    model: BackRss.Feed,

    url: function() {
      if (this.siteId) {
        return '/api/feeds/' + this.siteId;
      } else {
        return '/api/feeds';
      }
    },

    initialize: function(models, options) {
      this.siteId = options.siteId;
    },

    parse: function(response) {
      console.log(response.data);
      return response.data;
    }
  });

  BackRss.SiteItemView = Backbone.Marionette.ItemView.extend({
    tagName: "li",
    template: '#site-item-template',

    modelEvents: {
      'markSelected': 'addActiveClass',
      'markUnselected': 'removeActiveClass',
      'change': 'fieldsChanged'
    },

    fieldsChanged: function() {
      this.render();
    },

    addActiveClass: function() {
      this.$el.addClass('active');
    },

    removeActiveClass: function() {
      this.$el.removeClass('active');
    }
  });

  BackRss.SitesCollectionView = Backbone.Marionette.CollectionView.extend({
    tagName: "ul",
    className: "nav nav-sidebar",
    childView: BackRss.SiteItemView,

    initialize : function() {
      this.listenTo(this.collection, "reset", this.render);
    }
  });

  BackRss.FeedItemView = Backbone.Marionette.ItemView.extend({
    tagName: "tr",
    template: '#feed-item-template',

    initialize: function(options) {
      this.sites = options.sites;
      this.siteId = options.siteId;
    },

    templateHelpers: function() {
      return { sites: this.sites, siteId: this.siteId }
    }
  });

  BackRss.NoFeedItemsView = Backbone.Marionette.ItemView.extend({
    template: '#no-feeds-template'
  });

  BackRss.FeedsCollectionView = Backbone.Marionette.CompositeView.extend({
    template: '#feeds-template',
    childView: BackRss.FeedItemView,
    childViewContainer: "table",
    childViewOptions: function() {
      return { sites: this.sitesCollection, siteId: this.siteId }
    },

    emptyView: BackRss.NoFeedItemsView,

    events: {
      'click button#mark-read': "markAllAsRead",
      'click button#refresh': "refresh",
      'mouseenter tr': 'showMarkAsRead',
      'mouseleave tr': 'hideMarkAsRead',
      'click a.mark-as-read': 'markAsRead'
    },

    initialize: function(options) {
      this.listenTo(this.collection, "reset", this.render);
      this.siteId = options.siteId;
      this.sitesCollection = options.sitesCollection;
    },

    showMarkAsRead: function(e) {
      $(e.currentTarget).find('.date').addClass('hide');
      $(e.currentTarget).find('.link').removeClass('hide');
    },

    hideMarkAsRead: function(e) {
      $(e.currentTarget).find('.date').removeClass('hide');
      $(e.currentTarget).find('.link').addClass('hide');
    },

    markAsRead: function(e) {
      e.preventDefault();
      var id = $(e.currentTarget).data("id");
      var feed = this.collection.findWhere({ _id: id });
      var that = this;

      feed.save({ seen: true }, { success: function() {
        that.collection.remove(feed);

        if (!that.siteId)
        {
          var allSites = that.sitesCollection.findWhere({ _id: null });
          var site = that.sitesCollection.findWhere({ _id: feed.get('site_id') });
          allSites.set('count', allSites.get('count') - 1);
          site.set('count', site.get('count') - 1);
        } else {
          var site = that.sitesCollection.findWhere({ _id: that.siteId });
          var allSites = that.sitesCollection.findWhere({ _id: null });
          allSites.set('count', allSites.get('count') - 1);
          site.set('count', site.get('count') - 1);
        }
      }, error: function() {
        BackRss.vent.trigger("error", "Error occured");
      }});
    },

    markAllAsRead: function() {
      var that = this;

      bootbox.confirm("Are you sure?", function(result) {
        if (result) {
          that.collection.forEach(function(model) {
            model.save({ seen: true });
          });

          if (!that.siteId)
          {
            _(that.sitesCollection.models).each(function(site) {
              site.set('count', 0);
            });
          } else {
            var site = that.sitesCollection.findWhere({ _id: that.siteId });
            var allSites = that.sitesCollection.findWhere({ _id: null });
            allSites.set('count', allSites.get('count') - site.get('count'));
            site.set('count', 0);
          }

          that.collection.reset();
        }
      });
    },

    refresh: function() {
      Backbone.history.loadUrl();
    },

    templateHelpers: function() {
      return {
        siteId: this.collection.siteId,
        feedsCount: this.collection.length
      };
    }
  });

  BackRss.ManageSiteItemView = Backbone.Marionette.ItemView.extend({
    tagName: "tr",
    template: '#manage-sites-item-template'
  });

  BackRss.ManageSitesView = Backbone.Marionette.CompositeView.extend({
    template: '#manage-sites-template',

    childView: BackRss.ManageSiteItemView,
    childViewContainer: "table",

    events: {
      'click .btnDeleteSite': "deleteSite"
    },

    filter: function (child, index, collection) {
      return child.get('_id') !== null;
    },

    deleteSite: function(e) {
      e.preventDefault();

      var siteId = $(e.currentTarget).data("id");
      var that = this;

      bootbox.confirm("Are you sure?", function(result) {
        if (result) {
          var site = that.collection.findWhere({ _id: siteId });
          var allSites = that.collection.findWhere({ _id: null });
          allSites.set('count', allSites.get('count') - site.get('count'));

          site.destroy({ wait: true });
        }
      });
    }
  });

  BackRss.ManageSitesAddSiteView = Backbone.Marionette.ItemView.extend({
    template: "#add-site-template",

    events: {
      'click #btnAddSite': "addSite"
    },

    ui: {
      inputTitle: '#title',
      inputUrl: '#url'
    },

    onShow: function() {
      this.ui.inputTitle.focus();
    },

    addSite: function(e) {
      e.preventDefault();

      if (!this.ui.inputTitle.val() || !this.ui.inputUrl.val()) {
        return false;
      }

      var model = new BackRss.Site();
      var that = this;

      model.save({title: this.ui.inputTitle.val(), url: this.ui.inputUrl.val()}, {
        success: function(model, resp) {
          that.collection.add(resp.data);
          Backbone.history.navigate("sites", { trigger: true });
        }, error: function() {
          BackRss.vent.trigger("error", "Error occured");
        }, wait: true
      });
    }
  });

  BackRss.MainController = Marionette.Controller.extend({
    initialize: function() {
      this.sites = new BackRss.SitesCollection();
    },

    onError: function() {
      BackRss.vent.trigger("error", "Error occured");
    },

    unmarkSelectedSite: function() {
      _(this.sites.models).each(function(site) {
        site.trigger('markUnselected');
      });
    },

    getSites: function(callback) {
      var that = this;

      if (!BackRss.mainLayout.menu.hasView()) {
        this.sites.fetch({ success: function(collection) {
          var allCount = 0;

          for (var site in collection.models)
          {
            allCount += collection.models[site].get('count');
          }

          that.sites.add({ title: 'All', _id: null, count: allCount }, { at: 0 });

          var sitesListView = new BackRss.SitesCollectionView({
            collection: that.sites,
          });

          BackRss.mainLayout.menu.show(sitesListView);

          if (typeof callback === "function") {
            callback.call(that);
          }
        }, error: that.onError });
      } else {
        var sites = new BackRss.SitesCollection();

        sites.fetch({ success: function(collection) {
          var allCount = 0;

          for (var site in collection.models)
          {
            allCount += collection.models[site].get('count');
            that.sites.findWhere({ _id: collection.models[site].get('_id') }).set('count', collection.models[site].get('count'));
          }

          that.sites.findWhere({ _id: null }).set('count', allCount);

          if (typeof callback === "function") {
            callback.call(that);
          }
        }, error: that.onError });
      }
    },

    getFeeds: function(siteId) {
      var feeds = new BackRss.FeedsCollection([], { siteId: siteId });
      var that = this;

      feeds.fetch().done(function() {
        var feedsListView = new BackRss.FeedsCollectionView({
          collection: feeds,
          siteId: siteId,
          sitesCollection: that.sites
        });

        BackRss.mainLayout.content.show(feedsListView);

        that.unmarkSelectedSite();
        that.sites.findWhere({ _id: siteId }).trigger('markSelected');
      });
    },

    feeds: function(siteId) {
      this.getSites(function() {
        this.getFeeds(siteId);
      });
    },

    manageSites: function() {
      this.getSites(function() {
        this.unmarkSelectedSite();

        var sitesView = new BackRss.ManageSitesView({
          collection: this.sites
        });

        BackRss.mainLayout.content.show(sitesView);
      });
    },

    addSite: function() {
      this.getSites(function() {
        var addSiteView = new BackRss.ManageSitesAddSiteView({
          collection: this.sites
        });

        BackRss.mainLayout.content.show(addSiteView);
      });
    },

    notFound: function() {
      Backbone.history.navigate("feeds", { trigger: true });
    }
  });

  BackRss.Router = Marionette.AppRouter.extend({
    appRoutes: {
      'feeds': 'feeds',
      'feeds/:siteId': 'feeds',
      'sites': 'manageSites',
      'sites/add': 'addSite',
      '*notFound': 'notFound'
    }
  });

  BackRss.addInitializer(function(){
    var mainController = new BackRss.MainController();

    new BackRss.Router({
      controller: mainController
    });
  });

  BackRss.addRegions({
    menuRegion: "#menu",
    mainRegion: "#main"
  });

  BackRss.vent.on("error", function(message) {
    bootbox.alert(message, function() {
      Backbone.history.navigate("/", { trigger: true });
    });
  });

  BackRss.on('start', function(){
    $('body').append(BackRss.mainLayout.render().el);

    if (Backbone.history)
    {
      Backbone.history.start({ pushState: true });
    }
  });

  $(document).on('click', "a[href^='/']", function(e) {
    e.preventDefault();
    var href = $(e.currentTarget).attr('href');
    Backbone.history.navigate(href, { trigger: true });
  });

  BackRss.start();
});
<commit_msg>fixed bugs<commit_after>$(document).ready(function() {
  "use strict";

  var BackRss = new Marionette.Application();

  BackRss.AppLayoutView = Marionette.LayoutView.extend({
    template: "#layout-view-template",

    regions: {
      menu: "#menu",
      content: "#content"
    }
  });

  BackRss.mainLayout = new BackRss.AppLayoutView();

  BackRss.Site = Backbone.Model.extend({
    urlRoot: '/api/sites',
    idAttribute: '_id',

    defaults: {
      title: '',
      url: '',
      count: 0
    }
  });

  BackRss.SitesCollection = Backbone.Collection.extend({
    model: BackRss.Site,
    url: '/api/sites',

    comparator: function(model1, model2) {
      if (model1.get('title') > model2.get('title') && model1.get('_id') != null) {
        return 1;
      } else {
        return -1;
      }
    },

    parse: function(response) {
      return response.data;
    }
  });

  BackRss.Feed = Backbone.Model.extend({
    url: '/api/feeds',
    idAttribute: '_id'
  });

  BackRss.FeedsCollection = Backbone.Collection.extend({
    model: BackRss.Feed,

    url: function() {
      if (this.siteId) {
        return '/api/feeds/' + this.siteId;
      } else {
        return '/api/feeds';
      }
    },

    initialize: function(models, options) {
      this.siteId = options.siteId;
    },

    parse: function(response) {
      return response.data;
    }
  });

  BackRss.SiteItemView = Backbone.Marionette.ItemView.extend({
    tagName: "li",
    template: '#site-item-template',

    modelEvents: {
      'markSelected': 'addActiveClass',
      'markUnselected': 'removeActiveClass',
      'change': 'fieldsChanged'
    },

    fieldsChanged: function() {
      this.render();
    },

    addActiveClass: function() {
      this.$el.addClass('active');
    },

    removeActiveClass: function() {
      this.$el.removeClass('active');
    }
  });

  BackRss.SitesCollectionView = Backbone.Marionette.CollectionView.extend({
    tagName: "ul",
    className: "nav nav-sidebar",
    childView: BackRss.SiteItemView,

    initialize : function() {
      this.listenTo(this.collection, "reset", this.render);
    }
  });

  BackRss.FeedItemView = Backbone.Marionette.ItemView.extend({
    tagName: "tr",
    template: '#feed-item-template',

    initialize: function(options) {
      this.sites = options.sites;
      this.siteId = options.siteId;
    },

    templateHelpers: function() {
      return { sites: this.sites, siteId: this.siteId }
    }
  });

  BackRss.NoFeedItemsView = Backbone.Marionette.ItemView.extend({
    template: '#no-feeds-template'
  });

  BackRss.FeedsCollectionView = Backbone.Marionette.CompositeView.extend({
    template: '#feeds-template',
    childView: BackRss.FeedItemView,
    childViewContainer: "table",
    childViewOptions: function() {
      return { sites: this.sitesCollection, siteId: this.siteId }
    },

    emptyView: BackRss.NoFeedItemsView,

    events: {
      'click button#mark-read': "markAllAsRead",
      'click button#refresh': "refresh",
      'mouseenter tr': 'showMarkAsRead',
      'mouseleave tr': 'hideMarkAsRead',
      'click a.mark-as-read': 'markAsRead'
    },

    initialize: function(options) {
      this.listenTo(this.collection, "reset", this.render);
      this.siteId = options.siteId;
      this.sitesCollection = options.sitesCollection;
    },

    showMarkAsRead: function(e) {
      $(e.currentTarget).find('.date').addClass('hide');
      $(e.currentTarget).find('.link').removeClass('hide');
    },

    hideMarkAsRead: function(e) {
      $(e.currentTarget).find('.date').removeClass('hide');
      $(e.currentTarget).find('.link').addClass('hide');
    },

    markAsRead: function(e) {
      e.preventDefault();
      var id = $(e.currentTarget).data("id");
      var feed = this.collection.findWhere({ _id: id });
      var that = this;

      feed.save({ seen: true }, { success: function() {
        that.collection.remove(feed);

        if (!that.siteId)
        {
          var allSites = that.sitesCollection.findWhere({ _id: null });
          var site = that.sitesCollection.findWhere({ _id: feed.get('site_id') });
          allSites.set('count', allSites.get('count') - 1);
          site.set('count', site.get('count') - 1);
        } else {
          var site = that.sitesCollection.findWhere({ _id: that.siteId });
          var allSites = that.sitesCollection.findWhere({ _id: null });
          allSites.set('count', allSites.get('count') - 1);
          site.set('count', site.get('count') - 1);
        }
      }, error: function() {
        BackRss.vent.trigger("error", "Error occured");
      }});
    },

    markAllAsRead: function() {
      var that = this;

      bootbox.confirm("Are you sure?", function(result) {
        if (result) {
          that.collection.forEach(function(model) {
            model.save({ seen: true });
          });

          if (!that.siteId)
          {
            _(that.sitesCollection.models).each(function(site) {
              site.set('count', 0);
            });
          } else {
            var site = that.sitesCollection.findWhere({ _id: that.siteId });
            var allSites = that.sitesCollection.findWhere({ _id: null });
            allSites.set('count', allSites.get('count') - site.get('count'));
            site.set('count', 0);
          }

          that.collection.reset();
        }
      });
    },

    refresh: function() {
      Backbone.history.loadUrl();
    },

    templateHelpers: function() {
      return {
        siteId: this.collection.siteId,
        feedsCount: this.collection.length
      };
    }
  });

  BackRss.ManageSiteItemView = Backbone.Marionette.ItemView.extend({
    tagName: "tr",
    template: '#manage-sites-item-template'
  });

  BackRss.ManageSitesView = Backbone.Marionette.CompositeView.extend({
    template: '#manage-sites-template',

    childView: BackRss.ManageSiteItemView,
    childViewContainer: "table",

    events: {
      'click .btnDeleteSite': "deleteSite"
    },

    filter: function (child, index, collection) {
      return child.get('_id') !== null;
    },

    deleteSite: function(e) {
      e.preventDefault();

      var siteId = $(e.currentTarget).data("id");
      var that = this;

      bootbox.confirm("Are you sure?", function(result) {
        if (result) {
          var site = that.collection.findWhere({ _id: siteId });
          var allSites = that.collection.findWhere({ _id: null });
          allSites.set('count', allSites.get('count') - site.get('count'));

          site.destroy({ wait: true });
        }
      });
    }
  });

  BackRss.ManageSitesAddSiteView = Backbone.Marionette.ItemView.extend({
    template: "#add-site-template",

    events: {
      'click #btnAddSite': "addSite"
    },

    ui: {
      inputTitle: '#title',
      inputUrl: '#url'
    },

    onShow: function() {
      this.ui.inputTitle.focus();
    },

    addSite: function(e) {
      e.preventDefault();

      if (!this.ui.inputTitle.val() || !this.ui.inputUrl.val()) {
        return false;
      }

      var model = new BackRss.Site();
      var that = this;

      model.save({title: this.ui.inputTitle.val(), url: this.ui.inputUrl.val()}, {
        success: function(model, resp) {
          that.collection.add(resp.data);
          Backbone.history.navigate("sites", { trigger: true });
        }, error: function() {
          BackRss.vent.trigger("error", "Error occured");
        }, wait: true
      });
    }
  });

  BackRss.MainController = Marionette.Controller.extend({
    initialize: function() {
      this.sites = new BackRss.SitesCollection();
    },

    onError: function() {
      BackRss.vent.trigger("error", "Error occured");
    },

    unmarkSelectedSite: function() {
      _(this.sites.models).each(function(site) {
        site.trigger('markUnselected');
      });
    },

    getSites: function(callback) {
      var that = this;

      if (!BackRss.mainLayout.menu.hasView()) {
        this.sites.fetch({ success: function(collection) {
          var allCount = 0;

          for (var site in collection.models)
          {
            allCount += collection.models[site].get('count');
          }

          that.sites.add({ title: 'All', _id: null, count: allCount }, { at: 0 });

          var sitesListView = new BackRss.SitesCollectionView({
            collection: that.sites,
          });

          BackRss.mainLayout.menu.show(sitesListView);

          if (typeof callback === "function") {
            callback.call(that);
          }
        }, error: that.onError });
      } else {
        var sites = new BackRss.SitesCollection();

        sites.fetch({ success: function(collection) {
          var allCount = 0;

          for (var site in collection.models)
          {
            allCount += collection.models[site].get('count');
            that.sites.findWhere({ _id: collection.models[site].get('_id') }).set('count', collection.models[site].get('count'));
          }

          that.sites.findWhere({ _id: null }).set('count', allCount);

          if (typeof callback === "function") {
            callback.call(that);
          }
        }, error: that.onError });
      }
    },

    getFeeds: function(siteId) {
      var feeds = new BackRss.FeedsCollection([], { siteId: siteId });
      var that = this;

      feeds.fetch().done(function() {
        var feedsListView = new BackRss.FeedsCollectionView({
          collection: feeds,
          siteId: siteId,
          sitesCollection: that.sites
        });

        BackRss.mainLayout.content.show(feedsListView);

        that.unmarkSelectedSite();
        that.sites.findWhere({ _id: siteId }).trigger('markSelected');
      });
    },

    feeds: function(siteId) {
      this.getSites(function() {
        this.getFeeds(siteId);
      });
    },

    manageSites: function() {
      this.getSites(function() {
        this.unmarkSelectedSite();

        var sitesView = new BackRss.ManageSitesView({
          collection: this.sites
        });

        BackRss.mainLayout.content.show(sitesView);
      });
    },

    addSite: function() {
      this.getSites(function() {
        var addSiteView = new BackRss.ManageSitesAddSiteView({
          collection: this.sites
        });

        BackRss.mainLayout.content.show(addSiteView);
      });
    },

    notFound: function() {
      Backbone.history.navigate("feeds", { trigger: true });
    }
  });

  BackRss.Router = Marionette.AppRouter.extend({
    appRoutes: {
      'feeds': 'feeds',
      'feeds/:siteId': 'feeds',
      'sites': 'manageSites',
      'sites/add': 'addSite',
      '*notFound': 'notFound'
    }
  });

  BackRss.addInitializer(function(){
    var mainController = new BackRss.MainController();

    new BackRss.Router({
      controller: mainController
    });
  });

  BackRss.addRegions({
    menuRegion: "#menu",
    mainRegion: "#main"
  });

  BackRss.vent.on("error", function(message) {
    bootbox.alert(message, function() {
      Backbone.history.navigate("/", { trigger: true });
    });
  });

  BackRss.on('start', function(){
    $('body').append(BackRss.mainLayout.render().el);

    if (Backbone.history)
    {
      Backbone.history.start({ pushState: true });
    }
  });

  $(document).on('click', "a[href^='/']", function(e) {
    e.preventDefault();
    var href = $(e.currentTarget).attr('href');
    Backbone.history.navigate(href, { trigger: true });
  });

  BackRss.start();
});
<|endoftext|>