<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

var ready = function() {
  Highcharts.setOptions({
    chart: {
      backgroundColor: '#A4DEF4',
      height: 600,
      width: 1400
    },
    title: {
      style: {
        color: '#A4DEF4'
      }
    },
    legend: {
      title: {
        style: {
          color: '#161A59'
        }
      }
    },
    colorAxis: {
      minColor: '#A9E455',
      maxColor: '#71A33D'
    }
  });

  $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=world-population-density.json&callback=?', function (data) {
        // Initiate the chart
        $('#container').highcharts('Map', {
          mapNavigation: {
            buttonOptions: {
              verticalAlign: 'bottom'
            },
            enableDoubleClickZoomTo: true
          },
          legend: {
            enabled: true
          },
          tooltip: {
            style: {
              backgroundColor: 'black',
              opacity: '1.0',
              color: 'black',
              fontSize: '12px',
              padding: '8px',
              border: 'black'
            }
          },
        //     chart: {
        //     events: {
        //         click: function(event) {
        //             alert ('x: '+ event.xAxis[0].value +', y: '+
        //                   event.yAxis[0].value);
        //         }
        //     }
        // },
        colorAxis: {
          min: 1,
          max: 1000,
          type: 'logarithmic',
          minColor: '#9BDA6A',
          maxColor: '#004D26',
        },
        plotOptions: {
          series: {
            cursor: 'pointer',
            events: {
              click: function(event) {
                $("#search").val(event.point.code);
                $("#searchbutton").click();
              }
            }
          }
        },
        series : [{
          data : data,
          mapData: Highcharts.maps['custom/world'],
          joinBy: ['iso-a2', 'code'],
          borderColor: 'black',
          name: 'Country',
          states: {
            hover: {
              // changes country color on map
              color: '#CCFFB3'
            }
          },
          tooltip: {
            pointFormat: '{point.name}'
          }
        }]
      });
});
};

$(document).ready(ready);
$(document).on('page:load', ready);
<commit_msg>adds blue / red coloring<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

var positiveState = {
  color: '#FF0000',
  tweets: 120
}

var negativeState = {
  color: '#0000FF',
  tweets: 120
}

var ready = function() {
  Highcharts.setOptions({
    chart: {
      backgroundColor: '#A4DEF4',
      height: 600,
      width: 1400
    },
    title: {
      style: {
        color: '#A4DEF4'
      }
    },
    legend: {
      title: {
        style: {
          color: '#161A59'
        }
      }
    },
    colorAxis: {
      minColor: '#0000FF',
      maxColor: '#FF0000'
    }
  });

  $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=world-population-density.json&callback=?', function (data) {
        // Initiate the chart
        $('#container').highcharts('Map', {
          mapNavigation: {
            buttonOptions: {
              verticalAlign: 'bottom'
            },
            enableDoubleClickZoomTo: true
          },
          legend: {
            enabled: true
          },
          tooltip: {
            style: {
              backgroundColor: 'black',
              opacity: '1.0',
              color: 'black',
              fontSize: '12px',
              padding: '8px',
              border: 'black'
            }
          },
        //     chart: {
        //     events: {
        //         click: function(event) {
        //             alert ('x: '+ event.xAxis[0].value +', y: '+
        //                   event.yAxis[0].value);
        //         }
        //     }
        // },
        colorAxis: {
          min: 1,
          max: 1000,
          type: 'logarithmic',
          minColor: '#0000FF',
          maxColor: '#FF0000',
        },
        plotOptions: {
          series: {
            cursor: 'pointer',
            events: {
              click: function(event) {
                $("#search").val(event.point.code);
                $("#searchbutton").click();
              }
            }
          }
        },
        series : [{
          data : data,
          mapData: Highcharts.maps['custom/world'],
          joinBy: ['iso-a2', 'code'],
          borderColor: 'black',
          name: 'Country',
          states: {
            hover: {
              // changes country color on map
              color: '#CCFFB3'
            }
          },
          tooltip: {
            pointFormat: '{point.name}'
          }
        }]
      });
});
};

$(document).ready(ready);
$(document).on('page:load', ready);
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require_tree .

$( document ).ready(function() {
  $(function(){ $(document).foundation(); });

  $("body").on("click", ".add_waypoint a", function(event){
    event.preventDefault();

    $("#new_waypoint").show();

    $(".add_waypoint a").hide();
    })

  $("body").on("click", "#close_waypoint", function(event){
    event.preventDefault();
    $(".waypoint_placeholder").hide();
    $(".add_waypoint a").show();
    $(".waypoint_placeholder").append( $("#new_waypoint").hide() );
    })

});<commit_msg>fixed add waypoint button on the start page.  It now appears again when you add it back in<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require_tree .

$( document ).ready(function() {
  $(function(){ $(document).foundation(); });

  $("body").on("click", ".add_waypoint a", function(event){
    event.preventDefault();

    $("#new_waypoint").show();
    $(".add_waypoint a").hide();
  });

  $("body").on("click", "#close_waypoint", function(event){
    event.preventDefault();
    $("#new_waypoint").hide();
    $("#new_waypoint input").val(null);
    $(".add_waypoint a").show();
  });

});<|endoftext|>


<commit_before>// ==UserScript==
// @name Greasemonkey EndomondoDesign
// @namespace https://github.com/JanisE
// @description Project URL: https://github.com/JanisE/greasemonkey-endomondo-design
// @include *www.endomondo.com/*
// @version 1
// @grant none
// ==/UserScript==

var css = document.createElement('style');
css.type = 'text/css';
css.innerHTML = ".feedItem-footer .eoAvatar-image {visibility: hidden} .eoFeedWorkout-right {display: none}";
document.head.appendChild(css);
<commit_msg>Avatars should be hidden only before the comment input field.<commit_after>// ==UserScript==
// @name Greasemonkey EndomondoDesign
// @namespace https://github.com/JanisE
// @description Project URL: https://github.com/JanisE/greasemonkey-endomondo-design
// @include *www.endomondo.com/*
// @version 1
// @grant none
// ==/UserScript==

var css = document.createElement('style');
css.type = 'text/css';
css.innerHTML = ".feedItem-footer .eoComments-post .eoAvatar-image {visibility: hidden} .eoFeedWorkout-right {display: none}";
document.head.appendChild(css);
<|endoftext|>


<commit_before>/**
 * @module Foundation
 * @submodule Declaration
 * @for p5
 */

/**
 * Creates and names a new variable. A variable is a container for a value.
 * Variables that are declared with let will have block-scope.
 * This means that the variable only exists within the
 * block that it is created within.
 *
 *
 * From the MDN entry:
 * Declares a block scope local variable, optionally initializing it to a value.
 *
 * @property let
 *
 * @example
 *

 *
 * let x = 2;
 * console.log(x); // prints 2 to the console
 * x = 1;
 * console.log(x); // prints 1 to the console
 *
 *

 */

/**
 * Creates and names a new constant. Like a variable created with let, a constant
 * that is created with const is a container for a value,
 * however constants cannot be changed once they are declared.
 * Constants have block-scope. This means that the constant only exists within
 * the
 * block that it is created within. A constant cannot be redeclared within a scope in which it
 * already exists.
 *
 * From the MDN entry:
 * Declares a read-only named constant.
 * Constants are block-scoped, much like variables defined using the 'let' statement.
 * The value of a constant can't be changed through reassignment, and it can't be redeclared.
 * @property const
 *
 * @example
 *

 *
 * // define myFavNumber as a constant and give it the value 7
 * const myFavNumber = 7;
 * console.log('my favorite number is: ' + myFavNumber);
 *
 *

 */

/**
 * @submodule Control Statement
 */

/**
 * The if-else statement helps control the flow of your code.
 * A condition is placed between the parenthesis following 'if'.
 * When that condition evalues to truthy,
 * the code between the following curly braces is run.
 * Alternatively, when the condition evaluates to falsy,
 * the code between the curly braces that follow 'else' is run instead.
 *
 * From the MDN entry:
 * The 'if' statement executes a statement if a specified condition is truthy.
 * If the condition is falsy, another statement can be executed
 * @property if-else
 *
 * @example
 *

 *
 * let a = 4;
 * if (a > 0) {
 *   console.log('positive');
 * } else {
 *   console.log('negative');
 * }
 *
 *

 */

/**
 * @submodule Function
 */

/**
 * Creates and names a function.
 * A function is a set of statements that perform a task.
 * Optionally, functions can have parameters. Parameters
 * are variables that are scoped to the function, that can be assigned a value when calling the function.
 *
 * From the MDN entry:
 * Declares a function with the specified parameters.
 * @property function
 *
 * @example
 *

 *
 * function calculateRectArea(width, height) {
 *   return width * height;
 * }
 * calculateRectArea(4, 5); // calling the function
 *
 *

 */

/**
 * Specifies the value to be returned by a function.
 * For more info checkout
 * the MDN entry for return.
 * @property return
 *
 * @example
 *

 *
 * function calculateSquare(x) {
 *   return x * x;
 * }
 * calculateSquare(4); // returns 16
 *
 *

 */

/**
 * @submodule Types
 */

/**
 * A boolean is one of the 7 primitive data types in Javascript.
 * A boolean can only be `true` or `false`.
 *
 * From the MDN entry:
 * Boolean represents a logical entity and can have two values: true, and false.
 *
 * @property boolean
 *
 * @example
 *

 *
 * let myBoolean = false;
 * console.log(typeof myBoolean); // prints 'boolean' to the console
 *
 *

 */

/**
 * A string is one of the 7 primitive data types in Javascript.
 * A string is a series of text characters. In Javascript, a string value must be surrounded by either single-quotation marks(') or double-quotation marks(").
 *
 * From the MDN entry:
 * A string is a sequence of characters used to represent text.
 *
 * @property string
 *
 * @example
 *

 *
 * let mood = 'chill';
 * console.log(typeof mood); // prints 'string' to the console
 *
 *

 */

/**
 * A number is one of the 7 primitive data types in Javascript.
 * A number can be a whole number or a decimal number.
 *
 * The MDN entry for number
 *
 * @property number
 *
 * @example
 *

 *
 * let num = 46.5;
 * console.log(typeof num); // prints 'number' to the console
 *
 *

 */

