<commit_before>import { appDurations, appSizes } from '/imports/ui/helpers/settings';
import _ from 'lodash';

/**
 * Draw a line between the circle and the picture
 *
 * The line helps people know which picture goes with which spot
 *
 * @param {object} el Parent SVG element
 * @param {object} projection D3 map projection
 * @param {object} place Meteor data object for the place
 */
function drawLine(el, projection, place) {
  const dur = appDurations();
  var placeGroup = d3.select(el).selectAll('.map-points')
    .append('g')
    .attr('id', 'line-' + place.slug)
    .classed('place-line', true);

  var line = linePoints(projection, place);
  placeGroup.append('line')
    .attr('x1', line.x1)
    .attr('y1', line.y1)
    .attr('x2', line.x1)
    .attr('y2', line.y1)
    .attr('opacity', 0)
    .classed('map-line', true)
    .transition()
    .duration(dur.default)
    .attr('x1', line.x2)
    .attr('y1', line.y2)
    .attr('opacity', 1);
}

function linePoints(projection, place) {
  const sizes = appSizes();
  var line = {};
  line.x1 = projection([place.long, place.lat])[0];
  line.y1 = projection([place.long, place.lat])[1];
  line.x2 = line.x1 + place.offsetX + (sizes.maxWidth / 2);
  line.y2 = line.y1 + place.offsetY + (sizes.maxWidth / 2);
  return line;
}

/**
 * Draw individual location circle
 *
 * We draw this separately since we don't want any other transformations to
 * move the lat/long based map circle.
 *
 * @param {object} el Top level react DOM parent for our SVG elements
 * @param {function} projection D3 map projection object
 * @param {object} place Place object data from Meteor
 */
function drawCircle(el, projection, place) {
  const sizes = appSizes();
  var placeGroup = d3.select(el).selectAll('.map-points')
    .append('g')
    .attr('id', 'circle-' + place.slug)
    .classed('place-circle', true);
  placeGroup.append('circle')
    .attr('r', '5px')
    .attr('id', 'circle-' + place.slug + '-base')
    .attr('stroke-width', 4)
    .attr('stroke', '#062926')
    .classed('map-circle', true);
  var line = linePoints(projection, place, sizes.maxWidth);
  placeGroup.attr('transform', 'translate(' + line.x1 + ',' + line.y1 + ')');
}

/**
 * Draw individual location label group
 *
 * Draw the text label, picture, and click-able box near each location circle
 *
 * @param  {function} projection D3 map projection object
 * @param  {object} place Place object data from Meteor
 * @param  {object} placeImage TODO: add description
 */
function drawImageLabel(projection, place, placeImage) {
  const sizes = appSizes();
  const dur = appDurations();

  var center = {};
  center.x1 = projection([place.long, place.lat])[0];
  center.y1 = projection([place.long, place.lat])[1];
  center.x2 = projection([place.long, place.lat])[0] + place.offsetX;
  center.y2 = projection([place.long, place.lat])[1] + place.offsetY;

  // Parent group div for picture and the labels
  var xStyle = ['left', center.x1 + 'px'];
  var yStyle = ['top', center.y1 + 'px'];

  var $newDiv = $('<div/>')
    .attr('id', place.slug)
    .addClass('place-label')
    .css(yStyle[0], yStyle[1])
    .css(xStyle[0], xStyle[1]);
  console.log(placeImage.filename);
  console.log('----^ ^ ^ ^ ^ placeImage.filename ^ ^ ^ ^ ^----');
  var backgroundImage = '/images/collection/' + placeImage.filename;
  let displayDimension = placeImage.width;
  if (placeImage.width >= sizes.maxWidth) {
    displayDimension = sizes.maxWidth;
  }

  let backgroundSize = '';
  if (placeImage.width > placeImage.height) {
    const backgroundWidth = (
      (placeImage.width * sizes.maxWidth) / placeImage.height
    );
    backgroundSize = `${backgroundWidth}px ${sizes.maxWidth}px`;
  } else {
    backgroundSize = '100%';
  }

  var $placeLabelBackground = $('<div/>')
    .attr('id', placeImage.slug)
    .addClass('place-label-background')
    .css('background-image', 'url(' + backgroundImage + ')')
    .css('background-size', backgroundSize)
    .css('width', '0px')
    .css('height', '0px');

  $newDiv.append($placeLabelBackground);
  $('.Chart').append($newDiv);

  $newDiv.animate({
    opacity: 1,
    left: center.x2,
    top: center.y2,
  }, dur.default, function () {
    const labelRotation = _.sample(['-3', '3']);
    var $placeLabelText = $('<div/>')
      .addClass('place-label-text')
      .css({ transform: `rotate(${labelRotation}deg)` })
      .html(place.name);
    $placeLabelBackground.append($placeLabelText);
    $placeLabelText
      .animate({
        opacity: 1,
      }, 500);
  });

  $placeLabelBackground.animate({
    width: displayDimension + 'px',
    height: displayDimension + 'px',
  }, dur.default);

}

function drawPlace(el, projection, place, placeImage) {
  // Draw the location labels and images
  drawImageLabel(projection, place, placeImage);

  // Draw map circle, for each location
  drawLine(el, projection, place);

  // Draw map circle, for each location
  drawCircle(el, projection, place);
}

/**
 * Draw all the places when you enter the map
 *
 * @param el
 * @param projection
 * @param places
 * @param images
 */
export function drawPlaces(el, projection, places, images) {
  const dur = appDurations();

  // Remove any past circles
  d3.selectAll('.place-circle')
    .remove();

  _.each(places, function (place, i) {
    // Find the images for this location
    const placeImages = _.filter(images, function (o) {
      if (o.place == place.name) {
        return true;
      }
    });

    // Select a random image
    const placeImage = _.sample(placeImages);
    setTimeout(function () {
      drawPlace(el, projection, place, placeImage);
    }, dur.stagger * (i + 1 - 0.9));
  });
}

/**
 * Hide places that weren't clicked
 *
 * @param elemId
 * @param projection
 * @param places
 * @param maxWidth
 */
export function hidePlaces(elemId, projection, places, maxWidth) {
  _.each(places, function (place) {
    hidePlace(elemId, projection, place, maxWidth);
  });

}

/**
 * Hide a single place
 *
 * @param elemId
 * @param projection
 * @param place
 * @param maxWidth
 */
function hidePlace(elemId, projection, place, maxWidth) {
  const dur = appDurations();
  const sizes = appSizes();

  // Fade out the divs, that weren't clicked
  let $filteredPlaces = $('.place-label');
  $filteredPlaces.animate({
    opacity: 0,
  }, 300, function () {
    $filteredPlaces.remove();
  });

  // Fade out the SVG elements, that weren't clicked
  let shapes = ['line', 'circle'];
  _.each(shapes, function (shape) {
    let placeShape = d3.selectAll('#' + shape + '-' + place.slug);

    // Leave the circle for the clicked element in place
    if (placeShape.attr('id') != 'circle-' + elemId) {
      placeShape
        .select(shape)
        .transition()
        .duration(300)
        .attr('opacity', 0);
      placeShape
        .remove();
    } else {

      // Move the clicked highlight circle
      var circleGroup = '#circle-' + elemId;
      var line = linePoints(projection, place, maxWidth);
      d3.select(circleGroup)
        .transition()
        .duration(dur.bgZoom)
        .attr('transform', 'translate(' +
          ((sizes.screenWidth - sizes.infoWidthExpanded) / 2) +
          ',' + line.y1 + ')');

      /**
       * Animate selected map point circle
       */

      // Add a second stroke
      d3.select('#circle-' + elemId)
        .append('circle')
        .attr('id', 'circle-' + elemId + '-stroke')
        .attr('r', '5px')
        .attr('stroke-width', 4)
        .attr('stroke', '#33444C');
      var circlePathBase = '#circle-' + elemId + '-base';
      var circlePathStroke = '#circle-' + elemId + '-stroke';

      setTimeout(
        function () {
          d3.select(circlePathBase)
            .transition()
            .duration(dur.bounce)
            .attr('r', '45px')
            .attr('stroke-width', 9)
            .attr('stroke', '#0083c0')
            .attr('fill-opacity', .1)
            .transition()
            .duration(dur.bounce)
            .attr('r', '30px');

          d3.select(circlePathStroke)
            .transition()
            .duration(dur.bounce)
            .attr('r', '45px')
            .attr('stroke-width', 6)
            .attr('fill-opacity', .1)
            .transition()
            .duration(dur.bounce)
            .attr('r', '30px');
        },

      dur.bgZoom - 500);
    }
  });

}

<commit_msg>Unused console<commit_after>import { appDurations, appSizes } from '/imports/ui/helpers/settings';
import _ from 'lodash';

/**
 * Draw a line between the circle and the picture
 *
 * The line helps people know which picture goes with which spot
 *
 * @param {object} el Parent SVG element
 * @param {object} projection D3 map projection
 * @param {object} place Meteor data object for the place
 */
function drawLine(el, projection, place) {
  const dur = appDurations();
  var placeGroup = d3.select(el).selectAll('.map-points')
    .append('g')
    .attr('id', 'line-' + place.slug)
    .classed('place-line', true);

  var line = linePoints(projection, place);
  placeGroup.append('line')
    .attr('x1', line.x1)
    .attr('y1', line.y1)
    .attr('x2', line.x1)
    .attr('y2', line.y1)
    .attr('opacity', 0)
    .classed('map-line', true)
    .transition()
    .duration(dur.default)
    .attr('x1', line.x2)
    .attr('y1', line.y2)
    .attr('opacity', 1);
}

