<commit_before>/**
@module ember
@submodule ember-routing
*/

require('ember-handlebars/ext');
require('ember-handlebars/helpers/view');

Ember.onLoad('Ember.Handlebars', function(Handlebars) {

  var resolveParams = Ember.Router.resolveParams,
      isSimpleClick = Ember.ViewUtils.isSimpleClick;

  var EmberHandlebars = Ember.Handlebars,
      handlebarsGet = EmberHandlebars.get,
      SafeString = EmberHandlebars.SafeString,
      forEach = Ember.ArrayPolyfills.forEach,
      get = Ember.get,
      a_slice = Array.prototype.slice;

  function args(options, actionName) {
    var ret = [];
    if (actionName) { ret.push(actionName); }

    var types = options.options.types.slice(1),
        data = options.options.data;

    return ret.concat(resolveParams(options.context, options.params, { types: types, data: data }));
  }

  var ActionHelper = EmberHandlebars.ActionHelper = {
    registeredActions: {}
  };

  var keys = ["alt", "shift", "meta", "ctrl"];

  var isAllowedClick = function(event, allowedKeys) {
    if (typeof allowedKeys === "undefined") {
      return isSimpleClick(event);
    }

    var allowed = true;

    forEach.call(keys, function(key) {
      if (event[key + "Key"] && allowedKeys.indexOf(key) === -1) {
        allowed = false;
      }
    });

    return allowed;
  };

  ActionHelper.registerAction = function(actionName, options, allowedKeys) {
    var actionId = (++Ember.uuid).toString();

    ActionHelper.registeredActions[actionId] = {
      eventName: options.eventName,
      handler: function(event) {
        if (!isAllowedClick(event, allowedKeys)) { return true; }

        event.preventDefault();

        if (options.bubbles === false) {
          event.stopPropagation();
        }

        var target = options.target;

        if (target.target) {
          target = handlebarsGet(target.root, target.target, target.options);
        } else {
          target = target.root;
        }

        Ember.run(function() {
          if (target.send) {
            target.send.apply(target, args(options.parameters, actionName));
          } else {
            Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function');
            target[actionName].apply(target, args(options.parameters));
          }
        });
      }
    };

    options.view.on('willClearRender', function() {
      delete ActionHelper.registeredActions[actionId];
    });

    return actionId;
  };

  /**
    The `{{action}}` helper registers an HTML element within a template for DOM
    event handling and forwards that interaction to the view's controller
    or supplied `target` option (see 'Specifying a Target').

    If the view's controller does not implement the event, the event is sent
    to the current route, and it bubbles up the route hierarchy from there.

    User interaction with that element will invoke the supplied action name on
    the appropriate target.

    Given the following Handlebars template on the page

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action anActionName}}>
        click me
      </div>
    </script>
    ```

    And application code

    ```javascript
    AController = Ember.Controller.extend({
      anActionName: function() {}
    });

    AView = Ember.View.extend({
      controller: AController.create(),
      templateName: 'a-template'
    });

    aView = AView.create();
    aView.appendTo('body');
    ```

    Will result in the following rendered HTML

    ```html
    <div class="ember-view">
      <div data-ember-action="1">
        click me
      </div>
    </div>
    ```

    Clicking "click me" will trigger the `anActionName` method of the
    `AController`. In this case, no additional parameters will be passed.

    If you provide additional parameters to the helper:

    ```handlebars
    <button {{action 'edit' post}}>Edit</button>
    ```

    Those parameters will be passed along as arguments to the JavaScript
    function implementing the action.

    ### Event Propagation

    Events triggered through the action helper will automatically have
    `.preventDefault()` called on them. You do not need to do so in your event
    handlers.

    To also disable bubbling, pass `bubbles=false` to the helper:

    ```handlebars
    <button {{action 'edit' post bubbles=false}}>Edit</button>
    ```

    If you need the default handler to trigger you should either register your
    own event handler, or use event methods on your view class. See `Ember.View`
    'Responding to Browser Events' for more information.

    ### Specifying DOM event type

    By default the `{{action}}` helper registers for DOM `click` events. You can
    supply an `on` option to the helper to specify a different DOM event name:

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action anActionName on="doubleClick"}}>
        click me
      </div>
    </script>
    ```

    See `Ember.View` 'Responding to Browser Events' for a list of
    acceptable DOM event names.

    NOTE: Because `{{action}}` depends on Ember's event dispatch system it will
    only function if an `Ember.EventDispatcher` instance is available. An
    `Ember.EventDispatcher` instance will be created when a new `Ember.Application`
    is created. Having an instance of `Ember.Application` will satisfy this
    requirement.

    ### Specifying whitelisted modifier keys

    By default the `{{action}}` helper will ignore click event with pressed modifier
    keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action anActionName allowedKeys="alt"}}>
        click me
      </div>
    </script>
    ```

    This way the `{{action}}` will fire when clicking with the alt key pressed down.

    ### Specifying a Target

    There are several possible target objects for `{{action}}` helpers:

    In a typical Ember application, where views are managed through use of the
    `{{outlet}}` helper, actions will bubble to the current controller, then
    to the current route, and then up the route hierarchy.

    Alternatively, a `target` option can be provided to the helper to change
    which object will receive the method call. This option must be a path
    to an object, accessible in the current context:

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action anActionName target="MyApplication.someObject"}}>
        click me
      </div>
    </script>
    ```

    Clicking "click me" in the rendered HTML of the above template will trigger
    the  `anActionName` method of the object at `MyApplication.someObject`.

    If an action's target does not implement a method that matches the supplied
    action name an error will be thrown.

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action aMethodNameThatIsMissing}}>
        click me
      </div>
    </script>
    ```

    With the following application code

    ```javascript
    AView = Ember.View.extend({
      templateName; 'a-template',
      // note: no method 'aMethodNameThatIsMissing'
      anActionName: function(event) {}
    });

    aView = AView.create();
    aView.appendTo('body');
    ```

    Will throw `Uncaught TypeError: Cannot call method 'call' of undefined` when
    "click me" is clicked.

    ### Additional Parameters

    You may specify additional parameters to the `{{action}}` helper. These
    parameters are passed along as the arguments to the JavaScript function
    implementing the action.

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      {{#each person in people}}
        <div {{action edit person}}>
          click me
        </div>
      {{/each}}
    </script>
    ```

    Clicking "click me" will trigger the `edit` method on the current view's
    controller with the current person as a parameter.

    @method action
    @for Ember.Handlebars.helpers
    @param {String} actionName
    @param {Object} [context]*
    @param {Hash} options
  */
  EmberHandlebars.registerHelper('action', function(actionName) {
    var options = arguments[arguments.length - 1],
        contexts = a_slice.call(arguments, 1, -1);

    var hash = options.hash,
        controller;

    // create a hash to pass along to registerAction
    var action = {
      eventName: hash.on || "click"
    };

    action.parameters = {
      context: this,
      options: options,
      params: contexts
    };

    action.view = options.data.view;

    var root, target;

    if (hash.target) {
      root = this;
      target = hash.target;
    } else if (controller = options.data.keywords.controller) {
      root = controller;
    }

    action.target = { root: root, target: target, options: options };
    action.bubbles = hash.bubbles;

    var actionId = ActionHelper.registerAction(actionName, action, hash.allowedKeys);
    return new SafeString('data-ember-action="' + actionId + '"');
  });

});
<commit_msg>Wrap action names in quotes in the action helper documentation.<commit_after>/**
@module ember
@submodule ember-routing
*/

require('ember-handlebars/ext');
require('ember-handlebars/helpers/view');

