<commit_before>import alt from "alt-instance";
import SettingsActions from "actions/SettingsActions";
import IntlActions from "actions/IntlActions";
import Immutable from "immutable";
import {merge} from "lodash";
import ls from "common/localStorage";
import { Apis } from "bitsharesjs-ws";
import { settingsAPIs } from "api/apiConfig";

const CORE_ASSET = "BTS"; // Setting this to BTS to prevent loading issues when used with BTS chain which is the most usual case currently

const STORAGE_KEY = "__graphene__";
let ss = new ls(STORAGE_KEY);

class SettingsStore {
    constructor() {
        this.exportPublicMethods({init: this.init.bind(this), getSetting: this.getSetting.bind(this)});

        this.bindListeners({
            onChangeSetting: SettingsActions.changeSetting,
            onChangeViewSetting: SettingsActions.changeViewSetting,
            onChangeMarketDirection: SettingsActions.changeMarketDirection,
            onAddStarMarket: SettingsActions.addStarMarket,
            onRemoveStarMarket: SettingsActions.removeStarMarket,
            onAddWS: SettingsActions.addWS,
            onRemoveWS: SettingsActions.removeWS,
            onHideAsset: SettingsActions.hideAsset,
            onClearSettings: SettingsActions.clearSettings,
            onSwitchLocale: IntlActions.switchLocale,
            onSetUserMarket: SettingsActions.setUserMarket,
            onUpdateLatencies: SettingsActions.updateLatencies
        });

        this.initDone = false;
        this.defaultSettings = Immutable.Map({
            locale: "en",
            apiServer: settingsAPIs.DEFAULT_WS_NODE,
            faucet_address: settingsAPIs.DEFAULT_FAUCET,
            unit: CORE_ASSET,
            showSettles: false,
            showAssetPercent: false,
            walletLockTimeout: 60 * 10,
            themes: "darkTheme",
            passwordLogin: true
        });

        // If you want a default value to be translated, add the translation to settings in locale-xx.js
        // and use an object {translate: key} in the defaults array
        let apiServer = settingsAPIs.WS_NODE_LIST;

        let defaults = {
            locale: [
                "en",
                "zh",
                "fr",
                "ko",
                "de",
                "es",
                "it",
                "tr",
                "ru"
            ],
            apiServer: [],
            unit: [
                CORE_ASSET,
                "USD",
                "CNY",
                "BTC",
                "EUR",
                "GBP"
            ],
            showSettles: [
                {translate: "yes"},
                {translate: "no"}
            ],
            showAssetPercent: [
                {translate: "yes"},
                {translate: "no"}
            ],
            themes: [
                "darkTheme",
                "lightTheme",
                "olDarkTheme"
            ],
            passwordLogin: [
                {translate: "cloud_login"},
                {translate: "local_wallet"}
            ]
            // confirmMarketOrder: [
            //     {translate: "confirm_yes"},
            //     {translate: "confirm_no"}
            // ]
        };

        this.settings = Immutable.Map(merge(this.defaultSettings.toJS(), ss.get("settings_v3")));

        let savedDefaults = ss.get("defaults_v1", {});
        this.defaults = merge({}, defaults, savedDefaults);

        (savedDefaults.apiServer || []).forEach(api => {
            let hasApi = false;
            if (typeof api === "string") {
                api = {url: api, location: null};
            }
            this.defaults.apiServer.forEach(server => {
                if (server.url === api.url) {
                    hasApi = true;
                }
            });

            if (!hasApi) {
                this.defaults.apiServer.push(api);
            }
        });

        if (!savedDefaults || (savedDefaults && (!savedDefaults.apiServer || !savedDefaults.apiServer.length))) {
            for (let i = apiServer.length - 1; i >= 0; i--) {
                let hasApi = false;
                this.defaults.apiServer.forEach(api => {
                    if (api.url === apiServer[i].url) {
                        hasApi = true;
                    }
                });
                if (!hasApi) {
                    this.defaults.apiServer.unshift(apiServer[i]);
                }
            }
        }

        this.viewSettings = Immutable.Map(ss.get("viewSettings_v1"));

        this.marketDirections = Immutable.Map(ss.get("marketDirections"));

        this.hiddenAssets = Immutable.List(ss.get("hiddenAssets", []));

        this.apiLatencies = ss.get("apiLatencies", {});

        this.mainnet_faucet = ss.get("mainnet_faucet", settingsAPIs.DEFAULT_FAUCET);
        this.testnet_faucet = ss.get("testnet_faucet", settingsAPIs.TESTNET_FAUCET);
    }

    init() {
        return new Promise((resolve) => {
            if (this.initDone) resolve();
            this.starredKey = this._getChainKey("markets");
            this.marketsKey = this._getChainKey("userMarkets");
            // Default markets setup
            let topMarkets = {
                markets_4018d784: [ // BTS MAIN NET
                    "OPEN.MKR", "BTS", "OPEN.ETH", "ICOO", "BTC", "OPEN.LISK", "BKT",
                    "OPEN.STEEM", "OPEN.GAME", "OCT", "USD", "CNY", "BTSR", "OBITS",
                    "OPEN.DGD", "EUR", "GOLD", "SILVER", "IOU.CNY", "OPEN.DASH",
                    "OPEN.USDT", "OPEN.EURT", "OPEN.BTC", "CADASTRAL", "BLOCKPAY", "BTWTY",
                    "OPEN.INCNT", "KAPITAL", "OPEN.MAID", "OPEN.SBD", "OPEN.GRC",
                    "YOYOW", "HERO", "RUBLE", "SMOKE", "STEALTH", "BRIDGE.BCO",
                    "BRIDGE.BTC", "KEXCOIN", "PPY", "OPEN.EOS", "OPEN.OMG"
                ],
                markets_39f5e2ed: [ // TESTNET
                    "PEG.FAKEUSD", "BTWTY"
                ]
            };

            let bases = {
                markets_4018d784: [ // BTS MAIN NET
                    "USD", "OPEN.BTC", "CNY", "BTS", "BTC"
                ],
                markets_39f5e2ed: [ // TESTNET
                    "TEST"
                ]
            };

            let coreAssets = {markets_4018d784: "BTS", markets_39f5e2ed: "TEST"};
            let coreAsset = coreAssets[this.starredKey] || "BTS";
            this.defaults.unit[0] = coreAsset;

            let chainBases = bases[this.starredKey] || bases.markets_4018d784;
            this.preferredBases = Immutable.List(chainBases);

            function addMarkets(target, base, markets) {
                markets.filter(a => {
                    return a !== base;
                }).forEach(market => {
                    target.push([`${market}_${base}`, {"quote": market,"base": base}]);
                });
            }

            let defaultMarkets = [];
            let chainMarkets = topMarkets[this.starredKey] || [];
            this.preferredBases.forEach(base => {
                addMarkets(defaultMarkets, base, chainMarkets);
            });

            this.defaultMarkets = Immutable.Map(defaultMarkets);
            this.starredMarkets = Immutable.Map(ss.get(this.starredKey, []));
            this.userMarkets = Immutable.Map(ss.get(this.marketsKey, {}));

            this.initDone = true;
            resolve();
        });
    }

    getSetting(setting) {
        return this.settings.get(setting);
    }

    onChangeSetting(payload) {
        this.settings = this.settings.set(
            payload.setting,
            payload.value
        );

        switch(payload.setting) {
            case "faucet_address":
                if (payload.value.indexOf("testnet") === -1) {
                    this.mainnet_faucet = payload.value;
                    ss.set("mainnet_faucet", payload.value);
                } else {
                    this.testnet_faucet = payload.value;
                    ss.set("testnet_faucet", payload.value);
                }
                break;

            case "apiServer":
                let faucetUrl = payload.value.indexOf("testnet") !== -1 ?
                    this.testnet_faucet : this.mainnet_faucet;
                this.settings = this.settings.set(
                    "faucet_address",
                    faucetUrl
                );
                break;

            case "walletLockTimeout":
                ss.set("lockTimeout", payload.value);
                break;

            default:
                break;
        }

        ss.set("settings_v3", this.settings.toJS());
    }

    onChangeViewSetting(payload) {
        for (let key in payload) {
            this.viewSettings = this.viewSettings.set(key, payload[key]);
        }

        ss.set("viewSettings_v1", this.viewSettings.toJS());
    }

    onChangeMarketDirection(payload) {
        for (let key in payload) {
            this.marketDirections = this.marketDirections.set(key, payload[key]);
        }
        ss.set("marketDirections", this.marketDirections.toJS());
    }

    onHideAsset(payload) {
        if (payload.id) {
            if (!payload.status) {
                this.hiddenAssets = this.hiddenAssets.delete(this.hiddenAssets.indexOf(payload.id));
            } else {
                this.hiddenAssets = this.hiddenAssets.push(payload.id);
            }
        }

        ss.set("hiddenAssets", this.hiddenAssets.toJS());
    }

    onAddStarMarket(market) {
        let marketID = market.quote + "_" + market.base;
        if (!this.starredMarkets.has(marketID)) {
            this.starredMarkets = this.starredMarkets.set(marketID, {quote: market.quote, base: market.base});

            ss.set(this.starredKey, this.starredMarkets.toJS());
        } else {
            return false;
        }
    }

    onSetUserMarket(payload) {
        let marketID = payload.quote + "_" + payload.base;
        if (payload.value) {
            this.userMarkets = this.userMarkets.set(marketID, {quote: payload.quote, base: payload.base});
        } else {
            this.userMarkets = this.userMarkets.delete(marketID);
        }
        ss.set(this.marketsKey, this.userMarkets.toJS());
    }

    onRemoveStarMarket(market) {
        let marketID = market.quote + "_" + market.base;

        this.starredMarkets = this.starredMarkets.delete(marketID);

        ss.set(this.starredKey, this.starredMarkets.toJS());
    }

    onAddWS(ws) {
        if (typeof ws === "string") {
            ws = {url: ws, location: null};
        }
        this.defaults.apiServer.push(ws);
        ss.set("defaults_v1", this.defaults);
    }

    onRemoveWS(index) {
        if (index !== 0) { // Prevent removing the default apiServer
            this.defaults.apiServer.splice(index, 1);
            ss.set("defaults_v1", this.defaults);
        }
    }

    onClearSettings(resolve) {
        ss.remove("settings_v3");
        this.settings = this.defaultSettings;

        ss.set("settings_v3", this.settings.toJS());

        if (resolve) {
            resolve();
        }
    }

    onSwitchLocale({locale}) {
        this.onChangeSetting({setting: "locale", value: locale});
    }

    _getChainKey(key) {
        const chainId = Apis.instance().chain_id;
        return key + (chainId ? `_${chainId.substr(0, 8)}` : "");
    }

    onUpdateLatencies(latencies) {
        ss.set("apiLatencies", latencies);
        this.apiLatencies = latencies;
    }
}

