<commit_before>var videovr = {
  started: false,
  iconClicked: function() {
    if (this.started == false) {
      // start() has not yet run
      this.start();
    }
    else {
      // start() has already been run
      // Just try to fullscreen the canvas
      if (this.canvas !== undefined)
        this.canvas.webkitRequestFullscreen();
    }
  },
  start: function () {
    if (this.started == true)
      return;
    // Three.js setup
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    this.camera.position.z = 10;
    this.renderer = new THREE.WebGLRenderer();
    this.canvas = this.renderer.domElement;
    document.body.appendChild(this.canvas);
    this.canvas.style.position = "fixed";
    this.canvas.style.top = 0;
    this.canvas.style.left = 0;
    this.canvas.style.zIndex = 2999999999;
    this.canvas.style.outline = "none";
    this.canvas.tabIndex = 1000;
    this.canvas.webkitRequestFullscreen();

    // Add OculusRiftEffect
    this.effect = new THREE.OculusRiftEffect(this.renderer);
    this.effect.setSize( window.innerWidth, window.innerHeight );
    //effect.separation = 20;
    //effect.distortion = 0.1;
    //effect.fov = 110;

    document.addEventListener("webkitfullscreenchange", function () {
      console.log("fullscreenchange");
      console.log(videovr.canvas.height);
      if (videovr.effect !== undefined && videovr.canvas !== undefined)
        videovr.effect.setSize(window.innerWidth, window.innerHeight);
    }, false);

    // Grab the video element from the page
    var videos = document.getElementsByTagName('video');
    if (videos.length < 1) {
      alert("This only works on pages containing a video element.");
      return;
    }
    else if (videos.length > 1) {
      alert("This only works on pages containing only one video element.");
      return;
    }
    this.video = videos[0];

    // Set up a rectangular plane object
    var geometry = new THREE.PlaneGeometry(16, 9);
    this.texture = new THREE.Texture(this.video);
    var material = new THREE.MeshBasicMaterial( { map: this.texture, overdraw: true, side:THREE.DoubleSide } );
    //var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    var plane = new THREE.Mesh( geometry, material );
    this.scene.add( plane );

    // Set up skybox thing
    var cubegeometry = new THREE.CubeGeometry(50, 50, 50);
    var cubematerial = new THREE.MeshBasicMaterial( { color: 0x111111, side: THREE.BackSide } );
    var cube = new THREE.Mesh( cubegeometry, cubematerial );
    this.scene.add( cube );

    // Begin rendering to canvas
    (function animloop(){
      requestAnimationFrame(animloop);
      if( videovr.video.readyState === videovr.video.HAVE_ENOUGH_DATA ){
        videovr.texture.needsUpdate = true;
      }
      videovr.effect.render(videovr.scene, videovr.camera);
    })();

    // Set up keyboard capture
    this.canvas.onkeydown = function(e) {
      e = e || window.event;
      switch (e.keyCode) {
        case 38: // up arrow
          videovr.camera.position.z -= 1; // move in
          break;
        case 40: // down arrow
          videovr.camera.position.z += 1; // move out
          break;
        case 32: // spacebar
          // play/pause
          if (videovr.video.paused)
            videovr.video.play();
          else
            videovr.video.pause();
          break;
      }
    };
  }
};

// Listen for messages from the background page
// (It actually listens for messages from anyone in the context,
//  but the background page is the one that interrests us)
chrome.runtime.onMessage.addListener(function(msg, sender, response) {
  // If we've been asked to post grades...
  if (msg.action && (msg.action == "startVideoVRMode")) {
    // ...confirm we got the message and...
    response();
    // ...do what we do best: post grades !
    videovr.iconClicked();
  }
  else console.log(action);
});
<commit_msg>Bail and destroy viewer when an exception is caught<commit_after>var videovr = {
  started: false,
  iconClicked: function() {
    if (this.started == false) {
      // start() has not yet run
      this.start();
    }
    else {
      // start() has already been run
      // Just try to fullscreen the canvas
      if (this.canvas !== undefined)
        this.canvas.webkitRequestFullscreen();
    }
  },
  destroy: function() {
    this.canvas.parentNode.removeChild(this.canvas);
    this.started = false;
  },
  start: function () {
    if (this.started == true)
      return;
    // Three.js setup
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    this.renderer = new THREE.WebGLRenderer();
    this.canvas = this.renderer.domElement;
    document.body.appendChild(this.canvas);
    this.canvas.style.position = "fixed";
    this.canvas.style.top = 0;
    this.canvas.style.left = 0;
    this.canvas.style.zIndex = 2999999999;
    this.canvas.style.outline = "none";
    this.canvas.tabIndex = 1000;
    this.canvas.webkitRequestFullscreen();

    // Add OculusRiftEffect
    this.effect = new THREE.OculusRiftEffect(this.renderer);
    this.effect.setSize( window.innerWidth, window.innerHeight );
    //effect.separation = 20;
    //effect.distortion = 0.1;
    //effect.fov = 110;

    document.addEventListener("webkitfullscreenchange", function () {
      if (videovr.effect !== undefined && videovr.canvas !== undefined)
        videovr.effect.setSize(window.innerWidth, window.innerHeight);
    }, false);

    // Grab the video element from the page
    var videos = document.getElementsByTagName('video');
    if (videos.length < 1) {
      alert("This only works on pages containing a video element.");
      return;
    }
    else if (videos.length > 1) {
      alert("This only works on pages containing only one video element.");
      return;
    }
    this.video = videos[0];

    // Set up a rectangular plane object as a screen
    var geometry = new THREE.PlaneGeometry(15, 15*(this.video.videoHeight/this.video.videoWidth));
    this.texture = new THREE.Texture(this.video);
    var material = new THREE.MeshBasicMaterial( { map: this.texture, overdraw: true, side:THREE.DoubleSide } );
    this.sceen = new THREE.Mesh( geometry, material );
    this.sceen.position.z = -10;
    this.scene.add( this.sceen );

    // Set up skybox thing
    var cubegeometry = new THREE.CubeGeometry(100, 100, 200);
    var cubematerial = new THREE.MeshBasicMaterial( { color: 0x111111, side: THREE.BackSide } );
    var cube = new THREE.Mesh( cubegeometry, cubematerial );
    this.scene.add( cube );

    // Begin rendering to canvas
    (function animloop(){
      try {
        if( videovr.video.readyState === videovr.video.HAVE_ENOUGH_DATA ){
          videovr.texture.needsUpdate = true;
        }
        videovr.effect.render(videovr.scene, videovr.camera);
        requestAnimationFrame(animloop);
      } catch (e) {
        alert("Sorry, this video isn't supported.");
        videovr.destroy();
      }
    })();

    // Set up keyboard capture
    this.canvas.onkeydown = function(e) {
      e = e || window.event;
      switch (e.keyCode) {
        case 38: // up arrow
          videovr.sceen.position.z += 1; // move screen closer
          if (videovr.sceen.position.z > -1)
            videovr.sceen.position.z = -1; // limit closeness
          break;
        case 40: // down arrow
          videovr.sceen.position.z -= 1; // move screen farther
          if (videovr.sceen.position.z < -99)
            videovr.sceen.position.z = -99; // limit distance
          break;
        case 32: // spacebar
          // play/pause
          if (videovr.video.paused)
            videovr.video.play();
          else
            videovr.video.pause();
          break;
      }
    };
  }
};

// Listen for messages from the background page
// (It actually listens for messages from anyone in the context,
//  but the background page is the one that interrests us)
chrome.runtime.onMessage.addListener(function(msg, sender, response) {
  // If we've been asked to post grades...
  if (msg.action && (msg.action == "startVideoVRMode")) {
    // ...confirm we got the message and...
    response();
    // ...do what we do best: post grades !
    videovr.iconClicked();
  }
  else console.log(action);
});
<|endoftext|>


<commit_before><commit_msg>added notes for on focus specs<commit_after><|endoftext|>


<commit_before><commit_msg>Cleanup + using new logger where it's missing<commit_after><|endoftext|>


<commit_before><commit_msg>add proptypes for TextInput<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Owner: felix@famo.us
 * @license MPL 2.0
 * @copyright Famous Industries, Inc. 2014
 */