Ember.onLoad('Ember.Handlebars', function(Handlebars) {

  var resolveParams = Ember.Router.resolveParams,
      isSimpleClick = Ember.ViewUtils.isSimpleClick;

  var EmberHandlebars = Ember.Handlebars,
      handlebarsGet = EmberHandlebars.get,
      SafeString = EmberHandlebars.SafeString,
      forEach = Ember.ArrayPolyfills.forEach,
      get = Ember.get,
      a_slice = Array.prototype.slice;

  function args(options, actionName) {
    var ret = [];
    if (actionName) { ret.push(actionName); }

    var types = options.options.types.slice(1),
        data = options.options.data;

    return ret.concat(resolveParams(options.context, options.params, { types: types, data: data }));
  }

  var ActionHelper = EmberHandlebars.ActionHelper = {
    registeredActions: {}
  };

  var keys = ["alt", "shift", "meta", "ctrl"];

  var isAllowedClick = function(event, allowedKeys) {
    if (typeof allowedKeys === "undefined") {
      return isSimpleClick(event);
    }

    var allowed = true;

    forEach.call(keys, function(key) {
      if (event[key + "Key"] && allowedKeys.indexOf(key) === -1) {
        allowed = false;
      }
    });

    return allowed;
  };

  ActionHelper.registerAction = function(actionName, options, allowedKeys) {
    var actionId = (++Ember.uuid).toString();

    ActionHelper.registeredActions[actionId] = {
      eventName: options.eventName,
      handler: function(event) {
        if (!isAllowedClick(event, allowedKeys)) { return true; }

        event.preventDefault();

        if (options.bubbles === false) {
          event.stopPropagation();
        }

        var target = options.target;

        if (target.target) {
          target = handlebarsGet(target.root, target.target, target.options);
        } else {
          target = target.root;
        }

        Ember.run(function() {
          if (target.send) {
            target.send.apply(target, args(options.parameters, actionName));
          } else {
            Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function');
            target[actionName].apply(target, args(options.parameters));
          }
        });
      }
    };

    options.view.on('willClearRender', function() {
      delete ActionHelper.registeredActions[actionId];
    });

    return actionId;
  };

  /**
    The `{{action}}` helper registers an HTML element within a template for DOM
    event handling and forwards that interaction to the view's controller
    or supplied `target` option (see 'Specifying a Target').

    If the view's controller does not implement the event, the event is sent
    to the current route, and it bubbles up the route hierarchy from there.

    User interaction with that element will invoke the supplied action name on
    the appropriate target.

    Given the following Handlebars template on the page

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action 'anActionName'}}>
        click me
      </div>
    </script>
    ```

    And application code

    ```javascript
    AController = Ember.Controller.extend({
      anActionName: function() {}
    });

    AView = Ember.View.extend({
      controller: AController.create(),
      templateName: 'a-template'
    });

    aView = AView.create();
    aView.appendTo('body');
    ```

    Will result in the following rendered HTML

    ```html
    <div class="ember-view">
      <div data-ember-action="1">
        click me
      </div>
    </div>
    ```

    Clicking "click me" will trigger the `anActionName` method of the
    `AController`. In this case, no additional parameters will be passed.

    If you provide additional parameters to the helper:

    ```handlebars
    <button {{action 'edit' post}}>Edit</button>
    ```

    Those parameters will be passed along as arguments to the JavaScript
    function implementing the action.

    ### Event Propagation

    Events triggered through the action helper will automatically have
    `.preventDefault()` called on them. You do not need to do so in your event
    handlers.

    To also disable bubbling, pass `bubbles=false` to the helper:

    ```handlebars
    <button {{action 'edit' post bubbles=false}}>Edit</button>
    ```

    If you need the default handler to trigger you should either register your
    own event handler, or use event methods on your view class. See `Ember.View`
    'Responding to Browser Events' for more information.

    ### Specifying DOM event type

    By default the `{{action}}` helper registers for DOM `click` events. You can
    supply an `on` option to the helper to specify a different DOM event name:

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action 'anActionName' on="doubleClick"}}>
        click me
      </div>
    </script>
    ```

    See `Ember.View` 'Responding to Browser Events' for a list of
    acceptable DOM event names.

    NOTE: Because `{{action}}` depends on Ember's event dispatch system it will
    only function if an `Ember.EventDispatcher` instance is available. An
    `Ember.EventDispatcher` instance will be created when a new `Ember.Application`
    is created. Having an instance of `Ember.Application` will satisfy this
    requirement.

    ### Specifying whitelisted modifier keys

    By default the `{{action}}` helper will ignore click event with pressed modifier
    keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action 'anActionName' allowedKeys="alt"}}>
        click me
      </div>
    </script>
    ```

    This way the `{{action}}` will fire when clicking with the alt key pressed down.

    ### Specifying a Target

    There are several possible target objects for `{{action}}` helpers:

    In a typical Ember application, where views are managed through use of the
    `{{outlet}}` helper, actions will bubble to the current controller, then
    to the current route, and then up the route hierarchy.

    Alternatively, a `target` option can be provided to the helper to change
    which object will receive the method call. This option must be a path
    to an object, accessible in the current context:

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action 'anActionName' target="MyApplication.someObject"}}>
        click me
      </div>
    </script>
    ```

    Clicking "click me" in the rendered HTML of the above template will trigger
    the  `anActionName` method of the object at `MyApplication.someObject`.

    If an action's target does not implement a method that matches the supplied
    action name an error will be thrown.

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      <div {{action 'aMethodNameThatIsMissing'}}>
        click me
      </div>
    </script>
    ```

    With the following application code

    ```javascript
    AView = Ember.View.extend({
      templateName; 'a-template',
      // note: no method 'aMethodNameThatIsMissing'
      anActionName: function(event) {}
    });

    aView = AView.create();
    aView.appendTo('body');
    ```

    Will throw `Uncaught TypeError: Cannot call method 'call' of undefined` when
    "click me" is clicked.

    ### Additional Parameters

    You may specify additional parameters to the `{{action}}` helper. These
    parameters are passed along as the arguments to the JavaScript function
    implementing the action.

    ```handlebars
    <script type="text/x-handlebars" data-template-name='a-template'>
      {{#each person in people}}
        <div {{action 'edit' person}}>
          click me
        </div>
      {{/each}}
    </script>
    ```

    Clicking "click me" will trigger the `edit` method on the current view's
    controller with the current person as a parameter.

    @method action
    @for Ember.Handlebars.helpers
    @param {String} actionName
    @param {Object} [context]*
    @param {Hash} options
  */
  EmberHandlebars.registerHelper('action', function(actionName) {
    var options = arguments[arguments.length - 1],
        contexts = a_slice.call(arguments, 1, -1);

    var hash = options.hash,
        controller;

    // create a hash to pass along to registerAction
    var action = {
      eventName: hash.on || "click"
    };

    action.parameters = {
      context: this,
      options: options,
      params: contexts
    };

    action.view = options.data.view;

    var root, target;

    if (hash.target) {
      root = this;
      target = hash.target;
    } else if (controller = options.data.keywords.controller) {
      root = controller;
    }

    action.target = { root: root, target: target, options: options };
    action.bubbles = hash.bubbles;

    var actionId = ActionHelper.registerAction(actionName, action, hash.allowedKeys);
    return new SafeString('data-ember-action="' + actionId + '"');
  });

});
<|endoftext|>


<commit_before><commit_msg>Consistently have notify=true when taking snashots in snapshot test<commit_after><|endoftext|>


<commit_before>define([
           'dojo/_base/declare',
           'JBrowse/View/Track/Alignments',
           'WebApollo/View/Track/DraggableHTMLFeatures'
       ],
       function(
           declare,
           AlignmentsTrack,
           DraggableTrack
       ) {

return declare([ DraggableTrack, AlignmentsTrack ], {} );

});<commit_msg>Added DraggableAlignments._defaultConfig() to set various defaults.<commit_after>define([
           'dojo/_base/declare',
           'JBrowse/View/Track/Alignments',
           'WebApollo/View/Track/DraggableHTMLFeatures',
           'JBrowse/Util',
       ],
       function(
           declare,
           AlignmentsTrack,
           DraggableTrack,
           Util
       ) {

return declare([ DraggableTrack, AlignmentsTrack ], {
    _defaultConfig: function()  {
        var thisConfig = Util.deepUpdate(
//       return Util.deepUpdate(
            dojo.clone( this.inherited(arguments) ),
            {
                layoutPitchY: 2,
                subfeatures: true,
                style: {
                    className: "bam",
                    renderClassName: null,
                    arrowheadClass: "arrowhead",
	            centerChildrenVertically: false,
	            showSubfeatures: true,
	            showMismatches: false,
                    subfeatureClasses: {
	                M: "cigarM",
		        D: "cigarD",
		        N: "cigarN",
		        E: "cigarEQ",  /* "=" converted to "E" in BAM/LazyFeature subfeature construction */
		        X: "cigarX",
		        I: "cigarI"
                    }
                }
            }
        );
        return thisConfig;
    }

} );

});<|endoftext|>