export default alt.createStore(SettingsStore, "SettingsStore");
<commit_msg>Fix locale loading after renaming cn to zh #654<commit_after>import alt from "alt-instance";
import SettingsActions from "actions/SettingsActions";
import IntlActions from "actions/IntlActions";
import Immutable from "immutable";
import {merge} from "lodash";
import ls from "common/localStorage";
import { Apis } from "bitsharesjs-ws";
import { settingsAPIs } from "api/apiConfig";

const CORE_ASSET = "BTS"; // Setting this to BTS to prevent loading issues when used with BTS chain which is the most usual case currently

const STORAGE_KEY = "__graphene__";
let ss = new ls(STORAGE_KEY);

class SettingsStore {
    constructor() {
        this.exportPublicMethods({init: this.init.bind(this), getSetting: this.getSetting.bind(this)});

        this.bindListeners({
            onChangeSetting: SettingsActions.changeSetting,
            onChangeViewSetting: SettingsActions.changeViewSetting,
            onChangeMarketDirection: SettingsActions.changeMarketDirection,
            onAddStarMarket: SettingsActions.addStarMarket,
            onRemoveStarMarket: SettingsActions.removeStarMarket,
            onAddWS: SettingsActions.addWS,
            onRemoveWS: SettingsActions.removeWS,
            onHideAsset: SettingsActions.hideAsset,
            onClearSettings: SettingsActions.clearSettings,
            onSwitchLocale: IntlActions.switchLocale,
            onSetUserMarket: SettingsActions.setUserMarket,
            onUpdateLatencies: SettingsActions.updateLatencies
        });

        this.initDone = false;
        this.defaultSettings = Immutable.Map({
            locale: "en",
            apiServer: settingsAPIs.DEFAULT_WS_NODE,
            faucet_address: settingsAPIs.DEFAULT_FAUCET,
            unit: CORE_ASSET,
            showSettles: false,
            showAssetPercent: false,
            walletLockTimeout: 60 * 10,
            themes: "darkTheme",
            passwordLogin: true
        });

        // If you want a default value to be translated, add the translation to settings in locale-xx.js
        // and use an object {translate: key} in the defaults array
        let apiServer = settingsAPIs.WS_NODE_LIST;

        let defaults = {
            locale: [
                "en",
                "zh",
                "fr",
                "ko",
                "de",
                "es",
                "it",
                "tr",
                "ru"
            ],
            apiServer: [],
            unit: [
                CORE_ASSET,
                "USD",
                "CNY",
                "BTC",
                "EUR",
                "GBP"
            ],
            showSettles: [
                {translate: "yes"},
                {translate: "no"}
            ],
            showAssetPercent: [
                {translate: "yes"},
                {translate: "no"}
            ],
            themes: [
                "darkTheme",
                "lightTheme",
                "olDarkTheme"
            ],
            passwordLogin: [
                {translate: "cloud_login"},
                {translate: "local_wallet"}
            ]
            // confirmMarketOrder: [
            //     {translate: "confirm_yes"},
            //     {translate: "confirm_no"}
            // ]
        };

        this.settings = Immutable.Map(merge(this.defaultSettings.toJS(), ss.get("settings_v3")));

        let savedDefaults = ss.get("defaults_v1", {});
        /* Fix for old clients after changing cn to zh */
        let cnIdx = savedDefaults.locale.findIndex(a => a === "cn");
        if (cnIdx !== -1) savedDefaults.locale[cnIdx] = "zh";

        this.defaults = merge({}, defaults, savedDefaults);

        (savedDefaults.apiServer || []).forEach(api => {
            let hasApi = false;
            if (typeof api === "string") {
                api = {url: api, location: null};
            }
            this.defaults.apiServer.forEach(server => {
                if (server.url === api.url) {
                    hasApi = true;
                }
            });

            if (!hasApi) {
                this.defaults.apiServer.push(api);
            }
        });

        if (!savedDefaults || (savedDefaults && (!savedDefaults.apiServer || !savedDefaults.apiServer.length))) {
            for (let i = apiServer.length - 1; i >= 0; i--) {
                let hasApi = false;
                this.defaults.apiServer.forEach(api => {
                    if (api.url === apiServer[i].url) {
                        hasApi = true;
                    }
                });
                if (!hasApi) {
                    this.defaults.apiServer.unshift(apiServer[i]);
                }
            }
        }

        this.viewSettings = Immutable.Map(ss.get("viewSettings_v1"));

        this.marketDirections = Immutable.Map(ss.get("marketDirections"));

        this.hiddenAssets = Immutable.List(ss.get("hiddenAssets", []));

        this.apiLatencies = ss.get("apiLatencies", {});

        this.mainnet_faucet = ss.get("mainnet_faucet", settingsAPIs.DEFAULT_FAUCET);
        this.testnet_faucet = ss.get("testnet_faucet", settingsAPIs.TESTNET_FAUCET);
    }

    init() {
        return new Promise((resolve) => {
            if (this.initDone) resolve();
            this.starredKey = this._getChainKey("markets");
            this.marketsKey = this._getChainKey("userMarkets");
            // Default markets setup
            let topMarkets = {
                markets_4018d784: [ // BTS MAIN NET
                    "OPEN.MKR", "BTS", "OPEN.ETH", "ICOO", "BTC", "OPEN.LISK", "BKT",
                    "OPEN.STEEM", "OPEN.GAME", "OCT", "USD", "CNY", "BTSR", "OBITS",
                    "OPEN.DGD", "EUR", "GOLD", "SILVER", "IOU.CNY", "OPEN.DASH",
                    "OPEN.USDT", "OPEN.EURT", "OPEN.BTC", "CADASTRAL", "BLOCKPAY", "BTWTY",
                    "OPEN.INCNT", "KAPITAL", "OPEN.MAID", "OPEN.SBD", "OPEN.GRC",
                    "YOYOW", "HERO", "RUBLE", "SMOKE", "STEALTH", "BRIDGE.BCO",
                    "BRIDGE.BTC", "KEXCOIN", "PPY", "OPEN.EOS", "OPEN.OMG"
                ],
                markets_39f5e2ed: [ // TESTNET
                    "PEG.FAKEUSD", "BTWTY"
                ]
            };

            let bases = {
                markets_4018d784: [ // BTS MAIN NET
                    "USD", "OPEN.BTC", "CNY", "BTS", "BTC"
                ],
                markets_39f5e2ed: [ // TESTNET
                    "TEST"
                ]
            };

            let coreAssets = {markets_4018d784: "BTS", markets_39f5e2ed: "TEST"};
            let coreAsset = coreAssets[this.starredKey] || "BTS";
            this.defaults.unit[0] = coreAsset;

            let chainBases = bases[this.starredKey] || bases.markets_4018d784;
            this.preferredBases = Immutable.List(chainBases);

            function addMarkets(target, base, markets) {
                markets.filter(a => {
                    return a !== base;
                }).forEach(market => {
                    target.push([`${market}_${base}`, {"quote": market,"base": base}]);
                });
            }

            let defaultMarkets = [];
            let chainMarkets = topMarkets[this.starredKey] || [];
            this.preferredBases.forEach(base => {
                addMarkets(defaultMarkets, base, chainMarkets);
            });

            this.defaultMarkets = Immutable.Map(defaultMarkets);
            this.starredMarkets = Immutable.Map(ss.get(this.starredKey, []));
            this.userMarkets = Immutable.Map(ss.get(this.marketsKey, {}));

            this.initDone = true;
            resolve();
        });
    }

    getSetting(setting) {
        return this.settings.get(setting);
    }

    onChangeSetting(payload) {
        this.settings = this.settings.set(
            payload.setting,
            payload.value
        );

        switch(payload.setting) {
            case "faucet_address":
                if (payload.value.indexOf("testnet") === -1) {
                    this.mainnet_faucet = payload.value;
                    ss.set("mainnet_faucet", payload.value);
                } else {
                    this.testnet_faucet = payload.value;
                    ss.set("testnet_faucet", payload.value);
                }
                break;

            case "apiServer":
                let faucetUrl = payload.value.indexOf("testnet") !== -1 ?
                    this.testnet_faucet : this.mainnet_faucet;
                this.settings = this.settings.set(
                    "faucet_address",
                    faucetUrl
                );
                break;

            case "walletLockTimeout":
                ss.set("lockTimeout", payload.value);
                break;

            default:
                break;
        }

        ss.set("settings_v3", this.settings.toJS());
    }

    onChangeViewSetting(payload) {
        for (let key in payload) {
            this.viewSettings = this.viewSettings.set(key, payload[key]);
        }

        ss.set("viewSettings_v1", this.viewSettings.toJS());
    }

    onChangeMarketDirection(payload) {
        for (let key in payload) {
            this.marketDirections = this.marketDirections.set(key, payload[key]);
        }
        ss.set("marketDirections", this.marketDirections.toJS());
    }

    onHideAsset(payload) {
        if (payload.id) {
            if (!payload.status) {
                this.hiddenAssets = this.hiddenAssets.delete(this.hiddenAssets.indexOf(payload.id));
            } else {
                this.hiddenAssets = this.hiddenAssets.push(payload.id);
            }
        }

        ss.set("hiddenAssets", this.hiddenAssets.toJS());
    }

    onAddStarMarket(market) {
        let marketID = market.quote + "_" + market.base;
        if (!this.starredMarkets.has(marketID)) {
            this.starredMarkets = this.starredMarkets.set(marketID, {quote: market.quote, base: market.base});

            ss.set(this.starredKey, this.starredMarkets.toJS());
        } else {
            return false;
        }
    }

    onSetUserMarket(payload) {
        let marketID = payload.quote + "_" + payload.base;
        if (payload.value) {
            this.userMarkets = this.userMarkets.set(marketID, {quote: payload.quote, base: payload.base});
        } else {
            this.userMarkets = this.userMarkets.delete(marketID);
        }
        ss.set(this.marketsKey, this.userMarkets.toJS());
    }

    onRemoveStarMarket(market) {
        let marketID = market.quote + "_" + market.base;

        this.starredMarkets = this.starredMarkets.delete(marketID);

        ss.set(this.starredKey, this.starredMarkets.toJS());
    }

    onAddWS(ws) {
        if (typeof ws === "string") {
            ws = {url: ws, location: null};
        }
        this.defaults.apiServer.push(ws);
        ss.set("defaults_v1", this.defaults);
    }

    onRemoveWS(index) {
        if (index !== 0) { // Prevent removing the default apiServer
            this.defaults.apiServer.splice(index, 1);
            ss.set("defaults_v1", this.defaults);
        }
    }

    onClearSettings(resolve) {
        ss.remove("settings_v3");
        this.settings = this.defaultSettings;

        ss.set("settings_v3", this.settings.toJS());

        if (resolve) {
            resolve();
        }
    }

