<commit_before>/**
 * Copyright (c) 2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * https://raw.github.com/facebook/regenerator/master/LICENSE file. An
 * additional grant of patent rights can be found in the PATENTS file in
 * the same directory.
 */

(function(
  // Reliable reference to the global object (i.e. window in browsers).
  global,

  // Dummy constructor that we use as the .constructor property for
  // functions that return Generator objects.
  GeneratorFunction,

  // Undefined value, more compressible than void 0.
  undefined
) {
  var hasOwn = Object.prototype.hasOwnProperty;

  if (global.wrapGenerator) {
    return;
  }

  function wrapGenerator(innerFn, outerFn, self, tryList) {
    return new Generator(innerFn, outerFn, self || null, tryList || []);
  }

  global.wrapGenerator = wrapGenerator;
  if (typeof exports !== "undefined") {
    exports.wrapGenerator = wrapGenerator;
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed";

  // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.
  var ContinueSentinel = {};

  var Gp = Generator.prototype;
  var GFp = GeneratorFunction.prototype = Object.create(Function.prototype);
  GFp.constructor = GeneratorFunction;
  GFp.prototype = Gp;
  Gp.constructor = GFp;

  wrapGenerator.mark = function(genFun) {
    genFun.__proto__ = GFp;
    genFun.prototype = Object.create(Gp);
    return genFun;
  };

  // Ensure isGeneratorFunction works when Function#name not supported.
  if (GeneratorFunction.name !== "GeneratorFunction") {
    GeneratorFunction.name = "GeneratorFunction";
  }

  wrapGenerator.isGeneratorFunction = function(genFun) {
    var ctor = genFun && genFun.constructor;
    return ctor ? GeneratorFunction.name === ctor.name : false;
  };

  function Generator(innerFn, outerFn, self, tryList) {
    var generator = outerFn ? Object.create(outerFn.prototype) : this;
    var context = new Context(tryList);
    var state = GenStateSuspendedStart;

    function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        throw new Error("Generator has already finished");
      }

      while (true) {
        var delegate = context.delegate;
        if (delegate) {
          try {
            var info = delegate.iterator[method](arg);

            // Delegate generator ran and handled its own exceptions so
            // regardless of what the method was, we continue as if it is
            // "next" with an undefined arg.
            method = "next";
            arg = undefined;

          } catch (uncaught) {
            context.delegate = null;

            // Like returning generator.throw(uncaught), but without the
            // overhead of an extra function call.
            method = "throw";
            arg = uncaught;

            continue;
          }

          if (info.done) {
            context[delegate.resultName] = info.value;
            context.next = delegate.nextLoc;
          } else {
            state = GenStateSuspendedYield;
            return info;
          }

          context.delegate = null;
        }

        if (method === "next") {
          if (state === GenStateSuspendedStart &&
              typeof arg !== "undefined") {
            // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
            throw new TypeError(
              "attempt to send " + JSON.stringify(arg) + " to newborn generator"
            );
          }

          if (state === GenStateSuspendedYield) {
            context.sent = arg;
          } else {
            delete context.sent;
          }

        } else if (method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw arg;
          }

          if (context.dispatchException(arg)) {
            // If the dispatched exception was caught by a catch block,
            // then let that catch block handle the exception normally.
            method = "next";
            arg = undefined;
          }
        }

        state = GenStateExecuting;

        try {
          var value = innerFn.call(self, context);

          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done
            ? GenStateCompleted
            : GenStateSuspendedYield;

          var info = {
            value: value,
            done: context.done
          };

          if (value === ContinueSentinel) {
            if (context.delegate && method === "next") {
              // Deliberately forget the last sent value so that we don't
              // accidentally pass it on to the delegate.
              arg = undefined;
            }
          } else {
            return info;
          }

        } catch (thrown) {
          state = GenStateCompleted;

          if (method === "next") {
            context.dispatchException(thrown);
          } else {
            arg = thrown;
          }
        }
      }
    }

    generator.next = invoke.bind(generator, "next");
    generator.throw = invoke.bind(generator, "throw");

    return generator;
  }

  Generator.prototype.toString = function() {
    return "[object Generator]";
  };

  function pushTryEntry(triple) {
    var entry = { tryLoc: triple[0] };

    if (1 in triple) {
      entry.catchLoc = triple[1];
    }

    if (2 in triple) {
      entry.finallyLoc = triple[2];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry, i) {
    var record = entry.completion || {};
    record.type = i === 0 ? "normal" : "return";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{ tryLoc: "root" }];
    tryList.forEach(pushTryEntry, this);
    this.reset();
  }

  wrapGenerator.keys = function(object) {
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
    keys.reverse();

    // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.
    return function next() {
      while (keys.length) {
        var key = keys.pop();
        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      }

      // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.
      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    var iterator = iterable;
    var Symbol = global.Symbol;
    if (Symbol && Symbol.iterator in iterable) {
      iterator = iterable[Symbol.iterator]();
    } else if (!isNaN(iterable.length)) {
      var i = -1;
      iterator = function next() {
        while (++i < iterable.length) {
          if (i in iterable) {
            next.value = iterable[i];
            next.done = false;
            return next;
          }
        };
        next.done = true;
        return next;
      };
      iterator.next = iterator;
    }
    return iterator;
  }
  wrapGenerator.values = values;

  Context.prototype = {
    constructor: Context,

    reset: function() {
      this.prev = 0;
      this.next = 0;
      this.sent = undefined;
      this.done = false;
      this.delegate = null;

      this.tryEntries.forEach(resetTryEntry);

      // Pre-initialize at least 20 temporary variables to enable hidden
      // class optimizations for simple generators.
      for (var tempIndex = 0, tempName;
           hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20;
           ++tempIndex) {
        this[tempName] = null;
      }
    },

    stop: function() {
      this.done = true;

      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;
      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },

    dispatchException: function(exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;
      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;
        return !!caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }

          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },

    _findFinallyEntry: function(finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc <= this.prev &&
            hasOwn.call(entry, "finallyLoc") && (
              entry.finallyLoc === finallyLoc ||
              this.prev < entry.finallyLoc)) {
          return entry;
        }
      }
    },

    abrupt: function(type, arg) {
      var entry = this._findFinallyEntry();
      var record = entry ? entry.completion : {};

      record.type = type;
      record.arg = arg;

      if (entry) {
        this.next = entry.finallyLoc;
      } else {
        this.complete(record);
      }

      return ContinueSentinel;
    },

    complete: function(record) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" ||
          record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = record.arg;
        this.next = "end";
      }

      return ContinueSentinel;
    },

    finish: function(finallyLoc) {
      var entry = this._findFinallyEntry(finallyLoc);
      return this.complete(entry.completion);
    },

    "catch": function(tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;
          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry, i);
          }
          return thrown;
        }
      }

      // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.
      throw new Error("illegal catch attempt");
    },

    delegateYield: function(iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      return ContinueSentinel;
    }
  };
}).apply(this, Function("return [this, function GeneratorFunction(){}]")());
<commit_msg>Copy runtime/dev.js from master for @@iterator support.<commit_after>/**
 * Copyright (c) 2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * https://raw.github.com/facebook/regenerator/master/LICENSE file. An
 * additional grant of patent rights can be found in the PATENTS file in
 * the same directory.
 */

