<commit_before>/**
 * Copyright 2014-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ReactHostComponent
 */

'use strict';

var invariant = require('invariant');

var genericComponentClass = null;
// This registry keeps track of wrapper classes around host tags.
var tagToComponentClass = {};
var textComponentClass = null;

var ReactHostComponentInjection = {
  // This accepts a class that receives the tag string. This is a catch all
  // that can render any kind of tag.
  injectGenericComponentClass: function(componentClass) {
    genericComponentClass = componentClass;
  },
  // This accepts a text component class that takes the text string to be
  // rendered as props.
  injectTextComponentClass: function(componentClass) {
    textComponentClass = componentClass;
  },
  // This accepts a keyed object with classes as values. Each key represents a
  // tag. That particular tag will use this class instead of the generic one.
  injectComponentClasses: function(componentClasses) {
    Object.assign(tagToComponentClass, componentClasses);
  },
};

/**
 * Get a host internal component class for a specific tag.
 *
 * @param {ReactElement} element The element to create.
 * @return {function} The internal class constructor function.
 */
function createInternalComponent(element) {
  invariant(
    genericComponentClass,
    'There is no registered component for the tag %s',
    element.type
  );
  return new genericComponentClass(element);
}

/**
 * @param {ReactText} text
 * @return {ReactComponent}
 */
function createInstanceForText(text) {
  return new textComponentClass(text);
}

/**
 * @param {ReactComponent} component
 * @return {boolean}
 */
function isTextComponent(component) {
  return component instanceof textComponentClass;
}

var ReactHostComponent = {
  createInternalComponent: createInternalComponent,
  createInstanceForText: createInstanceForText,
  isTextComponent: isTextComponent,
  injection: ReactHostComponentInjection,
};

