<commit_before>import { observer } from "mobx-react"
import React, { Component } from "react"
import AppStyles from "../Theme/AppStyles"
import Colors from "../Theme/Colors"
import IconPhoneDefault from "react-icons/lib/md/phone"
import IconPhoneApple from "react-icons/lib/fa/apple"
import IconPhoneAndroid from "react-icons/lib/fa/android"

const Styles = {
  container: {
    display: "flex",
    flexDirection: "row",
    marginTop: 0,
    alignItems: "center",
    borderBottom: `1px solid ${Colors.line}`,
    paddingTop: 10,
    paddingBottom: 10,
  },
  icon: {
    color: Colors.foregroundLight,
  },
  platform: {
    paddingLeft: 10,
    color: Colors.tag,
    width: 100,
  },
  platformDetails: {
    borderLeft: `1px solid ${Colors.subtleLine}`,
    color: Colors.foregroundDark,
    paddingLeft: 10,
    marginLeft: 10,
  },
  screen: {
    borderLeft: `1px solid ${Colors.subtleLine}`,
    paddingLeft: 10,
    marginLeft: 10,
    color: Colors.backgroundHighlight,
  },
}

const ICON_SIZE = 32

const PHONE_MAP = {
  ios: IconPhoneApple,
  android: IconPhoneAndroid,
}

function getPlatformName(connection) {
  switch (connection.platform) {
    case "ios":
      return "iOS"
    case "android":
      return "Android"
    default:
      return connection.platform
  }
}

function getPlatformDetails(connection) {
  const { platformVersion, osRelease, platform } = connection

  switch (platform) {
    case "ios": {
      return `${platformVersion}`
    }

    case "android": {
      return `${osRelease} sdk ${platformVersion}`
    }

    default:
      return platform
  }
}

function getScreen(connection) {
  const { screenWidth, screenHeight, screenScale } = connection

  if (screenWidth && screenHeight && screenScale) {
    return `${screenWidth} x ${screenHeight}`
  }
}

@observer
class ConnectionCell extends Component {
  render() {
    const { connection = {} } = this.props
    const { platform = "?" } = connection
    const WhichIcon = PHONE_MAP[connection.platform] || IconPhoneDefault

    return (

          <WhichIcon size={ICON_SIZE} />

{getPlatformName(connection)}

{getPlatformDetails(connection)}

{getScreen(connection)}

    )
  }
}

export default ConnectionCell
<commit_msg>💄 adds a nicer fallback message when platform isn't detected<commit_after>import { observer } from "mobx-react"
import React, { Component } from "react"
import AppStyles from "../Theme/AppStyles"
import Colors from "../Theme/Colors"
import IconPhoneDefault from "react-icons/lib/fa/question"
import IconPhoneApple from "react-icons/lib/fa/apple"
import IconPhoneAndroid from "react-icons/lib/fa/android"

const Styles = {
  container: {
    display: "flex",
    flexDirection: "row",
    marginTop: 0,
    alignItems: "center",
    borderBottom: `1px solid ${Colors.line}`,
    paddingTop: 10,
    paddingBottom: 10,
  },
  icon: {
    color: Colors.foregroundLight,
  },
  platform: {
    paddingLeft: 10,
    color: Colors.tag,
    width: "25%",
  },
  platformDetails: {
    borderLeft: `1px solid ${Colors.subtleLine}`,
    color: Colors.foregroundDark,
    paddingLeft: 10,
    marginLeft: 10,
  },
  screen: {
    borderLeft: `1px solid ${Colors.subtleLine}`,
    paddingLeft: 10,
    marginLeft: 10,
    color: Colors.backgroundHighlight,
  },
}

const ICON_SIZE = 32

const PHONE_MAP = {
  ios: IconPhoneApple,
  android: IconPhoneAndroid,
}

function getPlatformName(connection) {
  switch (connection.platform) {
    case "ios":
      return "iOS"
    case "android":
      return "Android"
    default:
      return connection.platform || "Unknown platform"
  }
}

function getPlatformDetails(connection) {
  const { platformVersion, osRelease, platform } = connection

  switch (platform) {
    case "ios": {
      return `${platformVersion}`
    }

    case "android": {
      return `${osRelease} (sdk ${platformVersion})`
    }

    default:
      return ""
  }
}

function getScreen(connection) {
  const { screenWidth, screenHeight, screenScale } = connection

  if (screenWidth && screenHeight && screenScale) {
    return `${screenWidth} x ${screenHeight}`
  }
}

@observer
class ConnectionCell extends Component {
  render() {
    const { connection = {} } = this.props
    const { platform = "?" } = connection
    const WhichIcon = PHONE_MAP[connection.platform] || IconPhoneDefault

    return (

          <WhichIcon size={ICON_SIZE} />

{getPlatformName(connection)}

{getPlatformDetails(connection)}

{getScreen(connection)}

    )
  }
}

export default ConnectionCell
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*globals $, jQuery, angular, TypiCMS, alertify, top, window, console*/

(function (angular) {

    'use strict';

    angular.module('typicms').controller('FilesController', ['$http', '$scope', '$location', '$api', function ($http, $scope, $location, $api) {

        var moduleName = 'files',
            $params = {};

        /**
         * Empty object that will contain checked items
         */
        $scope.checked = {
            models: []
        };

        if (TypiCMS.content_locale == null) {
            TypiCMS.content_locale = TypiCMS.locale;
        }
        $scope.TypiCMS = TypiCMS;

        if (TypiCMS.models) {
            $scope.models = TypiCMS.models;
            $scope.displayedModels = [].concat($scope.models);
        } else {
            $api.query($params).$promise.then(function (all) {
                $scope.models = all;
                //copy the references (you could clone ie angular.copy but then have to go through a dirty checking for the matches)
                $scope.displayedModels = [].concat($scope.models);
            });
        }

        $scope.dropped = function(draggedModel, droppedModel) {
            var index = $scope.models.indexOf(draggedModel);
            $scope.models.splice(index, 1);
        }

        $scope.allowDrop = function(e) {
            return false;
        }

        /**
         * Open folder
         */
        $scope.open = function (model) {
            if (model.type === 'f') {
                window.location.href = '?folder_id='+model.id;
            }
        };

        /**
         * Check all items
         */
        $scope.toggleCheck = function (model) {
            console.log(model);
            let index = $scope.checked.models.indexOf(model);
            if (index !== -1) {
                $scope.checked.models.splice(index, 1);
            } else {
                $scope.checked.models.push(model);
            }
            // console.log($scope.checked.models);
        };

        /**
         * Delete checked items
         */
        $scope.deleteChecked = function () {

            var ids = [],
                models = $scope.checked.models,
                number = models.length;

            if ($scope.checked.models.length > $scope.deleteLimit) {
                alertify.error('Impossible to delete more than ' + $scope.deleteLimit + ' items in one go.');
                return false;
            }
            if (!window.confirm('Are you sure you want to delete ' + number + ' items?')) {
                return false;
            }

            models.forEach(function (model) {
                ids.push(model.id);
                var index = $scope.models.indexOf(model);
                $scope.models.splice(index, 1);
            });

            $scope.checked.models = [];

            $scope.loading = true;

            $api.delete({id: ids.join()}).$promise.then(
                function (data) {
                    $scope.loading = false;
                    if (data.number < number) {
                        alertify.error((number - data.number) + ' items could not be deleted.');
                    }
                    if (data.number > 0) {
                        alertify.success(data.number + ' items deleted.');
                    }
                },
                function (reason) {
                    $scope.loading = false;
                    alertify.error('Error ' + reason.status + ' ' + reason.statusText);
                }
            );

        };

    }]);

}(angular));
<commit_msg>persist data on drop in a folder<commit_after>/*jslint browser: true*/
/*globals $, jQuery, angular, TypiCMS, alertify, top, window, console*/

(function (angular) {

    'use strict';

    angular.module('typicms').controller('FilesController', ['$http', '$scope', '$location', '$api', function ($http, $scope, $location, $api) {

        var moduleName = 'files',
            $params = {};

        /**
         * Empty object that will contain checked items
         */
        $scope.checked = {
            models: []
        };

        if (TypiCMS.content_locale == null) {
            TypiCMS.content_locale = TypiCMS.locale;
        }
        $scope.TypiCMS = TypiCMS;

        if (TypiCMS.models) {
            $scope.models = TypiCMS.models;
            $scope.displayedModels = [].concat($scope.models);
        } else {
            $api.query($params).$promise.then(function (all) {
                $scope.models = all;
                //copy the references (you could clone ie angular.copy but then have to go through a dirty checking for the matches)
                $scope.displayedModels = [].concat($scope.models);
            });
        }

        $scope.dropped = function(draggedModel, droppedModel) {
            if (droppedModel.type === 'f') {
                var index = $scope.models.indexOf(draggedModel);
                $scope.models.splice(index, 1);

                let data = {
                    folder_id: droppedModel.id
                }
                $api.update({id: draggedModel.id}, data).$promise.then(
                    function (data) {},
                    function (reason) {
                        alertify.error('Error ' + reason.status + ' ' + reason.statusText);
                    }
                );

            }
        }

        $scope.allowDrop = function(e) {
            return false;
        }

        /**
         * Open folder
         */
        $scope.open = function (model) {
            if (model.type === 'f') {
                window.location.href = '?folder_id='+model.id;
            }
        };

        /**
         * Check all items
         */
        $scope.toggleCheck = function (model) {
            console.log(model);
            let index = $scope.checked.models.indexOf(model);
            if (index !== -1) {
                $scope.checked.models.splice(index, 1);
            } else {
                $scope.checked.models.push(model);
            }
            // console.log($scope.checked.models);
        };

        /**
         * Delete checked items
         */
        $scope.deleteChecked = function () {

            var ids = [],
                models = $scope.checked.models,
                number = models.length;

            if ($scope.checked.models.length > $scope.deleteLimit) {
                alertify.error('Impossible to delete more than ' + $scope.deleteLimit + ' items in one go.');
                return false;
            }
            if (!window.confirm('Are you sure you want to delete ' + number + ' items?')) {
                return false;
            }

            models.forEach(function (model) {
                ids.push(model.id);
                var index = $scope.models.indexOf(model);
                $scope.models.splice(index, 1);
            });

            $scope.checked.models = [];

            $scope.loading = true;

            $api.delete({id: ids.join()}).$promise.then(
                function (data) {
                    $scope.loading = false;
                    if (data.number < number) {
                        alertify.error((number - data.number) + ' items could not be deleted.');
                    }
                    if (data.number > 0) {
                        alertify.success(data.number + ' items deleted.');
                    }
                },
                function (reason) {
                    $scope.loading = false;
                    alertify.error('Error ' + reason.status + ' ' + reason.statusText);
                }
            );

        };

    }]);

}(angular));
<|endoftext|>