define(function(require, exports, module) {
    var OptionsManager = require('famous/core/OptionsManager');
    var Transform = require('famous/core/Transform');
    var ViewSequence = require('famous/core/ViewSequence');
    var Utility = require('famous/utilities/Utility');

    /**
     * SequentialLayout will lay out a collection of renderables sequentially in the specified direction.
     * @class SequentialLayout
     * @constructor
     * @param {Options} [options] An object of configurable options.
     * @param {Number} [options.direction=Utility.Direction.Y] Using the direction helper found in the famous Utility
     * module, this option will lay out the SequentialLayout instance's renderables either horizontally
     * (x) or vertically (y). Utility's direction is essentially either zero (X) or one (Y), so feel free
     * to just use integers as well.
     * @param {Array.Number} [options.defaultItemSize=[50, 50]] In the case where a renderable layed out
     * under SequentialLayout's control doesen't have a getSize method, SequentialLayout will assign it
     * this default size. (Commonly a case with Views).
     */
    function SequentialLayout(options) {
        this._items = null;
        this._size = null;
        this._outputFunction = SequentialLayout.DEFAULT_OUTPUT_FUNCTION;

        this.options = Object.create(this.constructor.DEFAULT_OPTIONS);
        this.optionsManager = new OptionsManager(this.options);

        this._itemsCache = [];
        this._outputCache = {
            size: null,
            target: this._itemsCache
        };

        if (options) this.setOptions(options);
    }

    SequentialLayout.DEFAULT_OPTIONS = {
        direction: Utility.Direction.Y,
        itemSpacing: 0,
        defaultItemSize: [50, 50]
    };

    SequentialLayout.DEFAULT_OUTPUT_FUNCTION = function DEFAULT_OUTPUT_FUNCTION(input, offset, index) {
        var transform = (this.options.direction === Utility.Direction.X) ? Transform.translate(offset, 0) : Transform.translate(0, offset);
        return {
            transform: transform,
            target: input.render()
        };
    };

    /**
     * Returns the width and the height of the SequentialLayout instance.
     *
     * @method getSize
     * @return {Array} A two value array of the SequentialLayout instance's current width and height (in that order).
     */
    SequentialLayout.prototype.getSize = function getSize() {
        if (!this._size) this.render(); // hack size in
        return this._size;
    };

    /**
     * Sets the collection of renderables under the SequentialLayout instance's control.
     *
     * @method sequenceFrom
     * @param {Array|ViewSequence} items Either an array of renderables or a Famous viewSequence.
     * @chainable
     */
    SequentialLayout.prototype.sequenceFrom = function sequenceFrom(items) {
        if (items instanceof Array) items = new ViewSequence(items);
        this._items = items;
        return this;
    };

    /**
     * Patches the SequentialLayout instance's options with the passed-in ones.
     *
     * @method setOptions
     * @param {Options} options An object of configurable options for the SequentialLayout instance.
     * @chainable
     */
    SequentialLayout.prototype.setOptions = function setOptions(options) {
        this.optionsManager.setOptions.apply(this.optionsManager, arguments);
        return this;
    };

    /**
     * setOutputFunction is used to apply a user-defined output transform on each processed renderable.
     *  For a good example, check out SequentialLayout's own DEFAULT_OUTPUT_FUNCTION in the code.
     *
     * @method setOutputFunction
     * @param {Function} outputFunction An output processer for each renderable in the SequentialLayout
     * instance.
     * @chainable
     */
    SequentialLayout.prototype.setOutputFunction = function setOutputFunction(outputFunction) {
        this._outputFunction = outputFunction;
        return this;
    };

    /**
     * Generate a render spec from the contents of this component.
     *
     * @private
     * @method render
     * @return {number} Render spec for this component
     */
    SequentialLayout.prototype.render = function render() {
        var length = 0;
        var girth = 0;

        var lengthDim = (this.options.direction === Utility.Direction.X) ? 0 : 1;
        var girthDim = (this.options.direction === Utility.Direction.X) ? 1 : 0;

        var currentNode = this._items;
        var result = this._itemsCache;
        var i = 0;
        while (currentNode) {
            var item = currentNode.get();
            if (!item) break;

            var itemSize;
            if (item && item.getSize) itemSize = item.getSize();
            if (!itemSize) itemSize = this.options.defaultItemSize;
            if (itemSize[girthDim] !== true) girth = Math.max(girth, itemSize[girthDim]);

            var output = this._outputFunction.call(this, item, length, i);
            result[i] = output;

            if (itemSize[lengthDim] && (itemSize[lengthDim] !== true)) length += itemSize[lengthDim] + this.options.itemSpacing;
            currentNode = currentNode.getNext();
            i++;
        }
        this._itemsCache.splice(i);

        if (!girth) girth = undefined;

        if (!this._size) this._size = [0, 0];
        this._size[lengthDim] = length - this.options.itemSpacing; // account for last itemSpacing
        this._size[girthDim] = girth;

        this._outputCache.size = this.getSize();
        return this._outputCache;
    };

    module.exports = SequentialLayout;
});
<commit_msg>Removed unneeded features of SequentialLayout<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Owner: felix@famo.us
 * @license MPL 2.0
 * @copyright Famous Industries, Inc. 2014
 */

define(function(require, exports, module) {
    var OptionsManager = require('famous/core/OptionsManager');
    var Transform = require('famous/core/Transform');
    var ViewSequence = require('famous/core/ViewSequence');
    var Utility = require('famous/utilities/Utility');

    /**
     * SequentialLayout will lay out a collection of renderables sequentially in the specified direction.
     * @class SequentialLayout
     * @constructor
     * @param {Options} [options] An object of configurable options.
     * @param {Number} [options.direction=Utility.Direction.Y] Using the direction helper found in the famous Utility
     * module, this option will lay out the SequentialLayout instance's renderables either horizontally
     * (x) or vertically (y). Utility's direction is essentially either zero (X) or one (Y), so feel free
     * to just use integers as well.
     */
    function SequentialLayout(options) {
        this._items = null;
        this._size = null;
        this._outputFunction = SequentialLayout.DEFAULT_OUTPUT_FUNCTION;

        this.options = Object.create(this.constructor.DEFAULT_OPTIONS);
        this.optionsManager = new OptionsManager(this.options);

        if (options) this.setOptions(options);
    }

    SequentialLayout.DEFAULT_OPTIONS = {
        direction: Utility.Direction.Y
    };

    SequentialLayout.DEFAULT_OUTPUT_FUNCTION = function DEFAULT_OUTPUT_FUNCTION(input, offset, index) {
        var transform = (this.options.direction === Utility.Direction.X) ? Transform.translate(offset, 0) : Transform.translate(0, offset);
        return {
            transform: transform,
            target: input.render()
        };
    };

    /**
     * Returns the width and the height of the SequentialLayout instance.
     *
     * @method getSize
     * @return {Array} A two value array of the SequentialLayout instance's current width and height (in that order).
     */
    SequentialLayout.prototype.getSize = function getSize() {
        if (!this._size) this.render(); // hack size in
        return this._size;
    };

    /**
     * Sets the collection of renderables under the SequentialLayout instance's control.
     *
     * @method sequenceFrom
     * @param {Array|ViewSequence} items Either an array of renderables or a Famous viewSequence.
     * @chainable
     */
    SequentialLayout.prototype.sequenceFrom = function sequenceFrom(items) {
        if (items instanceof Array) items = new ViewSequence(items);
        this._items = items;
        return this;
    };

    /**
     * Patches the SequentialLayout instance's options with the passed-in ones.
     *
     * @method setOptions
     * @param {Options} options An object of configurable options for the SequentialLayout instance.
     * @chainable
     */
    SequentialLayout.prototype.setOptions = function setOptions(options) {
        this.optionsManager.setOptions.apply(this.optionsManager, arguments);
        return this;
    };

    /**
     * setOutputFunction is used to apply a user-defined output transform on each processed renderable.
     *  For a good example, check out SequentialLayout's own DEFAULT_OUTPUT_FUNCTION in the code.
     *
     * @method setOutputFunction
     * @param {Function} outputFunction An output processer for each renderable in the SequentialLayout
     * instance.
     * @chainable
     */
    SequentialLayout.prototype.setOutputFunction = function setOutputFunction(outputFunction) {
        this._outputFunction = outputFunction;
        return this;
    };

    /**
     * Generate a render spec from the contents of this component.
     *
     * @private
     * @method render
     * @return {number} Render spec for this component
     */
    SequentialLayout.prototype.render = function render() {
        var length = 0,
            secondaryDirection = (this.options.direction + 1) % 2,
            currentNode = this._items,
            item,
            itemSize,
            output,
            result = [],
            i = 0;

        this._size = [0, 0];

        while(currentNode) {
            item = currentNode.get();
            if (!item) break;

            if (item.getSize) itemSize = item.getSize();
            if (!itemSize) itemSize = this.options.defaultItemSize;

            output = this._outputFunction.call(this, item, length, i++);
            result.push(output);

            if (itemSize[this.options.direction] && (itemSize[this.options.direction] !== true)) length += itemSize[this.options.direction] + this.options.itemSpacing;
            if (itemSize[secondaryDirection] > this._size[secondaryDirection]) this._size[secondaryDirection] = itemSize[secondaryDirection];

            currentNode = currentNode.getNext();
        }

        this._size[this.options.direction] = length;

        return result;
    };

    module.exports = SequentialLayout;
});
<|endoftext|>


<commit_before><commit_msg>Move to correct location<commit_after><|endoftext|>


<commit_before><commit_msg>#623 se-input changes event trigger issue fixed<commit_after><|endoftext|>


<commit_before>Package.describe({
  summary: "An XML builder for node.js similar to java-xmlbuilder.",
  version: '2.5.15'
});

Npm.depends({
  'xmlbuilder': '2.4.4'  // XXX next time we update this to X.Y.Z,
                         // make the version above be X.Y.Z_0 so we
                         // don't accidentally unsync version numbers
});