(function(
  // Reliable reference to the global object (i.e. window in browsers).
  global,

  // Dummy constructor that we use as the .constructor property for
  // functions that return Generator objects.
  GeneratorFunction,

  // Undefined value, more compressible than void 0.
  undefined
) {
  var hasOwn = Object.prototype.hasOwnProperty;

  if (global.wrapGenerator) {
    return;
  }

  function wrapGenerator(innerFn, outerFn, self, tryList) {
    return new Generator(innerFn, outerFn, self || null, tryList || []);
  }

  global.wrapGenerator = wrapGenerator;
  if (typeof exports !== "undefined") {
    exports.wrapGenerator = wrapGenerator;
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed";

  // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.
  var ContinueSentinel = {};

  var Gp = Generator.prototype;
  var GFp = GeneratorFunction.prototype = Object.create(Function.prototype);
  GFp.constructor = GeneratorFunction;
  GFp.prototype = Gp;
  Gp.constructor = GFp;

  wrapGenerator.mark = function(genFun) {
    genFun.__proto__ = GFp;
    genFun.prototype = Object.create(Gp);
    return genFun;
  };

  // Ensure isGeneratorFunction works when Function#name not supported.
  if (GeneratorFunction.name !== "GeneratorFunction") {
    GeneratorFunction.name = "GeneratorFunction";
  }

  wrapGenerator.isGeneratorFunction = function(genFun) {
    var ctor = genFun && genFun.constructor;
    return ctor ? GeneratorFunction.name === ctor.name : false;
  };

  function Generator(innerFn, outerFn, self, tryList) {
    var generator = outerFn ? Object.create(outerFn.prototype) : this;
    var context = new Context(tryList);
    var state = GenStateSuspendedStart;

    function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        throw new Error("Generator has already finished");
      }

      while (true) {
        var delegate = context.delegate;
        if (delegate) {
          try {
            var info = delegate.iterator[method](arg);

            // Delegate generator ran and handled its own exceptions so
            // regardless of what the method was, we continue as if it is
            // "next" with an undefined arg.
            method = "next";
            arg = undefined;

          } catch (uncaught) {
            context.delegate = null;

            // Like returning generator.throw(uncaught), but without the
            // overhead of an extra function call.
            method = "throw";
            arg = uncaught;

            continue;
          }

          if (info.done) {
            context[delegate.resultName] = info.value;
            context.next = delegate.nextLoc;
          } else {
            state = GenStateSuspendedYield;
            return info;
          }

          context.delegate = null;
        }

        if (method === "next") {
          if (state === GenStateSuspendedStart &&
              typeof arg !== "undefined") {
            // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
            throw new TypeError(
              "attempt to send " + JSON.stringify(arg) + " to newborn generator"
            );
          }

          if (state === GenStateSuspendedYield) {
            context.sent = arg;
          } else {
            delete context.sent;
          }

        } else if (method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw arg;
          }

          if (context.dispatchException(arg)) {
            // If the dispatched exception was caught by a catch block,
            // then let that catch block handle the exception normally.
            method = "next";
            arg = undefined;
          }
        }

        state = GenStateExecuting;

        try {
          var value = innerFn.call(self, context);

          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done
            ? GenStateCompleted
            : GenStateSuspendedYield;

          var info = {
            value: value,
            done: context.done
          };

          if (value === ContinueSentinel) {
            if (context.delegate && method === "next") {
              // Deliberately forget the last sent value so that we don't
              // accidentally pass it on to the delegate.
              arg = undefined;
            }
          } else {
            return info;
          }

        } catch (thrown) {
          state = GenStateCompleted;

          if (method === "next") {
            context.dispatchException(thrown);
          } else {
            arg = thrown;
          }
        }
      }
    }

    generator.next = invoke.bind(generator, "next");
    generator.throw = invoke.bind(generator, "throw");

    return generator;
  }

  Gp[typeof Symbol === "function"
     && Symbol.iterator
     || "@@iterator"] = function() {
    return this;
  };

  Gp.toString = function() {
    return "[object Generator]";
  };

  function pushTryEntry(triple) {
    var entry = { tryLoc: triple[0] };

    if (1 in triple) {
      entry.catchLoc = triple[1];
    }

    if (2 in triple) {
      entry.finallyLoc = triple[2];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry, i) {
    var record = entry.completion || {};
    record.type = i === 0 ? "normal" : "return";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{ tryLoc: "root" }];
    tryList.forEach(pushTryEntry, this);
    this.reset();
  }

  wrapGenerator.keys = function(object) {
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
    keys.reverse();

    // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.
    return function next() {
      while (keys.length) {
        var key = keys.pop();
        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      }

      // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.
      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    var iterator = iterable;
    var Symbol = global.Symbol;
    if (Symbol && Symbol.iterator in iterable) {
      iterator = iterable[Symbol.iterator]();
    } else if (!isNaN(iterable.length)) {
      var i = -1;
      iterator = function next() {
        while (++i < iterable.length) {
          if (i in iterable) {
            next.value = iterable[i];
            next.done = false;
            return next;
          }
        };
        next.done = true;
        return next;
      };
      iterator.next = iterator;
    }
    return iterator;
  }
  wrapGenerator.values = values;

  Context.prototype = {
    constructor: Context,

    reset: function() {
      this.prev = 0;
      this.next = 0;
      this.sent = undefined;
      this.done = false;
      this.delegate = null;

      this.tryEntries.forEach(resetTryEntry);

      // Pre-initialize at least 20 temporary variables to enable hidden
      // class optimizations for simple generators.
      for (var tempIndex = 0, tempName;
           hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20;
           ++tempIndex) {
        this[tempName] = null;
      }
    },

    stop: function() {
      this.done = true;

      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;
      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },

    dispatchException: function(exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;
      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;
        return !!caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }

          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },

    _findFinallyEntry: function(finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc <= this.prev &&
            hasOwn.call(entry, "finallyLoc") && (
              entry.finallyLoc === finallyLoc ||
              this.prev < entry.finallyLoc)) {
          return entry;
        }
      }
    },

    abrupt: function(type, arg) {
      var entry = this._findFinallyEntry();
      var record = entry ? entry.completion : {};

      record.type = type;
      record.arg = arg;

      if (entry) {
        this.next = entry.finallyLoc;
      } else {
        this.complete(record);
      }

      return ContinueSentinel;
    },

    complete: function(record) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" ||
          record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = record.arg;
        this.next = "end";
      }

      return ContinueSentinel;
    },

    finish: function(finallyLoc) {
      var entry = this._findFinallyEntry(finallyLoc);
      return this.complete(entry.completion);
    },

    "catch": function(tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;
          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry, i);
          }
          return thrown;
        }
      }

      // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.
      throw new Error("illegal catch attempt");
    },

    delegateYield: function(iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      return ContinueSentinel;
    }
  };
}).apply(this, Function("return [this, function GeneratorFunction(){}]")());
<|endoftext|>


<commit_before>
$ViewDirective.$inject = ['$state', '$compile', '$controller', '$anchorScroll'];
function $ViewDirective(   $state,   $compile,   $controller,   $anchorScroll) {
  var directive = {
    restrict: 'ECA',
    terminal: true,
    link: function(scope, element, attr) {
      var viewScope, viewLocals,
        name = attr[directive.name] || attr.name || '',
        onloadExp = attr.onload || '';

      // Find the details of the parent view directive (if any) and use it
      // to derive our own qualified view name, then hang our own details
      // off the DOM so child directives can find it.
      var parent = element.parent().inheritedData('$uiView');
      if (name.indexOf('@') < 0) name  = name + '@' + (parent ? parent.state.name : '');
      var view = { name: name, state: null };
      element.data('$uiView', view);

      scope.$on('$stateChangeSuccess', updateView);
      updateView();

      function updateView() {
        var locals = $state.$current && $state.$current.locals[name];
        if (locals === viewLocals) return; // nothing to do

        // Destroy previous view scope (if any)
        if (viewScope) {
          viewScope.$destroy();
          viewScope = null;
        }

        if (locals) {
          viewLocals = locals;
          view.state = locals.$$state;

          element.html(locals.$template);
          // element.html('
' + name + '
' + locals.$template);
          var link = $compile(element.contents());
          viewScope = scope.$new();
          if (locals.$$controller) {
            locals.$scope = viewScope;
            // This is a 'directive controller'. need to allow element and attr injections (TBD: transcludeFn)
            locals.$element = element;
            locals.$attrs = attr;
            //store directive controller with distinct name on the element.data as per angular.js convention
            var controller = $controller(locals.$$controller, locals);
            element.data('$' + name+'Controller', controller);
          }
          link(viewScope);
          viewScope.$emit('$viewContentLoaded');
          viewScope.$eval(onloadExp);

          // TODO: This seems strange, shouldn't $anchorScroll listen for $viewContentLoaded if necessary?
          // $anchorScroll might listen on event...
          $anchorScroll();
        } else {
          viewLocals = null;
          view.state = null;
          element.html('');
        }
      }
    }
  };
  return directive;
}

angular.module('ui.state').directive('uiView', $ViewDirective);
<commit_msg>Revert "Allow element and attr injections"<commit_after>
$ViewDirective.$inject = ['$state', '$compile', '$controller', '$anchorScroll'];
function $ViewDirective(   $state,   $compile,   $controller,   $anchorScroll) {
  var directive = {
    restrict: 'ECA',
    terminal: true,
    link: function(scope, element, attr) {
      var viewScope, viewLocals,
        name = attr[directive.name] || attr.name || '',
        onloadExp = attr.onload || '';

      // Find the details of the parent view directive (if any) and use it
      // to derive our own qualified view name, then hang our own details
      // off the DOM so child directives can find it.
      var parent = element.parent().inheritedData('$uiView');
      if (name.indexOf('@') < 0) name  = name + '@' + (parent ? parent.state.name : '');
      var view = { name: name, state: null };
      element.data('$uiView', view);

      scope.$on('$stateChangeSuccess', updateView);
      updateView();

      function updateView() {
        var locals = $state.$current && $state.$current.locals[name];
        if (locals === viewLocals) return; // nothing to do

        // Destroy previous view scope (if any)
        if (viewScope) {
          viewScope.$destroy();
          viewScope = null;
        }

        if (locals) {
          viewLocals = locals;
          view.state = locals.$$state;

          element.html(locals.$template);
          // element.html('
' + name + '
' + locals.$template);
          var link = $compile(element.contents());
          viewScope = scope.$new();
          if (locals.$$controller) {
            locals.$scope = viewScope;
            var controller = $controller(locals.$$controller, locals);
            element.contents().data('$ngControllerController', controller);
          }
          link(viewScope);
          viewScope.$emit('$viewContentLoaded');
          viewScope.$eval(onloadExp);

          // TODO: This seems strange, shouldn't $anchorScroll listen for $viewContentLoaded if necessary?
          // $anchorScroll might listen on event...
          $anchorScroll();
        } else {
          viewLocals = null;
          view.state = null;
          element.html('');
        }
      }
    }
  };
  return directive;
}