/**
 *
 * From MDN's object basics:
 * An object is a collection of related data and/or functionality (which usually consists of several variables and functions —
 * which are called properties and methods when they are inside objects.)
 * @property object
 *
 * @example
 *

 *
 * let author = {
 *   name: 'Ursula K Le Guin',
 *   books: [
 *     'The Left Hand of Darkness',
 *     'The Dispossessed',
 *     'A Wizard of Earthsea'
 *   ]
 * };
 * console.log(author.name); // prints 'Ursula K Le Guin' to the console
 *
 *

 */

/**
 * @submodule Classes
 */

/**
 * Creates and names a class which is a template for the creation of objects.
 *
 * From the MDN entry:
 * The class declaration creates a new Class with a given name using prototype-based inheritance.
 * @property class
 *
 * @example
 *

 *
 * class Polygon {
 *   constructor(name, height, width) {
 *     this.name = name;
 *     this.height = height;
 *     this.width = width;
 *   }
 * }
 * let square = new Polygon('square', 1, 1); // creating new instance of Polygon Class.
 * console.log(square.width); // prints '1' to the console
 *
 *

 */

/**
 * @submodule Iterative Statement
 */

/**
 * for creates a loop that is useful for executing the code multiple times.
 *
 * A 'for loop' consists of three different expressions inside of a parenthesis, all of which are optional.
 * These expressions are used to control the number of times the loop is run.
 * The first expression is a statement that is used to set the initial state for the loop.
 * The second expression is a condition that you would like to check before each loop. If this expression returns
 * false then the loop will exit.
 * The third expression is executed at the end of each loop.
 *
 * The code inside of the loop body (in between the curly braces) is executed between the evaluation of the second
 * and third expression.
 *
 * From the MDN entry:
 * Creates a loop that executes a specified statement until the test condition evaluates to false.
 * The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
 * @property for
 *
 * @example
 *

 *
 * for (let i = 0; i < 9; i++) {
 *   console.log(i);
 * }
 *
 *

 */

/**
 * @submodule JS Method
 */

/**
 * From the MDN entry:
 * The JSON.stringify() method converts a JavaScript object or value to a JSON string.
 * @method stringify
 * @for JSON
 * @param {Object} object :Javascript object that you would like to convert to JSON
 *
 * @example
 *

 *
 * let myObject = { x: 5, y: 6 };
 * let myObjectAsString = JSON.stringify(myObject);
 * console.log(myObjectAsString); // prints "{"x":5,"y":6}" to the console
 * console.log(typeof myObjectAsString); // prints 'string' to the console
 *
 *

 */
<commit_msg>Add console.log reference<commit_after>/**
 * @module Foundation
 * @submodule Declaration
 * @for p5
 */

/**
 * Creates and names a new variable. A variable is a container for a value.
 * Variables that are declared with let will have block-scope.
 * This means that the variable only exists within the
 * block that it is created within.
 *
 *
 * From the MDN entry:
 * Declares a block scope local variable, optionally initializing it to a value.
 *
 * @property let
 *
 * @example
 *

 *
 * let x = 2;
 * console.log(x); // prints 2 to the console
 * x = 1;
 * console.log(x); // prints 1 to the console
 *
 *

 */

/**
 * Creates and names a new constant. Like a variable created with let, a constant
 * that is created with const is a container for a value,
 * however constants cannot be changed once they are declared.
 * Constants have block-scope. This means that the constant only exists within
 * the
 * block that it is created within. A constant cannot be redeclared within a scope in which it
 * already exists.
 *
 * From the MDN entry:
 * Declares a read-only named constant.
 * Constants are block-scoped, much like variables defined using the 'let' statement.
 * The value of a constant can't be changed through reassignment, and it can't be redeclared.
 * @property const
 *
 * @example
 *

 *
 * // define myFavNumber as a constant and give it the value 7
 * const myFavNumber = 7;
 * console.log('my favorite number is: ' + myFavNumber);
 *
 *

 */

/**
 * @submodule Control Statement
 */

/**
 * The if-else statement helps control the flow of your code.
 * A condition is placed between the parenthesis following 'if'.
 * When that condition evalues to truthy,
 * the code between the following curly braces is run.
 * Alternatively, when the condition evaluates to falsy,
 * the code between the curly braces that follow 'else' is run instead.
 *
 * From the MDN entry:
 * The 'if' statement executes a statement if a specified condition is truthy.
 * If the condition is falsy, another statement can be executed
 * @property if-else
 *
 * @example
 *

 *
 * let a = 4;
 * if (a > 0) {
 *   console.log('positive');
 * } else {
 *   console.log('negative');
 * }
 *
 *

 */

/**
 * @submodule Function
 */

/**
 * Creates and names a function.
 * A function is a set of statements that perform a task.
 * Optionally, functions can have parameters. Parameters
 * are variables that are scoped to the function, that can be assigned a value when calling the function.
 *
 * From the MDN entry:
 * Declares a function with the specified parameters.
 * @property function
 *
 * @example
 *

 *
 * function calculateRectArea(width, height) {
 *   return width * height;
 * }
 * calculateRectArea(4, 5); // calling the function
 *
 *

 */

/**
 * Specifies the value to be returned by a function.
 * For more info checkout
 * the MDN entry for return.
 * @property return
 *
 * @example
 *

 *
 * function calculateSquare(x) {
 *   return x * x;
 * }
 * calculateSquare(4); // returns 16
 *
 *

 */

/**
 * @submodule Types
 */

/**
 * A boolean is one of the 7 primitive data types in Javascript.
 * A boolean can only be `true` or `false`.
 *
 * From the MDN entry:
 * Boolean represents a logical entity and can have two values: true, and false.
 *
 * @property boolean
 *
 * @example
 *

 *
 * let myBoolean = false;
 * console.log(typeof myBoolean); // prints 'boolean' to the console
 *
 *

 */

/**
 * A string is one of the 7 primitive data types in Javascript.
 * A string is a series of text characters. In Javascript, a string value must be surrounded by either single-quotation marks(') or double-quotation marks(").
 *
 * From the MDN entry:
 * A string is a sequence of characters used to represent text.
 *
 * @property string
 *
 * @example
 *

 *
 * let mood = 'chill';
 * console.log(typeof mood); // prints 'string' to the console
 *
 *

 */

/**
 * A number is one of the 7 primitive data types in Javascript.
 * A number can be a whole number or a decimal number.
 *
 * The MDN entry for number
 *
 * @property number
 *
 * @example
 *

 *
 * let num = 46.5;
 * console.log(typeof num); // prints 'number' to the console
 *
 *

 */

/**
 *
 * From MDN's object basics:
 * An object is a collection of related data and/or functionality (which usually consists of several variables and functions —
 * which are called properties and methods when they are inside objects.)
 * @property object
 *
 * @example
 *

 *
 * let author = {
 *   name: 'Ursula K Le Guin',
 *   books: [
 *     'The Left Hand of Darkness',
 *     'The Dispossessed',
 *     'A Wizard of Earthsea'
 *   ]
 * };
 * console.log(author.name); // prints 'Ursula K Le Guin' to the console
 *
 *

 */

/**
 * @submodule Classes
 */

/**
 * Creates and names a class which is a template for the creation of objects.
 *
 * From the MDN entry:
 * The class declaration creates a new Class with a given name using prototype-based inheritance.
 * @property class
 *
 * @example
 *

 *
 * class Polygon {
 *   constructor(name, height, width) {
 *     this.name = name;
 *     this.height = height;
 *     this.width = width;
 *   }
 * }
 * let square = new Polygon('square', 1, 1); // creating new instance of Polygon Class.
 * console.log(square.width); // prints '1' to the console
 *
 *

 */

/**
 * @submodule Iterative Statement
 */

/**
 * for creates a loop that is useful for executing the code multiple times.
 *
 * A 'for loop' consists of three different expressions inside of a parenthesis, all of which are optional.
 * These expressions are used to control the number of times the loop is run.
 * The first expression is a statement that is used to set the initial state for the loop.
 * The second expression is a condition that you would like to check before each loop. If this expression returns
 * false then the loop will exit.
 * The third expression is executed at the end of each loop.
 *
 * The code inside of the loop body (in between the curly braces) is executed between the evaluation of the second
 * and third expression.
 *
 * From the MDN entry:
 * Creates a loop that executes a specified statement until the test condition evaluates to false.
 * The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
 * @property for
 *
 * @example
 *

 *
 * for (let i = 0; i < 9; i++) {
 *   console.log(i);
 * }
 *
 *

 */

/**
 * @submodule JS Method
 */

/**
 * From the MDN entry:
 * The JSON.stringify() method converts a JavaScript object or value to a JSON string.
 * @method stringify
 * @for JSON
 * @param {Object} object :Javascript object that you would like to convert to JSON
 *
 * @example
 *

 *
 * let myObject = { x: 5, y: 6 };
 * let myObjectAsString = JSON.stringify(myObject);
 * console.log(myObjectAsString); // prints "{"x":5,"y":6}" to the console
 * console.log(typeof myObjectAsString); // prints 'string' to the console
 *
 *

 */

/**
 * Prints a message to your browser's web console. When using p5, you can use print
 * and console.log interchangeably.
 *
 * The console is opened differently depending on which browser you are using.
 * Here are links on how to open the console in Firefox
 * , Chrome, Edge,
 * and Safari. With the online p5 editor the
 * console is embedded directly in the page underneath the code editor.
 *
 * From the MDN entry:
 * The Console method log() outputs a message to the web console. The message may be a single string (with optional substitution values),
 * or it may be any one or more JavaScript objects.
 * @method log
 * @for console
 * @param {String|Expression|Object} message :Message that you would like to print to the console
 *
 * @example
 *

 *
 * let myNum = 5;
 * console.log(myNum); // prints 5 to the console
 * console.log(myNum + 12); // prints 17 to the console
 *
 *

 */
<|endoftext|>


<commit_before>/**
 * Deal with various features of the fancy "Forms UI" type implementaion
 */