<commit_before>import { create as createMutex } from 'mutex-browser';

import { RETRY_ATTEMPTS_MAX, RETRY_DELAY_MAX, OFFLINE_RETRY_ATTEMPTS_MAX, OFFLINE_RETRY_DELAY } from '../../constants';
import { createOnceHandler } from '../../apiHandlers';
import { wait } from '../../helpers/promise';
import { API_CUSTOM_ERROR_CODES, HTTP_ERROR_CODES } from '../../errors';
import { withUIDHeaders } from '../../fetch/headers';
import { setRefreshCookies } from '../auth';
import { getApiError } from './apiErrorHelper';
import { noop, randomIntFromInterval } from '../../helpers/function';
import { getDateHeader } from '../../fetch/helpers';
import { getLastRefreshDate, setLastRefreshDate } from './refreshStorage';

export const InactiveSessionError = () => {
    const error = new Error('Inactive session');
    error.name = 'InactiveSession';
    return error;
};

export const AppVersionBadError = () => {
    const error = new Error('App version outdated');
    error.name = 'AppVersionBadError';
    return error;
};

export const RetryError = () => {
    const error = new Error('Retry-After');
    error.name = 'RetryAfterError';
    return error;
};

export const CancelUnlockError = () => {
    const error = new Error('Cancel unlock');
    error.name = 'CancelUnlock';
    return error;
};

export const CancelVerificationError = () => {
    const error = new Error('Cancel verification');
    error.name = 'CancelVerification';
    return error;
};

/**
 * Handle retry-after
 * @param {Error} e
 * @returns {Promise}
 */
const retryHandler = (e) => {
    const {
        response: { headers },
    } = e;

    const retryAfterSeconds = parseInt(headers.get('retry-after') || 0, 10);

    if (retryAfterSeconds < 0 || retryAfterSeconds >= RETRY_DELAY_MAX) {
        return Promise.reject(RetryError());
    }

    return wait(retryAfterSeconds * 1000);
};

/**
 * Handle refresh token. Happens when the access token has expired.
 * Multiple calls can fail, so this ensures the refresh route is called once.
 * Needs to re-handle errors here for that reason.
 */
const refresh = (call, UID, attempts, maxAttempts) => {
    return call(withUIDHeaders(UID, setRefreshCookies())).catch((e) => {
        if (attempts >= maxAttempts) {
            throw e;
        }

        const { status, name } = e;

        if (name === 'OfflineError') {
            if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
                throw e;
            }
            return wait(OFFLINE_RETRY_DELAY).then(() => refresh(call, UID, attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX));
        }

        if (name === 'TimeoutError') {
            if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
                throw e;
            }
            return refresh(call, UID, attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX);
        }

        if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
            return retryHandler(e).then(() => refresh(call, UID, attempts + 1, RETRY_ATTEMPTS_MAX));
        }

        throw e;
    });
};

/**
 * Attach a catch handler to every API call to handle 401, 403, and other errors.
 * @param {function} call
 * @param {string} UID
 * @param {function} onUnlock
 * @param {function} onError
 * @param {function} onVerification
 * @return {function}
 */
export default ({ call, UID, onUnlock, onError, onVerification }) => {
    let loggedOut = false;
    let appVersionBad = false;

    const refreshHandlers = {};
    const refreshHandler = (UID, responseDate) => {
        if (!refreshHandlers[UID]) {
            const mutex = createMutex({ expiry: 15000 });

            const getMutexLock = async (UID) => {
                try {
                    await mutex.lock(UID);
                    return () => {
                        return mutex.unlock(UID).catch(noop);
                    };
                } catch (e) {
                    // If getting the mutex fails, fall back to a random wait
                    await wait(randomIntFromInterval(100, 2000));
                    return () => {
                        return Promise.resolve();
                    };
                }
            };

            /**
             * Refreshing the session needs to handle multiple race conditions.
             * 1) Race conditions within the context (tab). Solved by the once handler.
             * 2) Race conditions within multiple contexts (tabs). Solved by the shared mutex.
             */
            refreshHandlers[UID] = createOnceHandler(async (responseDate = new Date()) => {
                const unlockMutex = await getMutexLock(UID);
                try {
                    const lastRefreshDate = getLastRefreshDate(UID);
                    if (lastRefreshDate === undefined || responseDate > lastRefreshDate) {
                        const result = await refresh(call, UID, 1, RETRY_ATTEMPTS_MAX);
                        setLastRefreshDate(UID, getDateHeader(result.headers) || new Date());
                        // Add an artificial delay to ensure cookies are properly updated to avoid race conditions
                        await wait(50);
                    }
                } finally {
                    await unlockMutex();
                }
            });
        }

        return refreshHandlers[UID](responseDate);
    };
    const unlockHandler = createOnceHandler(onUnlock);

    return (options) => {
        const perform = (attempts, maxAttempts) => {
            if (loggedOut) {
                return Promise.resolve().then(() => {
                    return onError(InactiveSessionError());
                });
            }
            if (appVersionBad) {
                return Promise.resolve().then(() => {
                    return onError(AppVersionBadError());
                });
            }

            return call(options).catch((e) => {
                if (loggedOut) {
                    return onError(InactiveSessionError());
                }

                if (maxAttempts && attempts >= maxAttempts) {
                    return onError(e);
                }

                const { status, name, response } = e;

                const { ignoreHandler, silence = [], headers } = options || {};

                if (name === 'OfflineError') {
                    if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
                        return onError(e);
                    }
                    return wait(OFFLINE_RETRY_DELAY).then(() => perform(attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX));
                }

                if (name === 'TimeoutError') {
                    if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
                        return onError(e);
                    }
                    return perform(attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX);
                }

                const ignoreUnauthorized =
                    Array.isArray(ignoreHandler) && ignoreHandler.includes(HTTP_ERROR_CODES.UNAUTHORIZED);
                const requestUID = (headers && headers['x-pm-uid']) || UID;
                // Sending a request with a UID but without an authorization header is when the public app makes
                // authenticated requests (mostly for persisted sessions), and ignoring "login" or "signup" requests.
                if (
                    status === HTTP_ERROR_CODES.UNAUTHORIZED &&
                    !ignoreUnauthorized &&
                    (UID || (requestUID && !(headers && !!headers.Authorization)))
                ) {
                    return refreshHandler(requestUID, getDateHeader(response && response.headers)).then(
                        () => perform(attempts + 1, RETRY_ATTEMPTS_MAX),
                        (error) => {
                            // Any 4xx and the session is no longer valid, 429 is already handled in the refreshHandler
                            if ((error.status >= 400 && error.status <= 499) || error.name === 'RetryAfterError') {
                                // Disable any further requests on this session if it was created with a UID
                                if (UID) {
                                    loggedOut = true;
                                }
                                return onError(InactiveSessionError());
                            }
                            return onError(error);
                        }
                    );
                }

                const ignoreUnlock = Array.isArray(ignoreHandler) && ignoreHandler.includes(HTTP_ERROR_CODES.UNLOCK);
                if (status === HTTP_ERROR_CODES.UNLOCK && !ignoreUnlock) {
                    const { Details: { MissingScopes: missingScopes = [] } = {} } = e.data || {};
                    return unlockHandler(missingScopes, e).then(
                        () => perform(attempts + 1, RETRY_ATTEMPTS_MAX),
                        (unlockError) => onError(unlockError)
                    );
                }

                if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
                    return retryHandler(e).then(
                        () => perform(attempts + 1, RETRY_ATTEMPTS_MAX),
                        () => onError(e)
                    );
                }

                const { code } = getApiError(e);

                if (code === API_CUSTOM_ERROR_CODES.APP_VERSION_BAD) {
                    appVersionBad = true;
                    return onError(AppVersionBadError());
                }

                const ignoreHumanVerification =
                    Array.isArray(ignoreHandler) &&
                    ignoreHandler.includes(API_CUSTOM_ERROR_CODES.HUMAN_VERIFICATION_REQUIRED);
                if (code === API_CUSTOM_ERROR_CODES.HUMAN_VERIFICATION_REQUIRED && !ignoreHumanVerification) {
                    const {
                        Details: { HumanVerificationToken: captchaToken, HumanVerificationMethods: methods = [] } = {},
                    } = e.data || {};

                    const onVerify = (token, tokenType) => {
                        return call({
                            ...options,
                            silence: [...silence, API_CUSTOM_ERROR_CODES.TOKEN_INVALID],
                            headers: {
                                ...options.headers,
                                'x-pm-human-verification-token': token,
                                'x-pm-human-verification-token-type': tokenType,
                            },
                        }).catch(onError);
                    };

                    return onVerification({ token: captchaToken, methods, onVerify });
                }

                return onError(e);
            });
        };

        return perform(1);
    };
};
<commit_msg>Allow configuring of timeout retry attempts in fetch options<commit_after>import { create as createMutex } from 'mutex-browser';

import { RETRY_ATTEMPTS_MAX, RETRY_DELAY_MAX, OFFLINE_RETRY_ATTEMPTS_MAX, OFFLINE_RETRY_DELAY } from '../../constants';
import { createOnceHandler } from '../../apiHandlers';
import { wait } from '../../helpers/promise';
import { API_CUSTOM_ERROR_CODES, HTTP_ERROR_CODES } from '../../errors';
import { withUIDHeaders } from '../../fetch/headers';
import { setRefreshCookies } from '../auth';
import { getApiError } from './apiErrorHelper';
import { noop, randomIntFromInterval } from '../../helpers/function';
import { getDateHeader } from '../../fetch/helpers';
import { getLastRefreshDate, setLastRefreshDate } from './refreshStorage';

export const InactiveSessionError = () => {
    const error = new Error('Inactive session');
    error.name = 'InactiveSession';
    return error;
};

export const AppVersionBadError = () => {
    const error = new Error('App version outdated');
    error.name = 'AppVersionBadError';
    return error;
};

export const RetryError = () => {
    const error = new Error('Retry-After');
    error.name = 'RetryAfterError';
    return error;
};