    onSwitchLocale({locale}) {
        this.onChangeSetting({setting: "locale", value: locale});
    }

    _getChainKey(key) {
        const chainId = Apis.instance().chain_id;
        return key + (chainId ? `_${chainId.substr(0, 8)}` : "");
    }

    onUpdateLatencies(latencies) {
        ss.set("apiLatencies", latencies);
        this.apiLatencies = latencies;
    }
}

export default alt.createStore(SettingsStore, "SettingsStore");
<|endoftext|>


<commit_before>"use strict";
define(['i18n!./nls/locale','./modules/user/main'],
	function(locale, user){
	return openbiz.Application.extend({
		name:'cubi',
		modules:{
			user: user
		},
		init:function(){
			var view = new user.views.LoginView();
			return view.render().el;
		},
		locale: locale
	});
});<commit_msg>add dynamic setup URL path<commit_after>"use strict";
define(['i18n!./nls/locale','./modules/user/main'],
	function(locale, user){
	return openbiz.Application.extend({
		name:'cubi',
		appUrl:null,
		modules:{
			user: user
		},
		init:function(){
			var view = new user.views.LoginView();
			return view.render().el;
		},
		locale: locale
	});
});<|endoftext|>


<commit_before>#!/usr/bin/env node
//
// alaserver.js = Alasql Server
// Date: 25.11.2014
// (c) 2014, Andrey Gershun
//

var alasql = require('alasql');
var http = require('http');
var url = require('url');
var port = (process.argv[2] || 1337)|0;
if(!port) {
	throw new Error('Wrong port number '+process.argv[3]);
}

http.createServer(function (req, res) {
	var sql = decodeURI(url.parse(req.url).search).substr(1);
	var a = '';
	try {
		a = alasql(sql);
	} catch(err) {
		a = err.toString();
	};
  	res.writeHead(200, {'Content-Type': 'application/json'});
  	res.end(JSON.stringify(a));
}).listen(port, '127.0.0.1');

console.log('Server running at http://127.0.0.1:'+port+'/');
<commit_msg>alaserver.js CRLF -> LF<commit_after>#!/usr/bin/env node
//
// alaserver.js = Alasql Server
// Date: 25.11.2014
// (c) 2014, Andrey Gershun
//

var alasql = require('alasql');
var http = require('http');
var url = require('url');
var port = (process.argv[2] || 1337)|0;
if(!port) {
	throw new Error('Wrong port number '+process.argv[3]);
}

http.createServer(function (req, res) {
	var sql = decodeURI(url.parse(req.url).search).substr(1);
	var a = '';
	try {
		a = alasql(sql);
	} catch(err) {
		a = err.toString();
	};
  	res.writeHead(200, {'Content-Type': 'application/json'});
  	res.end(JSON.stringify(a));
}).listen(port, '127.0.0.1');

console.log('Server running at http://127.0.0.1:'+port+'/');
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { connect } from 'react-redux';

import { MODAL_KEYS, debounce } from '../utilities';

import { DataTablePageModal } from '../widgets/modals';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';
import { DataTablePageView, PageButton, PageInfo, SearchBar } from '../widgets';

import { getItemLayout } from './dataTableUtilities';

import { useRecordListener } from '../hooks';

import globalStyles from '../globalStyles';
import { buttonStrings } from '../localization';

/**
 * Renders a mSupply mobile page with a customer requisition loaded for editing
 *
 * State:
 * Uses a reducer to manage state with `backingData` being a realm results
 * of items to display. `data` is a plain JS array of realm objects. data is
 * hydrated from the `backingData` for displaying in the interface.
 * i.e: When filtering, data is populated from filtered items of `backingData`.
 *
 * dataState is a simple map of objects corresponding to a row being displayed,
 * holding the state of a given row. Each object has the shape :
 * { isSelected, isDisabled },
 *
 * @prop {Object} requisition The realm transaction object for this invoice.
 * @prop {Func}   runWithLoadingIndicator Callback for displaying a fullscreen spinner.
 * @prop {String} routeName The current route name for the top of the navigation stack.
 */
export const CustomerRequisition = ({
  runWithLoadingIndicator,
  data,
  dispatch,
  dataState,
  sortBy,
  isAscending,
  modalKey,
  pageObject,
  keyExtractor,
  modalValue,
  searchTerm,
  PageActions,
  columns,
  getPageInfoColumns,
}) => {
  // Listen for changes to this pages requisition. Refreshing data on side effects i.e. finalizing.
  useRecordListener(() => dispatch(PageActions.refreshData()), pageObject, 'Requisition');

  const { isFinalised, comment } = pageObject;

  // On click handlers
  const onCloseModal = () => dispatch(PageActions.closeModal());
  const onAddItem = value => dispatch(PageActions.addRequisitionItem(value));
  const onEditComment = value => dispatch(PageActions.editComment(value, 'Requisition'));
  const onFilterData = value => dispatch(PageActions.filterData(value));
  const onEditSuppliedQuantity = (newValue, rowKey, columnKey) =>
    dispatch(PageActions.editSuppliedQuantity(newValue, rowKey, columnKey));
  const onSetSuppliedToRequested = () =>
    runWithLoadingIndicator(() => dispatch(PageActions.setSuppliedToRequested()));
  const onSetSuppliedToSuggested = () =>
    runWithLoadingIndicator(() => dispatch(PageActions.setSuppliedToSuggested()));
  const onSortColumn = useCallback(
    debounce(columnKey => dispatch(PageActions.sortData(columnKey)), 250, true),
    []
  );
  const pageInfoColumns = useCallback(getPageInfoColumns(pageObject, dispatch, PageActions), [
    comment,
    isFinalised,
  ]);

  const getCallback = useCallback(colKey => {
    switch (colKey) {
      case 'suppliedQuantity':
        return onEditSuppliedQuantity;
      default:
        return null;
    }
  }, []);

  const getModalOnSelect = () => {
    switch (modalKey) {
      case MODAL_KEYS.SELECT_ITEM:
        return onAddItem;
      case MODAL_KEYS.REQUISITION_COMMENT_EDIT:
        return onEditComment;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowKey={rowKey}
          columns={columns}
          isFinalised={isFinalised}
          getCallback={getCallback}
          rowIndex={index}
        />
      );
    },
    [data, dataState]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        onPress={onSortColumn}
        isAscending={isAscending}
        sortBy={sortBy}
      />
    ),
    [sortBy, isAscending]
  );

  const {
    pageTopSectionContainer,
    pageTopLeftSectionContainer,
    pageTopRightSectionContainer,
  } = globalStyles;
  return (
    <DataTablePageView>
      <View style={pageTopSectionContainer}>
        <View style={pageTopLeftSectionContainer}>
          <PageInfo columns={pageInfoColumns} isEditingDisabled={isFinalised} />
          <SearchBar onChangeText={onFilterData} value={searchTerm} />
        </View>
        <View style={pageTopRightSectionContainer}>
          <PageButton
            style={globalStyles.topButton}
            text={buttonStrings.use_requested_quantities}
            onPress={onSetSuppliedToRequested}
            isDisabled={isFinalised}
          />
          <PageButton
            style={globalStyles.topButton}
            text={buttonStrings.use_suggested_quantities}
            onPress={onSetSuppliedToSuggested}
            isDisabled={isFinalised}
          />
        </View>
      </View>
      <DataTable
        data={data}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
        columns={columns}
      />
      <DataTablePageModal
        fullScreen={false}
        isOpen={!!modalKey}
        modalKey={modalKey}
        onClose={onCloseModal}
        onSelect={getModalOnSelect()}
        dispatch={dispatch}
        currentValue={modalValue}
      />
    </DataTablePageView>
  );
};

const mapStateToProps = state => {
  const { pages } = state;
  const { customerRequisition } = pages;
  return customerRequisition;
};

export const CustomerRequisitionPage = connect(mapStateToProps)(CustomerRequisition);

CustomerRequisition.defaultProps = {
  modalValue: null,
};

CustomerRequisition.propTypes = {
  dispatch: PropTypes.func.isRequired,
  data: PropTypes.array.isRequired,
  sortBy: PropTypes.string.isRequired,
  isAscending: PropTypes.bool.isRequired,
  searchTerm: PropTypes.string.isRequired,
  PageActions: PropTypes.object.isRequired,
  columns: PropTypes.array.isRequired,
  keyExtractor: PropTypes.func.isRequired,
  runWithLoadingIndicator: PropTypes.func.isRequired,
  dataState: PropTypes.object.isRequired,
  modalKey: PropTypes.string.isRequired,
  pageObject: PropTypes.object.isRequired,
  modalValue: PropTypes.any,
  getPageInfoColumns: PropTypes.func.isRequired,
};
<commit_msg>Add factor CustomerRequisitionPage to use mapDispatchToProps<commit_after>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { connect } from 'react-redux';

import { MODAL_KEYS } from '../utilities';

import { DataTablePageModal } from '../widgets/modals';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';
import { DataTablePageView, PageButton, PageInfo, SearchBar } from '../widgets';
import { ROUTES } from '../navigation/constants';
import { getItemLayout, getPageDispatchers, PageActions } from './dataTableUtilities';

import { useRecordListener } from '../hooks';

import globalStyles from '../globalStyles';
import { buttonStrings } from '../localization';

/**
 * Renders a mSupply mobile page with a customer requisition loaded for editing
 *
 * State:
 * Uses a reducer to manage state with `backingData` being a realm results
 * of items to display. `data` is a plain JS array of realm objects. data is
 * hydrated from the `backingData` for displaying in the interface.
 * i.e: When filtering, data is populated from filtered items of `backingData`.
 *
 * dataState is a simple map of objects corresponding to a row being displayed,
 * holding the state of a given row. Each object has the shape :
 * { isSelected, isDisabled },
 */