Package.onUse(function (api) {
  api.addFiles(['xmlbuilder.js'], 'server');

  api.export('XmlBuilder', 'server');
});
<commit_msg>update the xmlbuilder isopack's package.js file<commit_after>Package.describe({
  summary: "An XML builder for node.js similar to java-xmlbuilder.",
  version: '2.5.16'
});

Npm.depends({
  'xmlbuilder2': '1.3.0'
});

Package.onUse(function (api) {
  api.addFiles(['xmlbuilder.js'], 'server');

  api.export('XmlBuilder', 'server');
});

Package.onTest(function (api) {
  api.use(['tinytest', 'xmlbuilder', 'underscore']);

  api.addFiles('xmlbuilder_tests.js', 'server');
});<|endoftext|>


<commit_before>// @flow
import { join } from "path"
import fs from "fs-extra"
import colors from "chalk"

import log from "../_utils/log"

import webpack from "./webpack"
import sortAssets from "./webpack/sortAssets.js"
import devServer from "./server.js"
import postBuild from "./post-build.js"

import webpackConfigBrowser from "./webpack/config.browser.js"
import webpackConfigNode, { cacheDir } from "./webpack/config.node.js"
import dynamicRequire from "./dynamic-require.js"

import PhenomicLoaderWebpackPlugin from "../loader/plugin.js"

export default function(config: Object): void {
  // log(JSON.stringify(config, null, 2))

  const makeWebpackConfigModule = dynamicRequire(
    join(config.cwd, config["webpack-config"])
  )
  const makeWebpackConfig =
    typeof makeWebpackConfigModule.default === "function"
    ? makeWebpackConfigModule.default
    // : makeWebpackConfigModule
    // @todo remove block below and uncomment line above
    : typeof makeWebpackConfigModule === "function"
    ? makeWebpackConfigModule
    // deprecated
    : makeWebpackConfigModule.makeConfig

  if (typeof makeWebpackConfig !== "function") {
    throw new Error(
      "Your webpack config must export a function. " +
      "This function will be called with a single argument " +
      "(Phenomic configuration object) and must return a valid webpack config."
    )
  }

  config.webpackConfig = makeWebpackConfig(config)
  config.webpackConfigBrowser = webpackConfigBrowser(config)
  config.webpackConfigNode = webpackConfigNode(config)

  const destination = join(config.cwd, config.destination)
  fs.emptyDirSync(destination)

  const env = process.env.NODE_ENV || "development"
  process.env.BABEL_ENV = "webpack-" + env

  if (config.static) {
    // Copy static assets to build folder
    if (config.assets) {
      log("Copying assets", () => {
        const copyDest = join(destination, config.assets.route)
        fs.copySync(config.assets.path, copyDest)
      })
    }

    const webpackPromise = (webpackConfig): Promise<any> => (
      new Promise((resolve: Function, reject: Function) => {
        try {
          webpack(webpackConfig, log, resolve)
        }
        catch (e) {
          reject(e)
        }
      })
    )

    log("Building client files", webpackPromise(config.webpackConfigBrowser))
    .then((clientBundleStats) => (
      log("Preparing static build", webpackPromise(config.webpackConfigNode))
      .then(() => clientBundleStats)
    ))
    .then((clientBundleStats) => log("Building static files", () => (
      dynamicRequire(join(
        config.webpackConfigNode.output.path,
        config.webpackConfigNode.output.filename
      ))({
        ...config,
        collection: PhenomicLoaderWebpackPlugin.collection,
        assetsFiles: sortAssets(
          clientBundleStats.toJson().assetsByChunkName
        ),
      })
    )))
    .then((files) => postBuild(config, files))
    .then(() => config.server && devServer(config))
    .catch((err) => {
      log(colors.red("Build failed"), "error")
      setTimeout(() => {

        // improve Error
        const cleanPathRE = new RegExp(cacheDir + "\/(webpack:\/)?", "g")
        err.message = "\n\n" + colors.red(err.message) + "\n"
        err.stack = err.stack.replace(cleanPathRE, "")

        throw err
      }, 1)
    })
  }
  else if (config.server) {
    devServer(config)
  }
  else {
    console.error(colors.red(
      "phenomic: CLI needs --static or --server"
    ))
  }
}
<commit_msg>Add a warning for makeConfig being deprecated<commit_after>// @flow
import { join } from "path"
import fs from "fs-extra"
import colors from "chalk"

import log from "../_utils/log"

import webpack from "./webpack"
import sortAssets from "./webpack/sortAssets.js"
import devServer from "./server.js"
import postBuild from "./post-build.js"

import webpackConfigBrowser from "./webpack/config.browser.js"
import webpackConfigNode, { cacheDir } from "./webpack/config.node.js"
import dynamicRequire from "./dynamic-require.js"

import PhenomicLoaderWebpackPlugin from "../loader/plugin.js"

export default function(config: Object): void {
  // log(JSON.stringify(config, null, 2))

  const makeWebpackConfigModule = dynamicRequire(
    join(config.cwd, config["webpack-config"])
  )
  const makeWebpackConfig =
    typeof makeWebpackConfigModule.default === "function"
    ? makeWebpackConfigModule.default
    // : makeWebpackConfigModule
    // @todo remove block below and uncomment line above
    : typeof makeWebpackConfigModule === "function"
    ? makeWebpackConfigModule
    // deprecated
    : makeWebpackConfigModule.makeConfig

  if (makeWebpackConfigModule.makeConfig) {
    log(
      "Your webpack config should now directly export a function.\n" +
      "No need to export a makeConfig() function anymore as webpack@2 " +
      "natively support a function. " +
      "(makeConfig() is currently deprecated and support will be remove in a " +
      "futur release). ",
      "warning"
    )
  }

  if (typeof makeWebpackConfig !== "function") {
    throw new Error(
      "Your webpack config must export a function. " +
      "This function will be called with a single argument " +
      "(Phenomic configuration object) and must return a valid webpack config."
    )
  }

  config.webpackConfig = makeWebpackConfig(config)
  config.webpackConfigBrowser = webpackConfigBrowser(config)
  config.webpackConfigNode = webpackConfigNode(config)

  const destination = join(config.cwd, config.destination)
  fs.emptyDirSync(destination)

  const env = process.env.NODE_ENV || "development"
  process.env.BABEL_ENV = "webpack-" + env

  if (config.static) {
    // Copy static assets to build folder
    if (config.assets) {
      log("Copying assets", () => {
        const copyDest = join(destination, config.assets.route)
        fs.copySync(config.assets.path, copyDest)
      })
    }

    const webpackPromise = (webpackConfig): Promise<any> => (
      new Promise((resolve: Function, reject: Function) => {
        try {
          webpack(webpackConfig, log, resolve)
        }
        catch (e) {
          reject(e)
        }
      })
    )

    log("Building client files", webpackPromise(config.webpackConfigBrowser))
    .then((clientBundleStats) => (
      log("Preparing static build", webpackPromise(config.webpackConfigNode))
      .then(() => clientBundleStats)
    ))
    .then((clientBundleStats) => log("Building static files", () => (
      dynamicRequire(join(
        config.webpackConfigNode.output.path,
        config.webpackConfigNode.output.filename
      ))({
        ...config,
        collection: PhenomicLoaderWebpackPlugin.collection,
        assetsFiles: sortAssets(
          clientBundleStats.toJson().assetsByChunkName
        ),
      })
    )))
    .then((files) => postBuild(config, files))
    .then(() => config.server && devServer(config))
    .catch((err) => {
      log(colors.red("Build failed"), "error")
      setTimeout(() => {

        // improve Error
        const cleanPathRE = new RegExp(cacheDir + "\/(webpack:\/)?", "g")
        err.message = "\n\n" + colors.red(err.message) + "\n"
        err.stack = err.stack.replace(cleanPathRE, "")

        throw err
      }, 1)
    })
  }
  else if (config.server) {
    devServer(config)
  }
  else {
    console.error(colors.red(
      "phenomic: CLI needs --static or --server"
    ))
  }
}
<|endoftext|>


<commit_before><commit_msg>removed debug output undo/redo for element titles<commit_after><|endoftext|>


<commit_before>var Container = require('../display/Container'),
    Sprite = require('../display/Sprite'),
    Rectangle = require('../geom/Rectangle'),
    Vector = require('../math/Vector'),
    ObjectPool = require('../utils/ObjectPool'),
    ObjectFactory = require('../utils/ObjectFactory'),
    inherit = require('../utils/inherit'),
    math = require('../math/math'),
    C = require('../constants');

/**
 * A basic Camera object that provides some effects. It also will contain the HUD and GUI
 * to ensure they are using "screen-coords".
 *
 * @class Camera
 * @extends Container
 * @constructor
 */