angular.module('ui.state').directive('uiView', $ViewDirective);
<|endoftext|>


<commit_before>var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var nconf = require('nconf');
var nukible = require('./../nukible');
var sodium = require('sodium');
var keypress = require('keypress');

var config = new nconf.Provider({
  env: true,
  argv: true,
  store: {
    type: 'file',
    file: path.join(__dirname, 'config.json')
  }
});

var nuki = new nukible();
var appId = config.get('appId');
var appType = config.get('appType');
var name = config.get('name');
var nukiLocks = config.get('nukiLocks');

if (_.isNumber(appId) && _.isNumber(appType) && _.isString(name)) {
  handleKeyboard();
} else {
  var self = this;
  var appIdBuffer = new Buffer(4);
  sodium.api.randombytes_buf(appIdBuffer);

  appId = appIdBuffer.readUInt32LE();
  config.set("appId", appId);
  config.set("appType", 2);   // Nuki Fob
  config.set("name", "HB NFC Key " + appId);
  config.set("nukiLocks", {});
  config.save(function (err) {
    if (err) {
      console.log("Writing configuration failed", err);
    } else {
      reReadConfig.call(self);
      console.log("initial configuration saved");
      handleKeyboard();
    }
  });
}

function handleKeyboard() {

  var peripheralId;
  var firstLock;

  var nukiLockUuids = _.keys(nukiLocks);
  if (nukiLockUuids.length > 0) {
    peripheralId = _.first(nukiLockUuids);
    firstLock = nukiLocks[peripheralId];
  }

  // make `process.stdin` begin emitting "keypress" events
  keypress(process.stdin);

  // listen for the "keypress" event
  var allowCommands = true;
  var self = this;
  process.stdin.on('keypress', function (ch, key) {
    //console.log('got "keypress"', key);
      console.log("c: exit");
      console.log("p: pair");
      if (isPaired()) {
        console.log("l: lock");
        console.log("u: unlock");
      }
    if (key) {
      if (key.ctrl && key.name == 'c') {
        process.stdin.pause();
        process.exit();
      } else {
        if (allowCommands) {
          switch (key.name) {
          case 'p':
            if (!isPaired()) {
              allowCommands = false;
              startPairing(function (err, pairedLockData) {
                allowCommands = true;
              });
            }
            break;
          case 'l':
            if (isPaired()) {
              allowCommands = false;
              options = {
                appId: appId,
                appType: appType,
                name: name,
                nukiLock: firstLock,
                peripheralId: peripheralId
              };
              nuki.lock(options, function (err) {
                if (err) {
                  console.log("ERROR: locking the door failed", err);
                } else {
                  console.log("DOOR LOCKED.");
                }
                allowCommands = true;
              });
            }
            break;
          case 'u':
            if (isPaired()) {
              allowCommands = false;
              options = {
                appId: appId,
                appType: appType,
                name: name,
                nukiLock: firstLock,
                peripheralId: peripheralId
              };
              nuki.unlock(options, function (err) {
                if (err) {
                  console.log("ERROR: unlocking the door failed", err);
                } else {
                  console.log("DOOR UNLOCKED.");
                }
                allowCommands = true;
              });
            }
            break;
          case 'q':
            process.exit();
            break;
          }
        } else {
          console.log("previous command not finished");
        }
      }
    }
  });

  process.stdin.setRawMode(true);
  process.stdin.resume();
}

function reReadConfig() {
  appId = config.get('appId');
  appType = config.get('appType');
  name = config.get('name');
  nukiLocks = config.get('nukiLocks');
}

function isPaired() {
  if (_.isNumber(appId) && _.isNumber(appType) && _.isString(name)) {
    return !!(_.isObject(nukiLocks) && _.keys(nukiLocks).length > 0);
  } else {
    return false;
  }
}

function startPairing(callback) {
  var options = {
    appId: appId, appType: appType, name: name, nukiLocks: nukiLocks
  };

  nuki.pair(options, function (err, pairingData) {
    if (err) {
      console.log("Pairing failed:", err);
      callback(err);
    } else {
      console.log("Paired successfully.");
      nukiLocks[pairingData.peripheralId] = {
        nukiUuid: pairingData.nukiUuid,
        nukiAuthorizationId: pairingData.nukiAuthorizationId,
        sharedSecret: pairingData.sharedSecret
      };
      config.set("nukiLocks", nukiLocks);
      config.save(function (err) {
        if (err) {
          console.log("Writing configuration failed", err);
          callback(err);
        } else {
          callback(null, nukiLocks[pairingData.peripheralId]);
        }
      });
    }
  });
}
<commit_msg>moved usage before keypress handler<commit_after>var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var nconf = require('nconf');
var nukible = require('./../nukible');
var sodium = require('sodium');
var keypress = require('keypress');

var config = new nconf.Provider({
  env: true,
  argv: true,
  store: {
    type: 'file',
    file: path.join(__dirname, 'config.json')
  }
});

var nuki = new nukible();
var appId = config.get('appId');
var appType = config.get('appType');
var name = config.get('name');
var nukiLocks = config.get('nukiLocks');

if (_.isNumber(appId) && _.isNumber(appType) && _.isString(name)) {
  handleKeyboard();
} else {
  var self = this;
  var appIdBuffer = new Buffer(4);
  sodium.api.randombytes_buf(appIdBuffer);

  appId = appIdBuffer.readUInt32LE();
  config.set("appId", appId);
  config.set("appType", 2);   // Nuki Fob
  config.set("name", "HB NFC Key " + appId);
  config.set("nukiLocks", {});
  config.save(function (err) {
    if (err) {
      console.log("Writing configuration failed", err);
    } else {
      reReadConfig.call(self);
      console.log("initial configuration saved");
      handleKeyboard();
    }
  });
}

function handleKeyboard() {

  var peripheralId;
  var firstLock;

  var nukiLockUuids = _.keys(nukiLocks);
  if (nukiLockUuids.length > 0) {
    peripheralId = _.first(nukiLockUuids);
    firstLock = nukiLocks[peripheralId];
  }

  // make `process.stdin` begin emitting "keypress" events
  keypress(process.stdin);

  // listen for the "keypress" event
  var allowCommands = true;
  console.log("c: exit");
  console.log("p: pair");
  if (isPaired()) {
    console.log("l: lock");
    console.log("u: unlock");
  }
  process.stdin.on('keypress', function (ch, key) {
    //console.log('got "keypress"', key);
    if (key) {
      if (key.ctrl && key.name === 'c') {
        process.stdin.pause();
        process.exit();
      } else {
        if (allowCommands) {
          switch (key.name) {
          case 'p':
            if (!isPaired()) {
              allowCommands = false;
              startPairing(function (err, pairedLockData) {
                allowCommands = true;
              });
            }
            break;
          case 'l':
            if (isPaired()) {
              allowCommands = false;
              options = {
                appId: appId,
                appType: appType,
                name: name,
                nukiLock: firstLock,
                peripheralId: peripheralId
              };
              nuki.lock(options, function (err) {
                if (err) {
                  console.log("ERROR: locking the door failed", err);
                } else {
                  console.log("DOOR LOCKED.");
                }
                allowCommands = true;
              });
            }
            break;
          case 'u':
            if (isPaired()) {
              allowCommands = false;
              options = {
                appId: appId,
                appType: appType,
                name: name,
                nukiLock: firstLock,
                peripheralId: peripheralId
              };
              nuki.unlock(options, function (err) {
                if (err) {
                  console.log("ERROR: unlocking the door failed", err);
                } else {
                  console.log("DOOR UNLOCKED.");
                }
                allowCommands = true;
              });
            }
            break;
          case 'q':
            process.exit();
            break;
          }
        } else {
          console.log("previous command not finished");
        }
      }
    }
  });

  process.stdin.setRawMode(true);
  process.stdin.resume();
}

function reReadConfig() {
  appId = config.get('appId');
  appType = config.get('appType');
  name = config.get('name');
  nukiLocks = config.get('nukiLocks');
}