export const CustomerRequisition = ({
  runWithLoadingIndicator,
  data,
  dispatch,
  dataState,
  sortBy,
  isAscending,
  modalKey,
  pageObject,
  keyExtractor,
  modalValue,
  searchTerm,
  columns,
  getPageInfoColumns,
  refreshData,
  onEditComment,
  onFilterData,
  onCloseModal,
  onSortColumn,
  onEditSuppliedQuantity,
}) => {
  // Listen for changes to this pages requisition. Refreshing data on side effects i.e. finalizing.
  useRecordListener(refreshData, pageObject, 'Requisition');

  const { isFinalised, comment } = pageObject;

  const onSetSuppliedToRequested = () =>
    runWithLoadingIndicator(() => dispatch(PageActions.setSuppliedToRequested()));
  const onSetSuppliedToSuggested = () =>
    runWithLoadingIndicator(() => dispatch(PageActions.setSuppliedToSuggested()));

  const pageInfoColumns = useCallback(getPageInfoColumns(pageObject, dispatch, PageActions), [
    comment,
    isFinalised,
  ]);

  const getCallback = useCallback(colKey => {
    switch (colKey) {
      case 'suppliedQuantity':
        return onEditSuppliedQuantity;
      default:
        return null;
    }
  }, []);

  const getModalOnSelect = () => {
    switch (modalKey) {
      case MODAL_KEYS.REQUISITION_COMMENT_EDIT:
        return onEditComment;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowKey={rowKey}
          columns={columns}
          isFinalised={isFinalised}
          getCallback={getCallback}
          rowIndex={index}
        />
      );
    },
    [data, dataState]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        onPress={onSortColumn}
        isAscending={isAscending}
        sortBy={sortBy}
      />
    ),
    [sortBy, isAscending]
  );

  const {
    pageTopSectionContainer,
    pageTopLeftSectionContainer,
    pageTopRightSectionContainer,
  } = globalStyles;
  return (
    <DataTablePageView>
      <View style={pageTopSectionContainer}>
        <View style={pageTopLeftSectionContainer}>
          <PageInfo columns={pageInfoColumns} isEditingDisabled={isFinalised} />
          <SearchBar onChangeText={onFilterData} value={searchTerm} />
        </View>
        <View style={pageTopRightSectionContainer}>
          <PageButton
            style={globalStyles.topButton}
            text={buttonStrings.use_requested_quantities}
            onPress={onSetSuppliedToRequested}
            isDisabled={isFinalised}
          />
          <PageButton
            style={globalStyles.topButton}
            text={buttonStrings.use_suggested_quantities}
            onPress={onSetSuppliedToSuggested}
            isDisabled={isFinalised}
          />
        </View>
      </View>
      <DataTable
        data={data}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
        columns={columns}
      />
      <DataTablePageModal
        fullScreen={false}
        isOpen={!!modalKey}
        modalKey={modalKey}
        onClose={onCloseModal}
        onSelect={getModalOnSelect()}
        dispatch={dispatch}
        currentValue={modalValue}
      />
    </DataTablePageView>
  );
};

const mapDispatchToProps = (dispatch, ownProps) =>
  getPageDispatchers(dispatch, ownProps, 'Requisition', ROUTES.CUSTOMER_REQUISITION);

const mapStateToProps = state => {
  const { pages } = state;
  const { customerRequisition } = pages;
  return customerRequisition;
};

export const CustomerRequisitionPage = connect(
  mapStateToProps,
  mapDispatchToProps
)(CustomerRequisition);

CustomerRequisition.defaultProps = {
  modalValue: null,
};

CustomerRequisition.propTypes = {
  dispatch: PropTypes.func.isRequired,
  data: PropTypes.array.isRequired,
  sortBy: PropTypes.string.isRequired,
  isAscending: PropTypes.bool.isRequired,
  searchTerm: PropTypes.string.isRequired,
  columns: PropTypes.array.isRequired,
  keyExtractor: PropTypes.func.isRequired,
  runWithLoadingIndicator: PropTypes.func.isRequired,
  dataState: PropTypes.object.isRequired,
  modalKey: PropTypes.string.isRequired,
  pageObject: PropTypes.object.isRequired,
  modalValue: PropTypes.any,
  getPageInfoColumns: PropTypes.func.isRequired,
  refreshData: PropTypes.func.isRequired,
  onEditComment: PropTypes.func.isRequired,
  onFilterData: PropTypes.func.isRequired,
  onCloseModal: PropTypes.func.isRequired,
  onSortColumn: PropTypes.func.isRequired,
  onEditSuppliedQuantity: PropTypes.func.isRequired,
};
<|endoftext|>


<commit_before>var styles = {
      centeredOnlyHorizontal: {
        left: "50%",
        transform: "translate(-50%, -50%)",
        marginTop: "50px",
        marginBottom: "10%",
        position: "absolute"
      },
      fab: {
        margin: 0,
        top: 'auto',
        right: 20,
        bottom: 20,
        left: 'auto',
        position: 'fixed',
      }
    };

export default styles;<commit_msg>added zindex to button<commit_after>var styles = {
      centeredOnlyHorizontal: {
        left: "50%",
        transform: "translate(-50%, -50%)",
        marginTop: "50px",
        marginBottom: "10%",
        position: "absolute"
      },
      fab: {
        margin: 0,
        top: 'auto',
        right: 20,
        bottom: 20,
        left: 'auto',
        position: 'fixed',
        zIndex: 999
      }
    };

export default styles;<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
const JoynrException = require("../exceptions/JoynrException");
const SharedWebSocket = require("../messaging/websocket/SharedWebSocket");
const WebSocketMessagingSkeleton = require("../messaging/websocket/WebSocketMessagingSkeleton");
const WebSocketMessagingStubFactory = require("../messaging/websocket/WebSocketMessagingStubFactory");
const WebSocketMulticastAddressCalculator = require("../messaging/websocket/WebSocketMulticastAddressCalculator");
const MessagingStubFactory = require("../messaging/MessagingStubFactory");
const WebSocketAddress = require("../../generated/joynr/system/RoutingTypes/WebSocketAddress");
const WebSocketClientAddress = require("../../generated/joynr/system/RoutingTypes/WebSocketClientAddress");
const InProcessMessagingStubFactory = require("../messaging/inprocess/InProcessMessagingStubFactory");
const InProcessAddress = require("../messaging/inprocess/InProcessAddress");
const InProcessSkeleton = require("../util/InProcessSkeleton");
const MessagingQos = require("../messaging/MessagingQos");
const DiscoveryQos = require("../proxy/DiscoveryQos");
const DiscoveryProxy = require("../../generated/joynr/system/DiscoveryProxy");
const RoutingProxy = require("../../generated/joynr/system/RoutingProxy");
const DiscoveryScope = require("../../generated/joynr/types/DiscoveryScope");
const DiscoveryEntryWithMetaInfo = require("../../generated/joynr/types/DiscoveryEntryWithMetaInfo");
const UtilInternal = require("../util/UtilInternal");
const uuid = require("uuid/v4");
const loggingManager = require("../system/LoggingManager");
const defaultWebSocketSettings = require("./settings/defaultWebSocketSettings");
const defaultLibjoynrSettings = require("./settings/defaultLibjoynrSettings");
const JoynrMessage = require("../../joynr/messaging/JoynrMessage");
const JoynrRuntime = require("./JoynrRuntime");

const JoynrStates = {
    SHUTDOWN: "shut down",
    STARTING: "starting",
    STARTED: "started",
    SHUTTINGDOWN: "shutting down"
};

const log = loggingManager.getLogger("joynr.start.WebSocketLibjoynrRuntime");

/**
 * The WebSocketLibjoynrRuntime is the version of the libjoynr-js runtime that communicates with
 * a cluster controller via a WebSocket. The cluster controller is the WebSocket Server, and the
 * libjoynr connects to it with a single websocket for all communication.
 *
 * @name WebSocketLibjoynrRuntime
 * @constructor
 * @param {Object} provisioning
 */
class WebSocketLibjoynrRuntime extends JoynrRuntime {
    constructor() {
        super();
        this._signingCallback = this._signingCallback.bind(this);
        this._bufferedOwnerId = null;
        this._webSocketMessagingSkeleton = null;
    }

    _signingCallback() {
        return this._bufferedOwnerId;
    }

    /**
     * Starts up the libjoynr instance
     *
     * @name WebSocketLibjoynrRuntime#start
     * @function
     * @returns {Object} an A+ promise object, reporting when libjoynr startup is
     *          completed or has failed
     * @throws {Error}
     *             if libjoynr is not in SHUTDOWN state
     */
    async start(provisioning) {
        super.start(provisioning);

        if (UtilInternal.checkNullUndefined(provisioning.ccAddress)) {
            throw new Error("ccAddress not set in provisioning.ccAddress");
        }

        const keychain = provisioning.keychain;

        if (keychain) {
            if (UtilInternal.checkNullUndefined(keychain.tlsCert)) {
                throw new Error("tlsCert not set in keychain.tlsCert");
            }
            if (UtilInternal.checkNullUndefined(keychain.tlsKey)) {
                throw new Error("tlsKey not set in keychain.tlsKey");
            }
            if (UtilInternal.checkNullUndefined(keychain.tlsCa)) {
                throw new Error("tlsCa not set in keychain.tlsCa");
            }
            if (UtilInternal.checkNullUndefined(keychain.ownerId)) {
                throw new Error("ownerId not set in keychain.ownerId");
            }

            this._bufferedOwnerId = Buffer.from(keychain.ownerId);
            JoynrMessage.setSigningCallback(this._signingCallback);

            keychain.checkServerIdentity = function(server) {
                if (provisioning.ccAddress.host === server) {
                    return undefined;
                } else {
                    throw new Error(
                        `message from unknown host: ${server} on accepted host is cc: ${provisioning.ccAddress.host}.`
                    );
                }
            };
        }

        const initialRoutingTable = {};
        let untypedCapabilities = this._provisioning.capabilities || [];
        const defaultCapabilities = defaultLibjoynrSettings.capabilities || [];

        untypedCapabilities = untypedCapabilities.concat(defaultCapabilities);

        const ccAddress = new WebSocketAddress({
            protocol: provisioning.ccAddress.protocol || defaultWebSocketSettings.protocol,
            host: provisioning.ccAddress.host,
            port: provisioning.ccAddress.port,
            path: provisioning.ccAddress.path || defaultWebSocketSettings.path
        });

        const typedCapabilities = [];
        for (let i = 0; i < untypedCapabilities.length; i++) {
            const capability = new DiscoveryEntryWithMetaInfo(untypedCapabilities[i]);
            initialRoutingTable[capability.participantId] = ccAddress;
            typedCapabilities.push(capability);
        }

        const localAddress = new WebSocketClientAddress({
            id: uuid()
        });

        this._sharedWebSocket = new SharedWebSocket({
            remoteAddress: ccAddress,
            localAddress,
            provisioning: provisioning.websocket || {},
            keychain
        });

        this._webSocketMessagingSkeleton = new WebSocketMessagingSkeleton({
            sharedWebSocket: this._sharedWebSocket,
            mainTransport: true
        });

        const messagingStubFactories = {};
        messagingStubFactories[InProcessAddress._typeName] = new InProcessMessagingStubFactory();
        messagingStubFactories[WebSocketAddress._typeName] = new WebSocketMessagingStubFactory({
            address: ccAddress,
            sharedWebSocket: this._sharedWebSocket
        });

        const messagingStubFactory = new MessagingStubFactory({
            messagingStubFactories
        });

        const messageRouterSettings = {
            initialRoutingTable,
            joynrInstanceId: uuid(),
            messagingStubFactory,
            multicastAddressCalculator: new WebSocketMulticastAddressCalculator({
                globalAddress: ccAddress
            }),
            parentMessageRouterAddress: ccAddress,
            incomingAddress: localAddress
        };

        this._messagingSkeletons[WebSocketAddress._typeName] = this._webSocketMessagingSkeleton;

        await super._initializePersistency(provisioning);
        super._initializeComponents(provisioning, messageRouterSettings, typedCapabilities);

        this._webSocketMessagingSkeleton.registerListener(this._messageRouter.route);

        const internalMessagingQos = new MessagingQos(provisioning.internalMessagingQos);

        const discovery = this._discovery;
        function buildDiscoveryProxyOnSuccess(newDiscoveryProxy) {
            discovery.setSkeleton(
                new InProcessSkeleton({
                    lookup: function lookup(domains, interfaceName, discoveryQos) {
                        return newDiscoveryProxy
                            .lookup({
                                domains,
                                interfaceName,
                                discoveryQos
                            })
                            .then(opArgs => {
                                return opArgs.result;
                            });
                    },
                    add: function add(discoveryEntry, awaitGlobalRegistration) {
                        return newDiscoveryProxy.add({
                            discoveryEntry,
                            awaitGlobalRegistration
                        });
                    },
                    remove: function remove(participantId) {
                        return newDiscoveryProxy.remove({
                            participantId
                        });
                    }
                })
            );
            return;
        }

        function buildDiscoveryProxyOnError(error) {
            throw new Error(`Failed to create discovery proxy: ${error}`);
        }

        function buildRoutingProxyOnError(error) {
            throw new Error(
                `Failed to create routing proxy: ${error}${
                    error instanceof JoynrException ? ` ${error.detailMessage}` : ""
                }`
            );
        }

        return this.proxyBuilder
            .build(RoutingProxy, {
                domain: "io.joynr",
                messagingQos: internalMessagingQos,
                discoveryQos: new DiscoveryQos({
                    discoveryScope: DiscoveryScope.LOCAL_ONLY
                }),
                staticArbitration: true
            })
            .then(newRoutingProxy => {
                return this._messageRouter.setRoutingProxy(newRoutingProxy);
            })
            .catch(buildRoutingProxyOnError)
            .then(() => {
                return this.proxyBuilder.build(DiscoveryProxy, {
                    domain: "io.joynr",
                    messagingQos: internalMessagingQos,
                    discoveryQos: new DiscoveryQos({
                        discoveryScope: DiscoveryScope.LOCAL_ONLY
                    }),
                    staticArbitration: true
                });
            })
            .then(buildDiscoveryProxyOnSuccess)
            .catch(buildDiscoveryProxyOnError)
            .then(() => {
                this._joynrState = JoynrStates.STARTED;
                this._publicationManager.restore();
                log.debug("joynr web socket initialized");
            })
            .catch(async error => {
                log.error(`error starting up joynr: ${error}`);

                await this.shutdown();
                throw error;
            });
    }