module.exports = ReactHostComponent;
<commit_msg>Injected Host Component classes are not being considered by the reconciler (#8050)<commit_after>/**
 * Copyright 2014-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ReactHostComponent
 */

'use strict';

var invariant = require('invariant');

var genericComponentClass = null;
var textComponentClass = null;

var ReactHostComponentInjection = {
  // This accepts a class that receives the tag string. This is a catch all
  // that can render any kind of tag.
  injectGenericComponentClass: function(componentClass) {
    genericComponentClass = componentClass;
  },
  // This accepts a text component class that takes the text string to be
  // rendered as props.
  injectTextComponentClass: function(componentClass) {
    textComponentClass = componentClass;
  },
};

/**
 * Get a host internal component class for a specific tag.
 *
 * @param {ReactElement} element The element to create.
 * @return {function} The internal class constructor function.
 */
function createInternalComponent(element) {
  invariant(
    genericComponentClass,
    'There is no registered component for the tag %s',
    element.type
  );
  return new genericComponentClass(element);
}

/**
 * @param {ReactText} text
 * @return {ReactComponent}
 */
function createInstanceForText(text) {
  return new textComponentClass(text);
}

/**
 * @param {ReactComponent} component
 * @return {boolean}
 */
function isTextComponent(component) {
  return component instanceof textComponentClass;
}

var ReactHostComponent = {
  createInternalComponent: createInternalComponent,
  createInstanceForText: createInstanceForText,
  isTextComponent: isTextComponent,
  injection: ReactHostComponentInjection,
};

module.exports = ReactHostComponent;
<|endoftext|>


<commit_before>define(["dojo/_base/declare", "ppwcode-util-contracts/_Mixin", "dojo/_base/lang", "dijit/registry", "dojo/dom-class",
        "dijit/_WidgetBase", "../../SemanticObject",
        "dijit/form/ValidationTextBox", "dojox/mvc/Output", "dojox/form/CheckedMultiSelect", "dijit/form/SimpleTextarea",
         "dijit/form/CheckBox", "dijit/form/Select",
         "xstyle/css!./_SemanticObjectPane.css"],
    function(declare, _ContractMixin, lang, registry, domClass,
             _WidgetBase, SemanticObject,
             ValidationTextBox, Output, CheckedMultiSelect, SimpleTextarea,
             CheckBox, Select) {

      var presentationModes = [
        // presentationMode and stylePresentationMode for viewing the data. No interaction allowed.
        "VIEW",

        // presentationMode and stylePresentationMode for editing the data. Interaction allowed.
        "EDIT",

        // presentationMode and stylePresentationMode while the SemanticObject is busy. No interaction allowed.
        "BUSY",

        // presentationMode and stylePresentationMode representing unacceptable data (the object is
        // not civilized, or we have other means of knowing the data is unacceptable).
        // Interaction must be allowed to reset the object, or ammeliorate the data/
        // This means this is a sub-state of EDIT.
        "WILD",

        // presentationMode and stylePresentationMode representing an error occured. We cannot proceed. The widget
        // and its object must be destroyed.
        "ERROR"];

      var stylePresentationModes = presentationModes.slice(0); // copy
      // stylePresentationMode for when there is no target
      stylePresentationModes.push("NOTARGET");

      function recursiveChildWidgets(domNode) {
        return registry.findWidgets(domNode).reduce(
          function(acc, w) {
            acc.push(w);
            return acc.concat(recursiveChildWidgets(w.domNode));
          },
          []
        );
      }

      function setStylepresentationMode(sop, stylePresentationMode, /*Boolean?*/ created) {
        // create:
        //   Only relevant for "EDIT". Falsy if we are editing a fresh object, truthy if not.
        var domNode = sop.get("domNode");
        if (domNode) {
          var widgetState = null;
          //noinspection FallthroughInSwitchStatementJS
          switch (stylePresentationMode) {
            case _SemanticObjectPane.prototype.NOTARGET:
              widgetState = { readOnly:false, disabled:true };
              break;
            case _SemanticObjectPane.prototype.EDIT:
            case _SemanticObjectPane.prototype.WILD:
              widgetState = { readOnly:false, disabled:false };
              break;
            case _SemanticObjectPane.prototype.BUSY:
            case _SemanticObjectPane.prototype.ERROR:
              widgetState = { readOnly:false, disabled:true };
              break;
            default: // VIEW
              widgetState = { readOnly:true, disabled:false };
          }
          var innerWidgets = recursiveChildWidgets(domNode);
          innerWidgets.forEach(function (w) {
            if (w.isInstanceOf(ValidationTextBox) || w.isInstanceOf(Output)
                || w.isInstanceOf(CheckedMultiSelect) || w.isInstanceOf(SimpleTextarea) || w.isInstanceOf(CheckBox)
                || w.isInstanceOf(Select)) {
              w.set("readOnly", widgetState.readOnly || !!(created && w.cannotBeChangedAfterCreate));
              w.set("disabled", widgetState.disabled);
            }
          });
          if (stylePresentationMode == _SemanticObjectPane.prototype.VIEW ||
              stylePresentationMode == _SemanticObjectPane.prototype.EDIT) {
            domClass.replace(domNode,
              "SemanticObjectPane_enabled",
              "SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
          }
          else if (stylePresentationMode == _SemanticObjectPane.prototype.BUSY) {
            domClass.replace(domNode,
              "SemanticObjectPane_busy",
              "SemanticObjectPane_enabled SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
          }
          else if (stylePresentationMode == _SemanticObjectPane.prototype.WILD) {
            domClass.replace(domNode,
              "SemanticObjectPane_wild",
              "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
          }
          else if (stylePresentationMode == _SemanticObjectPane.prototype.ERROR) {
            domClass.replace(domNode,
              "SemanticObjectPane_error",
              "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_notarget");
          }
          else { // NOTARGET
            domClass.replace(domNode,
              " SemanticObjectPane_notarget",
              "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_error SemanticObjectPane_disabled");
          }
        }
      }

      var _SemanticObjectPane = declare([_WidgetBase, _ContractMixin], {
        // summary:
        //   Widget that represents a SemanticObject in detail, and that gives the opportunity
        //   to the user the view the details, edit the details, and create a new object.
        //   Abstract class to be extended for particular subtypes of SemanticObject.
        // description:
        //   What is common to all subtypes is that the widget:
        //   - has a `target` that is a SemanticObject; getTargetType() returns the top-most supported
        //     Constructor of supported targets. All targets must be instances of this type.
        //   - has an `presentationMode` (view, edit, busy, wild, error)
        //   - has a `stylePresentationMode`
        //
        //   The representation should reflect the presentationMode in a clear visual way to the user.
        //   This is the `stylePresentationModel`. It is the `presentationMode` if `target !== null`,
        //   and `NOTARGET` otherwise.
        //   Even when the information shown is completely read-only, widgets should extend
        //   this class, to change the representation of the displayed information consistently
        //   with other information in different presentationModes, e.g., in "busy" mode.
        //   The available presentation modes are defined in _SemanticObjectPane.prototype.presentationModes.
        //
        //   Instances can be wrapped around zero or more _SemanticObjectPanes, recursively (no loops!).
        //   We take care of propagating `presentationMode`. Subclasses need to override
        //   getWrappedDetails to return the wrapped details. All instances need to be instances of this class.
        //   The default implementation returns an empty array.
        //   The target of a wrapped detail might be the same target as our target, but it might be
        //   another related object, of a different type. set("target", ...) will call _propagateTarget, which is
        //   chained, so that subclasses can add propagation of setting the target. Our implementation only sets our
        //   target.
        //
        //   This class is concerned with presentation. Other classes might add presentation
        //   and functionality to support interaction with the user (save and cancel buttons, etc. -
        //   see e.g. ppwcode persistence).

        _c_invar: [
          function() {return this.get("presentationMode");},
          function() {return this.presentationModes.indexOf(this.get("presentationMode")) >= 0;},
          function() {return this.getTargetType() != null;},
          // TODO getTargetType is a subtype of SemanticObject
          function() {return this.get("target") == null ||
                        (this.get("target").isInstanceOf && this.get("target").isInstanceOf(this.getTargetType()));},
          function() {return this.get("stylePresentationMode");},
          function() {return this.stylePresentationModes.indexOf(this.get("stylePresentationMode")) >= 0;},
          function() {return (this.get("stylePresentationMode") === this.NOTARGET) === (this.get("target") === null);},
          function() {return this.get("target") !== null ? this.get("stylePresentationMode") === this.get("presentationMode") : true;},
          function() {return this._wrappedDetails() != null;},
          function() {return lang.isArray(this._wrappedDetails());},
          {
            objectSelector: function() {
              return this._wrappedDetails();
            },
            invars: [
              function(wd) {
                return wd && wd != null &&
                  wd.isInstanceOf && wd.isInstanceOf(_SemanticObjectPane);
              },
              // wrapped details might contain other objects of other types as target,
              // or null, but the presentationMode needs to be in sync. The stylePresentationMode
              // can differ.
              function(wd) {
                return wd.get("presentationMode") === this.get("presentationMode");
              }
            ]
          }
        ],

        "-chains-": {
          _propagateTarget: "after",
          _propagateOpener: "after",
          _localPresentationModeChange: "after"
        },

        // target: SemanticObject
        //    SemanticObject that is represented.
        //    Access in declarative template with  ... data-dojo-props="value: at('rel:', BINDING_PROPERTY_NAME)
        target: null,

        // presentationMode: String
        //    The presentation mode is either view, edit, busy, wild, or error
        presentationMode: stylePresentationModes[0], // default value

        // opener: Function
        //   Function that attempts to open a new "window" or "pane" for another PersistentObject
        //   (which is mostly linked to the current one)
        opener: null,

        postCreate: function() {
          this.inherited(arguments);
          domClass.add(this.get("domNode"), "SemanticObjectPane");
        },

        // stylePresentationMode: String
        //    The stylePresentationMode is the same as the presentationMode, except when there is no target.
        //    Then it is NOTARGET.
        _getStylePresentationModeAttr: function() {
          return this.target ? this.get("presentationMode") : this.NOTARGET;
        },

        isInEditMode: function() {
          // summary:
          //    This is in a `stylePresentationMode` that allows the user to change the values, if there is a target and
          //    it is editable.
          return this.target &&
            (this.presentationMode === this.EDIT || this.presentationMode === this.BUSY || this.presentationMode === this.WILD);
        },

        _wrappedDetails: function() {
          // summary:
          //   Array containing the wrapped details, a subclass wants the presentationMode propagated to.
          // tags:
          //   protected

          return []; // return Array
        },

        getTargetType: function() {
          // summary:
          //    The supported type of SemanticObjects. All targets must be an instance of this type.
          // description:
          //    Subclasses should overwrite to return the correct type.

          return SemanticObject;
        },

        _propagateTarget: function(/*SemanticObject*/ so) {
          // summary:
          //   Propagate the target as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(so);
        },

        _setTargetAttr: function(so) {
          // summary:
          //    Sets the target of this instance. Chained. Subtypes could add propagation to wrapped details.
          this._c_pre(function() {return so == null || (so.isInstanceOf && so.isInstanceOf(this.getTargetType()));});

          if (so !== this.get("target")) {
            this._set("target", so);
          }
          this._propagateTarget(so);
          this.set("presentationMode", so !== null && so.persistenceId === null ? this.EDIT : this.VIEW);
        },

        _propagateOpener: function(/*Function*/ opener) {
          // summary:
          //   Propagate the opener function as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(opener);
        },

        _setOpenerAttr: function(opener) {
          if (opener !== this.get("opener")) {
            this._set("opener", opener);
          }
          this._propagateOpener(opener);
        },

        _setPresentationModeAttr: function(value) {
          // summary:
          //    Set the presentationMode, and propagate to the wrapped details.
          //    Also makes all innerWidgets read-only in presentationMode VIEW,
          //    disabled in presentationMode BUSY, and not-read-only and enabled
          //    in the other presentationModes.

          // Called during create by _WidgetBase with default value automatically
          this._c_pre(function() {return value != null});
          this._c_pre(function() {return _SemanticObjectPane.prototype.presentationModes.indexOf(value) >= 0});

          this._set("presentationMode", value);
          this._wrappedDetails().forEach(function(wd) {
            wd.set("presentationMode", value);
          });
          var stylePresentationMode = this.get("stylePresentationMode");
          var target = this.get("target");
          setStylepresentationMode(this, stylePresentationMode, target && target.get("persistenceId"));
          if (!this._destroyed) {
            // if we are destroyed, there are no more domNodes
            this._localPresentationModeChange(value);
          }
        },

        _localPresentationModeChange: function(/*String*/ presentationMode) {
          // summary:
          //   Make changes to representation to represent the
          //   new edit mode. Chained. Overwrite when needed.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane

          this._c_NOP(presentationMode);
        }

      });

      // All supported presentationModes
      _SemanticObjectPane.prototype.presentationModes = presentationModes;
      // All supported stylePresentationModes
      _SemanticObjectPane.prototype.stylePresentationModes = stylePresentationModes;
      stylePresentationModes.forEach(function(em) {
        _SemanticObjectPane.prototype[em] = em;
      });

      return _SemanticObjectPane; // return _SemanticObjectPane

    });
<commit_msg>so might also be undefined<commit_after>define(["dojo/_base/declare", "ppwcode-util-contracts/_Mixin", "dojo/_base/lang", "dijit/registry", "dojo/dom-class",
        "dijit/_WidgetBase", "../../SemanticObject",
        "dijit/form/ValidationTextBox", "dojox/mvc/Output", "dojox/form/CheckedMultiSelect", "dijit/form/SimpleTextarea",
         "dijit/form/CheckBox", "dijit/form/Select",
         "xstyle/css!./_SemanticObjectPane.css"],
    function(declare, _ContractMixin, lang, registry, domClass,
             _WidgetBase, SemanticObject,
             ValidationTextBox, Output, CheckedMultiSelect, SimpleTextarea,
             CheckBox, Select) {

      var presentationModes = [
        // presentationMode and stylePresentationMode for viewing the data. No interaction allowed.
        "VIEW",

        // presentationMode and stylePresentationMode for editing the data. Interaction allowed.
        "EDIT",

        // presentationMode and stylePresentationMode while the SemanticObject is busy. No interaction allowed.
        "BUSY",

        // presentationMode and stylePresentationMode representing unacceptable data (the object is
        // not civilized, or we have other means of knowing the data is unacceptable).
        // Interaction must be allowed to reset the object, or ammeliorate the data/
        // This means this is a sub-state of EDIT.
        "WILD",

        // presentationMode and stylePresentationMode representing an error occured. We cannot proceed. The widget
        // and its object must be destroyed.
        "ERROR"];

      var stylePresentationModes = presentationModes.slice(0); // copy
      // stylePresentationMode for when there is no target
      stylePresentationModes.push("NOTARGET");

      function recursiveChildWidgets(domNode) {
        return registry.findWidgets(domNode).reduce(
          function(acc, w) {
            acc.push(w);
            return acc.concat(recursiveChildWidgets(w.domNode));
          },
          []
        );
      }

      function setStylepresentationMode(sop, stylePresentationMode, /*Boolean?*/ created) {
        // create:
        //   Only relevant for "EDIT". Falsy if we are editing a fresh object, truthy if not.
        var domNode = sop.get("domNode");
        if (domNode) {
          var widgetState = null;
          //noinspection FallthroughInSwitchStatementJS
          switch (stylePresentationMode) {
            case _SemanticObjectPane.prototype.NOTARGET:
              widgetState = { readOnly:false, disabled:true };
              break;
            case _SemanticObjectPane.prototype.EDIT:
            case _SemanticObjectPane.prototype.WILD:
              widgetState = { readOnly:false, disabled:false };
              break;
            case _SemanticObjectPane.prototype.BUSY:
            case _SemanticObjectPane.prototype.ERROR:
              widgetState = { readOnly:false, disabled:true };
              break;
            default: // VIEW
              widgetState = { readOnly:true, disabled:false };
          }
          var innerWidgets = recursiveChildWidgets(domNode);
          innerWidgets.forEach(function (w) {
            if (w.isInstanceOf(ValidationTextBox) || w.isInstanceOf(Output)
                || w.isInstanceOf(CheckedMultiSelect) || w.isInstanceOf(SimpleTextarea) || w.isInstanceOf(CheckBox)
                || w.isInstanceOf(Select)) {
              w.set("readOnly", widgetState.readOnly || !!(created && w.cannotBeChangedAfterCreate));
              w.set("disabled", widgetState.disabled);
            }
          });
          if (stylePresentationMode == _SemanticObjectPane.prototype.VIEW ||
              stylePresentationMode == _SemanticObjectPane.prototype.EDIT) {
            domClass.replace(domNode,
              "SemanticObjectPane_enabled",
              "SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
          }
          else if (stylePresentationMode == _SemanticObjectPane.prototype.BUSY) {
            domClass.replace(domNode,
              "SemanticObjectPane_busy",
              "SemanticObjectPane_enabled SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
          }
          else if (stylePresentationMode == _SemanticObjectPane.prototype.WILD) {
            domClass.replace(domNode,
              "SemanticObjectPane_wild",
              "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
          }
          else if (stylePresentationMode == _SemanticObjectPane.prototype.ERROR) {
            domClass.replace(domNode,
              "SemanticObjectPane_error",
              "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_notarget");
          }
          else { // NOTARGET
            domClass.replace(domNode,
              " SemanticObjectPane_notarget",
              "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_error SemanticObjectPane_disabled");
          }
        }
      }

      var _SemanticObjectPane = declare([_WidgetBase, _ContractMixin], {
        // summary:
        //   Widget that represents a SemanticObject in detail, and that gives the opportunity
        //   to the user the view the details, edit the details, and create a new object.
        //   Abstract class to be extended for particular subtypes of SemanticObject.
        // description:
        //   What is common to all subtypes is that the widget:
        //   - has a `target` that is a SemanticObject; getTargetType() returns the top-most supported
        //     Constructor of supported targets. All targets must be instances of this type.
        //   - has an `presentationMode` (view, edit, busy, wild, error)
        //   - has a `stylePresentationMode`
        //
        //   The representation should reflect the presentationMode in a clear visual way to the user.
        //   This is the `stylePresentationModel`. It is the `presentationMode` if `target !== null`,
        //   and `NOTARGET` otherwise.
        //   Even when the information shown is completely read-only, widgets should extend
        //   this class, to change the representation of the displayed information consistently
        //   with other information in different presentationModes, e.g., in "busy" mode.
        //   The available presentation modes are defined in _SemanticObjectPane.prototype.presentationModes.
        //
        //   Instances can be wrapped around zero or more _SemanticObjectPanes, recursively (no loops!).
        //   We take care of propagating `presentationMode`. Subclasses need to override
        //   getWrappedDetails to return the wrapped details. All instances need to be instances of this class.
        //   The default implementation returns an empty array.
        //   The target of a wrapped detail might be the same target as our target, but it might be
        //   another related object, of a different type. set("target", ...) will call _propagateTarget, which is
        //   chained, so that subclasses can add propagation of setting the target. Our implementation only sets our
        //   target.
        //
        //   This class is concerned with presentation. Other classes might add presentation
        //   and functionality to support interaction with the user (save and cancel buttons, etc. -
        //   see e.g. ppwcode persistence).

        _c_invar: [
          function() {return this.get("presentationMode");},
          function() {return this.presentationModes.indexOf(this.get("presentationMode")) >= 0;},
          function() {return this.getTargetType() != null;},
          // TODO getTargetType is a subtype of SemanticObject
          function() {return this.get("target") == null ||
                        (this.get("target").isInstanceOf && this.get("target").isInstanceOf(this.getTargetType()));},
          function() {return this.get("stylePresentationMode");},
          function() {return this.stylePresentationModes.indexOf(this.get("stylePresentationMode")) >= 0;},
          function() {return (this.get("stylePresentationMode") === this.NOTARGET) === (this.get("target") === null);},
          function() {return this.get("target") !== null ? this.get("stylePresentationMode") === this.get("presentationMode") : true;},
          function() {return this._wrappedDetails() != null;},
          function() {return lang.isArray(this._wrappedDetails());},
          {
            objectSelector: function() {
              return this._wrappedDetails();
            },
            invars: [
              function(wd) {
                return wd && wd != null &&
                  wd.isInstanceOf && wd.isInstanceOf(_SemanticObjectPane);
              },
              // wrapped details might contain other objects of other types as target,
              // or null, but the presentationMode needs to be in sync. The stylePresentationMode
              // can differ.
              function(wd) {
                return wd.get("presentationMode") === this.get("presentationMode");
              }
            ]
          }
        ],

        "-chains-": {
          _propagateTarget: "after",
          _propagateOpener: "after",
          _localPresentationModeChange: "after"
        },

        // target: SemanticObject
        //    SemanticObject that is represented.
        //    Access in declarative template with  ... data-dojo-props="value: at('rel:', BINDING_PROPERTY_NAME)
        target: null,

        // presentationMode: String
        //    The presentation mode is either view, edit, busy, wild, or error
        presentationMode: stylePresentationModes[0], // default value

        // opener: Function
        //   Function that attempts to open a new "window" or "pane" for another PersistentObject
        //   (which is mostly linked to the current one)
        opener: null,

        postCreate: function() {
          this.inherited(arguments);
          domClass.add(this.get("domNode"), "SemanticObjectPane");
        },

        // stylePresentationMode: String
        //    The stylePresentationMode is the same as the presentationMode, except when there is no target.
        //    Then it is NOTARGET.
        _getStylePresentationModeAttr: function() {
          return this.target ? this.get("presentationMode") : this.NOTARGET;
        },

        isInEditMode: function() {
          // summary:
          //    This is in a `stylePresentationMode` that allows the user to change the values, if there is a target and
          //    it is editable.
          return this.target &&
            (this.presentationMode === this.EDIT || this.presentationMode === this.BUSY || this.presentationMode === this.WILD);
        },

        _wrappedDetails: function() {
          // summary:
          //   Array containing the wrapped details, a subclass wants the presentationMode propagated to.
          // tags:
          //   protected

          return []; // return Array
        },

        getTargetType: function() {
          // summary:
          //    The supported type of SemanticObjects. All targets must be an instance of this type.
          // description:
          //    Subclasses should overwrite to return the correct type.

          return SemanticObject;
        },

        _propagateTarget: function(/*SemanticObject*/ so) {
          // summary:
          //   Propagate the target as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(so);
        },

        _setTargetAttr: function(so) {
          // summary:
          //    Sets the target of this instance. Chained. Subtypes could add propagation to wrapped details.
          this._c_pre(function() {return so == null || (so.isInstanceOf && so.isInstanceOf(this.getTargetType()));});

          if (so !== this.get("target")) {
            this._set("target", so);
          }
          this._propagateTarget(so);
          this.set("presentationMode", so && so.persistenceId === null ? this.EDIT : this.VIEW);
        },

        _propagateOpener: function(/*Function*/ opener) {
          // summary:
          //   Propagate the opener function as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(opener);
        },

        _setOpenerAttr: function(opener) {
          if (opener !== this.get("opener")) {
            this._set("opener", opener);
          }
          this._propagateOpener(opener);
        },

        _setPresentationModeAttr: function(value) {
          // summary:
          //    Set the presentationMode, and propagate to the wrapped details.
          //    Also makes all innerWidgets read-only in presentationMode VIEW,
          //    disabled in presentationMode BUSY, and not-read-only and enabled
          //    in the other presentationModes.

          // Called during create by _WidgetBase with default value automatically
          this._c_pre(function() {return value != null});
          this._c_pre(function() {return _SemanticObjectPane.prototype.presentationModes.indexOf(value) >= 0});

          this._set("presentationMode", value);
          this._wrappedDetails().forEach(function(wd) {
            wd.set("presentationMode", value);
          });
          var stylePresentationMode = this.get("stylePresentationMode");
          var target = this.get("target");
          setStylepresentationMode(this, stylePresentationMode, target && target.get("persistenceId"));
          if (!this._destroyed) {
            // if we are destroyed, there are no more domNodes
            this._localPresentationModeChange(value);
          }
        },

        _localPresentationModeChange: function(/*String*/ presentationMode) {
          // summary:
          //   Make changes to representation to represent the
          //   new edit mode. Chained. Overwrite when needed.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane

          this._c_NOP(presentationMode);
        }

      });

      // All supported presentationModes
      _SemanticObjectPane.prototype.presentationModes = presentationModes;
      // All supported stylePresentationModes
      _SemanticObjectPane.prototype.stylePresentationModes = stylePresentationModes;
      stylePresentationModes.forEach(function(em) {
        _SemanticObjectPane.prototype[em] = em;
      });

      return _SemanticObjectPane; // return _SemanticObjectPane

    });
<|endoftext|>


<commit_before>/**
 * @file ready event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const COLOR = require('chalk');

module.exports = Bastion => {
  Bastion.user.setStatus(Bastion.config.status);
  Bastion.user.setGame(Bastion.config.game);

  Bastion.db.run('CREATE TABLE IF NOT EXISTS guildSettings' +
          '(guildID TEXT NOT NULL UNIQUE,' +
          `prefix TEXT NOT NULL DEFAULT '${Bastion.config.prefix}',` +
          'greet TEXT NOT NULL DEFAULT \'false\',' +
          'greetChannelID TEXT,' +
          'greetMessage TEXT NOT NULL DEFAULT \'Welcome to $server.\',' +
          'greetTimeout INTEGER NOT NULL DEFAULT 30,' +
          'greetDM TEXT NOT NULL DEFAULT \'false\',' +
          'greetDMMessage TEXT NOT NULL DEFAULT \'Welcome to $server.\',' +
          'farewell TEXT NOT NULL DEFAULT \'false\',' +
          'farewellChannelID TEXT UNIQUE,' +
          'farewellMessage TEXT NOT NULL DEFAULT \'We hope you enjoyed your stay here!\',' +
          'farewellTimeout INTEGER NOT NULL DEFAULT 15,' +
          'log TEXT NOT NULL DEFAULT \'false\',' +
          'logChannelID TEXT UNIQUE,' +
          'musicTextChannelID TEXT UNIQUE,' +
          'musicVoiceChannelID TEXT UNIQUE,' +
          'musicMasterRoleID TEXT UNIQUE,' +
          'filterInvite TEXT NOT NULL DEFAULT \'false\',' +
          'filterLink TEXT NOT NULL DEFAULT \'false\',' +
          'filterWord TEXT NOT NULL DEFAULT \'false\',' +
          'filteredWords TEXT NOT NULL DEFAULT \'[]\',' +
          'chat TEXT NOT NULL DEFAULT \'false\',' +
          'levelUpMessage TEXT NOT NULL DEFAULT \'false\',' +
          'selfAssignableRoles TEXT NOT NULL DEFAULT \'[]\',' +
          'autoAssignableRoles TEXT NOT NULL DEFAULT \'[]\',' +
          'modLog TEXT NOT NULL DEFAULT \'false\',' +
          'modLogChannelID TEXT UNIQUE,' +
          'modCaseNo TEXT NOT NULL DEFAULT \'1\',' +
          'PRIMARY KEY(guildID))').then(() => {
            let bastionGuilds = Bastion.guilds.map(g => g.id);

            Bastion.db.all('SELECT guildID from guildSettings').then(row => {
              row = row.map(r => r.guildID);

              for (let i = 0; i < bastionGuilds.length; i++) {
                let found = false;
                for (let j = 0; j < row.length; j++) {
                  if (bastionGuilds[i] === row[j]){
                    found = true;
                    break;
                  }
                }
                if (found === false) {
                  Bastion.db.run('INSERT INTO guildSettings (guildID) VALUES (?)', [ bastionGuilds[i] ]).catch(e => {
                    Bastion.log.error(e.stack);
                  });
                }
              }

              for (let i = 0; i < row.length; i++) {
                let found = false;
                for (let j = 0; j < bastionGuilds.length; j++) {
                  if (row[i] === bastionGuilds[j]){
                    found = true;
                    break;
                  }
                }
                if (found === false) {
                  Bastion.db.run(`DELETE FROM guildSettings WHERE guildID=${row[i]}`).catch(e => {
                    Bastion.log.error(e.stack);
                  });
                }
              }
            }).catch(e => {
              Bastion.log.error(e.stack);
            });
          }).catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS blacklistedUsers' +
          '(userID TEXT NOT NULL UNIQUE,' +
          'PRIMARY KEY(userID))').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS profiles' +
          '(userID TEXT NOT NULL UNIQUE,' +
          'bastionCurrencies INTEGER DEFAULT 0,' +
          'xp INTEGER DEFAULT 0,' +
          'level INTEGER DEFAULT 0,' +
          'status TEXT,' +
          'PRIMARY KEY(userID))').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS triggers' +
          '(trigger TEXT NOT NULL,' +
          'response TEXT NOT NULL)').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS todo' +
          '(ownerID TEXT NOT NULL UNIQUE,' +
          'list TEXT NOT NULL DEFAULT \'[]\')').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS bastionSettings' +
          '(log TEXT NOT NULL DEFAULT \'false\',' +
          'logChannelID TEXT UNIQUE)').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.log.console('\n');
  Bastion.log.console(COLOR.green('[Author] ') + Bastion.package.author);
  Bastion.log.console(COLOR.green('[Author URL] ') + Bastion.package.authorUrl);
  Bastion.log.console(COLOR.green('[Library] ') + Bastion.package.library);
  Bastion.log.console(`${COLOR.green('[Bot]')} Bastion v${Bastion.package.version}`);
  Bastion.log.console(COLOR.green('[Bot ID] ') + Bastion.credentials.botId);
  Bastion.log.console(COLOR.green('[Owner IDs] ') + Bastion.credentials.ownerId.join(', '));
  Bastion.log.console(COLOR.green('[Servers] ') + Bastion.guilds.size);
  Bastion.log.console(COLOR.green('[Prefix] ') + Bastion.config.prefix);
  Bastion.log.console(`${COLOR.cyan(`\n[${Bastion.user.username}]:`)} I'm ready to roll! o7`);
};
<commit_msg>Minor change<commit_after>/**
 * @file ready event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const COLOR = require('chalk');

module.exports = Bastion => {
  Bastion.user.setStatus(Bastion.config.status);
  Bastion.user.setGame(Bastion.config.game);

  Bastion.db.run('CREATE TABLE IF NOT EXISTS guildSettings' +
          '(guildID TEXT NOT NULL UNIQUE,' +
          `prefix TEXT NOT NULL DEFAULT '${Bastion.config.prefix}',` +
          'greet TEXT NOT NULL DEFAULT \'false\',' +
          'greetChannelID TEXT,' +
          'greetMessage TEXT NOT NULL DEFAULT \'Welcome to $server.\',' +
          'greetTimeout INTEGER NOT NULL DEFAULT 30,' +
          'greetDM TEXT NOT NULL DEFAULT \'false\',' +
          'greetDMMessage TEXT NOT NULL DEFAULT \'Welcome to $server.\',' +
          'farewell TEXT NOT NULL DEFAULT \'false\',' +
          'farewellChannelID TEXT UNIQUE,' +
          'farewellMessage TEXT NOT NULL DEFAULT \'We hope you enjoyed your stay here!\',' +
          'farewellTimeout INTEGER NOT NULL DEFAULT 15,' +
          'log TEXT NOT NULL DEFAULT \'false\',' +
          'logChannelID TEXT UNIQUE,' +
          'musicTextChannelID TEXT UNIQUE,' +
          'musicVoiceChannelID TEXT UNIQUE,' +
          'musicMasterRoleID TEXT UNIQUE,' +
          'filterInvite TEXT NOT NULL DEFAULT \'false\',' +
          'filterLink TEXT NOT NULL DEFAULT \'false\',' +
          'filterWord TEXT NOT NULL DEFAULT \'false\',' +
          'filteredWords TEXT NOT NULL DEFAULT \'[]\',' +
          'chat TEXT NOT NULL DEFAULT \'false\',' +
          'levelUpMessage TEXT NOT NULL DEFAULT \'false\',' +
          'selfAssignableRoles TEXT NOT NULL DEFAULT \'[]\',' +
          'autoAssignableRoles TEXT NOT NULL DEFAULT \'[]\',' +
          'modLog TEXT NOT NULL DEFAULT \'false\',' +
          'modLogChannelID TEXT UNIQUE,' +
          'modCaseNo TEXT NOT NULL DEFAULT \'1\',' +
          'PRIMARY KEY(guildID))').then(() => {
            let bastionGuilds = Bastion.guilds.map(g => g.id);

            Bastion.db.all('SELECT guildID from guildSettings').then(row => {
              row = row.map(r => r.guildID);

              for (let i = 0; i < bastionGuilds.length; i++) {
                let found = false;
                for (let j = 0; j < row.length; j++) {
                  if (bastionGuilds[i] === row[j]){
                    found = true;
                    break;
                  }
                }
                if (found === false) {
                  Bastion.db.run('INSERT INTO guildSettings (guildID) VALUES (?)', [ bastionGuilds[i] ]).catch(e => {
                    Bastion.log.error(e.stack);
                  });
                }
              }

              for (let i = 0; i < row.length; i++) {
                let found = false;
                for (let j = 0; j < bastionGuilds.length; j++) {
                  if (row[i] === bastionGuilds[j]){
                    found = true;
                    break;
                  }
                }
                if (found === false) {
                  Bastion.db.run(`DELETE FROM guildSettings WHERE guildID=${row[i]}`).catch(e => {
                    Bastion.log.error(e.stack);
                  });
                }
              }
            }).catch(e => {
              Bastion.log.error(e.stack);
            });
          }).catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS blacklistedUsers' +
          '(userID TEXT NOT NULL UNIQUE,' +
          'PRIMARY KEY(userID))').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS profiles' +
          '(userID TEXT NOT NULL UNIQUE,' +
          'bastionCurrencies INTEGER DEFAULT 0,' +
          'xp INTEGER DEFAULT 0,' +
          'level INTEGER DEFAULT 0,' +
          'bio TEXT,' +
          'PRIMARY KEY(userID))').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS triggers' +
          '(trigger TEXT NOT NULL,' +
          'response TEXT NOT NULL)').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS todo' +
          '(ownerID TEXT NOT NULL UNIQUE,' +
          'list TEXT NOT NULL DEFAULT \'[]\')').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.db.run('CREATE TABLE IF NOT EXISTS bastionSettings' +
          '(log TEXT NOT NULL DEFAULT \'false\',' +
          'logChannelID TEXT UNIQUE)').catch(e => {
            Bastion.log.error(e.stack);
          });

  Bastion.log.console('\n');
  Bastion.log.console(COLOR.green('[Author] ') + Bastion.package.author);
  Bastion.log.console(COLOR.green('[Author URL] ') + Bastion.package.authorUrl);
  Bastion.log.console(COLOR.green('[Library] ') + Bastion.package.library);
  Bastion.log.console(`${COLOR.green('[Bot]')} Bastion v${Bastion.package.version}`);
  Bastion.log.console(COLOR.green('[Bot ID] ') + Bastion.credentials.botId);
  Bastion.log.console(COLOR.green('[Owner IDs] ') + Bastion.credentials.ownerId.join(', '));
  Bastion.log.console(COLOR.green('[Servers] ') + Bastion.guilds.size);
  Bastion.log.console(COLOR.green('[Prefix] ') + Bastion.config.prefix);
  Bastion.log.console(`${COLOR.cyan(`\n[${Bastion.user.username}]:`)} I'm ready to roll! o7`);
};
<|endoftext|>


<commit_before>var io = require('socket.io-client');
var port = '80',
    server =  'thing.everymote.com';

var xbeeSerialPort = '/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A800csie-if00-port0';
var serialport = require('serialport');
var serialPort = new serialport.SerialPort(xbeeSerialPort,
{//Listening on the serial port for data coming from Arduino over USB
	baudRate: 57600,
	parser: serialport.parsers.readline('\n')
});

var connectLed = function(thing, onAction){
	console.log(thing);
	var socket = io.connect('http://' + server + ':' + port + '/thing'
		,{"force new connection":true
            ,'reconnect': true
            ,'reconnection delay': 5000
            ,'reconnection limit': 5000
            ,'max reconnection attempts': 10 });

	socket.on('connect', function () {
		console.log('connected');
		socket.emit('setup', thing);
	}).on('doAction', function (action) {
		//console.log(action);
		onAction(action, socket);

	}).on('connect_failed', function () {
		console.log('error:' + socket );
	}).on('disconnect', function () {
		console.log('disconnected');
	}).on('reconnect', function () {
		console.log('reconnect');
	}).on('reconnecting', function () {
		console.log('reconnecting');
	}).on('reconnect_failed', function () {
		console.log('reconnect_failed');
	});
};

var createLed = function(light, lightSettings){

	return {
		"name": "Led Stripe",
		"id": 4,
		"iconType": "Lamp",
		//"info":"Press link button on hub and pair"
		"actionControles": [
                {"type":"button", "name":"On", "id":"on"},
                {"type":"button", "name":"Off", "id":"off"},
                {"type":"hsl", "name":"color picker", "id":"color",
                	 "curentState":
                	 				{"hue":1,"bri":1,"sat":20}}
            ]
	};
};

var sendCollor = function(rgb){
	serialPort.write(new Buffer([4, rgb[0], rgb[1], rgb[2], 10]));
};

var on = function(){
	sendCollor([255,255,255]);
};

var off = function(){
	sendCollor([0,0,0]);
};

function hsvToRgb(h, s, v){
      //h *= 360;
        var r, g, b, X, C;
        h = (h % 360) / 60;
        C = v * s;
        X = C * (1 - Math.abs(h % 2 - 1));
        R = G = B = v - C;

        h = ~~h;
        r = [C, X, 0, 0, X, C][h];
        g = [X, C, C, X, 0, 0][h];
        b = [0, 0, X, C, C, X][h];
    return [Math.floor(r * 255), Math.floor(g * 255), Math.floor(b * 255)];
};

var createActonHandler = function(){
	var actions = {};
	actions.on = function(value){
		on();
	};
	actions.off = function(value){
		off();
	};
	actions.color = function(value, socket){
		processAcction = true;
		//hueApi.setLightState(light.id, offState).done();
		socket.emit('updateActionControlerState', {"id":"color",
			"curentState":{"hue":value.hue,"bri":value.bri,"sat":value.sat}});
	var data = {
		"hue":  Math.round(value.hue * 65535),
		"sat":  value.sat,
		"bri": 	value.bri
		};
		console.log("value");
		console.log(value);
		console.log("data");
		console.log(data);

		var rgb = hsvToRgb(data.hue, data.sat, data.bri);
		console.log(rgb);
		sendCollor(rgb);
	};

	var actionHandler = function(action, socket){
		actions[action.id](action.value, socket);
	};

	return actionHandler;
};

connectLed(createLed(), createActonHandler());

<commit_msg>fixed setup<commit_after>var io = require('socket.io-client');
var port = '80',
    server =  'thing.everymote.com';

var xbeeSerialPort = '/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A800csie-if00-port0';
var serialport = require('serialport');
var serialPort = new serialport.SerialPort(xbeeSerialPort,
{//Listening on the serial port for data coming from Arduino over USB
	baudRate: 57600,
	parser: serialport.parsers.readline('\n')
});

var connectLed = function(thing, onAction){
	console.log(thing);
	var socket = io.connect('http://' + server + ':' + port + '/thing'
		,{"force new connection":true
            ,'reconnect': true
            ,'reconnection delay': 5000
            ,'reconnection limit': 5000
            ,'max reconnection attempts': 10 });

	socket.on('connect', function () {
		console.log('connected');
		socket.emit('setup', thing);
	}).on('doAction', function (action) {
		//console.log(action);
		onAction(action, socket);

	}).on('connect_failed', function () {
		console.log('error:' + socket );
	}).on('disconnect', function () {
		console.log('disconnected');
	}).on('reconnect', function () {
		console.log('reconnect');
	}).on('reconnecting', function () {
		console.log('reconnecting');
	}).on('reconnect_failed', function () {
		console.log('reconnect_failed');
	});
};

var createLed = function(light, lightSettings){

	return {
		"name": "Led Stripe",
		"id": 4,
		"iconType": "Lamp",
		//"info":"Press link button on hub and pair"
		"actionControles": [
                {"type":"button", "name":"On", "id":"on"},
                {"type":"button", "name":"Off", "id":"off"},
                {"type":"hsl", "name":"color picker", "id":"color",
                	 "curentState":
                	 				{"hue":0,"bri":1,"sat":0}}
            ]
	};
};

var sendCollor = function(rgb){
	serialPort.write(new Buffer([4, rgb[0], rgb[1], rgb[2], 10]));
};

var on = function(){
	sendCollor([255,255,255]);
};

var off = function(){
	sendCollor([0,0,0]);
};

function hsv2rgb(h,s,v) {
// Adapted from http://www.easyrgb.com/math.html
// hsv values = 0 - 1, rgb values = 0 - 255
var r, g, b;
var RGB = new Array();
if(s==0){
  RGB['red']=RGB['green']=RGB['blue']=Math.round(v*255);
}else{
  // h must be < 1
  var var_h = h * 6;
  if (var_h==6) var_h = 0;
  //Or ... var_i = floor( var_h )
  var var_i = Math.floor( var_h );
  var var_1 = v*(1-s);
  var var_2 = v*(1-s*(var_h-var_i));
  var var_3 = v*(1-s*(1-(var_h-var_i)));
  if(var_i==0){
    var_r = v;
    var_g = var_3;
    var_b = var_1;
  }else if(var_i==1){
    var_r = var_2;
    var_g = v;
    var_b = var_1;
  }else if(var_i==2){
    var_r = var_1;
    var_g = v;
    var_b = var_3
  }else if(var_i==3){
    var_r = var_1;
    var_g = var_2;
    var_b = v;
  }else if (var_i==4){
    var_r = var_3;
    var_g = var_1;
    var_b = v;
  }else{
    var_r = v;
    var_g = var_1;
    var_b = var_2
  }
  //rgb results = 0 ÷ 255
  RGB['red']=Math.round(var_r * 255);
  RGB['green']=Math.round(var_g * 255);
  RGB['blue']=Math.round(var_b * 255);
  }
return [RGB.red, RGB.green, RGB.blue];
};

var createActonHandler = function(){
	var actions = {};
	actions.on = function(value){
		on();
	};
	actions.off = function(value){
		off();
	};
	actions.color = function(value, socket){
		processAcction = true;
		//hueApi.setLightState(light.id, offState).done();
		socket.emit('updateActionControlerState', {"id":"color",
			"curentState":{"hue":value.hue,"bri":value.bri,"sat":value.sat}});
	var data = {
		"hue":  Math.round(value.hue * 65535),
		"sat":  value.sat,
		"bri": 	value.bri
		};
		console.log("value");
		console.log(value);
		console.log("data");
		console.log(data);

		var rgb = hsv2rgb(data.hue, data.sat, data.bri);
		console.log(rgb);
		sendCollor(rgb);
	};

	var actionHandler = function(action, socket){
		actions[action.id](action.value, socket);
	};

	return actionHandler;
};

connectLed(createLed(), createActonHandler());

<|endoftext|>


<commit_before>import { Core,
         Dummy,
         Dashboard,
         GoogleDrive,
         Webcam,
         Tus10,
         MetaData,
         Informer } from '../src/index.js'

// import ru_RU from '../src/locales/ru_RU.js'
// import MagicLog from '../src/plugins/MagicLog'

const uppy = new Core({debug: true, autoProceed: false})
  // .use(FileInput, {text: 'Выбрать файл', pretty: true})
  .use(Dashboard, {trigger: '#uppyModalOpener', inline: false})
  .use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'})
  .use(Dummy, {target: Dashboard})
  .use(Webcam, {target: Dashboard})
  .use(Tus10, {endpoint: 'https://tusd.tus.io/files/', resume: true})
  .use(Informer, {target: Dashboard})
  .use(MetaData, {
    fields: [
      { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
      { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
    ]
  })
uppy.run()

uppy.on('core:success', (fileCount) => {
  console.log(fileCount)
})

// uppy.emit('informer', 'Smile!', 'info', 2000)

document.querySelector('#uppyModalOpener').click()
<commit_msg>PersistentState in example<commit_after>import { Core,
         Dummy,
         Dashboard,
         GoogleDrive,
         Webcam,
         Tus10,
         MetaData,
         Informer } from '../src/index.js'

// import ru_RU from '../src/locales/ru_RU.js'
// import MagicLog from '../src/plugins/MagicLog'
// import PersistentState from '../src/plugins/PersistentState'

const uppy = new Core({debug: true, autoProceed: false})
  // .use(FileInput, {text: 'Выбрать файл', pretty: true})
  // .use(PersistentState)
  .use(Dashboard, {trigger: '#uppyModalOpener', inline: false})
  .use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'})
  .use(Dummy, {target: Dashboard})
  .use(Webcam, {target: Dashboard})
  .use(Tus10, {endpoint: 'https://tusd.tus.io/files/', resume: true})
  .use(Informer, {target: Dashboard})
  .use(MetaData, {
    fields: [
      { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
      { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
    ]
  })
uppy.run()

uppy.on('core:success', (fileCount) => {
  console.log(fileCount)
})

// uppy.emit('informer', 'Smile!', 'info', 2000)

document.querySelector('#uppyModalOpener').click()
<|endoftext|>


<commit_before>$(document).ready(function () {
    var locale = 'en' !== LOCALE ? LOCALE : '';
    var options = $.extend({}, $.datepicker.regional[locale], $.timepicker.regional[locale], {
        dateFormat: 'dd.mm.yy'
    });

    var init;
    (init = function () {
        $('input.date').datepicker(options);
        $('input.datetime').datetimepicker(options);
        $('input.time').timepicker(options);
    })();

    $(document).bind('ajaxSuccess', init);
});
<commit_msg>Simplify date time pickers init JS.<commit_after>$(document).ready(function () {
    var locale = 'en' !== LOCALE ? LOCALE : '';
    var options = $.extend({}, $.datepicker.regional[locale], $.timepicker.regional[locale], {
        dateFormat: 'dd.mm.yy'
    });

    var init;
    (init = function () {
        ['date', 'datetime', 'time'].map(function (type) {
            $('input.' + type)[type + 'picker'](options);
        });
    })();

    $(document).bind('ajaxSuccess', init);
});
<|endoftext|>


<commit_before>/*jshint node:true, es3:false, regexp:false*/

'use strict';

var fs        = require('fs');
var rjs       = require('requirejs');
var UglifyJS  = require('uglify-js');
var cleanCSS  = require('clean-css');
var gzip      = require('gzip-js');

module.exports = function (task) {
    task
    .id('build')
    .name('Build')
    .author('Indigo United')
    .description('Build project')
    .option('env', 'The environment to build', 'prod')

    .setup(function (opts, ctx, next) {
        // Validate environment
        if (opts.env === 'dev') {
            return next(new Error('dev environment can\'t be built'));
        }

        var cwd = process.cwd();
        fs.readFile(cwd + '/app/config/config_' + opts.env + '.js', function (err, contents) {
            if (err) {
                return next(new Error('Unknown environment: ' + opts.env));
            }

            // Expose the version in the opts
            // Convert from decimal base to base36 to decrease the size of the number
            opts.version = Date.now().toString(36);

            // Set some necessary vars to be used bellow
            opts.targetDir = cwd  + '/web/' + opts.env;
            opts.tempDir = cwd + '/tmp';
            opts.projectDir = cwd;

            ctx.log.writeln('Will build version ' + opts.version.green);
            next();
        });
    })

    .do('rm', {
        description: 'Clean up previous build',
        options: {
            files: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('mkdir', {
        description: 'Create build folder',
        options: {
            dirs: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('cp', {
        description: 'Copy necessary files to temporary folder',
        options: {
            files: {
                '{{projectDir}}/app/**/*': '{{tempDir}}/app/',
                '{{projectDir}}/src/**/*': '{{tempDir}}/src/',
                '{{projectDir}}/bower_components/**/*': '{{tempDir}}/bower_components/',
                '{{projectDir}}/*': '{{tempDir}}/'
            }
        }
    })
    .do(function (opts, ctx, next) {
        var loaderFile = opts.tempDir + '/app/loader.js';

        fs.readFile(loaderFile, function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents.toString().replace(/\/app\/config\/config_\w+/g, '/app/config/config_' + opts.env);
            fs.writeFile(loaderFile, contents, next);
        });
    }, {
        description: 'Change target environment in loader config'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        rjs.optimize({
            // Loader settings
            mainConfigFile: opts.tempDir + '/app/loader.js',       // Include the main configuration file
            baseUrl: opts.tempDir + '/src',                        // Point to the tmp folder
            // r.js specific settings
            name: '../bower_components/almond/almond',                      // Use almond
            include: ['../app/loader', '../app/bootstrap'],
            out: opts.tempDir + '/app.js',
            has: {
                debug: false
            },
            optimize: 'none',
            separateCSS: true,
            stubModules: ['has', 'text', 'css', 'css/css', 'css/normalize']
        }, function (log) {
            ctx.log.info(log);
            next();
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Run r.js optimizer'
    })
    .do(function (opts, ctx, next) {
        // Replace baseUrl with the correct environment
        fs.readFile(opts.tempDir + '/app.js', function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents.toString().replace('\'./dev/src\'', '\'./' + opts.env + '/src\'');

            fs.writeFile(opts.tempDir + '/app.js', contents, next);
        });
    }, {
        description: 'Replace base URL'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        rjs.optimize({
            optimizeCss: 'standard.keepLines',
            cssIn: opts.tempDir + '/app.css',
            out: opts.tempDir + '/app.css',
            preserveLicenseComments: opts.licenses
        }, function (log) {
            ctx.log.write(log);

            // Replace trailing css from loader defs
            fs.readFile(opts.tempDir + '/app.js', function (err, contents) {
                if (err) {
                    return next(err);
                }

                contents = contents.toString().replace(/css!(.*?)\.css/g, 'css!$1');
                fs.writeFile(opts.tempDir + '/app.js', contents, next);
            });
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Expand css files'
    })
    .do('mv', {
        description: 'Move assets to the build folder',
        options: {
            files: {
                '{{tempDir}}/src/**/assets/!(css|tmpl)/**/*': '{{targetDir}}/src/',
                '{{tempDir}}/app.js': '{{targetDir}}/app.js',
                '{{tempDir}}/app.css': '{{targetDir}}/app.css'
            }
        }
    })
    // TODO. create automaton task for cache busting or use scaffolding-replace with regexp support
    .do(function (opts, ctx, next) {
        var index = opts.projectDir + '/web/index_' + opts.env + '.html',
            css = opts.targetDir + '/app.css';

        // Update index file
        fs.readFile(index, function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents
                .toString()
                .replace(/(app(?:\.min)?\.(?:css|js))(?:\?\d+)?/g, function (all, match) {
                    return match + '?' + opts.version;
                });

            fs.writeFile(index, contents, function (err) {
                if (err) {
                    return next(err);
                }

                // Update css file
                fs.readFile(css, function (err, contents) {
                    if (err) {
                        return next(err);
                    }

                    contents = contents
                        .toString()
                        .replace(/(url\s*\(["']?)(.*?)(["']?\))/ig, function (match, start, url, end) {
                            url = start + url.split('?', 2)[0] + '?' + opts.version + end;
                            return url;
                        });

                    fs.writeFile(css, contents, next);
                });
            });
        });
    }, {
        description: 'Apply cache busting'
    })
    // TODO: create automaton task for this (minjs)
    .do(function (opts, ctx, next) {
        // TODO: minified also contains a .map with the source mappings
        //       investigate how to integrate it!
        var minified = UglifyJS.minify(opts.targetDir + '/app.js'),
            minifiedSize = String(minified.code.length),
            gzipSize = String(gzip.zip(minified.code, {}).length);

        ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

        fs.writeFile(opts.targetDir + '/app.min.js', minified.code, next);
    }, {
        description: 'Minify js file'
    })
    // TODO: create automaton task for this (mincss)
    .do(function (opts, ctx, next) {
        fs.readFile(opts.targetDir + '/app.css', function (err, contents) {
            if (err) {
                return next(err);
            }

            var minified = cleanCSS.process(contents.toString(), opts),
                minifiedSize = String(minified.length),
                gzipSize = String(gzip.zip(minified, {}).length);

            ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

            fs.writeFile(opts.targetDir + '/app.min.css', minified, next);
        });
    }, {
        description: 'Minify css file'
    })
    .do('rm', {
        description: 'Clean up temporary files',
        options: {
            files: '{{tempDir}}'
        }
    });
};
<commit_msg>Fix replace of builds in query string.<commit_after>/*jshint node:true, es3:false, regexp:false*/

'use strict';

var fs        = require('fs');
var rjs       = require('requirejs');
var UglifyJS  = require('uglify-js');
var cleanCSS  = require('clean-css');
var gzip      = require('gzip-js');

module.exports = function (task) {
    task
    .id('build')
    .name('Build')
    .author('Indigo United')
    .description('Build project')
    .option('env', 'The environment to build', 'prod')

    .setup(function (opts, ctx, next) {
        // Validate environment
        if (opts.env === 'dev') {
            return next(new Error('dev environment can\'t be built'));
        }

        var cwd = process.cwd();
        fs.readFile(cwd + '/app/config/config_' + opts.env + '.js', function (err, contents) {
            if (err) {
                return next(new Error('Unknown environment: ' + opts.env));
            }

            // Expose the version in the opts
            // Convert from decimal base to base36 to decrease the size of the number
            opts.version = Date.now().toString(36);

            // Set some necessary vars to be used bellow
            opts.targetDir = cwd  + '/web/' + opts.env;
            opts.tempDir = cwd + '/tmp';
            opts.projectDir = cwd;

            ctx.log.writeln('Will build version ' + opts.version.green);
            next();
        });
    })

    .do('rm', {
        description: 'Clean up previous build',
        options: {
            files: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('mkdir', {
        description: 'Create build folder',
        options: {
            dirs: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('cp', {
        description: 'Copy necessary files to temporary folder',
        options: {
            files: {
                '{{projectDir}}/app/**/*': '{{tempDir}}/app/',
                '{{projectDir}}/src/**/*': '{{tempDir}}/src/',
                '{{projectDir}}/bower_components/**/*': '{{tempDir}}/bower_components/',
                '{{projectDir}}/*': '{{tempDir}}/'
            }
        }
    })
    .do(function (opts, ctx, next) {
        var loaderFile = opts.tempDir + '/app/loader.js';

        fs.readFile(loaderFile, function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents.toString().replace(/\/app\/config\/config_\w+/g, '/app/config/config_' + opts.env);
            fs.writeFile(loaderFile, contents, next);
        });
    }, {
        description: 'Change target environment in loader config'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        rjs.optimize({
            // Loader settings
            mainConfigFile: opts.tempDir + '/app/loader.js',       // Include the main configuration file
            baseUrl: opts.tempDir + '/src',                        // Point to the tmp folder
            // r.js specific settings
            name: '../bower_components/almond/almond',                      // Use almond
            include: ['../app/loader', '../app/bootstrap'],
            out: opts.tempDir + '/app.js',
            has: {
                debug: false
            },
            optimize: 'none',
            separateCSS: true,
            stubModules: ['has', 'text', 'css', 'css/css', 'css/normalize']
        }, function (log) {
            ctx.log.info(log);
            next();
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Run r.js optimizer'
    })
    .do(function (opts, ctx, next) {
        // Replace baseUrl with the correct environment
        fs.readFile(opts.tempDir + '/app.js', function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents.toString().replace('\'./dev/src\'', '\'./' + opts.env + '/src\'');

            fs.writeFile(opts.tempDir + '/app.js', contents, next);
        });
    }, {
        description: 'Replace base URL'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        rjs.optimize({
            optimizeCss: 'standard.keepLines',
            cssIn: opts.tempDir + '/app.css',
            out: opts.tempDir + '/app.css',
            preserveLicenseComments: opts.licenses
        }, function (log) {
            ctx.log.write(log);

            // Replace trailing css from loader defs
            fs.readFile(opts.tempDir + '/app.js', function (err, contents) {
                if (err) {
                    return next(err);
                }

                contents = contents.toString().replace(/css!(.*?)\.css/g, 'css!$1');
                fs.writeFile(opts.tempDir + '/app.js', contents, next);
            });
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Expand css files'
    })
    .do('mv', {
        description: 'Move assets to the build folder',
        options: {
            files: {
                '{{tempDir}}/src/**/assets/!(css|tmpl)/**/*': '{{targetDir}}/src/',
                '{{tempDir}}/app.js': '{{targetDir}}/app.js',
                '{{tempDir}}/app.css': '{{targetDir}}/app.css'
            }
        }
    })
    // TODO. create automaton task for cache busting or use scaffolding-replace with regexp support
    .do(function (opts, ctx, next) {
        var index = opts.projectDir + '/web/index_' + opts.env + '.html',
            css = opts.targetDir + '/app.css';

        // Update index file
        fs.readFile(index, function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents
                .toString()
                .replace(/(app(?:\.min)?\.(?:css|js))(?:\?\w+)?/g, function (all, match) {
                    return match + '?' + opts.version;
                });

            fs.writeFile(index, contents, function (err) {
                if (err) {
                    return next(err);
                }

                // Update css file
                fs.readFile(css, function (err, contents) {
                    if (err) {
                        return next(err);
                    }

                    contents = contents
                        .toString()
                        .replace(/(url\s*\(["']?)(.*?)(["']?\))/ig, function (match, start, url, end) {
                            url = start + url.split('?', 2)[0] + '?' + opts.version + end;
                            return url;
                        });

                    fs.writeFile(css, contents, next);
                });
            });
        });
    }, {
        description: 'Apply cache busting'
    })
    // TODO: create automaton task for this (minjs)
    .do(function (opts, ctx, next) {
        // TODO: minified also contains a .map with the source mappings
        //       investigate how to integrate it!
        var minified = UglifyJS.minify(opts.targetDir + '/app.js'),
            minifiedSize = String(minified.code.length),
            gzipSize = String(gzip.zip(minified.code, {}).length);

        ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

        fs.writeFile(opts.targetDir + '/app.min.js', minified.code, next);
    }, {
        description: 'Minify js file'
    })
    // TODO: create automaton task for this (mincss)
    .do(function (opts, ctx, next) {
        fs.readFile(opts.targetDir + '/app.css', function (err, contents) {
            if (err) {
                return next(err);
            }

            var minified = cleanCSS.process(contents.toString(), opts),
                minifiedSize = String(minified.length),
                gzipSize = String(gzip.zip(minified, {}).length);

            ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

            fs.writeFile(opts.targetDir + '/app.min.css', minified, next);
        });
    }, {
        description: 'Minify css file'
    })
    .do('rm', {
        description: 'Clean up temporary files',
        options: {
            files: '{{tempDir}}'
        }
    });
};
<|endoftext|>


<commit_before>'use strict';

const model = require('../mongo/model');
const aggregation = require('../mongo/models/aggregation');

exports.getData = function* (next) {
    const since = +this.query.since || 0;
    const limit = +this.query.limit || 100;
    const db = this.params.name;

    const Model = model.getAggregation(db);
    const d = yield Model.find({seqid: {$gt: since}})
        .sort({seqid: 'asc'})
        .select({seqid: 1, value: 1})
        .limit(limit).exec();

    var body = {
        lastSeqId: d.length ? d[d.length-1].seqid : 0,
        data: d
    };

    this.body = body;
    this.status = 200;

    yield next;
};

exports.getInfo = function * (next) {
    const since = +this.query.since || 0;
    const db = this.params.name;

    this.body = {
        data: {
            remaining: yield aggregation.countFromSeqId(db, since),
            total: yield aggregation.count(db)
        }
    };
    this.status = 200;
    yield next;
};
<commit_msg>Update middleware.js<commit_after>'use strict';

const model = require('../mongo/model');
const aggregation = require('../mongo/models/aggregation');

exports.getData = function* (next) {
    const since = +this.query.since || 0;
    const limit = +this.query.limit || 100;
    const db = this.params.name;

    const Model = model.getAggregation(db);
    const d = yield Model.find({seqid: {$gt: since}})
        .sort({seqid: 'asc'})
        .select({_id: -1, __v: -1})
        .limit(limit).exec();

    var body = {
        lastSeqId: d.length ? d[d.length-1].seqid : 0,
        data: d
    };

    this.body = body;
    this.status = 200;

    yield next;
};

exports.getInfo = function * (next) {
    const since = +this.query.since || 0;
    const db = this.params.name;

    this.body = {
        data: {
            remaining: yield aggregation.countFromSeqId(db, since),
            total: yield aggregation.count(db)
        }
    };
    this.status = 200;
    yield next;
};
<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macro';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkTexture from 'vtk.js/Sources/Rendering/Core/Texture';
import vtkCubeSource from 'vtk.js/Sources/Filters/Sources/CubeSource';
import ImageHelper from 'vtk.js/Sources/Common/Core/ImageHelper';

const FACE_TO_INDEX = {
  xPlus: 0,
  xMinus: 1,
  yPlus: 2,
  yMinus: 3,
  zPlus: 4,
  zMinus: 5,
};

// ----------------------------------------------------------------------------
// vtkAnnotatedCubeActor
// ----------------------------------------------------------------------------

function vtkAnnotatedCubeActor(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkAnnotatedCubeActor');

  // Make sure face properties are not references to the default value
  model.xPlusFaceProperty = Object.assign({}, model.xPlusFaceProperty);
  model.xMinusFaceProperty = Object.assign({}, model.xMinusFaceProperty);
  model.yPlusFaceProperty = Object.assign({}, model.yPlusFaceProperty);
  model.yMinusFaceProperty = Object.assign({}, model.yMinusFaceProperty);
  model.zPlusFaceProperty = Object.assign({}, model.zPlusFaceProperty);
  model.zMinusFaceProperty = Object.assign({}, model.zMinusFaceProperty);

  // private variables

  let cubeSource = null;

  const canvas = document.createElement('canvas');
  const mapper = vtkMapper.newInstance();
  const texture = vtkTexture.newInstance();
  texture.setInterpolate(true);

  // private methods

  function updateFaceTexture(faceName, newProp = null) {
    if (newProp) {
      Object.assign(model[`${faceName}FaceProperty`], newProp);
    }

    const prop = Object.assign(
      {},
      model.defaultStyle,
      model[`${faceName}FaceProperty`]
    );

    // set canvas resolution
    canvas.width = prop.resolution;
    canvas.height = prop.resolution;

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

    // set background color
    ctxt.fillStyle = prop.faceColor;
    ctxt.fillRect(0, 0, canvas.width, canvas.height);

    // draw edge
    if (prop.edgeThickness > 0) {
      ctxt.strokeStyle = prop.edgeColor;
      ctxt.lineWidth = prop.edgeThickness * canvas.width;
      ctxt.strokeRect(0, 0, canvas.width, canvas.height);
    }

    // set face rotation
    ctxt.save();

    // vertical flip
    ctxt.translate(0, canvas.height);
    ctxt.scale(1, -1);

    ctxt.translate(canvas.width / 2, canvas.height / 2);
    ctxt.rotate(-Math.PI * (prop.faceRotation / 180.0));

    // set foreground text
    const textSize = prop.fontSizeScale(prop.resolution);
    ctxt.fillStyle = prop.fontColor;
    ctxt.textAlign = 'center';
    ctxt.textBaseline = 'middle';
    ctxt.font = `${prop.fontStyle} ${textSize}px "${prop.fontFamily}"`;
    ctxt.fillText(prop.text, 0, 0);

    ctxt.restore();

    const vtkImage = ImageHelper.canvasToImageData(canvas);
    texture.setInputData(vtkImage, FACE_TO_INDEX[faceName]);
    publicAPI.modified();
  }

  function updateAllFaceTextures() {
    cubeSource = vtkCubeSource.newInstance({
      generate3DTextureCoordinates: true,
    });

    mapper.setInputConnection(cubeSource.getOutputPort());

    updateFaceTexture('xPlus');
    updateFaceTexture('xMinus');
    updateFaceTexture('yPlus');
    updateFaceTexture('yMinus');
    updateFaceTexture('zPlus');
    updateFaceTexture('zMinus');
  }

  // public methods

  publicAPI.setDefaultStyle = (style) => {
    model.defaultStyle = Object.assign({}, model.defaultStyle, style);
    updateAllFaceTextures();
  };

  publicAPI.setXPlusFaceProperty = (prop) => updateFaceTexture('xPlus', prop);
  publicAPI.setXMinusFaceProperty = (prop) => updateFaceTexture('xMinus', prop);
  publicAPI.setYPlusFaceProperty = (prop) => updateFaceTexture('yPlus', prop);
  publicAPI.setYMinusFaceProperty = (prop) => updateFaceTexture('yMinus', prop);
  publicAPI.setZPlusFaceProperty = (prop) => updateFaceTexture('zPlus', prop);
  publicAPI.setZMinusFaceProperty = (prop) => updateFaceTexture('zMinus', prop);

  // constructor

  updateAllFaceTextures();

  // set mapper
  mapper.setInputConnection(cubeSource.getOutputPort());
  publicAPI.setMapper(mapper);

  // set texture
  publicAPI.addTexture(texture);
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

export const DEFAULT_VALUES = {
  defaultStyle: {
    text: '',
    faceColor: 'white',
    faceRotation: 0,
    fontFamily: 'Arial',
    fontColor: 'black',
    fontStyle: 'normal',
    fontSizeScale: (resolution) => resolution / 1.8,
    edgeThickness: 0.1,
    edgeColor: 'black',
    resolution: 200,
  },
  // xPlusFaceProperty: null,
  // xMinusFaceProperty: null,
  // yPlusFaceProperty: null,
  // yMinusFaceProperty: null,
  // zPlusFaceProperty: null,
  // zMinusFaceProperty: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Inheritance
  vtkActor.extend(publicAPI, model, initialValues);

  macro.get(publicAPI, model, [
    'defaultStyle',
    'xPlusFaceProperty',
    'xMinusFaceProperty',
    'yPlusFaceProperty',
    'yMinusFaceProperty',
    'zPlusFaceProperty',
    'zMinusFaceProperty',
  ]);

  // Object methods
  vtkAnnotatedCubeActor(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkAnnotatedCubeActor');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(AnnotatedCubeActor): Add presets to exports<commit_after>import macro from 'vtk.js/Sources/macro';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkTexture from 'vtk.js/Sources/Rendering/Core/Texture';
import vtkCubeSource from 'vtk.js/Sources/Filters/Sources/CubeSource';
import ImageHelper from 'vtk.js/Sources/Common/Core/ImageHelper';

import Presets from 'vtk.js/Sources/Rendering/Core/AnnotatedCubeActor/Presets';

const FACE_TO_INDEX = {
  xPlus: 0,
  xMinus: 1,
  yPlus: 2,
  yMinus: 3,
  zPlus: 4,
  zMinus: 5,
};

// ----------------------------------------------------------------------------
// vtkAnnotatedCubeActor
// ----------------------------------------------------------------------------

function vtkAnnotatedCubeActor(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkAnnotatedCubeActor');

  // Make sure face properties are not references to the default value
  model.xPlusFaceProperty = Object.assign({}, model.xPlusFaceProperty);
  model.xMinusFaceProperty = Object.assign({}, model.xMinusFaceProperty);
  model.yPlusFaceProperty = Object.assign({}, model.yPlusFaceProperty);
  model.yMinusFaceProperty = Object.assign({}, model.yMinusFaceProperty);
  model.zPlusFaceProperty = Object.assign({}, model.zPlusFaceProperty);
  model.zMinusFaceProperty = Object.assign({}, model.zMinusFaceProperty);

  // private variables

  let cubeSource = null;

  const canvas = document.createElement('canvas');
  const mapper = vtkMapper.newInstance();
  const texture = vtkTexture.newInstance();
  texture.setInterpolate(true);

  // private methods

  function updateFaceTexture(faceName, newProp = null) {
    if (newProp) {
      Object.assign(model[`${faceName}FaceProperty`], newProp);
    }

    const prop = Object.assign(
      {},
      model.defaultStyle,
      model[`${faceName}FaceProperty`]
    );

    // set canvas resolution
    canvas.width = prop.resolution;
    canvas.height = prop.resolution;

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

    // set background color
    ctxt.fillStyle = prop.faceColor;
    ctxt.fillRect(0, 0, canvas.width, canvas.height);

    // draw edge
    if (prop.edgeThickness > 0) {
      ctxt.strokeStyle = prop.edgeColor;
      ctxt.lineWidth = prop.edgeThickness * canvas.width;
      ctxt.strokeRect(0, 0, canvas.width, canvas.height);
    }

    // set face rotation
    ctxt.save();

    // vertical flip
    ctxt.translate(0, canvas.height);
    ctxt.scale(1, -1);

    ctxt.translate(canvas.width / 2, canvas.height / 2);
    ctxt.rotate(-Math.PI * (prop.faceRotation / 180.0));

    // set foreground text
    const textSize = prop.fontSizeScale(prop.resolution);
    ctxt.fillStyle = prop.fontColor;
    ctxt.textAlign = 'center';
    ctxt.textBaseline = 'middle';
    ctxt.font = `${prop.fontStyle} ${textSize}px "${prop.fontFamily}"`;
    ctxt.fillText(prop.text, 0, 0);

    ctxt.restore();

    const vtkImage = ImageHelper.canvasToImageData(canvas);
    texture.setInputData(vtkImage, FACE_TO_INDEX[faceName]);
    publicAPI.modified();
  }

  function updateAllFaceTextures() {
    cubeSource = vtkCubeSource.newInstance({
      generate3DTextureCoordinates: true,
    });

    mapper.setInputConnection(cubeSource.getOutputPort());

    updateFaceTexture('xPlus');
    updateFaceTexture('xMinus');
    updateFaceTexture('yPlus');
    updateFaceTexture('yMinus');
    updateFaceTexture('zPlus');
    updateFaceTexture('zMinus');
  }

  // public methods

  publicAPI.setDefaultStyle = (style) => {
    model.defaultStyle = Object.assign({}, model.defaultStyle, style);
    updateAllFaceTextures();
  };

  publicAPI.setXPlusFaceProperty = (prop) => updateFaceTexture('xPlus', prop);
  publicAPI.setXMinusFaceProperty = (prop) => updateFaceTexture('xMinus', prop);
  publicAPI.setYPlusFaceProperty = (prop) => updateFaceTexture('yPlus', prop);
  publicAPI.setYMinusFaceProperty = (prop) => updateFaceTexture('yMinus', prop);
  publicAPI.setZPlusFaceProperty = (prop) => updateFaceTexture('zPlus', prop);
  publicAPI.setZMinusFaceProperty = (prop) => updateFaceTexture('zMinus', prop);

  // constructor

  updateAllFaceTextures();

  // set mapper
  mapper.setInputConnection(cubeSource.getOutputPort());
  publicAPI.setMapper(mapper);

  // set texture
  publicAPI.addTexture(texture);
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

export const DEFAULT_VALUES = {
  defaultStyle: {
    text: '',
    faceColor: 'white',
    faceRotation: 0,
    fontFamily: 'Arial',
    fontColor: 'black',
    fontStyle: 'normal',
    fontSizeScale: (resolution) => resolution / 1.8,
    edgeThickness: 0.1,
    edgeColor: 'black',
    resolution: 200,
  },
  // xPlusFaceProperty: null,
  // xMinusFaceProperty: null,
  // yPlusFaceProperty: null,
  // yMinusFaceProperty: null,
  // zPlusFaceProperty: null,
  // zMinusFaceProperty: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Inheritance
  vtkActor.extend(publicAPI, model, initialValues);

  macro.get(publicAPI, model, [
    'defaultStyle',
    'xPlusFaceProperty',
    'xMinusFaceProperty',
    'yPlusFaceProperty',
    'yMinusFaceProperty',
    'zPlusFaceProperty',
    'zMinusFaceProperty',
  ]);

  // Object methods
  vtkAnnotatedCubeActor(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkAnnotatedCubeActor');

// ----------------------------------------------------------------------------

export default { newInstance, extend, Presets };
<|endoftext|>


<commit_before>requirejs.config({
    'baseUrl': '../lib',
    'paths': {
        'leaflet.wms': '../leaflet.wms' //.js'
    }
});

define(['leaflet', 'leaflet.wms'],
function(L, wms) {

var overlayMap = createMap('overlay-map', false);
var tiledMap = createMap('tiled-map', true);

function createMap(div, tiled) {
    // Map configuration
    var map = L.map(div);
    map.setView([45, -93.2], 6);

    var basemaps = {
        'Basemap': basemap(),
        'Blank': blank().addTo(map)
    };

    // Add WMS source/layers
    var source = wms.source(
        "http://webservices.nationalatlas.gov/wms",
        {
            "format": "image/png",
            "transparent": "true",
            "attribution": "NationalAtlas.gov",
            "tiled": tiled
        }
    );

    var layers = {
        'Time Zones': source.getLayer("timezones"),
        'Lakes & Rivers': source.getLayer("lakesrivers"),
        'Airports': source.getLayer("airports"),
        'State Capitals': source.getLayer("statecap")
    };
    for (var name in layers) {
        layers[name].addTo(map);
    }

    // Create layer control
    L.control.layers(basemaps, layers).addTo(map);

    // Opacity slider
    var slider = L.DomUtil.get('range-' + div);
    L.DomEvent.addListener(slider, 'change', function() {
        source.setOpacity(this.value);
    });
    return map;
}

function basemap() {
    // Attribution (https://gist.github.com/mourner/1804938)
    var mqcdn = "http://otile{s}.mqcdn.com/tiles/1.0.0/{type}/{z}/{x}/{y}.png";
    var osmAttr = 'Map data © OpenStreetMap contributors, CC-BY-SA';
    var mqTilesAttr = 'Tiles © MapQuest ';
    return L.tileLayer(mqcdn, {
        'subdomains': '1234',
        'type': 'map',
        'attribution': osmAttr + ', ' + mqTilesAttr
    });
}

function blank() {
    var layer = new L.Layer();
    layer.onAdd = layer.onRemove = function() {};
    return layer;
}

// Export maps for console experimentation
return {
    'maps': {
        'overlay': overlayMap,
        'tiled': tiledMap
    }
};

});

<commit_msg>update broken map layers (fixes #27)<commit_after>requirejs.config({
    'baseUrl': '../lib',
    'paths': {
        'leaflet.wms': '../leaflet.wms' //.js'
    }
});

define(['leaflet', 'leaflet.wms'],
function(L, wms) {

var overlayMap = createMap('overlay-map', false);
var tiledMap = createMap('tiled-map', true);

function createMap(div, tiled) {
    // Map configuration
    var map = L.map(div);
    map.setView([45, -93.2], 6);

    var basemaps = {
        'Basemap': basemap().addTo(map),
        'Blank': blank()
    };

    // Add WMS source/layers
    var source = wms.source(
        "http://services.nationalmap.gov/arcgis/services/GlobalMap/GlobalMapWMS/MapServer/WMSServer",
        {
            "format": "image/png",
            "transparent": "true",
            "attribution": "NationalAtlas.gov",
            "info_format": "text/html",
            "tiled": tiled
        }
    );

    var layers = {
        'Water Courses': source.getLayer("18"),
        'Airports': source.getLayer("14").addTo(map),
        'Large Cities': source.getLayer("27").addTo(map),
        'Medium Cities': source.getLayer("26").addTo(map)
    };

    // Create layer control
    L.control.layers(basemaps, layers).addTo(map);

    // Opacity slider
    var slider = L.DomUtil.get('range-' + div);
    L.DomEvent.addListener(slider, 'change', function() {
        source.setOpacity(this.value);
    });
    return map;
}

function basemap() {
    // maps.stamen.com
    var attr = 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL.';
    return L.tileLayer("http://tile.stamen.com/toner-background/{z}/{x}/{y}.png", {
        opacity: 0.1,
        attribution: attr
    });
}

function blank() {
    var layer = new L.Layer();
    layer.onAdd = layer.onRemove = function() {};
    return layer;
}

// Export maps for console experimentation
return {
    'maps': {
        'overlay': overlayMap,
        'tiled': tiledMap
    }
};

});

<|endoftext|>


<commit_before>var express = require('express')
, passport = require('passport')
, session = require('express-session')
, NaverStrategy = require('../lib/index.js').Strategy;

var client_id = '************ your app client id ************';
var client_secret = '************ your app client secret ************';
var callback_url = '************ your app callback url ************';

passport.serializeUser(function(user, done) {
	done(null, user);
});

passport.deserializeUser(function(obj, done) {
	done(null, obj);
});

passport.use(new NaverStrategy({
    clientID: client_id,
    clientSecret: client_secret,
    callbackURL: callback_url
}, function(accessToken, refreshToken, profile, done) {
	process.nextTick(function () {
		//console.log("profile=");
		//console.log(profile);
		// data to be saved in DB
		user = {
			name: profile.displayName,
			email: profile.emails[0].value,
			username: profile.displayName,
			provider: 'naver',
			naver: profile._json
		};
		//console.log("user=");
		//console.log(user);
		return done(null, profile);
	});
}));

var app = express();

app.use(session({secret: 'keyboard cat'}));
app.use(passport.initialize());
app.use(passport.session());

app.set('view engine', 'jade');
app.set('views', __dirname + '/views/');

app.get('/', function(req, res){
	res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res) {
	console.log(req.user);
	res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
	res.render('login', { user: req.user });
});

// Setting the naver oauth routes
app.get('/auth/naver',
	passport.authenticate('naver', null), function(req, res) {
    	console.log('/auth/naver failed, stopped');
    });

// creates an account if no account of the new user
app.get('/auth/naver/callback',
	passport.authenticate('naver', {
        failureRedirect: '#!/auth/login'
    }), function(req, res) {
    	res.redirect('/');
    });

app.get('/logout', function(req, res){
	req.logout();
	res.redirect('/');
});

app.listen(3000);

function ensureAuthenticated(req, res, next) {
	if (req.isAuthenticated()) { return next(); }
	res.redirect('/login');
}
<commit_msg>Added todo of example code.<commit_after>var express = require('express')
, passport = require('passport')
, session = require('express-session')
, NaverStrategy = require('../lib/index.js').Strategy;

// @todo Use single `var` keyword?
var client_id = '************ your app client id ************';
var client_secret = '************ your app client secret ************';
var callback_url = '************ your app callback url ************';

passport.serializeUser(function(user, done) {
	done(null, user);
});

passport.deserializeUser(function(obj, done) {
	done(null, obj);
});

passport.use(new NaverStrategy({
    clientID: client_id,
    clientSecret: client_secret,
    callbackURL: callback_url
	// @todo Suggest to use `state` parameter?
}, function(accessToken, refreshToken, profile, done) {
	process.nextTick(function () {
		// @todo Remove necessary comment
		//console.log("profile=");
		//console.log(profile);
		// data to be saved in DB
		user = {
			name: profile.displayName,
			email: profile.emails[0].value,
			username: profile.displayName,
			provider: 'naver',
			naver: profile._json
		};
		//console.log("user=");
		//console.log(user);
		return done(null, profile);
	});
}));

var app = express();

app.use(session({secret: 'keyboard cat'}));
app.use(passport.initialize());
app.use(passport.session());

app.set('view engine', 'jade');
app.set('views', __dirname + '/views/');

app.get('/', function(req, res){
	res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res) {
	console.log(req.user);
	res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
	res.render('login', { user: req.user });
});

// Setting the naver oauth routes
app.get('/auth/naver',
	passport.authenticate('naver', null), function(req, res) { // @todo Additional handler is necessary. Remove?
    	console.log('/auth/naver failed, stopped');
    });

// creates an account if no account of the new user
app.get('/auth/naver/callback',
	passport.authenticate('naver', {
        failureRedirect: '#!/auth/login'
    }), function(req, res) {
    	res.redirect('/');
    });

app.get('/logout', function(req, res){
	req.logout();
	res.redirect('/');
});

app.listen(3000);

function ensureAuthenticated(req, res, next) {
	if (req.isAuthenticated()) { return next(); }
	res.redirect('/login');
}
<|endoftext|>