function isPaired() {
  if (_.isNumber(appId) && _.isNumber(appType) && _.isString(name)) {
    return !!(_.isObject(nukiLocks) && _.keys(nukiLocks).length > 0);
  } else {
    return false;
  }
}

function startPairing(callback) {
  var options = {
    appId: appId, appType: appType, name: name, nukiLocks: nukiLocks
  };

  nuki.pair(options, function (err, pairingData) {
    if (err) {
      console.log("Pairing failed:", err);
      callback(err);
    } else {
      console.log("Paired successfully.");
      nukiLocks[pairingData.peripheralId] = {
        nukiUuid: pairingData.nukiUuid,
        nukiAuthorizationId: pairingData.nukiAuthorizationId,
        sharedSecret: pairingData.sharedSecret
      };
      config.set("nukiLocks", nukiLocks);
      config.save(function (err) {
        if (err) {
          console.log("Writing configuration failed", err);
          callback(err);
        } else {
          callback(null, nukiLocks[pairingData.peripheralId]);
        }
      });
    }
  });
}
<|endoftext|>


<commit_before>'use strict';

window.App = {};

$(function() {

	var initializeAuthors = function() {
		var authorCollection = new App.AuthorCollection([{
			name : 'sekai',
			id   : 'sekai',
			words: ['this', 'is', 'sample']
		}]);

		authorCollection.each(function(author) {
			author.save();
		});

		return authorCollection.models;
	};

	App.authorCollection = new App.AuthorCollection();
	App.mainContainer    = new App.Container({
		el: '#mainContainer'
	});

	App.authorCollection.fetch().then(function(authors) {
		if(authors.length === 0) {
			var models = initializeAuthors();
			App.authorCollection.reset(models);
		}

		var urlRegExp = /http:\/\/[htz]?\.?livetube\.cc\/([^\/]*)\/[^\/]*/;
		var query = {
			active  : true,
			windowId: chrome.windows.WINDOW_ID_CURRENT
		};

		chrome.tabs.query(query, function(tabs) {
			var currentTab = tabs[0];
			var currentURL = currentTab.url;
			var match = urlRegExp.exec(currentURL);

			if(match) {
				App.authorId = decodeURI(match[1]);
				App.tabId    = currentTab.id;

				var author = App.authorCollection.get(App.authorId);

				App.isNewAuthor = (typeof author === 'undefined');
			}

			App.router = new App.Router();
			Backbone.history.start();
		});
	});
});
<commit_msg>delete debug code<commit_after>'use strict';

window.App = {};

$(function() {

	App.authorCollection = new App.AuthorCollection();
	App.mainContainer    = new App.Container({
		el: '#mainContainer'
	});

	App.authorCollection.fetch().then(function(authors) {
		var urlRegExp = /http:\/\/[htz]?\.?livetube\.cc\/([^\/]*)\/[^\/]*/;
		var query = {
			active  : true,
			windowId: chrome.windows.WINDOW_ID_CURRENT
		};

		chrome.tabs.query(query, function(tabs) {
			var currentTab = tabs[0];
			var currentURL = currentTab.url;
			var match = urlRegExp.exec(currentURL);

			if(match) {
				App.authorId = decodeURI(match[1]);
				App.tabId    = currentTab.id;

				var author = App.authorCollection.get(App.authorId);

				App.isNewAuthor = (typeof author === 'undefined');
			}

			App.router = new App.Router();
			Backbone.history.start();
		});
	});
});
<|endoftext|>


<commit_before>/*jslint browser: true, node: true */
/*global window */