    /**
     *  Sends subscriptionStop messages for all active subscriptions.
     *
     *  @param timeout {number} optional timeout defaulting to 0 = no timeout
     *  @returns {Promise}
     *  - resolved after all SubscriptionStop messages are sent.
     *  - rejected in case of any issues or timeout occurs.
     */
    terminateAllSubscriptions(timeout = 0) {
        this._sharedWebSocket.enableShutdownMode();
        return super.terminateSubscriptions(timeout);
    }

    /**
     * Shuts down libjoynr
     * @param settings.clearSubscriptionsTimeoutMs {number} time in ms till clearSubscriptionsPromise will be rejected
     *  if it's not resolved yet
     * @param settings.clearSubscriptionsEnabled {boolean} clear all subscriptions before shutting down.
     *  Set this to false in process.exit handler as this is not synchronous.
     *
     * @returns {Promise}
     * - resolved after successful shutdown
     * - rejected in case of any issues
     */
    async shutdown(settings) {
        if (this._sharedWebSocket) {
            this._sharedWebSocket.enableShutdownMode();
        }

        await super.shutdown(settings);

        if (this._webSocketMessagingSkeleton !== null) {
            this._webSocketMessagingSkeleton.shutdown();
        }
    }
}

module.exports = WebSocketLibjoynrRuntime;
<commit_msg>[JS] Fixed typo in WebSocketLibjoynrRuntime<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
const JoynrException = require("../exceptions/JoynrException");
const SharedWebSocket = require("../messaging/websocket/SharedWebSocket");
const WebSocketMessagingSkeleton = require("../messaging/websocket/WebSocketMessagingSkeleton");
const WebSocketMessagingStubFactory = require("../messaging/websocket/WebSocketMessagingStubFactory");
const WebSocketMulticastAddressCalculator = require("../messaging/websocket/WebSocketMulticastAddressCalculator");
const MessagingStubFactory = require("../messaging/MessagingStubFactory");
const WebSocketAddress = require("../../generated/joynr/system/RoutingTypes/WebSocketAddress");
const WebSocketClientAddress = require("../../generated/joynr/system/RoutingTypes/WebSocketClientAddress");
const InProcessMessagingStubFactory = require("../messaging/inprocess/InProcessMessagingStubFactory");
const InProcessAddress = require("../messaging/inprocess/InProcessAddress");
const InProcessSkeleton = require("../util/InProcessSkeleton");
const MessagingQos = require("../messaging/MessagingQos");
const DiscoveryQos = require("../proxy/DiscoveryQos");
const DiscoveryProxy = require("../../generated/joynr/system/DiscoveryProxy");
const RoutingProxy = require("../../generated/joynr/system/RoutingProxy");
const DiscoveryScope = require("../../generated/joynr/types/DiscoveryScope");
const DiscoveryEntryWithMetaInfo = require("../../generated/joynr/types/DiscoveryEntryWithMetaInfo");
const UtilInternal = require("../util/UtilInternal");
const uuid = require("uuid/v4");
const loggingManager = require("../system/LoggingManager");
const defaultWebSocketSettings = require("./settings/defaultWebSocketSettings");
const defaultLibjoynrSettings = require("./settings/defaultLibjoynrSettings");
const JoynrMessage = require("../../joynr/messaging/JoynrMessage");
const JoynrRuntime = require("./JoynrRuntime");

const JoynrStates = {
    SHUTDOWN: "shut down",
    STARTING: "starting",
    STARTED: "started",
    SHUTTINGDOWN: "shutting down"
};

const log = loggingManager.getLogger("joynr.start.WebSocketLibjoynrRuntime");

/**
 * The WebSocketLibjoynrRuntime is the version of the libjoynr-js runtime that communicates with
 * a cluster controller via a WebSocket. The cluster controller is the WebSocket Server, and the
 * libjoynr connects to it with a single websocket for all communication.
 *
 * @name WebSocketLibjoynrRuntime
 * @constructor
 * @param {Object} provisioning
 */
class WebSocketLibjoynrRuntime extends JoynrRuntime {
    constructor() {
        super();
        this._signingCallback = this._signingCallback.bind(this);
        this._bufferedOwnerId = null;
        this._webSocketMessagingSkeleton = null;
    }

    _signingCallback() {
        return this._bufferedOwnerId;
    }

    /**
     * Starts up the libjoynr instance
     *
     * @name WebSocketLibjoynrRuntime#start
     * @function
     * @returns {Object} an A+ promise object, reporting when libjoynr startup is
     *          completed or has failed
     * @throws {Error}
     *             if libjoynr is not in SHUTDOWN state
     */
    async start(provisioning) {
        super.start(provisioning);

        if (UtilInternal.checkNullUndefined(provisioning.ccAddress)) {
            throw new Error("ccAddress not set in provisioning.ccAddress");
        }

        const keychain = provisioning.keychain;

        if (keychain) {
            if (UtilInternal.checkNullUndefined(keychain.tlsCert)) {
                throw new Error("tlsCert not set in keychain.tlsCert");
            }
            if (UtilInternal.checkNullUndefined(keychain.tlsKey)) {
                throw new Error("tlsKey not set in keychain.tlsKey");
            }
            if (UtilInternal.checkNullUndefined(keychain.tlsCa)) {
                throw new Error("tlsCa not set in keychain.tlsCa");
            }
            if (UtilInternal.checkNullUndefined(keychain.ownerId)) {
                throw new Error("ownerId not set in keychain.ownerId");
            }

            this._bufferedOwnerId = Buffer.from(keychain.ownerId);
            JoynrMessage.setSigningCallback(this._signingCallback);

            keychain.checkServerIdentity = function(server) {
                if (provisioning.ccAddress.host === server) {
                    return undefined;
                } else {
                    throw new Error(
                        `message from unknown host: ${server} on accepted host is cc: ${provisioning.ccAddress.host}.`
                    );
                }
            };
        }

        const initialRoutingTable = {};
        let untypedCapabilities = this._provisioning.capabilities || [];
        const defaultCapabilities = defaultLibjoynrSettings.capabilities || [];

        untypedCapabilities = untypedCapabilities.concat(defaultCapabilities);

        const ccAddress = new WebSocketAddress({
            protocol: provisioning.ccAddress.protocol || defaultWebSocketSettings.protocol,
            host: provisioning.ccAddress.host,
            port: provisioning.ccAddress.port,
            path: provisioning.ccAddress.path || defaultWebSocketSettings.path
        });

        const typedCapabilities = [];
        for (let i = 0; i < untypedCapabilities.length; i++) {
            const capability = new DiscoveryEntryWithMetaInfo(untypedCapabilities[i]);
            initialRoutingTable[capability.participantId] = ccAddress;
            typedCapabilities.push(capability);
        }

        const localAddress = new WebSocketClientAddress({
            id: uuid()
        });

        this._sharedWebSocket = new SharedWebSocket({
            remoteAddress: ccAddress,
            localAddress,
            provisioning: provisioning.websocket || {},
            keychain
        });

        this._webSocketMessagingSkeleton = new WebSocketMessagingSkeleton({
            sharedWebSocket: this._sharedWebSocket,
            mainTransport: true
        });

        const messagingStubFactories = {};
        messagingStubFactories[InProcessAddress._typeName] = new InProcessMessagingStubFactory();
        messagingStubFactories[WebSocketAddress._typeName] = new WebSocketMessagingStubFactory({
            address: ccAddress,
            sharedWebSocket: this._sharedWebSocket
        });

        const messagingStubFactory = new MessagingStubFactory({
            messagingStubFactories
        });

        const messageRouterSettings = {
            initialRoutingTable,
            joynrInstanceId: uuid(),
            messagingStubFactory,
            multicastAddressCalculator: new WebSocketMulticastAddressCalculator({
                globalAddress: ccAddress
            }),
            parentMessageRouterAddress: ccAddress,
            incomingAddress: localAddress
        };

        this._messagingSkeletons[WebSocketAddress._typeName] = this._webSocketMessagingSkeleton;

        await super._initializePersistency(provisioning);
        super._initializeComponents(provisioning, messageRouterSettings, typedCapabilities);

        this._webSocketMessagingSkeleton.registerListener(this._messageRouter.route);

        const internalMessagingQos = new MessagingQos(provisioning.internalMessagingQos);

        const discovery = this._discovery;
        function buildDiscoveryProxyOnSuccess(newDiscoveryProxy) {
            discovery.setSkeleton(
                new InProcessSkeleton({
                    lookup: function lookup(domains, interfaceName, discoveryQos) {
                        return newDiscoveryProxy
                            .lookup({
                                domains,
                                interfaceName,
                                discoveryQos
                            })
                            .then(opArgs => {
                                return opArgs.result;
                            });
                    },
                    add: function add(discoveryEntry, awaitGlobalRegistration) {
                        return newDiscoveryProxy.add({
                            discoveryEntry,
                            awaitGlobalRegistration
                        });
                    },
                    remove: function remove(participantId) {
                        return newDiscoveryProxy.remove({
                            participantId
                        });
                    }
                })
            );
            return;
        }

        function buildDiscoveryProxyOnError(error) {
            throw new Error(`Failed to create discovery proxy: ${error}`);
        }

        function buildRoutingProxyOnError(error) {
            throw new Error(
                `Failed to create routing proxy: ${error}${
                    error instanceof JoynrException ? ` ${error.detailMessage}` : ""
                }`
            );
        }

        return this.proxyBuilder
            .build(RoutingProxy, {
                domain: "io.joynr",
                messagingQos: internalMessagingQos,
                discoveryQos: new DiscoveryQos({
                    discoveryScope: DiscoveryScope.LOCAL_ONLY
                }),
                staticArbitration: true
            })
            .then(newRoutingProxy => {
                return this._messageRouter.setRoutingProxy(newRoutingProxy);
            })
            .catch(buildRoutingProxyOnError)
            .then(() => {
                return this.proxyBuilder.build(DiscoveryProxy, {
                    domain: "io.joynr",
                    messagingQos: internalMessagingQos,
                    discoveryQos: new DiscoveryQos({
                        discoveryScope: DiscoveryScope.LOCAL_ONLY
                    }),
                    staticArbitration: true
                });
            })
            .then(buildDiscoveryProxyOnSuccess)
            .catch(buildDiscoveryProxyOnError)
            .then(() => {
                this._joynrState = JoynrStates.STARTED;
                this._publicationManager.restore();
                log.debug("joynr web socket initialized");
            })
            .catch(async error => {
                log.error(`error starting up joynr: ${error}`);

                await this.shutdown();
                throw error;
            });
    }