(function($) {
	var fapi = window.wpFormsApi = window.wpFormsApi || {}
		, media = wp.media;

	// Adjust styles to account for variations when using box-sizing
	$.widget('custom.postListMenu', $.ui.autocomplete, {
		_resizeMenu: function() {
			this.menu.element.width($(this.element).outerWidth());
			$(this.menu.element).css('z-index', 10000000);
		},
	});

	// Multiple-list field
	$(function() {
		$('.wp-form .wp-form-multiple').each(function() {
			var $container = $(this),
			  $list = $('#' + $container.data('list')),
			  $tmpl = $('#' + $container.data('template'));

			function reindex() {
				// Note which elements are checked to prevent radio buttons from losing
				// their checked state when elements are renamed (and there is a brief
				// name collision!)
				var $checked = $list.find(':checked');

				$list.find('> li').each(function(i) {
					var $item = $(this);

					$item.find('*').each(function() {
						// Replace patterns like -2- or [4] with -$index- and [$index] in attributes
						// Not exactly super safe, but easy
						for(var j = 0; j < this.attributes.length; j++) {
							this.attributes[j].value = this.attributes[j].value.replace(
								/([ \w_\[\]-]+[\[-])\d+([\]-][ \w_\[\]-]+)/g, '$1' + i + '$2');
						}
					});
				});

				$checked.prop('checked', true);
			}

			$container.find('.wp-form-multiple-list').sortable({
				handle: '.sort-multiple-item',
				update: reindex
			});

			$container
				// Add a new multiple item on click
				.on('click', '.add-multiple-item', function() {
					var $t = $(this),
						count = $list.children('li').length,
						$html = $($tmpl.text().replace(/%INDEX%/g, count));

					initialize($html);

					$list.append($html);
				})

				// Remove an item item on click
				.on('click', '.remove-multiple-item', function() {
					var $t = $(this),
						$item = $t.parents('li');

					$item.remove();

					reindex();
				});
		});
	});

	// Image field
	if (media && typeof media == 'object') {
		var WPFormImageField = media.View.extend({
			template: media.template('wp-form-attachment-field'),
			events: {
				'change .wp-form-attachment-id': 'update',
				'click .attachment-delete': 'removeAttachment',
				'click .attachment-container': 'selectAttachment'
			},

			selectAttachment: function() {
				var view = this,
					frameOpts = {
						frame: 'select',
						title: this.input_type == 'image' ? "Select Image" : "Select Attachment"
					};

				if(this.input_type == 'image') {
					frameOpts.library = { type: 'image' };
				}

				media.frame = media(frameOpts).open();

				media.frame.on('select', function(el) {
					var image = this.get('library').get('selection').single();

					view.model.set(image.attributes);
				});
			},

			removeAttachment: function() {
				this.model.clear();
			},

			initialize: function() {
				if(!this.model) {
					this.model = new Backbone.Model();
				}

				this.model.on('change', this.render, this);
			},

			prepare: function() {
				var data = this.model.toJSON();

				data.input_name = this.input_name;
				data.input_type = this.input_type;

				return data;
			},

			update: function() {
				var view = this,
					$field = this.$el.find('.wp-form-attachment-id'),
					attachmentId = $field.val(),
					attachment = media.model.Attachment.get(attachmentId).clone();

				view.model.clear({ silent: true });
				view.model.set({ id: attachmentId });

				$field.addClass('ui-dirty');

				attachment.fetch()
					.done(function() {
						$field.removeClass('ui-dirty');
						view.model.set(this.attributes);
					})
					.fail(function() {
						$field.addClass('ui-dirty');
					});
			}
		});

		var initializeAttachments = function(context) {
			$(context).find('.select-attachment-field').each(function() {
				var view = new WPFormImageField({
					model: media.model.Attachment.get(this.value).clone()
				});

				view.model.fetch();

				// Don't save input name as part of the model as it should be invariant
				view.input_name = this.name;
				view.input_type = $(this).data('attachment-type');

				view.render();

				view.$el.attr('class', $(this).attr('class'));
				view.$el.data('view', view);

				$(this).replaceWith(view.$el);
			});
		}
	}

	var initializePostSelect = function(context, args) {
		args = args || {};

		$(context).find('.wp-form-post-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input'),
			  model = new Backbone.Model({ id: $input.val() });

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('title')) {
				$field.val($input.data('title'));
				model.set('title', $input.data('title'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));

			var update = function(ev, ui) {
				var id = ui.item && ui.item.model.get('id');

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			// Extend jQuery UI autocomplete with a custom resizer
			$field.postListMenu(_.extend(args, {
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('post-type')) {
						attrs['post_type'] = $input.data('post-type').split(' ');
					}

					wp.ajax.post('wp_form_search_posts', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.post_title,
									value: v.post_title,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			}));

			$input.trigger('selected', { model: model });
		});
	}

	var initializeTermSelect = function(context) {
		$(context).find('.wp-form-term-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input');

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('name')) {
				$field.val($input.data('name'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));
			$field.attr('class', $input.attr('class').replace(/\bwp-form-[^\s]*\s*/g, ''));

			var update = function(ev, ui) {
				var id = ui.item ? ui.item.model.get('term_id') : '',
						label = ui.item ? ui.item.model.get('name') : '';

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			$field.autocomplete({
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('taxonomy')) {
						attrs['taxonomy'] = $input.data('taxonomy');
					}

					wp.ajax.post('wp_form_search_terms', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.name,
									value: v.name,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			});
		});
	}

	function initializeConditionalLogic(context) {
		$(context).find('[data-conditional-element]').each(function() {
			$(this).on('change', conditionalLogicInputChange);
			conditionalLogicInputChange.apply(this);
		});
	}

	function conditionalLogicInputChange() {
		var $this      = $(this)
		  , target     = $this.data('conditional-element')
	  	  , value      = $this.data('conditional-value')
	  	  , action     = $this.data('conditional-action')
	  	  , $target    = $(target)
	  	  , inputValue = $this.val();

	  	if ($target.length == 0) {
	  		// Bail - target element doesn't exist
	  		return;
	  	}

	  	// For checkboxes, we can not use .val() because it will always
	  	// return the value attribute regardless if the checkbox is checked
		if ($this.is(':checkbox') && !$this.is(':checked')) {
			inputValue = false;
		}

		if (action == 'show') {
			if (value == inputValue) {
				$target.show();
			}
			else {
				$target.hide();
			}
		}

		if (action == 'hide') {
			if (value == inputValue) {
				$target.hide();
			}
			else {
				$target.show();
			}
		}
	}

	function initialize(context) {
		if (media && typeof media == 'object') {
			initializeAttachments(context);
		}

		initializePostSelect(context);
		initializeTermSelect(context);
		initializeConditionalLogic(context);
	}

	$(function() {
		initialize('body');
	});

	fapi.setup = initialize;

	if (media && typeof media == 'object') {
		fapi.initializeAttachments = initializeAttachments;
	}

	fapi.initializePostSelect = initializePostSelect;
	fapi.initializeTermSelect = initializeTermSelect;
	fapi.initializeConditionalLogic = initializeConditionalLogic;
})(jQuery);
<commit_msg>Fix bug where image field is not display properly<commit_after>/**
 * Deal with various features of the fancy "Forms UI" type implementaion
 */
(function($) {
	var fapi = window.wpFormsApi = window.wpFormsApi || {}
		, media = wp.media;

	// Adjust styles to account for variations when using box-sizing
	$.widget('custom.postListMenu', $.ui.autocomplete, {
		_resizeMenu: function() {
			this.menu.element.width($(this.element).outerWidth());
			$(this.menu.element).css('z-index', 10000000);
		},
	});

	// Multiple-list field
	$(function() {
		$('.wp-form .wp-form-multiple').each(function() {
			var $container = $(this),
			  $list = $('#' + $container.data('list')),
			  $tmpl = $('#' + $container.data('template'));

			function reindex() {
				// Note which elements are checked to prevent radio buttons from losing
				// their checked state when elements are renamed (and there is a brief
				// name collision!)
				var $checked = $list.find(':checked');

				$list.find('> li').each(function(i) {
					var $item = $(this);

					$item.find('*').each(function() {
						// Replace patterns like -2- or [4] with -$index- and [$index] in attributes
						// Not exactly super safe, but easy
						for(var j = 0; j < this.attributes.length; j++) {
							this.attributes[j].value = this.attributes[j].value.replace(
								/([ \w_\[\]-]+[\[-])\d+([\]-][ \w_\[\]-]+)/g, '$1' + i + '$2');
						}
					});
				});

				$checked.prop('checked', true);
			}

			$container.find('.wp-form-multiple-list').sortable({
				handle: '.sort-multiple-item',
				update: reindex
			});

			$container
				// Add a new multiple item on click
				.on('click', '.add-multiple-item', function() {
					var $t = $(this),
						count = $list.children('li').length,
						$html = $($tmpl.text().replace(/%INDEX%/g, count));

					initialize($html);

					$list.append($html);
				})

				// Remove an item item on click
				.on('click', '.remove-multiple-item', function() {
					var $t = $(this),
						$item = $t.parents('li');

					$item.remove();

					reindex();
				});
		});
	});

	// Image field
	if (media && typeof media == 'function') {
		var WPFormImageField = media.View.extend({
			template: media.template('wp-form-attachment-field'),
			events: {
				'change .wp-form-attachment-id': 'update',
				'click .attachment-delete': 'removeAttachment',
				'click .attachment-container': 'selectAttachment'
			},

			selectAttachment: function() {
				var view = this,
					frameOpts = {
						frame: 'select',
						title: this.input_type == 'image' ? "Select Image" : "Select Attachment"
					};

				if(this.input_type == 'image') {
					frameOpts.library = { type: 'image' };
				}

				media.frame = media(frameOpts).open();

				media.frame.on('select', function(el) {
					var image = this.get('library').get('selection').single();

					view.model.set(image.attributes);
				});
			},

			removeAttachment: function() {
				this.model.clear();
			},

			initialize: function() {
				if(!this.model) {
					this.model = new Backbone.Model();
				}

				this.model.on('change', this.render, this);
			},

			prepare: function() {
				var data = this.model.toJSON();

				data.input_name = this.input_name;
				data.input_type = this.input_type;

				return data;
			},

			update: function() {
				var view = this,
					$field = this.$el.find('.wp-form-attachment-id'),
					attachmentId = $field.val(),
					attachment = media.model.Attachment.get(attachmentId).clone();

				view.model.clear({ silent: true });
				view.model.set({ id: attachmentId });

				$field.addClass('ui-dirty');

				attachment.fetch()
					.done(function() {
						$field.removeClass('ui-dirty');
						view.model.set(this.attributes);
					})
					.fail(function() {
						$field.addClass('ui-dirty');
					});
			}
		});

		var initializeAttachments = function(context) {
			$(context).find('.select-attachment-field').each(function() {
				var view = new WPFormImageField({
					model: media.model.Attachment.get(this.value).clone()
				});

				view.model.fetch();

				// Don't save input name as part of the model as it should be invariant
				view.input_name = this.name;
				view.input_type = $(this).data('attachment-type');

				view.render();

				view.$el.attr('class', $(this).attr('class'));
				view.$el.data('view', view);

				$(this).replaceWith(view.$el);
			});
		}
	}

	var initializePostSelect = function(context, args) {
		args = args || {};

		$(context).find('.wp-form-post-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input'),
			  model = new Backbone.Model({ id: $input.val() });

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('title')) {
				$field.val($input.data('title'));
				model.set('title', $input.data('title'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));

			var update = function(ev, ui) {
				var id = ui.item && ui.item.model.get('id');

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			// Extend jQuery UI autocomplete with a custom resizer
			$field.postListMenu(_.extend(args, {
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('post-type')) {
						attrs['post_type'] = $input.data('post-type').split(' ');
					}

					wp.ajax.post('wp_form_search_posts', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.post_title,
									value: v.post_title,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			}));

			$input.trigger('selected', { model: model });
		});
	}

	var initializeTermSelect = function(context) {
		$(context).find('.wp-form-term-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input');

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('name')) {
				$field.val($input.data('name'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));
			$field.attr('class', $input.attr('class').replace(/\bwp-form-[^\s]*\s*/g, ''));

			var update = function(ev, ui) {
				var id = ui.item ? ui.item.model.get('term_id') : '',
						label = ui.item ? ui.item.model.get('name') : '';

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			$field.autocomplete({
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('taxonomy')) {
						attrs['taxonomy'] = $input.data('taxonomy');
					}

					wp.ajax.post('wp_form_search_terms', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.name,
									value: v.name,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			});
		});
	}

	function initializeConditionalLogic(context) {
		$(context).find('[data-conditional-element]').each(function() {
			$(this).on('change', conditionalLogicInputChange);
			conditionalLogicInputChange.apply(this);
		});
	}

	function conditionalLogicInputChange() {
		var $this      = $(this)
		  , target     = $this.data('conditional-element')
	  	  , value      = $this.data('conditional-value')
	  	  , action     = $this.data('conditional-action')
	  	  , $target    = $(target)
	  	  , inputValue = $this.val();

	  	if ($target.length == 0) {
	  		// Bail - target element doesn't exist
	  		return;
	  	}

	  	// For checkboxes, we can not use .val() because it will always
	  	// return the value attribute regardless if the checkbox is checked
		if ($this.is(':checkbox') && !$this.is(':checked')) {
			inputValue = false;
		}

		if (action == 'show') {
			if (value == inputValue) {
				$target.show();
			}
			else {
				$target.hide();
			}
		}

		if (action == 'hide') {
			if (value == inputValue) {
				$target.hide();
			}
			else {
				$target.show();
			}
		}
	}

	function initialize(context) {
		if (media && typeof media == 'function') {
			initializeAttachments(context);
		}

		initializePostSelect(context);
		initializeTermSelect(context);
		initializeConditionalLogic(context);
	}

	$(function() {
		initialize('body');
	});

	fapi.setup = initialize;

	if (media && typeof media == 'function') {
		fapi.initializeAttachments = initializeAttachments;
	}

	fapi.initializePostSelect = initializePostSelect;
	fapi.initializeTermSelect = initializeTermSelect;
	fapi.initializeConditionalLogic = initializeConditionalLogic;
})(jQuery);
<|endoftext|>