var Camera = function(state) {
    /**
     * The world instance this camera is tied to
     *
     * @property world
     * @type World
     */
    this.world = state.world;

    /**
     * The game instance this camera belongs to
     *
     * @property game
     * @type Game
     */
    this.game = state.game;

    /**
     * The game state this camera belongs to
     *
     * @property state
     * @type State
     */
    this.state = state;

    /**
     * The bounds of that the camera can move to
     *
     * @property bounds
     * @type Rectangle
     * @readOnly
     * @private
     */
    this.bounds = state.world.bounds.clone();

    /**
     * When following a sprite this is the space within the camera that it can move around
     * before the camera moves to track it.
     *
     * @property _deadzone
     * @type Rectangle
     * @readOnly
     * @private
     */
    this._deadzone = null;

    /**
     * The target that the camera will follow
     *
     * @property _target
     * @type Sprite
     * @readOnly
     * @private
     */
    this._target = null;

    /**
     * The size of the camera
     *
     * @property size
     * @type Vector
     * @readOnly
     */
    this.size = new Vector(0, 0);

    /**
     * Half of the size of the camera
     *
     * @property hSize
     * @type Vector
     * @readOnly
     */
    this.hSize = new Vector(0, 0);

    /**
     * The container that holds all the GUI items, direct children of Camera are effects
     *
     * @property gui
     * @type Container
     * @readOnly
     */
    this.gui = new Container();

    /**
     * An object factory for creating game objects
     *
     * @property add
     * @type ObjectFactory
     */
    this.add = new ObjectFactory(state, this.gui);

    /**
     * The fxpools for doing camera effects
     *
     * @property fxpools
     * @type Object
     * @private
     * @readOnly
     */
    this.fxpools = {
        flash: new ObjectPool(gf.fx.camera.Flash, this),
        fade: new ObjectPool(gf.fx.camera.Fade, this),
        shake: new ObjectPool(gf.fx.camera.Shake, this),
        scanlines: new ObjectPool(gf.fx.camera.Scanlines, this),
        close: new ObjectPool(gf.fx.camera.Close, this)
    };

    //Dynamic addition of fx shortcuts
    var self = this;
    Object.keys(this.fxpools).forEach(function(key) {
        self[key] = function() {
            var e = self.fxpools[key].create(),
                args = Array.prototype.slice.call(arguments),
                cb = args.pop();

            if(typeof cb !== 'function')
                args.push(cb);

            args.push(this._fxCallback.bind(this, e, key, cb));

            return e.start.apply(e, args);
        };
    });

    Container.call(this);

    //add the gui child
    this.addChild(this.gui);
};

inherit(Camera, Container, {
    _fxCallback: function(fx, type, cb) {
        var ret;

        if(typeof cb === 'function')
            ret = cb();

        this.fxpools[type].free(fx);

        return ret;
    },
    /**
     * Follows an sprite with the camera, ensuring they are always center view. You can
     * pass a follow style to change the area an sprite can move around in before we start
     * to move with them.
     *
     * @method follow
     * @param sprite {Sprite} The sprite to follow
     * @param [style=CAMERA_FOLLOW.LOCKON] {CAMERA_FOLLOW} The style of following
     * @return {Camera} Returns iteself for chainability
     */
    follow: function(spr, style) {
        if(!(spr instanceof Sprite))
            return this;

        this._target = spr;

        switch(style) {
            case C.CAMERA_FOLLOW.PLATFORMER:
                var w = this.size.x / 8;
                var h = this.size.y / 3;
                this._deadzone = new Rectangle(
                    (this.size.x - w) / 2,
                    (this.size.y - h) / 2 - (h / 4),
                    w,
                    h
                );
                break;
            case C.CAMERA_FOLLOW.TOPDOWN:
                var sq4 = Math.max(this.size.x, this.size.y) / 4;
                this._deadzone = new Rectangle(
                    (this.size.x - sq4) / 2,
                    (this.size.y - sq4) / 2,
                    sq4,
                    sq4
                );
                break;
            case C.CAMERA_FOLLOW.TOPDOWN_TIGHT:
                var sq8 = Math.max(this.size.x, this.size.y) / 8;
                this._deadzone = new Rectangle(
                    (this.size.x - sq8) / 2,
                    (this.size.y - sq8) / 2,
                    sq8,
                    sq8
                );
                break;
            case C.CAMERA_FOLLOW.LOCKON:
                /* falls through */
            default:
                this._deadzone = null;
                break;
        }

        this.focusSprite(this._target);

        return this;
    },
    /**
     * Stops following any sprites
     *
     * @method unfollow
     * @return {Camera} Returns iteself for chainability
     */
    unfollow: function() {
        this._target = null;
        return this;
    },
    /**
     * Focuses the camera on a sprite.
     *
     * @method focusSprite
     * @param sprite {Sprite} The sprite to focus on
     * @return {Camera} Returns iteself for chainability
     */
    focusSprite: function(spr) {
        return this.focus(
            math.round(spr.position.x),
            math.round(spr.position.y)
        );
    },
    /**
     * Focuses the camera on an x,y position. Ensures that the camera does
     * not go outside the bounds set with setBounds()
     *
     * @method focus
     * @param x {Number|Vector} The x coord to focus on, if a Vector is passed the y param is ignored
     * @param y {Number} The y coord to focus on
     * @return {Camera} Returns iteself for chainability
     */
    focus: function(x, y) {
        y = x.y !== undefined ? x.y : (y || 0);
        x = x.x !== undefined ? x.x : (x || 0);

        //calculate how much we need to pan
        var goToX = x - this.hSize.x,
            goToY = y - this.hSize.y,
            dx = goToX + this.world.position.x, //world pos is negative
            dy = goToY + this.world.position.y;

        return this.pan(dx, dy);
    },
    /**
     * Pans the camera around by the x,y amount. Ensures that the camera does
     * not go outside the bounds set with setBounds()
     *
     * @method pan
     * @param x {Number|Vector} The x amount to pan, if a Point is passed the y param is ignored
     * @param y {Number} The y ammount to pan
     * @return {Camera} Returns iteself for chainability
     */
    pan: function(dx, dy) {
        dy = dx.y !== undefined ? dx.y : (dy || 0);
        dx = dx.x !== undefined ? dx.x : (dx || 0);

        if(!dx && !dy) return;

            //world position
        var pos = this.world.position,
            //new world position
            newX = pos.x - dx,
            newY = pos.y - dy,
            b = this.bounds;

        if(b) {
            //check if X movement is illegal
            if(this._outsideBounds(-newX, -pos.y)) {
                dx = (dx < 0 ? b.x : b.right - this.size.x) + pos.x; //how far can we move since dx is too much
            }
            //check if Y movement is illegal
            if(this._outsideBounds(-pos.x, -newY)) {
                dy = (dy < 0 ? b.y : b.bottom - this.size.y) + pos.y;
            }
        }

        //prevent NaN
        if(!dx) dx = 0;
        if(!dy) dy = 0;

        this.world.pan(-dx, -dy);

        return this;
    },
    _outsideBounds: function(x, y) {
        //check if each corner of the camera is within the bounds
        return (
            !this.bounds.contains(x, y) || //top left
            !this.bounds.contains(x, y + this.size.y) || //bottom left
            !this.bounds.contains(x + this.size.x, y) || //top right
            !this.bounds.contains(x + this.size.x, y + this.size.y) //bottom right
        );
    },
    /**
     * Resizes the viewing area, this is called internally by your game instance
     * when you call mygame.resize(). DO NOT CALL THIS DIRECTLY
     *
     * @method resize
     * @private
     * @param w {Number} The new width
     * @param h {Number} The new height
     * @return {Camera} Returns iteself for chainability
     */
    resize: function(w, h) {
        this.size.set(w, h);
        this.hSize.set(
            math.round(this.size.x / 2),
            math.round(this.size.y / 2)
        );

        return this;
    },
    /**
     * Sets the bounds the camera is allowed to go. Usually this is the world's
     * size unless you set it manually.
     *
     * @method constrain
     * @param shape {Rectangle|Polygon|Circle|Ellipse} The shape to constrain the camera into
     * @return {Camera} Returns iteself for chainability
     */
    constrain: function(shape) {
        this.bounds = shape;

        return this;
    },
    /**
     * Removes the constraints of the camera, to allow free movement around the world
     *
     * @method unconstrain
     * @return {Camera} Returns iteself for chainability
     */
    unconstrain: function() {
        this.bounds = null;

        return this;
    },
    /**
     * Called internally every frame. Updates all effects and the follow
     *
     * @method update
     * @param dt {Number} The delta time (in seconds) since the last update
     * @return {Camera} Returns iteself for chainability
     * @private
     */
    update: function(dt) {
        //follow sprite
        if(this._target) {
            if(!this._deadzone) {
                this.focusSprite(this._target);
            } else {
                var moveX, moveY,
                    dx, dy,
                    //get the x,y of the sprite on the screen
                    camX = this._target.position.x + this.world.position.x,
                    camY = this._target.position.y + this.world.position.y;

                moveX = moveY = dx = dy = 0;

                //check less than
                dx = camX - this._deadzone.x;
                dy = camY - this._deadzone.y;

                if(dx < 0)
                    moveX = dx;
                if(dy < 0)
                    moveY = dy;

                //check greater than
                dx = camX - (this._deadzone.x + this._deadzone.width);
                dy = camY - (this._deadzone.y + this._deadzone.height);

                if(dx > 0)
                    moveX = dx;
                if(dy > 0)
                    moveY = dy;

                this.pan(
                    math.round(moveX),
                    math.round(moveY)
                );
            }
        }

        //update effects
        for(var i = 0, il = this.children.length; i < il; ++i) {
            var c = this.children[i];
            if(c.update)
                c.update(dt);
        }

        return this;
    }
});