function linePoints(projection, place) {
  const sizes = appSizes();
  var line = {};
  line.x1 = projection([place.long, place.lat])[0];
  line.y1 = projection([place.long, place.lat])[1];
  line.x2 = line.x1 + place.offsetX + (sizes.maxWidth / 2);
  line.y2 = line.y1 + place.offsetY + (sizes.maxWidth / 2);
  return line;
}

/**
 * Draw individual location circle
 *
 * We draw this separately since we don't want any other transformations to
 * move the lat/long based map circle.
 *
 * @param {object} el Top level react DOM parent for our SVG elements
 * @param {function} projection D3 map projection object
 * @param {object} place Place object data from Meteor
 */
function drawCircle(el, projection, place) {
  const sizes = appSizes();
  var placeGroup = d3.select(el).selectAll('.map-points')
    .append('g')
    .attr('id', 'circle-' + place.slug)
    .classed('place-circle', true);
  placeGroup.append('circle')
    .attr('r', '5px')
    .attr('id', 'circle-' + place.slug + '-base')
    .attr('stroke-width', 4)
    .attr('stroke', '#062926')
    .classed('map-circle', true);
  var line = linePoints(projection, place, sizes.maxWidth);
  placeGroup.attr('transform', 'translate(' + line.x1 + ',' + line.y1 + ')');
}

/**
 * Draw individual location label group
 *
 * Draw the text label, picture, and click-able box near each location circle
 *
 * @param  {function} projection D3 map projection object
 * @param  {object} place Place object data from Meteor
 * @param  {object} placeImage TODO: add description
 */
function drawImageLabel(projection, place, placeImage) {
  const sizes = appSizes();
  const dur = appDurations();

  var center = {};
  center.x1 = projection([place.long, place.lat])[0];
  center.y1 = projection([place.long, place.lat])[1];
  center.x2 = projection([place.long, place.lat])[0] + place.offsetX;
  center.y2 = projection([place.long, place.lat])[1] + place.offsetY;

  // Parent group div for picture and the labels
  var xStyle = ['left', center.x1 + 'px'];
  var yStyle = ['top', center.y1 + 'px'];

  var $newDiv = $('<div/>')
    .attr('id', place.slug)
    .addClass('place-label')
    .css(yStyle[0], yStyle[1])
    .css(xStyle[0], xStyle[1]);
  var backgroundImage = '/images/collection/' + placeImage.filename;
  let displayDimension = placeImage.width;
  if (placeImage.width >= sizes.maxWidth) {
    displayDimension = sizes.maxWidth;
  }

  let backgroundSize = '';
  if (placeImage.width > placeImage.height) {
    const backgroundWidth = (
      (placeImage.width * sizes.maxWidth) / placeImage.height
    );
    backgroundSize = `${backgroundWidth}px ${sizes.maxWidth}px`;
  } else {
    backgroundSize = '100%';
  }

  var $placeLabelBackground = $('<div/>')
    .attr('id', placeImage.slug)
    .addClass('place-label-background')
    .css('background-image', 'url(' + backgroundImage + ')')
    .css('background-size', backgroundSize)
    .css('width', '0px')
    .css('height', '0px');

  $newDiv.append($placeLabelBackground);
  $('.Chart').append($newDiv);

  $newDiv.animate({
    opacity: 1,
    left: center.x2,
    top: center.y2,
  }, dur.default, function () {
    const labelRotation = _.sample(['-3', '3']);
    var $placeLabelText = $('<div/>')
      .addClass('place-label-text')
      .css({ transform: `rotate(${labelRotation}deg)` })
      .html(place.name);
    $placeLabelBackground.append($placeLabelText);
    $placeLabelText
      .animate({
        opacity: 1,
      }, 500);
  });

  $placeLabelBackground.animate({
    width: displayDimension + 'px',
    height: displayDimension + 'px',
  }, dur.default);

}

function drawPlace(el, projection, place, placeImage) {
  // Draw the location labels and images
  drawImageLabel(projection, place, placeImage);

  // Draw map circle, for each location
  drawLine(el, projection, place);

  // Draw map circle, for each location
  drawCircle(el, projection, place);
}

/**
 * Draw all the places when you enter the map
 *
 * @param el
 * @param projection
 * @param places
 * @param images
 */
export function drawPlaces(el, projection, places, images) {
  const dur = appDurations();

  // Remove any past circles
  d3.selectAll('.place-circle')
    .remove();

  _.each(places, function (place, i) {
    // Find the images for this location
    const placeImages = _.filter(images, function (o) {
      if (o.place == place.name) {
        return true;
      }
    });

    // Select a random image
    const placeImage = _.sample(placeImages);
    setTimeout(function () {
      drawPlace(el, projection, place, placeImage);
    }, dur.stagger * (i + 1 - 0.9));
  });
}

/**
 * Hide places that weren't clicked
 *
 * @param elemId
 * @param projection
 * @param places
 * @param maxWidth
 */
export function hidePlaces(elemId, projection, places, maxWidth) {
  _.each(places, function (place) {
    hidePlace(elemId, projection, place, maxWidth);
  });

}

/**
 * Hide a single place
 *
 * @param elemId
 * @param projection
 * @param place
 * @param maxWidth
 */
function hidePlace(elemId, projection, place, maxWidth) {
  const dur = appDurations();
  const sizes = appSizes();

  // Fade out the divs, that weren't clicked
  let $filteredPlaces = $('.place-label');
  $filteredPlaces.animate({
    opacity: 0,
  }, 300, function () {
    $filteredPlaces.remove();
  });

  // Fade out the SVG elements, that weren't clicked
  let shapes = ['line', 'circle'];
  _.each(shapes, function (shape) {
    let placeShape = d3.selectAll('#' + shape + '-' + place.slug);

    // Leave the circle for the clicked element in place
    if (placeShape.attr('id') != 'circle-' + elemId) {
      placeShape
        .select(shape)
        .transition()
        .duration(300)
        .attr('opacity', 0);
      placeShape
        .remove();
    } else {

      // Move the clicked highlight circle
      var circleGroup = '#circle-' + elemId;
      var line = linePoints(projection, place, maxWidth);
      d3.select(circleGroup)
        .transition()
        .duration(dur.bgZoom)
        .attr('transform', 'translate(' +
          ((sizes.screenWidth - sizes.infoWidthExpanded) / 2) +
          ',' + line.y1 + ')');

      /**
       * Animate selected map point circle
       */

      // Add a second stroke
      d3.select('#circle-' + elemId)
        .append('circle')
        .attr('id', 'circle-' + elemId + '-stroke')
        .attr('r', '5px')
        .attr('stroke-width', 4)
        .attr('stroke', '#33444C');
      var circlePathBase = '#circle-' + elemId + '-base';
      var circlePathStroke = '#circle-' + elemId + '-stroke';

      setTimeout(
        function () {
          d3.select(circlePathBase)
            .transition()
            .duration(dur.bounce)
            .attr('r', '45px')
            .attr('stroke-width', 9)
            .attr('stroke', '#0083c0')
            .attr('fill-opacity', .1)
            .transition()
            .duration(dur.bounce)
            .attr('r', '30px');

          d3.select(circlePathStroke)
            .transition()
            .duration(dur.bounce)
            .attr('r', '45px')
            .attr('stroke-width', 6)
            .attr('fill-opacity', .1)
            .transition()
            .duration(dur.bounce)
            .attr('r', '30px');
        },

      dur.bgZoom - 500);
    }
  });

}

<|endoftext|>


<commit_before>import { TextureLoader, NearestFilter, Vector2 } from "three";

export class RenderTileset {
    constructor(tileset, texture, renderer) {
        this._tileset = tileset;
        this.texture = texture;

        this._renderer = renderer;
    }

    static load(tileset, renderer) {
        const resolveTexture = (resolve, texture) => {
            texture.name = `Tileset ${tileset.name}`;
            texture.magFilter = texture.minFilter = NearestFilter;
            texture.generateMipmaps = false;
            resolve(new RenderTileset(tileset, texture, renderer));
        };

        if (tileset.tilesetType === "image") {
            return new Promise((resolve, reject) => {
                const texture = new TextureLoader().load(tileset.url, () => {
                    resolveTexture(resolve, texture);
                }, undefined, e => {
                    reject(e);
                });
            });
        } else if (tileset.tilesetType === "test") {
            return new Promise((resolve, reject) => {
                const testTileset = generateTestImage(
                    tileset.name || "a",
                    25, 25,
                    tileset.tileWidth, tileset.tileHeight
                );

                const texture = new TextureLoader().load(testTileset, () => {
                    resolveTexture(resolve, texture);
                }, undefined, e => {
                    reject(e);
                });
            });
        } else {
            console.error(`Unknown tileset type ${tileset.tilesetType}`);
        }
    }

    getTileUvs(id) {
        if (id === -1) {
            const v = new Vector2(-1, -1);
            return makeTrisFromQuad([v, v, v, v]);
        }

        const array = [];

        const tileWidth = this._tileset.tileWidth,
            tileHeight = this._tileset.tileHeight,
            textureWidth = this.texture.image.width,
            textureHeight = this.texture.image.height,
            width = textureWidth / tileWidth,
            y = Math.floor(id / width),
            x = Math.floor(id - y * width);

        for (let ly = y; ly < y + 2; ly++) {
            for (let lx = x; lx < x + 2; lx++) {
                array.push(new Vector2(
                    lx * tileWidth / textureWidth,
                    ly * tileHeight / textureHeight * -1 + 1
                ));
            }
        }

        return makeTrisFromQuad(array);
    }
}