<commit_before>var Ipc = require('ipc');
var Async = require('async');
var Url = require('fire-url');

Ipc.on('scene:ipc-messages', function ( ipcList ) {
    for ( var i = 0; i < ipcList.length; ++i ) {
        Ipc.emit.apply( Ipc, ipcList[i] );
    }
});

Ipc.on('scene:new-scene', function () {
    window.sceneView.newScene();
});

Ipc.on('scene:save-scene-from-page', function ( url ) {
    var sceneAsset = new Fire.Scene();
    sceneAsset.scene = Fire.engine.getCurrentScene();

    // NOTE: we stash scene because we want to save and reload the connected browser
    Editor.stashScene(function () {
        // reload connected browser
        Editor.sendToCore('app:reload-on-device');

        //
        Editor.sendToCore( 'scene:save-scene', url, Editor.serialize(sceneAsset) );
    });
});

Ipc.on('scene:open-scene-by-uuid', function ( uuid ) {
    window.sceneView.loadScene(uuid);
});

Ipc.on('scene:play-on-device', function () {
    Editor.stashScene( function () {
        Editor.sendToCore( 'app:play-on-device' );
    });
});

Ipc.on('scene:reload-on-device', function () {
    Editor.stashScene( function () {
        Editor.sendToCore( 'app:reload-on-device' );
    });
});

Ipc.on('scene:drop', function ( uuids, type, x, y ) {
    Editor.Selection.clear('node');
    Async.each( uuids, function ( uuid, done ) {
        Async.waterfall([
            function ( next ) {
                Editor.createNode(uuid, next);
            },

            function ( node, next ) {
                var nodeID;
                if ( node ) {
                    var wrapper = Fire(node);
                    nodeID = wrapper.uuid;

                    wrapper.position = window.sceneView.pixelToScene( Fire.v2(x,y) );
                    wrapper.parent = Fire.engine.getCurrentScene();
                }

                next ( null, nodeID );
            },

        ], function ( err, nodeID ) {
            if ( err ) {
                Editor.failed( 'Failed to drop asset %s, message: %s', uuid, err.stack );
                return;
            }

            if ( nodeID ) {
                Editor.Selection.select('node', nodeID, false, true );
            }
            Fire.engine.repaintInEditMode();
            done();
        });
    });
});

Ipc.on('scene:create-nodes-by-uuids', function ( uuids, parentID ) {
    var parentNode;
    if ( parentID ) {
        parentNode = Fire.engine.getInstanceByIdN(parentID);
    }
    if ( !parentNode ) {
        parentNode = Fire.engine.getCurrentSceneN();
    }

    Editor.Selection.clear('node');

    //
    Async.each( uuids, function ( uuid, done ) {
        Async.waterfall([
            function ( next ) {
                Editor.createNode(uuid, next);
            },

            function ( node, next ) {
                var nodeID;
                if ( node ) {
                    var wrapper = Fire(node);
                    nodeID = wrapper.uuid;

                    if ( parentNode ) {
                        wrapper.parent = Fire(parentNode);
                    }
                    var center_x = Fire.engine.canvasSize.x/2;
                    var center_y = Fire.engine.canvasSize.y/2;
                    wrapper.scenePosition = window.sceneView.pixelToScene( Fire.v2(center_x, center_y) );
                }

                next ( null, nodeID );
            },

        ], function ( err, nodeID ) {
            if ( err ) {
                Editor.failed( 'Failed to drop asset %s, message: %s', uuid, err.stack );
                return;
            }

            if ( nodeID ) {
                Editor.Selection.select('node', nodeID, false, true );
            }
            Fire.engine.repaintInEditMode();
            done();
        });
    });
});

Ipc.on('scene:create-node-by-classid', function ( name, classID, referenceID, position ) {
    var parentNode;

    if ( referenceID ) {
        parentNode = Fire.engine.getInstanceByIdN(referenceID);
        if ( position === 'sibling' ) {
            parentNode = Fire(parentNode).parentN;
        }
    }

    if ( !parentNode ) {
        parentNode = Fire.engine.getCurrentSceneN();
    }
    var Wrapper = Fire.JS._getClassById(classID);
    if (Wrapper) {
        var wrapper = new Wrapper();
        wrapper.createAndAttachNode();
        wrapper.parent = Fire(parentNode);
        wrapper.name = name;

        var center_x = Fire.engine.canvasSize.x/2;
        var center_y = Fire.engine.canvasSize.y/2;
        wrapper.scenePosition = window.sceneView.pixelToScene( Fire.v2(center_x, center_y) );

        Fire.engine.repaintInEditMode();
        Editor.Selection.select('node', wrapper.uuid, true, true );
    }
    else {
        Editor.error('Unknown node to create:', classID);
    }
});

Ipc.on('scene:query-hierarchy', function ( queryID ) {
    var nodes = Editor.getHierarchyDump();
    var sceneUuid = Fire.engine.getCurrentScene().uuid;
    Editor.sendToWindows( 'scene:reply-query-hierarchy', queryID, sceneUuid, nodes );
});

Ipc.on('scene:query-node', function ( queryID, nodeID ) {
    var node = Fire.engine.getInstanceByIdN(nodeID);
    var dump = Editor.getNodeDump(node);
    dump = JSON.stringify(dump);    // 改成发送字符串，以免字典的顺序发生改变
    Editor.sendToWindows( 'scene:reply-query-node', queryID, dump );
});

Ipc.on('scene:query-node-info', function ( sessionID, nodeID ) {
    var nodeWrapper = Fire.engine.getInstanceById(nodeID);

    Editor.sendToWindows( 'scene:query-node-info:reply', sessionID, {
        name: nodeWrapper ? nodeWrapper.name : '',
        type: Fire.JS.getClassName(nodeWrapper),
        missed: nodeWrapper ? false : true,
    });
});

Ipc.on('scene:node-new-property', function ( info ) {
    var node = Fire.engine.getInstanceByIdN(info.id);
    if (node) {
        var objToSet = info.mixinType ? node : Fire(node);
        try {
            var id = info.type;
            var ctor;
            if (Fire.JS._isTempClassId(id)) {
                ctor = Fire.JS._getClassById(id);
            }
            else {
                ctor = Fire.JS.getClassByName(id);
            }
            if ( ctor ) {
                var obj;
                try {
                    obj = new ctor();
                }
                catch (e) {
                    Editor.error('Can not create new info.type directly.\nInner message: ' + e.stack);
                    return;
                }
                Editor.setDeepPropertyByPath(objToSet, info.path, obj, info.type);
                Fire.engine.repaintInEditMode();
            }
        }
        catch (e) {
            Editor.warn('Failed to new property %s of %s to %s, ' + e.message,
                info.path, Fire(node).name, info.value);
        }
    }
});

Ipc.on('scene:node-set-property', function ( info ) {
    var node = Fire.engine.getInstanceByIdN(info.id);
    if (node) {
        var objToSet = info.mixinType ? node : Fire(node);
        try {
            Editor.setDeepPropertyByPath(objToSet, info.path, info.value, info.type);
            Fire.engine.repaintInEditMode();
        }
        catch (e) {
            Editor.warn('Failed to set property %s of %s to %s, ' + e.message,
                info.path, Fire(node).name, info.value);
        }
    }
});