module.exports = Camera;
<commit_msg>import fx requires<commit_after>var Container = require('../display/Container'),
    Sprite = require('../display/Sprite'),
    Rectangle = require('../geom/Rectangle'),
    Vector = require('../math/Vector'),
    ObjectPool = require('../utils/ObjectPool'),
    ObjectFactory = require('../utils/ObjectFactory'),
    //camera fx
    Close = require('../fx/camera/Close'),
    Fade = require('../fx/camera/Fade'),
    Flash = require('../fx/camera/Flash'),
    Scanlines = require('../fx/camera/Scanlines'),
    Shake = require('../fx/camera/Shake'),

    inherit = require('../utils/inherit'),
    math = require('../math/math'),
    C = require('../constants');

/**
 * A basic Camera object that provides some effects. It also will contain the HUD and GUI
 * to ensure they are using "screen-coords".
 *
 * @class Camera
 * @extends Container
 * @constructor
 */
var Camera = function(state) {
    /**
     * The world instance this camera is tied to
     *
     * @property world
     * @type World
     */
    this.world = state.world;

    /**
     * The game instance this camera belongs to
     *
     * @property game
     * @type Game
     */
    this.game = state.game;

    /**
     * The game state this camera belongs to
     *
     * @property state
     * @type State
     */
    this.state = state;

    /**
     * The bounds of that the camera can move to
     *
     * @property bounds
     * @type Rectangle
     * @readOnly
     * @private
     */
    this.bounds = state.world.bounds.clone();

    /**
     * When following a sprite this is the space within the camera that it can move around
     * before the camera moves to track it.
     *
     * @property _deadzone
     * @type Rectangle
     * @readOnly
     * @private
     */
    this._deadzone = null;

    /**
     * The target that the camera will follow
     *
     * @property _target
     * @type Sprite
     * @readOnly
     * @private
     */
    this._target = null;

    /**
     * The size of the camera
     *
     * @property size
     * @type Vector
     * @readOnly
     */
    this.size = new Vector(0, 0);

    /**
     * Half of the size of the camera
     *
     * @property hSize
     * @type Vector
     * @readOnly
     */
    this.hSize = new Vector(0, 0);

    /**
     * The container that holds all the GUI items, direct children of Camera are effects
     *
     * @property gui
     * @type Container
     * @readOnly
     */
    this.gui = new Container();

    /**
     * An object factory for creating game objects
     *
     * @property add
     * @type ObjectFactory
     */
    this.add = new ObjectFactory(state, this.gui);

    /**
     * The fxpools for doing camera effects
     *
     * @property fxpools
     * @type Object
     * @private
     * @readOnly
     */
    this.fxpools = {
        flash: new ObjectPool(Flash, this),
        fade: new ObjectPool(Fade, this),
        shake: new ObjectPool(Shake, this),
        scanlines: new ObjectPool(Scanlines, this),
        close: new ObjectPool(Close, this)
    };

    //Dynamic addition of fx shortcuts
    var self = this;
    Object.keys(this.fxpools).forEach(function(key) {
        self[key] = function() {
            var e = self.fxpools[key].create(),
                args = Array.prototype.slice.call(arguments),
                cb = args.pop();

            if(typeof cb !== 'function')
                args.push(cb);

            args.push(this._fxCallback.bind(this, e, key, cb));

            return e.start.apply(e, args);
        };
    });

    Container.call(this);

    //add the gui child
    this.addChild(this.gui);
};

inherit(Camera, Container, {
    _fxCallback: function(fx, type, cb) {
        var ret;

        if(typeof cb === 'function')
            ret = cb();

        this.fxpools[type].free(fx);

        return ret;
    },
    /**
     * Follows an sprite with the camera, ensuring they are always center view. You can
     * pass a follow style to change the area an sprite can move around in before we start
     * to move with them.
     *
     * @method follow
     * @param sprite {Sprite} The sprite to follow
     * @param [style=CAMERA_FOLLOW.LOCKON] {CAMERA_FOLLOW} The style of following
     * @return {Camera} Returns iteself for chainability
     */
    follow: function(spr, style) {
        if(!(spr instanceof Sprite))
            return this;

        this._target = spr;

        switch(style) {
            case C.CAMERA_FOLLOW.PLATFORMER:
                var w = this.size.x / 8;
                var h = this.size.y / 3;
                this._deadzone = new Rectangle(
                    (this.size.x - w) / 2,
                    (this.size.y - h) / 2 - (h / 4),
                    w,
                    h
                );
                break;
            case C.CAMERA_FOLLOW.TOPDOWN:
                var sq4 = Math.max(this.size.x, this.size.y) / 4;
                this._deadzone = new Rectangle(
                    (this.size.x - sq4) / 2,
                    (this.size.y - sq4) / 2,
                    sq4,
                    sq4
                );
                break;
            case C.CAMERA_FOLLOW.TOPDOWN_TIGHT:
                var sq8 = Math.max(this.size.x, this.size.y) / 8;
                this._deadzone = new Rectangle(
                    (this.size.x - sq8) / 2,
                    (this.size.y - sq8) / 2,
                    sq8,
                    sq8
                );
                break;
            case C.CAMERA_FOLLOW.LOCKON:
                /* falls through */
            default:
                this._deadzone = null;
                break;
        }

        this.focusSprite(this._target);

        return this;
    },
    /**
     * Stops following any sprites
     *
     * @method unfollow
     * @return {Camera} Returns iteself for chainability
     */
    unfollow: function() {
        this._target = null;
        return this;
    },
    /**
     * Focuses the camera on a sprite.
     *
     * @method focusSprite
     * @param sprite {Sprite} The sprite to focus on
     * @return {Camera} Returns iteself for chainability
     */
    focusSprite: function(spr) {
        return this.focus(
            math.round(spr.position.x),
            math.round(spr.position.y)
        );
    },
    /**
     * Focuses the camera on an x,y position. Ensures that the camera does
     * not go outside the bounds set with setBounds()
     *
     * @method focus
     * @param x {Number|Vector} The x coord to focus on, if a Vector is passed the y param is ignored
     * @param y {Number} The y coord to focus on
     * @return {Camera} Returns iteself for chainability
     */
    focus: function(x, y) {
        y = x.y !== undefined ? x.y : (y || 0);
        x = x.x !== undefined ? x.x : (x || 0);

        //calculate how much we need to pan
        var goToX = x - this.hSize.x,
            goToY = y - this.hSize.y,
            dx = goToX + this.world.position.x, //world pos is negative
            dy = goToY + this.world.position.y;

        return this.pan(dx, dy);
    },
    /**
     * Pans the camera around by the x,y amount. Ensures that the camera does
     * not go outside the bounds set with setBounds()
     *
     * @method pan
     * @param x {Number|Vector} The x amount to pan, if a Point is passed the y param is ignored
     * @param y {Number} The y ammount to pan
     * @return {Camera} Returns iteself for chainability
     */
    pan: function(dx, dy) {
        dy = dx.y !== undefined ? dx.y : (dy || 0);
        dx = dx.x !== undefined ? dx.x : (dx || 0);

        if(!dx && !dy) return;

            //world position
        var pos = this.world.position,
            //new world position
            newX = pos.x - dx,
            newY = pos.y - dy,
            b = this.bounds;

        if(b) {
            //check if X movement is illegal
            if(this._outsideBounds(-newX, -pos.y)) {
                dx = (dx < 0 ? b.x : b.right - this.size.x) + pos.x; //how far can we move since dx is too much
            }
            //check if Y movement is illegal
            if(this._outsideBounds(-pos.x, -newY)) {
                dy = (dy < 0 ? b.y : b.bottom - this.size.y) + pos.y;
            }
        }

        //prevent NaN
        if(!dx) dx = 0;
        if(!dy) dy = 0;

        this.world.pan(-dx, -dy);

        return this;
    },
    _outsideBounds: function(x, y) {
        //check if each corner of the camera is within the bounds
        return (
            !this.bounds.contains(x, y) || //top left
            !this.bounds.contains(x, y + this.size.y) || //bottom left
            !this.bounds.contains(x + this.size.x, y) || //top right
            !this.bounds.contains(x + this.size.x, y + this.size.y) //bottom right
        );
    },
    /**
     * Resizes the viewing area, this is called internally by your game instance
     * when you call mygame.resize(). DO NOT CALL THIS DIRECTLY
     *
     * @method resize
     * @private
     * @param w {Number} The new width
     * @param h {Number} The new height
     * @return {Camera} Returns iteself for chainability
     */
    resize: function(w, h) {
        this.size.set(w, h);
        this.hSize.set(
            math.round(this.size.x / 2),
            math.round(this.size.y / 2)
        );

        return this;
    },
    /**
     * Sets the bounds the camera is allowed to go. Usually this is the world's
     * size unless you set it manually.
     *
     * @method constrain
     * @param shape {Rectangle|Polygon|Circle|Ellipse} The shape to constrain the camera into
     * @return {Camera} Returns iteself for chainability
     */
    constrain: function(shape) {
        this.bounds = shape;

        return this;
    },
    /**
     * Removes the constraints of the camera, to allow free movement around the world
     *
     * @method unconstrain
     * @return {Camera} Returns iteself for chainability
     */
    unconstrain: function() {
        this.bounds = null;

        return this;
    },
    /**
     * Called internally every frame. Updates all effects and the follow
     *
     * @method update
     * @param dt {Number} The delta time (in seconds) since the last update
     * @return {Camera} Returns iteself for chainability
     * @private
     */
    update: function(dt) {
        //follow sprite
        if(this._target) {
            if(!this._deadzone) {
                this.focusSprite(this._target);
            } else {
                var moveX, moveY,
                    dx, dy,
                    //get the x,y of the sprite on the screen
                    camX = this._target.position.x + this.world.position.x,
                    camY = this._target.position.y + this.world.position.y;

                moveX = moveY = dx = dy = 0;

                //check less than
                dx = camX - this._deadzone.x;
                dy = camY - this._deadzone.y;

                if(dx < 0)
                    moveX = dx;
                if(dy < 0)
                    moveY = dy;

                //check greater than
                dx = camX - (this._deadzone.x + this._deadzone.width);
                dy = camY - (this._deadzone.y + this._deadzone.height);

                if(dx > 0)
                    moveX = dx;
                if(dy > 0)
                    moveY = dy;

                this.pan(
                    math.round(moveX),
                    math.round(moveY)
                );
            }
        }

        //update effects
        for(var i = 0, il = this.children.length; i < il; ++i) {
            var c = this.children[i];
            if(c.update)
                c.update(dt);
        }

        return this;
    }
});

