<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.www';
import typeof * as DynamicFeatureFlags from './ReactFeatureFlags.www-dynamic';

// Re-export dynamic flags from the www version.
const dynamicFeatureFlags: DynamicFeatureFlags = require('ReactFeatureFlags');

export const {
  debugRenderPhaseSideEffectsForStrictMode,
  disableInputAttributeSyncing,
  enableTrustedTypesIntegration,
  disableSchedulerTimeoutBasedOnReactExpirationTime,
  warnAboutSpreadingKeyToJSX,
  replayFailedUnitOfWorkWithInvokeGuardedCallback,
  enableFilterEmptyStringAttributesDOM,
  enableLegacyFBSupport,
  deferRenderPhaseUpdateToNextBatch,
  decoupleUpdatePriorityFromScheduler,
  enableDebugTracing,
  skipUnmountedBoundaries,
  enableEagerRootListeners,
  enableDoubleInvokingEffects,
} = dynamicFeatureFlags;

// On WWW, __EXPERIMENTAL__ is used for a new modern build.
// It's not used anywhere in production yet.

export const enableProfilerTimer = __PROFILE__;

// Temporarily disable commit hooks flag to verify it does not cause a regression.
// TODO (brian) Re-enable this flag if performance is mostly neutral.
export const enableProfilerCommitHooks = false;

// Logs additional User Timing API marks for use with an experimental profiling tool.
export const enableSchedulingProfiler = __PROFILE__;

// Note: we'll want to remove this when we to userland implementation.
// For now, we'll turn it on for everyone because it's *already* on for everyone in practice.
// At least this will let us stop shipping <Profiler> implementation to all users.
export const enableSchedulerTracing = true;
export const enableSchedulerDebugging = true;

export const warnAboutDeprecatedLifecycles = true;
export const disableLegacyContext = __EXPERIMENTAL__;
export const warnAboutStringRefs = false;
export const warnAboutDefaultPropsOnFunctionComponents = false;

export const enableSuspenseServerRenderer = true;
export const enableSelectiveHydration = true;

export const enableBlocksAPI = true;
export const enableLazyElements = true;

export const disableJavaScriptURLs = true;

export const disableModulePatternComponents = true;

export const enableCreateEventHandleAPI = true;

export const enableFundamentalAPI = false;

export const enableScopeAPI = true;

export const warnAboutUnmockedScheduler = true;

export const enableSuspenseCallback = true;

export const enableComponentStackLocations = true;

export const disableTextareaChildren = __EXPERIMENTAL__;

export const warnUnstableRenderSubtreeIntoContainer = false;

export const enableDiscreteEventFlushingChange = true;

// Enable forked reconciler. Piggy-backing on the "variant" global so that we
// don't have to add another test dimension. The build system will compile this
// to the correct value.
export const enableNewReconciler = __VARIANT__;