Ipc.on('scene:node-mixin', function ( id, uuid ) {
    if (uuid && Editor.isUuid(uuid)) {
        // check script
        var className = Editor.compressUuid(uuid);
        var classToMix = Fire.JS._getClassById(className);
        if (!classToMix) {
            return Editor.error('Can not find Behavior in the script "%s".', uuid);
        }
        //
        var node = Fire.engine.getInstanceByIdN(id);
        if (node) {
            Fire.mixin(node, classToMix);
        }
        else {
            Editor.error('Can not find node to mixin: %s', id);
        }
    }
    else {
        Editor.error('invalid script to mixin');
    }
});

Ipc.on('scene:node-unmixin', function ( id, className ) {
    var node = Fire.engine.getInstanceByIdN(id);
    if (node) {
        Fire.unMixin( node, className);
    }
});

Ipc.on('scene:move-nodes', function ( ids, parentID, nextSiblingId ) {
    var parent;

    if (parentID)
        parent = Fire.engine.getInstanceById(parentID);
    else
        parent = Fire.engine.getCurrentScene();

    var next = nextSiblingId ? Fire.engine.getInstanceById(nextSiblingId) : null;
    var nextIndex = next ? next.getSiblingIndex() : -1;

    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var wrapper = Fire.engine.getInstanceById(id);
        if (wrapper && (!parent || !parent.isChildOf(wrapper))) {
            if (wrapper.parent !== parent) {
                // keep world transform not changed
                var worldPos = wrapper.worldPosition;
                var worldRotation = wrapper.worldRotation;
                var lossyScale = wrapper.worldScale;

                wrapper.parent = parent;

                // restore world transform
                wrapper.worldPosition = worldPos;
                wrapper.worldRotation = worldRotation;
                if (parent) {
                    wrapper.scale = lossyScale.divSelf(parent.worldScale);
                }
                else {
                    wrapper.scale = lossyScale;
                }

                if (next) {
                    wrapper.setSiblingIndex(nextIndex);
                    ++nextIndex;
                }
            }
            else if (next) {
                var lastIndex = wrapper.getSiblingIndex();
                var newIndex = nextIndex;
                if (newIndex > lastIndex) {
                    --newIndex;
                }
                if (newIndex !== lastIndex) {
                    wrapper.setSiblingIndex(newIndex);
                    if (lastIndex > newIndex) {
                        ++nextIndex;
                    }
                    else {
                        --nextIndex;
                    }
                }
            }
            else {
                wrapper.setAsLastSibling();
            }
        }
    }
});

Ipc.on('scene:delete-nodes', function ( ids ) {
    window.sceneView.delete(ids);
});

Ipc.on('scene:duplicate-nodes', function ( ids ) {
    var wrappers = [];
    for ( var i = 0; i < ids.length; ++i ) {
         var wrapper = Fire.engine.getInstanceById(ids[i]);
        if (wrapper) {
            wrappers.push(wrapper);
        }
    }

    // get top-level wrappers
    var results = Editor.Utils.arrayCmpFilter ( wrappers, function ( a, b ) {
        if (a === b) {
            return 0;
        }

        if (b.isChildOf(a)) {
            return 1;
        }

        if (a.isChildOf(b)) {
            return -1;
        }

        return 0;
    });

    // duplicate results
    var clones = [];
    results.forEach(function ( wrapper ) {
        var clone = Fire.instantiate(wrapper);
        clone.parent = wrapper.parent;

        clones.push(clone.uuid);
    });

    // select the last one
    Editor.Selection.select('node', clones);
});

Ipc.on('scene:stash-and-reload', function () {
    Editor.stashScene(function () {
        Ipc.sendToHost('scene:ask-for-reload');
    });
});

Ipc.on('scene:soft-reload', function (compiled) {
    Editor.softReload(compiled);
});

Ipc.on('selection:activated', function ( type, id ) {
    if ( type !== 'node' || !id ) {
        return;
    }

    window.sceneView.activate(id);
});

Ipc.on('selection:deactivated', function ( type, id ) {
    if ( type !== 'node' ) {
        return;
    }

    window.sceneView.deactivate(id);
});

Ipc.on('selection:selected', function ( type, ids ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.select(ids);
});

Ipc.on('selection:unselected', function ( type, ids ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.unselect(ids);
});

Ipc.on('selection:hoverin', function ( type, id ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.hoverin(id);
});

Ipc.on('selection:hoverout', function ( type, id ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.hoverout(id);
});

Ipc.on('scene:init-scene-view', function ( settings ) {
    window.sceneView.$.gizmosView.transformTool = settings.transformTool;
    window.sceneView.$.gizmosView.coordinate = settings.coordinate;
    window.sceneView.$.gizmosView.pivot = settings.pivot;
    window.sceneView.$.gizmosView.designSize = [settings.designWidth, settings.designHeight];
});

Ipc.on('scene:transform-tool-changed', function ( value ) {
    window.sceneView.$.gizmosView.transformTool = value;
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:coordinate-changed', function ( value ) {
    window.sceneView.$.gizmosView.coordinate = value;
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:pivot-changed', function ( value ) {
    window.sceneView.$.gizmosView.pivot = value;
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:design-size-changed', function ( w, h ) {
    window.sceneView.$.gizmosView.designSize = [w, h];
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:create-prefab', function ( id, baseUrl ) {
    var wrapper = Fire.engine.getInstanceById(id);
    var prefab = Editor.createPrefabFrom(wrapper);
    var json = Editor.serialize(prefab);
    var url = Url.join(baseUrl, wrapper.name + '.prefab');

    Editor.sendRequestToCore('scene:save-prefab', url, json, function (err, uuid) {
        if (!err) {
            Editor.linkWithPrefab(wrapper, uuid);
        }
    });
});

Ipc.on('scene:apply-prefab', function ( id ) {
    var wrapper = Fire.engine.getInstanceById(id);
    if (!wrapper || !wrapper._prefab) {
        return;
    }
    var uuid = wrapper._prefab.asset._uuid;
    var prefab = Editor.createPrefabFrom(wrapper);
    var json = Editor.serialize(prefab);

    Editor.sendToCore('scene:apply-prefab', uuid, json);
});

Ipc.on('scene:revert-prefab', function ( id ) {
    Editor.log('TODO - revert');
});