module.exports = Camera;
<|endoftext|>


<commit_before>import {adapt} from '@cycle/run/lib/adapt';
import xs from 'xstream';

function flatten (array) {
  if (typeof array.reduce !== 'function') {
    return array;
  }

  return array.reduce((flatArray, arrayElement) => flatArray.concat(flatten(arrayElement)), []);
}

function compact (array) {
  return array.filter(element => element !== undefined && element !== null);
}

function translateRect (element, origin) {
  return element.draw.map(operation => {
    const operations = [
      {set: 'lineWidth', value: operation.lineWidth || 1}
    ];

    if (operation.clear) {
      operations.push({
        call: 'clearRect',
        args: [
          origin.x,
          origin.y,
          element.width,
          element.height
        ]
      });
    }

    if (operation.fill) {
      operations.push({
        set: 'fillStyle',
        value: operation.fill || 'black'
      });

      operations.push({
        call: 'fillRect',
        args: [
          origin.x,
          origin.y,
          element.width,
          element.height
        ]
      });
    }

    if (operation.stroke) {
      operations.push({
        set: 'strokeStyle',
        value: operation.stroke || 'black'
      });

      operations.push({
        call: 'strokeRect',
        args: [
          origin.x,
          origin.y,
          element.width,
          element.height
        ]
      });
    }

    return operations;
  });
}

function translateLine (element, origin) {
  const operations = [
    {set: 'lineWidth', value: element.style.lineWidth || 1},
    {set: 'lineCap', value: element.style.lineCap || 'butt'},
    {set: 'lineJoin', value: element.style.lineJoin || 'mitter'},
    {set: 'strokeStyle', value: element.style.strokeStyle || 'black'}
  ];

  if (element.style.lineDash && element.style.lineDash.constructor === Array) {
    operations.push({
      call: 'setLineDash',
      args: element.style.lineDash
    });
  }

  operations.push({
    call: 'moveTo',
    args: [
      origin.x,
      origin.y
    ]
  });

  operations.push({
    call: 'beginPath',
    args: []
  });

  element.points.forEach(point => {
    operations.push({
      call: 'lineTo',
      args: [
        origin.x + point.x,
        origin.y + point.y
      ]
    });
  });

  operations.push({
    call: 'stroke',
    args: []
  });

  operations.push({
    call: 'setLineDash',
    args: []
  });

  return operations;
}

function translatePolygon (element, origin) {
  const [first, ...rest] = element.points;

  return [].concat(
    [{call: 'beginPath', args: []}],
    [{call: 'moveTo', args: [origin.x + first.x, origin.y + first. y]}],
    rest.map(point => {
      return {call: 'lineTo', args: [origin.x + point.x, origin.y + point.y]};
    }),
    [{call: 'closePath', args: []}],
    element.draw.map(operation => {
      const fillInstructions = [
        {set: 'fillStyle', value: operation.fill},
        {call: 'fill', args: []}
      ]
      const strokeInstructions = [
        {set: 'strokeStyle', value: operation.stroke},
        {call: 'stroke', args: []}
      ]
      return operation.fill
        ? fillInstructions
        : operation.stroke
          ? strokeInstructions
          : [];
    })
  );
}

function translateText (element, origin) {
  return element.draw.map(operation => {
    const operations = [
      {set: 'textAlign', value: element.textAlign || 'left'},
      {set: 'font', value: element.font}
    ];

    const args = [
      element.value,
      origin.x,
      origin.y
    ];

    if (element.width) {
      args.push(element.width);
    }

    if (operation.fill) {
      operations.push({
        set: 'fillStyle',
        value: operation.fill || 'black'
      });

      operations.push({
        call: 'fillText',
        args: args
      });
    }

    if (operation.stroke) {
      operations.push({
        set: 'strokeStyle',
        value: operation.stroke || 'black'
      });

      operations.push({
        call: 'strokeText',
        args: args
      });
    }

    return operations;
  });
}

export function translateVtreeToInstructions (element, parentEl) {
  if (!element) {
    return;
  }

  if (!parentEl) {
    parentEl = {x: 0, y: 0};
  }

  const origin = {
    x: element.x ? parentEl.x + element.x : parentEl.x,
    y: element.y ? parentEl.y + element.y : parentEl.y
  };

  const elementMapping = {
    rect: translateRect,
    line: translateLine,
    text: translateText,
    polygon: translatePolygon
  };

  const instructions = preDrawHooks(element);

  instructions.push(elementMapping[element.kind](element, origin));

  instructions.push(postDrawHooks());

  const flatInstructions = compact(flatten(instructions));

  if (element.children) {
    element.children.forEach((child) => {
      const childInstructions = translateVtreeToInstructions(child, element);

      if (childInstructions) {
        flatInstructions.push(...childInstructions);
      }
    });
  }

  return flatInstructions;
}

export function renderInstructionsToCanvas (instructions, context) {
  instructions.forEach(instruction => {
    if (instruction.set) {
      context[instruction.set] = instruction.value;
    } else if (instruction.call) {
      context[instruction.call](...instruction.args);
    }
  });
}

function preDrawHooks (element) {
  const operations = [
    {call: 'save', args: []}
  ];

  if (element.transformations) {
    element.transformations.forEach(transformation => {
      if (transformation.translate) {
        operations.push({
          call: 'translate',
          args: [transformation.translate.x, transformation.translate.y]
        });
      }

      if (transformation.rotate) {
        operations.push({
          call: 'rotate',
          args: [transformation.rotate]
        });
      }

      if (transformation.scale) {
        operations.push({
          call: 'scale',
          args: [transformation.scale.x, transformation.scale.y]
        });
      }
    });
  }

  return operations;
}

function postDrawHooks () {
  return [
    {call: 'restore', args: []}
  ];
}

export function c (kind, opts, children) {
  if (opts.children) {
    children = opts.children;
  }

  return Object.assign(
    {},
    opts,
    {kind, children}
  );
}

export function rect (opts, children) {
  return c('rect', opts, children);
}

export function text (opts, children) {
  const defaults = {
    draw: [
      {fill: 'black'}
    ]
  };

  return c('text', {...defaults, ...opts}, children);
}

export function line (opts, children) {
  const defaults = {
    style: {
      lineWidth: 1,
      lineCap: 'butt',
      lineJoin: 'miter',
      strokeStyle: 'black'
    }
  };
  return c('line', {...defaults, ...opts}, children);
}

export function polygon (opts, children) {
  return c('polygon', opts, children);
}

export function makeCanvasDriver (selector, canvasOptions = null) {
  let canvas = document.querySelector(selector);

  if (!canvas) {
    canvas = document.createElement('canvas');

    document.body.appendChild(canvas);
  }

  if (canvasOptions) {
    canvas.width = canvasOptions.width;
    canvas.height = canvasOptions.height;
  }

  const context = canvas.getContext('2d');

  let driver = function canvasDriver (sink$) {
    sink$.addListener({
      next: rootElement => {
        const defaults = {
          kind: 'rect',
          x: 0,
          y: 0,
          width: canvas.width,
          height: canvas.height,
          draw: [
          {clear: true}
          ]
        };

        const rootElementWithDefaults = Object.assign(
          {},
          defaults,
          rootElement
          );

        const instructions = translateVtreeToInstructions(rootElementWithDefaults);

        renderInstructionsToCanvas(instructions, context);
      },
      error: e => { throw e },
      complete: () => null
    });

    return adapt(xs.empty());
  }

  return driver;
}
<commit_msg>Rename second argument<commit_after>import {adapt} from '@cycle/run/lib/adapt';
import xs from 'xstream';