export const CancelUnlockError = () => {
    const error = new Error('Cancel unlock');
    error.name = 'CancelUnlock';
    return error;
};

export const CancelVerificationError = () => {
    const error = new Error('Cancel verification');
    error.name = 'CancelVerification';
    return error;
};

/**
 * Handle retry-after
 * @param {Error} e
 * @returns {Promise}
 */
const retryHandler = (e) => {
    const {
        response: { headers },
    } = e;

    const retryAfterSeconds = parseInt(headers.get('retry-after') || 0, 10);

    if (retryAfterSeconds < 0 || retryAfterSeconds >= RETRY_DELAY_MAX) {
        return Promise.reject(RetryError());
    }

    return wait(retryAfterSeconds * 1000);
};

/**
 * Handle refresh token. Happens when the access token has expired.
 * Multiple calls can fail, so this ensures the refresh route is called once.
 * Needs to re-handle errors here for that reason.
 */
const refresh = (call, UID, attempts, maxAttempts) => {
    return call(withUIDHeaders(UID, setRefreshCookies())).catch((e) => {
        if (attempts >= maxAttempts) {
            throw e;
        }

        const { status, name } = e;

        if (name === 'OfflineError') {
            if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
                throw e;
            }
            return wait(OFFLINE_RETRY_DELAY).then(() => refresh(call, UID, attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX));
        }

        if (name === 'TimeoutError') {
            if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
                throw e;
            }
            return refresh(call, UID, attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX);
        }

        if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
            return retryHandler(e).then(() => refresh(call, UID, attempts + 1, RETRY_ATTEMPTS_MAX));
        }

        throw e;
    });
};

/**
 * Attach a catch handler to every API call to handle 401, 403, and other errors.
 * @param {function} call
 * @param {string} UID
 * @param {function} onUnlock
 * @param {function} onError
 * @param {function} onVerification
 * @return {function}
 */
export default ({ call, UID, onUnlock, onError, onVerification }) => {
    let loggedOut = false;
    let appVersionBad = false;

    const refreshHandlers = {};
    const refreshHandler = (UID, responseDate) => {
        if (!refreshHandlers[UID]) {
            const mutex = createMutex({ expiry: 15000 });

            const getMutexLock = async (UID) => {
                try {
                    await mutex.lock(UID);
                    return () => {
                        return mutex.unlock(UID).catch(noop);
                    };
                } catch (e) {
                    // If getting the mutex fails, fall back to a random wait
                    await wait(randomIntFromInterval(100, 2000));
                    return () => {
                        return Promise.resolve();
                    };
                }
            };

            /**
             * Refreshing the session needs to handle multiple race conditions.
             * 1) Race conditions within the context (tab). Solved by the once handler.
             * 2) Race conditions within multiple contexts (tabs). Solved by the shared mutex.
             */
            refreshHandlers[UID] = createOnceHandler(async (responseDate = new Date()) => {
                const unlockMutex = await getMutexLock(UID);
                try {
                    const lastRefreshDate = getLastRefreshDate(UID);
                    if (lastRefreshDate === undefined || responseDate > lastRefreshDate) {
                        const result = await refresh(call, UID, 1, RETRY_ATTEMPTS_MAX);
                        setLastRefreshDate(UID, getDateHeader(result.headers) || new Date());
                        // Add an artificial delay to ensure cookies are properly updated to avoid race conditions
                        await wait(50);
                    }
                } finally {
                    await unlockMutex();
                }
            });
        }

        return refreshHandlers[UID](responseDate);
    };
    const unlockHandler = createOnceHandler(onUnlock);

    return (options) => {
        const perform = (attempts, maxAttempts) => {
            if (loggedOut) {
                return Promise.resolve().then(() => {
                    return onError(InactiveSessionError());
                });
            }
            if (appVersionBad) {
                return Promise.resolve().then(() => {
                    return onError(AppVersionBadError());
                });
            }

            return call(options).catch((e) => {
                if (loggedOut) {
                    return onError(InactiveSessionError());
                }

                if (maxAttempts && attempts >= maxAttempts) {
                    return onError(e);
                }

                const { status, name, response } = e;

                const {
                    ignoreHandler,
                    silence = [],
                    headers,
                    retriesOnOffline = OFFLINE_RETRY_ATTEMPTS_MAX,
                    retriesOnTimeout = OFFLINE_RETRY_ATTEMPTS_MAX,
                } = options || {};

                if (name === 'OfflineError') {
                    if (attempts > retriesOnOffline) {
                        return onError(e);
                    }
                    return wait(OFFLINE_RETRY_DELAY).then(() => perform(attempts + 1, retriesOnOffline));
                }

                if (name === 'TimeoutError') {
                    if (attempts > retriesOnTimeout) {
                        return onError(e);
                    }
                    return perform(attempts + 1, retriesOnTimeout);
                }

                const ignoreUnauthorized =
                    Array.isArray(ignoreHandler) && ignoreHandler.includes(HTTP_ERROR_CODES.UNAUTHORIZED);
                const requestUID = (headers && headers['x-pm-uid']) || UID;
                // Sending a request with a UID but without an authorization header is when the public app makes
                // authenticated requests (mostly for persisted sessions), and ignoring "login" or "signup" requests.
                if (
                    status === HTTP_ERROR_CODES.UNAUTHORIZED &&
                    !ignoreUnauthorized &&
                    (UID || (requestUID && !(headers && !!headers.Authorization)))
                ) {
                    return refreshHandler(requestUID, getDateHeader(response && response.headers)).then(
                        () => perform(attempts + 1, RETRY_ATTEMPTS_MAX),
                        (error) => {
                            // Any 4xx and the session is no longer valid, 429 is already handled in the refreshHandler
                            if ((error.status >= 400 && error.status <= 499) || error.name === 'RetryAfterError') {
                                // Disable any further requests on this session if it was created with a UID
                                if (UID) {
                                    loggedOut = true;
                                }
                                return onError(InactiveSessionError());
                            }
                            return onError(error);
                        }
                    );
                }

                const ignoreUnlock = Array.isArray(ignoreHandler) && ignoreHandler.includes(HTTP_ERROR_CODES.UNLOCK);
                if (status === HTTP_ERROR_CODES.UNLOCK && !ignoreUnlock) {
                    const { Details: { MissingScopes: missingScopes = [] } = {} } = e.data || {};
                    return unlockHandler(missingScopes, e).then(
                        () => perform(attempts + 1, RETRY_ATTEMPTS_MAX),
                        (unlockError) => onError(unlockError)
                    );
                }

                if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
                    return retryHandler(e).then(
                        () => perform(attempts + 1, RETRY_ATTEMPTS_MAX),
                        () => onError(e)
                    );
                }

                const { code } = getApiError(e);

                if (code === API_CUSTOM_ERROR_CODES.APP_VERSION_BAD) {
                    appVersionBad = true;
                    return onError(AppVersionBadError());
                }

                const ignoreHumanVerification =
                    Array.isArray(ignoreHandler) &&
                    ignoreHandler.includes(API_CUSTOM_ERROR_CODES.HUMAN_VERIFICATION_REQUIRED);
                if (code === API_CUSTOM_ERROR_CODES.HUMAN_VERIFICATION_REQUIRED && !ignoreHumanVerification) {
                    const {
                        Details: { HumanVerificationToken: captchaToken, HumanVerificationMethods: methods = [] } = {},
                    } = e.data || {};

                    const onVerify = (token, tokenType) => {
                        return call({
                            ...options,
                            silence: [...silence, API_CUSTOM_ERROR_CODES.TOKEN_INVALID],
                            headers: {
                                ...options.headers,
                                'x-pm-human-verification-token': token,
                                'x-pm-human-verification-token-type': tokenType,
                            },
                        }).catch(onError);
                    };

                    return onVerification({ token: captchaToken, methods, onVerify });
                }

                return onError(e);
            });
        };

        return perform(1);
    };
};
<|endoftext|>


<commit_before>import debugModule from "debug";
const debug = debugModule("debugger:data:decode");

import {BigNumber} from "bignumber.js";

import * as memory from "./memory";
import * as storage from "./storage";
import * as utils from "./utils";
import { WORD_SIZE } from "./utils";

export function read(pointer, state) {
  if (pointer.stack != undefined && state.stack && pointer.stack < state.stack.length) {
    return state.stack[pointer.stack];
  } else if (pointer.storage != undefined && state.storage) {
    return storage.readRange(state.storage, pointer.storage);
  } else if (pointer.memory != undefined && state.memory) {
    return memory.readBytes(state.memory, pointer.memory.start, pointer.memory.length);
  } else if (pointer.literal != undefined) {
    return pointer.literal;
  }
}