<commit_msg>should not dump hierarchy when the runtime is not initialized (fireball-x/fireball#321)<commit_after>var Ipc = require('ipc');
var Async = require('async');
var Url = require('fire-url');

Ipc.on('scene:ipc-messages', function ( ipcList ) {
    for ( var i = 0; i < ipcList.length; ++i ) {
        Ipc.emit.apply( Ipc, ipcList[i] );
    }
});

Ipc.on('scene:new-scene', function () {
    window.sceneView.newScene();
});

Ipc.on('scene:save-scene-from-page', function ( url ) {
    var sceneAsset = new Fire.Scene();
    sceneAsset.scene = Fire.engine.getCurrentScene();

    // NOTE: we stash scene because we want to save and reload the connected browser
    Editor.stashScene(function () {
        // reload connected browser
        Editor.sendToCore('app:reload-on-device');

        //
        Editor.sendToCore( 'scene:save-scene', url, Editor.serialize(sceneAsset) );
    });
});

Ipc.on('scene:open-scene-by-uuid', function ( uuid ) {
    window.sceneView.loadScene(uuid);
});

Ipc.on('scene:play-on-device', function () {
    Editor.stashScene( function () {
        Editor.sendToCore( 'app:play-on-device' );
    });
});

Ipc.on('scene:reload-on-device', function () {
    Editor.stashScene( function () {
        Editor.sendToCore( 'app:reload-on-device' );
    });
});

Ipc.on('scene:drop', function ( uuids, type, x, y ) {
    Editor.Selection.clear('node');
    Async.each( uuids, function ( uuid, done ) {
        Async.waterfall([
            function ( next ) {
                Editor.createNode(uuid, next);
            },

            function ( node, next ) {
                var nodeID;
                if ( node ) {
                    var wrapper = Fire(node);
                    nodeID = wrapper.uuid;

                    wrapper.position = window.sceneView.pixelToScene( Fire.v2(x,y) );
                    wrapper.parent = Fire.engine.getCurrentScene();
                }

                next ( null, nodeID );
            },

        ], function ( err, nodeID ) {
            if ( err ) {
                Editor.failed( 'Failed to drop asset %s, message: %s', uuid, err.stack );
                return;
            }

            if ( nodeID ) {
                Editor.Selection.select('node', nodeID, false, true );
            }
            Fire.engine.repaintInEditMode();
            done();
        });
    });
});

Ipc.on('scene:create-nodes-by-uuids', function ( uuids, parentID ) {
    var parentNode;
    if ( parentID ) {
        parentNode = Fire.engine.getInstanceByIdN(parentID);
    }
    if ( !parentNode ) {
        parentNode = Fire.engine.getCurrentSceneN();
    }

    Editor.Selection.clear('node');

    //
    Async.each( uuids, function ( uuid, done ) {
        Async.waterfall([
            function ( next ) {
                Editor.createNode(uuid, next);
            },

            function ( node, next ) {
                var nodeID;
                if ( node ) {
                    var wrapper = Fire(node);
                    nodeID = wrapper.uuid;

                    if ( parentNode ) {
                        wrapper.parent = Fire(parentNode);
                    }
                    var center_x = Fire.engine.canvasSize.x/2;
                    var center_y = Fire.engine.canvasSize.y/2;
                    wrapper.scenePosition = window.sceneView.pixelToScene( Fire.v2(center_x, center_y) );
                }

                next ( null, nodeID );
            },

        ], function ( err, nodeID ) {
            if ( err ) {
                Editor.failed( 'Failed to drop asset %s, message: %s', uuid, err.stack );
                return;
            }

            if ( nodeID ) {
                Editor.Selection.select('node', nodeID, false, true );
            }
            Fire.engine.repaintInEditMode();
            done();
        });
    });
});

Ipc.on('scene:create-node-by-classid', function ( name, classID, referenceID, position ) {
    var parentNode;

    if ( referenceID ) {
        parentNode = Fire.engine.getInstanceByIdN(referenceID);
        if ( position === 'sibling' ) {
            parentNode = Fire(parentNode).parentN;
        }
    }

    if ( !parentNode ) {
        parentNode = Fire.engine.getCurrentSceneN();
    }
    var Wrapper = Fire.JS._getClassById(classID);
    if (Wrapper) {
        var wrapper = new Wrapper();
        wrapper.createAndAttachNode();
        wrapper.parent = Fire(parentNode);
        wrapper.name = name;

        var center_x = Fire.engine.canvasSize.x/2;
        var center_y = Fire.engine.canvasSize.y/2;
        wrapper.scenePosition = window.sceneView.pixelToScene( Fire.v2(center_x, center_y) );

        Fire.engine.repaintInEditMode();
        Editor.Selection.select('node', wrapper.uuid, true, true );
    }
    else {
        Editor.error('Unknown node to create:', classID);
    }
});

Ipc.on('scene:query-hierarchy', function ( queryID ) {
    if (!Fire.engine.isInitialized) {
        return Editor.sendToWindows( 'scene:reply-query-hierarchy', queryID, '', [] );
    }
    var nodes = Editor.getHierarchyDump();
    var sceneUuid = Fire.engine.getCurrentScene().uuid;
    Editor.sendToWindows( 'scene:reply-query-hierarchy', queryID, sceneUuid, nodes );
});

Ipc.on('scene:query-node', function ( queryID, nodeID ) {
    var node = Fire.engine.getInstanceByIdN(nodeID);
    var dump = Editor.getNodeDump(node);
    dump = JSON.stringify(dump);    // 改成发送字符串，以免字典的顺序发生改变
    Editor.sendToWindows( 'scene:reply-query-node', queryID, dump );
});

Ipc.on('scene:query-node-info', function ( sessionID, nodeID ) {
    var nodeWrapper = Fire.engine.getInstanceById(nodeID);

    Editor.sendToWindows( 'scene:query-node-info:reply', sessionID, {
        name: nodeWrapper ? nodeWrapper.name : '',
        type: Fire.JS.getClassName(nodeWrapper),
        missed: nodeWrapper ? false : true,
    });
});

Ipc.on('scene:node-new-property', function ( info ) {
    var node = Fire.engine.getInstanceByIdN(info.id);
    if (node) {
        var objToSet = info.mixinType ? node : Fire(node);
        try {
            var id = info.type;
            var ctor;
            if (Fire.JS._isTempClassId(id)) {
                ctor = Fire.JS._getClassById(id);
            }
            else {
                ctor = Fire.JS.getClassByName(id);
            }
            if ( ctor ) {
                var obj;
                try {
                    obj = new ctor();
                }
                catch (e) {
                    Editor.error('Can not create new info.type directly.\nInner message: ' + e.stack);
                    return;
                }
                Editor.setDeepPropertyByPath(objToSet, info.path, obj, info.type);
                Fire.engine.repaintInEditMode();
            }
        }
        catch (e) {
            Editor.warn('Failed to new property %s of %s to %s, ' + e.message,
                info.path, Fire(node).name, info.value);
        }
    }
});

Ipc.on('scene:node-set-property', function ( info ) {
    var node = Fire.engine.getInstanceByIdN(info.id);
    if (node) {
        var objToSet = info.mixinType ? node : Fire(node);
        try {
            Editor.setDeepPropertyByPath(objToSet, info.path, info.value, info.type);
            Fire.engine.repaintInEditMode();
        }
        catch (e) {
            Editor.warn('Failed to set property %s of %s to %s, ' + e.message,
                info.path, Fire(node).name, info.value);
        }
    }
});

Ipc.on('scene:node-mixin', function ( id, uuid ) {
    if (uuid && Editor.isUuid(uuid)) {
        // check script
        var className = Editor.compressUuid(uuid);
        var classToMix = Fire.JS._getClassById(className);
        if (!classToMix) {
            return Editor.error('Can not find Behavior in the script "%s".', uuid);
        }
        //
        var node = Fire.engine.getInstanceByIdN(id);
        if (node) {
            Fire.mixin(node, classToMix);
        }
        else {
            Editor.error('Can not find node to mixin: %s', id);
        }
    }
    else {
        Editor.error('invalid script to mixin');
    }
});

Ipc.on('scene:node-unmixin', function ( id, className ) {
    var node = Fire.engine.getInstanceByIdN(id);
    if (node) {
        Fire.unMixin( node, className);
    }
});

Ipc.on('scene:move-nodes', function ( ids, parentID, nextSiblingId ) {
    var parent;

    if (parentID)
        parent = Fire.engine.getInstanceById(parentID);
    else
        parent = Fire.engine.getCurrentScene();

    var next = nextSiblingId ? Fire.engine.getInstanceById(nextSiblingId) : null;
    var nextIndex = next ? next.getSiblingIndex() : -1;

    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var wrapper = Fire.engine.getInstanceById(id);
        if (wrapper && (!parent || !parent.isChildOf(wrapper))) {
            if (wrapper.parent !== parent) {
                // keep world transform not changed
                var worldPos = wrapper.worldPosition;
                var worldRotation = wrapper.worldRotation;
                var lossyScale = wrapper.worldScale;

                wrapper.parent = parent;

                // restore world transform
                wrapper.worldPosition = worldPos;
                wrapper.worldRotation = worldRotation;
                if (parent) {
                    wrapper.scale = lossyScale.divSelf(parent.worldScale);
                }
                else {
                    wrapper.scale = lossyScale;
                }

                if (next) {
                    wrapper.setSiblingIndex(nextIndex);
                    ++nextIndex;
                }
            }
            else if (next) {
                var lastIndex = wrapper.getSiblingIndex();
                var newIndex = nextIndex;
                if (newIndex > lastIndex) {
                    --newIndex;
                }
                if (newIndex !== lastIndex) {
                    wrapper.setSiblingIndex(newIndex);
                    if (lastIndex > newIndex) {
                        ++nextIndex;
                    }
                    else {
                        --nextIndex;
                    }
                }
            }
            else {
                wrapper.setAsLastSibling();
            }
        }
    }
});

Ipc.on('scene:delete-nodes', function ( ids ) {
    window.sceneView.delete(ids);
});

Ipc.on('scene:duplicate-nodes', function ( ids ) {
    var wrappers = [];
    for ( var i = 0; i < ids.length; ++i ) {
         var wrapper = Fire.engine.getInstanceById(ids[i]);
        if (wrapper) {
            wrappers.push(wrapper);
        }
    }

    // get top-level wrappers
    var results = Editor.Utils.arrayCmpFilter ( wrappers, function ( a, b ) {
        if (a === b) {
            return 0;
        }

        if (b.isChildOf(a)) {
            return 1;
        }

        if (a.isChildOf(b)) {
            return -1;
        }

        return 0;
    });

    // duplicate results
    var clones = [];
    results.forEach(function ( wrapper ) {
        var clone = Fire.instantiate(wrapper);
        clone.parent = wrapper.parent;

        clones.push(clone.uuid);
    });

    // select the last one
    Editor.Selection.select('node', clones);
});

Ipc.on('scene:stash-and-reload', function () {
    Editor.stashScene(function () {
        Ipc.sendToHost('scene:ask-for-reload');
    });
});

Ipc.on('scene:soft-reload', function (compiled) {
    Editor.softReload(compiled);
});

Ipc.on('selection:activated', function ( type, id ) {
    if ( type !== 'node' || !id ) {
        return;
    }

    window.sceneView.activate(id);
});

Ipc.on('selection:deactivated', function ( type, id ) {
    if ( type !== 'node' ) {
        return;
    }

    window.sceneView.deactivate(id);
});

Ipc.on('selection:selected', function ( type, ids ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.select(ids);
});

Ipc.on('selection:unselected', function ( type, ids ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.unselect(ids);
});

Ipc.on('selection:hoverin', function ( type, id ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.hoverin(id);
});

Ipc.on('selection:hoverout', function ( type, id ) {
    if ( type !== 'node' ) {
        return;
    }
    window.sceneView.hoverout(id);
});

Ipc.on('scene:init-scene-view', function ( settings ) {
    window.sceneView.$.gizmosView.transformTool = settings.transformTool;
    window.sceneView.$.gizmosView.coordinate = settings.coordinate;
    window.sceneView.$.gizmosView.pivot = settings.pivot;
    window.sceneView.$.gizmosView.designSize = [settings.designWidth, settings.designHeight];
});

Ipc.on('scene:transform-tool-changed', function ( value ) {
    window.sceneView.$.gizmosView.transformTool = value;
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:coordinate-changed', function ( value ) {
    window.sceneView.$.gizmosView.coordinate = value;
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:pivot-changed', function ( value ) {
    window.sceneView.$.gizmosView.pivot = value;
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:design-size-changed', function ( w, h ) {
    window.sceneView.$.gizmosView.designSize = [w, h];
    Fire.engine.repaintInEditMode();
});

Ipc.on('scene:create-prefab', function ( id, baseUrl ) {
    var wrapper = Fire.engine.getInstanceById(id);
    var prefab = Editor.createPrefabFrom(wrapper);
    var json = Editor.serialize(prefab);
    var url = Url.join(baseUrl, wrapper.name + '.prefab');

    Editor.sendRequestToCore('scene:save-prefab', url, json, function (err, uuid) {
        if (!err) {
            Editor.linkWithPrefab(wrapper, uuid);
        }
    });
});

Ipc.on('scene:apply-prefab', function ( id ) {
    var wrapper = Fire.engine.getInstanceById(id);
    if (!wrapper || !wrapper._prefab) {
        return;
    }
    var uuid = wrapper._prefab.asset._uuid;
    var prefab = Editor.createPrefabFrom(wrapper);
    var json = Editor.serialize(prefab);

    Editor.sendToCore('scene:apply-prefab', uuid, json);
});

Ipc.on('scene:revert-prefab', function ( id ) {
    Editor.log('TODO - revert');
});

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .
//= require moment
//= require bootstrap-datetimepicker
//= require select2-full
//= require zeroclipboard
<commit_msg>Fix select2 not targeting inputs on navigation<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .
//= require moment
//= require bootstrap-datetimepicker
//= require select2-full
//= require zeroclipboard

$(document).on('turbolinks:render', function() {
  $('.select2').select2();
});
<|endoftext|>


<commit_before>import keyMirror from 'keymirror';

const SET_PROJECT_ID = 'scratch-gui/project-id/SET_PROJECT_ID';
const TRANSITION_STATE = 'scratch-gui/project-id/TRANSITION_STATE';

const defaultProjectId = 0; // hardcoded id of default project