function flatten (array) {
  if (typeof array.reduce !== 'function') {
    return array;
  }

  return array.reduce((flatArray, arrayElement) => flatArray.concat(flatten(arrayElement)), []);
}

function compact (array) {
  return array.filter(element => element !== undefined && element !== null);
}

function translateRect (element, origin) {
  return element.draw.map(operation => {
    const operations = [
      {set: 'lineWidth', value: operation.lineWidth || 1}
    ];

    if (operation.clear) {
      operations.push({
        call: 'clearRect',
        args: [
          origin.x,
          origin.y,
          element.width,
          element.height
        ]
      });
    }

    if (operation.fill) {
      operations.push({
        set: 'fillStyle',
        value: operation.fill || 'black'
      });

      operations.push({
        call: 'fillRect',
        args: [
          origin.x,
          origin.y,
          element.width,
          element.height
        ]
      });
    }

    if (operation.stroke) {
      operations.push({
        set: 'strokeStyle',
        value: operation.stroke || 'black'
      });

      operations.push({
        call: 'strokeRect',
        args: [
          origin.x,
          origin.y,
          element.width,
          element.height
        ]
      });
    }

    return operations;
  });
}

function translateLine (element, origin) {
  const operations = [
    {set: 'lineWidth', value: element.style.lineWidth || 1},
    {set: 'lineCap', value: element.style.lineCap || 'butt'},
    {set: 'lineJoin', value: element.style.lineJoin || 'mitter'},
    {set: 'strokeStyle', value: element.style.strokeStyle || 'black'}
  ];

  if (element.style.lineDash && element.style.lineDash.constructor === Array) {
    operations.push({
      call: 'setLineDash',
      args: element.style.lineDash
    });
  }

  operations.push({
    call: 'moveTo',
    args: [
      origin.x,
      origin.y
    ]
  });

  operations.push({
    call: 'beginPath',
    args: []
  });

  element.points.forEach(point => {
    operations.push({
      call: 'lineTo',
      args: [
        origin.x + point.x,
        origin.y + point.y
      ]
    });
  });

  operations.push({
    call: 'stroke',
    args: []
  });

  operations.push({
    call: 'setLineDash',
    args: []
  });

  return operations;
}

function translatePolygon (element, origin) {
  const [first, ...rest] = element.points;

  return [].concat(
    [{call: 'beginPath', args: []}],
    [{call: 'moveTo', args: [origin.x + first.x, origin.y + first. y]}],
    rest.map(point => {
      return {call: 'lineTo', args: [origin.x + point.x, origin.y + point.y]};
    }),
    [{call: 'closePath', args: []}],
    element.draw.map(operation => {
      const fillInstructions = [
        {set: 'fillStyle', value: operation.fill},
        {call: 'fill', args: []}
      ]
      const strokeInstructions = [
        {set: 'strokeStyle', value: operation.stroke},
        {call: 'stroke', args: []}
      ]
      return operation.fill
        ? fillInstructions
        : operation.stroke
          ? strokeInstructions
          : [];
    })
  );
}

function translateText (element, origin) {
  return element.draw.map(operation => {
    const operations = [
      {set: 'textAlign', value: element.textAlign || 'left'},
      {set: 'font', value: element.font}
    ];

    const args = [
      element.value,
      origin.x,
      origin.y
    ];

    if (element.width) {
      args.push(element.width);
    }

    if (operation.fill) {
      operations.push({
        set: 'fillStyle',
        value: operation.fill || 'black'
      });

      operations.push({
        call: 'fillText',
        args: args
      });
    }

    if (operation.stroke) {
      operations.push({
        set: 'strokeStyle',
        value: operation.stroke || 'black'
      });

      operations.push({
        call: 'strokeText',
        args: args
      });
    }

    return operations;
  });
}

export function translateVtreeToInstructions (element, parentEl) {
  if (!element) {
    return;
  }

  if (!parentEl) {
    parentEl = {x: 0, y: 0};
  }

  const origin = {
    x: element.x ? parentEl.x + element.x : parentEl.x,
    y: element.y ? parentEl.y + element.y : parentEl.y
  };

  const elementMapping = {
    rect: translateRect,
    line: translateLine,
    text: translateText,
    polygon: translatePolygon
  };

  const instructions = preDrawHooks(element);

  instructions.push(elementMapping[element.kind](element, origin));

  instructions.push(postDrawHooks());

  const flatInstructions = compact(flatten(instructions));

  if (element.children) {
    element.children.forEach((child) => {
      const childInstructions = translateVtreeToInstructions(child, element);

      if (childInstructions) {
        flatInstructions.push(...childInstructions);
      }
    });
  }

  return flatInstructions;
}

export function renderInstructionsToCanvas (instructions, context) {
  instructions.forEach(instruction => {
    if (instruction.set) {
      context[instruction.set] = instruction.value;
    } else if (instruction.call) {
      context[instruction.call](...instruction.args);
    }
  });
}

function preDrawHooks (element) {
  const operations = [
    {call: 'save', args: []}
  ];

  if (element.transformations) {
    element.transformations.forEach(transformation => {
      if (transformation.translate) {
        operations.push({
          call: 'translate',
          args: [transformation.translate.x, transformation.translate.y]
        });
      }

      if (transformation.rotate) {
        operations.push({
          call: 'rotate',
          args: [transformation.rotate]
        });
      }

      if (transformation.scale) {
        operations.push({
          call: 'scale',
          args: [transformation.scale.x, transformation.scale.y]
        });
      }
    });
  }

  return operations;
}

function postDrawHooks () {
  return [
    {call: 'restore', args: []}
  ];
}

export function c (kind, opts, children) {
  if (opts.children) {
    children = opts.children;
  }

  return Object.assign(
    {},
    opts,
    {kind, children}
  );
}

export function rect (opts, children) {
  return c('rect', opts, children);
}

export function text (opts, children) {
  const defaults = {
    draw: [
      {fill: 'black'}
    ]
  };

  return c('text', {...defaults, ...opts}, children);
}

export function line (opts, children) {
  const defaults = {
    style: {
      lineWidth: 1,
      lineCap: 'butt',
      lineJoin: 'miter',
      strokeStyle: 'black'
    }
  };
  return c('line', {...defaults, ...opts}, children);
}

export function polygon (opts, children) {
  return c('polygon', opts, children);
}

export function makeCanvasDriver (selector, canvasSize = null) {
  let canvas = document.querySelector(selector);

  if (!canvas) {
    canvas = document.createElement('canvas');

    document.body.appendChild(canvas);
  }

  if (canvasSize) {
    canvas.width = canvasSize.width;
    canvas.height = canvasSize.height;
  }

  const context = canvas.getContext('2d');

  let driver = function canvasDriver (sink$) {
    sink$.addListener({
      next: rootElement => {
        const defaults = {
          kind: 'rect',
          x: 0,
          y: 0,
          width: canvas.width,
          height: canvas.height,
          draw: [
          {clear: true}
          ]
        };

        const rootElementWithDefaults = Object.assign(
          {},
          defaults,
          rootElement
          );

        const instructions = translateVtreeToInstructions(rootElementWithDefaults);

        renderInstructionsToCanvas(instructions, context);
      },
      error: e => { throw e },
      complete: () => null
    });

    return adapt(xs.empty());
  }

  return driver;
}
<|endoftext|>


<commit_before>/**
 * birds - a project to visualize bird migration flow for Belgium & Netherlands.
 *
 * Copyright (c) 2014 LifeWatch - INBO
 * The MIT License - http://opensource.org/licenses/MIT
 *
 * https://github.com/enram/bird-migration-flow-visualization
 *
 */

function fetchRadarData(url) {
	var result = jQuery.get(url, function(data) {
 		jQuery('.result').html(data);
 	});
 	return result;
 }

/*
 * Retrieve data from our radars with altitude and start time as parameter
 * @param altitude a number to define which altitude band you need.  Currently 1 == low and 2 == high
 */