<commit_before>var HTMLCS_RUNNER = new function() {

	this.run = function(standard, screenshot_url, errLevel) {

		HTMLCS.process(standard, document, function() {
			var msgs = HTMLCS.getMessages();
			var content = [];
			var heading = "";
			var type = '';
			var outerHTML = '';

			try {
				var principles = {
						'Principle1': 'Perceivable',
						'Principle2': 'Operable',
						'Principle3': 'Understandable',
						'Principle4': 'Robust'
					};

				if (msgs.length === 0) {
					content.push({'message':'No violations found'});
					return;
				}

				var errors   = 0;
				var warnings = 0;
				var notices  = 0;
				var count=1;

				for (var i = 0; i < msgs.length; i++) {
					var msg = msgs[i];

					if(errLevel.indexOf(msg.type) !=-1 ) {

						var temp_obj = {};

						switch (msg.type) {
							case HTMLCS.ERROR:
							type = 'Error';
							errors += 1;
							break;
							case HTMLCS.WARNING:
								type = 'Warning';
								warnings++;
							break;

							case HTMLCS.NOTICE:
								type = 'Notice';
								notices++;
							break;

							default:
								type = 'Unknown:' + msg.type +' ';
							break;

							 }

						 	if (msg.element.innerHTML && msg.element.innerHTML.length > 50) {
								var outerHTML = msg.element.outerHTML.replace(msg.element.innerHTML, msg.element.innerHTML.substr(0, 50) + '...');
							} else {
								var outerHTML = msg.element.outerHTML;
							}
							// Get the success criterion so we can provide a link.
							var msgParts   = msg.code.split('.');
							var principle  = msgParts[1];
							var sc         = msgParts[3].split('_').slice(0, 3).join('_');
							var techniques = msgParts[4];
							techniques     = techniques.split(',');

							msgParts.shift();
							msgParts.unshift('[Standard]');
							var noStdMsgParts = msgParts.join('.');

							temp_obj["type"] = type.toLowerCase();
							temp_obj["msg"] = msg.msg;
							temp_obj["code"] = splitLine(outerHTML.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'), 30);
							temp_obj["principle"] = '' + principles[principle] + '';
							var technique='';
							for (var j = 0; j < techniques.length; j++) {
								technique += '' + techniques[j] + '';

							}
							temp_obj["techniques"] = technique;
							count++;
							content.push(temp_obj);

					} //if Closing
				} //Closing for loop

				if (errors === 0) {
					content.push({'message':'----  No Errors ---'});
					return;
				}

				var address = document.location.href;

				if(address.indexOf("file:") === -1){
					heading += '
' + address +'
';
					heading += '
Screenshot:   ' + screenshot_url + '
';
				}

				content.push( {'errorcount':errors} );

			} catch (e) {
				console.log('Error:', e.toString());
			}
			console.log(JSON.stringify(content));
			console.log('done');
		});
	};
};

//Break the code snippet into multiple lines.
function splitLine(st,n) {
		var b = '';
		var s = st;while (s.length > n) {
			var c = s.substring(0,n);
			var d = c.lastIndexOf(' ');
			var e =c.lastIndexOf('\n');
		if (e != -1)
		d = e;
		if (d == -1)
		d = n;
		b += c.substring(0,d) + '\n';
		s = s.substring(d+1);
		}
		return b+s;
}
<commit_msg>Output JSON when no errors found<commit_after>var HTMLCS_RUNNER = new function() {

	this.run = function(standard, screenshot_url, errLevel) {

		HTMLCS.process(standard, document, function() {
			var msgs = HTMLCS.getMessages();
			var content = [];
			var heading = "";
			var type = '';
			var outerHTML = '';

			try {
				var principles = {
						'Principle1': 'Perceivable',
						'Principle2': 'Operable',
						'Principle3': 'Understandable',
						'Principle4': 'Robust'
					};

				if (msgs.length === 0) {
					content.push({'message':'No violations found'});
					console.log(JSON.stringify(content));
					console.log('done');
					return;
				}

				var errors   = 0;
				var warnings = 0;
				var notices  = 0;
				var count=1;

				for (var i = 0; i < msgs.length; i++) {
					var msg = msgs[i];

					if(errLevel.indexOf(msg.type) !=-1 ) {

						var temp_obj = {};

						switch (msg.type) {
							case HTMLCS.ERROR:
							type = 'Error';
							errors += 1;
							break;
							case HTMLCS.WARNING:
								type = 'Warning';
								warnings++;
							break;

							case HTMLCS.NOTICE:
								type = 'Notice';
								notices++;
							break;

							default:
								type = 'Unknown:' + msg.type +' ';
							break;

							 }

						 	if (msg.element.innerHTML && msg.element.innerHTML.length > 50) {
								var outerHTML = msg.element.outerHTML.replace(msg.element.innerHTML, msg.element.innerHTML.substr(0, 50) + '...');
							} else {
								var outerHTML = msg.element.outerHTML;
							}
							// Get the success criterion so we can provide a link.
							var msgParts   = msg.code.split('.');
							var principle  = msgParts[1];
							var sc         = msgParts[3].split('_').slice(0, 3).join('_');
							var techniques = msgParts[4];
							techniques     = techniques.split(',');

							msgParts.shift();
							msgParts.unshift('[Standard]');
							var noStdMsgParts = msgParts.join('.');

							temp_obj["type"] = type.toLowerCase();
							temp_obj["msg"] = msg.msg;
							temp_obj["code"] = splitLine(outerHTML.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'), 30);
							temp_obj["principle"] = '' + principles[principle] + '';
							var technique='';
							for (var j = 0; j < techniques.length; j++) {
								technique += '' + techniques[j] + '';

							}
							temp_obj["techniques"] = technique;
							count++;
							content.push(temp_obj);

					} //if Closing
				} //Closing for loop

				if (errors === 0) {
					content.push({'message':'----  No Errors ---'});
					console.log(JSON.stringify(content));
					console.log('done');
					return;
				}

				var address = document.location.href;

				if(address.indexOf("file:") === -1){
					heading += '
' + address +'
';
					heading += '
Screenshot:   ' + screenshot_url + '
';
				}

				content.push( {'errorcount':errors} );

			} catch (e) {
				console.log('Error:', e.toString());
			}
			console.log(JSON.stringify(content));
			console.log('done');
		});
	};
};

//Break the code snippet into multiple lines.
function splitLine(st,n) {
		var b = '';
		var s = st;while (s.length > n) {
			var c = s.substring(0,n);
			var d = c.lastIndexOf(' ');
			var e =c.lastIndexOf('\n');
		if (e != -1)
		d = e;
		if (d == -1)
		d = n;
		b += c.substring(0,d) + '\n';
		s = s.substring(d+1);
		}
		return b+s;
}
<|endoftext|>


<commit_before>require('ember-routing/route_matcher');
require('ember-routing/routable');
require('ember-application/system/location');

var get = Ember.get, getPath = Ember.getPath, set = Ember.set;

/**
  @class

  `Ember.Router` is the subclass of `Ember.StateManager` responsible for providing URL-based
  application state detection. The `Ember.Router` instance of an application detects the browser URL
  at application load time and attempts to match it to a specific application state. Additionally
  the router will update the URL to reflect an application's state changes over time.

  ## Adding a Router Instance to Your Application
  An instance of Ember.Router can be associated with an instance of Ember.Application in one of two ways:

  You can provide a subclass of Ember.Router as the `Router` property of your application. An instance
  of this Router class will be instantiated and route detection will be enabled when the application's
  `initialize` method is called. The Router instance will be available as the `router` property
  of the application:

      App = Ember.Application.create({
        Router: Ember.Router.extend({ ... })
      });

      App.initialize();
      App.get('router') // an instance of App.Router

  If you want to define a Router instance elsewhere, you can pass the instance to the application's
  `initialize` method:

      App = Ember.Application.create();
      aRouter = Ember.Router.create({ ... });

      App.initialize(aRouter);
      App.get('router') // aRouter

  ## Adding Routes to a Router
  The `initialState` property of Ember.Router instances is named `root`. The state stored in this
  property should be a subclass of Ember.Route. The `root` route should itself have states that are
  also subclasses of Ember.Route and have `route` properties describing the URL pattern you would
  like to detect.

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            index: Ember.Route.extend({
              route: '/'
            }),
            ... additional Ember.Routes ...
          })
        })
      });
      App.initialize();

  When an application loads, Ember will parse the URL and attempt to find an Ember.Route within
  the application's states that matches. (The example URL-matching below will use the default
  'hash syntax' provided by `Ember.HashLocation`.)

  In the following route structure:

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/'
            }),
            bRoute: Ember.Route.extend({
              route: '/alphabeta'
            })
          })
        })
      });
      App.initialize();

  Loading the page at the URL '#/' will detect the route property of 'root.aRoute' ('/') and
  transition the router first to the state named 'root' and then to the substate 'aRoute'.

  Respectively, loading the page at the URL '#/alphabeta' would detect the route property of
  'root.bRoute' ('/alphabeta') and transition the router first to the state named 'root' and
  then to the substate 'bRoute'.

  ## Route Transition Events
  Transitioning between Ember.Route instances (including the transition into the detected
  route when loading the application)  triggers the same transition events as state transitions for
  base `Ember.State`s. However, the default `setup` transition event is named `connectOutlets` on
  Ember.Router instances (see 'Changing View Hierarchy in Response To State Change').

  The following route structure when loaded with the URL "#/"

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/'
              enter: function(router){
                console.log("entering root.aRoute from", router.getPath('currentState.name'));
              },
              connectOutlets: function(router){
                console.log("entered root.aRoute, fully transitioned to", router.getPath('currentState.path'));
              }
            })
          })
        })
      });
      App.initialize();

  Will result in console output of:

      'entering root.aRoute from root'
      'entered root.aRoute, fully transitioned to root.aRoute '

  ## Routes With Dynamic Segments
  An Ember.Route's `route` property can reference dynamic sections of the URL by prefacing a URL segment
  with the ':' character.  The values of these dynamic segments will be passed as a hash to the
  `connectOutlets` method of the matching Route. The following route structure when loaded with the URL
  "#/fixed/thefirstvalue/anotherFixed/thesecondvalue":

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/fixed/:dynamicSectionA/anotherFixed/:dynamicSectionB'
              connectOutlets: function(router, context){}
            })
          })
        })
      });
      App.initialize();

  Will call the 'connectOutlets' method of the Route instance at the path 'root.aRoute' with the
  following hash as its second argument:

      {
        dynamicSectionA: 'thefirstvalue',
        dynamicSectionB: 'thesecondvalue'
      }

  ## Transitions Between States
  Once a routed application has initialized its state based on the entry URL subsequent transitions to other
  states will update the URL if the entered State has a `route` property. Given the following state structure
  loaded at the URL '#/':

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              moveElsewhere: Ember.Route.transitionTo('bRoute')
            }),
            bRoute: Ember.Route.extend({
              route: '/someOtherLocation'
            })
          })
        })
      });
      App.initialize();

  And application code:

      App.get('router').send('moveElsewhere');

  Will transition the application's state to 'root.bRoute' and trigger an update of the URL to
  '#/someOtherLocation

  For URL patterns with dynamic segments a context can be supplied as the second argument to `send`.
  The router will match dynamic segments names to keys on this object and fill in the URL with the
  supplied values. Given the following state structure loaded at the URL '#/':

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              moveElsewhere: Ember.Route.transitionTo('bRoute')
            }),
            bRoute: Ember.Route.extend({
              route: '/a/route/:dynamicSection/:anotherDynamicSection'
              connectOutlets: function(router, context){},
            })
          })
        })
      });
      App.initialize();

  And application code:

      App.get('router').send('moveElsewhere', {
        dynamicSection: '42',
        anotherDynamicSection: 'Life'
      });

  Will transition the application's state to 'root.bRoute' and trigger an update of the URL to
  '#/a/route/42/Life'.

  The context argument will also be passed as the second argument to the `connectOutlets` method call.

  ## Detecting Routing/Non-Routing Calls to `connectOutlets`
  Because `connectOutlets` will be called both for the initial route detection and on subsequent application
  state changes that affect the browser URL the router can differentiate between these two conditions with
  its `isRouting` property. During the application's initial loading, `isRouting` will be `true`, during state
  transitions after the application has loaded `isRouting` will be false. If you need to take special action
  for either condition (e.g. loading remote data), check this property:

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              connectOutlets: function(router, context){
                if (router.get('isRouting')) {
                  // intitial app loading, get data from server
                };
              },
            })
          })
        })
      });
      App.initialize();

  ## Injection of Controller Singletons
  During application initialization Ember will detect properties of the application ending in 'Controller',
  create singleton instances of each class, and assign them as a properties on the router.  The property name
  will be the UpperCamel name converted to lowerCamel format. These controller classes should be subclasses
  of Ember.ObjectController, Ember.ArrayController, or a custom Ember.Object that includes the
  Ember.ControllerMixin mixin.

      App = Ember.Application.create({
        FooController: Ember.Object.create(Ember.ControllerMixin),
        Router: Ember.Router.extend({ ... })
      });

      App.getPath('router.fooController'); // instance of App.FooController

  The controller singletons will have their `namespace` property set to the application and their `target`
  property set to the application's router singleton for easy integration with Ember's user event system.
  See 'Changing View Hierarchy in Response To State Change' and 'Responding to User-initiated Events'

  ## Responding to User-initiated Events
  Controller instances injected into the router at application initialization have their `target` property
  set to the application's router instance. These controllers will also be the default `context` for their
  associated views.  Uses of the `{{action}}` helper will automatically target the application's router.

  Given the following application entered at the URL '#/':

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              anActionOnTheRouter: function(router, context){
                router.transitionTo('anotherState', context);
              }
            })
            anotherState: Ember.Route.extend({
              route: '/differentUrl',
              connectOutlets: function(router, context){

              }
            })
          })
        })
      });
      App.initialize();

  The following template:

  Will delegate `click` events on the rendered `h1` to the application's router instance. In this case the
  `anActionOnTheRouter` method of the state at 'root.aRoute' will be called with the view's controller
  as the context argument. This context will be passed to the `connectOutlets` as its second argument.

  Different `context` can be supplied from within the `{{action}}` helper, allowing specific context passing
  between application states:

  See Handlebars.helpers.actions for additional usage examples.

  ## Changing View Hierarchy in Response To State Change
  Changes in application state that change the URL should be accompanied by associated changes in view
  hierarchy.  This can be accomplished by calling 'connectOutlet' on the injected controller singletons from
  within the 'connectOutlets' event of an Ember.Route:

      App = Ember.Application.create({
        OneController: Ember.ObjectController.extend(),
        OneView: Ember.View.extend(),

        AnotherController: Ember.ObjectController.extend(),
        AnotherView: Ember.View.extend(),

        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              connectOutlets: function(router, context){
                router.get('oneController').connectOutlet('another');
              },
            })
          })
        })
      });
      App.initialize();

  This will detect the '{{outlet}}' portion of `oneController`'s view (an instance of `App.OneView`) and
  fill it with a rendered instance of `App.AnotherView` whose `context` will be the single instance of
  `App.AnotherController` stored on the router in the `anotherController` property.

  For more information about Outlets see Ember.Handlebars.helpers.outlet. For more information about controller
  injections see Ember.Application#initialize(). For additional information about view context see Ember.View.

  @extends Ember.StateManager
*/
Ember.Router = Ember.StateManager.extend(
/** @scope Ember.Router.prototype */ {

  /**
    @property {String}
    @default 'root'
  */
  initialState: 'root',

  /**
    The `Ember.Location` implementation to be used to manage the application
    URL state. The following values are supported:

    * 'hash': Uses URL fragment identifiers (like #/blog/1) for routing.
    * 'none': Does not read or set the browser URL, but still allows for
      routing to happen. Useful for testing.

    @type String
    @default 'hash'
  */
  location: 'hash',

  /**
    On router, transitionEvent should be called connectOutlets

    @property {String}
    @default 'connectOutlets'
  */
  transitionEvent: 'connectOutlets',

  route: function(path) {
    set(this, 'isRouting', true);

    try {
      path = path.replace(/^(?=[^\/])/, "/");

      this.send('unroutePath', path);

      var currentURL = get(this, 'currentState').absoluteRoute(this);
      var rest = path.substr(currentURL.length);

      this.send('routePath', rest);
    } finally {
      set(this, 'isRouting', false);
    }

    get(this, 'currentState').updateRoute(this, get(this, 'location'));
  },

  urlFor: function(path, hash) {
    var currentState = get(this, 'currentState') || this,
        state = this.findStateByPath(currentState, path);

    Ember.assert("To get a URL for a state, it must have a `route` property.", !!get(state, 'routeMatcher'));

    var location = get(this, 'location'),
        absoluteRoute = state.absoluteRoute(this, hash);

    return location.formatURL(absoluteRoute);
  },

  urlForEvent: function(eventName, context) {
    var currentState = get(this, 'currentState');
    var targetStateName = currentState.lookupEventTransition(eventName);

    Ember.assert(Ember.String.fmt("You must specify a target state for event '%@' in order to link to it in the current state '%@'.", [eventName, get(currentState, 'path')]), !!targetStateName);

    var targetState = this.findStateByPath(currentState, targetStateName);

    Ember.assert("Your target state name " + targetStateName + " for event " + eventName + " did not resolve to a state", !!targetState);
    var hash = targetState.serialize(this, context);

    return this.urlFor(targetStateName, hash);
  },

  /** @private */
  init: function() {
    this._super();

    var location = get(this, 'location');
    if ('string' === typeof location) {
      set(this, 'location', Ember.Location.create({ implementation: location }));
    }
  },

  /** @private */
  willDestroy: function() {
    get(this, 'location').destroy();
  }
});
<commit_msg>commas, how do they even work.<commit_after>require('ember-routing/route_matcher');
require('ember-routing/routable');
require('ember-application/system/location');

var get = Ember.get, getPath = Ember.getPath, set = Ember.set;

/**
  @class

  `Ember.Router` is the subclass of `Ember.StateManager` responsible for providing URL-based
  application state detection. The `Ember.Router` instance of an application detects the browser URL
  at application load time and attempts to match it to a specific application state. Additionally
  the router will update the URL to reflect an application's state changes over time.

  ## Adding a Router Instance to Your Application
  An instance of Ember.Router can be associated with an instance of Ember.Application in one of two ways:

  You can provide a subclass of Ember.Router as the `Router` property of your application. An instance
  of this Router class will be instantiated and route detection will be enabled when the application's
  `initialize` method is called. The Router instance will be available as the `router` property
  of the application:

      App = Ember.Application.create({
        Router: Ember.Router.extend({ ... })
      });

      App.initialize();
      App.get('router') // an instance of App.Router

  If you want to define a Router instance elsewhere, you can pass the instance to the application's
  `initialize` method:

      App = Ember.Application.create();
      aRouter = Ember.Router.create({ ... });

      App.initialize(aRouter);
      App.get('router') // aRouter

  ## Adding Routes to a Router
  The `initialState` property of Ember.Router instances is named `root`. The state stored in this
  property should be a subclass of Ember.Route. The `root` route should itself have states that are
  also subclasses of Ember.Route and have `route` properties describing the URL pattern you would
  like to detect.

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            index: Ember.Route.extend({
              route: '/'
            }),
            ... additional Ember.Routes ...
          })
        })
      });
      App.initialize();

  When an application loads, Ember will parse the URL and attempt to find an Ember.Route within
  the application's states that matches. (The example URL-matching below will use the default
  'hash syntax' provided by `Ember.HashLocation`.)

  In the following route structure:

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/'
            }),
            bRoute: Ember.Route.extend({
              route: '/alphabeta'
            })
          })
        })
      });
      App.initialize();

  Loading the page at the URL '#/' will detect the route property of 'root.aRoute' ('/') and
  transition the router first to the state named 'root' and then to the substate 'aRoute'.

  Respectively, loading the page at the URL '#/alphabeta' would detect the route property of
  'root.bRoute' ('/alphabeta') and transition the router first to the state named 'root' and
  then to the substate 'bRoute'.

  ## Route Transition Events
  Transitioning between Ember.Route instances (including the transition into the detected
  route when loading the application)  triggers the same transition events as state transitions for
  base `Ember.State`s. However, the default `setup` transition event is named `connectOutlets` on
  Ember.Router instances (see 'Changing View Hierarchy in Response To State Change').

  The following route structure when loaded with the URL "#/"

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              enter: function(router){
                console.log("entering root.aRoute from", router.getPath('currentState.name'));
              },
              connectOutlets: function(router){
                console.log("entered root.aRoute, fully transitioned to", router.getPath('currentState.path'));
              }
            })
          })
        })
      });
      App.initialize();

  Will result in console output of:

      'entering root.aRoute from root'
      'entered root.aRoute, fully transitioned to root.aRoute '

  ## Routes With Dynamic Segments
  An Ember.Route's `route` property can reference dynamic sections of the URL by prefacing a URL segment
  with the ':' character.  The values of these dynamic segments will be passed as a hash to the
  `connectOutlets` method of the matching Route. The following route structure when loaded with the URL
  "#/fixed/thefirstvalue/anotherFixed/thesecondvalue":

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/fixed/:dynamicSectionA/anotherFixed/:dynamicSectionB',
              connectOutlets: function(router, context){}
            })
          })
        })
      });
      App.initialize();

  Will call the 'connectOutlets' method of the Route instance at the path 'root.aRoute' with the
  following hash as its second argument:

      {
        dynamicSectionA: 'thefirstvalue',
        dynamicSectionB: 'thesecondvalue'
      }

  ## Transitions Between States
  Once a routed application has initialized its state based on the entry URL subsequent transitions to other
  states will update the URL if the entered State has a `route` property. Given the following state structure
  loaded at the URL '#/':

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              moveElsewhere: Ember.Route.transitionTo('bRoute')
            }),
            bRoute: Ember.Route.extend({
              route: '/someOtherLocation'
            })
          })
        })
      });
      App.initialize();

  And application code:

      App.get('router').send('moveElsewhere');

  Will transition the application's state to 'root.bRoute' and trigger an update of the URL to
  '#/someOtherLocation

  For URL patterns with dynamic segments a context can be supplied as the second argument to `send`.
  The router will match dynamic segments names to keys on this object and fill in the URL with the
  supplied values. Given the following state structure loaded at the URL '#/':

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              moveElsewhere: Ember.Route.transitionTo('bRoute')
            }),
            bRoute: Ember.Route.extend({
              route: '/a/route/:dynamicSection/:anotherDynamicSection'
              connectOutlets: function(router, context){},
            })
          })
        })
      });
      App.initialize();

  And application code:

      App.get('router').send('moveElsewhere', {
        dynamicSection: '42',
        anotherDynamicSection: 'Life'
      });

  Will transition the application's state to 'root.bRoute' and trigger an update of the URL to
  '#/a/route/42/Life'.

  The context argument will also be passed as the second argument to the `connectOutlets` method call.

  ## Detecting Routing/Non-Routing Calls to `connectOutlets`
  Because `connectOutlets` will be called both for the initial route detection and on subsequent application
  state changes that affect the browser URL the router can differentiate between these two conditions with
  its `isRouting` property. During the application's initial loading, `isRouting` will be `true`, during state
  transitions after the application has loaded `isRouting` will be false. If you need to take special action
  for either condition (e.g. loading remote data), check this property:

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              connectOutlets: function(router, context){
                if (router.get('isRouting')) {
                  // intitial app loading, get data from server
                };
              },
            })
          })
        })
      });
      App.initialize();

  ## Injection of Controller Singletons
  During application initialization Ember will detect properties of the application ending in 'Controller',
  create singleton instances of each class, and assign them as a properties on the router.  The property name
  will be the UpperCamel name converted to lowerCamel format. These controller classes should be subclasses
  of Ember.ObjectController, Ember.ArrayController, or a custom Ember.Object that includes the
  Ember.ControllerMixin mixin.

      App = Ember.Application.create({
        FooController: Ember.Object.create(Ember.ControllerMixin),
        Router: Ember.Router.extend({ ... })
      });

      App.getPath('router.fooController'); // instance of App.FooController

  The controller singletons will have their `namespace` property set to the application and their `target`
  property set to the application's router singleton for easy integration with Ember's user event system.
  See 'Changing View Hierarchy in Response To State Change' and 'Responding to User-initiated Events'

  ## Responding to User-initiated Events
  Controller instances injected into the router at application initialization have their `target` property
  set to the application's router instance. These controllers will also be the default `context` for their
  associated views.  Uses of the `{{action}}` helper will automatically target the application's router.

  Given the following application entered at the URL '#/':

      App = Ember.Application.create({
        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              anActionOnTheRouter: function(router, context){
                router.transitionTo('anotherState', context);
              }
            })
            anotherState: Ember.Route.extend({
              route: '/differentUrl',
              connectOutlets: function(router, context){

              }
            })
          })
        })
      });
      App.initialize();

  The following template:

  Will delegate `click` events on the rendered `h1` to the application's router instance. In this case the
  `anActionOnTheRouter` method of the state at 'root.aRoute' will be called with the view's controller
  as the context argument. This context will be passed to the `connectOutlets` as its second argument.

  Different `context` can be supplied from within the `{{action}}` helper, allowing specific context passing
  between application states:

  See Handlebars.helpers.actions for additional usage examples.

  ## Changing View Hierarchy in Response To State Change
  Changes in application state that change the URL should be accompanied by associated changes in view
  hierarchy.  This can be accomplished by calling 'connectOutlet' on the injected controller singletons from
  within the 'connectOutlets' event of an Ember.Route:

      App = Ember.Application.create({
        OneController: Ember.ObjectController.extend(),
        OneView: Ember.View.extend(),

        AnotherController: Ember.ObjectController.extend(),
        AnotherView: Ember.View.extend(),

        Router: Ember.Router.extend({
          root: Ember.Route.extend({
            aRoute: Ember.Route.extend({
              route: '/',
              connectOutlets: function(router, context){
                router.get('oneController').connectOutlet('another');
              },
            })
          })
        })
      });
      App.initialize();

  This will detect the '{{outlet}}' portion of `oneController`'s view (an instance of `App.OneView`) and
  fill it with a rendered instance of `App.AnotherView` whose `context` will be the single instance of
  `App.AnotherController` stored on the router in the `anotherController` property.

  For more information about Outlets see Ember.Handlebars.helpers.outlet. For more information about controller
  injections see Ember.Application#initialize(). For additional information about view context see Ember.View.

  @extends Ember.StateManager
*/
Ember.Router = Ember.StateManager.extend(
/** @scope Ember.Router.prototype */ {

  /**
    @property {String}
    @default 'root'
  */
  initialState: 'root',

  /**
    The `Ember.Location` implementation to be used to manage the application
    URL state. The following values are supported:

    * 'hash': Uses URL fragment identifiers (like #/blog/1) for routing.
    * 'none': Does not read or set the browser URL, but still allows for
      routing to happen. Useful for testing.

    @type String
    @default 'hash'
  */
  location: 'hash',

  /**
    On router, transitionEvent should be called connectOutlets

    @property {String}
    @default 'connectOutlets'
  */
  transitionEvent: 'connectOutlets',

  route: function(path) {
    set(this, 'isRouting', true);

    try {
      path = path.replace(/^(?=[^\/])/, "/");

      this.send('unroutePath', path);

      var currentURL = get(this, 'currentState').absoluteRoute(this);
      var rest = path.substr(currentURL.length);

      this.send('routePath', rest);
    } finally {
      set(this, 'isRouting', false);
    }

    get(this, 'currentState').updateRoute(this, get(this, 'location'));
  },

  urlFor: function(path, hash) {
    var currentState = get(this, 'currentState') || this,
        state = this.findStateByPath(currentState, path);

    Ember.assert("To get a URL for a state, it must have a `route` property.", !!get(state, 'routeMatcher'));

    var location = get(this, 'location'),
        absoluteRoute = state.absoluteRoute(this, hash);

    return location.formatURL(absoluteRoute);
  },

  urlForEvent: function(eventName, context) {
    var currentState = get(this, 'currentState');
    var targetStateName = currentState.lookupEventTransition(eventName);

    Ember.assert(Ember.String.fmt("You must specify a target state for event '%@' in order to link to it in the current state '%@'.", [eventName, get(currentState, 'path')]), !!targetStateName);

    var targetState = this.findStateByPath(currentState, targetStateName);

    Ember.assert("Your target state name " + targetStateName + " for event " + eventName + " did not resolve to a state", !!targetState);
    var hash = targetState.serialize(this, context);

    return this.urlFor(targetStateName, hash);
  },

  /** @private */
  init: function() {
    this._super();

    var location = get(this, 'location');
    if ('string' === typeof location) {
      set(this, 'location', Ember.Location.create({ implementation: location }));
    }
  },

  /** @private */
  willDestroy: function() {
    get(this, 'location').destroy();
  }
});
<|endoftext|>


<commit_before>var EventEmitter = require('events')
var u            = require('./util')
var Hookable     = require('hoox')
var camelize     = require('to-camel-case')
var deepMerge        = require('deep-merge')(function (a, b) { return b })

function toCamelCase (n) {
  return n ? camelize(n) : n
}

function isFunction (f) {
  return 'function' === typeof f
}

function isString (s) {
  return s && 'string' === typeof s
}

function id (e) { return e }

function merge (a, b, mapper) {

  mapper = mapper || id

  for(var k in b) {
    if(b[k] && 'object' === typeof b[k] && !Buffer.isBuffer(b[k]) && !Array.isArray(b[k]))
      merge(a[k] = {}, b[k], mapper)
    else
      a[k] = mapper(b[k], k)
  }

  return a
}

function find(ary, test) {
  var v
  for(var i = 0; i < ary.length; i++)
    if(v = test(ary[i], i, ary)) return v
  return v
}

module.exports = function (plugins, defaults) {

  function create (opts) {
    console.log("DEFAUELTS", defaults)
    console.log("CONFIG", opts)
    opts = merge(merge({}, defaults), opts)
    console.log("RESULT", opts)
    //change event emitter to something with more rigorous security?
    var api = new EventEmitter()
    create.plugins.forEach(function (plug) {
      var _api = plug.init.call({createClient: create.createClient}, api, opts, create.permissions, create.manifest)
      if(plug.name) {
        var o = {}; o[toCamelCase(plug.name)] = _api; _api = o
      }
      api = merge(api, _api, function (v, k) {
        if ('function' === typeof v) {
          v = Hookable(v)
          if (plug.manifest && plug.manifest[k] === 'sync') {
            u.hookOptionalCB(v)
          }
        }
        return v
      })
    })

    return api
  }

  create.plugins = []
  create.manifest = {}
  create.permissions = {}

  create.use = function (plug) {
    if(isFunction(plug))
      return create.plugins.push({init: plug}), create

    if(!plug.init)
      throw new Error('plugins *must* have "init" method')

    if(isString(plug.name))
      if(find(create.plugins, function (_plug) {
        return _plug.name === plug.name
      }))
        throw new Error('plugin named:'+plug.name+' is already loaded')

    var name = plug.name
    if(plug.manifest)
      create.manifest =
        u.merge.manifest(create.manifest, plug.manifest, toCamelCase(name))
    if(plug.permissions)
      create.permissions =
        u.merge.permissions(create.permissions, plug.permissions, toCamelCase(name))
    create.plugins.push(plug)

    return create
  }

  ;[].concat(plugins).filter(Boolean).forEach(create.use)

  return create
}

<commit_msg>remove logging and usused module: deep-merge<commit_after>var EventEmitter = require('events')
var u            = require('./util')
var Hookable     = require('hoox')
var camelize     = require('to-camel-case')

function toCamelCase (n) {
  return n ? camelize(n) : n
}

function isFunction (f) {
  return 'function' === typeof f
}

function isString (s) {
  return s && 'string' === typeof s
}

function id (e) { return e }

function merge (a, b, mapper) {

  mapper = mapper || id

  for(var k in b) {
    if(b[k] && 'object' === typeof b[k] && !Buffer.isBuffer(b[k]) && !Array.isArray(b[k]))
      merge(a[k] = {}, b[k], mapper)
    else
      a[k] = mapper(b[k], k)
  }

  return a
}

function find(ary, test) {
  var v
  for(var i = 0; i < ary.length; i++)
    if(v = test(ary[i], i, ary)) return v
  return v
}

module.exports = function (plugins, defaults) {

  function create (opts) {
    opts = merge(merge({}, defaults), opts)
    //change event emitter to something with more rigorous security?
    var api = new EventEmitter()
    create.plugins.forEach(function (plug) {
      var _api = plug.init.call({createClient: create.createClient}, api, opts, create.permissions, create.manifest)
      if(plug.name) {
        var o = {}; o[toCamelCase(plug.name)] = _api; _api = o
      }
      api = merge(api, _api, function (v, k) {
        if ('function' === typeof v) {
          v = Hookable(v)
          if (plug.manifest && plug.manifest[k] === 'sync') {
            u.hookOptionalCB(v)
          }
        }
        return v
      })
    })

    return api
  }

  create.plugins = []
  create.manifest = {}
  create.permissions = {}

  create.use = function (plug) {
    if(isFunction(plug))
      return create.plugins.push({init: plug}), create

    if(!plug.init)
      throw new Error('plugins *must* have "init" method')

    if(isString(plug.name))
      if(find(create.plugins, function (_plug) {
        return _plug.name === plug.name
      }))
        throw new Error('plugin named:'+plug.name+' is already loaded')

    var name = plug.name
    if(plug.manifest)
      create.manifest =
        u.merge.manifest(create.manifest, plug.manifest, toCamelCase(name))
    if(plug.permissions)
      create.permissions =
        u.merge.permissions(create.permissions, plug.permissions, toCamelCase(name))
    create.plugins.push(plug)

    return create
  }

  ;[].concat(plugins).filter(Boolean).forEach(create.use)

  return create
}

<|endoftext|>


<commit_before>/*! markdown-it-emphasis-alt 1.0.4 https://github.com/jay-hodgson/markdown-it-emphasis-alt @license MIT */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.markdownitEmphasisAlt=e()}}(function(){return function e(r,n,t){function o(i,a){if(!n[i]){if(!r[i]){var f="function"==typeof require&&require;if(!a&&f)return f(i,!0);if(s)return s(i,!0);var u=new Error("Cannot find module '"+i+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[i]={exports:{}};r[i][0].call(c.exports,function(e){var n=r[i][1][e];return o(n?n:e)},c,c.exports,e,r,n,t)}return n[i].exports}for(var s="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(e,r,n){"use strict";function t(e){a=!1,f=!1,u=e?e:0}function o(e){if(e>=8192&&8202>=e)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return!0}return!1}function s(e,r){var n,s,i,c=e.pos,p=e.src.charCodeAt(c),l=!1,d=c;if(r)return!1;if(95!==p&&42!==p)return!1;if(s=c>0?e.src.charCodeAt(c-1):32,i=e.pos+1<e.posMax?e.src.charCodeAt(e.pos+1):32,!o(s)&&s!==p&&!o(i)&&i!==p)return!1;for(c+1<=e.posMax&&e.src.charCodeAt(c+1)===p&&(l=!0);d<e.posMax&&"\n"!==e.src.charAt(d);)d++;return d>u&&t(d),n=e.push("text","",0),n.content=String.fromCharCode(p),l?(f=!f,n.content+=String.fromCharCode(p)):a=!a,e.delimiters.push({marker:p,jump:0,token:e.tokens.length-1,level:e.level,end:-1,open:l?f:a,close:l?!f:!a,isDoubleMarker:l}),e.pos++,l&&e.pos++,!0}function i(e){var r,n,t,o,s,i,a=e.delimiters,f=e.delimiters.length;for(r=0;f>r;r++)n=a[r],95!==n.marker&&42!==n.marker||-1!==n.end&&(t=a[n.end],i=n.isDoubleMarker,s=String.fromCharCode(n.marker),o=e.tokens[n.token],o.type=i?"strong_open":"em_open",o.tag=i?"strong":"em",o.nesting=1,o.markup=i?s+s:s,o.content="",o=e.tokens[t.token],o.type=i?"strong_close":"em_close",o.tag=i?"strong":"em",o.nesting=-1,o.markup=i?s+s:s,o.content="")}var a,f,u,c=!1;r.exports=function(e){t(0),c||(e.disable("emphasis"),e.inline.ruler.before("emphasis","emphasis_alt",s),e.inline.ruler2.before("emphasis","emphasis_alt",i),c=!0)}},{}]},{},[1])(1)});
<commit_msg>simplify and look for either marker<commit_after>/*! markdown-it-emphasis-alt 1.0.4 https://github.com/jay-hodgson/markdown-it-emphasis-alt @license MIT */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.markdownitEmphasisAlt=e()}}(function(){return function e(r,n,t){function o(i,a){if(!n[i]){if(!r[i]){var f="function"==typeof require&&require;if(!a&&f)return f(i,!0);if(s)return s(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[i]={exports:{}};r[i][0].call(u.exports,function(e){var n=r[i][1][e];return o(n?n:e)},u,u.exports,e,r,n,t)}return n[i].exports}for(var s="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(e,r,n){"use strict";function t(e){a=!1,f=!1,c=e?e:0}function o(e){if(e>=8192&&8202>=e)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:case 95:case 42:return!0}return!1}function s(e,r){var n,s,i,u=e.pos,p=e.src.charCodeAt(u),l=!1,d=u;if(r)return!1;if(95!==p&&42!==p)return!1;if(s=u>0?e.src.charCodeAt(u-1):32,i=e.pos+1<e.posMax?e.src.charCodeAt(e.pos+1):32,!o(s)&&!o(i))return!1;for(u+1<=e.posMax&&e.src.charCodeAt(u+1)===p&&(l=!0);d<e.posMax&&"\n"!==e.src.charAt(d);)d++;return d>c&&t(d),n=e.push("text","",0),n.content=String.fromCharCode(p),l?(f=!f,n.content+=String.fromCharCode(p)):a=!a,e.delimiters.push({marker:p,jump:0,token:e.tokens.length-1,level:e.level,end:-1,open:l?f:a,close:l?!f:!a,isDoubleMarker:l}),e.pos++,l&&e.pos++,!0}function i(e){var r,n,t,o,s,i,a=e.delimiters,f=e.delimiters.length;for(r=0;f>r;r++)n=a[r],95!==n.marker&&42!==n.marker||-1!==n.end&&(t=a[n.end],i=n.isDoubleMarker,s=String.fromCharCode(n.marker),o=e.tokens[n.token],o.type=i?"strong_open":"em_open",o.tag=i?"strong":"em",o.nesting=1,o.markup=i?s+s:s,o.content="",o=e.tokens[t.token],o.type=i?"strong_close":"em_close",o.tag=i?"strong":"em",o.nesting=-1,o.markup=i?s+s:s,o.content="")}var a,f,c,u=!1;r.exports=function(e){t(0),u||(e.disable("emphasis"),e.inline.ruler.before("emphasis","emphasis_alt",s),e.inline.ruler2.before("emphasis","emphasis_alt",i),u=!0)}},{}]},{},[1])(1)});
<|endoftext|>


<commit_before>/*:
 * RS_YoutubePlayer.js
 * @plugindesc This plugin allows you to start playback of the YouTube video.
 * @author biud436
 * @help
 * In general, In Android Chrome and Mobile Safari, It doesn't automatically
 * start playback. and you can stop the video by clicking around the YouTube video.
 * This plugin will automatically end the video playback if you watches
 * the video until the end.
 * =============================================================================
 * Plugin Command
 * =============================================================================
 * - This plugin command will start playback of the YouTube video. Please enter
 * the URL as follows. If the Internet had not connected, It could have caused
 * the error.
 *
 * YTPlayer play https://www.youtube.com/watch?v=C4ze-KCSxQY
 *
 * - Stop playback of the YouTube Video.
 *
 * YTPlayer stop
 *
 * =============================================================================
 * Change Log
 * =============================================================================
 * 2016.05.08 (v1.0.0) - First Release
 * 2016.05.09 (v1.0.1) - Added Error Handler
 */

var Imported = Imported || {};
Imported.RS_YoutubePlayer = true;

var player;

function YTPlayer() {
  throw new Error("This is a static class");
}

//----------------------------------------------------------------------------
// Youtube Event Handler
//
//
function onYouTubeIframeAPIReady() {
  player = new YT.Player('ytplayer-iframe', {
    height: '560',
    width: '315',
    videoId: 'BIbpYySZ-2Q',
    fs: 1,
    autoplay: 1,
    enablejsapi: 1,
    rel: 1,
    showinfo: 1,
    playsinline: 0,
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange,
      'onError': onPlayerError
    }
  });
}

function onPlayerReady(event) {
  var target = event.target;
  target.playVideo();
}

function onPlayerError(event) {
  var errorLog = "";
  switch (event.data) {
    case 2:
      // 요청에 잘못된 매개변수 값이 포함되어 있습니다. 예를 들어 11자리가 아닌 동영상 ID를 지정하거나
      // 동영상 ID에 느낌표 또는 별표와 같은 잘못된 문자가 포함된 경우에 이 오류가 발생합니다.
      errorLog += "Error Code : 2" + '\r\n';
      errorLog += "The request contains an invalid parameter value. For example, " + '\r\n';
      errorLog += "this error occurs if you specify a video ID that does not have 11 characters, " + '\r\n';
      errorLog += "or if the video ID contains invalid characters, " + '\r\n';
      errorLog += "such as exclamation points or asterisks.      " + '\r\n';
      break;
    case 5:
      // 요청한 콘텐츠는 HTML5플레이어에서 재생할 수 없는, 또는 HTML5플레이어에 대한 별도의 에러가 발생했습니다.
      errorLog += "Error Code : 5" + '\r\n';
      errorLog += " The requested content cannot be played in an HTML5 player" + '\r\n';
      errorLog += "or another error related to the HTML5 player has occurred." + '\r\n';
      break;
    case 100:
      // 요청한 동영상을 찾을 수 없습니다.
      // 어떠한 이유로든 동영상이 삭제되었거나 비공개로 표시된 경우에 이 오류가 발생합니다.
      errorLog += "Error Code : 100" + '\r\n';
      errorLog += "The video requested was not found. " + '\r\n';
      errorLog += "This error occurs when a video has been removed (for any reason) " + '\r\n';
      errorLog += "or has been marked as private." + '\r\n';
      break;
    case 101:
    case 150:
      // 요청한 동영상의 소유자가 내장 플레이어에서 동영상을 재생하는 것을 허용하지 않습니다.
      errorLog += "Error Code : 101 or 150" + '\r\n';
      errorLog += "The owner of the requested video does not allow it to be played in embedded players.";
      break;
  }
  YTPlayer.stopVideo();
  window.alert(errorLog);
}
function onPlayerStateChange (event) {
  switch(event.data) {
      case YT.PlayerState.ENDED: // 종료됨
          console.log('Video has ended.');
          YTPlayer._status = YT.PlayerState.ENDED;
          YTPlayer.removeAllElement();
          break;
      case YT.PlayerState.PLAYING: // 재생 중
          console.log('Video is playing.');
          YTPlayer._status = YT.PlayerState.PLAYING;
          break;
      case YT.PlayerState.PAUSED: // 일시 중지
          console.log('Video is paused.');
          YTPlayer._status = YT.PlayerState.PAUSED
          break;
      case YT.PlayerState.BUFFERING: // 버퍼링
          console.log('Video is buffering.');
          YTPlayer._status = YT.PlayerState.BUFFERING;
          break;
      case YT.PlayerState.CUED: // 동영상 신호
          console.log('Video is cued.');
          YTPlayer._status = YT.PlayerState.CUED;
          break;
      default: // 시작 전
          console.log('Unrecognized state.');
          break;
  }
}

(function() {

  //----------------------------------------------------------------------------
  // YTPlayer
  //
  //
  YTPlayer.initialize = function() {
    this._init = false;
    this._status = -1;
    this._ytPlayer = document.createElement('div');
    this._ytPlayer.id = 'ytplayer';
    this._ytPlayer.style.width = '560px';
    this._ytPlayer.style.height = '315px';
    document.body.appendChild(this._ytPlayer);
    this._tag = document.createElement('script');
    this._tag.src = "https://www.youtube.com/iframe_api";
    this.createIframe();
  };

  YTPlayer.createIframe = function () {
    this._iframe = document.createElement('iframe');
    this._iframe.id = 'ytplayer-iframe';
    this._iframe.width = 560;
    this._iframe.height = 315;
    this._iframe.style.opacity = '0';
    this._iframe.style.zIndex = '0';
    this._iframe.frameBorder = 0;
    this._iframe.allowfullscreen = true;
    Graphics._centerElement(this._iframe);
    this._ytPlayer.appendChild(this._iframe);
  };

  YTPlayer.preVideo = function(src) {
    if(src) {
      var v = src.replace('https://www.youtube.com/watch?v=','').replace('&feature=youtu.be','');
      this._iframe.src = 'https://www.youtube.com/embed/%1?enablejsapi=1&version=3'.format(v);
    }
    this._iframe.style.opacity = '1';
    this._iframe.style.zIndex = '20000';
    if(!this._init) {
      this._firstScriptTag = document.getElementsByTagName('script')[0];
      this._firstScriptTag.parentNode.insertBefore(this._tag, this._firstScriptTag);
      this._init = true;
    } else {
      window.onYouTubeIframeAPIReady();
    }
  };

  YTPlayer.playVideo = function(src) {
    if(!this._iframe) this.createIframe();
    this.preVideo(src);
    Graphics._canvas.style.opacity = '0.5';
    if($gamePlayer) $gamePlayer.lock();
  };

  YTPlayer.stopVideo = function() {
    if(!this._iframe) this.createIframe();
    this._iframe.style.opacity = '0';
    this._iframe.style.zIndex = '0';
    Graphics._canvas.style.opacity = '1.0';
    this.callPlayer("stopVideo");
    if($gamePlayer) $gamePlayer.unlock();
  };

  YTPlayer.removeAllElement = function() {
    this.stopVideo();
    this._iframe.style.opacity = '0';
    this._iframe.style.zIndex = '0';
  };

  YTPlayer.callPlayer = function(func, args) {
      var frame_id = 'ytplayer-iframe';
      var src = this._iframe.src;
      if (src.indexOf('youtube.com/embed') != -1) {
          this._iframe.contentWindow.postMessage(JSON.stringify({
              'event': 'command',
              'func': func,
              'args': args || [],
              'id': frame_id
          }), "*");
      }
  };

  YTPlayer.isOnPlayer = function() {
    if(!this._iframe) return false;
    if(!this._iframe.contentWindow) return false;
    return true;
  };

  // Checks whether the YoutubePlayer is playing.
  YTPlayer.isPlaying = function() {
    if(this._status === YT.PlayerState.PLAYING) {
      return true;
    }
    return false;
  }

  YTPlayer.isPaused = function() {
    if(this._status === YT.PlayerState.PAUSED) {
      return true;
    }
    return false;
  };

  YTPlayer.isBuffering = function() {
    if(this._status === YT.PlayerState.BUFFERING) {
      return true;
    }
    return false;
  };

  YTPlayer.isEnded = function() {
    if(this._status === YT.PlayerState.ENDED) {
      return true;
    }
    return false;
  };

  YTPlayer.getRect = function() {
    var w, h, gw, gh, x1, x2, y1, y2;
    w = 560 / 2;
    h = 315 / 2;
    gw = (Graphics.boxWidth / 2);
    gh = (Graphics.boxHeight / 2);
    x1 = gw - w;
    x2 = gw + w;
    y1 = gh - h;
    y2 = gh + h;
    return new Rectangle(x1, y1, x2, y2);
  }

  YTPlayer.isTouched = function() {
    var x = TouchInput.x;
    var y = TouchInput.y;
    var rect = this.getRect();
    return x >= rect.x && y >= rect.y && x < rect.width && y < rect.height;
  }

  //----------------------------------------------------------------------------
  // Graphics
  //
  //
  var alias_Graphics_initialize = Graphics.initialize;
  Graphics.initialize = function(width, height, type) {
    alias_Graphics_initialize.call(this, width, height, type);
    YTPlayer.initialize();
  }

  Graphics.playYoutube = function(src) {
    var lastStep;
    YTPlayer.playVideo(src);
    lastStep = setInterval(function() {
      YTPlayer.callPlayer('playVideo');
      if(YTPlayer.isOnPlayer()) {
          clearInterval(lastStep);
      }
    }, 2000);
  };

  //----------------------------------------------------------------------------
  // Game_Interpreter
  //
  //
  var alias_pluginCommand = Game_Interpreter.prototype.pluginCommand;
  Game_Interpreter.prototype.pluginCommand = function(command, args) {
      alias_pluginCommand.call(this, command, args);
      if(command === "YTPlayer") {
        switch (args[0].toLowerCase()) {
          case 'play':
            var src = args.slice(1, args.length).join('');
            setTimeout(function() {
              Graphics.playYoutube(src);
            }, 1);
            break;
          case 'stop':
            if(YTPlayer.isPlaying()) YTPlayer.stopVideo();
        }
      }
  };

  //----------------------------------------------------------------------------
  // Game_Player
  //
  //
  var alias_Game_Player_initMembers = Game_Player.prototype.initMembers;
  Game_Player.prototype.initMembers = function() {
    alias_Game_Player_initMembers.call(this);
    this._locked = false;
    this._prelockDirection = 2;
  }

  Game_Player.prototype.lock = function() {
    if (!this._locked) {
        this._prelockDirection = this.direction();
        this._locked = true;
    }
  };

  Game_Player.prototype.unlock = function() {
    if (this._locked) {
        this._locked = false;
        this.setDirection(this._prelockDirection);
    }
  };

  var alias_Game_Player_canMove = Game_Player.prototype.canMove;
  Game_Player.prototype.canMove = function() {
    if(this._locked) {
      return false;
    }
    return alias_Game_Player_canMove.call(this);
  };

  // ----------------------------------------------------------------------------
  // Scene_Map
  //
  //
  var alias_Scene_Map_update = Scene_Map.prototype.update;
  Scene_Map.prototype.update = function() {
    alias_Scene_Map_update.call(this);
    this.checkEscapeToYoutube();
  };

  Scene_Map.prototype.checkEscapeToYoutube = function() {
    if(TouchInput.isTriggered()) {
      if(!YTPlayer.isTouched() && (YTPlayer._status > 0) ) {
         YTPlayer.stopVideo();
      }
    }
  };

})();
<commit_msg>Fixed a function that parses a URL .<commit_after>/*:
 * RS_YoutubePlayer.js
 * @plugindesc This plugin allows you to start playback of the YouTube video.
 * @author biud436
 * @help
 * In general, In Android Chrome and Mobile Safari, It doesn't automatically
 * start playback. and you can stop the video by clicking around the YouTube video.
 * This plugin will automatically end the video playback if you watches
 * the video until the end.
 * =============================================================================
 * Plugin Command
 * =============================================================================
 * - This plugin command will start playback of the YouTube video. Please enter
 * the URL as follows. If the Internet had not connected, It could have caused
 * the error.
 *
 * YTPlayer play https://www.youtube.com/watch?v=C4ze-KCSxQY
 *
 * - Stop playback of the YouTube Video.
 *
 * YTPlayer stop
 *
 * =============================================================================
 * Change Log
 * =============================================================================
 * 2016.05.08 (v1.0.0) - First Release
 * 2016.05.09 (v1.0.1) - Added Error Handler
 * 2016.05.12 (v1.0.2) - Fixed a function that parses a URL .
 */

var Imported = Imported || {};
Imported.RS_YoutubePlayer = true;

var player;

function YTPlayer() {
  throw new Error("This is a static class");
}

//----------------------------------------------------------------------------
// Youtube Event Handler
//
//
function onYouTubeIframeAPIReady() {
  player = new YT.Player('ytplayer-iframe', {
    height: '560',
    width: '315',
    videoId: 'BIbpYySZ-2Q',
    fs: 1,
    autoplay: 1,
    enablejsapi: 1,
    rel: 1,
    showinfo: 1,
    playsinline: 0,
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange,
      'onError': onPlayerError
    }
  });
}

function onPlayerReady(event) {
  var target = event.target;
  target.playVideo();
}

function onPlayerError(event) {
  var errorLog = "";
  switch (event.data) {
    case 2:
      // 요청에 잘못된 매개변수 값이 포함되어 있습니다. 예를 들어 11자리가 아닌 동영상 ID를 지정하거나
      // 동영상 ID에 느낌표 또는 별표와 같은 잘못된 문자가 포함된 경우에 이 오류가 발생합니다.
      errorLog += "Error Code : 2" + '\r\n';
      errorLog += "The request contains an invalid parameter value. For example, " + '\r\n';
      errorLog += "this error occurs if you specify a video ID that does not have 11 characters, " + '\r\n';
      errorLog += "or if the video ID contains invalid characters, " + '\r\n';
      errorLog += "such as exclamation points or asterisks.      " + '\r\n';
      break;
    case 5:
      // 요청한 콘텐츠는 HTML5플레이어에서 재생할 수 없는, 또는 HTML5플레이어에 대한 별도의 에러가 발생했습니다.
      errorLog += "Error Code : 5" + '\r\n';
      errorLog += " The requested content cannot be played in an HTML5 player" + '\r\n';
      errorLog += "or another error related to the HTML5 player has occurred." + '\r\n';
      break;
    case 100:
      // 요청한 동영상을 찾을 수 없습니다.
      // 어떠한 이유로든 동영상이 삭제되었거나 비공개로 표시된 경우에 이 오류가 발생합니다.
      errorLog += "Error Code : 100" + '\r\n';
      errorLog += "The video requested was not found. " + '\r\n';
      errorLog += "This error occurs when a video has been removed (for any reason) " + '\r\n';
      errorLog += "or has been marked as private." + '\r\n';
      break;
    case 101:
    case 150:
      // 요청한 동영상의 소유자가 내장 플레이어에서 동영상을 재생하는 것을 허용하지 않습니다.
      errorLog += "Error Code : 101 or 150" + '\r\n';
      errorLog += "The owner of the requested video does not allow it to be played in embedded players.";
      break;
  }
  YTPlayer.stopVideo();
  window.alert(errorLog);
}
function onPlayerStateChange (event) {
  switch(event.data) {
      case YT.PlayerState.ENDED: // 종료됨
          console.log('Video has ended.');
          YTPlayer._status = YT.PlayerState.ENDED;
          YTPlayer.removeAllElement();
          break;
      case YT.PlayerState.PLAYING: // 재생 중
          console.log('Video is playing.');
          YTPlayer._status = YT.PlayerState.PLAYING;
          break;
      case YT.PlayerState.PAUSED: // 일시 중지
          console.log('Video is paused.');
          YTPlayer._status = YT.PlayerState.PAUSED
          break;
      case YT.PlayerState.BUFFERING: // 버퍼링
          console.log('Video is buffering.');
          YTPlayer._status = YT.PlayerState.BUFFERING;
          break;
      case YT.PlayerState.CUED: // 동영상 신호
          console.log('Video is cued.');
          YTPlayer._status = YT.PlayerState.CUED;
          break;
      default: // 시작 전
          console.log('Unrecognized state.');
          break;
  }
}

(function() {

  //----------------------------------------------------------------------------
  // YTPlayer
  //
  //
  YTPlayer.initialize = function() {
    this._init = false;
    this._status = -1;
    this._ytPlayer = document.createElement('div');
    this._ytPlayer.id = 'ytplayer';
    this._ytPlayer.style.width = '560px';
    this._ytPlayer.style.height = '315px';
    document.body.appendChild(this._ytPlayer);
    this._tag = document.createElement('script');
    this._tag.src = "https://www.youtube.com/iframe_api";
    this.createIframe();
  };

  YTPlayer.createIframe = function () {
    this._iframe = document.createElement('iframe');
    this._iframe.id = 'ytplayer-iframe';
    this._iframe.width = 560;
    this._iframe.height = 315;
    this._iframe.style.opacity = '0';
    this._iframe.style.zIndex = '0';
    this._iframe.frameBorder = 0;
    this._iframe.allowfullscreen = true;
    Graphics._centerElement(this._iframe);
    this._ytPlayer.appendChild(this._iframe);
  };

  YTPlayer.preVideo = function(src) {
    var v;
    if(src) {
      if(re.test(src)) {
          // v = src.split(re)[1];
          v = RegExp.$1;
      } else {
          v = src.replace('https://www.youtube.com/watch?v=','').replace('&feature=youtu.be','');
      }
      this._iframe.src = 'https://www.youtube.com/embed/%1?enablejsapi=1&version=3'.format(v);
    }
    this._iframe.style.opacity = '1';
    this._iframe.style.zIndex = '20000';
    if(!this._init) {
      this._firstScriptTag = document.getElementsByTagName('script')[0];
      this._firstScriptTag.parentNode.insertBefore(this._tag, this._firstScriptTag);
      this._init = true;
    } else {
      window.onYouTubeIframeAPIReady();
    }
  };

  YTPlayer.playVideo = function(src) {
    if(!this._iframe) this.createIframe();
    this.preVideo(src);
    Graphics._canvas.style.opacity = '0.5';
    if($gamePlayer) $gamePlayer.lock();
  };

  YTPlayer.stopVideo = function() {
    if(!this._iframe) this.createIframe();
    this._iframe.style.opacity = '0';
    this._iframe.style.zIndex = '0';
    Graphics._canvas.style.opacity = '1.0';
    this.callPlayer("stopVideo");
    if($gamePlayer) $gamePlayer.unlock();
  };

  YTPlayer.removeAllElement = function() {
    this.stopVideo();
    this._iframe.style.opacity = '0';
    this._iframe.style.zIndex = '0';
  };

  YTPlayer.callPlayer = function(func, args) {
      var frame_id = 'ytplayer-iframe';
      var src = this._iframe.src;
      if (src.indexOf('youtube.com/embed') != -1) {
          this._iframe.contentWindow.postMessage(JSON.stringify({
              'event': 'command',
              'func': func,
              'args': args || [],
              'id': frame_id
          }), "*");
      }
  };

  YTPlayer.isOnPlayer = function() {
    if(!this._iframe) return false;
    if(!this._iframe.contentWindow) return false;
    return true;
  };

  // Checks whether the YoutubePlayer is playing.
  YTPlayer.isPlaying = function() {
    if(this._status === YT.PlayerState.PLAYING) {
      return true;
    }
    return false;
  }

  YTPlayer.isPaused = function() {
    if(this._status === YT.PlayerState.PAUSED) {
      return true;
    }
    return false;
  };

  YTPlayer.isBuffering = function() {
    if(this._status === YT.PlayerState.BUFFERING) {
      return true;
    }
    return false;
  };

  YTPlayer.isEnded = function() {
    if(this._status === YT.PlayerState.ENDED) {
      return true;
    }
    return false;
  };

  YTPlayer.getRect = function() {
    var w, h, gw, gh, x1, x2, y1, y2;
    w = 560 / 2;
    h = 315 / 2;
    gw = (Graphics.boxWidth / 2);
    gh = (Graphics.boxHeight / 2);
    x1 = gw - w;
    x2 = gw + w;
    y1 = gh - h;
    y2 = gh + h;
    return new Rectangle(x1, y1, x2, y2);
  }

  YTPlayer.isTouched = function() {
    var x = TouchInput.x;
    var y = TouchInput.y;
    var rect = this.getRect();
    return x >= rect.x && y >= rect.y && x < rect.width && y < rect.height;
  }

  //----------------------------------------------------------------------------
  // Graphics
  //
  //
  var alias_Graphics_initialize = Graphics.initialize;
  Graphics.initialize = function(width, height, type) {
    alias_Graphics_initialize.call(this, width, height, type);
    YTPlayer.initialize();
  }

  Graphics.playYoutube = function(src) {
    var lastStep;
    YTPlayer.playVideo(src);
    lastStep = setInterval(function() {
      YTPlayer.callPlayer('playVideo');
      if(YTPlayer.isOnPlayer()) {
          clearInterval(lastStep);
      }
    }, 2000);
  };

  //----------------------------------------------------------------------------
  // Game_Interpreter
  //
  //
  var alias_pluginCommand = Game_Interpreter.prototype.pluginCommand;
  Game_Interpreter.prototype.pluginCommand = function(command, args) {
      alias_pluginCommand.call(this, command, args);
      if(command === "YTPlayer") {
        switch (args[0].toLowerCase()) {
          case 'play':
            var src = args.slice(1, args.length).join('');
            setTimeout(function() {
              Graphics.playYoutube(src);
            }, 1);
            break;
          case 'stop':
            if(YTPlayer.isPlaying()) YTPlayer.stopVideo();
        }
      }
  };

  //----------------------------------------------------------------------------
  // Game_Player
  //
  //
  var alias_Game_Player_initMembers = Game_Player.prototype.initMembers;
  Game_Player.prototype.initMembers = function() {
    alias_Game_Player_initMembers.call(this);
    this._locked = false;
    this._prelockDirection = 2;
  }

  Game_Player.prototype.lock = function() {
    if (!this._locked) {
        this._prelockDirection = this.direction();
        this._locked = true;
    }
  };

  Game_Player.prototype.unlock = function() {
    if (this._locked) {
        this._locked = false;
        this.setDirection(this._prelockDirection);
    }
  };

  var alias_Game_Player_canMove = Game_Player.prototype.canMove;
  Game_Player.prototype.canMove = function() {
    if(this._locked) {
      return false;
    }
    return alias_Game_Player_canMove.call(this);
  };

  // ----------------------------------------------------------------------------
  // Scene_Map
  //
  //
  var alias_Scene_Map_update = Scene_Map.prototype.update;
  Scene_Map.prototype.update = function() {
    alias_Scene_Map_update.call(this);
    this.checkEscapeToYoutube();
  };

  Scene_Map.prototype.checkEscapeToYoutube = function() {
    if(TouchInput.isTriggered()) {
      if(!YTPlayer.isTouched() && (YTPlayer._status > 0) ) {
         YTPlayer.stopVideo();
      }
    }
  };

})();
<|endoftext|>


<commit_before>"use strict";

var m = require("mithril");

module.exports = {
    view : function(ctrl, options) {
        var details = options.details;

        return m("div",
            m("strong", options.name),
            details.text ? m("p", details.text) : null
        );
    }
};
<commit_msg>Don't use name for instructions<commit_after>"use strict";

var m = require("mithril");

module.exports = {
    view : function(ctrl, options) {
        var details = options.details;

        return m("div",
            details.head ? m("p", m("strong", details.head)) : null,
            details.body ? m("p", details.body) : null
        );
    }
};
<|endoftext|>


<commit_before>module.exports = {
  'rules': {
    // enforce spacing inside array brackets
    'array-bracket-spacing': 0,
    // enforce one true brace style
    'brace-style': [2, '1tbs', {'allowSingleLine': true }],
    // require camel case names
    'camelcase': [2, {'properties': 'never'}],
    // enforce spacing before and after comma
    'comma-spacing': [2, {'before': false, 'after': true}],
    // enforce one true comma style
    'comma-style': [2, 'last'],
    // require or disallow padding inside computed properties
    'computed-property-spacing': 0,
    // enforces consistent naming when capturing the current execution context
    'consistent-this': 0,
    // enforce newline at the end of file, with no multiple empty lines
    'eol-last': 2,
    // require function expressions to have a name
    'func-names': 1,
    // enforces use of function declarations or expressions
    'func-style': 0,
    // this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
    'id-length': 0,
    // this option sets a specific tab width for your code
    'indent': [2, 2],
    // specify whether double or single quotes should be used in JSX attributes
    'jsx-quotes': 2,
    // enforces spacing between keys and values in object literal properties
    'key-spacing': [2, {'beforeColon': false, 'afterColon': true}],
    // enforces empty lines around comments
    'lines-around-comment': 0,
    // disallow mixed 'LF' and 'CRLF' as linebreaks
    'linebreak-style': 0,
    // specify the maximum depth callbacks can be nested
    'max-nested-callbacks': 0,
    // require a capital letter for constructors
    'new-cap': [2, {'newIsCap': true}],
    // disallow the omission of parentheses when invoking a constructor with no arguments
    'new-parens': 0,
    // allow/disallow an empty newline after var statement
    'newline-after-var': 0,
    // disallow use of the Array constructor
    'no-array-constructor': 0,
    // disallow use of the continue statement
    'no-continue': 0,
    // disallow comments inline after code
    'no-inline-comments': 0,
    // disallow if as the only statement in an else block
    'no-lonely-if': 0,
    // disallow mixed spaces and tabs for indentation
    'no-mixed-spaces-and-tabs': 2,
    // disallow multiple empty lines
    'no-multiple-empty-lines': [2, {'max': 2}],
    // disallow nested ternary expressions
    'no-nested-ternary': 2,
    // disallow use of the Object constructor
    'no-new-object': 2,
    // disallow space between function identifier and application
    'no-spaced-func': 2,
    // disallow the use of ternary operators
    'no-ternary': 0,
    // disallow trailing whitespace at the end of lines
    'no-trailing-spaces': 2,
    // disallow dangling underscores in identifiers
    'no-underscore-dangle': 0,
    // disallow the use of Boolean literals in conditional expressions
    'no-unneeded-ternary': 0,
    // require or disallow padding inside curly braces
    'object-curly-spacing': 0,
    // allow just one var statement per function
    'one-var': [2, 'never'],
    // require assignment operator shorthand where possible or prohibit it entirely
    'operator-assignment': 0,
    // enforce operators to be placed before or after line breaks
    'operator-linebreak': 0,
    // enforce padding within blocks
    'padded-blocks': [2, 'never'],
    // require quotes around object literal property names
    'quote-props': 0,
    // specify whether double or single quotes should be used
    'quotes': [2, 'single', 'avoid-escape'],
    // require identifiers to match the provided regular expression
    'id-match': 0,
    // enforce spacing before and after semicolons
    'semi-spacing': [2, {'before': false, 'after': true}],
    // require or disallow use of semicolons instead of ASI
    'semi': [2, 'always'],
    // sort variables within the same declaration block
    'sort-vars': 0,
    // require a space before certain keywords
    'space-before-keywords': [2, 'always'],
    // require a space after certain keywords
    'space-after-keywords': [2, 'always'],
    // require or disallow space before blocks
    'space-before-blocks': 2,
    // require or disallow space before function opening parenthesis
    'space-before-function-paren': [2, 'never'],
    // require or disallow spaces inside parentheses
    'space-in-parens': 0,
    // require spaces around operators
    'space-infix-ops': 2,
    // require a space after return, throw, and case
    'space-return-throw-case': 2,
    // Require or disallow spaces before/after unary operators
    'space-unary-ops': 0,
    // require or disallow a space immediately following the // or /* in a comment
    'spaced-comment': [2, 'always', {
      'exceptions': ['-', '+'],
      'markers': ['=', '!']           // space here to support sprockets directives
    }],
    // require regex literals to be wrapped in parentheses
    'wrap-regex': 0
  }
};
<commit_msg>[eslint] Enforce rule 18.5<commit_after>module.exports = {
  'rules': {
    // enforce spacing inside array brackets
    'array-bracket-spacing': 0,
    // enforce one true brace style
    'brace-style': [2, '1tbs', {'allowSingleLine': true }],
    // require camel case names
    'camelcase': [2, {'properties': 'never'}],
    // enforce spacing before and after comma
    'comma-spacing': [2, {'before': false, 'after': true}],
    // enforce one true comma style
    'comma-style': [2, 'last'],
    // require or disallow padding inside computed properties
    'computed-property-spacing': 0,
    // enforces consistent naming when capturing the current execution context
    'consistent-this': 0,
    // enforce newline at the end of file, with no multiple empty lines
    'eol-last': 2,
    // require function expressions to have a name
    'func-names': 1,
    // enforces use of function declarations or expressions
    'func-style': 0,
    // this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
    'id-length': 0,
    // this option sets a specific tab width for your code
    'indent': [2, 2],
    // specify whether double or single quotes should be used in JSX attributes
    'jsx-quotes': 2,
    // enforces spacing between keys and values in object literal properties
    'key-spacing': [2, {'beforeColon': false, 'afterColon': true}],
    // enforces empty lines around comments
    'lines-around-comment': 0,
    // disallow mixed 'LF' and 'CRLF' as linebreaks
    'linebreak-style': 0,
    // specify the maximum depth callbacks can be nested
    'max-nested-callbacks': 0,
    // require a capital letter for constructors
    'new-cap': [2, {'newIsCap': true}],
    // disallow the omission of parentheses when invoking a constructor with no arguments
    'new-parens': 0,
    // allow/disallow an empty newline after var statement
    'newline-after-var': 0,
    // disallow use of the Array constructor
    'no-array-constructor': 0,
    // disallow use of the continue statement
    'no-continue': 0,
    // disallow comments inline after code
    'no-inline-comments': 0,
    // disallow if as the only statement in an else block
    'no-lonely-if': 0,
    // disallow mixed spaces and tabs for indentation
    'no-mixed-spaces-and-tabs': 2,
    // disallow multiple empty lines and only one newline at the end
    'no-multiple-empty-lines': [2, {'max': 2, 'maxEOF': 1}],
    // disallow nested ternary expressions
    'no-nested-ternary': 2,
    // disallow use of the Object constructor
    'no-new-object': 2,
    // disallow space between function identifier and application
    'no-spaced-func': 2,
    // disallow the use of ternary operators
    'no-ternary': 0,
    // disallow trailing whitespace at the end of lines
    'no-trailing-spaces': 2,
    // disallow dangling underscores in identifiers
    'no-underscore-dangle': 0,
    // disallow the use of Boolean literals in conditional expressions
    'no-unneeded-ternary': 0,
    // require or disallow padding inside curly braces
    'object-curly-spacing': 0,
    // allow just one var statement per function
    'one-var': [2, 'never'],
    // require assignment operator shorthand where possible or prohibit it entirely
    'operator-assignment': 0,
    // enforce operators to be placed before or after line breaks
    'operator-linebreak': 0,
    // enforce padding within blocks
    'padded-blocks': [2, 'never'],
    // require quotes around object literal property names
    'quote-props': 0,
    // specify whether double or single quotes should be used
    'quotes': [2, 'single', 'avoid-escape'],
    // require identifiers to match the provided regular expression
    'id-match': 0,
    // enforce spacing before and after semicolons
    'semi-spacing': [2, {'before': false, 'after': true}],
    // require or disallow use of semicolons instead of ASI
    'semi': [2, 'always'],
    // sort variables within the same declaration block
    'sort-vars': 0,
    // require a space before certain keywords
    'space-before-keywords': [2, 'always'],
    // require a space after certain keywords
    'space-after-keywords': [2, 'always'],
    // require or disallow space before blocks
    'space-before-blocks': 2,
    // require or disallow space before function opening parenthesis
    'space-before-function-paren': [2, 'never'],
    // require or disallow spaces inside parentheses
    'space-in-parens': 0,
    // require spaces around operators
    'space-infix-ops': 2,
    // require a space after return, throw, and case
    'space-return-throw-case': 2,
    // Require or disallow spaces before/after unary operators
    'space-unary-ops': 0,
    // require or disallow a space immediately following the // or /* in a comment
    'spaced-comment': [2, 'always', {
      'exceptions': ['-', '+'],
      'markers': ['=', '!']           // space here to support sprockets directives
    }],
    // require regex literals to be wrapped in parentheses
    'wrap-regex': 0
  }
};
<|endoftext|>