const ProjectState = keyMirror({
    NOT_LOADED: null,
    ERROR: null,
    ANY: null,
    FETCHING_WITH_ID: null,
    FETCHING_FILE_UPLOAD: null,
    FETCHING_NEW_DEFAULT: null,
    LOADING_VM_WITH_ID: null,
    LOADING_VM_FILE_UPLOAD: null,
    LOADING_VM_NEW_DEFAULT: null,
    SHOWING_WITH_ID: null,
    SHOWING_FILE_UPLOAD: null,
    SHOWING_NEW_DEFAULT: null,
    SAVING_WITH_ID: null,
    SAVING_WITH_ID_BEFORE_NEW: null
});

const initialState = {
    projectData: null,
    projectId: null,
    projectState: ProjectState.NOT_LOADED
};

const reducer = function (state, action) {
    if (typeof state === 'undefined') state = initialState;

    switch (action.type) {
    // NOTE: delete this action entirely?
    case SET_PROJECT_ID:
        return Object.assign({}, state, {projectId: action.id});
    case TRANSITION_STATE:
        // "from" state must be either an array that includes current project state,
        // or null/undefined
        if (state.projectState in action.transitions || ProjectState.ANY in action.transitions) {
//            const resultState = action.transitions[state.projectState];
            switch (action.transitions[state.projectState] ?
                action.transitions[state.projectState] : action.transitions[ProjectState.ANY]) {
            case ProjectState.FETCHING_WITH_ID:
                return Object.assign({}, state, {
                    projectId: action.id,
                    projectState: ProjectState.FETCHING_WITH_ID
                });
            case ProjectState.FETCHING_FILE_UPLOAD:
                // goes straight to LOADING_VM_FILE_UPLOAD
                return Object.assign({}, state, {
                    projectId: null,
                    projectState: ProjectState.LOADING_VM_FILE_UPLOAD
                });
            case ProjectState.FETCHING_NEW_DEFAULT:
                return Object.assign({}, state, {
                    projectId: defaultProjectId,
                    projectState: ProjectState.FETCHING_NEW_DEFAULT
                });
            case ProjectState.LOADING_VM_WITH_ID:
                return Object.assign({}, state, {
                    projectData: action.data,
                    projectState: ProjectState.LOADING_VM_WITH_ID
                });
            case ProjectState.LOADING_VM_FILE_UPLOAD:
                // goes straight to LOADING_VM_FILE_UPLOAD
                return Object.assign({}, state, {
                    projectData: action.data,
                    projectState: ProjectState.LOADING_VM_FILE_UPLOAD
                });
            case ProjectState.LOADING_VM_NEW_DEFAULT:
                return Object.assign({}, state, {
                    projectData: action.data,
                    projectState: ProjectState.LOADING_VM_NEW_DEFAULT
                });
            default:
                return Object.assign({}, state, {projectState: (action.transitions[state.projectState] ?
                    action.transitions[state.projectState] : action.transitions[ProjectState.ANY])});
            }
        }
        // default to requiring transitions to successfully match current state
        if (action.require || typeof action.require === 'undefined') {
            // NOTE: how to throw error right here?
            console.log(`Error: tried to transition from state ${state.projectState} to states...`);
            console.log(action.transitions);
        }
        break;
    default:
        return state;
    }
};

const setProjectId = function (id) {
    return {
        type: SET_PROJECT_ID,
        id: id
    };
};

// "initial" here refers to being invoked, usually embedded in another app, with a projectId property
const setInitialProjectId = id => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.NOT_LOADED]: ProjectState.FETCHING_WITH_ID
    },
    id: id
});

const setHashProjectId = id => {
    if (id === defaultProjectId || id === null || typeof id === 'undefined') {
        // it's ok if nothing matches, we may have just stripped the hash.
        // only transition based on seeing no hash if this is the initial load.
        return {
            type: TRANSITION_STATE,
            transitions: {
                // NOTE: add other states like show -> loading_new, check that they work and
                // hash reaction to new or upload doesn't cause this to fire
                [ProjectState.NOT_LOADED]: ProjectState.FETCHING_NEW_DEFAULT
            },
            require: false
        };
    }
    return {
        type: TRANSITION_STATE,
        transitions: {
            [ProjectState.ANY]: ProjectState.FETCHING_WITH_ID
        },
        id: id
    };
};

const fetchedProjectData = data => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.FETCHING_WITH_ID]: ProjectState.LOADING_VM_WITH_ID,
        [ProjectState.FETCHING_FILE_UPLOAD]: ProjectState.LOADING_VM_FILE_UPLOAD,
        [ProjectState.FETCHING_NEW_DEFAULT]: ProjectState.LOADING_VM_NEW_DEFAULT
    },
    data: data
});

const startFetchingFileUpload = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.NOT_LOADED]: ProjectState.FETCHING_FILE_UPLOAD,
        [ProjectState.SHOWING_WITH_ID]: ProjectState.FETCHING_FILE_UPLOAD,
        [ProjectState.SHOWING_FILE_UPLOAD]: ProjectState.FETCHING_FILE_UPLOAD,
        [ProjectState.SHOWING_NEW_DEFAULT]: ProjectState.FETCHING_FILE_UPLOAD
    }
});

const doneLoadingFileUpload = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.LOADING_VM_FILE_UPLOAD]: ProjectState.SHOWING_FILE_UPLOAD
    }
});

const doneLoading = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.LOADING_VM_WITH_ID]: ProjectState.SHOWING_WITH_ID,
        [ProjectState.LOADING_VM_FILE_UPLOAD]: ProjectState.SHOWING_FILE_UPLOAD,
        [ProjectState.LOADING_VM_NEW_DEFAULT]: ProjectState.SHOWING_NEW_DEFAULT
    }
});

const stepTowardsNewProject = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.SHOWING_WITH_ID]: ProjectState.SAVING_WITH_ID_BEFORE_NEW,
        [ProjectState.SHOWING_FILE_UPLOAD]: ProjectState.FETCHING_NEW_DEFAULT,
        [ProjectState.SHOWING_NEW_DEFAULT]: ProjectState.FETCHING_NEW_DEFAULT
    }
});

const doneSavingWithId = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.SAVING_WITH_ID]: ProjectState.SHOWING_WITH_ID,
        [ProjectState.SAVING_WITH_ID_BEFORE_NEW]: ProjectState.FETCHING_NEW_DEFAULT
    }
});

export {
    reducer as default,
    initialState as projectIdInitialState,
    ProjectState,
    defaultProjectId,
    fetchedProjectData,
    doneLoading,
    doneLoadingFileUpload,
    doneSavingWithId,
    setHashProjectId,
    setInitialProjectId,
    setProjectId,
    startFetchingFileUpload,
    stepTowardsNewProject
};
<commit_msg>partial solution to reloading-on-switch-to-editor problem<commit_after>import keyMirror from 'keymirror';

const SET_PROJECT_ID = 'scratch-gui/project-id/SET_PROJECT_ID';
const TRANSITION_STATE = 'scratch-gui/project-id/TRANSITION_STATE';

const defaultProjectId = 0; // hardcoded id of default project

const ProjectState = keyMirror({
    NOT_LOADED: null,
    ERROR: null,
    ANY: null,
    FETCHING_WITH_ID: null,
    FETCHING_FILE_UPLOAD: null,
    FETCHING_NEW_DEFAULT: null,
    LOADING_VM_WITH_ID: null,
    LOADING_VM_FILE_UPLOAD: null,
    LOADING_VM_NEW_DEFAULT: null,
    SHOWING_WITH_ID: null,
    SHOWING_FILE_UPLOAD: null,
    SHOWING_NEW_DEFAULT: null,
    SAVING_WITH_ID: null,
    SAVING_WITH_ID_BEFORE_NEW: null
});

const initialState = {
    projectData: null,
    projectId: null,
    projectState: ProjectState.NOT_LOADED
};

const reducer = function (state, action) {
    if (typeof state === 'undefined') state = initialState;

    switch (action.type) {
    // NOTE: delete this action entirely?
    case SET_PROJECT_ID:
        return Object.assign({}, state, {projectId: action.id});
    case TRANSITION_STATE:
        // "from" state must be either an array that includes current project state,
        // or null/undefined
        debugger;
        if (state.projectState in action.transitions || ProjectState.ANY in action.transitions) {
//            const resultState = action.transitions[state.projectState];
            switch (action.transitions[state.projectState] ?
                action.transitions[state.projectState] : action.transitions[ProjectState.ANY]) {
            case ProjectState.FETCHING_WITH_ID:
                return Object.assign({}, state, {
                    projectId: action.id,
                    projectState: ProjectState.FETCHING_WITH_ID
                });
            case ProjectState.FETCH_WITH_ID_IF_DIFFERENT:
                if (state.projectId === action.id) { // don't re-fetch and reload same data
                    return Object.assign({}, state, {
                        projectId: action.id,
                        projectState: ProjectState.SHOWING_WITH_ID
                    });
                }
                // else, it's a new project id, so do fetch it
                return Object.assign({}, state, {
                    projectId: action.id,
                    projectState: ProjectState.FETCHING_WITH_ID
                });
            case ProjectState.FETCHING_FILE_UPLOAD:
                // goes straight to LOADING_VM_FILE_UPLOAD
                return Object.assign({}, state, {
                    projectId: null,
                    projectState: ProjectState.LOADING_VM_FILE_UPLOAD
                });
            case ProjectState.FETCHING_NEW_DEFAULT:
                return Object.assign({}, state, {
                    projectId: defaultProjectId,
                    projectState: ProjectState.FETCHING_NEW_DEFAULT
                });
            case ProjectState.LOADING_VM_WITH_ID:
                return Object.assign({}, state, {
                    projectData: action.data,
                    projectState: ProjectState.LOADING_VM_WITH_ID
                });
            case ProjectState.LOADING_VM_FILE_UPLOAD:
                // goes straight to LOADING_VM_FILE_UPLOAD
                return Object.assign({}, state, {
                    projectData: action.data,
                    projectState: ProjectState.LOADING_VM_FILE_UPLOAD
                });
            case ProjectState.LOADING_VM_NEW_DEFAULT:
                return Object.assign({}, state, {
                    projectData: action.data,
                    projectState: ProjectState.LOADING_VM_NEW_DEFAULT
                });
            default:
                return Object.assign({}, state, {projectState: (action.transitions[state.projectState] ?
                    action.transitions[state.projectState] : action.transitions[ProjectState.ANY])});
            }
        }
        // default to requiring transitions to successfully match current state
        if (action.require || typeof action.require === 'undefined') {
            // NOTE: how to throw error right here?
            console.log(`Error: tried to transition from state ${state.projectState} to states...`);
            console.log(action.transitions);
        }
        break;
    default:
        return state;
    }
};