function retrieveRadarDataByAltitudeAndTime(altitude, time) {
	var time_frame = "20 "; /* Time frames of 20 minutes */
 	var sql = vsprintf("WITH aggregated_data AS ( SELECT b.radar_id, ST_X(r.the_geom) AS longitude, ST_Y(r.the_geom) AS latitude, date_trunc('hour', b.start_time) + date_part('minute', b.start_time)::int / %s * interval '%s min' AS interval_start_time, CASE WHEN b.altitude >= 0.2 AND b.altitude < 1.6 THEN 1 WHEN b.altitude >= 1.6 THEN 2 END AS altitude_band, count(*) AS number_of_measurements, avg(b.u_speed) AS avg_u_speed, avg(b.v_speed) AS avg_v_speed, avg(b.bird_density) AS avg_bird_density FROM bird_migration_altitude_profiles b LEFT JOIN radars r ON b.radar_id = r.cartodb_id WHERE b.radial_velocity_std >= 2 AND b.bird_density >= 10 AND b.altitude >= 0.2 GROUP BY b.radar_id, r.the_geom, interval_start_time, altitude_band ORDER BY b.radar_id, interval_start_time, altitude_band DESC ) SELECT * FROM aggregated_data WHERE altitude_band = %s AND interval_start_time = '%s'", [time_frame, time_frame, altitude, time]);
 	var url = "https://lifewatch-inbo.cartodb.com/api/v2/sql?q=" + encodeURIComponent(sql);
 	console.log(sql);
    var result = fetchRadarData(url, "");
    return result;
}
<commit_msg>Update copyright statement<commit_after>/**
 * Bird migration flow visualization for Belgium & the Netherlands
 *
 * https://github.com/enram/bird-migration-flow-visualization
 * Copyright (c) 2014 LifeWatch INBO
 * The MIT License - http://opensource.org/licenses/MIT
 *
 */

function fetchRadarData(url) {
	var result = jQuery.get(url, function(data) {
 		jQuery('.result').html(data);
 	});
 	return result;
 }

/*
 * Retrieve data from our radars with altitude and start time as parameter
 * @param altitude a number to define which altitude band you need.  Currently 1 == low and 2 == high
 */
function retrieveRadarDataByAltitudeAndTime(altitude, time) {
	var time_frame = "20 "; /* Time frames of 20 minutes */
 	var sql = vsprintf("WITH aggregated_data AS ( SELECT b.radar_id, ST_X(r.the_geom) AS longitude, ST_Y(r.the_geom) AS latitude, date_trunc('hour', b.start_time) + date_part('minute', b.start_time)::int / %s * interval '%s min' AS interval_start_time, CASE WHEN b.altitude >= 0.2 AND b.altitude < 1.6 THEN 1 WHEN b.altitude >= 1.6 THEN 2 END AS altitude_band, count(*) AS number_of_measurements, avg(b.u_speed) AS avg_u_speed, avg(b.v_speed) AS avg_v_speed, avg(b.bird_density) AS avg_bird_density FROM bird_migration_altitude_profiles b LEFT JOIN radars r ON b.radar_id = r.cartodb_id WHERE b.radial_velocity_std >= 2 AND b.bird_density >= 10 AND b.altitude >= 0.2 GROUP BY b.radar_id, r.the_geom, interval_start_time, altitude_band ORDER BY b.radar_id, interval_start_time, altitude_band DESC ) SELECT * FROM aggregated_data WHERE altitude_band = %s AND interval_start_time = '%s'", [time_frame, time_frame, altitude, time]);
 	var url = "https://lifewatch-inbo.cartodb.com/api/v2/sql?q=" + encodeURIComponent(sql);
 	console.log(sql);
    var result = fetchRadarData(url, "");
    return result;
}
<|endoftext|>


<commit_before>import React, {Component} from "react";
import { FormattedDate } from 'react-intl';

import './Movie.css';

import {FormatList} from '../../Format';
import {Duration} from '../../Duration';

class Movie extends Component {
  render() {
    let movie = this.props.movie;
    return (

{movie.title}

          {movie.originalTitle}

            <Duration className="duration" value={movie.duration} />
            <FormattedDate className="theater-release-Date" value={new Date(movie.theaterReleaseDate * 1000)}/>
            <FormatList formats={movie.formats}/>

{movie.synopsis}

    )
  }
}

export default Movie;<commit_msg>updates Movie Component to new model format<commit_after>import React, {Component} from "react";
import { FormattedDate } from 'react-intl';

import './Movie.css';

import {FormatList} from '../../Format';
import {Duration} from '../../Duration';

class Movie extends Component {
  render() {
    let movie = this.props.movie;
    return (

        {movie.cover && }

{movie.title}

          {movie.originalTitle && {movie.originalTitle}}

            {movie.duration && <Duration className="duration" value={movie.duration} />}
            <FormattedDate className="theater-release-Date" value={new Date(movie.releaseDate)}/>
            {movie.formats && <FormatList formats={movie.formats}/>}

{movie.synopsis}

    )
  }
}

export default Movie;
<|endoftext|>


<commit_before>{"101":{"department":"FILMPROD","number":"101","title":"Screenwriting (FILMPROD 301)","description":"Priority to Film and Media Studies majors. Craft, form, and approaches to writing for the screen. Prerequisites: 1) ENGLISH 90, 2) ENGLISH 190F or FILMPROD 104, and 3) consent of instructor.","min_units":5,"max_units":5,"gers":[],"id":205795,"primary":[[],[],[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"1:15:00 PM","end":"3:05:00 PM","location":"540-103"}],"id":21838}]],"primary_type":"Lecture"},
"103":{"department":"FILMPROD","number":"103","title":"Adaptation","description":"A close analysis of film adaptation, using various source materials to examine the demands form makes on content and the creative choices made in adaptation to film. Source materials will include plays, fiction, biography, history, graphic novels, and reference to video games and amusement park rides. A weekly film screening is a requirement of the course.","min_units":4,"max_units":4,"gers":["WAY-CE"],"id":211138,"primary":[[],[],[{"instructors":[],"meeting-times":[{"days":[true,false,false,false,false],"start":"7:00:00 PM","end":"9:00:00 PM","location":"Art4"},{"days":[true,false,true,false,false],"start":"10:00:00 AM","end":"11:50:00 AM","location":"160-124"}],"id":39047}]],"primary_type":"Lecture"},
"105":{"department":"FILMPROD","number":"105","title":"Script Analysis (FILMPROD 305)","description":"Analysis of screenplay and film from the writer's perspective, with focus on ideation, structure, and dramatic tension in narrative features. Sources include screenplays and screenings.","min_units":4,"max_units":4,"gers":[],"id":209404,"primary":[[{"instructors":[],"meeting-times":[{"days":[true,false,false,false,false],"start":"7:00:00 PM","end":"9:00:00 PM","location":"120-S64"},{"days":[false,true,false,true,false],"start":"12:35:00 PM","end":"2:05:00 PM","location":"160-124"}],"id":29798}],[],[]],"primary_type":"Seminar"},
"106":{"department":"FILMPROD","number":"106","title":"Image and Sound","description":"This course will explore fiction, nonfiction, and experimental modes of storytelling using visual and aural elements. Through the production of five short projects, the student will be encouraged to adopt innovative approaches to a range of narrative forms.","min_units":2,"max_units":2,"gers":["WAY-CE"],"id":214866,"primary":[[],[{"instructors":[],"meeting-times":[{"days":[false,false,false,false,true],"start":"1:15:00 PM","end":"4:05:00 PM","location":"Meyer 220"}],"id":57290}],[{"instructors":[],"meeting-times":[{"days":[false,false,false,false,true],"start":"1:15:00 PM","end":"4:05:00 PM","location":"50-52E"}],"id":58009}]],"primary_type":"Seminar"},
"114":{"department":"FILMPROD","number":"114","title":"Introduction to Film and Video Production","description":"Hands-on. Techniques of film and video making including conceptualization, visualization, story structure, cinematography, sound recording, and editing. Enrollment limited to 12 students. Priority to junior/senior Film & Media Studies majors.","min_units":5,"max_units":5,"gers":["WAY-CE"],"id":205135,"primary":[[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"2:15:00 PM","end":"4:05:00 PM","location":"120-S60"}],"id":34678}],[],[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"1:15:00 PM","end":"3:05:00 PM","location":""}],"id":32686}]],"primary_type":"Practicum"},
"301":{"department":"FILMPROD","number":"301","title":"Screenwriting (FILMPROD 101)","description":"Priority to Film and Media Studies majors. Craft, form, and approaches to writing for the screen. Prerequisites: 1) ENGLISH 90, 2) ENGLISH 190F or FILMPROD 104, and 3) consent of instructor.","min_units":5,"max_units":5,"gers":[],"id":205795,"primary":[[],[],[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"1:15:00 PM","end":"3:05:00 PM","location":"540-103"}],"id":31110}]],"primary_type":"Lecture"},
"305":{"department":"FILMPROD","number":"305","title":"Script Analysis (FILMPROD 105)","description":"Analysis of screenplay and film from the writer's perspective, with focus on ideation, structure, and dramatic tension in narrative features. Sources include screenplays and screenings.","min_units":4,"max_units":4,"gers":[],"id":209404,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"12:35:00 PM","end":"2:05:00 PM","location":"160-124"},{"days":[true,false,false,false,false],"start":"7:00:00 PM","end":"9:00:00 PM","location":"120-S64"}],"id":29800}],[],[]],"primary_type":"Seminar"}}<commit_msg>Delete FILMPROD.js<commit_after><|endoftext|>


<commit_before><commit_msg>Create spectbackup.js<commit_after><|endoftext|>