// Flow magic to verify the exports of this file match the original version.
// eslint-disable-next-line no-unused-vars
type Check<_X, Y: _X, X: Y = _X> = null;
// eslint-disable-next-line no-unused-expressions
(null: Check<ExportsType, FeatureFlagsType>);
<commit_msg>Revert "Temporarily disable Profiler commit hooks flag (#19900)" (#19960)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.www';
import typeof * as DynamicFeatureFlags from './ReactFeatureFlags.www-dynamic';

// Re-export dynamic flags from the www version.
const dynamicFeatureFlags: DynamicFeatureFlags = require('ReactFeatureFlags');

export const {
  debugRenderPhaseSideEffectsForStrictMode,
  disableInputAttributeSyncing,
  enableTrustedTypesIntegration,
  disableSchedulerTimeoutBasedOnReactExpirationTime,
  warnAboutSpreadingKeyToJSX,
  replayFailedUnitOfWorkWithInvokeGuardedCallback,
  enableFilterEmptyStringAttributesDOM,
  enableLegacyFBSupport,
  deferRenderPhaseUpdateToNextBatch,
  decoupleUpdatePriorityFromScheduler,
  enableDebugTracing,
  skipUnmountedBoundaries,
  enableEagerRootListeners,
  enableDoubleInvokingEffects,
} = dynamicFeatureFlags;

// On WWW, __EXPERIMENTAL__ is used for a new modern build.
// It's not used anywhere in production yet.

export const enableProfilerTimer = __PROFILE__;
export const enableProfilerCommitHooks = __PROFILE__;

// Logs additional User Timing API marks for use with an experimental profiling tool.
export const enableSchedulingProfiler = __PROFILE__;

// Note: we'll want to remove this when we to userland implementation.
// For now, we'll turn it on for everyone because it's *already* on for everyone in practice.
// At least this will let us stop shipping <Profiler> implementation to all users.
export const enableSchedulerTracing = true;
export const enableSchedulerDebugging = true;

export const warnAboutDeprecatedLifecycles = true;
export const disableLegacyContext = __EXPERIMENTAL__;
export const warnAboutStringRefs = false;
export const warnAboutDefaultPropsOnFunctionComponents = false;

export const enableSuspenseServerRenderer = true;
export const enableSelectiveHydration = true;

export const enableBlocksAPI = true;
export const enableLazyElements = true;

export const disableJavaScriptURLs = true;

export const disableModulePatternComponents = true;

export const enableCreateEventHandleAPI = true;

export const enableFundamentalAPI = false;

export const enableScopeAPI = true;

export const warnAboutUnmockedScheduler = true;

export const enableSuspenseCallback = true;

export const enableComponentStackLocations = true;

export const disableTextareaChildren = __EXPERIMENTAL__;

export const warnUnstableRenderSubtreeIntoContainer = false;

export const enableDiscreteEventFlushingChange = true;

// Enable forked reconciler. Piggy-backing on the "variant" global so that we
// don't have to add another test dimension. The build system will compile this
// to the correct value.
export const enableNewReconciler = __VARIANT__;

// Flow magic to verify the exports of this file match the original version.
// eslint-disable-next-line no-unused-vars
type Check<_X, Y: _X, X: Y = _X> = null;
// eslint-disable-next-line no-unused-expressions
(null: Check<ExportsType, FeatureFlagsType>);
<|endoftext|>


<commit_before>'use strict';

var angular = require('camunda-bpm-sdk-js/vendor/angular');
var CamSDK = require('camunda-bpm-sdk-js/lib/angularjs/index');

module.exports = ['$rootScope', '$timeout', function($rootScope, $timeout) {

  function AngularClient(config) {
    this._wrapped = new CamSDK.Client.HttpClient(config);
  }

  angular.forEach(['post', 'get', 'load', 'put', 'del', 'options', 'head'], function(name) {
    AngularClient.prototype[name] = function(path, options) {
      if (!options.done) {
        return;
      }

      var myTimeout = $timeout(function() {}, 100000);

      var original = options.done;

      options.done = function(err, result) {

        function applyResponse() {
            // in case the session expired
          if (err && err.status === 401) {
              // broadcast that the authentication changed
            $rootScope.$broadcast('authentication.changed', null);
              // set authentication to null
            $rootScope.authentication = null;
              // broadcast event that a login is required
              // proceeds a redirect to /login
            $rootScope.$broadcast('authentication.login.required');
            return;
          }

          original(err, result);
        }

        var phase = $rootScope.$$phase;

        if(phase !== '$apply' && phase !== '$digest') {
          $rootScope.$apply(applyResponse);
        }
        else {
          applyResponse();
        }
        $timeout.cancel(myTimeout);
      };

      this._wrapped[name](path, options);
    };
  });

  angular.forEach(['on', 'once', 'off', 'trigger'], function(name) {
    AngularClient.prototype[name] = function() {
      this._wrapped[name].apply(this, arguments);
    };
  });

  return AngularClient;
}];
<commit_msg>improve: support for promisses in http client<commit_after>'use strict';

var angular = require('camunda-bpm-sdk-js/vendor/angular');
var CamSDK = require('camunda-bpm-sdk-js/lib/angularjs/index');

module.exports = ['$rootScope', '$timeout' , '$q', function($rootScope, $timeout, $q) {

  function AngularClient(config) {
    this._wrapped = new CamSDK.Client.HttpClient(config);
  }

  angular.forEach(['post', 'get', 'load', 'put', 'del', 'options', 'head'], function(name) {
    AngularClient.prototype[name] = function(path, options) {
      var myTimeout = $timeout(function() {}, 100000);

      var original = options.done;

      options.done = function(err, result) {

        function applyResponse() {
            // in case the session expired
          if (err && err.status === 401) {
              // broadcast that the authentication changed
            $rootScope.$broadcast('authentication.changed', null);
              // set authentication to null
            $rootScope.authentication = null;
              // broadcast event that a login is required
              // proceeds a redirect to /login
            $rootScope.$broadcast('authentication.login.required');
            return;
          }

          original(err, result);
        }

        var phase = $rootScope.$$phase;

        if(phase !== '$apply' && phase !== '$digest') {
          $rootScope.$apply(applyResponse);
        }
        else {
          applyResponse();
        }
        $timeout.cancel(myTimeout);
      };

      return $q.when(
        this._wrapped[name](path, options)
      );
    };
  });

  angular.forEach(['on', 'once', 'off', 'trigger'], function(name) {
    AngularClient.prototype[name] = function() {
      this._wrapped[name].apply(this, arguments);
    };
  });

  return AngularClient;
}];
<|endoftext|>


<commit_before>"use strict";

var ModelCollection = require("./ModelCollection.class.js"),
    modelCache = require("./modelCache.js"),
    services = require("./registries/serviceRegistry.js"),
    environment = require("./environment.js"),
    RemoteService = require("../client/RemoteService.js");

/**
 * Find a fully populated model-Instance by given ID
 *
 * Returns a cached instance if already in cache
 * Creates a new instance if nothing was found in cache an populates it with data (fetch)
 *
 * User.findById(12, function(err, user12){});
 *
 * User.findById(false, 12, function(err, user12){});
 *
 * User.findById({ Group : 2 }, 12, function(err, user12){});
 *
 * @param {Boolean} remote should the remote-service be contacted (default : true)
 * @param {Object} ids the parent IDs
 * @param {String|Number} id the ID of the model you want to load
 * @param {Function} callback
 */
function findById(remote, ids, id, callback) {

    var args = Array.prototype.slice.call(arguments, 0);

    //Called with three params
    if(typeof(id) === "function") {
        callback = args[2];

        //User.findById({ Group : 2 }, 12, function(err, user12){});
        if(typeof(args[0]) === "object") {
            ids = args[0];
            remote = true;
        }
        //User.findById(false, 12, function(err, user12){});
        else{
            ids = {};
        }

        id = args[1];
    }

    //called with two params
    //User.findById(12, function(err, user12){});
    if(typeof(ids) === "function") {
        callback = args[1];
        remote = true;
        id = args[0];
        ids = {};
    }

    var ModelClass = this;
    var instance = modelCache.get(ModelClass.prototype.url, id);

    //if we don't find an instance, we add one!
    if(instance === null) {
        instance = new ModelClass(id);
        //add instance to Cache
        modelCache.add(instance);
    }

    instance.setParentIds(ids);

    instance.fetch(remote, function(err) {
        if(err) {
            callback(err);
            return;
        }
        callback(null, instance);
    });
}

/**
 * Find a collection of models that match params and ids
 *
 * @param {Boolean} remote should the remoteService be contacted (default:true)
 * @param {Object} ids the parent ids for embedded-document finds
 * @param {!Object} params the params you want to select your models by
 * @param {Function} callback
 *
 *
 * User.find({ age : ">10"}, onFind);
 *
 * Comment.find({ blogPost : 1 }, { authorId : 3 }, onFind);
 *
 * //don't contact remoteServices
 * Comment.find(false, { blogPost : 1 }, { authorId : 3 }, onFind);
 *
 */
function find(remote, ids, params, callback) {

    function createInstances(modelDataArray) {
        var arrayElem,
            activeModelData,
            models = [],
            modelInstance;

        for(arrayElem in modelDataArray) {
            if(modelDataArray.hasOwnProperty(arrayElem)){
                activeModelData = modelDataArray[arrayElem];
                if(activeModelData.id !== undefined) {

                    //check for cached instances
                    modelInstance = modelCache.get(ModelClass.url, activeModelData.id);

                    if(modelInstance === null) {
                        modelInstance = new ModelClass(activeModelData.id);
                        modelCache.add(modelInstance);
                    }

                    //we can't set id via "set"
                    delete activeModelData.id;

                    //set parent IDs
                    if(activeModelData.ids !== undefined) {
                        modelInstance.setParentIds(activeModelData.ids);
                        //can't be used via SET
                        delete activeModelData.ids;
                    }

                    modelInstance.set(activeModelData);

                    models.push(modelInstance);
                }
            }
        }
        return models;
    }

    function onServiceResponse(response) {
        if(response.status === "success" && response.data !== undefined) {
            var modelsArray = createInstances(response.data);
            callback(null, new ModelCollection(ModelClass, modelsArray));
        }
        else {
            callback(new Error(response.message));
        }
    }

    var ModelClass = this,
        url = ModelClass.url,
        service = services.getService(url);

        var serviceFunction = service.readCollection,
        args = Array.prototype.slice.call(arguments, 0),
        serviceFunctionLength = serviceFunction.length;

    //we have to add one params which is remote
    //can be done by adding for server
    //or decrement on client
    //not really nice...
    if(environment.isServer()) {
        serviceFunctionLength++;
    }

    //check optional args
    if(args.length === 2) {
        params = args[0];
        callback = args[1];
        remote = true;
        ids = {};
    }
    else if(args.length === 3) {
        if(typeof(args[0]) === "object") {
            ids = args[0];
            remote = true;
        }
        else{
            ids = {};
            remote = args[0];
        }

        params = args[1];
        callback = args[2];
    }

    if(service === null) {
        throw new Error("(alamid) Can not call service: No service defined for '" + url + "'");
    }

    //we don't have remote on server-services!
    if(environment.isClient() && remote) {
        //load remote-service-adapter for given method
        remote = new RemoteService(url).readCollection;
    }

    if (serviceFunctionLength === 4) {
        if (!environment.isServer()) {
            serviceFunction(remote, ids, params, onServiceResponse);
        } else {
            serviceFunction(ids, params, onServiceResponse);
        }
    }
    else if(serviceFunctionLength === 3) {
        if (!environment.isServer()) {
            onServiceResponse(serviceFunction.apply(remote, ids, params));
        } else {
            onServiceResponse(serviceFunction.apply(ids, params));
        }
    }
    else {
        throw new Error("(alamid) Function '" +
            serviceFunction.toString().replace(/\s\{.*/, "") + "' accepts unexpected number of arguments (" + serviceFunctionLength + ")");
    }
}

exports.find = find;
exports.findById = findById;
<commit_msg>- scope error<commit_after>"use strict";

var ModelCollection = require("./ModelCollection.class.js"),
    modelCache = require("./modelCache.js"),
    services = require("./registries/serviceRegistry.js"),
    environment = require("./environment.js"),
    RemoteService = require("../client/RemoteService.js");

/**
 * Find a fully populated model-Instance by given ID
 *
 * Returns a cached instance if already in cache
 * Creates a new instance if nothing was found in cache an populates it with data (fetch)
 *
 * User.findById(12, function(err, user12){});
 *
 * User.findById(false, 12, function(err, user12){});
 *
 * User.findById({ Group : 2 }, 12, function(err, user12){});
 *
 * @param {Boolean} remote should the remote-service be contacted (default : true)
 * @param {Object} ids the parent IDs
 * @param {String|Number} id the ID of the model you want to load
 * @param {Function} callback
 */
function findById(remote, ids, id, callback) {

    var args = Array.prototype.slice.call(arguments, 0);

    //Called with three params
    if(typeof(id) === "function") {
        callback = args[2];

        //User.findById({ Group : 2 }, 12, function(err, user12){});
        if(typeof(args[0]) === "object") {
            ids = args[0];
            remote = true;
        }
        //User.findById(false, 12, function(err, user12){});
        else{
            ids = {};
        }

        id = args[1];
    }

    //called with two params
    //User.findById(12, function(err, user12){});
    if(typeof(ids) === "function") {
        callback = args[1];
        remote = true;
        id = args[0];
        ids = {};
    }

    var ModelClass = this;
    var instance = modelCache.get(ModelClass.prototype.url, id);

    //if we don't find an instance, we add one!
    if(instance === null) {
        instance = new ModelClass(id);
        //add instance to Cache
        modelCache.add(instance);
    }

    instance.setParentIds(ids);

    instance.fetch(remote, function(err) {
        if(err) {
            callback(err);
            return;
        }
        callback(null, instance);
    });
}

/**
 * Find a collection of models that match params and ids
 *
 * @param {Boolean} remote should the remoteService be contacted (default:true)
 * @param {Object} ids the parent ids for embedded-document finds
 * @param {!Object} params the params you want to select your models by
 * @param {Function} callback
 *
 *
 * User.find({ age : ">10"}, onFind);
 *
 * Comment.find({ blogPost : 1 }, { authorId : 3 }, onFind);
 *
 * //don't contact remoteServices
 * Comment.find(false, { blogPost : 1 }, { authorId : 3 }, onFind);
 *
 */
function find(remote, ids, params, callback) {

    function createInstances(modelDataArray) {
        var arrayElem,
            activeModelData,
            models = [],
            modelInstance;

        for(arrayElem in modelDataArray) {
            if(modelDataArray.hasOwnProperty(arrayElem)){
                activeModelData = modelDataArray[arrayElem];
                if(activeModelData.id !== undefined) {

                    //check for cached instances
                    modelInstance = modelCache.get(ModelClass.url, activeModelData.id);

                    if(modelInstance === null) {
                        modelInstance = new ModelClass(activeModelData.id);
                        modelCache.add(modelInstance);
                    }

                    //we can't set id via "set"
                    delete activeModelData.id;

                    //set parent IDs
                    if(activeModelData.ids !== undefined) {
                        modelInstance.setParentIds(activeModelData.ids);
                        //can't be used via SET
                        delete activeModelData.ids;
                    }

                    modelInstance.set(activeModelData);

                    models.push(modelInstance);
                }
            }
        }
        return models;
    }

    function onServiceResponse(response) {
        if(response.status === "success" && response.data !== undefined) {
            var modelsArray = createInstances(response.data);
            callback(null, new ModelCollection(ModelClass, modelsArray));
        }
        else {
            callback(new Error(response.message));
        }
    }

    var ModelClass = this,
        url = ModelClass.prototype.url,
        service = services.getService(url);

        var serviceFunction = service.readCollection,
        args = Array.prototype.slice.call(arguments, 0),
        serviceFunctionLength = serviceFunction.length;

    //we have to add one params which is remote
    //can be done by adding for server
    //or decrement on client
    //not really nice...
    if(environment.isServer()) {
        serviceFunctionLength++;
    }

    //check optional args
    if(args.length === 2) {
        params = args[0];
        callback = args[1];
        remote = true;
        ids = {};
    }
    else if(args.length === 3) {
        if(typeof(args[0]) === "object") {
            ids = args[0];
            remote = true;
        }
        else{
            ids = {};
            remote = args[0];
        }

        params = args[1];
        callback = args[2];
    }

    if(service === null) {
        throw new Error("(alamid) Can not call service: No service defined for '" + url + "'");
    }

    //we don't have remote on server-services!
    if(environment.isClient() && remote) {
        //load remote-service-adapter for given method
        remote = new RemoteService(url).readCollection;
    }

    if (serviceFunctionLength === 4) {
        if (!environment.isServer()) {
            serviceFunction(remote, ids, params, onServiceResponse);
        } else {
            serviceFunction(ids, params, onServiceResponse);
        }
    }
    else if(serviceFunctionLength === 3) {
        if (!environment.isServer()) {
            onServiceResponse(serviceFunction.apply(remote, ids, params));
        } else {
            onServiceResponse(serviceFunction.apply(ids, params));
        }
    }
    else {
        throw new Error("(alamid) Function '" +
            serviceFunction.toString().replace(/\s\{.*/, "") + "' accepts unexpected number of arguments (" + serviceFunctionLength + ")");
    }
}

exports.find = find;
exports.findById = findById;
<|endoftext|>


<commit_before>// @flow
import gray from 'gray-percentage'
import type { OptionsType } from 'Types'
import {
  MOBILE_MEDIA_QUERY,
  TABLET_MEDIA_QUERY,
} from 'typography-breakpoint-constants'

const theme: OptionsType = {
  title: 'Kirkham',
  baseFontSize: '18px',
  baseLineHeight: 1.44,
  scaleRatio: 2.15,
  blockMarginBottom: 0.75,
  googleFonts: [
    {
      name: 'Playfair Display',
      styles: ['700'],
    },
    {
      name: 'Fira Sans',
      styles: ['400', '400i', '700', '700i'],
    },
  ],
  headerFontFamily: ['Playfair Display', 'serif'],
  bodyFontFamily: ['Fira Sans', 'sans-serif'],
  headerColor: 'hsla(0,0%,0%,1)',
  bodyColor: 'hsla(0,0%,0%,0.8)',
  headerWeight: 700,
  bodyWeight: 400,
  boldWeight: 700,
  overrideStyles: ({ adjustFontSizeTo, scale, rhythm }, options) => ({
    a: {
      color: '#9f392b',
    },
    blockquote: {
      ...scale(1 / 5),
      color: gray(41),
      fontStyle: 'italic',
      paddingLeft: rhythm(13 / 16),
      marginLeft: 0,
      borderLeft: `${rhythm(3 / 16)} solid ${gray(80)}`,
    },
    'blockquote > :last-child': {
      marginBottom: 0,
    },
    'blockquote cite': {
      ...adjustFontSizeTo(options.baseFontSize),
      color: options.bodyColor,
      fontWeight: options.bodyWeight,
    },
    'blockquote cite:before': {
      content: '"— "',
    },
    [MOBILE_MEDIA_QUERY]: {
      blockquote: {
        marginLeft: rhythm(-3 / 4),
        marginRight: 0,
        paddingLeft: rhythm(9 / 16),
      },
    },
    'h3,h4,h5,h6': {
      fontStyle: 'italic',
    },
  }),
}

export default theme
<commit_msg>Remove italics from Kirkham theme<commit_after>// @flow
import gray from 'gray-percentage'
import type { OptionsType } from 'Types'
import {
  MOBILE_MEDIA_QUERY,
  TABLET_MEDIA_QUERY,
} from 'typography-breakpoint-constants'

const theme: OptionsType = {
  title: 'Kirkham',
  baseFontSize: '18px',
  baseLineHeight: 1.44,
  scaleRatio: 2.15,
  blockMarginBottom: 0.75,
  googleFonts: [
    {
      name: 'Playfair Display',
      styles: ['700'],
    },
    {
      name: 'Fira Sans',
      styles: ['400', '400i', '700', '700i'],
    },
  ],
  headerFontFamily: ['Playfair Display', 'serif'],
  bodyFontFamily: ['Fira Sans', 'sans-serif'],
  headerColor: 'hsla(0,0%,0%,1)',
  bodyColor: 'hsla(0,0%,0%,0.8)',
  headerWeight: 700,
  bodyWeight: 400,
  boldWeight: 700,
  overrideStyles: ({ adjustFontSizeTo, scale, rhythm }, options) => ({
    a: {
      color: '#9f392b',
    },
    blockquote: {
      ...scale(1 / 5),
      color: gray(41),
      fontStyle: 'italic',
      paddingLeft: rhythm(13 / 16),
      marginLeft: 0,
      borderLeft: `${rhythm(3 / 16)} solid ${gray(80)}`,
    },
    'blockquote > :last-child': {
      marginBottom: 0,
    },
    'blockquote cite': {
      ...adjustFontSizeTo(options.baseFontSize),
      color: options.bodyColor,
      fontWeight: options.bodyWeight,
    },
    'blockquote cite:before': {
      content: '"— "',
    },
    [MOBILE_MEDIA_QUERY]: {
      blockquote: {
        marginLeft: rhythm(-3 / 4),
        marginRight: 0,
        paddingLeft: rhythm(9 / 16),
      },
    },
  }),
}

export default theme
<|endoftext|>


<commit_before>Tag = {
	CTLCLS : 'tagctrl',
	TAGCLS : 'tag',
	TAGHOLE : 'taghole',
	attach : function(elm, cb, tags, cond) {
		var fout = false;
		var inp_out = $('

');
		var inp = $('<input type="text" placeholder="' +
					((cond&&cond.placeholder) ? cond.placeholder : '') + '">');
		inp_out.append(inp);
		var inpwidth = function(v) {
			var def = (cond&&cond.placeholder) ? cond.placeholder.length : 4;
			var len = (v.length<def) ? def+1 : v.length+1;
			inp.css('width', (len*12) + 'pt');
		};
		var isMax = function() {
			var tags = elm.find('.' + Tag.TAGCLS);
			if (!cond||!cond.max);
			return (tags.length>=cond.max);
		};
		if (tags===undefined) tags = [];
		elm.addClass(Tag.CTLCLS);
		if (cond!==undefined) {
			elm.on('click', function() {
				if (inp_out.parent().length==0) {
					elm.css('border', '1px solid #eee').append(inp_out);
					inpwidth('');
					inp.on('blur', function(e) {
						fout = true;
						window.setTimeout(function() {
							if (!fout) {
								inp.focus();
								return;
							}
							if (inp.val()!=='') push(e);
							blur(e);
						}, 300);
					}).keydown(function(e){
						if (e.which===8) {
							if (inp.val()==='') pop(e);
						}
						if (isMax()) {
							e.preventDefault();
							return false;
						}
						if (e.which===13) {
							if (inp.val()==='') blur(e);
							else push(e);
						}
					}).keypress(function(e){
						inpwidth(inp.val());
						if (cond&&cond.maxlen&&(inp.val().length>=cond.maxlen)) {
							inp.val(inp.val().substr(0,cond.maxlen));
							e.preventDefault();
							return false;
						}
					}).keyup(function(e){
						inpwidth(inp.val());
						if (cond&&cond.maxlen&&(inp.val().length>=cond.maxlen)) {
							inp.val(inp.val().substr(0,cond.maxlen));
							e.preventDefault();
							return false;
						}
					}).focus();
					tagmode(true);
				}
			}).click(function(e) {
				fout = false;
				e.preventDefault();
				return false;
			}).css('border', '1px solid #fff');
			var blur = function(e) {
				elm.css('border', '1px solid #fff');
				inp.val('');
				inp_out.remove();
				tagmode(false);
			};
			var pop = function() {
				var tags = elm.find('.' + Tag.TAGCLS);
				if (tags.length>0) {
					tags[tags.length-1].remove();
				}
			}
			var push = function() {
				inp_out.before(newtag(inp.val(), true));
				inp.val('');
			}
			var tagmode = function(edit) {
				var t = edit ? '×' : '';
				var hole = elm.find('.' + Tag.TAGHOLE);
				for ( var i=0; i<hole.length; i++ ) {
					$(hole[i]).html(t);
				}
			}
		}
		var newtag = function(n,edit) {
			var t = edit ? '×' : '';
			var elm =  $('

'
						+ n + '

' + t + '

');
			elm.click(function(e) {
				fout = false;
				if (inp_out.parent().length===0) {
					cb($(e.currentTarget).attr('n'));
				} else {
					$(e.currentTarget).remove();
				}
				e.preventDefault();
				return false;
			});
			return elm;
		}
		for (var i in tags) {
			elm.append(newtag(tags[i]));
		}
		elm[0].tag = function() {
			var o = elm.find('.' + Tag.TAGCLS);
			var ret = [];
			for ( var i=0; i<o.length; i++ ) {
				ret.push($(o[i]).attr('n'));
			}
			return ret;
		};
	}
};
<commit_msg>change behavior when re-attaching<commit_after>Tag = {
	CTLCLS : 'tagctrl',
	TAGCLS : 'tag',
	TAGHOLE : 'taghole',
	attach : function(elm, cb, tags, cond) {
		var fout = false;
		var inp_out = $('

');
		var inp = $('<input type="text" placeholder="' +
					((cond&&cond.placeholder) ? cond.placeholder : '') + '">');
		inp_out.append(inp);
		var inpwidth = function(v) {
			var def = (cond&&cond.placeholder) ? cond.placeholder.length : 4;
			var len = (v.length<def) ? def+1 : v.length+1;
			inp.css('width', (len*12) + 'pt');
		};
		var isMax = function() {
			var tags = elm.find('.' + Tag.TAGCLS);
			if (!cond||!cond.max);
			return (tags.length>=cond.max);
		};
		if (tags===undefined) tags = [];
		elm.html('');
		if (!elm.hasClass(Tag.CTLCLS)) {
			elm.addClass(Tag.CTLCLS);
		}
		if (cond!==undefined) {
			elm.on('click', function() {
				if (inp_out.parent().length==0) {
					elm.css('border', '1px solid #eee').append(inp_out);
					inpwidth('');
					inp.on('blur', function(e) {
						fout = true;
						window.setTimeout(function() {
							if (!fout) {
								inp.focus();
								return;
							}
							if (inp.val()!=='') push(e);
							blur(e);
						}, 300);
					}).keydown(function(e){
						if (e.which===8) {
							if (inp.val()==='') pop(e);
						}
						if (isMax()) {
							e.preventDefault();
							return false;
						}
						if (e.which===13) {
							if (inp.val()==='') blur(e);
							else push(e);
						}
					}).keypress(function(e){
						inpwidth(inp.val());
						if (cond&&cond.maxlen&&(inp.val().length>=cond.maxlen)) {
							inp.val(inp.val().substr(0,cond.maxlen));
							e.preventDefault();
							return false;
						}
					}).keyup(function(e){
						inpwidth(inp.val());
						if (cond&&cond.maxlen&&(inp.val().length>=cond.maxlen)) {
							inp.val(inp.val().substr(0,cond.maxlen));
							e.preventDefault();
							return false;
						}
					}).focus();
					tagmode(true);
				}
			}).click(function(e) {
				fout = false;
				e.preventDefault();
				return false;
			}).css('border', '1px solid #fff');
			var blur = function(e) {
				elm.css('border', '1px solid #fff');
				inp.val('');
				inp_out.remove();
				tagmode(false);
			};
			var pop = function() {
				var tags = elm.find('.' + Tag.TAGCLS);
				if (tags.length>0) {
					tags[tags.length-1].remove();
				}
			}
			var push = function() {
				inp_out.before(newtag(inp.val(), true));
				inp.val('');
			}
			var tagmode = function(edit) {
				var t = edit ? '×' : '';
				var hole = elm.find('.' + Tag.TAGHOLE);
				for ( var i=0; i<hole.length; i++ ) {
					$(hole[i]).html(t);
				}
			}
		}
		var newtag = function(n,edit) {
			var t = edit ? '×' : '';
			var elm =  $('

'
						+ n + '

' + t + '

');
			elm.click(function(e) {
				fout = false;
				if (inp_out.parent().length===0) {
					cb($(e.currentTarget).attr('n'));
				} else {
					$(e.currentTarget).remove();
				}
				e.preventDefault();
				return false;
			});
			return elm;
		}
		for (var i in tags) {
			if (tags[i]) elm.append(newtag(tags[i]));
		}
		elm[0].tag = function() {
			var o = elm.find('.' + Tag.TAGCLS);
			var ret = [];
			for ( var i=0; i<o.length; i++ ) {
				ret.push($(o[i]).attr('n'));
			}
			return ret;
		};
	}
};
<|endoftext|>


<commit_before><commit_msg>god why<commit_after><|endoftext|>


<commit_before>const os   = require('os')
const fs   = require('fs')
const path = require('path')

/* initial data */
const defaultPath = path.join(os.homedir(), 'nexrender')
const defaultName = 'database.js'

const database = process.env.NEXRENDER_DATABASE
    ? process.env.NEXRENDER_DATABASE
    : path.join(defaultPath, defaultName);

let data = fs.existsSync(database)
    ? JSON.parse(fs.readFileSync(database, 'utf8'))
    : [];

if (!fs.existsSync(defaultPath)) {
    fs.mkdirSync(defaultPath);
}

/* internal methods */
const save = () => fs.writeFileSync(database, JSON.stringify(data))

const indexOf = value => {
    for (var i = data.length - 1; i >= 0; i--) {
        const entry = data[i];
        if (entry.uid == value) {
            return i;
        }
    }

    return -1;
}

/* public api */
const fetch = uid => uid ? data[indexOf(uid)] : data

const insert = entry => {
    const now = new Date()

    Object.assign({}, entry, {
        updatedAt: now,
        createdAt: now
    })

    data.push(entry);
    setImmediate(save);
}

const update = (uid, entry) => {
    const value = indexOf(uid);

    if (value == -1) {
        return null;
    }

    const now = new Date()

    data[value] = Object.assign(
        {}, data[value], entry,
        { updatedAt: now }
    );

    setImmediate(save);
    return data[value];
}

const remove = uid => {
    const value = indexOf(uid);

    if (value === -1) {
        return null;
    }

    data.splice(value, 1)
    setImmediate(save);
    return true;
}

const cleanup = () => {
    data = []
    save()
}

module.exports = {
    insert,
    fetch,
    update,
    remove,
    cleanup,
}
<commit_msg>changed behavior for default folder in server<commit_after>const os   = require('os')
const fs   = require('fs')
const path = require('path')

/* initial data */
const defaultPath = path.join(os.homedir(), 'nexrender')
const defaultName = 'database.js'

const database = process.env.NEXRENDER_DATABASE
    ? process.env.NEXRENDER_DATABASE
    : path.join(defaultPath, defaultName);

let data = fs.existsSync(database)
    ? JSON.parse(fs.readFileSync(database, 'utf8'))
    : [];

if (!process.env.NEXRENDER_DATABASE && !fs.existsSync(defaultPath)) {
    fs.mkdirSync(defaultPath);
}

/* internal methods */
const save = () => fs.writeFileSync(database, JSON.stringify(data))

const indexOf = value => {
    for (var i = data.length - 1; i >= 0; i--) {
        const entry = data[i];
        if (entry.uid == value) {
            return i;
        }
    }

    return -1;
}

/* public api */
const fetch = uid => uid ? data[indexOf(uid)] : data

const insert = entry => {
    const now = new Date()

    Object.assign({}, entry, {
        updatedAt: now,
        createdAt: now
    })

    data.push(entry);
    setImmediate(save);
}

const update = (uid, entry) => {
    const value = indexOf(uid);

    if (value == -1) {
        return null;
    }

    const now = new Date()

    data[value] = Object.assign(
        {}, data[value], entry,
        { updatedAt: now }
    );

    setImmediate(save);
    return data[value];
}

const remove = uid => {
    const value = indexOf(uid);

    if (value === -1) {
        return null;
    }

    data.splice(value, 1)
    setImmediate(save);
    return true;
}

const cleanup = () => {
    data = []
    save()
}

module.exports = {
    insert,
    fetch,
    update,
    remove,
    cleanup,
}
<|endoftext|>


<commit_before>import { ObjectID as objectId } from 'mongodb';

export default {
  id: 'userFromJwt',
  factory: () => async (req, res, next) => {
    const UserRepository = req.modules.get('oors.mongodb').getRepository('oors.user.User');
    const AccountRepository = req.modules.get('oors.mongodb').getRepository('oors.user.Account');
    const { User } = req.modules.get('oors.user');

    if (!req.jwtPayload) {
      return next();
    }

    try {
      const { id } = req.jwtPayload;
      const user = await UserRepository.findById(objectId(id));
      const account = await AccountRepository.findById(user.accountId);

      if (!user) {
        return next();
      }

      await User.canLogin({ user, account });
      req.user = user;
      return next();
    } catch (error) {
      return next(error);
    }
  },
};
<commit_msg>[oors-user] bugfix<commit_after>import { ObjectID as objectId } from 'mongodb';

export default {
  id: 'userFromJwt',
  factory: () => async (req, res, next) => {
    const UserRepository = req.modules.get('oors.mongodb').getRepository('oors.user.User');
    const AccountRepository = req.modules.get('oors.mongodb').getRepository('oors.user.Account');
    const { User } = req.modules.get('oors.user');

    if (!req.jwtPayload) {
      return next();
    }

    try {
      const { id } = req.jwtPayload;
      const user = await UserRepository.findById(objectId(id));

      if (!user) {
        return next();
      }

      const account = await AccountRepository.findById(user.accountId);

      await User.canLogin({ user, account });
      req.user = user;
      return next();
    } catch (error) {
      return next(error);
    }
  },
};
<|endoftext|>


<commit_before>'use strict';

var Promise = require('bluebird'),
    _ = require('lodash'),
    logger = require('../../core/Logger')('storage');

module.exports = function (sequelize, DataTypes) {

    var Room = sequelize.define('Room', {
        // globally unique xmpp room name within one domain
        name: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false,
            onDelete: 'cascade'
        },
        subject: {
            type: DataTypes.STRING
        },
        description: {
            type: DataTypes.TEXT
        }
    }, {
        associate: function (models) {
            models.Room.hasMany(models.User, {
                through: models.RoomMember,
                as: 'members',
                onDelete: 'cascade'
            });
            models.Room.hasMany(models.RoomMessage, {
                as: 'messages',
                onDelete: 'cascade'
            });
            models.Room.hasMany(models.RoomConfiguration, {
                as: 'configurations',
                onDelete: 'cascade'
            });
        },
        instanceMethods: {

            /**
             * Join will:
             * - add a membership if not already established
             * - verify that the membership is properly, if the user
             *   is already a member
             * - possibly reset the new nickname
             */
            join: function (user, options) {
                logger.debug('user ' + JSON.stringify(user) + ' joins room ' + this.name);
                var self = this;

                // verify parameters
                if (!user || !options || !options.role || !options.affiliation || !options.nickname) {
                    throw new Error('wrong parameters');
                } else {
                    return self.getMembers({
                        where: {
                            id : user.id
                        }
                    }).then(function(members){
                        logger.debug('found members: '+ JSON.stringify(members));

                        // user is already part of this room
                        if (members && members.length > 0) {
                            var roomUser = members[0];
                            logger.debug('user is already member: ' + JSON.stringify(roomUser))

                            // update data
                            // @see http://xmpp.org/extensions/xep-0045.html#roles-default
                            switch (roomUser.RoomMember.affiliation) {
                                case sequelize.model('RoomMember').Affiliation.Admin:
                                case sequelize.model('RoomMember').Affiliation.Owner:
                                    roomUser.RoomMember.role = sequelize.model('RoomMember').Role.Moderator;
                                    break;
                                default:
                                    roomUser.RoomMember.role = sequelize.model('RoomMember').Role.Visitor;
                                    break;
                            }

                            roomUser.RoomMember.nickname = options.nickname;
                            return roomUser.RoomMember.save().then(function(){
                                return roomUser;
                            })
                        } else {
                            logger.debug('add user as new member ' + user.jid);
                            // add user to room
                            return self.addMember(user, {
                                "RoomMember.role" : options.role,
                                "RoomMember.affiliation" : options.affiliation,
                                "RoomMember.nickname" : options.nickname
                            })
                        }
                    })
                }
            },

            /**
             * leave the rum
             */
            leave: function (user) {
                return this.getMembers({
                    where: {
                        id : user.id
                    }
                }).then(function(members){
                    var roomUser = members[0];
                    roomUser.RoomMember.role = sequelize.model('RoomMember').Role.None;
                    roomUser.RoomMember.save()
                })
            },

            /**
             * verifies that the given user is a member of this room
             */
            isMember: function (user) {
                var self = this;

                // checkout if the current user is member
                return self.getMembers({
                    where: {
                        "User.id" : user.id
                    }
                }).then(function(users){
                    logger.debug('found users: ' + JSON.stringify(users));

                    return new Promise(function(resolve, reject) {
                        var user = _.first(users)
                        if (user) {
                            resolve(user);
                        } else {
                            reject();
                        }
                    });
                })
            },

            /**
             * returns the nickname of a user for this specific
             * room.
             */
            nickname: function (user) {
                var self = this;

                // checkout if the current user is member
                return self.getMembers({
                    where: {
                        UserId : user.id
                    }
                }).then(function(users){
                    return new Promise(function(resolve, reject) {
                        var user = _.first(users)
                        if (user) {
                            resolve(user);
                        } else {
                            reject();
                        }
                    });
                })
            },

            exportJSON : function (userjid) {

                var room = _.pick(this.toJSON(), ['name', 'subject', 'description', 'per_page', 'type']);

                // create event data, may not be availabe
                if (this.event){
                    room['event'] = this.event.toJSON();
                } else {
                    room['event'] = null;
                }

                // create members data
                var owner = null;
                room['members'] = _.map(this.members, function(member){
                    if (member.RoomMember.affiliation === 'owner') {
                        owner = member;
                    }
                    return {
                        'name' : member.name,
                        'jid' : member.jid,
                        'nickname' : member.RoomMember.nickname,
                        'role' : member.RoomMember.role,
                        'affiliation' : member.RoomMember.affiliation,
                        'state' : member.RoomMember.state
                    }
                })

                room['owner'] = {
                    'jid' : owner.jid,
                }

                return room;
            }
        }
    });

    return Room;
};<commit_msg>bugfix: fix toJSON for missing owner information<commit_after>'use strict';

var Promise = require('bluebird'),
    _ = require('lodash'),
    logger = require('../../core/Logger')('storage');

module.exports = function (sequelize, DataTypes) {

    var Room = sequelize.define('Room', {
        // globally unique xmpp room name within one domain
        name: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false,
            onDelete: 'cascade'
        },
        subject: {
            type: DataTypes.STRING
        },
        description: {
            type: DataTypes.TEXT
        }
    }, {
        associate: function (models) {
            models.Room.hasMany(models.User, {
                through: models.RoomMember,
                as: 'members',
                onDelete: 'cascade'
            });
            models.Room.hasMany(models.RoomMessage, {
                as: 'messages',
                onDelete: 'cascade'
            });
            models.Room.hasMany(models.RoomConfiguration, {
                as: 'configurations',
                onDelete: 'cascade'
            });
        },
        instanceMethods: {

            /**
             * Join will:
             * - add a membership if not already established
             * - verify that the membership is properly, if the user
             *   is already a member
             * - possibly reset the new nickname
             */
            join: function (user, options) {
                logger.debug('user ' + JSON.stringify(user) + ' joins room ' + this.name);
                var self = this;

                // verify parameters
                if (!user || !options || !options.role || !options.affiliation || !options.nickname) {
                    throw new Error('wrong parameters');
                } else {
                    return self.getMembers({
                        where: {
                            id : user.id
                        }
                    }).then(function(members){
                        logger.debug('found members: '+ JSON.stringify(members));

                        // user is already part of this room
                        if (members && members.length > 0) {
                            var roomUser = members[0];
                            logger.debug('user is already member: ' + JSON.stringify(roomUser))

                            // update data
                            // @see http://xmpp.org/extensions/xep-0045.html#roles-default
                            switch (roomUser.RoomMember.affiliation) {
                                case sequelize.model('RoomMember').Affiliation.Admin:
                                case sequelize.model('RoomMember').Affiliation.Owner:
                                    roomUser.RoomMember.role = sequelize.model('RoomMember').Role.Moderator;
                                    break;
                                default:
                                    roomUser.RoomMember.role = sequelize.model('RoomMember').Role.Visitor;
                                    break;
                            }

                            roomUser.RoomMember.nickname = options.nickname;
                            return roomUser.RoomMember.save().then(function(){
                                return roomUser;
                            })
                        } else {
                            logger.debug('add user as new member ' + user.jid);
                            // add user to room
                            return self.addMember(user, {
                                "RoomMember.role" : options.role,
                                "RoomMember.affiliation" : options.affiliation,
                                "RoomMember.nickname" : options.nickname
                            })
                        }
                    })
                }
            },

            /**
             * leave the rum
             */
            leave: function (user) {
                return this.getMembers({
                    where: {
                        id : user.id
                    }
                }).then(function(members){
                    var roomUser = members[0];
                    roomUser.RoomMember.role = sequelize.model('RoomMember').Role.None;
                    roomUser.RoomMember.save()
                })
            },

            /**
             * verifies that the given user is a member of this room
             */
            isMember: function (user) {
                var self = this;

                // checkout if the current user is member
                return self.getMembers({
                    where: {
                        "User.id" : user.id
                    }
                }).then(function(users){
                    logger.debug('found users: ' + JSON.stringify(users));

                    return new Promise(function(resolve, reject) {
                        var user = _.first(users)
                        if (user) {
                            resolve(user);
                        } else {
                            reject();
                        }
                    });
                })
            },

            /**
             * returns the nickname of a user for this specific
             * room.
             */
            nickname: function (user) {
                var self = this;

                // checkout if the current user is member
                return self.getMembers({
                    where: {
                        UserId : user.id
                    }
                }).then(function(users){
                    return new Promise(function(resolve, reject) {
                        var user = _.first(users)
                        if (user) {
                            resolve(user);
                        } else {
                            reject();
                        }
                    });
                })
            },

            exportJSON : function (userjid) {

                var room = _.pick(this.toJSON(), ['name', 'subject', 'description', 'per_page', 'type']);

                // create event data, may not be availabe
                if (this.event){
                    room['event'] = this.event.toJSON();
                } else {
                    room['event'] = null;
                }

                // create members data
                var owner = null;
                room['members'] = _.map(this.members, function(member){
                    if (member.RoomMember.affiliation === 'owner') {
                        owner = member;
                    }
                    return {
                        'name' : member.name,
                        'jid' : member.jid,
                        'nickname' : member.RoomMember.nickname,
                        'role' : member.RoomMember.role,
                        'affiliation' : member.RoomMember.affiliation,
                        'state' : member.RoomMember.state
                    }
                })

                // if we have information about the room
                if (owner && owner.jid) {
                    room['owner'] = {
                        'jid' : owner.jid,
                    }
                }

                return room;
            }
        }
    });

    return Room;
};<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var events = require('events');
var net = require('net');

/**
 * calculate crc16
 *
 * @param {buffer} buf the buffer to to crc on.
 *
 * @return {number} the calculated crc16
 */
function crc16(buf) {
    var length = buf.length - 2;
    var crc = 0xFFFF;
    var tmp;

    // calculate crc16
    for (var i = 0; i < length; i++) {
        crc = crc ^ buf[i];

        for (var j = 0; j < 8; j++) {
            tmp = crc & 0x0001;
            crc = crc >> 1;
            if (tmp) {
              crc = crc ^ 0xA001;
            }
        }
    }

    return crc;
}

/**
 * Simulate a modbus-RTU port using modbus-TCP connection
 */
var TcpPort = function(ip) {
    var _tcpport = this;
    this.ip = ip;
    this.port = 502; // modbus port

    // create a socket
    this._client = new net.Socket();
    this._client.on('data', function(data) {
        var buffer;
        var crc;

        // cut 6 bytes of mbap, copy pdu and add crc
        buffer = new Buffer(data.length - 6 + 2);
        data.copy(buffer, 0, 6);
        crc = crc16(buffer);
        buffer.writeUInt16LE(crc, buffer.length - 2);

        // emit a data signal
        _tcpport.emit('data', buffer);
    });

    events.call(this);
}
util.inherits(TcpPort, events);

/**
 * Simulate successful port open
 */
TcpPort.prototype.open = function (callback) {
    this._client.connect(this.port, this.ip, callback);
}

/**
 * Simulate successful close port
 */
TcpPort.prototype.close = function (callback) {
    this._client.end();
    if (callback)
        callback(null);
}

/**
 * Send data to a modbus-tcp slave
 */
TcpPort.prototype.write = function (data) {
    // remove crc and add mbap
    var buffer = new Buffer(data.length + 6 - 2);
    buffer.writeUInt16BE(1, 0);
    buffer.writeUInt16BE(0, 2);
    buffer.writeUInt16BE(data.length, 4);
    data.copy(buffer, 6);

    // send buffer to slave
    this._client.write(buffer);
}

module.exports = TcpPort;
<commit_msg>fix mbap payload length<commit_after>'use strict';
var util = require('util');
var events = require('events');
var net = require('net');

/**
 * calculate crc16
 *
 * @param {buffer} buf the buffer to to crc on.
 *
 * @return {number} the calculated crc16
 */
function crc16(buf) {
    var length = buf.length - 2;
    var crc = 0xFFFF;
    var tmp;

    // calculate crc16
    for (var i = 0; i < length; i++) {
        crc = crc ^ buf[i];

        for (var j = 0; j < 8; j++) {
            tmp = crc & 0x0001;
            crc = crc >> 1;
            if (tmp) {
              crc = crc ^ 0xA001;
            }
        }
    }

    return crc;
}

/**
 * Simulate a modbus-RTU port using modbus-TCP connection
 */
var TcpPort = function(ip) {
    var _tcpport = this;
    this.ip = ip;
    this.port = 502; // modbus port

    // create a socket
    this._client = new net.Socket();
    this._client.on('data', function(data) {
        var buffer;
        var crc;

        // cut 6 bytes of mbap, copy pdu and add crc
        buffer = new Buffer(data.length - 6 + 2);
        data.copy(buffer, 0, 6);
        crc = crc16(buffer);
        buffer.writeUInt16LE(crc, buffer.length - 2);

        // emit a data signal
        _tcpport.emit('data', buffer);
    });

    events.call(this);
}
util.inherits(TcpPort, events);

/**
 * Simulate successful port open
 */
TcpPort.prototype.open = function (callback) {
    this._client.connect(this.port, this.ip, callback);
}

/**
 * Simulate successful close port
 */
TcpPort.prototype.close = function (callback) {
    this._client.end();
    if (callback)
        callback(null);
}

/**
 * Send data to a modbus-tcp slave
 */
TcpPort.prototype.write = function (data) {
    // remove crc and add mbap
    var buffer = new Buffer(data.length + 6 - 2);
    buffer.writeUInt16BE(1, 0);
    buffer.writeUInt16BE(0, 2);
    // subtract crc bytes
    buffer.writeUInt16BE(data.length - 2, 4);
    data.copy(buffer, 6);

    // send buffer to slave
    this._client.write(buffer);
}

module.exports = TcpPort;
<|endoftext|>


<commit_before>/*
 * #%L
 * Wisdom-Framework
 * %%
 * Copyright (C) 2013 - 2014 Wisdom Framework
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/* global $, Exception*/

/**
 *
 * @class WisitShellComp
 * @extends HUBU.AbstractComponent
 * @extends wisit.shell.ShellService
 */

function WisitShellComp() {
    "use strict";

    var self = this;
    var _hub;

    var _root = "/monitor/terminal";
    var _topic = "/monitor/terminal/stream";

    //Completion cache for command with second argument
    var _completionCache = {};

    //List of the shell commands.
    var _commands = null;

    self.name = "WisitShellComp";

    /**
     *
     * @method startWithInList
     * @return the elemen that match the prefix in the given list
     */
    var startWithInList = function(list, prefix) {
        var regex = new RegExp("^" + prefix, "i");
        return list.filter(function(elem) {
            return elem.match(regex);
        });
    };

    self.getComponentName = function() {
        return self.name;
    };

    /**
     * Configure the instance of the WisitShellComp component.
     *
     * @method configure
     * @param {HUBU.hub} theHub
     * @param conf - The ShellService configuration.
     * @param {root} [conf.root="/wisit"] - The url root of the wisit shell resource (WisitShellController)
     */
    self.configure = function(theHub, conf) {
        _hub = theHub;

        if (typeof conf !== "undefined") {
            if ((typeof conf.root === "string") && conf.root.match(/^\/\w+(\/\w+)*$/)) {
                _root = conf.root;
            } else if (typeof conf.root !== "undefined") {
                throw new Exception("The property root must be a valid path string.");
            }

            if ((typeof conf.topic === "string") && conf.topic.match(/^\/\w+(\/\w+)*$/)) {
                _topic = conf.topic;
            } else if (typeof conf.topic !== "undefined") {
                throw new Exception("The property topic must be a valid topic string.");
            }
        }

        //register the RactiveRenderService
        _hub.provideService({
            component: self,
            contract: window.wisit.shell.ShellService,
            properties: {
                root: _root
            }
        });
    };

    self.start = function() {
        $.ajax({
            url: _root + "/command",
            type: "GET",
            async: false,
            dataType: "json"
        }).done(function(commands) {
            _commands = commands;
        }).fail(function(xhr, status, error) {
            console.warn("[" + self.name + "] cannot retrieve command: " + status + " - " + error);
        });

        //Get ipojo instances and factories autocompletion
        $.ajax({
            url: "/monitor/ipojo.json",
            type: "GET",
            async: false,
            dataType: "json"
        }).done(function(ipojo) {
            _completionCache.instance = ipojo.instances.map(function(elem){return elem.name;});
            _completionCache.factory = ipojo.factories.filter(function(elem){return !elem.handler;}).map(function(elem){return elem.name;});
        }).fail(function(xhr, status, error) {
            console.warn("[" + self.name + "] Cannot retrieve ipojo.json: " + status + " - " + error);
        });
    };

    self.stop = function() {
        _commands = null;
        _completionCache = null;
    };

    self.getCommands = function() {
        return _commands;
    };

    /**
     *
     * @method autoComplete
     * @memberof wisit.shell.ShellService
     * @param fullcommand - the shell command to be completed
     * @param callback - call with the result of completion
     */
    self.autoComplete = function(fullcommand, callback) {
        var command = fullcommand.split(" ");

        //command empty, return all shell commands
        if (command.length === 0) {
            callback(_commands);
        }

        //command does not have argument, return commands starting like it
        if (command.length === 1) {
            callback(startWithInList(_commands, command[0]));
        }

        if (command.length === 2 && command[0] in _completionCache) {
            callback(startWithInList(_completionCache[command[0]], command[1]));
        }
    };

    self.exec = function(cmd, args) {
        return $.ajax({
            url: _root + "/command/" + cmd,
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(args)
        }).done(function(data) {
            if (typeof data !== "undefined") {
                _hub.publish(self, _topic, {
                    data: data
                }); //Publish the command result if any
            }
        }).fail(function(xhr, status, error) {
            console.warn("[" + self.name + "] cannot exec command: " + status + " - " + error);
        });
    };

    self.getTopic = function() {
        return _topic;
    };
}
<commit_msg>Fix file header (trailing space)<commit_after>/*
 * #%L
 * Wisdom-Framework
 * %%
 * Copyright (C) 2013 - 2014 Wisdom Framework
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/* global $, Exception*/

/**
 *
 * @class WisitShellComp
 * @extends HUBU.AbstractComponent
 * @extends wisit.shell.ShellService
 */

function WisitShellComp() {
    "use strict";

    var self = this;
    var _hub;

    var _root = "/monitor/terminal";
    var _topic = "/monitor/terminal/stream";

    //Completion cache for command with second argument
    var _completionCache = {};

    //List of the shell commands.
    var _commands = null;

    self.name = "WisitShellComp";

    /**
     *
     * @method startWithInList
     * @return the elemen that match the prefix in the given list
     */
    var startWithInList = function(list, prefix) {
        var regex = new RegExp("^" + prefix, "i");
        return list.filter(function(elem) {
            return elem.match(regex);
        });
    };

    self.getComponentName = function() {
        return self.name;
    };

    /**
     * Configure the instance of the WisitShellComp component.
     *
     * @method configure
     * @param {HUBU.hub} theHub
     * @param conf - The ShellService configuration.
     * @param {root} [conf.root="/wisit"] - The url root of the wisit shell resource (WisitShellController)
     */
    self.configure = function(theHub, conf) {
        _hub = theHub;

        if (typeof conf !== "undefined") {
            if ((typeof conf.root === "string") && conf.root.match(/^\/\w+(\/\w+)*$/)) {
                _root = conf.root;
            } else if (typeof conf.root !== "undefined") {
                throw new Exception("The property root must be a valid path string.");
            }

            if ((typeof conf.topic === "string") && conf.topic.match(/^\/\w+(\/\w+)*$/)) {
                _topic = conf.topic;
            } else if (typeof conf.topic !== "undefined") {
                throw new Exception("The property topic must be a valid topic string.");
            }
        }

        //register the RactiveRenderService
        _hub.provideService({
            component: self,
            contract: window.wisit.shell.ShellService,
            properties: {
                root: _root
            }
        });
    };

    self.start = function() {
        $.ajax({
            url: _root + "/command",
            type: "GET",
            async: false,
            dataType: "json"
        }).done(function(commands) {
            _commands = commands;
        }).fail(function(xhr, status, error) {
            console.warn("[" + self.name + "] cannot retrieve command: " + status + " - " + error);
        });

        //Get ipojo instances and factories autocompletion
        $.ajax({
            url: "/monitor/ipojo.json",
            type: "GET",
            async: false,
            dataType: "json"
        }).done(function(ipojo) {
            _completionCache.instance = ipojo.instances.map(function(elem){return elem.name;});
            _completionCache.factory = ipojo.factories.filter(function(elem){return !elem.handler;}).map(function(elem){return elem.name;});
        }).fail(function(xhr, status, error) {
            console.warn("[" + self.name + "] Cannot retrieve ipojo.json: " + status + " - " + error);
        });
    };

    self.stop = function() {
        _commands = null;
        _completionCache = null;
    };

    self.getCommands = function() {
        return _commands;
    };

    /**
     *
     * @method autoComplete
     * @memberof wisit.shell.ShellService
     * @param fullcommand - the shell command to be completed
     * @param callback - call with the result of completion
     */
    self.autoComplete = function(fullcommand, callback) {
        var command = fullcommand.split(" ");

        //command empty, return all shell commands
        if (command.length === 0) {
            callback(_commands);
        }

        //command does not have argument, return commands starting like it
        if (command.length === 1) {
            callback(startWithInList(_commands, command[0]));
        }

        if (command.length === 2 && command[0] in _completionCache) {
            callback(startWithInList(_completionCache[command[0]], command[1]));
        }
    };

    self.exec = function(cmd, args) {
        return $.ajax({
            url: _root + "/command/" + cmd,
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(args)
        }).done(function(data) {
            if (typeof data !== "undefined") {
                _hub.publish(self, _topic, {
                    data: data
                }); //Publish the command result if any
            }
        }).fail(function(xhr, status, error) {
            console.warn("[" + self.name + "] cannot exec command: " + status + " - " + error);
        });
    };

    self.getTopic = function() {
        return _topic;
    };
}
<|endoftext|>


<commit_before>

var Input={

  accountHashID:
  {
    required: true
    validator: function(value , connection , actionTemplate){}
    default: function(value , connection , actionTemplate){return 0}
  },

  statusCode:
  {
    required: false
    validator: function(value , connection , actionTemplate){}
    default: function(value , connection , actionTemplate){return 0}
  },

  action:
  {
    required: false
    validator: function(value , connection , actionTemplate){}
    default: function ( value , connection , actionTemplate){return 0}
  },

  serviceCaller:
  {
    required: false
    validator: function(value , connection , actionTemplate){}
    default: function(value , connection , actionTemplate){return 0}
  },

  moduleCaller:
  {
    required: false
    validator: function(value , connection , actionTemplate){}
    default: function(value , connection , actionTemplate){return 0}
  }

}

exports.monitorList = {
  name = 'monitorList',
  description = 'Get monitor List',
  inputs : Input,

  run: function(api , data , next)
  {
    var filter = {
        statusCode: data.params.statusCode,
        action: data.params.action,
        serviceCaller: data.params.serviceCaller,
        moduleCaller: data.params.moduleCaller

    }

    monitorList(data.params.accountHashID, filter, function (error, result) {
      if (error)
      {
        data.response.error = error.error
        next(error)
      }
      else
      {
        data.response.result = result.result
        next()
      }})
    }
  }
<commit_msg>Fixing Writing Styles<commit_after>var Input = {
	accountHashID: {
    required: true
    validator: function(value , connection , actionTemplate) {}
    default: function(value , connection , actionTemplate) {return 0}
  },
	statusCode: {
    required: false
    validator: function(value , connection , actionTemplate) {}
    default: function(value , connection , actionTemplate) {return 0}
  },
	action: {
    required: false
    validator: function(value , connection , actionTemplate) {}
    default: function ( value , connection , actionTemplate) {return 0}
  },
	serviceCaller: {
    required: false
    validator: function(value , connection , actionTemplate) {}
    default: function(value , connection , actionTemplate) {return 0}
  },
	moduleCaller: {
    required: false
    validator: function(value , connection , actionTemplate) {}
    default: function(value , connection , actionTemplate) {return 0}
  }
}
exports.monitorList = {
  name = 'monitorList',
  description = 'Get monitor List',
  inputs : Input,
	run: function(api , data , next) {
    var filter = {
        statusCode: data.params.statusCode,
        action: data.params.action,
        serviceCaller: data.params.serviceCaller,
        moduleCaller: data.params.moduleCaller
      }
    monitorList(data.params.accountHashID, filter, function (error, result) {
      if (error) {
        data.response.error = error.error
        next(error)
      }
      else {
        data.response.result = result.result
        next()
      }})
    }
  }
<|endoftext|>


<commit_before>var gulp = require('gulp');
var runSequence = require('run-sequence');

gulp.task('default', function(callback) {
  return runSequence(
    'lint',
    'build',
    'doc',
    'test'
    callback
  );
});
<commit_msg>fix typo<commit_after>var gulp = require('gulp');
var runSequence = require('run-sequence');

gulp.task('default', function(callback) {
  return runSequence(
    'lint',
    'build',
    'doc',
    'test',
    callback
  );
});
<|endoftext|>


<commit_before>HTMLWidgets.widget({

  name: 'd3hive',

  type: 'output',

  initialize: function(el, width, height) {

    var svg = d3.select(el).append("svg")
      .attr("width", width)
      .attr("height", height)
    .append("g")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    return { width: width, height: height }

  },

  renderValue: function(el, x, instance) {

    var width = instance.width,
        height = instance.height,
        innerRadius = Math.sqrt(height)*2,
        outerRadius = .9*height/2;

    innerRadius = (x.options.innerRadius) ? x.options.innerRadius : innerRadius;
    outerRadius = (x.options.outerRadius) ? x.options.outerRadius : outerRadius;

    // hard way to get number of unique axes
    var n_axes = d3.keys(
      d3.nest().key(function(d){return d}).map(x.data.nodes.axis)
    ).length;

    // get nodes in a better form
    var nodes = d3.nest()
        .key(function(d){ return d.node_id })
        .rollup(function(d){ return d[0]; })
        .map(HTMLWidgets.dataframeToD3(x.data.nodes));

    var links = HTMLWidgets.dataframeToD3(x.data.edges).map(function(edge){
      edge.source = nodes[edge.source]
      edge.target = nodes[edge.target]

      return edge;
    })

    var angle = d3.scale.ordinal()
                  .domain(d3.range(n_axes+1))
                  .rangePoints([0, 2 * Math.PI]),
        radius = d3.scale.linear().range([innerRadius, outerRadius]),
        color = d3.scale.category10().domain(d3.range(20));

    var svg = d3.select(el).select("svg").select("g");

    svg.selectAll(".axis")
        .data(d3.range(n_axes))
      .enter().append("line")
        .attr("class", "axis")
        .attr("transform", function(d) { return "rotate(" + degrees(angle(d)) + ")"; })
        .attr("x1", radius.range()[0])
        .attr("x2", radius.range()[1])
        .style("stroke","#b3b2b2")
        .style("stroke-width","1px")
        .style("fill","none");

    svg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", d3.hive.link()
          .angle(function(d) { return angle(d.axis); })
          .radius(function(d) { return radius(d.radius); }))
        .style("stroke", function(d) { return d.color; })
        .style("fill","none");

    svg.selectAll(".node")
        .data(d3.entries(nodes))
      .enter().append("circle")
        .attr("class", "node")
        .attr("transform", function(d) { return "rotate(" + degrees(angle(d.value.axis)) + ")"; })
        .attr("cx", function(d) { return radius(d.value.radius); })
        .attr("r", function(d){ return d.value.size; })
        .style("fill", function(d) { return d.value.color; })
        .on("mouseover", nodemouseover )
        .on("mouseout", nodemouseout );

    function degrees(radians) {
      return radians / Math.PI * 180 - 90;
    }

    function nodemouseover(){
      var node = d3.select(this),
        nodeid = node.data()[0].value.node_id;
      var container = d3.select(this.parentNode);
      var linksWithNode = container.selectAll( ".link" )
                .filter(function(d){
                  return !(d.source.node_id == nodeid ||
                    d.target.node_id == nodeid);
                })
      var otherNodes = container.selectAll( ".node" )
          .filter(function(d){
            return !(d.value.node_id == nodeid);
          })

      linksWithNode
          .classed("unhighlighted",true)
          .style("stroke-opacity",.5)
          .style("stroke","rgb(220,216,217)");

      otherNodes
          .classed("unhighlighted",true)
          .style("fill-opacity",.5)
          .style("fill","rgb(220,216,217)");
    }

    function nodemouseout(){
      var container = d3.select(this.parentNode);
      container.selectAll(".link.unhighlighted")
        .style("stroke", function(d) { return d.color; })
        .style("stroke-opacity", 1);
      container.selectAll(".node.unhighlighted")
        .style("fill", function(d) { return d.value.color; })
        .style("fill-opacity", 1);
    }

  },

  resize: function(el, width, height, instance) {

  }

});
<commit_msg>add ability to specify tasks for post-draw/render customization<commit_after>HTMLWidgets.widget({

  name: 'd3hive',

  type: 'output',

  initialize: function(el, width, height) {

    var svg = d3.select(el).append("svg")
      .attr("width", width)
      .attr("height", height)
    .append("g")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    return { width: width, height: height }

  },

  renderValue: function(el, x, instance) {

    var width = instance.width,
        height = instance.height,
        innerRadius = Math.sqrt(height)*2,
        outerRadius = .9*height/2;

    innerRadius = (x.options.innerRadius) ? x.options.innerRadius : innerRadius;
    outerRadius = (x.options.outerRadius) ? x.options.outerRadius : outerRadius;

    // hard way to get number of unique axes
    var n_axes = d3.keys(
      d3.nest().key(function(d){return d}).map(x.data.nodes.axis)
    ).length;

    // get nodes in a better form
    var nodes = d3.nest()
        .key(function(d){ return d.node_id })
        .rollup(function(d){ return d[0]; })
        .map(HTMLWidgets.dataframeToD3(x.data.nodes));

    var links = HTMLWidgets.dataframeToD3(x.data.edges).map(function(edge){
      edge.source = nodes[edge.source]
      edge.target = nodes[edge.target]

      return edge;
    })

    var angle = d3.scale.ordinal()
                  .domain(d3.range(n_axes+1))
                  .rangePoints([0, 2 * Math.PI]),
        radius = d3.scale.linear().range([innerRadius, outerRadius]),
        color = d3.scale.category10().domain(d3.range(20));

    var svg = d3.select(el).select("svg").select("g");

    svg.selectAll(".axis")
        .data(d3.range(n_axes))
      .enter().append("line")
        .attr("class", "axis")
        .attr("transform", function(d) { return "rotate(" + degrees(angle(d)) + ")"; })
        .attr("x1", radius.range()[0])
        .attr("x2", radius.range()[1])
        .style("stroke","#b3b2b2")
        .style("stroke-width","1px")
        .style("fill","none");

    svg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", d3.hive.link()
          .angle(function(d) { return angle(d.axis); })
          .radius(function(d) { return radius(d.radius); }))
        .style("stroke", function(d) { return d.color; })
        .style("fill","none");

    svg.selectAll(".node")
        .data(d3.entries(nodes))
      .enter().append("circle")
        .attr("class", "node")
        .attr("transform", function(d) { return "rotate(" + degrees(angle(d.value.axis)) + ")"; })
        .attr("cx", function(d) { return radius(d.value.radius); })
        .attr("r", function(d){ return d.value.size; })
        .style("fill", function(d) { return d.value.color; })
        .on("mouseover", nodemouseover )
        .on("mouseout", nodemouseout );

    // set up a container for tasks to perform after completion
    //  one example would be add callbacks for event handling
    //  styling
    if (!(typeof x.tasks === "undefined" || x.tasks === null) ){
      if ( (typeof x.tasks.length === "undefined") ||
       (typeof x.tasks === "function" ) ) {
         // handle a function not enclosed in array
         // should be able to remove once using jsonlite
         x.tasks = [x.tasks];
      }
      x.tasks.map(function(t){
        // for each tasks run it and inside function this will equal el
        t.call(el);
      })
    }

    function degrees(radians) {
      return radians / Math.PI * 180 - 90;
    }

    function nodemouseover(){
      var node = d3.select(this),
        nodeid = node.data()[0].value.node_id;
      var container = d3.select(this.parentNode);
      var linksWithNode = container.selectAll( ".link" )
                .filter(function(d){
                  return !(d.source.node_id == nodeid ||
                    d.target.node_id == nodeid);
                })
      var otherNodes = container.selectAll( ".node" )
          .filter(function(d){
            return !(d.value.node_id == nodeid);
          })

      linksWithNode
          .classed("unhighlighted",true)
          .style("stroke-opacity",.5)
          .style("stroke","rgb(220,216,217)");

      otherNodes
          .classed("unhighlighted",true)
          .style("fill-opacity",.5)
          .style("fill","rgb(220,216,217)");
    }

    function nodemouseout(){
      var container = d3.select(this.parentNode);
      container.selectAll(".link.unhighlighted")
        .style("stroke", function(d) { return d.color; })
        .style("stroke-opacity", 1);
      container.selectAll(".node.unhighlighted")
        .style("fill", function(d) { return d.value.color; })
        .style("fill-opacity", 1);
    }

  },

  resize: function(el, width, height, instance) {

  }

});
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import ReactDOM from 'react-dom'
import { Glyphicon, Popover } from 'react-bootstrap'

export default class SidebarPopover extends Component {

  static propTypes = {
    children: PropTypes.node,
    expanded: PropTypes.bool,
    target: PropTypes.object,
    title: PropTypes.string,

    close: PropTypes.func,
    visible: PropTypes.func
  }

  constructor (props) {
    super(props)
    this.state = {
      top: 0,
      arrowOffset: 0
    }
  }

  componentDidMount () {
    window.addEventListener('resize', () => this.handleResize())
    this.reposition()
  }

  componentDidUpdate () {
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.visible()) this.reposition()
  }

  handleResize () {
    this.reposition()
  }

  reposition () {
    const padding = 10 // minimum space between popover and top/bottom of screen

    const height = ReactDOM.findDOMNode(this.refs.popover).offsetHeight
    const target = ReactDOM.findDOMNode(this.props.target)
    const targetTop = target ? target.getBoundingClientRect().top : 0
    const targetHeight = target ? target.getBoundingClientRect().bottom - target.getBoundingClientRect().top : 0

    let arrowOffset = height / 2
    let top = targetTop - height / 2 + targetHeight / 2

    if (top < padding) {
      arrowOffset = Math.max(padding + 5, arrowOffset - padding + top)
      top = padding
    }

    const maxTop = window.innerHeight - padding - height
    if (top > maxTop) {
      arrowOffset = Math.min(window.innerHeight - padding - 20, arrowOffset + (top - maxTop))
      top = maxTop
    }

    this.setState({ top, arrowOffset })
  }

  render () {
    const style = {
      position: 'fixed',
      marginLeft: this.props.expanded ? 160 : 60,
      width: 276, // max from bootstrap
      top: this.state.top,
      visibility: this.props.visible() ? 'visible' : 'hidden'
    }

    const title = (

      {this.props.title}
      <Glyphicon glyph='remove'
        className='pull-right'
        style={{ cursor: 'pointer' }}
        onClick={() => this.props.close() }
      />

)

    return (
      <Popover id='ptest'
        style={style}
        ref='popover'
        title={title}
        arrowOffsetTop={this.state.arrowOffset}
      >
        {this.props.children}
      </Popover>
    )
  }
}
<commit_msg>Fix error in popover height check<commit_after>import React, {Component, PropTypes} from 'react'
import ReactDOM from 'react-dom'
import { Glyphicon, Popover } from 'react-bootstrap'

export default class SidebarPopover extends Component {

  static propTypes = {
    children: PropTypes.node,
    expanded: PropTypes.bool,
    target: PropTypes.object,
    title: PropTypes.string,

    close: PropTypes.func,
    visible: PropTypes.func
  }

  constructor (props) {
    super(props)
    this.state = {
      top: 0,
      arrowOffset: 0
    }
  }

  componentDidMount () {
    window.addEventListener('resize', () => this.handleResize())
    this.reposition()
  }

  componentDidUpdate () {
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.visible()) this.reposition()
  }

  handleResize () {
    this.reposition()
  }

  reposition () {
    const padding = 10 // minimum space between popover and top/bottom of screen

    const height = ReactDOM.findDOMNode(this.refs.popover) ? ReactDOM.findDOMNode(this.refs.popover).offsetHeight : 0
    const target = ReactDOM.findDOMNode(this.props.target)
    const targetTop = target ? target.getBoundingClientRect().top : 0
    const targetHeight = target ? target.getBoundingClientRect().bottom - target.getBoundingClientRect().top : 0

    let arrowOffset = height / 2
    let top = targetTop - height / 2 + targetHeight / 2

    if (top < padding) {
      arrowOffset = Math.max(padding + 5, arrowOffset - padding + top)
      top = padding
    }

    const maxTop = window.innerHeight - padding - height
    if (top > maxTop) {
      arrowOffset = Math.min(window.innerHeight - padding - 20, arrowOffset + (top - maxTop))
      top = maxTop
    }

    this.setState({ top, arrowOffset })
  }

  render () {
    const style = {
      position: 'fixed',
      marginLeft: this.props.expanded ? 160 : 60,
      width: 276, // max from bootstrap
      top: this.state.top,
      visibility: this.props.visible() ? 'visible' : 'hidden'
    }

    const title = (

      {this.props.title}
      <Glyphicon glyph='remove'
        className='pull-right'
        style={{ cursor: 'pointer' }}
        onClick={() => this.props.close() }
      />

)

    return (
      <Popover id='ptest'
        style={style}
        ref='popover'
        title={title}
        arrowOffsetTop={this.state.arrowOffset}
      >
        {this.props.children}
      </Popover>
    )
  }
}
<|endoftext|>