function makeTrisFromQuad(quad) {
    return [
        [quad[0], quad[2], quad[1]],
        [quad[2], quad[3], quad[1]]
    ];
}

function generateTestImage(seed, width, height, tileWidth, tileHeight) {
    const canvas = document.createElement("canvas");
    canvas.width = width * tileWidth;
    canvas.height = height * tileHeight;
    const context = canvas.getContext("2d");

    randomSeed = seed.split("").reduce((acc, string) => acc + string.charCodeAt(0), 0);

    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            context.fillStyle = "#" + ("000000" +
                (Math.floor(random() * 0xffffff))).substr(-6);
            context.fillRect(
                x * tileWidth, y * tileHeight,
                (x + 1) * tileWidth, (y + 1) * tileHeight
            );
        }
    }

    return canvas.toDataURL();
}

let randomSeed = 0;

function random() {
    const x = Math.sin(randomSeed++) * 10000;
    return x - Math.floor(x);
}
<commit_msg>Change image tileset type to ortho<commit_after>import { TextureLoader, NearestFilter, Vector2 } from "three";

export class RenderTileset {
    constructor(tileset, texture, renderer) {
        this._tileset = tileset;
        this.texture = texture;

        this._renderer = renderer;
    }

    static load(tileset, renderer) {
        const resolveTexture = (resolve, texture) => {
            texture.name = `Tileset ${tileset.name}`;
            texture.magFilter = texture.minFilter = NearestFilter;
            texture.generateMipmaps = false;
            resolve(new RenderTileset(tileset, texture, renderer));
        };

        if (tileset.tilesetType === "ortho") {
            return new Promise((resolve, reject) => {
                const texture = new TextureLoader().load(tileset.url, () => {
                    resolveTexture(resolve, texture);
                }, undefined, e => {
                    reject(e);
                });
            });
        } else if (tileset.tilesetType === "test") {
            return new Promise((resolve, reject) => {
                const testTileset = generateTestImage(
                    tileset.name || "a",
                    25, 25,
                    tileset.tileWidth, tileset.tileHeight
                );

                const texture = new TextureLoader().load(testTileset, () => {
                    resolveTexture(resolve, texture);
                }, undefined, e => {
                    reject(e);
                });
            });
        } else {
            console.error(`Unknown tileset type ${tileset.tilesetType}`);
        }
    }

    getTileUvs(id) {
        if (id === -1) {
            const v = new Vector2(-1, -1);
            return makeTrisFromQuad([v, v, v, v]);
        }

        const array = [];

        const tileWidth = this._tileset.tileWidth,
            tileHeight = this._tileset.tileHeight,
            textureWidth = this.texture.image.width,
            textureHeight = this.texture.image.height,
            width = textureWidth / tileWidth,
            y = Math.floor(id / width),
            x = Math.floor(id - y * width);

        for (let ly = y; ly < y + 2; ly++) {
            for (let lx = x; lx < x + 2; lx++) {
                array.push(new Vector2(
                    lx * tileWidth / textureWidth,
                    ly * tileHeight / textureHeight * -1 + 1
                ));
            }
        }

        return makeTrisFromQuad(array);
    }
}

function makeTrisFromQuad(quad) {
    return [
        [quad[0], quad[2], quad[1]],
        [quad[2], quad[3], quad[1]]
    ];
}

function generateTestImage(seed, width, height, tileWidth, tileHeight) {
    const canvas = document.createElement("canvas");
    canvas.width = width * tileWidth;
    canvas.height = height * tileHeight;
    const context = canvas.getContext("2d");

    randomSeed = seed.split("").reduce((acc, string) => acc + string.charCodeAt(0), 0);

    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            context.fillStyle = "#" + ("000000" +
                (Math.floor(random() * 0xffffff))).substr(-6);
            context.fillRect(
                x * tileWidth, y * tileHeight,
                (x + 1) * tileWidth, (y + 1) * tileHeight
            );
        }
    }

    return canvas.toDataURL();
}

let randomSeed = 0;

function random() {
    const x = Math.sin(randomSeed++) * 10000;
    return x - Math.floor(x);
}
<|endoftext|>


<commit_before>'use strict';