export function decodeValue(definition, pointer, info) {
  const { state } = info;
  debug(
    "decoding value, pointer: %o, typeClass: %s",
    pointer, utils.typeClass(definition)
  );
  let bytes = read(pointer, state);
  if (bytes == undefined) {
    debug("segfault, pointer %o, state: %O", pointer, state);
    return undefined;
  }

  switch (utils.typeClass(definition)) {
    case "bool":
      return !utils.toBigNumber(bytes).isZero();

    case "uint":
      return utils.toBigNumber(bytes);

    case "int":
      return utils.toSignedBigNumber(bytes);

    case "address":
      return utils.toHexString(bytes, true);

    case "bytes":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      // HACK bytes may be getting passed in as a literal hexstring
      if (typeof bytes == "string") {
        return bytes;
      }
      let length = utils.specifiedSize(definition);
      return utils.toHexString(bytes, length);

    case "string":
    case "stringliteral":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      if (typeof bytes == "string") {
        return bytes;
      }
      return String.fromCharCode.apply(undefined, bytes);

    case "rational":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      return utils.toBigNumber(bytes);

    default:
      debug("Unknown value type: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

export function decodeMemoryReference(definition, pointer, info) {
  const { state } = info
  debug("pointer %o", pointer);
  let rawValue = read(pointer, state)
  if (rawValue == undefined) {
    return undefined;
  }

  rawValue = utils.toBigNumber(rawValue).toNumber();

  var bytes;
  switch (utils.typeClass(definition)) {

    case "bytes":
    case "string":
      bytes = read({
        memory: { start: rawValue, length: WORD_SIZE}
      }, state); // bytes contain length

      let childPointer = {
        memory: { start: rawValue + WORD_SIZE, length: bytes }
      }

      return decodeValue(definition, childPointer, info);

    case "array":
      bytes = utils.toBigNumber(read({
        memory: { start: rawValue, length: WORD_SIZE },
      }, state)).toNumber();  // bytes contain array length

      bytes = read({ memory: {
        start: rawValue + WORD_SIZE, length: bytes * WORD_SIZE
      }}, state); // now bytes contain items

      return memory.chunk(bytes, WORD_SIZE)
        .map(
          (chunk) => decode(utils.baseDefinition(definition), {
            literal: chunk
          }, info)
        )

    case "struct":
      const { scopes } = info;

      // Declaration reference usually appears in `typeName`, but for
      // { nodeType: "FunctionCall", kind: "structConstructorCall" }, this
      // reference appears to live in `expression`
      const referencedDeclaration = (definition.typeName)
        ? definition.typeName.referencedDeclaration
        : definition.expression.referencedDeclaration;

      let structDefinition = scopes[referencedDeclaration];
      let structVariables = structDefinition.variables || [];

      return Object.assign(
        {}, ...structVariables
          .map(
            ({name, id}, i) => {
              let memberDefinition = scopes[id].definition;
              let memberPointer = {
                memory: { start: rawValue + i * WORD_SIZE, length: WORD_SIZE }
              };
              // let memberPointer = memory.read(state.memory, pointer + i * WORD_SIZE);

              // HACK
              memberDefinition = {
                ...memberDefinition,

                typeDescriptions: {
                  ...memberDefinition.typeDescriptions,

                  typeIdentifier:
                    memberDefinition.typeDescriptions.typeIdentifier
                      .replace(/_storage_/g, "_memory_")
                }
              };

              return {
                [name]: decode(
                  memberDefinition, memberPointer, info
                )
              };
            }
          )
      );

    default:
      debug("Unknown memory reference type: %s", utils.typeIdentifier(definition));
      return undefined;

  }

}

export function decodeStorageReference(definition, pointer, info) {
  var data;
  var bytes;
  var length;
  var slot;

  const { state } = info;

  switch (utils.typeClass(definition)) {
    case "array":
      debug("storage array! %o", pointer);
      data = read(pointer, state);
      if (!data) {
        return undefined;
      }

      length = utils.toBigNumber(data).toNumber();
      debug("length %o", length);

      const baseSize = utils.storageSize(utils.baseDefinition(definition));
      const perWord = Math.floor(WORD_SIZE / baseSize);
      debug("baseSize %o", baseSize);
      debug("perWord %d", perWord);

      const offset = (i) => {
        if (perWord == 1) {
          return i;
        }

        return Math.floor(i * baseSize / WORD_SIZE);
      }

      const index = (i) => {
        if (perWord == 1) {
          return WORD_SIZE - baseSize;
        }

        const position = perWord - i % perWord - 1;
        return position * baseSize;
      }

      let from = {
        slot: utils.normalizeSlot(pointer.storage.from.slot),
        index: pointer.storage.from.index
      };

      debug("pointer: %o", pointer);
      return [...Array(length).keys()]
        .map( (i) => {
          let childFrom = {
            slot: {
              path: (from.slot.path instanceof Array)
                ? from.slot.path
                : [from.slot],
              offset: offset(i),
            },
            index: index(i)
          };
          return childFrom;
        })
        .map( (childFrom, idx) => {
          debug("childFrom %d, %o", idx, childFrom);
          return decode(utils.baseDefinition(definition), { storage: {
            from: childFrom,
            length: baseSize
          }}, info);
        });

    case "bytes":
    case "string":
      data = read(pointer, state);
      if (data == undefined) {
        return undefined;
      }

      debug("data %O", data);
      let lengthByte = data[WORD_SIZE - 1];
      if (!lengthByte) {
        lengthByte = 0;
      }

      if (lengthByte % 2 == 0) {
        // string lives in word, length is last byte / 2
        length = lengthByte / 2;
        debug("in-word; length %o", length);
        if (length == 0) {
          return "";
        }

        return decodeValue(definition, { storage: {
          from: { slot: pointer.storage.from.slot, index: 0 },
          to: { slot: pointer.storage.from.slot, index: length - 1}
        }}, info);

      } else {
        length = utils.toBigNumber(data).minus(1).div(2).toNumber();
        debug("new-word, length %o", length);

        return decodeValue(definition, { storage: {
          from: { slot: [pointer.storage.from.slot], index: 0 },
          length
        }}, info);
      }

    case "struct":
      const { scopes } = info;

      return Object.assign(
        {}, ...Object.entries(pointer.storage.children)
          .map( ([id, childPointer]) => ({
            [childPointer.name]: decode(
              scopes[id].definition, { storage: childPointer }, info
            )
          }))
      );

    default:
      debug("Unknown storage reference type: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

export function decodeMapping(definition, pointer, info) {
  if (definition.referencedDeclaration) {
    // attempting to decode reference to mapping, thus missing valid pointer
    return undefined;
  }

  const { mappingKeys } = info;

  debug("mapping %O", pointer);
  debug("mapping definition %O", definition);
  let keys = mappingKeys[definition.id] || [];
  debug("known keys %o", keys);

  let keyDefinition = definition.typeName.keyType;
  let valueDefinition = definition.typeName.valueType;

  let baseSlot = pointer.storage.from.slot;
  if (!Array.isArray(baseSlot)) {
    baseSlot = [baseSlot];
  }

  let mapping = {};
  debug("mapping %O", mapping);
  for (let key of keys) {
    let keyPointer = { "literal": key };
    let valuePointer = {
      storage: {
        from: {
          slot: [key, ...baseSlot],
          index: 0
        },
        to: {
          slot: [key, ...baseSlot],
          index: 31
        }
      }
    };
    debug("keyPointer %o", keyPointer);

    // NOTE mapping keys are potentially lossy because JS only likes strings
    let keyValue = decode(keyDefinition, keyPointer, info);
    debug("keyValue %o", keyValue);
    if (keyValue != undefined) {
      mapping[keyValue.toString()] =
        decode(valueDefinition, valuePointer, info);
    }
  }

  return mapping;
}

export default function decode(definition, pointer, info) {
  if (pointer.literal != undefined) {
    return decodeValue(definition, pointer, info);
  }

  const identifier = utils.typeIdentifier(definition);
  if (utils.isReference(definition)) {
    switch (utils.referenceType(definition)) {
      case "memory":
        debug("decoding memory reference, type: %s", identifier);
        return decodeMemoryReference(definition, pointer, info);
      case "storage":
        debug("decoding storage reference, type: %s", identifier);
        return decodeStorageReference(definition, pointer, info);
      default:
        debug("Unknown reference category: %s", utils.typeIdentifier(definition));
        return undefined;
    }
  }

  if (utils.isMapping(definition)) {
    debug("decoding mapping, type: %s", identifier);
    return decodeMapping(definition, pointer, info);
  }

  debug("decoding value, type: %s", identifier);
  return decodeValue(definition, pointer, info);
}
<commit_msg>Perform struct storage allocation at decode-time<commit_after>import debugModule from "debug";
const debug = debugModule("debugger:data:decode");

import {BigNumber} from "bignumber.js";

import * as memory from "./memory";
import * as storage from "./storage";
import * as utils from "./utils";
import { WORD_SIZE } from "./utils";

export function read(pointer, state) {
  if (pointer.stack != undefined && state.stack && pointer.stack < state.stack.length) {
    return state.stack[pointer.stack];
  } else if (pointer.storage != undefined && state.storage) {
    return storage.readRange(state.storage, pointer.storage);
  } else if (pointer.memory != undefined && state.memory) {
    return memory.readBytes(state.memory, pointer.memory.start, pointer.memory.length);
  } else if (pointer.literal != undefined) {
    return pointer.literal;
  }
}

export function decodeValue(definition, pointer, info) {
  const { state } = info;
  debug(
    "decoding value, pointer: %o, typeClass: %s",
    pointer, utils.typeClass(definition)
  );
  let bytes = read(pointer, state);
  if (bytes == undefined) {
    debug("segfault, pointer %o, state: %O", pointer, state);
    return undefined;
  }

  switch (utils.typeClass(definition)) {
    case "bool":
      return !utils.toBigNumber(bytes).isZero();

    case "uint":
      return utils.toBigNumber(bytes);

    case "int":
      return utils.toSignedBigNumber(bytes);

    case "address":
      return utils.toHexString(bytes, true);

    case "bytes":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      // HACK bytes may be getting passed in as a literal hexstring
      if (typeof bytes == "string") {
        return bytes;
      }
      let length = utils.specifiedSize(definition);
      return utils.toHexString(bytes, length);

    case "string":
    case "stringliteral":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      if (typeof bytes == "string") {
        return bytes;
      }
      return String.fromCharCode.apply(undefined, bytes);

    case "rational":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      return utils.toBigNumber(bytes);

    default:
      debug("Unknown value type: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

export function decodeMemoryReference(definition, pointer, info) {
  const { state } = info
  debug("pointer %o", pointer);
  let rawValue = read(pointer, state)
  if (rawValue == undefined) {
    return undefined;
  }

  rawValue = utils.toBigNumber(rawValue).toNumber();

  var bytes;
  switch (utils.typeClass(definition)) {

    case "bytes":
    case "string":
      bytes = read({
        memory: { start: rawValue, length: WORD_SIZE}
      }, state); // bytes contain length

      let childPointer = {
        memory: { start: rawValue + WORD_SIZE, length: bytes }
      }

      return decodeValue(definition, childPointer, info);

    case "array":
      bytes = utils.toBigNumber(read({
        memory: { start: rawValue, length: WORD_SIZE },
      }, state)).toNumber();  // bytes contain array length

      bytes = read({ memory: {
        start: rawValue + WORD_SIZE, length: bytes * WORD_SIZE
      }}, state); // now bytes contain items

      return memory.chunk(bytes, WORD_SIZE)
        .map(
          (chunk) => decode(utils.baseDefinition(definition), {
            literal: chunk
          }, info)
        )

    case "struct":
      const { scopes } = info;

      // Declaration reference usually appears in `typeName`, but for
      // { nodeType: "FunctionCall", kind: "structConstructorCall" }, this
      // reference appears to live in `expression`
      const referencedDeclaration = (definition.typeName)
        ? definition.typeName.referencedDeclaration
        : definition.expression.referencedDeclaration;

      let { variables } = (scopes[referencedDeclaration] || {});

      return Object.assign(
        {}, ...(variables || [])
          .map(
            ({name, id}, i) => {
              let memberDefinition = scopes[id].definition;
              let memberPointer = {
                memory: { start: rawValue + i * WORD_SIZE, length: WORD_SIZE }
              };
              // let memberPointer = memory.read(state.memory, pointer + i * WORD_SIZE);

              // HACK
              memberDefinition = {
                ...memberDefinition,

                typeDescriptions: {
                  ...memberDefinition.typeDescriptions,

                  typeIdentifier:
                    memberDefinition.typeDescriptions.typeIdentifier
                      .replace(/_storage_/g, "_memory_")
                }
              };

              return {
                [name]: decode(
                  memberDefinition, memberPointer, info
                )
              };
            }
          )
      );

    default:
      debug("Unknown memory reference type: %s", utils.typeIdentifier(definition));
      return undefined;

  }

}

export function decodeStorageReference(definition, pointer, info) {
  var data;
  var bytes;
  var length;
  var slot;

  const { state } = info;

  switch (utils.typeClass(definition)) {
    case "array":
      debug("storage array! %o", pointer);
      data = read(pointer, state);
      if (!data) {
        return undefined;
      }

      length = utils.toBigNumber(data).toNumber();
      debug("length %o", length);

      const baseSize = utils.storageSize(utils.baseDefinition(definition));
      const perWord = Math.floor(WORD_SIZE / baseSize);
      debug("baseSize %o", baseSize);
      debug("perWord %d", perWord);

      const offset = (i) => {
        if (perWord == 1) {
          return i;
        }

        return Math.floor(i * baseSize / WORD_SIZE);
      }

      const index = (i) => {
        if (perWord == 1) {
          return WORD_SIZE - baseSize;
        }

        const position = perWord - i % perWord - 1;
        return position * baseSize;
      }

      let from = {
        slot: utils.normalizeSlot(pointer.storage.from.slot),
        index: pointer.storage.from.index
      };

      debug("pointer: %o", pointer);
      return [...Array(length).keys()]
        .map( (i) => {
          let childFrom = {
            slot: {
              path: (from.slot.path instanceof Array)
                ? from.slot.path
                : [from.slot],
              offset: offset(i),
            },
            index: index(i)
          };
          return childFrom;
        })
        .map( (childFrom, idx) => {
          debug("childFrom %d, %o", idx, childFrom);
          return decode(utils.baseDefinition(definition), { storage: {
            from: childFrom,
            length: baseSize
          }}, info);
        });

    case "bytes":
    case "string":
      data = read(pointer, state);
      if (data == undefined) {
        return undefined;
      }

      debug("data %O", data);
      let lengthByte = data[WORD_SIZE - 1];
      if (!lengthByte) {
        lengthByte = 0;
      }

      if (lengthByte % 2 == 0) {
        // string lives in word, length is last byte / 2
        length = lengthByte / 2;
        debug("in-word; length %o", length);
        if (length == 0) {
          return "";
        }

        return decodeValue(definition, { storage: {
          from: { slot: pointer.storage.from.slot, index: 0 },
          to: { slot: pointer.storage.from.slot, index: length - 1}
        }}, info);

      } else {
        length = utils.toBigNumber(data).minus(1).div(2).toNumber();
        debug("new-word, length %o", length);

        return decodeValue(definition, { storage: {
          from: { slot: [pointer.storage.from.slot], index: 0 },
          length
        }}, info);
      }

    case "struct":
      const { scopes } = info;

      const referencedDeclaration = (definition.typeName)
        ? definition.typeName.referencedDeclaration
        : definition.referencedDeclaration;

      const { variables } = (scopes[referencedDeclaration] || {});

      const allocation = utils.allocateDeclarations(
        variables || [], scopes, pointer.storage.from.slot
      );

      return Object.assign(
        {}, ...Object.entries(allocation.children)
          .map( ([id, childPointer]) => ({
            [childPointer.name]: decode(
              scopes[id].definition, { storage: childPointer }, info
            )
          }))
      );

    default:
      debug("Unknown storage reference type: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

export function decodeMapping(definition, pointer, info) {
  if (definition.referencedDeclaration) {
    // attempting to decode reference to mapping, thus missing valid pointer
    return undefined;
  }

  const { mappingKeys } = info;

  debug("mapping %O", pointer);
  debug("mapping definition %O", definition);
  let keys = mappingKeys[definition.id] || [];
  debug("known keys %o", keys);

  let keyDefinition = definition.typeName.keyType;
  let valueDefinition = definition.typeName.valueType;

  let baseSlot = pointer.storage.from.slot;
  if (!Array.isArray(baseSlot)) {
    baseSlot = [baseSlot];
  }

  let mapping = {};
  debug("mapping %O", mapping);
  for (let key of keys) {
    let keyPointer = { "literal": key };
    let valuePointer = {
      storage: {
        from: {
          slot: [key, ...baseSlot],
          index: 0
        },
        to: {
          slot: [key, ...baseSlot],
          index: 31
        }
      }
    };
    debug("keyPointer %o", keyPointer);

    // NOTE mapping keys are potentially lossy because JS only likes strings
    let keyValue = decode(keyDefinition, keyPointer, info);
    debug("keyValue %o", keyValue);
    if (keyValue != undefined) {
      mapping[keyValue.toString()] =
        decode(valueDefinition, valuePointer, info);
    }
  }

  return mapping;
}

export default function decode(definition, pointer, info) {
  if (pointer.literal != undefined) {
    return decodeValue(definition, pointer, info);
  }

  const identifier = utils.typeIdentifier(definition);
  if (utils.isReference(definition)) {
    switch (utils.referenceType(definition)) {
      case "memory":
        debug("decoding memory reference, type: %s", identifier);
        return decodeMemoryReference(definition, pointer, info);
      case "storage":
        debug("decoding storage reference, type: %s", identifier);
        return decodeStorageReference(definition, pointer, info);
      default:
        debug("Unknown reference category: %s", utils.typeIdentifier(definition));
        return undefined;
    }
  }

  if (utils.isMapping(definition)) {
    debug("decoding mapping, type: %s", identifier);
    return decodeMapping(definition, pointer, info);
  }

  debug("decoding value, type: %s", identifier);
  return decodeValue(definition, pointer, info);
}
<|endoftext|>


<commit_before>/*!
 * accounting.js javascript library v0.3-alpha
 * http://josscrowcroft.github.com/accounting.js/
 *
 * Copyright 2011 by Joss Crowcroft
 * Licensed under GPL v3 | http://www.gnu.org/licenses/gpl-3.0.txt
 */

(function(root, undefined) {

	/* --- Setup --- */

	// Create the local library object, to be exported or referenced globally later
	var lib = {};

	// Current version
	lib.version = '0.3-alpha';

	/* --- Exposed settings --- */

	// The library's settings configuration object. Contains default parameters for
	// currency and number formatting
	lib.settings = {
		currency: {
			symbol : "$",		// default currency symbol is '$'
			format : "%s%v",	// controls output: %s = symbol, %v = value (can be object, see docs)
			decimal : ".",		// decimal point separator
			thousand : ",",		// thousands separator
			precision : 2,		// decimal places
			grouping : 3		// digit grouping (not implemented yet)
		},
		number: {
			precision : 0,		// default precision on numbers is 0
			grouping : 3,		// digit grouping (not implemented yet)
			thousand : ",",
			decimal : "."
		}
	};

	/* --- Internal Helper Methods --- */

	// Store reference to possibly-available ECMAScript 5 methods for later
	var nativeMap = Array.prototype.map,
		nativeIsArray = Array.isArray,
		toString = Object.prototype.toString;

	/**
	 * Tests whether supplied parameter is a string
	 * from underscore.js
	 */
	function isString(obj) {
		return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
	}

	/**
	 * Tests whether supplied parameter is a string
	 * from underscore.js, delegates to ECMA5's native Array.isArray
	 */
	function isArray(obj) {
		return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';
	}

	/**
	 * Tests whether supplied parameter is a true object
	 */
	function isObject(obj) {
		return toString.call(obj) === '[object Object]';
	}

	/**
	 * Extends an object with a defaults object, similar to underscore's _.defaults
	 *
	 * Used for abstracting parameter handling from API methods
	 */
	function defaults(object, defs) {
		var key;
		object = object || {};
		defs = defs || {};
		// Iterate over object non-prototype properties:
		for (key in defs) {
			if (defs.hasOwnProperty(key)) {
				// Replace values with defaults only if undefined (allow empty/zero values):
				if (object[key] == null) object[key] = defs[key];
			}
		}
		return object;
	}

	/**
	 * Implementation of `Array.map()` for iteration loops
	 *
	 * Returns a new Array as a result of calling `iterator` on each array value.
	 * Defers to native Array.map if available
	 */
	function map(obj, iterator, context) {
		var results = [], i, j;

		if (!obj) return results;

		// Use native .map method if it exists:
		if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);

		// Fallback for native .map:
		for (i = 0, j = obj.length; i < j; i++ ) {
			results[i] = iterator.call(context, obj[i], i, obj);
		}
		return results;
	}

	/**
	 * Check and normalise the value of precision (must be positive integer)
	 */
	function checkPrecision(val, base) {
		val = Math.round(Math.abs(val));
		return isNaN(val)? base : val;
	}

	/**
	 * Parses a format string or object and returns format obj for use in rendering
	 *
	 * `format` is either a string with the default (positive) format, or object
	 * containing `pos` (required), `neg` and `zero` values (or a function returning
	 * either a string or object)
	 *
	 * Either string or format.pos must contain "%v" (value) to be valid
	 */
	function checkCurrencyFormat(format) {
		var defaults = lib.settings.currency.format;

		// Allow function as format parameter (should return string or object):
		if ( typeof format === "function" ) format = format();

		// Format can be a string, in which case `value` ("%v") must be present:
		if ( isString( format ) && format.match("%v") ) {

			// Create and return positive, negative and zero formats:
			return {
				pos : format,
				neg : format.replace("-", "").replace("%v", "-%v"),
				zero : format
			};

		// If no format, or object is missing valid positive value, use defaults:
		} else if ( !format || !format.pos || !format.pos.match("%v") ) {

			// If defaults is a string, casts it to an object for faster checking next time:
			return ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = {
				pos : defaults,
				neg : defaults.replace("%v", "-%v"),
				zero : defaults
			};

		}
		// Otherwise, assume format was fine:
		return format;
	}

	/* --- API Methods --- */

	/**
	 * Takes a string/array of strings, removes all formatting/cruft and returns the raw float value
	 * alias: accounting.`parse(string)`
	 *
	 * Decimal must be included in the regular expression to match floats (default: "."), so if the number
	 * uses a non-standard decimal separator, provide it as the second argument.
	 *
	 * Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
	 *
	 * Doesn't throw any errors (`NaN`s become 0) but this may change in future
	 */
	var unformat = lib.unformat = lib.parse = function(number, decimal) {
		// Recursively unformat arrays:
		if (isArray(number)) {
			return map(number, function(val) {
				return unformat(val, decimal);
			});
		}

		// Fails silently (need decent errors):
		number = number || 0;

		// Default decimal point is "." but could be set to eg. "," in opts:
		decimal = decimal || ".";

		 // Build regex to strip out everything except digits, decimal point and minus sign:
		var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
			unformatted = parseFloat(
				("" + number)
				.replace(/\((.*)\)/, "-$1") // replace bracketed values with negatives
				.replace(regex, '')         // strip out any cruft
				.replace(decimal, '.')      // make sure decimal point is standard
			);

		// This will fail silently which may cause trouble, let's wait and see:
		return !isNaN(unformatted) ? unformatted : 0;
	};

	/**
	 * Implementation of toFixed() that treats floats more like decimals
	 *
	 * Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present
	 * problems for accounting- and finance-related software.
	 */
	var toFixed = lib.toFixed = function(value, precision) {
		precision = checkPrecision(precision, lib.settings.number.precision);
		var power = Math.pow(10, precision);

		// Multiply up by precision, round accurately, then divide and use native toFixed():
		return (Math.round(value * power) / power).toFixed(precision);
	};

	/**
	 * Format a number, with comma-separated thousands and custom precision/decimal places
	 *
	 * Localise by overriding the precision and thousand / decimal separators
	 * 2nd parameter `precision` can be an object matching `settings.number`
	 */
	var formatNumber = lib.formatNumber = function(number, precision, thousand, decimal) {
		// Resursively format arrays:
		if (isArray(number)) {
			return map(number, function(val) {
				return formatNumber(val, precision, thousand, decimal);
			});
		}

		// Clean up number:
		number = unformat(number);

		// Build options object from second param (if object) or all params, extending defaults:
		var opts = defaults(
				(isObject(precision) ? precision : {
					precision : precision,
					thousand : thousand,
					decimal : decimal
				}),
				lib.settings.number
			),

			// Clean up precision
			usePrecision = checkPrecision(opts.precision),

			// Do some calc:
			negative = number < 0 ? "-" : "",
			base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "",
			mod = base.length > 3 ? base.length % 3 : 0;

		// Format the number:
		return negative + (mod ? base.substr(0, mod) + opts.thousand : "") + base.substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1] : "");
	};

	/**
	 * Format a number into currency
	 *
	 * Usage: accounting.formatMoney(number, precision, symbol, thousandsSep, decimalSep, format)
	 * defaults: (0, 2, "$", ",", ".", "%s%v")
	 *
	 * Localise by overriding the symbol, precision, thousand / decimal separators and format
	 * Second param can be an object matching `settings.currency` which is the easiest way.
	 *
	 * To do: tidy up the parameters
	 */
	var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {
		// Resursively format arrays:
		if (isArray(number)) {
			return map(number, function(val){
				return formatMoney(val, symbol, precision, thousand, decimal, format);
			});
		}

		// Clean up number:
		number = unformat(number);

		// Build options object from second param (if object) or all params, extending defaults:
		var opts = defaults(
				(isObject(symbol) ? symbol : {
					symbol : symbol,
					precision : precision,
					thousand : thousand,
					decimal : decimal,
					format : format
				}),
				lib.settings.currency
			),

			// Check format (returns object with pos, neg and zero):
			formats = checkCurrencyFormat(opts.format),

			// Choose which format to use for this value:
			useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;

		// Return with currency symbol added:
		return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
	};

	/**
	 * Format a list of numbers into an accounting column, padding with whitespace
	 * to line up currency symbols, thousand separators and decimals places
	 *
	 * List should be an array of numbers
	 * Second parameter can be an object containing keys that match the params
	 *
	 * Returns array of accouting-formatted number strings of same length
	 *
	 * NB: `white-space:pre` CSS rule is required on the list container to prevent
	 * browsers from collapsing the whitespace in the output strings.
	 */
	lib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {
		if (!list) return [];

		// Build options object from second param (if object) or all params, extending defaults:
		var opts = defaults(
				(isObject(symbol) ? symbol : {
					symbol : symbol,
					precision : precision,
					thousand : thousand,
					decimal : decimal,
					format : format
				}),
				lib.settings.currency
			),

			// Check format (returns object with pos, neg and zero), only need pos for now:
			formats = checkCurrencyFormat(opts.format),

			// Whether to pad at start of string or after currency symbol:
			padAfterSymbol = formats.pos.indexOf("%s") < formats.pos.indexOf("%v") ? true : false,

			// Store value for the length of the longest string in the column:
			maxLength = 0,

			// Format the list according to options, store the length of the longest string:
			formatted = map(list, function(val, i) {
				if (isArray(val)) {
					// Recursively format columns if list is a multi-dimensional array:
					return lib.formatColumn(val, opts);
				} else {
					// Clean up the value
					val = unformat(val);

					// Choose which format to use for this value (pos, neg or zero):
					var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,

						// Format this value, push into formatted list and save the length:
						fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));

					if (fVal.length > maxLength) maxLength = fVal.length;
					return fVal;
				}
			});

		// Pad each number in the list and send back the column of numbers:
		return map(formatted, function(val, i) {
			// Only if this is a string (not a nested array, which would have already been padded):
			if (isString(val) && val.length < maxLength) {
				// Depending on symbol position, pad after symbol or at index 0:
				return padAfterSymbol ? val.replace(opts.symbol, opts.symbol+(new Array(maxLength - val.length + 1).join(" "))) : (new Array(maxLength - val.length + 1).join(" ")) + val;
			}
			return val;
		});
	};

	/* --- Module Definition --- */

	// Export accounting for CommonJS. If being loaded as an AMD module, define it as such.
	// Otherwise, just add `accounting` to the global object
	if (typeof module !== 'undefined' && module.exports) {
		module.exports = lib;
		lib.accounting = lib;
	} else if (typeof define === 'function' && define.amd) {
		// Return the library as an AMD module:
		define([], function() {
			return lib;
		});
	} else {
		// Use accounting.noConflict to restore `accounting` back to its original value.
		// Returns a reference to the library's `accounting` object;
		// e.g. `var numbers = accounting.noConflict();`
		lib.noConflict = (function(oldAccounting) {
			return function() {
				// Reset the value of the root's `accounting` variable:
				root.accounting = oldAccounting;
				// Delete the noConflict method:
				lib.noConflict = undefined;
				// Return reference to the library to re-assign it:
				return lib;
			};
		})(root.accounting);

		// Declare `fx` on the root (global/window) object:
		root['accounting'] = lib;
	}

	// Root will be `window` in browser or `global` on the server:
}(this));
<commit_msg>toFixed should attempt to unformat/parse number first to handle strings<commit_after>/*!
 * accounting.js javascript library v0.3-alpha
 * http://josscrowcroft.github.com/accounting.js/
 *
 * Copyright 2011 by Joss Crowcroft
 * Licensed under GPL v3 | http://www.gnu.org/licenses/gpl-3.0.txt
 */

(function(root, undefined) {

	/* --- Setup --- */

	// Create the local library object, to be exported or referenced globally later
	var lib = {};

	// Current version
	lib.version = '0.3-alpha';

	/* --- Exposed settings --- */

	// The library's settings configuration object. Contains default parameters for
	// currency and number formatting
	lib.settings = {
		currency: {
			symbol : "$",		// default currency symbol is '$'
			format : "%s%v",	// controls output: %s = symbol, %v = value (can be object, see docs)
			decimal : ".",		// decimal point separator
			thousand : ",",		// thousands separator
			precision : 2,		// decimal places
			grouping : 3		// digit grouping (not implemented yet)
		},
		number: {
			precision : 0,		// default precision on numbers is 0
			grouping : 3,		// digit grouping (not implemented yet)
			thousand : ",",
			decimal : "."
		}
	};

	/* --- Internal Helper Methods --- */

	// Store reference to possibly-available ECMAScript 5 methods for later
	var nativeMap = Array.prototype.map,
		nativeIsArray = Array.isArray,
		toString = Object.prototype.toString;

	/**
	 * Tests whether supplied parameter is a string
	 * from underscore.js
	 */
	function isString(obj) {
		return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
	}

	/**
	 * Tests whether supplied parameter is a string
	 * from underscore.js, delegates to ECMA5's native Array.isArray
	 */
	function isArray(obj) {
		return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';
	}

	/**
	 * Tests whether supplied parameter is a true object
	 */
	function isObject(obj) {
		return toString.call(obj) === '[object Object]';
	}

	/**
	 * Extends an object with a defaults object, similar to underscore's _.defaults
	 *
	 * Used for abstracting parameter handling from API methods
	 */
	function defaults(object, defs) {
		var key;
		object = object || {};
		defs = defs || {};
		// Iterate over object non-prototype properties:
		for (key in defs) {
			if (defs.hasOwnProperty(key)) {
				// Replace values with defaults only if undefined (allow empty/zero values):
				if (object[key] == null) object[key] = defs[key];
			}
		}
		return object;
	}

	/**
	 * Implementation of `Array.map()` for iteration loops
	 *
	 * Returns a new Array as a result of calling `iterator` on each array value.
	 * Defers to native Array.map if available
	 */
	function map(obj, iterator, context) {
		var results = [], i, j;

		if (!obj) return results;

		// Use native .map method if it exists:
		if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);

		// Fallback for native .map:
		for (i = 0, j = obj.length; i < j; i++ ) {
			results[i] = iterator.call(context, obj[i], i, obj);
		}
		return results;
	}

	/**
	 * Check and normalise the value of precision (must be positive integer)
	 */
	function checkPrecision(val, base) {
		val = Math.round(Math.abs(val));
		return isNaN(val)? base : val;
	}

	/**
	 * Parses a format string or object and returns format obj for use in rendering
	 *
	 * `format` is either a string with the default (positive) format, or object
	 * containing `pos` (required), `neg` and `zero` values (or a function returning
	 * either a string or object)
	 *
	 * Either string or format.pos must contain "%v" (value) to be valid
	 */
	function checkCurrencyFormat(format) {
		var defaults = lib.settings.currency.format;

		// Allow function as format parameter (should return string or object):
		if ( typeof format === "function" ) format = format();

		// Format can be a string, in which case `value` ("%v") must be present:
		if ( isString( format ) && format.match("%v") ) {

			// Create and return positive, negative and zero formats:
			return {
				pos : format,
				neg : format.replace("-", "").replace("%v", "-%v"),
				zero : format
			};

		// If no format, or object is missing valid positive value, use defaults:
		} else if ( !format || !format.pos || !format.pos.match("%v") ) {

			// If defaults is a string, casts it to an object for faster checking next time:
			return ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = {
				pos : defaults,
				neg : defaults.replace("%v", "-%v"),
				zero : defaults
			};

		}
		// Otherwise, assume format was fine:
		return format;
	}

	/* --- API Methods --- */

	/**
	 * Takes a string/array of strings, removes all formatting/cruft and returns the raw float value
	 * alias: accounting.`parse(string)`
	 *
	 * Decimal must be included in the regular expression to match floats (default: "."), so if the number
	 * uses a non-standard decimal separator, provide it as the second argument.
	 *
	 * Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
	 *
	 * Doesn't throw any errors (`NaN`s become 0) but this may change in future
	 */
	var unformat = lib.unformat = lib.parse = function(number, decimal) {
		// Recursively unformat arrays:
		if (isArray(number)) {
			return map(number, function(val) {
				return unformat(val, decimal);
			});
		}

		// Fails silently (need decent errors):
		number = number || 0;

		// Default decimal point is "." but could be set to eg. "," in opts:
		decimal = decimal || ".";

		 // Build regex to strip out everything except digits, decimal point and minus sign:
		var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
			unformatted = parseFloat(
				("" + number)
				.replace(/\((.*)\)/, "-$1") // replace bracketed values with negatives
				.replace(regex, '')         // strip out any cruft
				.replace(decimal, '.')      // make sure decimal point is standard
			);

		// This will fail silently which may cause trouble, let's wait and see:
		return !isNaN(unformatted) ? unformatted : 0;
	};

	/**
	 * Implementation of toFixed() that treats floats more like decimals
	 *
	 * Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present
	 * problems for accounting- and finance-related software.
	 */
	var toFixed = lib.toFixed = function(value, precision) {
		precision = checkPrecision(precision, lib.settings.number.precision);
		var power = Math.pow(10, precision);

		// Multiply up by precision, round accurately, then divide and use native toFixed():
		return (Math.round(accounting.unformat(value) * power) / power).toFixed(precision);
	};

	/**
	 * Format a number, with comma-separated thousands and custom precision/decimal places
	 *
	 * Localise by overriding the precision and thousand / decimal separators
	 * 2nd parameter `precision` can be an object matching `settings.number`
	 */
	var formatNumber = lib.formatNumber = function(number, precision, thousand, decimal) {
		// Resursively format arrays:
		if (isArray(number)) {
			return map(number, function(val) {
				return formatNumber(val, precision, thousand, decimal);
			});
		}

		// Clean up number:
		number = unformat(number);

		// Build options object from second param (if object) or all params, extending defaults:
		var opts = defaults(
				(isObject(precision) ? precision : {
					precision : precision,
					thousand : thousand,
					decimal : decimal
				}),
				lib.settings.number
			),

			// Clean up precision
			usePrecision = checkPrecision(opts.precision),

			// Do some calc:
			negative = number < 0 ? "-" : "",
			base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "",
			mod = base.length > 3 ? base.length % 3 : 0;

		// Format the number:
		return negative + (mod ? base.substr(0, mod) + opts.thousand : "") + base.substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1] : "");
	};

	/**
	 * Format a number into currency
	 *
	 * Usage: accounting.formatMoney(number, precision, symbol, thousandsSep, decimalSep, format)
	 * defaults: (0, 2, "$", ",", ".", "%s%v")
	 *
	 * Localise by overriding the symbol, precision, thousand / decimal separators and format
	 * Second param can be an object matching `settings.currency` which is the easiest way.
	 *
	 * To do: tidy up the parameters
	 */
	var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {
		// Resursively format arrays:
		if (isArray(number)) {
			return map(number, function(val){
				return formatMoney(val, symbol, precision, thousand, decimal, format);
			});
		}

		// Clean up number:
		number = unformat(number);

		// Build options object from second param (if object) or all params, extending defaults:
		var opts = defaults(
				(isObject(symbol) ? symbol : {
					symbol : symbol,
					precision : precision,
					thousand : thousand,
					decimal : decimal,
					format : format
				}),
				lib.settings.currency
			),

			// Check format (returns object with pos, neg and zero):
			formats = checkCurrencyFormat(opts.format),

			// Choose which format to use for this value:
			useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;

		// Return with currency symbol added:
		return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
	};

	/**
	 * Format a list of numbers into an accounting column, padding with whitespace
	 * to line up currency symbols, thousand separators and decimals places
	 *
	 * List should be an array of numbers
	 * Second parameter can be an object containing keys that match the params
	 *
	 * Returns array of accouting-formatted number strings of same length
	 *
	 * NB: `white-space:pre` CSS rule is required on the list container to prevent
	 * browsers from collapsing the whitespace in the output strings.
	 */
	lib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {
		if (!list) return [];

		// Build options object from second param (if object) or all params, extending defaults:
		var opts = defaults(
				(isObject(symbol) ? symbol : {
					symbol : symbol,
					precision : precision,
					thousand : thousand,
					decimal : decimal,
					format : format
				}),
				lib.settings.currency
			),

			// Check format (returns object with pos, neg and zero), only need pos for now:
			formats = checkCurrencyFormat(opts.format),

			// Whether to pad at start of string or after currency symbol:
			padAfterSymbol = formats.pos.indexOf("%s") < formats.pos.indexOf("%v") ? true : false,

			// Store value for the length of the longest string in the column:
			maxLength = 0,

			// Format the list according to options, store the length of the longest string:
			formatted = map(list, function(val, i) {
				if (isArray(val)) {
					// Recursively format columns if list is a multi-dimensional array:
					return lib.formatColumn(val, opts);
				} else {
					// Clean up the value
					val = unformat(val);

					// Choose which format to use for this value (pos, neg or zero):
					var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,

						// Format this value, push into formatted list and save the length:
						fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));

					if (fVal.length > maxLength) maxLength = fVal.length;
					return fVal;
				}
			});

		// Pad each number in the list and send back the column of numbers:
		return map(formatted, function(val, i) {
			// Only if this is a string (not a nested array, which would have already been padded):
			if (isString(val) && val.length < maxLength) {
				// Depending on symbol position, pad after symbol or at index 0:
				return padAfterSymbol ? val.replace(opts.symbol, opts.symbol+(new Array(maxLength - val.length + 1).join(" "))) : (new Array(maxLength - val.length + 1).join(" ")) + val;
			}
			return val;
		});
	};

	/* --- Module Definition --- */

	// Export accounting for CommonJS. If being loaded as an AMD module, define it as such.
	// Otherwise, just add `accounting` to the global object
	if (typeof module !== 'undefined' && module.exports) {
		module.exports = lib;
		lib.accounting = lib;
	} else if (typeof define === 'function' && define.amd) {
		// Return the library as an AMD module:
		define([], function() {
			return lib;
		});
	} else {
		// Use accounting.noConflict to restore `accounting` back to its original value.
		// Returns a reference to the library's `accounting` object;
		// e.g. `var numbers = accounting.noConflict();`
		lib.noConflict = (function(oldAccounting) {
			return function() {
				// Reset the value of the root's `accounting` variable:
				root.accounting = oldAccounting;
				// Delete the noConflict method:
				lib.noConflict = undefined;
				// Return reference to the library to re-assign it:
				return lib;
			};
		})(root.accounting);

		// Declare `fx` on the root (global/window) object:
		root['accounting'] = lib;
	}

	// Root will be `window` in browser or `global` on the server:
}(this));
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import update from 'immutability-helper'

import Popup from 'components/ConfigForm/General/Popup.js'
import InputsOutputsForm from 'components/ConfigForm/SectorModel/InputsOutputsForm.js'
import ParameterSelector from 'components/ConfigForm/SectorModel/ParameterSelector.js'
import PropertyList from 'components/ConfigForm/General/PropertyList.js'
import DeleteForm from 'components/ConfigForm/General/DeleteForm.js'
import { SaveButton, CancelButton } from 'components/ConfigForm/General/Buttons'

class SectorModelConfigForm extends Component {
    constructor(props) {
        super(props)

        this.handleChange = this.handleChange.bind(this)
        this.handleSave = this.handleSave.bind(this)
        this.handleCancel = this.handleCancel.bind(this)

        this.state = {
            selectedSectorModel: this.props.sectorModel,
            deletePopupIsOpen: false
        }

        this.closeDeletePopup = this.closeDeletePopup.bind(this)
        this.openDeletePopup = this.openDeletePopup.bind(this)
        this.handleDelete = this.handleDelete.bind(this)
    }

    handleChange(event) {
        const target = event.target
        const value = target.type === 'checkbox' ? target.checked : target.value
        const name = target.name

        this.setState({
            selectedSectorModel: update(this.state.selectedSectorModel, {[name]: {$set: value}})
        })
    }

    handleDelete(config) {

        const {deletePopupType, selectedSectorModel} = this.state

        switch(deletePopupType) {
        case 'inputs':
            for (let i = 0; i < selectedSectorModel.inputs.length; i++) {
                if (selectedSectorModel.inputs[i].name == config)
                    selectedSectorModel.inputs.splice(i, 1)
            }
            break

        case 'outputs':
            for (let i = 0; i < selectedSectorModel.outputs.length; i++) {
                if (selectedSectorModel.outputs[i].name == config)
                    selectedSectorModel.outputs.splice(i, 1)
            }
            break

        case 'parameters':
            for (let i = 0; i < selectedSectorModel.parameters.length; i++) {
                if (selectedSectorModel.parameters[i].name == config)
                    selectedSectorModel.parameters.splice(i, 1)
            }
            break
        }

        this.forceUpdate()
        this.closeDeletePopup()
    }

    handleSave() {
        this.props.saveSectorModel(this.state.selectedSectorModel)
    }

    handleCancel() {
        this.props.cancelSectorModel()
    }

    openDeletePopup(event) {

        let target_in_use_by = []

        switch(event.target.name) {
        case 'inputs' || 'parameters':
            this.props.sosModels.forEach(function(sos_model) {
                sos_model.dependencies.forEach(function(dependency) {
                    if (dependency.sink_model_input == event.target.value) {
                        target_in_use_by.push({
                            name: sos_model.name,
                            link: '/configure/sos-models/',
                            type: 'SosModel'
                        })
                    }
                })
            })
            break
        case 'outputs':
            this.props.sosModels.forEach(function(sos_model) {
                sos_model.dependencies.forEach(function(dependency) {
                    if (dependency.source_model_output == event.target.value) {
                        target_in_use_by.push({
                            name: sos_model.name,
                            link: '/configure/sos-models/',
                            type: 'SosModel'
                        })
                    }
                })
            })
            break
        }

        this.setState({
            deletePopupIsOpen: true,
            deletePopupConfigName: event.target.value,
            deletePopupType: event.target.name,
            deletePopupInUseBy: target_in_use_by
        })
    }

    closeDeletePopup() {
        this.setState({deletePopupIsOpen: false})
    }

    renderSectorModelConfigForm() {
        const {selectedSectorModel} = this.state

        return (

                <form>

General

                                Name

                                    <input id="sector_model_name" className="form-control" name="name" type="text" disabled="true" defaultValue={selectedSectorModel.name} onChange={this.handleChange}/>

                                Description

                                    <textarea id="sector_model_description" className="form-control" name="description" rows="5" defaultValue={selectedSectorModel.description} onChange={this.handleChange}/>

Environment

                                Class Name

                                    <input id="sector_model_classname" className="form-control" name="classname" type="text" defaultValue={selectedSectorModel.classname} onChange={this.handleChange}/>

                                Path

                                    <input id="sector_model_path" className="form-control" name="path" type="text" defaultValue={selectedSectorModel.path} onChange={this.handleChange}/>

Inputs

                            <PropertyList itemsName="inputs" items={selectedSectorModel.inputs} columns={{name: 'Name', spatial_resolution: 'Spatial Resolution', temporal_resolution: 'Temporal Resolution', units: 'Units'}} editButton={false} deleteButton={true} onDelete={this.openDeletePopup} />
                            <InputsOutputsForm items={selectedSectorModel.inputs} isInputs={true} onChange={this.handleChange}/>

Outputs

                            <PropertyList itemsName="outputs" items={selectedSectorModel.outputs} columns={{name: 'Name', spatial_resolution: 'Spatial Resolution', temporal_resolution: 'Temporal Resolution', units: 'Units'}} editButton={false} deleteButton={true} onDelete={this.openDeletePopup} />
                            <InputsOutputsForm items={selectedSectorModel.outputs} isOutputs={true} onChange={this.handleChange}/>

Parameters

                            <PropertyList itemsName="parameters" items={selectedSectorModel.parameters} columns={{name: 'Name', description: 'Description', default_value: 'Default Value', units: 'Units', absolute_range: 'Absolute Range', suggested_range: 'Suggested Range'}} editButton={false} deleteButton={true} onDelete={this.openDeletePopup} />
                            <ParameterSelector parameters={selectedSectorModel.parameters} onChange={this.handleChange}/>

                </form>

                <Popup name="popup_delete_form" onRequestOpen={this.state.deletePopupIsOpen}>
                    <DeleteForm config_name={this.state.deletePopupConfigName} config_type={this.state.deletePopupType} in_use_by={this.state.deletePopupInUseBy} submit={this.handleDelete} cancel={this.closeDeletePopup}/>
                </Popup>

                <SaveButton onClick={this.handleSave} />
                <CancelButton onClick={this.handleCancel} />

        )
    }

    renderDanger(message) {
        return (

                    {message}

                <CancelButton onClick={this.handleCancel} />

        )
    }

    render() {
        const {selectedSectorModel} = this.state

        if (selectedSectorModel.name == undefined) {
            return this.renderDanger('This Scenario Set does not exist.')
        } else {
            return this.renderSectorModelConfigForm()
        }
    }
}

SectorModelConfigForm.propTypes = {
    sosModels: PropTypes.array.isRequired,
    sectorModel: PropTypes.object.isRequired,
    saveSectorModel: PropTypes.func,
    cancelSectorModel: PropTypes.func
}

SectorModelConfigForm.defaultProps = {
    sosModels: [],
    sectorModel: {},
}

export default SectorModelConfigForm
<commit_msg>Add new Spec forms to SectorModelConfig<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import update from 'immutability-helper'

import Popup from 'components/ConfigForm/General/Popup.js'
import ParameterSelector from 'components/ConfigForm/SectorModel/ParameterSelector.js'
import SpecList from 'components/ConfigForm/General/SpecList.js'
import DeleteForm from 'components/ConfigForm/General/DeleteForm.js'
import { SaveButton, CancelButton } from 'components/ConfigForm/General/Buttons'

class SectorModelConfigForm extends Component {
    constructor(props) {
        super(props)

        this.handleChange = this.handleChange.bind(this)
        this.handleSave = this.handleSave.bind(this)
        this.handleCancel = this.handleCancel.bind(this)

        this.state = {
            selectedSectorModel: this.props.sectorModel,
            deletePopupIsOpen: false
        }

        this.closeDeletePopup = this.closeDeletePopup.bind(this)
        this.openDeletePopup = this.openDeletePopup.bind(this)
        this.handleDelete = this.handleDelete.bind(this)
    }

    handleChange(event) {
        const target = event.target
        const value = target.type === 'checkbox' ? target.checked : target.value
        const name = target.name

        this.setState({
            selectedSectorModel: update(this.state.selectedSectorModel, {[name]: {$set: value}})
        })
    }

    handleDelete(config) {

        const {deletePopupType, selectedSectorModel} = this.state

        switch(deletePopupType) {
        case 'inputs':
            for (let i = 0; i < selectedSectorModel.inputs.length; i++) {
                if (selectedSectorModel.inputs[i].name == config)
                    selectedSectorModel.inputs.splice(i, 1)
            }
            break

        case 'outputs':
            for (let i = 0; i < selectedSectorModel.outputs.length; i++) {
                if (selectedSectorModel.outputs[i].name == config)
                    selectedSectorModel.outputs.splice(i, 1)
            }
            break

        case 'parameters':
            for (let i = 0; i < selectedSectorModel.parameters.length; i++) {
                if (selectedSectorModel.parameters[i].name == config)
                    selectedSectorModel.parameters.splice(i, 1)
            }
            break
        }

        this.forceUpdate()
        this.closeDeletePopup()
    }

    handleSave() {
        this.props.saveSectorModel(this.state.selectedSectorModel)
    }

    handleCancel() {
        this.props.cancelSectorModel()
    }

    openDeletePopup(event) {

        let target_in_use_by = []

        switch(event.target.name) {
        case 'inputs' || 'parameters':
            this.props.sosModels.forEach(function(sos_model) {
                sos_model.dependencies.forEach(function(dependency) {
                    if (dependency.sink_model_input == event.target.value) {
                        target_in_use_by.push({
                            name: sos_model.name,
                            link: '/configure/sos-models/',
                            type: 'SosModel'
                        })
                    }
                })
            })
            break
        case 'outputs':
            this.props.sosModels.forEach(function(sos_model) {
                sos_model.dependencies.forEach(function(dependency) {
                    if (dependency.source_model_output == event.target.value) {
                        target_in_use_by.push({
                            name: sos_model.name,
                            link: '/configure/sos-models/',
                            type: 'SosModel'
                        })
                    }
                })
            })
            break
        }

        this.setState({
            deletePopupIsOpen: true,
            deletePopupConfigName: event.target.value,
            deletePopupType: event.target.name,
            deletePopupInUseBy: target_in_use_by
        })
    }

    closeDeletePopup() {
        this.setState({deletePopupIsOpen: false})
    }

    renderSectorModelConfigForm() {
        const {selectedSectorModel} = this.state

        return (

                <form>

General

                                Name

                                    <input id="sector_model_name" className="form-control" name="name" type="text" disabled="true" defaultValue={selectedSectorModel.name} onChange={this.handleChange}/>

                                Description

                                    <textarea id="sector_model_description" className="form-control" name="description" rows="5" defaultValue={selectedSectorModel.description} onChange={this.handleChange}/>

Environment

                                Class Name

                                    <input id="sector_model_classname" className="form-control" name="classname" type="text" defaultValue={selectedSectorModel.classname} onChange={this.handleChange}/>

                                Path

                                    <input id="sector_model_path" className="form-control" name="path" type="text" defaultValue={selectedSectorModel.path} onChange={this.handleChange}/>

Inputs

                            <SpecList name="input" specs={selectedSectorModel.inputs} dims={[{value: 'country', label: 'country'}, {value: 'lad', label: 'lad'}]} />

Outputs

                            <SpecList name="output" specs={selectedSectorModel.outputs} dims={[{value: 'country', label: 'country'}, {value: 'lad', label: 'lad'}]} />

Parameters

                            <SpecList name="parameter" specs={selectedSectorModel.parameters} dims={[{value: 'country', label: 'country'}, {value: 'lad', label: 'lad'}]} />

                </form>

                <Popup name="popup_delete_form" onRequestOpen={this.state.deletePopupIsOpen}>
                    <DeleteForm config_name={this.state.deletePopupConfigName} config_type={this.state.deletePopupType} in_use_by={this.state.deletePopupInUseBy} submit={this.handleDelete} cancel={this.closeDeletePopup}/>
                </Popup>

                <SaveButton onClick={this.handleSave} />
                <CancelButton onClick={this.handleCancel} />

        )
    }

    renderDanger(message) {
        return (

                    {message}

                <CancelButton onClick={this.handleCancel} />

        )
    }

    render() {
        const {selectedSectorModel} = this.state

        if (selectedSectorModel.name == undefined) {
            return this.renderDanger('This Scenario Set does not exist.')
        } else {
            return this.renderSectorModelConfigForm()
        }
    }
}

SectorModelConfigForm.propTypes = {
    sosModels: PropTypes.array.isRequired,
    sectorModel: PropTypes.object.isRequired,
    saveSectorModel: PropTypes.func,
    cancelSectorModel: PropTypes.func
}

SectorModelConfigForm.defaultProps = {
    sosModels: [],
    sectorModel: {},
}

export default SectorModelConfigForm
<|endoftext|>