    /**
     *  Sends subscriptionStop messages for all active subscriptions.
     *
     *  @param timeout {number} optional timeout defaulting to 0 = no timeout
     *  @returns {Promise}
     *  - resolved after all SubscriptionStop messages are sent.
     *  - rejected in case of any issues or timeout occurs.
     */
    terminateAllSubscriptions(timeout = 0) {
        this._sharedWebSocket.enableShutdownMode();
        return super.terminateAllSubscriptions(timeout);
    }

    /**
     * Shuts down libjoynr
     * @param settings.clearSubscriptionsTimeoutMs {number} time in ms till clearSubscriptionsPromise will be rejected
     *  if it's not resolved yet
     * @param settings.clearSubscriptionsEnabled {boolean} clear all subscriptions before shutting down.
     *  Set this to false in process.exit handler as this is not synchronous.
     *
     * @returns {Promise}
     * - resolved after successful shutdown
     * - rejected in case of any issues
     */
    async shutdown(settings) {
        if (this._sharedWebSocket) {
            this._sharedWebSocket.enableShutdownMode();
        }

        await super.shutdown(settings);

        if (this._webSocketMessagingSkeleton !== null) {
            this._webSocketMessagingSkeleton.shutdown();
        }
    }
}

module.exports = WebSocketLibjoynrRuntime;
<|endoftext|>


<commit_before>import Palette from '../../core/palette.js';
export default class LinePalette extends Palette {
  constructor(SL, config) {
    super(SL, config);
    this.id = 'Lines';
  }
  get paletteType() {
    return 'Lines';
  }
  get paletteItems() {
    if (this.config && this.config.lines) {
      return this.config.lines;
    }
    return super.paletteItems;
  }

  createLine(from, to, lineDef) {
    let line = this.SL.Paper.generatePaperItem({Source: this, Type: 'Line', Line: lineDef}, paper.Path.Line, from.point, to.point);
    this.SL.Paper.Item.addCustomMethod(line, 'refresh', this.refreshItem, this);
    if (lineDef && lineDef.style) {
      this.SL.Paper.applyStyle(line, lineDef.style);
    }
    return line;
  }
  refreshItem(item, args) {
    console.log('[LinePalette]->refreshItem =>', item);
    // @TODO: draw Line label
  }

  getImagePath(item) {
    var width = (this.config.preview && this.config.preview.width ) || 50;
    var height = (this.config.preview && this.config.preview.height ) || 25;
    var linePreviewCanvas = $(`<canvas width="${width}" height="${height}"></canvas>`);
    var linePreview = linePreviewCanvas[0].getContext('2d');
    if (item.style) {
      if (item.style.strokeColor) {
        linePreview.strokeStyle = item.style.strokeColor;
      }
      if (item.style.strokeWidth) {
        linePreview.lineWidth = item.style.strokeWidth;
      }
      if (item.style.dashArray) {
        linePreview.setLineDash(item.style.dashArray);
      }
    }
    linePreview.beginPath();
    linePreview.moveTo(0, height/2.0);
    linePreview.lineTo(width, height/2.0);
    linePreview.stroke();
    return linePreviewCanvas[0].toDataURL('image/png');
  }

  generateDOMItem(item) {
    let itemName = (item.name || item.id);
    let lineButton = $('');
    lineButton.addClass('sl-palette-button');
    lineButton.addClass('sl-line-button');
    lineButton.data('Line', item);
    lineButton.data('Palette', this);
    lineButton.attr('alt', itemName);
    lineButton.attr('title', itemName);
    lineButton.click((event) => {
      let target = $(event.currentTarget);
      let line = target.data('Line');
      let palette = target.data('Palette');
      this.SL.Tools.Belt['CreateLine'].loadLine(line, palette);
    });
    let lineContent = $('

');
    lineContent.addClass('sl-palette-content sl-palette-img');
    lineContent.addClass('sl-line-content sl-line-img');
    lineContent.attr('draggable', false);
    let imagePath = this.getImagePath(item);
    if (imagePath) {
      lineContent.append($(`<img src="${imagePath}" draggable="false" />`));
    }
    lineButton.append(lineContent);
    if (this.config.showNames) {
      lineContent = $(`<div>${itemName}</div>`);
      lineContent.addClass('sl-palette-content sl-palette-item-name');
      lineContent.addClass('sl-line-content sl-line-name');
      lineButton.append(lineContent);
    }
    return lineButton;
  }
}
<commit_msg>Draws the Line Label - not positioned correctly yet<commit_after>import Palette from '../../core/palette.js';
export default class LinePalette extends Palette {
  constructor(SL, config) {
    super(SL, config);
    this.id = 'Lines';
    this.PaperItems = [];
    this.initialized = true;
    this.configure();
  }
  get paletteType() {
    return 'Lines';
  }
  get paletteItems() {
    if (this.config && this.config.lines) {
      return this.config.lines;
    }
    return super.paletteItems;
  }
  configure(config) {
    config = super.configure(config);
    this.initEventHandlers();
    this.registerSnappers();
    return config;
  }
  reset() {
    if (!this.initialized) {
      return;
    }
    super.reset();
    this.unregisterSnappers();
    this.resetEventHandlers();
  }