const setProjectId = function (id) {
    return {
        type: SET_PROJECT_ID,
        id: id
    };
};

// "initial" here refers to being invoked, usually embedded in another app, with a projectId property
const setInitialProjectId = id => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.NOT_LOADED]: ProjectState.FETCHING_WITH_ID,
        // if alreadin in the middle of fetching, just start fetching over
        [ProjectState.FETCHING_WITH_ID]: ProjectState.FETCHING_WITH_ID,
        [ProjectState.SHOWING_WITH_ID]: ProjectState.FETCH_WITH_ID_IF_DIFFERENT
    },
    id: id
});

const setHashProjectId = id => {
    if (id === defaultProjectId || id === null || typeof id === 'undefined') {
        // it's ok if nothing matches, we may have just stripped the hash.
        // only transition based on seeing no hash if this is the initial load.
        return {
            type: TRANSITION_STATE,
            transitions: {
                // NOTE: add other states like show -> loading_new, check that they work and
                // hash reaction to new or upload doesn't cause this to fire
                [ProjectState.NOT_LOADED]: ProjectState.FETCHING_NEW_DEFAULT
            },
            require: false
        };
    }
    return {
        type: TRANSITION_STATE,
        transitions: {
            [ProjectState.ANY]: ProjectState.FETCHING_WITH_ID
        },
        id: id
    };
};

const fetchedProjectData = data => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.FETCHING_WITH_ID]: ProjectState.LOADING_VM_WITH_ID,
        [ProjectState.FETCHING_FILE_UPLOAD]: ProjectState.LOADING_VM_FILE_UPLOAD,
        [ProjectState.FETCHING_NEW_DEFAULT]: ProjectState.LOADING_VM_NEW_DEFAULT
    },
    data: data
});

const startFetchingFileUpload = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.NOT_LOADED]: ProjectState.FETCHING_FILE_UPLOAD,
        [ProjectState.SHOWING_WITH_ID]: ProjectState.FETCHING_FILE_UPLOAD,
        [ProjectState.SHOWING_FILE_UPLOAD]: ProjectState.FETCHING_FILE_UPLOAD,
        [ProjectState.SHOWING_NEW_DEFAULT]: ProjectState.FETCHING_FILE_UPLOAD
    }
});

const doneLoadingFileUpload = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.LOADING_VM_FILE_UPLOAD]: ProjectState.SHOWING_FILE_UPLOAD
    }
});

const doneLoading = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.LOADING_VM_WITH_ID]: ProjectState.SHOWING_WITH_ID,
        [ProjectState.LOADING_VM_FILE_UPLOAD]: ProjectState.SHOWING_FILE_UPLOAD,
        [ProjectState.LOADING_VM_NEW_DEFAULT]: ProjectState.SHOWING_NEW_DEFAULT
    }
});

const stepTowardsNewProject = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.SHOWING_WITH_ID]: ProjectState.SAVING_WITH_ID_BEFORE_NEW,
        [ProjectState.SHOWING_FILE_UPLOAD]: ProjectState.FETCHING_NEW_DEFAULT,
        [ProjectState.SHOWING_NEW_DEFAULT]: ProjectState.FETCHING_NEW_DEFAULT
    }
});

const doneSavingWithId = () => ({
    type: TRANSITION_STATE,
    transitions: {
        [ProjectState.SAVING_WITH_ID]: ProjectState.SHOWING_WITH_ID,
        [ProjectState.SAVING_WITH_ID_BEFORE_NEW]: ProjectState.FETCHING_NEW_DEFAULT
    }
});

export {
    reducer as default,
    initialState as projectIdInitialState,
    ProjectState,
    defaultProjectId,
    fetchedProjectData,
    doneLoading,
    doneLoadingFileUpload,
    doneSavingWithId,
    setHashProjectId,
    setInitialProjectId,
    setProjectId,
    startFetchingFileUpload,
    stepTowardsNewProject
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name        WordPress.com classic stats
// @namespace   tpenguinltg
// @description Redirects the new stats page to the classic stats page
// @include     https://wordpress.com/stats/*
// @version     2.0.0
// @updateURL   https://github.com/tpenguinltg/wpcom-stats-redirect.user.js/raw/master/wpcom-stats-redirect.user.js
// @homepageURL https://greasyfork.org/en/scripts/8621-wordpress-com-classic-stats
// @homepageURL https://github.com/tpenguinltg/wpcom-stats-redirect.user.js
// @grant       none
// @license     MPLv2.0; http://mozilla.org/MPL/2.0/
// @copyright   2015-2016, tPenguinLTG (http://tpenguinltg.wordpress.com/)
// @run-at      document-start
// ==/UserScript==

var parsedUrl = window.location.pathname.match(/stats\/(insights|day|week|month|year)(?:\/([^\/]*))?/);
var statsType = parsedUrl[1];
var blogDomain = parsedUrl[2];

// Function by dystroy. From http://stackoverflow.com/a/14388512
function fetchJSONFile(path, callback, fallback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        if (callback) callback(JSON.parse(httpRequest.responseText));
      } else if (fallback) {
        fallback();
      }
    }
  };
  httpRequest.open('GET', path);
  httpRequest.send();
}

function redirectToClassicStats(baseUrl) {
  var query = ["page=stats"];

  switch (statsType) {
    case "day":
      query.push("unit=1");
      break;
    case "week":
      query.push("unit=7");
      break;
    case "month":
      query.push("unit=31");
      break;
  }

  window.location.replace(baseUrl + '/wp-admin/index.php?' + query.join("&"));
}

if (blogDomain) {
  // Redirect to post URL based on API results
  // API docs: https://developer.wordpress.com/docs/api/
  fetchJSONFile("https://public-api.wordpress.com/rest/v1.1/sites/" + blogDomain,
    // attempt to redirect using API
    function(data) {
      redirectToClassicStats(data.URL);
    },

    // fallback: attempt to use the blog domain
    function() {
      // use http instead of https in case the server doesn't support https
      // (e.g. for Jetpack sites)
      redirectToClassicStats('http://' + blogDomain);
    }
  );
}
<commit_msg>Correctly match URLs with no stats type<commit_after>// ==UserScript==
// @name        WordPress.com classic stats
// @namespace   tpenguinltg
// @description Redirects the new stats page to the classic stats page
// @include     https://wordpress.com/stats/*
// @version     2.0.1
// @updateURL   https://github.com/tpenguinltg/wpcom-stats-redirect.user.js/raw/master/wpcom-stats-redirect.user.js
// @homepageURL https://greasyfork.org/en/scripts/8621-wordpress-com-classic-stats
// @homepageURL https://github.com/tpenguinltg/wpcom-stats-redirect.user.js
// @grant       none
// @license     MPLv2.0; http://mozilla.org/MPL/2.0/
// @copyright   2015-2016, tPenguinLTG (http://tpenguinltg.wordpress.com/)
// @run-at      document-start
// ==/UserScript==

var parsedUrl = window.location.pathname.match(/stats(?:\/(insights|day|week|month|year))?(?:\/([^\/]*))?/);
var statsType = parsedUrl[1];
var blogDomain = parsedUrl[2];

// Function by dystroy. From http://stackoverflow.com/a/14388512
function fetchJSONFile(path, callback, fallback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        if (callback) callback(JSON.parse(httpRequest.responseText));
      } else if (fallback) {
        fallback();
      }
    }
  };
  httpRequest.open('GET', path);
  httpRequest.send();
}

function redirectToClassicStats(baseUrl) {
  var query = ["page=stats"];

  switch (statsType) {
    case "day":
      query.push("unit=1");
      break;
    case "week":
      query.push("unit=7");
      break;
    case "month":
      query.push("unit=31");
      break;
  }

  window.location.replace(baseUrl + '/wp-admin/index.php?' + query.join("&"));
}

if (blogDomain) {
  // Redirect to post URL based on API results
  // API docs: https://developer.wordpress.com/docs/api/
  fetchJSONFile("https://public-api.wordpress.com/rest/v1.1/sites/" + blogDomain,
    // attempt to redirect using API
    function(data) {
      redirectToClassicStats(data.URL);
    },

    // fallback: attempt to use the blog domain
    function() {
      // use http instead of https in case the server doesn't support https
      // (e.g. for Jetpack sites)
      redirectToClassicStats('http://' + blogDomain);
    }
  );
}
<|endoftext|>


<commit_before>
  $("#add_comparable").on "click", ->
    checked = $(".property_checkbox:checked");
    ids = []
    property_id = $(this).data("id")
    $.each checked, (index, element) -> ids.push $(element).data("property-id")
    // console.log("ids", ids)
    $.post("/properties/"+property_id+"/add_comparable", { ids: ids, property_id: property_id })
    window.location.href = "/properties/#{id}"
<commit_msg>updated java<commit_after>$("#add_comparable").on "click", ->
  checked = $(".property_checkbox:checked");
  ids = []
  property_id = $(this).data("id")
  $.each checked, (index, element) -> ids.push $(element).data("property-id")
  // console.log("ids", ids)
  $.post("/properties/"+property_id+"/add_comparable", { ids: ids, property_id: property_id })
  window.location.href = "/properties/#{id}"
<|endoftext|>


<commit_before>$(document).ready(function(){
  $('[name="email_address"]').on('blur', function(){
    var message_div = $('#mailcheck_message');
    $(this).mailcheck({
      suggested: function(element, suggestion) {
        message_div.html('Did you mean ' + suggestion['full'] + '?');
        message_div.removeClass('hidden');
      },
      empty: function() {
        message_div.addClass('hidden');
      }
    });
  });
});

<commit_msg>Offering change UX to mail check.<commit_after>$(document).ready(function(){
  $('[name="email_address"]').on('blur', function(){
    var message_div = $('#mailcheck_message');
    $(this).mailcheck({
      suggested: function(element, suggestion) {
        message_div.html('Did you mean ' + suggestion['full'] + '? - Change');
        $('#change_email').on('click', function(){
          $('[name="email_address"]').val(suggestion['full'])
          message_div.addClass('hidden');
        });
        message_div.removeClass('hidden');
      },
      empty: function() {
        message_div.addClass('hidden');
      }
    });
  });
});

<|endoftext|>