describe('Service: QuerySet', () => {
    let $httpBackend,
        QuerySet,
        Authorization,
        SmartSearchService;

    beforeEach(angular.mock.module('Tower', ($provide) =>{
        // @todo: improve app source / write testing utilities for interim
        // we don't want to be concerned with this provision in every test that involves the Rest module
        Authorization = {
            getToken: () => true,
            isUserLoggedIn: angular.noop
        };
        $provide.value('LoadBasePaths', angular.noop);
        $provide.value('Authorization', Authorization);
    }));
    beforeEach(angular.mock.module('RestServices'));

    beforeEach(angular.mock.inject((_$httpBackend_, _QuerySet_, _SmartSearchService_) => {
        $httpBackend = _$httpBackend_;
        QuerySet = _QuerySet_;
        SmartSearchService = _SmartSearchService_;

        // @todo: improve app source
        // config.js / local_settings emit $http requests in the app's run block
        $httpBackend
            .whenGET(/\/static\/*/)
            .respond(200, {});
        // @todo: improve appsource
        // provide api version via package.json config block
        $httpBackend
            .whenGET('/api')
            .respond(200, '');
    }));

    describe('fn encodeParam', () => {
        it('should encode parameters properly', () =>{
            expect(QuerySet.encodeParam({term: "name:foo", searchTerm: true})).toEqual({"name__icontains_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "-name:foo", searchTerm: true})).toEqual({"not__name__icontains_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "name:'foo bar'", searchTerm: true})).toEqual({"name__icontains_DEFAULT" : "'foo bar'"});
            expect(QuerySet.encodeParam({term: "-name:'foo bar'", searchTerm: true})).toEqual({"not__name__icontains_DEFAULT" : "'foo bar'"});
            expect(QuerySet.encodeParam({term: "organization:foo", relatedSearchTerm: true})).toEqual({"organization__search_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "-organization:foo", relatedSearchTerm: true})).toEqual({"not__organization__search_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "organization.name:foo", relatedSearchTerm: true})).toEqual({"organization__name" : "foo"});
            expect(QuerySet.encodeParam({term: "-organization.name:foo", relatedSearchTerm: true})).toEqual({"not__organization__name" : "foo"});
            expect(QuerySet.encodeParam({term: "id:11", searchTerm: true})).toEqual({"id__icontains_DEFAULT" : "11"});
            expect(QuerySet.encodeParam({term: "-id:11", searchTerm: true})).toEqual({"not__id__icontains_DEFAULT" : "11"});
            expect(QuerySet.encodeParam({term: "id:>11", searchTerm: true})).toEqual({"id__gt" : "11"});
            expect(QuerySet.encodeParam({term: "-id:>11", searchTerm: true})).toEqual({"not__id__gt" : "11"});
            expect(QuerySet.encodeParam({term: "id:>=11", searchTerm: true})).toEqual({"id__gte" : "11"});
            expect(QuerySet.encodeParam({term: "-id:>=11", searchTerm: true})).toEqual({"not__id__gte" : "11"});
            expect(QuerySet.encodeParam({term: "id:<11", searchTerm: true})).toEqual({"id__lt" : "11"});
            expect(QuerySet.encodeParam({term: "-id:<11", searchTerm: true})).toEqual({"not__id__lt" : "11"});
            expect(QuerySet.encodeParam({term: "id:<=11", searchTerm: true})).toEqual({"id__lte" : "11"});
            expect(QuerySet.encodeParam({term: "-id:<=11", searchTerm: true})).toEqual({"not__id__lte" : "11"});
        });
    });

    describe('fn search', () => {
        let pattern = /\/api\/v1\/inventories\/(.+)\/groups\/*/,
            endpoint = '/api/v1/inventories/1/groups/',
            params = {
            or__name: 'borg',
            or__description__icontains: 'assimilate'
        };

        it('should GET expected URL', () =>{
            $httpBackend
                .expectGET(pattern)
                .respond(200, {});
            QuerySet.search(endpoint, params).then((data) =>{
                expect(data.config.url).toEqual('/api/v1/inventories/1/groups/?or__name=borg&or__description__icontains=assimilate');
            });
            $httpBackend.flush();
        });

        xit('should memoize new DjangoModel', ()=>{});
        xit('should not replace memoized DjangoModel', ()=>{});
        xit('should provide an alias interface', ()=>{});

        afterEach(() => {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });
    });

});
<commit_msg>Fixed unit tests<commit_after>'use strict';

describe('Service: QuerySet', () => {
    let $httpBackend,
        QuerySet,
        Authorization,
        SmartSearchService;

    beforeEach(angular.mock.module('Tower', ($provide) =>{
        // @todo: improve app source / write testing utilities for interim
        // we don't want to be concerned with this provision in every test that involves the Rest module
        Authorization = {
            getToken: () => true,
            isUserLoggedIn: angular.noop
        };
        $provide.value('LoadBasePaths', angular.noop);
        $provide.value('Authorization', Authorization);
    }));
    beforeEach(angular.mock.module('RestServices'));

    beforeEach(angular.mock.inject((_$httpBackend_, _QuerySet_, _SmartSearchService_) => {
        $httpBackend = _$httpBackend_;
        QuerySet = _QuerySet_;
        SmartSearchService = _SmartSearchService_;

        // @todo: improve app source
        // config.js / local_settings emit $http requests in the app's run block
        $httpBackend
            .whenGET(/\/static\/*/)
            .respond(200, {});
        // @todo: improve appsource
        // provide api version via package.json config block
        $httpBackend
            .whenGET('/api')
            .respond(200, '');
    }));

    describe('fn encodeParam', () => {
        it('should encode parameters properly', () =>{
            expect(QuerySet.encodeParam({term: "name:foo", searchTerm: true})).toEqual({"name__icontains_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "-name:foo", searchTerm: true})).toEqual({"not__name__icontains_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "name:'foo bar'", searchTerm: true})).toEqual({"name__icontains_DEFAULT" : "'foo%20bar'"});
            expect(QuerySet.encodeParam({term: "-name:'foo bar'", searchTerm: true})).toEqual({"not__name__icontains_DEFAULT" : "'foo%20bar'"});
            expect(QuerySet.encodeParam({term: "organization:foo", relatedSearchTerm: true})).toEqual({"organization__search_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "-organization:foo", relatedSearchTerm: true})).toEqual({"not__organization__search_DEFAULT" : "foo"});
            expect(QuerySet.encodeParam({term: "organization.name:foo", relatedSearchTerm: true})).toEqual({"organization__name" : "foo"});
            expect(QuerySet.encodeParam({term: "-organization.name:foo", relatedSearchTerm: true})).toEqual({"not__organization__name" : "foo"});
            expect(QuerySet.encodeParam({term: "id:11", searchTerm: true})).toEqual({"id__icontains_DEFAULT" : "11"});
            expect(QuerySet.encodeParam({term: "-id:11", searchTerm: true})).toEqual({"not__id__icontains_DEFAULT" : "11"});
            expect(QuerySet.encodeParam({term: "id:>11", searchTerm: true})).toEqual({"id__gt" : "11"});
            expect(QuerySet.encodeParam({term: "-id:>11", searchTerm: true})).toEqual({"not__id__gt" : "11"});
            expect(QuerySet.encodeParam({term: "id:>=11", searchTerm: true})).toEqual({"id__gte" : "11"});
            expect(QuerySet.encodeParam({term: "-id:>=11", searchTerm: true})).toEqual({"not__id__gte" : "11"});
            expect(QuerySet.encodeParam({term: "id:<11", searchTerm: true})).toEqual({"id__lt" : "11"});
            expect(QuerySet.encodeParam({term: "-id:<11", searchTerm: true})).toEqual({"not__id__lt" : "11"});
            expect(QuerySet.encodeParam({term: "id:<=11", searchTerm: true})).toEqual({"id__lte" : "11"});
            expect(QuerySet.encodeParam({term: "-id:<=11", searchTerm: true})).toEqual({"not__id__lte" : "11"});
        });
    });

    describe('fn search', () => {
        let pattern = /\/api\/v1\/inventories\/(.+)\/groups\/*/,
            endpoint = '/api/v1/inventories/1/groups/',
            params = {
            or__name: 'borg',
            or__description__icontains: 'assimilate'
        };

        it('should GET expected URL', () =>{
            $httpBackend
                .expectGET(pattern)
                .respond(200, {});
            QuerySet.search(endpoint, params).then((data) =>{
                expect(data.config.url).toEqual('/api/v1/inventories/1/groups/?or__name=borg&or__description__icontains=assimilate');
            });
            $httpBackend.flush();
        });

        xit('should memoize new DjangoModel', ()=>{});
        xit('should not replace memoized DjangoModel', ()=>{});
        xit('should provide an alias interface', ()=>{});

        afterEach(() => {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });
    });

});
<|endoftext|>


<commit_before>'use strict';

var React = require('react'),
	ReactDOMServer = require('react-dom/server'),
	T = React.PropTypes;

var defaultColors = [
	'rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
	'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
	'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
	'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
	'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
	'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
	'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
	'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
	'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
	'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
	'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
	'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)',
].map(function(color){ return { value: color } });

var defaultItems = [

	{ label:'Formats', type:'group', items: [
		{ label:'Font', type:'font', items: [
			{ label:'Sans Serif',  value:'sans-serif', selected:true },
			{ label:'Serif',       value:'serif' },
			{ label:'Monospace',   value:'monospace' }
		]},
		{ label:'Size', type:'size', items: [
			{ label:'Small',  value:'10px' },
			{ label:'Normal', value:'13px', selected:true },
			{ label:'Large',  value:'18px' },
			{ label:'Huge',   value:'32px' }
		]},
		{ label:'Alignment', type:'align', items: [
			{ label:'', value:'', selected:true },
			{ label:'', value:'center' },
			{ label:'', value:'right' },
			{ label:'', value:'justify' }
		]}
	]},

	{ label:'Text', type:'group', items: [
		{ type:'bold', label:'Bold' },
		{ type:'italic', label:'Italic' },
		{ type:'strike', label:'Strike' },
		{ type:'underline', label:'Underline' },
		{ type:'color', label:'Color', items:defaultColors },
		{ type:'background', label:'Background color', items:defaultColors },
		{ type:'link', label:'Link' }
	]},

	{ label:'Blocks', type:'group', items: [
		{ type:'list', value:'bullet' },
		{ type:'list', value:'ordered' }
	]},

	// { label:'Blocks', type:'group', items: [
	// 	{ type:'image', label:'Image' }
	// ]}

];

var QuillToolbar = React.createClass({

	displayName: 'Quill Toolbar',

	propTypes: {
		id:        T.string,
		className: T.string,
		items:     T.array
	},

	getDefaultProps: function(){
		return {
			items: defaultItems
		};
	},

	renderGroup: function(item, key) {
		return React.DOM.span({
			key: item.label || key,
			className:'ql-formats' },
			item.items.map(this.renderItem)
		);
	},

	renderChoiceItem: function(item, key) {
		return React.DOM.option({
			key: item.label || item.value || key,
			value:item.value },
			item.label
		);
	},

	renderChoices: function(item, key) {
		var attrs = {
			key: item.label || key,
			title: item.label,
			className: 'ql-'+item.type
		};
		var self = this;
		var choiceItems = item.items.map(function(item, key) {
			if (item.selected) {
				attrs.defaultValue = item.value;
			}
			return self.renderChoiceItem(item, key);
		})
		return React.DOM.select(attrs, choiceItems);
	},

	renderButton: function(item, key) {
		return React.DOM.button({
			key: item.label || item.value || key,
			value: item.value,
			className: 'ql-'+item.type,
			title: item.label },
			item.children
		);
	},

	renderAction: function(item, key) {
		return React.DOM.span({
			key: item.label || item.value || key,
			className: 'ql-'+item.type,
			title: item.label },
			item.children
		);
	},

	renderItem: function(item, key) {
		switch (item.type) {
			case 'group':
				return this.renderGroup(item, key);
			case 'font':
			case 'align':
			case 'size':
			case 'color':
			case 'background':
				return this.renderChoices(item, key);
			case 'bold':
			case 'italic':
			case 'underline':
			case 'strike':
			case 'link':
			case 'list':
				return this.renderButton(item, key);
			default:
				return this.renderAction(item, key);
		}
	},

	getClassName: function() {
		return 'quill-toolbar ' + (this.props.className||'');
	},

	render: function() {
		var children = this.props.items.map(this.renderItem);
		var html = children.map(ReactDOMServer.renderToStaticMarkup).join('');
		return React.DOM.div({
			className: this.getClassName(),
			style: this.props.style || {},
			dangerouslySetInnerHTML: { __html:html }
		});
	}

});

module.exports = QuillToolbar;
QuillToolbar.defaultItems = defaultItems;
QuillToolbar.defaultColors = defaultColors;
<commit_msg>Re-enable image button<commit_after>'use strict';

var React = require('react'),
	ReactDOMServer = require('react-dom/server'),
	T = React.PropTypes;

var defaultColors = [
	'rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
	'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
	'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
	'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
	'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
	'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
	'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
	'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
	'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
	'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
	'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
	'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)',
].map(function(color){ return { value: color } });

var defaultItems = [

	{ label:'Formats', type:'group', items: [
		{ label:'Font', type:'font', items: [
			{ label:'Sans Serif',  value:'sans-serif', selected:true },
			{ label:'Serif',       value:'serif' },
			{ label:'Monospace',   value:'monospace' }
		]},
		{ label:'Size', type:'size', items: [
			{ label:'Small',  value:'10px' },
			{ label:'Normal', value:'13px', selected:true },
			{ label:'Large',  value:'18px' },
			{ label:'Huge',   value:'32px' }
		]},
		{ label:'Alignment', type:'align', items: [
			{ label:'', value:'', selected:true },
			{ label:'', value:'center' },
			{ label:'', value:'right' },
			{ label:'', value:'justify' }
		]}
	]},

	{ label:'Text', type:'group', items: [
		{ type:'bold', label:'Bold' },
		{ type:'italic', label:'Italic' },
		{ type:'strike', label:'Strike' },
		{ type:'underline', label:'Underline' },
		{ type:'color', label:'Color', items:defaultColors },
		{ type:'background', label:'Background color', items:defaultColors },
		{ type:'link', label:'Link' }
	]},

	{ label:'Blocks', type:'group', items: [
		{ type:'list', value:'bullet' },
		{ type:'list', value:'ordered' }
	]},

	{ label:'Blocks', type:'group', items: [
		{ type:'image', label:'Image' }
	]}

];

var QuillToolbar = React.createClass({

	displayName: 'Quill Toolbar',

	propTypes: {
		id:        T.string,
		className: T.string,
		items:     T.array
	},

	getDefaultProps: function(){
		return {
			items: defaultItems
		};
	},

	renderGroup: function(item, key) {
		return React.DOM.span({
			key: item.label || key,
			className:'ql-formats' },
			item.items.map(this.renderItem)
		);
	},

	renderChoiceItem: function(item, key) {
		return React.DOM.option({
			key: item.label || item.value || key,
			value:item.value },
			item.label
		);
	},

	renderChoices: function(item, key) {
		var attrs = {
			key: item.label || key,
			title: item.label,
			className: 'ql-'+item.type
		};
		var self = this;
		var choiceItems = item.items.map(function(item, key) {
			if (item.selected) {
				attrs.defaultValue = item.value;
			}
			return self.renderChoiceItem(item, key);
		})
		return React.DOM.select(attrs, choiceItems);
	},

	renderButton: function(item, key) {
		return React.DOM.button({
			key: item.label || item.value || key,
			value: item.value,
			className: 'ql-'+item.type,
			title: item.label },
			item.children
		);
	},

	renderAction: function(item, key) {
		return React.DOM.span({
			key: item.label || item.value || key,
			className: 'ql-'+item.type,
			title: item.label },
			item.children
		);
	},

	renderItem: function(item, key) {
		switch (item.type) {
			case 'group':
				return this.renderGroup(item, key);
			case 'font':
			case 'align':
			case 'size':
			case 'color':
			case 'background':
				return this.renderChoices(item, key);
			case 'bold':
			case 'italic':
			case 'underline':
			case 'strike':
			case 'link':
			case 'list':
			case 'image':
				return this.renderButton(item, key);
			default:
				return this.renderAction(item, key);
		}
	},

	getClassName: function() {
		return 'quill-toolbar ' + (this.props.className||'');
	},

	render: function() {
		var children = this.props.items.map(this.renderItem);
		var html = children.map(ReactDOMServer.renderToStaticMarkup).join('');
		return React.DOM.div({
			className: this.getClassName(),
			style: this.props.style || {},
			dangerouslySetInnerHTML: { __html:html }
		});
	}

});

module.exports = QuillToolbar;
QuillToolbar.defaultItems = defaultItems;
QuillToolbar.defaultColors = defaultColors;
<|endoftext|>


<commit_before>/*
  Ignite Specific Additions -
  this should not be taken an example of good code by anyone
*/
(function($, deck, undefined) {
	var $d = $(document)

	// TODO: change to false to enable auto-advance
	var autoAdvancing = true

	var timers = {}

	// interval timer for auto-advance
	var autoAdvanceTimer

	// Toggle timers for fadein/fadeout
	var enableTimer = true

  $d.bind('deck.init', function () {
    $d.bind('keydown', function(event) {
      if (event.which === 84) {
        // disable timers
        if (enableTimer) {
          console.log("transition timing disabled")
          enableTimer = false
        }
        else {
          enableTimer = true
          console.log("transition timing enabled")
        }
      }
      if (event.which === 65) {
        // reset current autoadvance timer
        clearInterval(autoAdvanceTimer)
        if (autoAdvanceTimer === null) {
          console.log("autoadvance disabled")
          // true makes it not start the autoadvance timer again
          autoAdvancing = true
          // clears the timer so it can be reenabled
          autoAdvanceTimer = null
        }
        else {
          console.log("autoadvance enabled - will start on next slide change")
          // will restart auto-advance on next slide transition
          autoAdvancing = false
        }
      }
    })
  })

	$d.bind('deck.change', function (event, from, to) {
    // console.log("from " + from + " to " + to)
	  var $subs = $.deck('getSlide', to).find('.sub')
    timers[to] = timers[to] || []
	  if (timers[to].length) {
	    // if no timers for that slide, make an array for them
	    // clear any existing timers
	    _.each(timers[to], function (timer) {
	      clearInterval(timer)
	    })
	    timers[to] = []
	  }
    $.each($subs, function(index, sub) {
      // fade in
      if (enableTimer && $(sub).attr('in')) {
        $(sub).hide()
        // show after the specified time
        timers[to].push(setTimeout(function () {
          $(sub).fadeIn(200)
        }, $(sub).attr('in') * 1000))
      }
      // fade out
      if (enableTimer && $(sub).attr('out')) {
        $(sub).show()
        timers[to].push(setTimeout(function () {
          $(sub).fadeOut(200)
        }, $(sub).attr('out') * 1000))
      }
    })

	  // Enable autoadvance once we reach slide 1
    if (!autoAdvancing && to === 1) {
      // $.deck('enableScale')
      console.log("Auto-Advance Enabled")
      autoAdvancing = true
      // Autoadvance every 15 seconds
      autoAdvanceTimer = setInterval(function () {
          $.deck('next')
      }, 15000)
    }
	})
})(jQuery, 'deck');<commit_msg>disabled all timers by default. can be turned on by hitting t then a at the first slide<commit_after>/*
  Ignite Specific Additions -
  this should not be taken an example of good code by anyone
*/
(function($, deck, undefined) {
	var $d = $(document)

	// TODO: change to false to enable auto-advance
	var autoAdvancing = true

	var timers = {}

	// interval timer for auto-advance
	var autoAdvanceTimer

	// Toggle timers for fadein/fadeout
	var enableTimer = false

	// Enable/disable timers for transitions and builds
  $d.bind('deck.init', function () {
    $d.bind('keydown', function(event) {
      if (event.which === 84) {
        // disable timers
        if (enableTimer) {
          console.log("transition timing disabled")
          enableTimer = false
        }
        else {
          enableTimer = true
          console.log("transition timing enabled")
        }
      }
      if (event.which === 65) {
        // reset current autoadvance timer
        clearInterval(autoAdvanceTimer)
        if (autoAdvanceTimer === null) {
          console.log("autoadvance disabled")
          // true makes it not start the autoadvance timer again
          autoAdvancing = true
          // clears the timer so it can be reenabled
          autoAdvanceTimer = null
        }
        else {
          console.log("autoadvance enabled - will start on next slide change")
          // will restart auto-advance on next slide transition
          autoAdvancing = false
        }
      }
    })
  })

	$d.bind('deck.change', function (event, from, to) {
    // console.log("from " + from + " to " + to)
	  var $subs = $.deck('getSlide', to).find('.sub')
    timers[to] = timers[to] || []
	  if (timers[to].length) {
	    // if no timers for that slide, make an array for them
	    // clear any existing timers
	    _.each(timers[to], function (timer) {
	      clearInterval(timer)
	    })
	    timers[to] = []
	  }
    $.each($subs, function(index, sub) {
      // fade in
      if (enableTimer && $(sub).attr('in')) {
        $(sub).hide()
        // show after the specified time
        timers[to].push(setTimeout(function () {
          $(sub).fadeIn(200)
        }, $(sub).attr('in') * 1000))
      }
      // fade out
      if (enableTimer && $(sub).attr('out')) {
        $(sub).show()
        timers[to].push(setTimeout(function () {
          $(sub).fadeOut(200)
        }, $(sub).attr('out') * 1000))
      }
    })

	  // Enable autoadvance once we reach slide 1
    if (!autoAdvancing && to === 1) {
      // $.deck('enableScale')
      console.log("Auto-Advance Enabled")
      autoAdvancing = true
      // Autoadvance every 15 seconds
      autoAdvanceTimer = setInterval(function () {
          $.deck('next')
      }, 15000)
    }
	})
})(jQuery, 'deck');<|endoftext|>


<commit_before>// Copyright (c) 2007-2009 gocept gmbh & co. kg
// See also LICENSE.txt
// $Id$

zeit.cms.LightboxForm = Class.extend({
    // Javascript support for forms in a light box

    construct: function(url) {
        // URL: URL of the form to load
        //
        var othis = this;
        this.lightbox = new gocept.Lightbox($('body'));
        this.content_box = this.lightbox.content_box;
        connect(this.content_box, 'onclick', this, 'handle_click');
        connect(window, 'zeit.cms.LightboxReload', function(event) {
            othis.loading();
        });

        var d = this.lightbox.load_url(url);
        d.addCallback(
            function(result) {
                othis.post_process_html();
                return result;
            });

    },

    handle_click: function(event) {
        var target = event.target()
        if (target.nodeName != 'INPUT')
            return
        if (target.type != 'button')
            return
        this.handle_submit(target.name);
        event.stop();
    },

    handle_submit: function(action) {
        var othis = this;

        // collect data
        var elements = filter(
            function(element) {
                return (element.type != 'button')
            }, this.form.elements);

        var data = map(function(element) {
                if ((element.type == 'radio' || element.type == 'checkbox')
                    && !element.checked) {
                    return
                }
                return element.name + "=" + encodeURIComponent(element.value)
            }, elements);
        data.push(action + '=clicked')
        data = data.join('&');
        var submit_to = this.form.getAttribute('action');

        // clear box with loading message
        this.loading();

        var d = doXHR(submit_to, {
            'method': 'POST',
            'headers': {
                'Content-Type': 'application/x-www-form-urlencoded'},
            'sendContent': data});
        d.addCallbacks(
            function(result) {
                othis.content_box.innerHTML = result.responseText;
                if (action.indexOf('form.actions.') != 0) {
                    // This was no action. No error could have been generated.
                    // Also the form is not done, yet.
                    return result;
                }
                var errors = getFirstElementByTagAndClassName(
                    'ul', 'errors', othis.content_box)
                if (errors != null) {
                    return result;
                }
                var next_url_node = getFirstElementByTagAndClassName(
                    'span', 'nextUrl', othis.content_box);
                if (next_url_node == null) {
                    return result;
                }
                window.location = next_url_node.textContent;
                return null;
            },
            function(error) {
                logError(error.req.status, error.req.statusText);
                var parser = new DOMParser()
                var doc = parser.parseFromString(
                    error.req.responseText, "text/xml");
                document.firstChild.nextSibling.innerHTML = doc.firstChild.nextSibling.innerHTML;
            });
        d.addCallback(function(result) {
            if (result === null) {
                return null;
            }
            othis.post_process_html();
            return result;
        });
    },

    loading: function(message) {
        if (typeof message == 'undefined') {
            message = 'Loading ...';
        }
        this.content_box.innerHTML = 'Loading ...';
    },

    post_process_html: function() {
        var othis = this;
        // Change all submits to buttons to be able to handle them in
        // java script
        forEach(
            getElementsByTagAndClassName(
                'input', null, othis.content_box),
            function(button) {
                if (button.type == 'submit') {
                    button.type = 'button';
                }
            });
        othis.form = $('lightbox.form');
        if (othis.form != null) {
            connect(othis.form, 'onsubmit', function(event) {
                // prevent accidential submit
                event.stop()
            });
        }

        // check for javascript
        forEach(
            getElementsByTagAndClassName('SCRIPT', null,
                                         othis.content_box),
            function(script) {
                eval(script.text);
            });
    },

});

zeit.cms.lightbox_form = function(url) {
    new zeit.cms.LightboxForm(url);
}
<commit_msg>allow to specify the element to put the lighbox in<commit_after>// Copyright (c) 2007-2009 gocept gmbh & co. kg
// See also LICENSE.txt
// $Id$

zeit.cms.LightboxForm = Class.extend({
    // Javascript support for forms in a light box

    construct: function(url, container) {
        // URL: URL of the form to load
        if (isUndefinedOrNull(container)) {
            container = $('body');
        }
        var othis = this;
        this.lightbox = new gocept.Lightbox(container);
        this.content_box = this.lightbox.content_box;
        connect(this.content_box, 'onclick', this, 'handle_click');
        connect(window, 'zeit.cms.LightboxReload', function(event) {
            othis.loading();
        });

        var d = this.lightbox.load_url(url);
        d.addCallback(
            function(result) {
                othis.post_process_html();
                return result;
            });

    },

    handle_click: function(event) {
        var target = event.target()
        if (target.nodeName != 'INPUT')
            return
        if (target.type != 'button')
            return
        this.handle_submit(target.name);
        event.stop();
    },

    handle_submit: function(action) {
        var othis = this;

        // collect data
        var elements = filter(
            function(element) {
                return (element.type != 'button')
            }, this.form.elements);

        var data = map(function(element) {
                if ((element.type == 'radio' || element.type == 'checkbox')
                    && !element.checked) {
                    return
                }
                return element.name + "=" + encodeURIComponent(element.value)
            }, elements);
        data.push(action + '=clicked')
        data = data.join('&');
        var submit_to = this.form.getAttribute('action');

        // clear box with loading message
        this.loading();

        var d = doXHR(submit_to, {
            'method': 'POST',
            'headers': {
                'Content-Type': 'application/x-www-form-urlencoded'},
            'sendContent': data});
        d.addCallbacks(
            function(result) {
                othis.content_box.innerHTML = result.responseText;
                if (action.indexOf('form.actions.') != 0) {
                    // This was no action. No error could have been generated.
                    // Also the form is not done, yet.
                    return result;
                }
                var errors = getFirstElementByTagAndClassName(
                    'ul', 'errors', othis.content_box)
                if (errors != null) {
                    return result;
                }
                var next_url_node = getFirstElementByTagAndClassName(
                    'span', 'nextUrl', othis.content_box);
                if (next_url_node == null) {
                    return result;
                }
                window.location = next_url_node.textContent;
                return null;
            },
            function(error) {
                logError(error.req.status, error.req.statusText);
                var parser = new DOMParser()
                var doc = parser.parseFromString(
                    error.req.responseText, "text/xml");
                document.firstChild.nextSibling.innerHTML = doc.firstChild.nextSibling.innerHTML;
            });
        d.addCallback(function(result) {
            if (result === null) {
                return null;
            }
            othis.post_process_html();
            return result;
        });
    },

    loading: function(message) {
        if (typeof message == 'undefined') {
            message = 'Loading ...';
        }
        this.content_box.innerHTML = 'Loading ...';
    },

    post_process_html: function() {
        var othis = this;
        // Change all submits to buttons to be able to handle them in
        // java script
        forEach(
            getElementsByTagAndClassName(
                'input', null, othis.content_box),
            function(button) {
                if (button.type == 'submit') {
                    button.type = 'button';
                }
            });
        othis.form = $('lightbox.form');
        if (othis.form != null) {
            connect(othis.form, 'onsubmit', function(event) {
                // prevent accidential submit
                event.stop()
            });
        }

        // check for javascript
        forEach(
            getElementsByTagAndClassName('SCRIPT', null,
                                         othis.content_box),
            function(script) {
                eval(script.text);
            });
    },

});

zeit.cms.lightbox_form = function(url) {
    new zeit.cms.LightboxForm(url);
}
<|endoftext|>


<commit_before>import google from 'googleapis';
import { stringify } from 'querystring';
import fetch from 'node-fetch';
const OAuth2 = google.auth.OAuth2;
import BrowserWindow from 'browser-window';

function getAuthenticationUrl(scopes, clientId, clientSecret) {
  const oauth2Client = new OAuth2(
    clientId,
    clientSecret,
    'urn:ietf:wg:oauth:2.0:oob'
  );

  const url = oauth2Client.generateAuthUrl({
    access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
    scope: scopes // If you only need one scope you can pass it as string
  });
  return url;
}

function authorizeApp(url, __unused_BrowserWindow, browserWindowParams) {

  return new Promise( (resolve, reject) => {

    const win = new BrowserWindow(browserWindowParams || {'use-content-size': true });

    win.loadUrl(url);

    win.on('closed', () => {
      reject(new Error('User closed  the window'));
    });

    win.on('page-title-updated', () => {
      setImmediate(() => {
        const title = win.getTitle();
        if (title.startsWith('Denied')) {
          reject(new Error(title.split(/[ =]/)[2]));
          win.removeAllListeners('closed');
          win.close();
        } else if (title.startsWith('Success')) {
          resolve(title.split(/[ =]/)[2]);
          win.removeAllListeners('closed');
          win.close();
        }
      });
    });
  });
}

export default function electronGoogleOauth(__unused_BrowserWindow, browserWindowParams) {
  // to keep compatibility, if browserwindow arg is supplied
  // we ignore it
  if (__unused_BrowserWindow && browserWindowParams) {
    browserWindowParams = __unused_BrowserWindow;
  }

  const exports = {
    getAuthorizationCode(scopes, clientId, clientSecret) {
      const url = getAuthenticationUrl(scopes, clientId, clientSecret);
      return authorizeApp(url, BrowserWindow, browserWindowParams);
    },

    async getAccessToken(scopes, clientId, clientSecret) {
      const authorizationCode = await exports.getAuthorizationCode(scopes, clientId, clientSecret);

      const data = stringify({
        code: authorizationCode,
        client_id: clientId,
        client_secret: clientSecret,
        grant_type: 'authorization_code',
        redirect_uri: 'urn:ietf:wg:oauth:2.0:oob'
      });

      const res = await fetch('https://accounts.google.com/o/oauth2/token', {
        method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: data
      });

      return await res.json();
    }

  };

  return exports;
}

<commit_msg>Added http proxy option. Updated loadUrl to be loadURL<commit_after>import google from 'googleapis';
import { stringify } from 'querystring';
import fetch from 'node-fetch';
const OAuth2 = google.auth.OAuth2;
import BrowserWindow from 'browser-window';

function getAuthenticationUrl(scopes, clientId, clientSecret) {
  const oauth2Client = new OAuth2(
    clientId,
    clientSecret,
    'urn:ietf:wg:oauth:2.0:oob'
  );

  const url = oauth2Client.generateAuthUrl({
    access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
    scope: scopes // If you only need one scope you can pass it as string
  });
  return url;
}

function authorizeApp(url, __unused_BrowserWindow, browserWindowParams) {

  return new Promise( (resolve, reject) => {

    const win = new BrowserWindow(browserWindowParams || {'use-content-size': true });

    win.loadURL(url);

    win.on('closed', () => {
      reject(new Error('User closed  the window'));
    });

    win.on('page-title-updated', () => {
      setImmediate(() => {
        const title = win.getTitle();
        if (title.startsWith('Denied')) {
          reject(new Error(title.split(/[ =]/)[2]));
          win.removeAllListeners('closed');
          win.close();
        } else if (title.startsWith('Success')) {
          resolve(title.split(/[ =]/)[2]);
          win.removeAllListeners('closed');
          win.close();
        }
      });
    });
  });
}

export default function electronGoogleOauth(__unused_BrowserWindow, browserWindowParams, httpAgent) {
  // to keep compatibility, if browserwindow arg is supplied
  // we ignore it
  if (__unused_BrowserWindow && browserWindowParams) {
    browserWindowParams = __unused_BrowserWindow;
  }

  const exports = {
    getAuthorizationCode(scopes, clientId, clientSecret) {
      const url = getAuthenticationUrl(scopes, clientId, clientSecret);
      return authorizeApp(url, BrowserWindow, browserWindowParams);
    },

    async getAccessToken(scopes, clientId, clientSecret) {
      const authorizationCode = await exports.getAuthorizationCode(scopes, clientId, clientSecret);

      const data = stringify({
        code: authorizationCode,
        client_id: clientId,
        client_secret: clientSecret,
        grant_type: 'authorization_code',
        redirect_uri: 'urn:ietf:wg:oauth:2.0:oob'
      });

      const res = await fetch('https://accounts.google.com/o/oauth2/token', {
        method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: data,
        agent: httpAgent
      });

      return await res.json();
    }

  };

  return exports;
}

<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var MATH_CONST = require('../../math/const');
var WrapAngle = require('../../math/angle/Wrap');
var WrapAngleDegrees = require('../../math/angle/WrapDegrees');

//  global bitmask flag for GameObject.renderMask (used by Scale)
var _FLAG = 4; // 0100

/**
 * Provides methods used for getting and setting the position, scale and rotation of a Game Object.
 *
 * @name Phaser.GameObjects.Components.Transform
 * @since 3.0.0
 */

var Transform = {

    /**
     * Private internal value. Holds the horizontal scale value.
     *
     * @name Phaser.GameObjects.Components.Transform#_scaleX
     * @type {float}
     * @private
     * @default 1
     * @since 3.0.0
     */
    _scaleX: 1,

    /**
     * Private internal value. Holds the vertical scale value.
     *
     * @name Phaser.GameObjects.Components.Transform#_scaleY
     * @type {float}
     * @private
     * @default 1
     * @since 3.0.0
     */
    _scaleY: 1,

    /**
     * Private internal value. Holds the rotation value in radians.
     *
     * @name Phaser.GameObjects.Components.Transform#_rotation
     * @type {float}
     * @private
     * @default 0
     * @since 3.0.0
     */
    _rotation: 0,

    /**
     * The x position of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#x
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    x: 0,

    /**
     * The y position of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#y
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    y: 0,

    /**
     * The z position of this Game Object.
     * Note: Do not use this value to set the z-index, instead see the `depth` property.
     *
     * @name Phaser.GameObjects.Components.Transform#z
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    z: 0,

    /**
     * The w position of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#w
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    w: 0,

    /**
     * The horizontal scale of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#scaleX
     * @type {number}
     * @default 1
     * @since 3.0.0
     */
    scaleX: {

        get: function ()
        {
            return this._scaleX;
        },

        set: function (value)
        {
            this._scaleX = value;

            if (this._scaleX === 0)
            {
                this.renderFlags &= ~_FLAG;
            }
            else
            {
                this.renderFlags |= _FLAG;
            }
        }

    },

    /**
     * The vertical scale of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#scaleY
     * @type {number}
     * @default 1
     * @since 3.0.0
     */
    scaleY: {

        get: function ()
        {
            return this._scaleY;
        },

        set: function (value)
        {
            this._scaleY = value;

            if (this._scaleY === 0)
            {
                this.renderFlags &= ~_FLAG;
            }
            else
            {
                this.renderFlags |= _FLAG;
            }
        }

    },

    /**
     * The angle of this Game Object as expressed in degrees.
     *
     * Where 0 is to the right, 90 is down, 180 is left.
     *
     * If you prefer to work in radians, see the `rotation` property instead.
     *
     * @name Phaser.GameObjects.Components.Transform#angle
     * @type {integer}
     * @default 0
     * @since 3.0.0
     */
    angle: {

        get: function ()
        {
            return WrapAngleDegrees(this._rotation * MATH_CONST.RAD_TO_DEG);
        },

        set: function (value)
        {
            //  value is in degrees
            this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD;
        }
    },

    /**
     * The angle of this Game Object in radians.
     *
     * If you prefer to work in degrees, see the `angle` property instead.
     *
     * @name Phaser.GameObjects.Components.Transform#rotation
     * @type {number}
     * @default 1
     * @since 3.0.0
     */
    rotation: {

        get: function ()
        {
            return this._rotation;
        },

        set: function (value)
        {
            //  value is in radians
            this._rotation = WrapAngle(value);
        }
    },

    /**
     * Sets the position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setPosition
     * @since 3.0.0
     *
     * @param {number} [x=0] - The x position of this Game Object.
     * @param {number} [y] - The y position of this Game Object. If not set it will use the `x` value.
     * @param {number} [z=0] - The z position of this Game Object.
     * @param {number} [w=0] - The w position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setPosition: function (x, y, z, w)
    {
        if (x === undefined) { x = 0; }
        if (y === undefined) { y = x; }
        if (z === undefined) { z = 0; }
        if (w === undefined) { w = 0; }

        this.x = x;
        this.y = y;
        this.z = z;
        this.w = w;

        return this;
    },

    /**
     * Sets the rotation of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setRotation
     * @since 3.0.0
     *
     * @param {number} [radians=0] - The rotation of this Game Object, in radians.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setRotation: function (radians)
    {
        if (radians === undefined) { radians = 0; }

        this.rotation = radians;

        return this;
    },

    /**
     * Sets the angle of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setAngle
     * @since 3.0.0
     *
     * @param {number} [degrees=0] - The rotation of this Game Object, in degrees.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setAngle: function (degrees)
    {
        if (degrees === undefined) { degrees = 0; }

        this.angle = degrees;

        return this;
    },

    /**
     * Sets the scale of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setScale
     * @since 3.0.0
     *
     * @param {number} x - The horizontal scale of this Game Object.
     * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the `x` value.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setScale: function (x, y)
    {
        if (x === undefined) { x = 1; }
        if (y === undefined) { y = x; }

        this.scaleX = x;
        this.scaleY = y;

        return this;
    },

    /**
     * Sets the x position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setX
     * @since 3.0.0
     *
     * @param {number} [value=0] - The x position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setX: function (value)
    {
        if (value === undefined) { value = 0; }

        this.x = value;

        return this;
    },

    /**
     * Sets the y position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setY
     * @since 3.0.0
     *
     * @param {number} [value=0] - The y position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setY: function (value)
    {
        if (value === undefined) { value = 0; }

        this.y = value;

        return this;
    },

    /**
     * Sets the z position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setZ
     * @since 3.0.0
     *
     * @param {number} [value=0] - The z position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setZ: function (value)
    {
        if (value === undefined) { value = 0; }

        this.z = value;

        return this;
    },

    /**
     * Sets the w position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setW
     * @since 3.0.0
     *
     * @param {number} [value=0] - The w position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setW: function (value)
    {
        if (value === undefined) { value = 0; }

        this.w = value;

        return this;
    }

};

module.exports = Transform;
<commit_msg>jsdoc fix<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var MATH_CONST = require('../../math/const');
var WrapAngle = require('../../math/angle/Wrap');
var WrapAngleDegrees = require('../../math/angle/WrapDegrees');

//  global bitmask flag for GameObject.renderMask (used by Scale)
var _FLAG = 4; // 0100

/**
 * Provides methods used for getting and setting the position, scale and rotation of a Game Object.
 *
 * @name Phaser.GameObjects.Components.Transform
 * @since 3.0.0
 */

var Transform = {

    /**
     * Private internal value. Holds the horizontal scale value.
     *
     * @name Phaser.GameObjects.Components.Transform#_scaleX
     * @type {float}
     * @private
     * @default 1
     * @since 3.0.0
     */
    _scaleX: 1,

    /**
     * Private internal value. Holds the vertical scale value.
     *
     * @name Phaser.GameObjects.Components.Transform#_scaleY
     * @type {float}
     * @private
     * @default 1
     * @since 3.0.0
     */
    _scaleY: 1,

    /**
     * Private internal value. Holds the rotation value in radians.
     *
     * @name Phaser.GameObjects.Components.Transform#_rotation
     * @type {float}
     * @private
     * @default 0
     * @since 3.0.0
     */
    _rotation: 0,

    /**
     * The x position of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#x
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    x: 0,

    /**
     * The y position of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#y
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    y: 0,

    /**
     * The z position of this Game Object.
     * Note: Do not use this value to set the z-index, instead see the `depth` property.
     *
     * @name Phaser.GameObjects.Components.Transform#z
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    z: 0,

    /**
     * The w position of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#w
     * @type {number}
     * @default 0
     * @since 3.0.0
     */
    w: 0,

    /**
     * The horizontal scale of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#scaleX
     * @type {number}
     * @default 1
     * @since 3.0.0
     */
    scaleX: {

        get: function ()
        {
            return this._scaleX;
        },

        set: function (value)
        {
            this._scaleX = value;

            if (this._scaleX === 0)
            {
                this.renderFlags &= ~_FLAG;
            }
            else
            {
                this.renderFlags |= _FLAG;
            }
        }

    },

    /**
     * The vertical scale of this Game Object.
     *
     * @name Phaser.GameObjects.Components.Transform#scaleY
     * @type {number}
     * @default 1
     * @since 3.0.0
     */
    scaleY: {

        get: function ()
        {
            return this._scaleY;
        },

        set: function (value)
        {
            this._scaleY = value;

            if (this._scaleY === 0)
            {
                this.renderFlags &= ~_FLAG;
            }
            else
            {
                this.renderFlags |= _FLAG;
            }
        }

    },

    /**
     * The angle of this Game Object as expressed in degrees.
     *
     * Where 0 is to the right, 90 is down, 180 is left.
     *
     * If you prefer to work in radians, see the `rotation` property instead.
     *
     * @name Phaser.GameObjects.Components.Transform#angle
     * @type {integer}
     * @default 0
     * @since 3.0.0
     */
    angle: {

        get: function ()
        {
            return WrapAngleDegrees(this._rotation * MATH_CONST.RAD_TO_DEG);
        },

        set: function (value)
        {
            //  value is in degrees
            this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD;
        }
    },

    /**
     * The angle of this Game Object in radians.
     *
     * If you prefer to work in degrees, see the `angle` property instead.
     *
     * @name Phaser.GameObjects.Components.Transform#rotation
     * @type {number}
     * @default 1
     * @since 3.0.0
     */
    rotation: {

        get: function ()
        {
            return this._rotation;
        },

        set: function (value)
        {
            //  value is in radians
            this._rotation = WrapAngle(value);
        }
    },

    /**
     * Sets the position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setPosition
     * @since 3.0.0
     *
     * @param {number} [x=0] - The x position of this Game Object.
     * @param {number} [y=x] - The y position of this Game Object. If not set it will use the `x` value.
     * @param {number} [z=0] - The z position of this Game Object.
     * @param {number} [w=0] - The w position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setPosition: function (x, y, z, w)
    {
        if (x === undefined) { x = 0; }
        if (y === undefined) { y = x; }
        if (z === undefined) { z = 0; }
        if (w === undefined) { w = 0; }

        this.x = x;
        this.y = y;
        this.z = z;
        this.w = w;

        return this;
    },

    /**
     * Sets the rotation of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setRotation
     * @since 3.0.0
     *
     * @param {number} [radians=0] - The rotation of this Game Object, in radians.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setRotation: function (radians)
    {
        if (radians === undefined) { radians = 0; }

        this.rotation = radians;

        return this;
    },

    /**
     * Sets the angle of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setAngle
     * @since 3.0.0
     *
     * @param {number} [degrees=0] - The rotation of this Game Object, in degrees.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setAngle: function (degrees)
    {
        if (degrees === undefined) { degrees = 0; }

        this.angle = degrees;

        return this;
    },

    /**
     * Sets the scale of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setScale
     * @since 3.0.0
     *
     * @param {number} x - The horizontal scale of this Game Object.
     * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the `x` value.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setScale: function (x, y)
    {
        if (x === undefined) { x = 1; }
        if (y === undefined) { y = x; }

        this.scaleX = x;
        this.scaleY = y;

        return this;
    },

    /**
     * Sets the x position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setX
     * @since 3.0.0
     *
     * @param {number} [value=0] - The x position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setX: function (value)
    {
        if (value === undefined) { value = 0; }

        this.x = value;

        return this;
    },

    /**
     * Sets the y position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setY
     * @since 3.0.0
     *
     * @param {number} [value=0] - The y position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setY: function (value)
    {
        if (value === undefined) { value = 0; }

        this.y = value;

        return this;
    },

    /**
     * Sets the z position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setZ
     * @since 3.0.0
     *
     * @param {number} [value=0] - The z position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setZ: function (value)
    {
        if (value === undefined) { value = 0; }

        this.z = value;

        return this;
    },

    /**
     * Sets the w position of this Game Object.
     *
     * @method Phaser.GameObjects.Components.Transform#setW
     * @since 3.0.0
     *
     * @param {number} [value=0] - The w position of this Game Object.
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object instance.
     */
    setW: function (value)
    {
        if (value === undefined) { value = 0; }

        this.w = value;

        return this;
    }

};

module.exports = Transform;
<|endoftext|>


<commit_before>/* global Node, ShadowRoot */

import { getEl } from './util.js';
import { doUnmount } from './unmount.js';

const hookNames = ['onmount', 'onremount', 'onunmount'];
const shadowRootAvailable = typeof window !== 'undefined' && 'ShadowRoot' in window;

export function mount (parent, child, before, replace) {
  const parentEl = getEl(parent);
  const childEl = getEl(child);

  if (child === childEl && childEl.__redom_view) {
    // try to look up the view if not provided
    child = childEl.__redom_view;
  }

  if (child !== childEl) {
    childEl.__redom_view = child;
  }

  const wasMounted = childEl.__redom_mounted;
  const oldParent = childEl.parentNode;

  if (wasMounted && (oldParent !== parentEl)) {
    doUnmount(child, childEl, oldParent);
  }

  if (before != null) {
    if (replace) {
      parentEl.replaceChild(childEl, getEl(before));
    } else {
      parentEl.insertBefore(childEl, getEl(before));
    }
  } else {
    parentEl.appendChild(childEl);
  }

  doMount(child, childEl, parentEl, oldParent);

  return child;
}

export function trigger (el, eventName) {
  if (eventName === 'onmount' || eventName === 'onremount') {
    el.__redom_mounted = true;
  } else if (eventName === 'onunmount') {
    el.__redom_mounted = false;
  }

  const hooks = el.__redom_lifecycle;

  if (!hooks) {
    return;
  }

  const view = el.__redom_view;
  let hookCount = 0;

  view && view[eventName] && view[eventName]();

  for (const hook in hooks) {
    if (hook) {
      hookCount++;
    }
  }

  if (hookCount) {
    let traverse = el.firstChild;

    while (traverse) {
      const next = traverse.nextSibling;

      trigger(traverse, eventName);

      traverse = next;
    }
  }
}

function doMount (child, childEl, parentEl, oldParent) {
  const hooks = childEl.__redom_lifecycle || (childEl.__redom_lifecycle = {});
  const remount = (parentEl === oldParent);
  let hooksFound = false;

  for (const hookName of hookNames) {
    if (!remount) { // if already mounted, skip this phase
      if (child !== childEl) { // only Views can have lifecycle events
        if (hookName in child) {
          hooks[hookName] = (hooks[hookName] || 0) + 1;
        }
      }
    }
    if (hooks[hookName]) {
      hooksFound = true;
    }
  }

  if (!hooksFound) {
    childEl.__redom_lifecycle = {};
    return;
  }

  let traverse = parentEl;
  let triggered = false;

  if (remount || (traverse && traverse.__redom_mounted)) {
    trigger(childEl, remount ? 'onremount' : 'onmount');
    triggered = true;
  }

  while (traverse) {
    const parent = traverse.parentNode;
    const parentHooks = traverse.__redom_lifecycle || (traverse.__redom_lifecycle = {});

    for (const hook in hooks) {
      parentHooks[hook] = (parentHooks[hook] || 0) + hooks[hook];
    }

    if (triggered) {
      break;
    } else {
      if (traverse.nodeType === Node.DOCUMENT_NODE ||
        (shadowRootAvailable && (traverse instanceof ShadowRoot)) ||
        (parent && parent.__redom_mounted)
      ) {
        trigger(traverse, remount ? 'onremount' : 'onmount');
        triggered = true;
      }
      traverse = parent;
    }
  }
}
<commit_msg>Fix #339<commit_after>/* global Node, ShadowRoot */

import { getEl } from './util.js';
import { doUnmount } from './unmount.js';

const hookNames = ['onmount', 'onremount', 'onunmount'];
const shadowRootAvailable = typeof window !== 'undefined' && 'ShadowRoot' in window;

export function mount (parent, child, before, replace) {
  const parentEl = getEl(parent);
  const childEl = getEl(child);

  if (child === childEl && childEl.__redom_view) {
    // try to look up the view if not provided
    child = childEl.__redom_view;
  }

  if (child !== childEl) {
    childEl.__redom_view = child;
  }

  const wasMounted = childEl.__redom_mounted;
  const oldParent = childEl.parentNode;

  if (wasMounted && (oldParent !== parentEl)) {
    doUnmount(child, childEl, oldParent);
  }

  if (before != null) {
    if (replace) {
      const beforeEl = getEl(before);

      if (beforeEl.__redom_mounted) {
        trigger(before.el, 'onunmount');
      }

      parentEl.replaceChild(childEl, beforeEl);
    } else {
      parentEl.insertBefore(childEl, getEl(before));
    }
  } else {
    parentEl.appendChild(childEl);
  }

  doMount(child, childEl, parentEl, oldParent);

  return child;
}

export function trigger (el, eventName) {
  if (eventName === 'onmount' || eventName === 'onremount') {
    el.__redom_mounted = true;
  } else if (eventName === 'onunmount') {
    el.__redom_mounted = false;
  }

  const hooks = el.__redom_lifecycle;

  if (!hooks) {
    return;
  }

  const view = el.__redom_view;
  let hookCount = 0;

  view && view[eventName] && view[eventName]();

  for (const hook in hooks) {
    if (hook) {
      hookCount++;
    }
  }

  if (hookCount) {
    let traverse = el.firstChild;

    while (traverse) {
      const next = traverse.nextSibling;

      trigger(traverse, eventName);

      traverse = next;
    }
  }
}

function doMount (child, childEl, parentEl, oldParent) {
  const hooks = childEl.__redom_lifecycle || (childEl.__redom_lifecycle = {});
  const remount = (parentEl === oldParent);
  let hooksFound = false;

  for (const hookName of hookNames) {
    if (!remount) { // if already mounted, skip this phase
      if (child !== childEl) { // only Views can have lifecycle events
        if (hookName in child) {
          hooks[hookName] = (hooks[hookName] || 0) + 1;
        }
      }
    }
    if (hooks[hookName]) {
      hooksFound = true;
    }
  }

  if (!hooksFound) {
    childEl.__redom_lifecycle = {};
    return;
  }

  let traverse = parentEl;
  let triggered = false;

  if (remount || (traverse && traverse.__redom_mounted)) {
    trigger(childEl, remount ? 'onremount' : 'onmount');
    triggered = true;
  }

  while (traverse) {
    const parent = traverse.parentNode;
    const parentHooks = traverse.__redom_lifecycle || (traverse.__redom_lifecycle = {});

    for (const hook in hooks) {
      parentHooks[hook] = (parentHooks[hook] || 0) + hooks[hook];
    }

    if (triggered) {
      break;
    } else {
      if (traverse.nodeType === Node.DOCUMENT_NODE ||
        (shadowRootAvailable && (traverse instanceof ShadowRoot)) ||
        (parent && parent.__redom_mounted)
      ) {
        trigger(traverse, remount ? 'onremount' : 'onmount');
        triggered = true;
      }
      traverse = parent;
    }
  }
}
<|endoftext|>