  getImagePath(item) {
    var width = (this.config.preview && this.config.preview.width ) || 50;
    var height = (this.config.preview && this.config.preview.height ) || 25;
    var linePreviewCanvas = $(`<canvas width="${width}" height="${height}"></canvas>`);
    var linePreview = linePreviewCanvas[0].getContext('2d');
    if (item.style) {
      if (item.style.strokeColor) {
        linePreview.strokeStyle = item.style.strokeColor;
      }
      if (item.style.strokeWidth) {
        linePreview.lineWidth = item.style.strokeWidth;
      }
      if (item.style.dashArray) {
        linePreview.setLineDash(item.style.dashArray);
      }
    }
    linePreview.beginPath();
    linePreview.moveTo(0, height/2.0);
    linePreview.lineTo(width, height/2.0);
    linePreview.stroke();
    return linePreviewCanvas[0].toDataURL('image/png');
  }
  generateDOMItem(item) {
    let itemName = (item.name || item.id);
    let lineButton = $('');
    lineButton.addClass('sl-palette-button');
    lineButton.addClass('sl-line-button');
    lineButton.data('Line', item);
    lineButton.data('Palette', this);
    lineButton.attr('alt', itemName);
    lineButton.attr('title', itemName);
    lineButton.click((event) => {
      let target = $(event.currentTarget);
      let line = target.data('Line');
      let palette = target.data('Palette');
      this.SL.Tools.Belt['CreateLine'].loadLine(line, palette);
    });
    let lineContent = $('

');
    lineContent.addClass('sl-palette-content sl-palette-img');
    lineContent.addClass('sl-line-content sl-line-img');
    lineContent.attr('draggable', false);
    let imagePath = this.getImagePath(item);
    if (imagePath) {
      lineContent.append($(`<img src="${imagePath}" draggable="false" />`));
    }
    lineButton.append(lineContent);
    if (this.config.showNames) {
      lineContent = $(`<div>${itemName}</div>`);
      lineContent.addClass('sl-palette-content sl-palette-item-name');
      lineContent.addClass('sl-line-content sl-line-name');
      lineButton.append(lineContent);
    }
    return lineButton;
  }
  createLine(from, to, lineDef) {
    let line = this.SL.Paper.generatePaperItem({Source: this, Type: 'Line', Line: lineDef}, paper.Path.Line, from.point, to.point);
    this.SL.Paper.Item.addCustomMethod(line, 'refresh', this.refreshItem, this);
    if (lineDef && lineDef.style) {
      this.SL.Paper.applyStyle(line, lineDef.style);
    }
    return line;
  }
  refreshItem(item, args) {
    if (item && item.data && item.data.label) {
      this.assertItemLabel(item);
      this.refreshItemLabel(item);
    }
    else if (item.data.paperLabel) {
      this.removeItemLabel(item);
    }
  }

  assertItemLabel(item) {
    if (item && item.data && !item.data.paperLabel) {
      let labelData = {
        Source: this,
        Type: 'LineLabel',
        Class: 'ContentAddon',
        Layer: ((item.data && item.data.Layer) ? item.data.Layer : 'CONTENT'),
        ParentItem: item,
        position: {x: 0, y: 0} // @TODO: is labelData.position needed?
      };
      // @TODO: configure Line.Label (position, font)
      item.data.paperLabel = this.SL.Paper.generatePaperItem(labelData, paper.PointText, item.bounds.center);
      item.data.paperLabel.fillColor = '#000000';
      item.data.paperLabel.fontSize = '12pt';
      this.SL.Paper.Item.addChild(item, item.data.paperLabel);
    }
  }
  refreshItemLabel(item) {
    if (item && item.data && item.data.paperLabel) {
      item.data.paperLabel.content = item.data.label;
      item.data.paperLabel.insertAbove(item);
      let Geo = this.SL.Utils.get('Geo');
      if (Geo && item.data.paperLabel.data) {
        let rotation = item.rotation;
        let rotationPoint = item.bounds.center;
        if (rotation) {
          item.rotate(-rotation, rotationPoint);
        }
        let position = ((item.data.labelPosition == 'bottom') ? -1.0 : 1.0);
        let distance = (item.data.labelDistance || 0.5);
        var space = (item.data.labelSpace || 15);
        let normal = Geo.Normalize.pointAtLineDistance(item, distance, true);
        normal.vector = normal.vector.rotate(-90);
        normal.vector.length = space*position;
        let point = normal.point.add(normal.vector);
        if (rotation) {
          item.rotate(rotation, rotationPoint);
          point = point.rotate(rotation, rotationPoint);
        }
        item.data.paperLabel.position.set(point);
      }
    }
  }
  removeItemLabel(item) {
    if (item && item.data && item.data.paperLabel) {
      this.SL.Paper.Item.removeChild(item, item.data.paperLabel);
      this.SL.Paper.destroyPaperItem(item.data.paperLabel);
      item.data.paperLabel = undefined;
      delete item.data.paperLabel;
    }
  }

  lineSelected(line) {
    if (line && line.data && line.data.Type == 'Line') {
      if (line.data.paperLabel) {
        line.data.paperLabel.insertAbove(line);
      }
    }
  }
  lineUnselected(line) {
    if (line && line.data && line.data.Type == 'Line') {
      if (line.data.paperLabel) {
        line.data.paperLabel.insertAbove(line);
      }
    }
  }
  snapItem(item, config={}) {
    if (item && item.data && item.data.Type == 'Line') {
      this.SL.Paper.Item.callCustomMethod(item, 'refresh');
    }
    return item;
  }
  snapPoint(point, config={}) {
    if (config.context == 'line-point' && config.segment && config.segment.path) {
      this.SL.Paper.Item.callCustomMethod(config.segment.path, 'refresh');
    }
  }

  initEventHandlers() {
    if (!this.initialized) {
      return;
    }
    if (!this.eventHandlers) {
      this.eventHandlers = {};
    }
    let ItemFilter = {Type: 'Line'};
    if (!this.eventHandlers.ItemSelected) {
      this.eventHandlers.ItemSelected = this.SL.Paper.on('SelectionItemSelected', ItemFilter, (args, item) => {
        if (!item && args && args.item && this.SL.Paper.Item.passesFilter(args.item, ItemFilter)) {
          item = args.item;
        }
        if (item && this.SL.Paper.Item.passesFilter(item, ItemFilter)) {
          this.lineSelected(item);
        }
      }, 'Line.Selected');
    }
    if (!this.eventHandlers.ItemUnselected) {
      this.eventHandlers.ItemUnselected = this.SL.Paper.on('SelectionItemUnselected', ItemFilter, (args, item) => {
        if (args.items) {
          args.items.forEach((item) => {
            if (item && this.SL.Paper.Item.passesFilter(item, ItemFilter)) {
              this.lineUnselected(item);
            }
          });
        }
        else if (item && this.SL.Paper.Item.passesFilter(item, ItemFilter)) {
          this.lineUnselected(item);
        }
      }, 'Line.Unselected');
    }
    if (!this.eventHandlers.ItemDestroyed) {
      this.eventHandlers.ItemDestroyed = this.SL.Paper.on('Destroy', ItemFilter, (args, item) => {
        this.removeItemLabel(item);
      }, 'Item.Destroyed');
    }
  }
  resetEventHandlers() {
    if (!this.initialized || !this.eventHandlers) {
      return;
    }
    if (this.eventHandlers.ItemSelected) {
      this.SL.Paper.off('SelectionItemSelected', this.eventHandlers.ItemSelected.id);
      delete this.eventHandlers.ItemSelected;
      this.eventHandlers.ItemSelected = undefined;
    }
    if (this.eventHandlers.ItemUnselected) {
      this.SL.Paper.off('SelectionItemUnselected', this.eventHandlers.ItemUnselected.id);
      delete this.eventHandlers.ItemUnselected;
      this.eventHandlers.ItemUnselected = undefined;
    }
    if (this.eventHandlers.ItemDestroyed) {
      this.SL.Paper.off('Destroy', this.eventHandlers.ItemDestroyed.id);
      delete this.eventHandlers.ItemDestroyed;
      this.eventHandlers.ItemDestroyed = undefined;
    }
  }
  registerSnappers() {
    let Snap = this.SL.Utils.get('Snap');
    if (Snap) {
      if (!this.Snappers) {
        this.Snappers = {};
      }
      this.Snappers.item = Snap.addSnapper('item', {
        priority: 1000,
        callback: (item, config) => {
          return this.snapItem(item, config);
        }
      });
      this.Snappers.point = Snap.addSnapper('point', {
        priority: 1000,
        callback: (point, config) => {
          return this.snapPoint(point, config);
        }
      });
    }
  }
  unregisterSnappers() {
    let Snap = this.SL.Utils.get('Snap');
    if (!Snap || !this.Snappers) {
      return;
    }
    if (this.Snappers.item) {
      Snap.dropSnapper('item', this.Snappers.item.id);
      this.Snappers.item = undefined;
    }
    if (this.Snappers.point) {
      Snap.dropSnapper('point', this.Snappers.point.id);
      this.Snappers.point = undefined;
    }
  }
}
<|endoftext|>


<commit_before>define([
    'promise',
    'kb_common/html',
    'kb_common/observed',
    'kb_widget/widgetSet'
], function (Promise, html, observed, fWidgetSet) {
    'use strict';

    function widget(config) {
        var mount, container, runtime = config.runtime,
            widgetSet = fWidgetSet.make({ runtime: runtime }),
            viewState = observed.make();

        function renderPanel() {
            return new Promise(function (resolve) {
                // View stat is a local state machine for this view.
                var div = html.tag('div'),
                    panel = div({ class: 'kbase-view kbase-dashboard-view container-fluid', 'data-kbase-view': 'social' }, [
                        div({ class: 'row' }, [
                            div({ class: 'col-sm-12' }, [
                                div({
                                    id: widgetSet.addWidget('dashboardNarratives', {
                                        viewState: viewState
                                    })
                                }),
                                div({
                                    id: widgetSet.addWidget('dashboardNarratorials', {
                                        viewState: viewState
                                    })
                                }),
                                div({
                                    id: widgetSet.addWidget('dashboardSharedNarratives', {
                                        viewState: viewState
                                    })
                                }),
                                div({
                                    id: widgetSet.addWidget('dashboardPublicNarratives', {
                                        viewState: viewState
                                    })
                                }),
                                div({
                                    id: widgetSet.addWidget('dashboardMetrics', {
                                        viewState: viewState
                                    })
                                }),
                                div({
                                    id: widgetSet.addWidget('dashboardCollaborators', {
                                        viewState: viewState
                                    })
                                })
                            ])
                        ])
                    ]);
                resolve({
                    title: 'Your Dashboard',
                    content: panel
                });
            });
        }

        // API
        function attach(node) {
            return Promise.try(function () {
                mount = node;
                container = document.createElement('div');
                mount.appendChild(container);
                return renderPanel()
                    .then(function (rendered) {
                        container.innerHTML = rendered.content;
                        runtime.send('ui', 'setTitle', rendered.title);
                        // create widgets.
                        return widgetSet.init();
                    })
                    .then(function () {
                        return widgetSet.attach(container);
                    });
            });
        }

        function start(params) {
            return widgetSet.start(params);
        }

        function run(params) {
            return widgetSet.run(params);
        }

        function stop() {
            return widgetSet.stop();
        }

        function detach() {
            return widgetSet.detach();
        }
        return {
            attach: attach,
            start: start,
            run: run,
            stop: stop,
            detach: detach
        };
    }

    return {
        make: function (config) {
            return widget(config);
        }
    };
});
<commit_msg>Remove div layer to enable integration with ui layout<commit_after>define([
    'promise',
    'kb_common/html',
    'kb_common/observed',
    'kb_widget/widgetSet'
], function (Promise, html, observed, fWidgetSet) {
    'use strict';

    function widget(config) {
        var mount, container, runtime = config.runtime,
            widgetSet = fWidgetSet.make({ runtime: runtime }),
            viewState = observed.make();

        function renderPanel() {
            return new Promise(function (resolve) {
                // View stat is a local state machine for this view.
                var div = html.tag('div'),
                    panel = div(
                        div({ class: 'kbase-view kbase-dashboard-view container-fluid', 'data-kbase-view': 'social' }, [
                            div({ class: 'row' }, [
                                div({ class: 'col-sm-12' }, [
                                    div({
                                        id: widgetSet.addWidget('dashboardNarratives', {
                                            viewState: viewState
                                        })
                                    }),
                                    div({
                                        id: widgetSet.addWidget('dashboardNarratorials', {
                                            viewState: viewState
                                        })
                                    }),
                                    div({
                                        id: widgetSet.addWidget('dashboardSharedNarratives', {
                                            viewState: viewState
                                        })
                                    }),
                                    div({
                                        id: widgetSet.addWidget('dashboardPublicNarratives', {
                                            viewState: viewState
                                        })
                                    }),
                                    div({
                                        id: widgetSet.addWidget('dashboardMetrics', {
                                            viewState: viewState
                                        })
                                    }),
                                    div({
                                        id: widgetSet.addWidget('dashboardCollaborators', {
                                            viewState: viewState
                                        })
                                    })
                                ])
                            ])
                        ]));
                resolve({
                    title: 'Your Dashboard',
                    content: panel
                });
            });
        }

        // API
        function attach(node) {
            return Promise.try(function () {
                mount = node;
                container = document.createElement('div');
                mount.appendChild(container);
                return renderPanel()
                    .then(function (rendered) {
                        container.innerHTML = rendered.content;
                        runtime.send('ui', 'setTitle', rendered.title);
                        // create widgets.
                        return widgetSet.init();
                    })
                    .then(function () {
                        return widgetSet.attach(container);
                    });
            });
        }

        function start(params) {
            return widgetSet.start(params);
        }

        function run(params) {
            return widgetSet.run(params);
        }

        function stop() {
            return widgetSet.stop();
        }

        function detach() {
            return widgetSet.detach();
        }
        return {
            attach: attach,
            start: start,
            run: run,
            stop: stop,
            detach: detach
        };
    }

    return {
        make: function (config) {
            return widget(config);
        }
    };
});<|endoftext|>


<commit_before>(function() {

  /**
   * contains information about the table, not the data itself
   */
  cdb.open.PublicCartoDBTableMetadata = cdb.admin.CartoDBTableMetadata.extend({

    data: function() {
      var self = this;
      if(this._data === undefined) {
        this._data = new cdb.admin.CartoDBTableData(null, {
          table: this
        });

        this._data.fetch = function() { self._data.trigger('reset'); self._data.trigger('dataLoaded'); };
      }
      if(this.sqlView) {
        return this.sqlView;
      }
      return this._data;
    },
  });

})();
<commit_msg>fix failing request inherited from private table<commit_after>(function() {

  /**
   * contains information about the table, not the data itself
   */
  cdb.open.PublicCartoDBTableMetadata = cdb.admin.CartoDBTableMetadata.extend({

    fetch: function() {
      this.trigger('sync');
      //nothing to fetch here
    },
    data: function() {
      var self = this;
      if(this._data === undefined) {
        this._data = new cdb.admin.CartoDBTableData(null, {
          table: this
        });

        this._data.fetch = function() { self._data.trigger('reset'); self._data.trigger('dataLoaded'); };
      }
      if(this.sqlView) {
        return this.sqlView;
      }
      return this._data;
    },
  });

})();
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var cdb = require('cartodb-deep-insights.js');
var _ = require('underscore');

module.exports = Backbone.Collection.extend({

  model: cdb.core.Model,

  constructor: function(models, options) {
    options = _.extend(options || {}, { silent: false });
    Backbone.Collection.prototype.constructor.call(this, models, options);
  },

  initialize: function() {
    this.bind('reset', this._setSelected, this);
    this.bind('change:selected', this._onSelectedChange, this);
    this._setSelected();
  },

  getSelected: function() {
    return this.find(function(model) {
      return model.get('selected');
    });
  },

  _setSelected: function() {
    var isSelected = this.getSelected();

    if (!isSelected && this.size() > 0) {
      this.at(0).set('selected', true)
    }
  },

  _onSelectedChange: function(itemModel, isSelected) {
    if (!isSelected) {
      return;
    }

    this.each(function(model) {
      if (model.cid !== itemModel.cid) {
        model.set('selected', false);
      }
    }, this);
  }
});
<commit_msg>Simplifies compare<commit_after>var Backbone = require('backbone');
var cdb = require('cartodb-deep-insights.js');
var _ = require('underscore');

module.exports = Backbone.Collection.extend({

  model: cdb.core.Model,

  constructor: function(models, options) {
    options = _.extend(options || {}, { silent: false });
    Backbone.Collection.prototype.constructor.call(this, models, options);
  },

  initialize: function() {
    this.bind('reset', this._setSelected, this);
    this.bind('change:selected', this._onSelectedChange, this);
    this._setSelected();
  },

  getSelected: function() {
    return this.find(function(model) {
      return model.get('selected');
    });
  },

  _setSelected: function() {
    var isSelected = this.getSelected();

    if (!isSelected && this.size() > 0) {
      this.at(0).set('selected', true)
    }
  },

  _onSelectedChange: function(itemModel, isSelected) {
    if (!isSelected) {
      return;
    }

    this.each(function(model) {
      if (model !== itemModel) {
        model.set('selected', false);
      }
    }, this);
  }
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var isnan = require( '@stdlib/math/base/utils/is-nan' );
var nan = require( './nan.js' );

// MAIN //

/**
* Returns a function for evaluating the quantile function of a degenerate distribution centered at a provided mean value.
*
* @param {number} mu - value at which to center the distribution
* @returns {Function} function to evaluate the quantile function
*
* @example
* var quantile = factory( 5.0 );
* var y = quantile( 0.3 );
* // returns 5.0
* y = quantile( 0.1 );
* // returns 5.0
* y = quantile( 1.1 );
* // returns NaN
*/
function factory( mu ) {
	if ( isnan( mu ) ) {
		return nan;
	}
	return quantile;

	/**
	* Evaluates the quantile function of a degenerate distribution.
	*
	* @private
	* @param {Probability} p - input value
	* @returns {number} evaluated quantile function
	*
	* @example
	* var y = quantile( 0.5 );
	* // returns mu
	*/
	function quantile( p ) {
		if ( isnan( p ) || p < 0.0 || p > 1.0 ) {
			return NaN;
		}
		return mu;
	} // end FUNCTION quantile()
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<commit_msg>Add empty lines<commit_after>'use strict';

// MODULES //

var isnan = require( '@stdlib/math/base/utils/is-nan' );
var nan = require( './nan.js' );

// MAIN //

/**
* Returns a function for evaluating the quantile function of a degenerate distribution centered at a provided mean value.
*
* @param {number} mu - value at which to center the distribution
* @returns {Function} function to evaluate the quantile function
*
* @example
* var quantile = factory( 5.0 );
*
* var y = quantile( 0.3 );
* // returns 5.0
*
* y = quantile( 0.1 );
* // returns 5.0
*
* y = quantile( 1.1 );
* // returns NaN
*/
function factory( mu ) {
	if ( isnan( mu ) ) {
		return nan;
	}
	return quantile;

	/**
	* Evaluates the quantile function of a degenerate distribution.
	*
	* @private
	* @param {Probability} p - input value
	* @returns {number} evaluated quantile function
	*
	* @example
	* var y = quantile( 0.5 );
	* // returns <number>
	*/
	function quantile( p ) {
		if ( isnan( p ) || p < 0.0 || p > 1.0 ) {
			return NaN;
		}
		return mu;
	} // end FUNCTION quantile()
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<|endoftext|>


<commit_before>angular.module('NodeWebBase')
    .controller('detailsController', ['$scope','$rootScope', function ($scope, $rootScope) {
        $scope.data = null;
        $scope.currentItemIndex = null;
        $scope.displayIndex = null;
        $scope.displayCaptionHtml = "None";
        $scope.termArray = [];
        $scope.currentItem = {"usr":"unknown",
                                "cap":"none",
                                "sco":"0"};

        $rootScope.$on('loadItemData', function (event, data) {
            $scope.$apply(function () {
                $scope.data = data;
                $scope.currentItemIndex = 0;
                $scope.displayIndex = 1;
                $scope.currentItem = $scope.data.posts[0];
            });
        });

        $rootScope.$on("setTermDictionary", function(event,data){
            $scope.$apply(function () {
                    angular.forEach(data,function(entry,idx){
                        $scope.termArray.push(entry[0]);
                    })
                });
        });

        $scope.highlightText = function(text){
            var words = text.split(' ');
            angular.forEach($scope.termArray,function(term,idx){
                angular.forEach(words,function(word,idx){
                    if(word.toLowerCase() == term.toLowerCase()){
                        words[idx] = '' + word + "";
                    }
                    else{
                    }
                });
            });
            return words.join(' ');
        };

        $scope.next = function(){
            $scope.currentItemIndex++;

            if($scope.currentItemIndex >= $scope.data.posts.length)
                $scope.currentItemIndex = 0;

            $scope.displayIndex = $scope.currentItemIndex+1;
            $scope.currentItem = $scope.data.posts[$scope.currentItemIndex];
            $scope.displayCaptionHtml = $scope.highlightText($scope.currentItem.cap);
            $("#caption").html($scope.displayCaptionHtml);
        };

        $scope.previous = function(){
            $scope.currentItemIndex--;

            if($scope.currentItemIndex < 0)
                $scope.currentItemIndex = $scope.data.posts.length-1;

            $scope.displayIndex = $scope.currentItemIndex+1;
            $scope.currentItem = $scope.data.posts[$scope.currentItemIndex];
            $scope.displayCaptionHtml = $scope.highlightText($scope.currentItem.cap);
            $("#caption").html($scope.displayCaptionHtml);
        };

        $scope.getUser = function(){
            $.ajax({
                url:  $rootScope.baseUrl + "app/twitter/user",
                data : {
                    "screen_name":"twitterapi"
                },
                dataType: "json",
                success: function (response) {
                    $scope.user = response;
                },
                error: $rootScope.showError
            });
        };
    }]);<commit_msg>make sure first item when viewing cards is bound<commit_after>angular.module('NodeWebBase')
    .controller('detailsController', ['$scope','$rootScope', function ($scope, $rootScope) {
        $scope.data = null;
        $scope.currentItemIndex = null;
        $scope.displayIndex = null;
        $scope.displayCaptionHtml = "None";
        $scope.termArray = [];
        $scope.currentItem = {"usr":"unknown",
                                "cap":"none",
                                "sco":"0"};

        $rootScope.$on('loadItemData', function (event, data) {
            $scope.$apply(function () {
                $scope.data = data;
                $scope.currentItemIndex = 0;
                $scope.displayIndex = 1;
                $scope.currentItem = $scope.data.posts[0];
                $scope.displayCaptionHtml = $scope.highlightText($scope.currentItem.cap);
                $("#caption").html($scope.displayCaptionHtml);
            });
        });

        $rootScope.$on("setTermDictionary", function(event,data){
            $scope.$apply(function () {
                    angular.forEach(data,function(entry,idx){
                        $scope.termArray.push(entry[0]);
                    })
                });
        });

        $scope.highlightText = function(text){
            var words = text.split(' ');
            angular.forEach($scope.termArray,function(term,idx){
                angular.forEach(words,function(word,idx){
                    if(word.toLowerCase() == term.toLowerCase()){
                        words[idx] = '' + word + "";
                    }
                    else{
                    }
                });
            });
            return words.join(' ');
        };

        $scope.next = function(){
            $scope.currentItemIndex++;

            if($scope.currentItemIndex >= $scope.data.posts.length)
                $scope.currentItemIndex = 0;

            $scope.displayIndex = $scope.currentItemIndex+1;
            $scope.currentItem = $scope.data.posts[$scope.currentItemIndex];
            $scope.displayCaptionHtml = $scope.highlightText($scope.currentItem.cap);
            $("#caption").html($scope.displayCaptionHtml);
        };

        $scope.previous = function(){
            $scope.currentItemIndex--;

            if($scope.currentItemIndex < 0)
                $scope.currentItemIndex = $scope.data.posts.length-1;

            $scope.displayIndex = $scope.currentItemIndex+1;
            $scope.currentItem = $scope.data.posts[$scope.currentItemIndex];
            $scope.displayCaptionHtml = $scope.highlightText($scope.currentItem.cap);
            $("#caption").html($scope.displayCaptionHtml);
        };

        $scope.getUser = function(){
            $.ajax({
                url:  $rootScope.baseUrl + "app/twitter/user",
                data : {
                    "screen_name":"twitterapi"
                },
                dataType: "json",
                success: function (response) {
                    $scope.user = response;
                },
                error: $rootScope.showError
            });
        };
    }]);<|endoftext|>