/*!

   Thumbnail image plugin for Flowplayer HTML5

   Copyright (c) 2015-2017, Flowplayer Drive Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   requires:
   - Flowplayer HTML5 version 6.x or greater
   revision: $GIT_ID$

*/
(function () {
    "use strict";
    var extension = function (flowplayer) {

        flowplayer(function (api, root) {
            var common = flowplayer.common,
                bean = flowplayer.bean,
                extend = flowplayer.extend,
                support = flowplayer.support,
                timeline = common.find('.fp-timeline', root)[0],
                timelineTooltip = common.find('.fp-time' + (flowplayer.version.indexOf('6.') === 0
                    ? 'line-tooltip'
                    : 'stamp'), root)[0];

            if (support.touch || !support.inlineVideo) {
                return;
            }

            api.on('ready', function (_ev, a, video) {
                // cleanup
                bean.off(root, '.thumbnails');
                common.css(timelineTooltip, {
                    width: '',
                    height: '',
                    'background-image': '',
                    'background-repeat': '',
                    'background-size': '',
                    'background-position': '',
                    'border': '',
                    'text-shadow': ''
                });

                var c = extend({}, a.conf.thumbnails, video.thumbnails),
                    template = c.template,
                    sprite = template.indexOf('{time}') < 0;

                if (!template || (sprite && (!c.rows || !c.columns || !c.width || !c.height))) {
                    return;
                }

                var height = sprite
                        ? c.height / c.rows
                        : c.height || 80,
                    engine = common.find('.fp-engine', root)[0],
                    ratio = (video.height || common.height(engine)) / (video.width || common.width(engine)),
                    width = sprite
                        ? c.width / c.columns
                        : height / ratio,
                    interval = c.interval || 1,
                    time_format = c.time_format || function (t) {
                        return t;
                    },
                    startIndex = typeof c.startIndex === 'number'
                        ? c.startIndex
                        : 1,
                    thumb = c.lazyload !== false
                        ? new Image()
                        : null,
                    preloadImages = function (max, start) {
                        max = Math.floor(max / interval + start);
                        function load() {
                            if (start > max) {
                                return;
                            }
                            var img = new Image();
                            img.src = template.replace('{time}', time_format(start));
                            img.onload = function () {
                                start += 1;
                                load();
                            };
                        }
                        load();
                    };

                if (c.preload) {
                    preloadImages(video.duration, startIndex);
                }

                bean.on(root, 'mousemove.thumbnails', '.fp-timeline', function (ev) {
                    var x = ev.pageX || ev.clientX,
                        delta = x - common.offset(timeline).left,
                        percentage = delta / common.width(timeline),
                        seconds = Math.round(percentage * api.video.duration),
                        url,
                        displayThumb = function () {
                            var css = {
                                width: width + 'px',
                                height: height + 'px',
                                'background-image': "url('" + url + "')",
                                'background-repeat': 'no-repeat',
                                border: '1px solid #333',
                                'text-shadow': '1px 1px #000'
                            };
                            if (sprite) {
                                var left = Math.floor(seconds % c.columns) * -width,
                                    top = Math.floor(seconds / c.columns) * -height;
                                css['background-position'] = left + 'px ' + top + 'px';
                            } else {
                                extend(css, {
                                    'background-size': 'cover',
                                    'background-position': 'center'
                                });
                            }
                            common.css(timelineTooltip, css);
                        };

                    // 2nd condition safeguards at out of range retrieval attempts
                    if (seconds < 0 || seconds > Math.round(api.video.duration)) {
                        return;
                    }
                    // enables greater interval than one second between thumbnails
                    seconds = Math.floor(seconds / interval);

                    // {time} template expected to start at 1, video time/first frame starts at 0
                    url = template.replace('{time}', time_format(seconds + startIndex));

                    if (c.lazyload !== false) {
                        thumb.src = url;
                        bean.on(thumb, 'load', displayThumb);
                    } else {
                        displayThumb();
                    }
                });
            });

        });
    };

    if (typeof module === 'object' && module.exports) {
        module.exports = extension;
    } else if (window.flowplayer) {
        extension(window.flowplayer);
    }
}());
<commit_msg>Make thumbnail size responsive (#15)<commit_after>/*jslint browser: true, node: true */
/*global window */

/*!

   Thumbnail image plugin for Flowplayer HTML5

   Copyright (c) 2015-2017, Flowplayer Drive Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   requires:
   - Flowplayer HTML5 version 6.x or greater
   revision: $GIT_ID$

*/
(function () {
    "use strict";
    var extension = function (flowplayer) {

        flowplayer(function (api, root) {
            var common = flowplayer.common,
                bean = flowplayer.bean,
                extend = flowplayer.extend,
                support = flowplayer.support,
                timeline = common.find('.fp-timeline', root)[0],
                timelineTooltip = common.find('.fp-time' + (flowplayer.version.indexOf('6.') === 0
                    ? 'line-tooltip'
                    : 'stamp'), root)[0];

            if (support.touch || !support.inlineVideo) {
                return;
            }

            api.on('ready', function (_ev, a, video) {
                // cleanup
                bean.off(root, '.thumbnails');
                common.css(timelineTooltip, {
                    width: '',
                    height: '',
                    'background-image': '',
                    'background-repeat': '',
                    'background-size': '',
                    'background-position': '',
                    'border': '',
                    'text-shadow': ''
                });

                var c = extend({
                        lazyload: true,
                        responsive: true
                    }, a.conf.thumbnails, video.thumbnails),
                    template = c.template,
                    sprite = template.indexOf('{time}') < 0;

                if (!template || (sprite && (!c.rows || !c.columns || !c.width || !c.height))) {
                    return;
                }

                var height = sprite
                        ? c.height / c.rows
                        : c.height || 80,
                    engine = common.find('.fp-engine', root)[0],
                    ratio = (video.height || common.height(engine)) / (video.width || common.width(engine)),
                    width = sprite
                        ? c.width / c.columns
                        : height / ratio,
                    interval = c.interval || 1,
                    time_format = c.time_format || function (t) {
                        return t;
                    },
                    startIndex = typeof c.startIndex === 'number'
                        ? c.startIndex
                        : 1,
                    thumb = c.lazyload
                        ? new Image()
                        : null,
                    preloadImages = function (max, start) {
                        max = Math.floor(max / interval + start);
                        function load() {
                            if (start > max) {
                                return;
                            }
                            var img = new Image();
                            img.src = template.replace('{time}', time_format(start));
                            img.onload = function () {
                                start += 1;
                                load();
                            };
                        }
                        load();
                    };

                if (c.preload) {
                    preloadImages(video.duration, startIndex);
                }

                bean.on(root, 'mousemove.thumbnails', '.fp-timeline', function (ev) {
                    var x = ev.pageX || ev.clientX,
                        delta = x - common.offset(timeline).left,
                        percentage = delta / common.width(timeline),
                        seconds = Math.round(percentage * api.video.duration),
                        url,
                        displayThumb = function () {
                            var scale = (c.responsive && common.hasClass(root, 'is-small'))
                                    ? 0.7
                                    : (c.responsive && common.hasClass(root, 'is-tiny'))
                                        ? 0.6
                                        : 1,
                                css = {
                                    width: (width * scale) + 'px',
                                    height: (height * scale) + 'px',
                                    'background-image': "url('" + url + "')",
                                    'background-repeat': 'no-repeat',
                                    border: '1px solid #333',
                                    'text-shadow': '1px 1px #000'
                                };
                            if (sprite) {
                                var left = Math.floor(seconds % c.columns) * -width - (width - width * scale) / 2,
                                    top = Math.floor(seconds / c.columns) * -height - (height - height * scale) / 2;
                                css['background-position'] = left + 'px ' + top + 'px';
                            } else {
                                extend(css, {
                                    'background-size': 'cover',
                                    'background-position': 'center'
                                });
                            }
                            common.css(timelineTooltip, css);
                        };

                    // 2nd condition safeguards at out of range retrieval attempts
                    if (seconds < 0 || seconds > Math.round(api.video.duration)) {
                        return;
                    }
                    // enables greater interval than one second between thumbnails
                    seconds = Math.floor(seconds / interval);

                    // {time} template expected to start at 1, video time/first frame starts at 0
                    url = template.replace('{time}', time_format(seconds + startIndex));

                    if (c.lazyload !== false) {
                        thumb.src = url;
                        bean.on(thumb, 'load', displayThumb);
                    } else {
                        displayThumb();
                    }
                });
            });

        });
    };

    if (typeof module === 'object' && module.exports) {
        module.exports = extension;
    } else if (window.flowplayer) {
        extension(window.flowplayer);
    }
}());
<|endoftext|>


<commit_before>/**
 * @file XML XPath child search operator
 * @since 1.0.1
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_START*/
/*global _gpfAssert*/ // Assertion method
/*global _gpfArrayTail*/
/*global _gpfDefine*/
/*global _GpfXmlXPathBase*/
/*global _gpfXmlXpathConcatNodes*/
/*exported _GpfXmlXPathSub*/ // gpf.xml.xpath.Sub
/*#endif*/

/**
 * Implementation of the / operator
 *
 * @class gpf.xml.xpath.Sub
 * @extend gpf.xml.xpath.Base
 * @since 1.0.1
 */
var _GpfXmlXPathSub = _gpfDefine({
    $class: "gpf.xml.xpath.Sub",
    $extend: _GpfXmlXPathBase,

    _lookupChildNodes: function (operator, childNodes, namespaces) {
        var nodes = [];
        if (childNodes) {
            childNodes.forEach(function (child) {
                nodes = _gpfXmlXpathConcatNodes(nodes, operator(child, namespaces));
            });
        }
        return nodes;
    },

    _lookup: function (operator, node, namespaces) {
        return _gpfXmlXpathConcatNodes(
            this._lookupChildNodes(operator, node.getChildNodes(), namespaces),
            this._lookupChildNodes(operator, node.getAttributes(), namespaces)
        );
    },

    _getOperator: function () {
        _gpfAssert(!_gpfArrayTail(this._children).length, "Only one child operator expected");
        return this._children[_GPF_START];
    },

    /**
     * @inheritdoc
     * @since 1.0.1
     */
    execute: function (contextNode, namespaces) {
        return this._lookup(this._getOperator(), contextNode, namespaces);
    }
});
<commit_msg>Implements toString & relative search (#326)<commit_after>/**
 * @file XML XPath child search operator
 * @since 1.0.1
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_START*/
/*global _gpfAssert*/ // Assertion method
/*global _gpfArrayTail*/
/*global _gpfDefine*/
/*global _GpfXmlXPathBase*/
/*global _gpfXmlXpathConcatNodes*/
/*exported _GpfXmlXPathSub*/ // gpf.xml.xpath.Sub
/*#endif*/

function _gpfXmlXPathGetRoot (contextNode) {
    var current,
        parent = contextNode;
    while (parent) {
        current = parent;
        parent = current.getParentNode();
    }
    return current;
}

var _GpfXmlXPathSub = _gpfDefine({
    $class: "gpf.xml.xpath.Sub",
    $extend: _GpfXmlXPathBase,

    _relative: true,

    _lookupChildNodes: function (operator, childNodes, namespaces) {
        var nodes = [];
        if (childNodes) {
            childNodes.forEach(function (child) {
                nodes = _gpfXmlXpathConcatNodes(nodes, operator(child, namespaces));
            });
        }
        return nodes;
    },

    _lookup: function (operator, node, namespaces) {
        return _gpfXmlXpathConcatNodes(
            this._lookupChildNodes(operator, node.getChildNodes(), namespaces),
            this._lookupChildNodes(operator, node.getAttributes(), namespaces)
        );
    },

    _getOperator: function () {
        _gpfAssert(!_gpfArrayTail(this._children).length, "Only one child operator expected");
        return this._children[_GPF_START];
    },

    resolveContextNode: function (contextNode) {
        if (this._relative) {
            return contextNode;
        }
        return _gpfXmlXPathGetRoot(contextNode);
    },

    /**
     * @inheritdoc
     * @since 1.0.1
     */
    execute: function (contextNode, namespaces) {
        return this._lookup(this._getOperator(), this.resolveContextNode(contextNode), namespaces);
    },

    _toSearchString: function () {
        return "/" + this._children[0].toString();
    },

    toString: function () {
        var searchString = this._toSearchString();
        if (this._relative) {
            return "." + searchString;
        }
        return searchString;
    },

    /**
     * Implementation of the / operator
     *
     * @constructor gpf.xml.xpath.Sub
     * @param {Boolean} relative Search is relative to context node (or from the root)
     * @extend gpf.xml.xpath.Base
     * @since 1.0.1
     */
    constructor: function (relative) {
        this.$super();
        this._relative = relative;
    }
});
<|endoftext|>


<commit_before>/**
 * Created by Aaron on 7/3/2015.
 */

import Promise from 'bluebird';

let yieldHandlers = [];

export function isThenable( obj ) {
    return obj !== void 0 && obj !== null && (obj instanceof Promise || typeof obj.then === 'function');
}

export function isGenerator( obj ) {
    return 'function' === typeof obj.next && 'function' === typeof obj.throw;
}

export function isGeneratorFunction( obj ) {
    if( !obj.constructor ) {
        return false;

    } else if( 'GeneratorFunction' === obj.constructor.name ||
               'GeneratorFunction' === obj.constructor.displayName ) {
        return true;

    } else {
        return isGenerator( obj.constructor.prototype );
    }
}

class YieldException extends TypeError {
}

function objectToPromise( obj ) {
    var results = new obj.constructor();
    var promises = [];

    for( let key of Object.keys( obj ) ) {
        let promise = toPromise.call( this, obj[key] );

        if( promise && isThenable( promise ) ) {
            results[key] = void 0;

            promises.push( promise.then( function( res ) {
                results[key] = res;
            } ) );

        } else {
            results[key] = obj[key];
        }
    }

    return Promise.all( promises ).return( results );
}

function resolveGenerator( gen ) {
    return new Promise( ( resolve, reject ) => {

        //Just in case
        if( typeof gen === 'function' ) {
            gen = gen();
        }

        if( !gen || !isGenerator( gen ) ) {
            return Promise.resolve( gen );

        } else {
            let next = ret => {
                if( ret.done ) {
                    return resolve( ret.value );

                } else {
                    var value = toPromise.call( this, ret.value, true );

                    if( isThenable( value ) ) {
                        return value.then( onFulfilled ).catch( onRejected );

                    } else {
                        let err = new TypeError( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${ret.value}"` );

                        return onRejected( err );
                    }
                }
            };

            function onFulfilled( res ) {
                try {
                    next( gen.next( res ) );

                } catch( e ) {
                    return reject( e );
                }
            }

            function onRejected( err ) {
                try {
                    next( gen.throw( err ) );

                } catch( e ) {
                    return reject( e );
                }
            }

            onFulfilled();
        }
    } );
}

function toPromise( value, strict ) {
    if( isThenable( value ) ) {
        return value;

    } else if( Array.isArray( value ) ) {
        return Promise.all( value.map( val => {
            return toPromise.call( this, val );
        } ) );

    } else if( typeof value === 'object' && value !== null ) {
        if( isGenerator( value ) ) {
            return resolveGenerator.call( this, value );

        } else {
            return objectToPromise.call( this, value );
        }

    } else if( typeof value === 'function' ) {
        if( isGeneratorFunction( value ) ) {
            return Promise.coroutine( value )();

        } else {
            //Thunks
            return new Promise( ( resolve, reject ) => {
                try {
                    value.call( this, ( err, ...res ) => {
                        if( err ) {
                            reject( err );

                        } else if( res.length > 1 ) {
                            resolve( res );

                        } else {
                            resolve( res[0] );
                        }
                    } );

                } catch( err ) {
                    reject( err );
                }
            } );
        }

    } else if( yieldHandlers.length > 0 ) {
        for( let handler of yieldHandlers ) {
            let res = handler.call( this, value );

            if( isThenable( res ) ) {
                return res;
            }
        }

    } else if( strict ) {
        throw new YieldException( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${value}"` );

    } else {
        return Promise.resolve( value );
    }
}

export function addYieldHandler( handler ) {
    if( typeof handler !== 'function' ) {
        throw new TypeError( 'yield handler is not a function' );

    } else {
        yieldHandlers.push( handler );
    }
}

let addedYieldHandler = false;

if( !addedYieldHandler ) {
    Promise.coroutine.addYieldHandler( function( value ) {
        try {
            return toPromise.call( this, value, true );

        } catch( err ) {
            if( err instanceof YieldException ) {
                return void 0;

            } else {
                return Promise.reject( err );
            }
        }
    } );

    addedYieldHandler = true;
}

export default {
               addYieldHandler,
               isThenable,
    isPromise: isThenable,
               isGenerator,
               isGeneratorFunction
};
<commit_msg>src: Wrap generator next in a try-catch block to catch YieldExceptions and pass them along correctly instead of breakout out... somewhere.<commit_after>/**
 * Created by Aaron on 7/3/2015.
 */

import Promise from 'bluebird';

let yieldHandlers = [];

export function isThenable( obj ) {
    return obj !== void 0 && obj !== null && (obj instanceof Promise || typeof obj.then === 'function');
}

export function isGenerator( obj ) {
    return 'function' === typeof obj.next && 'function' === typeof obj.throw;
}

export function isGeneratorFunction( obj ) {
    if( !obj.constructor ) {
        return false;

    } else if( 'GeneratorFunction' === obj.constructor.name ||
               'GeneratorFunction' === obj.constructor.displayName ) {
        return true;

    } else {
        return isGenerator( obj.constructor.prototype );
    }
}

class YieldException extends TypeError {
}

function objectToPromise( obj ) {
    var results = new obj.constructor();
    var promises = [];

    for( let key of Object.keys( obj ) ) {
        let promise = toPromise.call( this, obj[key] );

        if( promise && isThenable( promise ) ) {
            results[key] = void 0;

            promises.push( promise.then( function( res ) {
                results[key] = res;
            } ) );

        } else {
            results[key] = obj[key];
        }
    }

    return Promise.all( promises ).return( results );
}

function resolveGenerator( gen ) {
    return new Promise( ( resolve, reject ) => {

        //Just in case
        if( typeof gen === 'function' ) {
            gen = gen();
        }

        if( !gen || !isGenerator( gen ) ) {
            return Promise.resolve( gen );

        } else {
            let next = ret => {
                if( ret.done ) {
                    return resolve( ret.value );

                } else {
                    try {
                        var value = toPromise.call( this, ret.value, true );

                        if( isThenable( value ) ) {
                            return value.then( onFulfilled ).catch( onRejected );

                        } else {
                            let err = new TypeError( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${ret.value}"` );

                            return onRejected( err );
                        }

                    } catch( err ) {
                        return onRejected( err );
                    }
                }
            };

            function onFulfilled( res ) {
                try {
                    next( gen.next( res ) );

                } catch( e ) {
                    return reject( e );
                }
            }

            function onRejected( err ) {
                try {
                    next( gen.throw( err ) );

                } catch( e ) {
                    return reject( e );
                }
            }

            onFulfilled();
        }
    } );
}

function toPromise( value, strict ) {
    if( isThenable( value ) ) {
        return value;

    } else if( Array.isArray( value ) ) {
        return Promise.all( value.map( val => {
            return toPromise.call( this, val );
        } ) );

    } else if( typeof value === 'object' && value !== null ) {
        if( isGenerator( value ) ) {
            return resolveGenerator.call( this, value );

        } else {
            return objectToPromise.call( this, value );
        }

    } else if( typeof value === 'function' ) {
        if( isGeneratorFunction( value ) ) {
            return Promise.coroutine( value )();

        } else {
            //Thunks
            return new Promise( ( resolve, reject ) => {
                try {
                    value.call( this, ( err, ...res ) => {
                        if( err ) {
                            reject( err );

                        } else if( res.length > 1 ) {
                            resolve( res );

                        } else {
                            resolve( res[0] );
                        }
                    } );

                } catch( err ) {
                    reject( err );
                }
            } );
        }

    } else if( yieldHandlers.length > 0 ) {
        for( let handler of yieldHandlers ) {
            let res = handler.call( this, value );

            if( isThenable( res ) ) {
                return res;
            }
        }

    } else if( strict ) {
        throw new YieldException( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${value}"` );

    } else {
        return Promise.resolve( value );
    }
}

export function addYieldHandler( handler ) {
    if( typeof handler !== 'function' ) {
        throw new TypeError( 'yield handler is not a function' );

    } else {
        yieldHandlers.push( handler );
    }
}

let addedYieldHandler = false;

if( !addedYieldHandler ) {
    Promise.coroutine.addYieldHandler( function( value ) {
        try {
            return toPromise.call( this, value, true );

        } catch( err ) {
            if( err instanceof YieldException ) {
                return void 0;

            } else {
                return Promise.reject( err );
            }
        }
    } );

    addedYieldHandler = true;
}

export default {
               addYieldHandler,
               isThenable,
    isPromise: isThenable,
               isGenerator,
               isGeneratorFunction
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { withState, withSidebar, withToolbar, withAutoMarkdown, withUniqueId, useBlocks } from './editor-decorators';
import { Editor } from 'slate';
import { setKeyGenerator } from 'slate/lib/utils/generate-key';
import shortId from 'shortid';
import './style.less';
setKeyGenerator(shortId.generate);

const options = {
  defaultNode: 'paragraph',
  toolbarMarks: [
    { type: 'bold', icon: 'bold' },
    { type: 'italic', icon: 'italic' },
    { type: 'underlined', icon: 'underline' },
    { type: 'code', icon: 'code' },
  ],
  toolbarTypes: [
    { type: 'heading-one', icon: 'header' },
    { type: 'heading-two', icon: 'header' },
    { type: 'block-quote', icon: 'quote-left' },
    { type: 'numbered-list', icon: 'list-ol' },
    { type: 'bulleted-list', icon: 'list-ul' },
  ],
  sidebarTypes: [],
  nodes: {
    paragraph: ({ children }) =>
{children}
,
    'block-quote': ({ children }) =>
{children}
,
    'bulleted-list': ({ children }) =>
{children}
,
    'numbered-list': ({ children, attributes }) =>
{children}
,
    'heading-one': ({ children }) =>
{children}
,
    'heading-two': ({ children }) =>
{children}
,
    'heading-three': ({ children }) =>
{children}
,
    'heading-four': ({ children }) =>
{children}
,
    'heading-five': ({ children }) =>
{children}
,
    'heading-six': ({ children }) =>
{children}
,
    'bulleted-list-item': ({ children }) =>
{children}
,
    'numbered-list-item': ({ children }) =>
{children}
,
  },
  marks: {
    bold: ({ children }) => {children},
    code: ({ children }) => {children},
    italic: ({ children }) => {children},
    underlined: ({ children }) => {children},
  },
  getMarkdownType: (chars) => {
    switch (chars) {
      case '*':
      case '-':
      case '+': return 'bulleted-list-item';
      case '>': return 'block-quote';
      case '#': return 'heading-one';
      case '##': return 'heading-two';
      case '###': return 'heading-three';
      case '####': return 'heading-four';
      case '#####': return 'heading-five';
      case '######': return 'heading-six';
      case '1.': return 'numbered-list-item';
      default: return null;
    }
  },
};

@withUniqueId()
@withState({ terse: true })
@useBlocks(options)
@withAutoMarkdown(options)
@withToolbar(options)
@withSidebar(options)
export default class SlateEditor extends Component {
  static propTypes = {
    readOnly: PropTypes.bool,
    children: PropTypes.node,
    value: PropTypes.object,
    onChange: PropTypes.func,
    marks: PropTypes.object,
    nodes: PropTypes.object,
    autoMarkDownKeyDown: PropTypes.func,
    plugins: PropTypes.array,
    className: PropTypes.string,
  }
  render = () => {
    const { children, value, onChange, readOnly, marks, nodes, plugins, className, spellcheck } = this.props;
    return (

        {children}
        <Editor
          spellcheck={spellcheck || false}
          readOnly={readOnly}
          plugins={plugins}
          schema={{ marks, nodes }}
          state={value}
          onChange={onChange}
        />

    );
  }
}
<commit_msg>small fix on slate<commit_after>import React, { Component, PropTypes } from 'react';
import { withState, withSidebar, withToolbar, withAutoMarkdown, withUniqueId, useBlocks } from './editor-decorators';
import { Editor } from 'slate';
import './style.less';

const options = {
  defaultNode: 'paragraph',
  toolbarMarks: [
    { type: 'bold', icon: 'bold' },
    { type: 'italic', icon: 'italic' },
    { type: 'underlined', icon: 'underline' },
    { type: 'code', icon: 'code' },
  ],
  toolbarTypes: [
    { type: 'heading-one', icon: 'header' },
    { type: 'heading-two', icon: 'header' },
    { type: 'block-quote', icon: 'quote-left' },
    { type: 'numbered-list', icon: 'list-ol' },
    { type: 'bulleted-list', icon: 'list-ul' },
  ],
  sidebarTypes: [],
  nodes: {
    paragraph: ({ children }) =>
{children}
,
    'block-quote': ({ children }) =>
{children}
,
    'bulleted-list': ({ children }) =>
{children}
,
    'numbered-list': ({ children, attributes }) =>
{children}
,
    'heading-one': ({ children }) =>
{children}
,
    'heading-two': ({ children }) =>
{children}
,
    'heading-three': ({ children }) =>
{children}
,
    'heading-four': ({ children }) =>
{children}
,
    'heading-five': ({ children }) =>
{children}
,
    'heading-six': ({ children }) =>
{children}
,
    'bulleted-list-item': ({ children }) =>
{children}
,
    'numbered-list-item': ({ children }) =>
{children}
,
  },
  marks: {
    bold: ({ children }) => {children},
    code: ({ children }) => {children},
    italic: ({ children }) => {children},
    underlined: ({ children }) => {children},
  },
  getMarkdownType: (chars) => {
    switch (chars) {
      case '*':
      case '-':
      case '+': return 'bulleted-list-item';
      case '>': return 'block-quote';
      case '#': return 'heading-one';
      case '##': return 'heading-two';
      case '###': return 'heading-three';
      case '####': return 'heading-four';
      case '#####': return 'heading-five';
      case '######': return 'heading-six';
      case '1.': return 'numbered-list-item';
      default: return null;
    }
  },
};

@withUniqueId()
@withState({ terse: true })
@useBlocks(options)
@withAutoMarkdown(options)
@withToolbar(options)
@withSidebar(options)
export default class SlateEditor extends Component {
  static propTypes = {
    readOnly: PropTypes.bool,
    children: PropTypes.node,
    value: PropTypes.object,
    onChange: PropTypes.func,
    marks: PropTypes.object,
    nodes: PropTypes.object,
    autoMarkDownKeyDown: PropTypes.func,
    plugins: PropTypes.array,
    className: PropTypes.string,
  }
  render = () => {
    const { children, value, onChange, readOnly, marks, nodes, plugins, className, spellcheck } = this.props;
    return (

        {children}
        <Editor
          spellcheck={spellcheck || false}
          readOnly={readOnly}
          plugins={plugins}
          schema={{ marks, nodes }}
          state={value}
          onChange={onChange}
        />

    );
  }
}
<|endoftext|>


<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import _ from 'lodash';

export default function camelizeKeys(obj) {
    if (!_.isPlainObject(obj) && !_.isArray(obj)) {
        return obj;
    }

    if (_.isArray(obj)) {
        return obj.map(camelizeKeys);
    }

    return Object.entries(obj).reduce((accum, [key, value]) => {
        return {...accum, [_.camelCase(key)]: camelizeKeys(value)};
    }, {});
}
<commit_msg>Camelize keys containing only letters<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import _ from 'lodash';

export default function camelizeKeys(obj) {
    if (!_.isPlainObject(obj) && !_.isArray(obj)) {
        return obj;
    }

    if (_.isArray(obj)) {
        return obj.map(camelizeKeys);
    }

    return Object.entries(obj).reduce((accum, [key, value]) => {
        if (key.match('^[A-Za-z_]+$')) {
            return {...accum, [_.camelCase(key)]: camelizeKeys(value)};
        } else {
            return {...accum, key: camelizeKeys(value)};
        }
    }, {});
}
<|endoftext|>


<commit_before>dojo.provide("dijit.form._DropDownTextBox");

dojo.declare(
	"dijit.form._DropDownTextBox",
	null,
	{
		// summary:
		//		Mixin text box with drop down

		templatePath: dojo.moduleUrl("dijit.form", "templates/ComboBox.html"),

		baseClass:"dijitComboBox",

		// hasDownArrow: Boolean
		// Set this textbox to have a down arrow button
		// Defaults to true
		hasDownArrow:true,

		// _popupWidget: Widget
		//	link to the popup widget created by makePopop
		_popupWidget:null,

		// _hasMasterPopup: Boolean
		//	Flag that determines if this widget should share one popup per widget prototype,
		//	or create one popup per widget instance.
		//	If true, then makePopup() creates one popup per widget prototype.
		//	If false, then makePopup() creates one popup per widget instance.
		_hasMasterPopup:false,

		// _popupClass: String
		//	Class of master popup (dijit.form._ComboBoxMenu)
		_popupClass:"",

		// _popupArgs: Object
		//	Object to pass to popup widget on initialization
		_popupArgs:{},

		// _hasFocus: Boolean
		// Represents focus state of the textbox
		_hasFocus:false,

		_arrowPressed: function(){
			if(!this.disabled&&this.hasDownArrow){
				dojo.addClass(this.downArrowNode, "dijitArrowButtonActive");
			}
		},

		_arrowIdle: function(){
			if(!this.disabled&&this.hasDownArrow){
				dojo.removeClass(this.downArrowNode, "dojoArrowButtonPushed");
			}
		},

		makePopup: function(){
			// summary:
			//	create popup widget on demand
			var _this=this;
			function _createNewPopup(){
				// common code from makePopup
				var node=document.createElement("div");
				var popupProto=dojo.getObject(_this._popupClass, false);
				return new popupProto(_this._popupArgs, node);
			}
			// this code only runs if there is no popup reference
			if(!this._popupWidget){
				// does this widget have one "master" popup?
				if(this._hasMasterPopup){
					// does the master popup not exist yet?
					var parentClass = dojo.getObject(this.declaredClass, false);
					if(!parentClass.prototype._popupWidget){
						// create the master popup for the first time
						parentClass.prototype._popupWidget=_createNewPopup();
					}
					// assign master popup to local link
					this._popupWidget=parentClass.prototype._popupWidget;
				}else{
					// if master popup is not being used, create one popup per widget instance
					this._popupWidget=_createNewPopup();
				}
			}
		},

		_onArrowClick: function(){
			// summary: callback when arrow is clicked
			if(this.disabled){
				return;
			}
			this.focus();
			this.makePopup();
			if(this._isShowingNow){
				this._hideResultList();
			}else{
				// forces full population of results, if they click
				// on the arrow it means they want to see more options
				this._openResultList();
			}
		},

		_hideResultList: function(){
			if(this._isShowingNow){
				dijit.popup.close();
				this._arrowIdle();
				this._isShowingNow=false;
			}
		},

		_openResultList:function(){
			// summary:
			//	any code that needs to happen before the popup appears.
			//	creating the popupWidget contents etc.
			this._showResultList();
		},

		onfocus:function(){
			this._hasFocus=true;
		},

		onblur:function(){
			this._arrowIdle();
			this._hasFocus=false;
			// removeClass dijitInputFieldFocused
			dojo.removeClass(this.nodeWithBorder, "dijitInputFieldFocused");
			// hide the Tooltip
			this.validate(false);
		},

		compositionend: function(/*Event*/ evt){
			// summary: When inputting characters using an input method, such as Asian
			// languages, it will generate this event instead of onKeyDown event
			this.onkeypress({charCode:-1});
		},

		_showResultList: function(){
			// Our dear friend IE doesnt take max-height so we need to calculate that on our own every time
			this._hideResultList();
			var childs = this._popupWidget.getListLength ? this._popupWidget.getItems() : [this._popupWidget.domNode];

			if(childs.length){
				var visibleCount = Math.min(childs.length,this.maxListLength);
				this._arrowPressed();
				// hide the tooltip
				this._displayMessage("");
				var best=this.open();
				// #3212: only set auto scroll bars if necessary
				// prevents issues with scroll bars appearing when they shouldn't when node is made wider (fractional pixels cause this)
				var popupbox=dojo.marginBox(this._popupWidget.domNode);
				this._popupWidget.domNode.style.overflow=((best.h==popupbox.h)&&(best.w==popupbox.w))?"hidden":"auto";
				// #4134: borrow TextArea scrollbar test so content isn't covered by scrollbar and horizontal scrollbar doesn't appear
				var newwidth=best.w;
				if(best.h<this._popupWidget.domNode.scrollHeight){newwidth+=16;}
				dojo.marginBox(this._popupWidget.domNode, {h:best.h,w:Math.max(newwidth,this.domNode.offsetWidth)});
			}
		},

		getDisplayedValue:function(){
			return this.textbox.value;
		},

		setDisplayedValue:function(/*String*/ value){
			this.textbox.value=value;
		},

		uninitialize:function(){
			if(this._popupWidget&&!this._hasMasterPopup){
				this._hideResultList();
				this._popupWidget.destroy()
			};
		},

		open:function(){
			this.makePopup();
			this._isShowingNow=true;
			return dijit.popup.open({
				popup: this._popupWidget,
				around: this.domNode,
				parent: this
			});
		},

		_onBlur: function(){
			// summary: called magically when focus has shifted away from this widget and it's dropdown
			this._hideResultList();
		},

		postMixInProperties:function(){
			this.baseClass=this.hasDownArrow?this.baseClass:this.baseClass+"NoArrow";
		}
	}
);
<commit_msg>When the number of elements in the drop down list changes, height wasn't being adjusted.   Need to set drop down list to it's natural height so that dijit.popup can suggest a proper height setting.  Fixes #4482, refs #3058.<commit_after>dojo.provide("dijit.form._DropDownTextBox");

dojo.declare(
	"dijit.form._DropDownTextBox",
	null,
	{
		// summary:
		//		Mixin text box with drop down

		templatePath: dojo.moduleUrl("dijit.form", "templates/ComboBox.html"),

		baseClass:"dijitComboBox",

		// hasDownArrow: Boolean
		// Set this textbox to have a down arrow button
		// Defaults to true
		hasDownArrow:true,

		// _popupWidget: Widget
		//	link to the popup widget created by makePopop
		_popupWidget:null,

		// _hasMasterPopup: Boolean
		//	Flag that determines if this widget should share one popup per widget prototype,
		//	or create one popup per widget instance.
		//	If true, then makePopup() creates one popup per widget prototype.
		//	If false, then makePopup() creates one popup per widget instance.
		_hasMasterPopup:false,

		// _popupClass: String
		//	Class of master popup (dijit.form._ComboBoxMenu)
		_popupClass:"",

		// _popupArgs: Object
		//	Object to pass to popup widget on initialization
		_popupArgs:{},

		// _hasFocus: Boolean
		// Represents focus state of the textbox
		_hasFocus:false,

		_arrowPressed: function(){
			if(!this.disabled&&this.hasDownArrow){
				dojo.addClass(this.downArrowNode, "dijitArrowButtonActive");
			}
		},

		_arrowIdle: function(){
			if(!this.disabled&&this.hasDownArrow){
				dojo.removeClass(this.downArrowNode, "dojoArrowButtonPushed");
			}
		},

		makePopup: function(){
			// summary:
			//	create popup widget on demand
			var _this=this;
			function _createNewPopup(){
				// common code from makePopup
				var node=document.createElement("div");
				var popupProto=dojo.getObject(_this._popupClass, false);
				return new popupProto(_this._popupArgs, node);
			}
			// this code only runs if there is no popup reference
			if(!this._popupWidget){
				// does this widget have one "master" popup?
				if(this._hasMasterPopup){
					// does the master popup not exist yet?
					var parentClass = dojo.getObject(this.declaredClass, false);
					if(!parentClass.prototype._popupWidget){
						// create the master popup for the first time
						parentClass.prototype._popupWidget=_createNewPopup();
					}
					// assign master popup to local link
					this._popupWidget=parentClass.prototype._popupWidget;
				}else{
					// if master popup is not being used, create one popup per widget instance
					this._popupWidget=_createNewPopup();
				}
			}
		},

		_onArrowClick: function(){
			// summary: callback when arrow is clicked
			if(this.disabled){
				return;
			}
			this.focus();
			this.makePopup();
			if(this._isShowingNow){
				this._hideResultList();
			}else{
				// forces full population of results, if they click
				// on the arrow it means they want to see more options
				this._openResultList();
			}
		},

		_hideResultList: function(){
			if(this._isShowingNow){
				dijit.popup.close();
				this._arrowIdle();
				this._isShowingNow=false;
			}
		},

		_openResultList:function(){
			// summary:
			//	any code that needs to happen before the popup appears.
			//	creating the popupWidget contents etc.
			this._showResultList();
		},

		onfocus:function(){
			this._hasFocus=true;
		},

		onblur:function(){
			this._arrowIdle();
			this._hasFocus=false;
			// removeClass dijitInputFieldFocused
			dojo.removeClass(this.nodeWithBorder, "dijitInputFieldFocused");
			// hide the Tooltip
			this.validate(false);
		},

		compositionend: function(/*Event*/ evt){
			// summary: When inputting characters using an input method, such as Asian
			// languages, it will generate this event instead of onKeyDown event
			this.onkeypress({charCode:-1});
		},

		_showResultList: function(){
			// Our dear friend IE doesnt take max-height so we need to calculate that on our own every time
			this._hideResultList();
			var childs = this._popupWidget.getListLength ? this._popupWidget.getItems() : [this._popupWidget.domNode];

			if(childs.length){
				var visibleCount = Math.min(childs.length,this.maxListLength);
				with(this._popupWidget.domNode.style){
					// natural size of the list has changed, so erase old width/height settings,
					// which were hardcoded in a previous call to this function (via dojo.marginBox() call)
					width="";
					height="";
				}
				this._arrowPressed();
				// hide the tooltip
				this._displayMessage("");
				var best=this.open();
				// #3212: only set auto scroll bars if necessary
				// prevents issues with scroll bars appearing when they shouldn't when node is made wider (fractional pixels cause this)
				var popupbox=dojo.marginBox(this._popupWidget.domNode);
				this._popupWidget.domNode.style.overflow=((best.h==popupbox.h)&&(best.w==popupbox.w))?"hidden":"auto";
				// #4134: borrow TextArea scrollbar test so content isn't covered by scrollbar and horizontal scrollbar doesn't appear
				var newwidth=best.w;
				if(best.h<this._popupWidget.domNode.scrollHeight){newwidth+=16;}
				dojo.marginBox(this._popupWidget.domNode, {h:best.h,w:Math.max(newwidth,this.domNode.offsetWidth)});
			}
		},

		getDisplayedValue:function(){
			return this.textbox.value;
		},

		setDisplayedValue:function(/*String*/ value){
			this.textbox.value=value;
		},

		uninitialize:function(){
			if(this._popupWidget&&!this._hasMasterPopup){
				this._hideResultList();
				this._popupWidget.destroy()
			};
		},

		open:function(){
			this.makePopup();
			this._isShowingNow=true;
			return dijit.popup.open({
				popup: this._popupWidget,
				around: this.domNode,
				parent: this
			});
		},

		_onBlur: function(){
			// summary: called magically when focus has shifted away from this widget and it's dropdown
			this._hideResultList();
		},

		postMixInProperties:function(){
			this.baseClass=this.hasDownArrow?this.baseClass:this.baseClass+"NoArrow";
		}
	}
);
<|endoftext|>