<commit_before>// Dependencies

let builder = require('focus').component.builder;
let React = require('react');
let assign = require('object-assign');

// Components

let FacetBox = require('../../../search/facet-box').component;
let ListActionBar = require('../../../list/action-bar/index').component;
let ListSummary = require('../../../list/summary/index').component;

// Store

let SearchStore = require('focus').store.SearchStore;

// Mixins

let ScrollInfoMixin = require('../common/scroll-info-mixin').mixin;
let GroupByMixin = require('../common/group-by-mixin').mixin;
let SearchMixin = require('../common/search-mixin').mixin;
let type = require('focus').component.types;
/**
 * Page mixin of the advanced search.
 * @type {Object}
 */
let AdvancedSearchMixin = {
    mixins: [ScrollInfoMixin, GroupByMixin, SearchMixin],
    /**
     * Display name.
     */
    displayName: 'advanced-search',
    /**
     * Component initialisation
     */
    componentDidMount() {
        this._registerListeners();
        this.search();
    },
    /**
     * Actions before component will unmount.
     * @constructor
     */
    componentWillUnmount() {
        this._unRegisterListeners();
    },
    /** @inheritedDoc
     */
    getDefaultProps() {
        return {
            facetConfig: {},
            idField: 'id', //To remove?
            isSelection: true,
            criteria: {
                scope: undefined,
                searchText: undefined
            },
            exportAction: undefined,
            unselectedScopeAction: undefined
        };
    },
    propTypes: {
      facetConfig: type('object'),
      idField: type('string'),
      isSelection: type('bool'),
      criteria: type('object'),
      exportAction: type(['function', 'object']),
      unselectedScopeAction: type(['function', 'object'])
    },
    /**
     * Init default state.
     * @returns {object} Initialized state.
     */
    getInitialState() {
        return assign({
            facetList: {},
            selectedFacetList: {},
            openedFacetList: this.props.openedFacetList,
            selectionStatus: 'none',
            orderSelected: undefined,
            groupSelectedKey: undefined
        });
    },
    /**
     * Get the state from store.
     * @returns {object} Dtat to update store.
     */
    _getStateFromStore() {
        if (this.store) {
            let data = this.store.get();
            return assign({
                facetList: data.facet
            }, this.getScrollState());
        }
    },

    /**
     * Register a listener on the store.
     * @private
     */
    _registerListeners() {
        if (this.store) {
            this.store.addSearchChangeListener(this._onSearchChange);
        }
    },
    /**
     * Unregister a listener on the store.
     * @private
     */
    _unRegisterListeners() {
        if (this.store) {
            this.store.removeSearchChangeListener(this._onSearchChange);
        }
    },

    /**
     * Handler when store emit a change event.
     */
    _onSearchChange() {
        this.setState(this._getStateFromStore());
    },
    /**
     * Get the list of facet to print into the top bar.
     * @returns {{}} Facets object : [facet1: 'Label of facet1', facet2: 'Label of facet2'}.
     * @private
     */
    _getFacetListForBar() {
        let facetList = {};
        for (let key in this.state.selectedFacetList) {
            let facet = this.state.selectedFacetList[key];
            facetList[key] = facet.data.label;
        }
        return facetList;
    },
    /**
     * Click on bar facet action handler.
     * @param key [string}  Key of the clicked facet.
     * @private
     */
    _facetBarClick(key) {
        let selectedFacetList = this.state.selectedFacetList;
        delete selectedFacetList[key];

        this.state.selectedFacetList = selectedFacetList;
        this.setState(
            assign(
                {selectedFacetList: selectedFacetList},
                this.getNoFetchState())
            , this.search);
    },
    /**
     * Group action click handler.
     * @param {string} key Name of the column to group (if null => ungroup action).
     * @private
     */
    _groupClick(key) {
        console.log('Group by : ' + key);
        this.setState(
            assign(
                {groupSelectedKey: key},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Order action click handler.
     * @param {string} key Column to order.
     * @param {string} order Order  asc/desc
     * @private
     */
    _orderClick(key, order) {
        console.log('Order : ' + key + ' - ' + order);
        this.setState(
            assign(
                {orderSelected: {key: key, order: order}},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Selection action handler.
     * @param selectionStatus Current selection status.
     * @private
     */
    _selectionGroupLineClick(selectionStatus) {
        console.log('Selection status : ' + selectionStatus);
        this.setState({
            selectionStatus
        });
    },
    /**
     * Handler called when facet is selected.
     * @param facetComponentData Data of facet.
     */
    _facetSelectionClick(facetComponentData, isDisableGroup) {
        console.warn('Facet selection ');
        console.log(facetComponentData.selectedFacetList);

        let newState = {
            selectedFacetList: facetComponentData.selectedFacetList,
            openedFacetList: facetComponentData.openedFacetList
        };
        if (isDisableGroup) {
            newState.groupSelectedKey = undefined;
        }

        this.setState(assign(newState, this.getNoFetchState()), this.search);
    },
    /**
     * Line selection handler.
     * @param item Line checked/unchecked.
     */
    _selectItem(item) {
        this.setState({selectionStatus: 'partial'});
    },
    /**
     * Export action handler.
     */
    _exportHandler() {
        this.props.exportAction();
    },
    /**
     * Click on scope action handler.
     */
    _scopeClick() {
        this.props.unselectedScopeAction();
    },
    /**
     * Action on line click.
     * @param {object} item  the item clicked
     */
    _lineClick(item) {
        if (this.props.onLineClick) {
            this.props.onLineClick(item);
        }
    },
    /**
     * Render the show all button  seect the group corresponding facet.
     * @param groupKey Group key.
     * @returns {Function} Function to select the facet.
     */
    showAllGroupListHandler(groupKey) {
        return (event)=> {
            let selectedFacetList = this.state.selectedFacetList;

            let facet = this.store.getFacet();
            selectedFacetList[this.state.groupSelectedKey] = {
                data: facet[this.state.groupSelectedKey][groupKey],
                key: groupKey
            };
            this._facetSelectionClick({
                selectedFacetList: selectedFacetList,
                facetComponentData: this.state.openedFacetList
            }, true);
        };
    },

    /**
     * Render the facet box.
     * @returns {XML} Render the facetBox.
     */
    getFacetBoxComponent() {
        return (
          <FacetBox
              facetList={this.state.facetList}
              selectedFacetList={this.state.selectedFacetList}
              openedFacetList={this.state.openedFacetList}
              config={this.props.facetConfig}
              dataSelectionHandler={this._facetSelectionClick}
          />
        );
    },
    /**
     * Render the list summary component.
     * @returns {XML} Htm code.
     */
    getListSummaryComponent() {
        let scopeList = {scope: this.props.criteria.scope};
        return (
            <div className='listSummaryContainer panel'>
                <ListSummary
                    nb={this.state.totalRecords}
                    queryText={this.props.criteria.searchText}
                    scopeList={scopeList}
                    scopeClickAction={this._scopeClick}
                    exportAction={this._exportHandler}/>
            </div>
        );
    },
    /**
     * Render the action bar.
     * @returns {XML} Rendering of the action bar.
     */
    getActionBarComponent() {
        let groupableColumnList = Object.keys(this.state.facetList).reduce((result, facetKey) => {
            result[facetKey] = facetKey;
            return result;
        }, {});
        return (
            <ListActionBar selectionStatus={this.state.selectionStatus}
                           selectionAction={this._selectionGroupLineClick}
                           orderableColumnList={this.props.orderableColumnList}
                           orderAction={this._orderClick}
                           orderSelected={this.state.orderSelected}
                           groupableColumnList={groupableColumnList}
                           groupAction={this._groupClick}
                           groupSelectedKey={this.state.groupSelectedKey}
                           facetList={this._getFacetListForBar()}
                           facetClickAction={this._facetBarClick}
                           operationList={this.props.lineOperationList}/>
        );
    }
};

module.exports = builder(AdvancedSearchMixin, true);
<commit_msg>[advanced-search]<commit_after>// Dependencies

let builder = require('focus').component.builder;
let React = require('react');
let assign = require('object-assign');

// Components

let FacetBox = require('../../../search/facet-box').component;
let ListActionBar = require('../../../list/action-bar/index').component;
let ListSummary = require('../../../list/summary/index').component;

// Store

let SearchStore = require('focus').store.SearchStore;

// Mixins

let ScrollInfoMixin = require('../common/scroll-info-mixin').mixin;
let GroupByMixin = require('../common/group-by-mixin').mixin;
let SearchMixin = require('../common/search-mixin').mixin;
let type = require('focus').component.types;
/**
 * Page mixin of the advanced search.
 * @type {Object}
 */
let AdvancedSearchMixin = {
    mixins: [ScrollInfoMixin, GroupByMixin, SearchMixin],
    /**
     * Display name.
     */
    displayName: 'advanced-search',
    /**
     * Component initialisation
     */
    componentDidMount() {
        this._registerListeners();
        this.search();
    },
    /**
     * Actions before component will unmount.
     * @constructor
     */
    componentWillUnmount() {
        this._unRegisterListeners();
    },
    /** @inheritedDoc
     */
    getDefaultProps() {
        return {
            facetConfig: {},
            idField: 'id', //To remove?
            isSelection: true,
            criteria: {
                scope: undefined,
                searchText: undefined
            },
            exportAction: undefined,
            unselectedScopeAction: undefined
        };
    },
    propTypes: {
      facetConfig: type('object'),
      idField: type('string'),
      isSelection: type('bool'),
      criteria: type('object'),
      exportAction: type(['function', 'object']),
      unselectedScopeAction: type(['function', 'object'])
    },
    /**
     * Init default state.
     * @returns {object} Initialized state.
     */
    getInitialState() {
        return assign({
            facetList: {},
            selectedFacetList: {},
            openedFacetList: this.props.openedFacetList,
            selectionStatus: 'none',
            orderSelected: undefined,
            groupSelectedKey: undefined,
            scope: this.props.scope,
            query: this.props.query
        });
    },
    /**
     * Get the state from store.
     * @returns {object} Dtat to update store.
     */
    _getStateFromStore() {
        if (this.store) {
            let data = this.store.get();
            return assign({
                facetList: data.facet
            }, this.getScrollState());
        }
    },

    /**
     * Register a listener on the store.
     * @private
     */
    _registerListeners() {
        if (this.store) {
            this.store.addSearchChangeListener(this._onSearchChange);
        }
    },
    /**
     * Unregister a listener on the store.
     * @private
     */
    _unRegisterListeners() {
        if (this.store) {
            this.store.removeSearchChangeListener(this._onSearchChange);
        }
    },

    /**
     * Handler when store emit a change event.
     */
    _onSearchChange() {
        this.setState(this._getStateFromStore());
    },
    /**
     * Get the list of facet to print into the top bar.
     * @returns {{}} Facets object : [facet1: 'Label of facet1', facet2: 'Label of facet2'}.
     * @private
     */
    _getFacetListForBar() {
        let facetList = {};
        for (let key in this.state.selectedFacetList) {
            let facet = this.state.selectedFacetList[key];
            facetList[key] = facet.data.label;
        }
        return facetList;
    },
    /**
     * Click on bar facet action handler.
     * @param key [string}  Key of the clicked facet.
     * @private
     */
    _facetBarClick(key) {
        let selectedFacetList = this.state.selectedFacetList;
        delete selectedFacetList[key];

        this.state.selectedFacetList = selectedFacetList;
        this.setState(
            assign(
                {selectedFacetList: selectedFacetList},
                this.getNoFetchState())
            , this.search);
    },
    /**
     * Group action click handler.
     * @param {string} key Name of the column to group (if null => ungroup action).
     * @private
     */
    _groupClick(key) {
        console.log('Group by : ' + key);
        this.setState(
            assign(
                {groupSelectedKey: key},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Order action click handler.
     * @param {string} key Column to order.
     * @param {string} order Order  asc/desc
     * @private
     */
    _orderClick(key, order) {
        console.log('Order : ' + key + ' - ' + order);
        this.setState(
            assign(
                {orderSelected: {key: key, order: order}},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Selection action handler.
     * @param selectionStatus Current selection status.
     * @private
     */
    _selectionGroupLineClick(selectionStatus) {
        console.log('Selection status : ' + selectionStatus);
        this.setState({
            selectionStatus
        });
    },
    /**
     * Handler called when facet is selected.
     * @param facetComponentData Data of facet.
     */
    _facetSelectionClick(facetComponentData, isDisableGroup) {
        console.warn('Facet selection ');
        console.log(facetComponentData.selectedFacetList);

        let newState = {
            selectedFacetList: facetComponentData.selectedFacetList,
            openedFacetList: facetComponentData.openedFacetList
        };
        if (isDisableGroup) {
            newState.groupSelectedKey = undefined;
        }

        this.setState(assign(newState, this.getNoFetchState()), this.search);
    },
    /**
     * Line selection handler.
     * @param item Line checked/unchecked.
     */
    _selectItem(item) {
        this.setState({selectionStatus: 'partial'});
    },
    /**
     * Export action handler.
     */
    _exportHandler() {
        this.props.exportAction();
    },
    /**
     * Click on scope action handler.
     */
    _scopeClick() {
        this.props.unselectedScopeAction();
    },
    /**
     * Action on line click.
     * @param {object} item  the item clicked
     */
    _lineClick(item) {
        if (this.props.onLineClick) {
            this.props.onLineClick(item);
        }
    },
    /**
     * Render the show all button  seect the group corresponding facet.
     * @param groupKey Group key.
     * @returns {Function} Function to select the facet.
     */
    showAllGroupListHandler(groupKey) {
        return (event)=> {
            let selectedFacetList = this.state.selectedFacetList;

            let facet = this.store.getFacet();
            selectedFacetList[this.state.groupSelectedKey] = {
                data: facet[this.state.groupSelectedKey][groupKey],
                key: groupKey
            };
            this._facetSelectionClick({
                selectedFacetList: selectedFacetList,
                facetComponentData: this.state.openedFacetList
            }, true);
        };
    },

    /**
     * Render the facet box.
     * @returns {XML} Render the facetBox.
     */
    getFacetBoxComponent() {
        return (
          <FacetBox
              facetList={this.state.facetList}
              selectedFacetList={this.state.selectedFacetList}
              openedFacetList={this.state.openedFacetList}
              config={this.props.facetConfig}
              dataSelectionHandler={this._facetSelectionClick}
          />
        );
    },
    /**
     * Render the list summary component.
     * @returns {XML} Htm code.
     */
    getListSummaryComponent() {
        let scopeList = {scope: this.props.criteria.scope};
        return (
          <ListSummary
                    nb={this.state.totalRecords}
                    queryText={this.props.criteria.searchText}
                    scopeList={scopeList}
                    scopeClickAction={this._scopeClick}
                    exportAction={this._exportHandler}/>
        );
    },
    /**
     * Render the action bar.
     * @returns {XML} Rendering of the action bar.
     */
    getActionBarComponent() {
        let groupableColumnList = Object.keys(this.state.facetList).reduce((result, facetKey) => {
            result[facetKey] = facetKey;
            return result;
        }, {});
        return (
            <ListActionBar selectionStatus={this.state.selectionStatus}
                           selectionAction={this._selectionGroupLineClick}
                           orderableColumnList={this.props.orderableColumnList}
                           orderAction={this._orderClick}
                           orderSelected={this.state.orderSelected}
                           groupableColumnList={groupableColumnList}
                           groupAction={this._groupClick}
                           groupSelectedKey={this.state.groupSelectedKey}
                           facetList={this._getFacetListForBar()}
                           facetClickAction={this._facetBarClick}
                           operationList={this.props.lineOperationList}/>
        );
    }
};

module.exports = builder(AdvancedSearchMixin, true);
<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
  API = require('json-api'),
  APIError = API.types.Error,
  morgan = require('morgan'),
  cors = require('cors'),
  mongoose = require('mongoose');

// Conect to mongoose
mongoose.connect('mongodb://52.23.229.207/fanscore');

// Models
var models =  {
  Fan: require('./models/fan'),
  Game: require('./models/game'),
  Team: require('./models/team'),
  Fanscore: require('./models/fanscore'),
  Stadium: require('./models/stadium')
};

// Register with json-api
var adapter = new API.dbAdapters.Mongoose(models);
var registry = new API.ResourceTypeRegistry({
  fans: require('./resources/fan'),
  games: require('./resources/game'),
  teams: require('./resources/team'),
  fanscores: require('./resources/fanscore'),
  stadiums: require('./resources/stadium')
}, { dbAdapter: adapter });

var Controller = new API.controllers.API(registry);

// Initialize the automatic documentation.
var Docs = new API.controllers.Documentation(registry, {name: 'FanScore API'});

// Initialize the express app + front controller.
var app = express();
app.use(morgan('dev'));

var Front = new API.httpStrategies.Express(Controller, Docs);
var apiReqHandler = Front.apiRequest.bind(Front);
var optionsHandler = function (req, res, next) {
  res.send(200);
};

// CORS
app.use(cors());

// Routes
app.get("/", Front.docsRequest.bind(Front));
app.route("/:type(fan|fans):/id")
  .get(apiReqHandler).post(apiReqHandler).patch(apiReqHandler).put(apiReqHandler).options(optionsHandler);
app.route("/:type(game|games)/:id")
  .get(apiReqHandler).post(apiReqHandler).patch(apiReqHandler).put(apiReqHandler).options(optionsHandler);
app.route("/:type(team|teams)/:id")
  .get(apiReqHandler).post(apiReqHandler).patch(apiReqHandler).put(apiReqHandler).options(optionsHandler);

app.use(function(req, res, next) {
  Front.sendError(new APIError(404, undefined, 'Not Found'), req, res);
});

// And we're done! Start 'er up!
console.log('Starting up! Visit 127.0.0.1 to see the docs.');
if (process.getuid && process.getuid() === 0) {
  app.listen(80);
  console.log('Listening on port 80.');
} else {
  app.listen(8080);
  console.log('Listening on port 8080 because you are not running as root.');
}
<commit_msg>route fixes?<commit_after>'use strict';

var express = require('express'),
  API = require('json-api'),
  APIError = API.types.Error,
  morgan = require('morgan'),
  cors = require('cors'),
  mongoose = require('mongoose');

// Conect to mongoose
mongoose.connect('mongodb://52.23.229.207/fanscore');

// Models
var models =  {
  Fan: require('./models/fan'),
  Game: require('./models/game'),
  Team: require('./models/team'),
  Fanscore: require('./models/fanscore'),
  Stadium: require('./models/stadium')
};

// Register with json-api
var adapter = new API.dbAdapters.Mongoose(models);
var registry = new API.ResourceTypeRegistry({
  fans: require('./resources/fan'),
  games: require('./resources/game'),
  teams: require('./resources/team'),
  fanscores: require('./resources/fanscore'),
  stadiums: require('./resources/stadium')
}, { dbAdapter: adapter });

var Controller = new API.controllers.API(registry);

// Initialize the automatic documentation.
var Docs = new API.controllers.Documentation(registry, {name: 'FanScore API'});

// Initialize the express app + front controller.
var app = express();
app.use(morgan('dev'));

var Front = new API.httpStrategies.Express(Controller, Docs);
var apiReqHandler = Front.apiRequest.bind(Front);
var optionsHandler = function (req, res, next) {
  res.send(200);
};

// CORS
app.use(cors());

// Routes
app.get("/", Front.docsRequest.bind(Front));
app.route("/:type(fan|fans)/:id")
  .get(apiReqHandler).post(apiReqHandler).patch(apiReqHandler).put(apiReqHandler).options(optionsHandler);
app.route("/:type(game|games)/:id")
  .get(apiReqHandler).post(apiReqHandler).patch(apiReqHandler).put(apiReqHandler).options(optionsHandler);
app.route("/:type(team|teams)/:id")
  .get(apiReqHandler).post(apiReqHandler).patch(apiReqHandler).put(apiReqHandler).options(optionsHandler);

app.use(function(req, res, next) {
  Front.sendError(new APIError(404, undefined, 'Not Found'), req, res);
});

// And we're done! Start 'er up!
console.log('Starting up! Visit 127.0.0.1 to see the docs.');
if (process.getuid && process.getuid() === 0) {
  app.listen(80);
  console.log('Listening on port 80.');
} else {
  app.listen(8080);
  console.log('Listening on port 8080 because you are not running as root.');
}
<|endoftext|>


<commit_before>import React from 'react';
import {observable, computed, toJS} from 'mobx';
import {observer} from 'mobx-react/native';
import autobind from 'autobind-decorator';
import navigationStore from './navigationStore';
import Scene from './Scene';
import { assert } from './Util';

import {TabNavigator, DrawerNavigator, StackNavigator, NavigationActions, addNavigationHelpers} from 'react-navigation';
// import StackNavigator from './components/nav/navigators/StackNavigator';
// import TabNavigator from './components/nav/navigators/TabNavigator';
// import DrawerNavigator from './components/nav/navigators/DrawerNavigator';
// import NavigationActions from './components/nav/NavigationActions';
// import addNavigationHelpers from './components/nav/addNavigationHelpers';
const reservedKeys = [
  'navigate',
  'currentState',
  'refresh',
  'dispatch',
  'push',
  'setParams',
  'back',
  'pop'
];

function filterParam(data) {
  if (data.toString() !== '[object Object]') {
    return {data};
  }
  const proto = (data || {}).constructor.name;
  // avoid passing React Native parameters
  if (!data || (proto !== 'Object')) {
    return {};
  }
  return data;
}

function getValue(value, params) {
  return value instanceof Function ? value(params) : value;
}

function createNavigationOptions({title, hideNavBar, hideTabBar, backTitle, right, left, headerStyle}) {
  return ({navigation, screenProps}) => {
    if (hideTabBar) {
      return {
        tabBarVisible: false
      };
    }
    if (hideNavBar) {
      return {
        header: null
      };
    }

    return {
      title: getValue((navigation.state.params && navigation.state.params.title) || title, {...navigation.state.params, ...screenProps}),
      headerBackTitle: getValue((navigation.state.params && navigation.state.params.backTitle) || backTitle, {...navigation.state.params, ...screenProps}),
      headerRight: getValue((navigation.state.params && navigation.state.params.right) || right, {...navigation.state.params, ...screenProps}),
      headerLeft: getValue((navigation.state.params && navigation.state.params.left) || left, {...navigation.state.params, ...screenProps}),
      headerStyle: getValue((navigation.state.params && navigation.state.params.headerStyle || headerStyle), {...navigation.state.params, ...screenProps}),
    }
  }
}

@observer
class Renderer extends React.Component {
  render() {
    const Component = this.props.router.screen;
    return <Component navigation={addNavigationHelpers({state: this.props.router.state, dispatch: this.props.router.dispatch})}/>
  }
}

// @autobind
// export default class Router {
//   _names = {};
//   _scenes = null;
//   _converted = {};
//   _root = null;
//   _rootKey;
//   @observable screen;
//   @observable _state;
//   @computed get state() {
//     return toJS(this._state);
//   }
//
//   create(props) {
//     this.screen = null;
//     this._state = null;
//     try {
//       console.log("CREATE SCENES", this._scenes, this.screen);
//       this.screen = this.convertScene(this._root, this._rootKey).screen;
//       this.dispatch(NavigationActions.init());
//       return props => <Renderer router={this}/>
//     } catch (e) {
//       console.log("ERROR:", e);
//     }
//
//   }
//
//   constructor(scenes = {}) {
//     this._scenes = scenes;
//     for (const key of Object.keys(scenes)) {
//       const scene = scenes[key];
//       if (scene.initial) {
//         if (this._root) {
//           throw `initial must be unique: ${this._root}, ${scene}`;
//         } else {
//           if (!scene.children) {
//             throw `Root scene "${key}" must have children`;
//           }
//           this._root = scene;
//           this._rootKey = key;
//         }
//       }
//       if (reservedKeys.indexOf(key) !== -1) {
//         throw `Scene name cannot be reserved word: ${key}`;
//       }
//       if (!scene.component && !scene.children) {
//         throw `component or children property should be defined for scene '${key}'`;
//       }
//
//       if (!this[key]) {
//         // a bit of magic ;)
//         this[key] = new Function('actions', `return function ${key}(params){ actions.push('${key}', params)}`)(this);
//         this._names[this[key]] = key;
//       }
//     }
//
//     if (!this._root) {
//       throw 'No root scene is defined, please set initial property to true for root scene';
//     }
//     //setTimeout((()=>this.init()));
//   }
//
//   convertScene(scene, key) {
//     if (!key) {
//       throw `key cannot be null for scene ${JSON.stringify(scene)}`;
//     }
//     const {children, component, hideNavBar, modal, ...props} = scene;
//     let screen = component;
//     if (!screen) {
//       const children = this._getChildren(scene);
//       if (scene.tabs) {
//         screen = TabNavigator(children, scene);
//       } else if (scene.drawer) {
//         screen = DrawerNavigator(children, scene);
//       } else {
//
//         screen = StackNavigator(children, {
//           mode: modal ? 'modal' : 'card',
//           initialRouteParams: children[this._names[scene.children()[0]]]
//         });
//       }
//     }
//     this._converted[key] = {screen, navigationOptions, ...props};
//     if (hideNavBar) {
//       this._converted[key].navigationOptions = () => ({header: null});
//     }
//     return this._converted[key];
//   }
//
//   _getChildren(scene) {
//     if (!scene.children) {
//       return scene;
//     }
//     const children = scene.children();
//     if (!Array.isArray(children)) {
//       throw `Scene ${scene.key} children() is not Array`;
//     }
//     const res = {};
//     for (const f of children) {
//       if (!this._names[f] || !this._scenes[this._names[f]]) {
//         throw `Cannot found children ${JSON.stringify(f)} for scene '${JSON.stringify(scene)}`;
//       }
//       const name = this._names[f];
//       res[name] = this.convertScene(this._scenes[name], name);
//     }
//     return res;
//   }
//
//   dispatch(action) {
//     this._state = this.screen.router.getStateForAction(action, this._state);
//   }
//
//   currentState(state) {
//     if (!state) {
//       state = this._state;
//     }
//     if (!state.routes) {
//       return state;
//     } else {
//       return this.currentState(state.routes[state.index]);
//     }
//   }
//
//   push(routeName, params) {
//     this.dispatch(NavigationActions.navigate({
//       routeName,
//       params: {...this._converted[routeName], ...filterParam(params)}
//     }));
//   }
//
//   refresh(params) {
//     const key = this.currentState(this.state).key;
//     this.dispatch(NavigationActions.setParams({key, params}));
//   }
//
//   pop() {
//     this.dispatch(NavigationActions.back());
//   }
//
// }

@observer
@autobind
class App extends React.Component {

  render() {
    const AppNavigator = this.props.navigator;
    return (
      <AppNavigator navigation={addNavigationHelpers({
        dispatch: this.props.store.dispatch,
        state: this.props.store.state,
      })} />
    );
  }
}

// @autobind
// export default class Router {
//   navigator;
//   store;
//
//   constructor(scenes){
//     this.navigator = StackNavigator(scenes);
//     this.store = new NavigationStore(this.navigator.router);
//   }
//
//   app(){
//     return () => <App navigator={this.navigator} store={this.store} />
//
//   }
// }

function processScene(scene: Scene, inheritProps) {
  assert(scene.props, 'props should be defined');
  if (!scene.props.children) {
    throw `children property should be defined`;
  }
  const res = {};
  const order = [];
  const {tabs, modal, drawer, ...parentProps} = scene.props;
  const children = !Array.isArray(parentProps.children) ? [parentProps.children] : parentProps.children;
  let initialRouteName, initialRouteParams;
  for (const child of children) {
    assert(child.key, `key should be defined for ${child}`);
    if (reservedKeys.indexOf(child.key) !== -1) {
      throw `Scene name cannot be reserved word: ${key}`;
    }
    const {component, ...props} = child.props;
    res[child.key] = {
      screen: component || processScene(child, parentProps),
      navigationOptions: createNavigationOptions(props)
    };

    // a bit of magic, create all 'actions' inside navigationStore
    if (!navigationStore[child.key]) {
      navigationStore[child.key] = new Function('actions', `return function ${child.key}(params){ actions.push('${child.key}', params)}`)(navigationStore);
    }
    order.push(child.key)
    if (child.props.initial || !initialRouteName) {
      initialRouteName = child.key;
      initialRouteParams = child.props;
    }
  }
  const mode = modal ? 'modal' : 'card';
  if (tabs) {
    return TabNavigator(res, {initialRouteParams, order, navigationOptions: createNavigationOptions(parentProps) });
  } else if (drawer) {
    return DrawerNavigator(res);
  } else {
    return StackNavigator(res, { mode, initialRouteParams, initialRouteName, navigationOptions: createNavigationOptions(parentProps) });
  }
}

export default (scene: Scene) => {
  const AppNavigator = processScene(scene);
  navigationStore.router = AppNavigator.router;

  return observer(()=><AppNavigator navigation={addNavigationHelpers({
    dispatch: navigationStore.dispatch,
    state: navigationStore.state,
  })} />);
}
<commit_msg>pass 'default' props to actions as well.<commit_after>import React from 'react';
import {observable, computed, toJS} from 'mobx';
import {observer} from 'mobx-react/native';
import autobind from 'autobind-decorator';
import navigationStore from './navigationStore';
import Scene from './Scene';
import { assert } from './Util';

import {TabNavigator, DrawerNavigator, StackNavigator, NavigationActions, addNavigationHelpers} from 'react-navigation';
// import StackNavigator from './components/nav/navigators/StackNavigator';
// import TabNavigator from './components/nav/navigators/TabNavigator';
// import DrawerNavigator from './components/nav/navigators/DrawerNavigator';
// import NavigationActions from './components/nav/NavigationActions';
// import addNavigationHelpers from './components/nav/addNavigationHelpers';
const reservedKeys = [
  'navigate',
  'currentState',
  'refresh',
  'dispatch',
  'push',
  'setParams',
  'back',
  'pop'
];

function filterParam(data) {
  if (data.toString() !== '[object Object]') {
    return {data};
  }
  const proto = (data || {}).constructor.name;
  // avoid passing React Native parameters
  if (!data || (proto !== 'Object')) {
    return {};
  }
  return data;
}

function getValue(value, params) {
  return value instanceof Function ? value(params) : value;
}

function createNavigationOptions({title, hideNavBar, hideTabBar, backTitle, right, left, headerStyle}) {
  return ({navigation, screenProps}) => {
    if (hideTabBar) {
      return {
        tabBarVisible: false
      };
    }
    if (hideNavBar) {
      return {
        header: null
      };
    }

    return {
      title: getValue((navigation.state.params && navigation.state.params.title) || title, {...navigation.state.params, ...screenProps}),
      headerBackTitle: getValue((navigation.state.params && navigation.state.params.backTitle) || backTitle, {...navigation.state.params, ...screenProps}),
      headerRight: getValue((navigation.state.params && navigation.state.params.right) || right, {...navigation.state.params, ...screenProps}),
      headerLeft: getValue((navigation.state.params && navigation.state.params.left) || left, {...navigation.state.params, ...screenProps}),
      headerStyle: getValue((navigation.state.params && navigation.state.params.headerStyle || headerStyle), {...navigation.state.params, ...screenProps}),
    }
  }
}

@observer
class Renderer extends React.Component {
  render() {
    const Component = this.props.router.screen;
    return <Component navigation={addNavigationHelpers({state: this.props.router.state, dispatch: this.props.router.dispatch})}/>
  }
}

// @autobind
// export default class Router {
//   _names = {};
//   _scenes = null;
//   _converted = {};
//   _root = null;
//   _rootKey;
//   @observable screen;
//   @observable _state;
//   @computed get state() {
//     return toJS(this._state);
//   }
//
//   create(props) {
//     this.screen = null;
//     this._state = null;
//     try {
//       console.log("CREATE SCENES", this._scenes, this.screen);
//       this.screen = this.convertScene(this._root, this._rootKey).screen;
//       this.dispatch(NavigationActions.init());
//       return props => <Renderer router={this}/>
//     } catch (e) {
//       console.log("ERROR:", e);
//     }
//
//   }
//
//   constructor(scenes = {}) {
//     this._scenes = scenes;
//     for (const key of Object.keys(scenes)) {
//       const scene = scenes[key];
//       if (scene.initial) {
//         if (this._root) {
//           throw `initial must be unique: ${this._root}, ${scene}`;
//         } else {
//           if (!scene.children) {
//             throw `Root scene "${key}" must have children`;
//           }
//           this._root = scene;
//           this._rootKey = key;
//         }
//       }
//       if (reservedKeys.indexOf(key) !== -1) {
//         throw `Scene name cannot be reserved word: ${key}`;
//       }
//       if (!scene.component && !scene.children) {
//         throw `component or children property should be defined for scene '${key}'`;
//       }
//
//       if (!this[key]) {
//         // a bit of magic ;)
//         this[key] = new Function('actions', `return function ${key}(params){ actions.push('${key}', params)}`)(this);
//         this._names[this[key]] = key;
//       }
//     }
//
//     if (!this._root) {
//       throw 'No root scene is defined, please set initial property to true for root scene';
//     }
//     //setTimeout((()=>this.init()));
//   }
//
//   convertScene(scene, key) {
//     if (!key) {
//       throw `key cannot be null for scene ${JSON.stringify(scene)}`;
//     }
//     const {children, component, hideNavBar, modal, ...props} = scene;
//     let screen = component;
//     if (!screen) {
//       const children = this._getChildren(scene);
//       if (scene.tabs) {
//         screen = TabNavigator(children, scene);
//       } else if (scene.drawer) {
//         screen = DrawerNavigator(children, scene);
//       } else {
//
//         screen = StackNavigator(children, {
//           mode: modal ? 'modal' : 'card',
//           initialRouteParams: children[this._names[scene.children()[0]]]
//         });
//       }
//     }
//     this._converted[key] = {screen, navigationOptions, ...props};
//     if (hideNavBar) {
//       this._converted[key].navigationOptions = () => ({header: null});
//     }
//     return this._converted[key];
//   }
//
//   _getChildren(scene) {
//     if (!scene.children) {
//       return scene;
//     }
//     const children = scene.children();
//     if (!Array.isArray(children)) {
//       throw `Scene ${scene.key} children() is not Array`;
//     }
//     const res = {};
//     for (const f of children) {
//       if (!this._names[f] || !this._scenes[this._names[f]]) {
//         throw `Cannot found children ${JSON.stringify(f)} for scene '${JSON.stringify(scene)}`;
//       }
//       const name = this._names[f];
//       res[name] = this.convertScene(this._scenes[name], name);
//     }
//     return res;
//   }
//
//   dispatch(action) {
//     this._state = this.screen.router.getStateForAction(action, this._state);
//   }
//
//   currentState(state) {
//     if (!state) {
//       state = this._state;
//     }
//     if (!state.routes) {
//       return state;
//     } else {
//       return this.currentState(state.routes[state.index]);
//     }
//   }
//
//   push(routeName, params) {
//     this.dispatch(NavigationActions.navigate({
//       routeName,
//       params: {...this._converted[routeName], ...filterParam(params)}
//     }));
//   }
//
//   refresh(params) {
//     const key = this.currentState(this.state).key;
//     this.dispatch(NavigationActions.setParams({key, params}));
//   }
//
//   pop() {
//     this.dispatch(NavigationActions.back());
//   }
//
// }

@observer
@autobind
class App extends React.Component {

  render() {
    const AppNavigator = this.props.navigator;
    return (
      <AppNavigator navigation={addNavigationHelpers({
        dispatch: this.props.store.dispatch,
        state: this.props.store.state,
      })} />
    );
  }
}

// @autobind
// export default class Router {
//   navigator;
//   store;
//
//   constructor(scenes){
//     this.navigator = StackNavigator(scenes);
//     this.store = new NavigationStore(this.navigator.router);
//   }
//
//   app(){
//     return () => <App navigator={this.navigator} store={this.store} />
//
//   }
// }

function processScene(scene: Scene, inheritProps) {
  assert(scene.props, 'props should be defined');
  if (!scene.props.children) {
    throw `children property should be defined`;
  }
  const res = {};
  const order = [];
  const {tabs, modal, drawer, ...parentProps} = scene.props;
  const children = !Array.isArray(parentProps.children) ? [parentProps.children] : parentProps.children;
  let initialRouteName, initialRouteParams;
  for (const child of children) {
    assert(child.key, `key should be defined for ${child}`);
    if (reservedKeys.indexOf(key) !== -1) {
      throw `Scene name cannot be reserved word: ${child.key}`;
    }
    const {component, children, ...props} = child.props;
    const key = child.key;
    res[key] = {
      screen: component || processScene(child, parentProps),
      navigationOptions: createNavigationOptions(child.props)
    };

    // a bit of magic, create all 'actions'-shortcuts inside navigationStore
    if (!navigationStore[key]) {
      navigationStore[key] = new Function('actions', 'props', `return function ${key}(params){ actions.push('${key}', Object.assign({}, props, params))}`)(navigationStore, props);
    }
    order.push(key);
    if (child.props.initial || !initialRouteName) {
      initialRouteName = key;
      initialRouteParams = props;
    }
  }
  const mode = modal ? 'modal' : 'card';
  if (tabs) {
    return TabNavigator(res, {initialRouteParams, order, navigationOptions: createNavigationOptions(parentProps) });
  } else if (drawer) {
    return DrawerNavigator(res);
  } else {
    return StackNavigator(res, { mode, initialRouteParams, initialRouteName, navigationOptions: createNavigationOptions(parentProps) });
  }
}

export default (scene: Scene) => {
  const AppNavigator = processScene(scene);
  navigationStore.router = AppNavigator.router;

  return observer(()=><AppNavigator navigation={addNavigationHelpers({
    dispatch: navigationStore.dispatch,
    state: navigationStore.state,
  })} />);
}
<|endoftext|>


<commit_before>"use strict";

var fs = require("fs");
var mapnik = require("mapnik");

mapnik.register_datasources("..");
mapnik.register_fonts("/usr/share/fonts/truetype/ttf-dejavu");

var map = new mapnik.Map(640, 480);
map.load("test.xml", function(err, map) {
    if (err)
        return console.log("style load error:", err.message);

    map.zoomAll();

    var img = new mapnik.Image(640, 480);
    map.render(img, function(err, img) {
        if (err)
            return console.log("rendering error:", err.message);

        img.encode("png", function(err, buffer) {
            if (err)
                return console.log("encoding error:", err.message);

            fs.writeFile("result.png", buffer, function(err) {
                if (err)
                    return console.log("saving error:", err.message);

                console.log("done...");
            });
        });
    });
});
<commit_msg>one hemisphere mongodb query req satisfied in js<commit_after>"use strict";

var fs = require("fs");
var mapnik = require("mapnik");

mapnik.register_datasources("..");
mapnik.register_fonts("/usr/share/fonts/truetype/ttf-dejavu");

var conf = [
    { extent: [ -180,   0,   0,  90 ], file: "1.png" },
    { extent: [    0,   0, 180,  90 ], file: "2.png" },
    { extent: [ -180, -90,   0,   0 ], file: "3.png" },
    { extent: [    0, -90, 180,   0 ], file: "4.png" }
];

var map = new mapnik.Map(256, 256);
map.load("test.xml", function(err, map) {
    if (err)
        return console.log("style load error:", err.message);

    (function step(i) {
        if (!conf[i]) return;
        render(conf[i], function() { setImmediate(function() { step(i + 1) }); });
    })(0);
});

function render(conf, callback) {
    map.zoomToBox(conf.extent);

    var img = new mapnik.Image(256, 256);
    map.render(img, function(err, img) {
        if (err)
            return console.log("rendering error:", err.message);

        img.encode("png", function(err, buffer) {
            if (err)
                return console.log("encoding error:", err.message);

            fs.writeFile(conf.file, buffer, function(err) {
                if (err)
                    return console.log("saving error:", err.message);

                console.log("done:", conf.file);
                return callback && callback();
            });
        });
    });
}
<|endoftext|>


<commit_before>angular.module('gateways', [])
.factory('gateways', function($http) {
  var defaultGateways;
  var custom;

  //load gateways list from API
  var promise = $http.get(API + '/gateways').success(function (data) {
    var normalized;
    var gateway;
    var currency;

    defaultGateways = data;
    custom = store.session.get('userGateways') ||
      store.get('userGateways') || { };

    //add or update gateways based
    //on data from api
    for (currency in defaultGateways) {

      //unknown currency,
      //add it as a default
      if (!custom[currency]) {
        custom[currency] = {
          custom  : false,
          issuers : { }
        };

      //must be a default
      //currency
      } else {
        custom[currency].custom = false;
      }

      //update gateways with the new data
      for (var i in defaultGateways[currency]) {
        gateway = defaultGateways[currency][i];

        //if its already here,
        //use the current include
        if (custom[currency].issuers[gateway.account]) {
          gateway.include = custom[currency].issuers[gateway.account].include;

        //otherwise, include it if featured
        } else {
          gateway.include = defaultGateways[currency][i].featured;
        }

        normalized     = gateway.name.toLowerCase().replace(/\W/g, '');
        gateway.irba   = gateway.assets.length ? true : false;
        gateway.assets = handleAssets(gateway.assets, normalized);
        custom[currency].issuers[gateway.account] = gateway;
      }
    }

    function sortIssuers (data) {
      var issuers = Object.keys(data.issuers)
        .map(function (issuer) {
          return data.issuers[issuer]
        });

      // sort by IRBA, featured
      issuers.sort(function (a, b) {
        var first  = (a.irba ? '0' : '1') + (a.featured ? '0' : '1') + a.name;
        var second = (b.irba ? '0' : '1') + (b.featured ? '0' : '1') + b.name;
        return (first >= second ? 1 : -1);
      });

      data.issuers = {};
      issuers.forEach(function(issuer) {
        data.issuers[issuer.account] = issuer;
      });
    }

    for (currency in custom) {
      sortIssuers(custom[currency]);

      // ensure that non-default
      // currencies are marked as custom
      if (!defaultGateways[currency]) {
        custom[currency].custom = true;
      }
    }

    // save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  });

  //add API endpoint to asset filenames
  function handleAssets(assets, normalized) {
    var obj = { };

    if (!assets) assets = [ ];

    assets.forEach(function(a) {
      obj[a] = API + '/gateways/' + normalized + '/assets/' + a;
    });

    return obj;
  }

  /**
   * getCurrencies
   * get currencies from user defined list
   */

  var getCurrencies = function (all) {

    var currencies = [];
    var include;

    //add currencies from cusom list
    for (var currency in custom) {
      if (currency === '0158415500000000C1F76FF6ECB0BAC600000000') {
        continue;
      }

      include = null;

      //find selected currencies
      for (var issuer in custom[currency].issuers) {
        if (custom[currency].issuers[issuer].include) {
          include = {
            currency : currency,
            icon     : API + '/currencies/'+ currency +'.svg',
            include  : true,
            custom   : custom[currency].custom
          };
          break;
        }
      }

      //if none are selected, only add if all = true
      if (include)  currencies.push(include);
      else if (all) currencies.push({
        currency : currency,
        icon     : API + '/currencies/'+ currency +'.svg',
        include  : false,
        custom   : custom[currency].custom
      });
    }

    currencies.sort(function(a, b){
      if(a.currency < b.currency) return -1;
      if(a.currency > b.currency) return 1;
      return 0;
    });

    currencies.unshift({
      currency : "XRP",
      icon     : API + '/currencies/xrp.svg',
      include  : true
    });

    return currencies;
  };

  /**
   * getIssuers
   * get issuers for a given currency
   */

  var getIssuers = function (currency, all) {
    var issuers = [ ];
    var normalized;
    var assets;
    var name;

    if (!custom[currency]) return [ ];

    for (var issuer in custom[currency].issuers) {
      if (all || custom[currency].issuers[issuer].include) {
        issuers.push(custom[currency].issuers[issuer]);
      }
    }

    issuers.sort(function(a,b) {
      if (a.featured && b.featured) return 0;
      else if (a.featured) return -1;
      else if (b.featured) return 1;
      else return 0;
    });

    return issuers;
  };

  /**
   * updateCurrency
   * add/remove/include/exclude
   */

  var updateCurrency = function (options) {
    var currency = options.currency.toUpperCase();
    var featured;
    var issuer;

    //include currency, include featured
    //if there are any, otherwise include all
    if (options.include && custom[currency]) {
      featured = hasFeatured(custom[currency].issuers);

      for (issuer in custom[currency].issuers) {
        if (featured && !custom[currency].issuers[issuer].featured) {
          continue;
        }

        custom[currency].issuers[issuer].include = true;
      }

    //exclude currency, exclude all issuers
    } else if (options.exclude && custom[currency]) {
      for (issuer in custom[currency].issuers) {
        custom[currency].issuers[issuer].include = false;
      }

    //add custom
    } else if (options.add && !custom[currency]) {
      custom[currency] = {
        custom  : true,
        issuers : { }
      };

    //remove custom
    } else if (options.remove && custom[currency] && custom[currency].custom) {
      delete custom[currency];

    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);

    //check for featured gateway
    function hasFeatured(issuers) {
      for (var i in issuers) {
        if (issuers[i].featured) return true;
      }

      return false;
    }
  };

  /**
   * updateIssuer
   * add/remove/include/exclude
   */

  var updateIssuer = function (options) {
    var currency = options.currency.toUpperCase();
    var issuer   = options.issuer;

    if (!custom[currency]) return;

    //include or exclude
    if (options.exclude || options.include) {
      if (!custom[currency].issuers[issuer]) return;
      custom[currency].issuers[issuer].include = options.include ? true : false;

    } else if (options.add && !custom[currency].issuers[issuer]) {
      custom[currency].issuers[issuer] = {
        account : issuer,
        name    : options.name || issuer,
        include : true,
        custom  : true
      };

    } else if (options.remove &&
               custom[currency].issuers[issuer] &&
               custom[currency].issuers[issuer].custom) {
      delete custom[currency].issuers[issuer];
    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  };

  var getName = function(currency, issuer) {
    if (currency === "XRP") return "";
    var gateways = custom[currency].issuers;
    if (gateways) return gateways[issuer].name;
    else return "";
  };

  return {
    promise        : promise,
    getCurrencies  : getCurrencies,
    getIssuers     : getIssuers,
    updateCurrency : updateCurrency,
    updateIssuer   : updateIssuer,
    getName        : getName
  }
});
<commit_msg>abreviate ripple exchange tokyo<commit_after>angular.module('gateways', [])
.factory('gateways', function($http) {
  var defaultGateways;
  var custom;

  //load gateways list from API
  var promise = $http.get(API + '/gateways').success(function (data) {
    var normalized;
    var gateway;
    var currency;

    defaultGateways = data;
    custom = store.session.get('userGateways') ||
      store.get('userGateways') || { };

    //add or update gateways based
    //on data from api
    for (currency in defaultGateways) {

      //unknown currency,
      //add it as a default
      if (!custom[currency]) {
        custom[currency] = {
          custom  : false,
          issuers : { }
        };

      //must be a default
      //currency
      } else {
        custom[currency].custom = false;
      }

      //update gateways with the new data
      for (var i in defaultGateways[currency]) {
        gateway = defaultGateways[currency][i];

        //if its already here,
        //use the current include
        if (custom[currency].issuers[gateway.account]) {
          gateway.include = custom[currency].issuers[gateway.account].include;

        //otherwise, include it if featured
        } else {
          gateway.include = defaultGateways[currency][i].featured;
        }

        normalized     = gateway.name.toLowerCase().replace(/\W/g, '');
        gateway.irba   = gateway.assets.length ? true : false;
        gateway.assets = handleAssets(gateway.assets, normalized);

        if (gateway.name === 'Ripple Exchange Tokyo') {
          gateway.name = "Ripple Exch Tokyo";
        }

        custom[currency].issuers[gateway.account] = gateway;
      }
    }

    function sortIssuers (data) {
      var issuers = Object.keys(data.issuers)
        .map(function (issuer) {
          return data.issuers[issuer]
        });

      // sort by IRBA, featured
      issuers.sort(function (a, b) {
        var first  = (a.irba ? '0' : '1') + (a.featured ? '0' : '1') + a.name;
        var second = (b.irba ? '0' : '1') + (b.featured ? '0' : '1') + b.name;
        return (first >= second ? 1 : -1);
      });

      data.issuers = {};
      issuers.forEach(function(issuer) {
        data.issuers[issuer.account] = issuer;
      });
    }

    for (currency in custom) {
      sortIssuers(custom[currency]);

      // ensure that non-default
      // currencies are marked as custom
      if (!defaultGateways[currency]) {
        custom[currency].custom = true;
      }
    }

    // save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  });

  //add API endpoint to asset filenames
  function handleAssets(assets, normalized) {
    var obj = { };

    if (!assets) assets = [ ];

    assets.forEach(function(a) {
      obj[a] = API + '/gateways/' + normalized + '/assets/' + a;
    });

    return obj;
  }

  /**
   * getCurrencies
   * get currencies from user defined list
   */

  var getCurrencies = function (all) {

    var currencies = [];
    var include;

    //add currencies from cusom list
    for (var currency in custom) {
      if (currency === '0158415500000000C1F76FF6ECB0BAC600000000') {
        continue;
      }

      include = null;

      //find selected currencies
      for (var issuer in custom[currency].issuers) {
        if (custom[currency].issuers[issuer].include) {
          include = {
            currency : currency,
            icon     : API + '/currencies/'+ currency +'.svg',
            include  : true,
            custom   : custom[currency].custom
          };
          break;
        }
      }

      //if none are selected, only add if all = true
      if (include)  currencies.push(include);
      else if (all) currencies.push({
        currency : currency,
        icon     : API + '/currencies/'+ currency +'.svg',
        include  : false,
        custom   : custom[currency].custom
      });
    }

    currencies.sort(function(a, b){
      if(a.currency < b.currency) return -1;
      if(a.currency > b.currency) return 1;
      return 0;
    });

    currencies.unshift({
      currency : "XRP",
      icon     : API + '/currencies/xrp.svg',
      include  : true
    });

    return currencies;
  };

  /**
   * getIssuers
   * get issuers for a given currency
   */

  var getIssuers = function (currency, all) {
    var issuers = [ ];
    var normalized;
    var assets;
    var name;

    if (!custom[currency]) return [ ];

    for (var issuer in custom[currency].issuers) {
      if (all || custom[currency].issuers[issuer].include) {
        issuers.push(custom[currency].issuers[issuer]);
      }
    }

    issuers.sort(function(a,b) {
      if (a.featured && b.featured) return 0;
      else if (a.featured) return -1;
      else if (b.featured) return 1;
      else return 0;
    });

    return issuers;
  };

  /**
   * updateCurrency
   * add/remove/include/exclude
   */

  var updateCurrency = function (options) {
    var currency = options.currency.toUpperCase();
    var featured;
    var issuer;

    //include currency, include featured
    //if there are any, otherwise include all
    if (options.include && custom[currency]) {
      featured = hasFeatured(custom[currency].issuers);

      for (issuer in custom[currency].issuers) {
        if (featured && !custom[currency].issuers[issuer].featured) {
          continue;
        }

        custom[currency].issuers[issuer].include = true;
      }

    //exclude currency, exclude all issuers
    } else if (options.exclude && custom[currency]) {
      for (issuer in custom[currency].issuers) {
        custom[currency].issuers[issuer].include = false;
      }

    //add custom
    } else if (options.add && !custom[currency]) {
      custom[currency] = {
        custom  : true,
        issuers : { }
      };

    //remove custom
    } else if (options.remove && custom[currency] && custom[currency].custom) {
      delete custom[currency];

    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);

    //check for featured gateway
    function hasFeatured(issuers) {
      for (var i in issuers) {
        if (issuers[i].featured) return true;
      }

      return false;
    }
  };

  /**
   * updateIssuer
   * add/remove/include/exclude
   */

  var updateIssuer = function (options) {
    var currency = options.currency.toUpperCase();
    var issuer   = options.issuer;

    if (!custom[currency]) return;

    //include or exclude
    if (options.exclude || options.include) {
      if (!custom[currency].issuers[issuer]) return;
      custom[currency].issuers[issuer].include = options.include ? true : false;

    } else if (options.add && !custom[currency].issuers[issuer]) {
      custom[currency].issuers[issuer] = {
        account : issuer,
        name    : options.name || issuer,
        include : true,
        custom  : true
      };

    } else if (options.remove &&
               custom[currency].issuers[issuer] &&
               custom[currency].issuers[issuer].custom) {
      delete custom[currency].issuers[issuer];
    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  };

  var getName = function(currency, issuer) {
    if (currency === "XRP") return "";
    var gateways = custom[currency].issuers;
    if (gateways) return gateways[issuer].name;
    else return "";
  };

  return {
    promise        : promise,
    getCurrencies  : getCurrencies,
    getIssuers     : getIssuers,
    updateCurrency : updateCurrency,
    updateIssuer   : updateIssuer,
    getName        : getName
  }
});
<|endoftext|>


<commit_before>// Dependencies

let builder = require('focus').component.builder;
let React = require('react');
let assign = require('object-assign');
let reduce = require('lodash/collection/reduce');
let includes = require('lodash/collection/includes');

// Components

let FacetBox = require('../../../search/facet-box').component;
let ListActionBar = require('../../../list/action-bar/index').component;
let ListSummary = require('../../../list/summary/index').component;

// Store

let SearchStore = require('focus').store.SearchStore;

// Mixins

let ScrollInfoMixin = require('../common/scroll-info-mixin').mixin;
let GroupByMixin = require('../common/group-by-mixin').mixin;
let SearchMixin = require('../common/search-mixin').mixin;
let CartridgeBehaviour = require('../../mixin/cartridge-behaviour');
let type = require('focus').component.types;
/**
 * Page mixin of the advanced search.
 * @type {Object}
 */
let AdvancedSearch = {
    mixins: [ScrollInfoMixin, GroupByMixin, SearchMixin, CartridgeBehaviour],
    /**
     * Display name.
     */
    displayName: 'advanced-search',
    /**
     * Component initialisation
     */
    componentDidMount() {
        this._registerListeners();
        this.search();
    },
    /**
     * Actions before component will unmount.
     * @constructor
     */
    componentWillUnmount() {
        this._unRegisterListeners();
    },
    /** @inheritedDoc
     */
    getDefaultProps() {
        return {
            facetConfig: {},
            idField: 'id', //To remove?
            isSelection: true
        };
    },
    propTypes: {
        facetConfig: type('object'),
        idField: type('string'),
        isSelection: type('bool'),
        scope: type('string'),
        query: type('string'),
        exportAction: type(['function', 'object']),
        unselectedScopeAction: type(['function', 'object'])
    },
    /**
     * Init default state.
     * @returns {object} Initialized state.
     */
    getInitialState() {
        return assign({
            facetList: {},
            selectedFacetList: {},
            openedFacetList: this.props.openedFacetList,
            selectionStatus: 'none',
            orderSelected: undefined,
            groupSelectedKey: undefined,
            scope: this.props.scope,
            query: this.props.query
        });
    },
    componentWillReceiveProps(nextProps) {
        this.setState(reduce(nextProps, (newState, key, value) => {
            if (includes(['scope', 'query'], key)) {
                newState[key] = value;
            }
            return newState;
        }, {}));
    },
    /**
     * Get the state from store.
     * @returns {object} Dtat to update store.
     */
    _getStateFromStore() {
        if (this.props.store) {
            let data = this.props.store.get();
            return assign({
                facetList: data.facet
            }, this.getScrollState());
        }
    },

    /**
     * Register a listener on the store.
     * @private
     */
    _registerListeners() {
        if (this.props.store) {
            this.props.store.addSearchChangeListener(this._onSearchChange);
        }
    },
    /**
     * Unregister a listener on the store.
     * @private
     */
    _unRegisterListeners() {
        if (this.props.store) {
            this.props.store.removeSearchChangeListener(this._onSearchChange);
        }
    },

    /**
     * Handler when store emit a change event.
     */
    _onSearchChange() {
        this.setState(this._getStateFromStore());
    },
    /**
     * Get the list of facet to print into the top bar.
     * @returns {{}} Facets object : [facet1: 'Label of facet1', facet2: 'Label of facet2'}.
     * @private
     */
    _getFacetListForBar() {
        let facetList = {};
        for (let key in this.state.selectedFacetList) {
            let facet = this.state.selectedFacetList[key];
            facetList[key] = facet.data.label;
        }
        return facetList;
    },
    /**
     * Click on bar facet action handler.
     * @param key [string}  Key of the clicked facet.
     * @private
     */
    _facetBarClick(key) {
        let selectedFacetList = this.state.selectedFacetList;
        delete selectedFacetList[key];

        this.state.selectedFacetList = selectedFacetList;
        this.setState(
            assign(
                {selectedFacetList: selectedFacetList},
                this.getNoFetchState())
            , this.search);
    },
    /**
     * Group action click handler.
     * @param {string} key Name of the column to group (if null => ungroup action).
     * @private
     */
    _groupClick(key) {
        console.log('Group by : ' + key);
        this.setState(
            assign(
                {groupSelectedKey: key},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Order action click handler.
     * @param {string} key Column to order.
     * @param {string} order Order  asc/desc
     * @private
     */
    _orderClick(key, order) {
        console.log('Order : ' + key + ' - ' + order);
        this.setState(
            assign(
                {orderSelected: {key: key, order: order}},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Selection action handler.
     * @param selectionStatus Current selection status.
     * @private
     */
    _selectionGroupLineClick(selectionStatus) {
        console.log('Selection status : ' + selectionStatus);
        this.setState({
            selectionStatus
        });
    },
    /**
     * Handler called when facet is selected.
     * @param facetComponentData Data of facet.
     */
    _facetSelectionClick(facetComponentData, isDisableGroup) {
        console.warn('Facet selection ');
        console.log(facetComponentData.selectedFacetList);

        let newState = {
            selectedFacetList: facetComponentData.selectedFacetList,
            openedFacetList: facetComponentData.openedFacetList
        };
        if (isDisableGroup) {
            newState.groupSelectedKey = undefined;
        }

        this.setState(assign(newState, this.getNoFetchState()), this.search);
    },
    /**
     * Line selection handler.
     * @param item Line checked/unchecked.
     */
    _selectItem(item) {
        this.setState({selectionStatus: 'partial'});
    },
    /**
     * Export action handler.
     */
    _exportHandler() {
        this.props.exportAction();
    },
    /**
     * Click on scope action handler.
     */
    _scopeClick() {
        this.props.unselectScopeAction();
    },
    /**
     * Action on line click.
     * @param {object} item  the item clicked
     */
    _lineClick(item) {
        if (this.props.onLineClick) {
            this.props.onLineClick(item);
        }
    },
    /**
     * Render the show all button  seect the group corresponding facet.
     * @param groupKey Group key.
     * @returns {Function} Function to select the facet.
     */
    showAllGroupListHandler(groupKey) {
        return (event)=> {
            let selectedFacetList = this.state.selectedFacetList;

            let facet = this.props.store.getFacet();
            selectedFacetList[this.state.groupSelectedKey] = {
                data: facet[this.state.groupSelectedKey][groupKey],
                key: groupKey
            };
            this._facetSelectionClick({
                selectedFacetList: selectedFacetList,
                facetComponentData: this.state.openedFacetList
            }, true);
        };
    },

    /**
     * Render the facet box.
     * @returns {XML} Render the facetBox.
     */
    getFacetBoxComponent() {
        return (
            <FacetBox
                data-focus='advanced-search-facet-box'
                facetList={this.state.facetList}
                selectedFacetList={this.state.selectedFacetList}
                openedFacetList={this.state.openedFacetList}
                config={this.props.facetConfig}
                dataSelectionHandler={this._facetSelectionClick}
                />
        );
    },
    /**
     * Render the list summary component.
     * @returns {XML} Htm code.
     */
    getListSummaryComponent() {
        let scopeList = {scope: this.props.scope};
        return (
            <ListSummary
                data-focus='advanced-search-list-summary'
                nb={this.state.totalRecords}
                queryText={this.props.query}
                scopeList={scopeList}
                scopeClickAction={this._scopeClick}
                exportAction={this._exportHandler}/>
        );
    },
    /**
     * Render the action bar.
     * @returns {XML} Rendering of the action bar.
     */
    getActionBarComponent() {
        let groupableColumnList = Object.keys(this.state.facetList).reduce((result, facetKey) => {
            result[facetKey] = facetKey;
            return result;
        }, {});
        return (
            <ListActionBar data-focus='advanced-search-action-bar'
                           selectionStatus={this.state.selectionStatus}
                           selectionAction={this._selectionGroupLineClick}
                           orderableColumnList={this.props.orderableColumnList}
                           orderAction={this._orderClick}
                           orderSelected={this.state.orderSelected}
                           groupableColumnList={groupableColumnList}
                           groupAction={this._groupClick}
                           groupSelectedKey={this.state.groupSelectedKey}
                           facetList={this._getFacetListForBar()}
                           facetClickAction={this._facetBarClick}
                           operationList={this.props.lineOperationList}/>
        );
    },
    render: function render() {
        return (

                    {this.getFacetBoxComponent()}

                    {this.getListSummaryComponent()}
                    {this.getActionBarComponent()}
                    {this.getResultListComponent(true)}

        );
    }
};

module.exports = builder(AdvancedSearch);
<commit_msg>[back-to-top] Add button back-to-top to the advanced-search page.<commit_after>// Dependencies

let builder = require('focus').component.builder;
let React = require('react');
let assign = require('object-assign');
let reduce = require('lodash/collection/reduce');
let includes = require('lodash/collection/includes');

// Components

let FacetBox = require('../../../search/facet-box').component;
let ListActionBar = require('../../../list/action-bar/index').component;
let ListSummary = require('../../../list/summary/index').component;
let BackToTopComponent = require('../../../common/button/back-to-top').component;
// Store

let SearchStore = require('focus').store.SearchStore;

// Mixins

let ScrollInfoMixin = require('../common/scroll-info-mixin').mixin;
let GroupByMixin = require('../common/group-by-mixin').mixin;
let SearchMixin = require('../common/search-mixin').mixin;
let CartridgeBehaviour = require('../../mixin/cartridge-behaviour');
let type = require('focus').component.types;
/**
 * Page mixin of the advanced search.
 * @type {Object}
 */
let AdvancedSearch = {
    mixins: [ScrollInfoMixin, GroupByMixin, SearchMixin, CartridgeBehaviour],
    /**
     * Display name.
     */
    displayName: 'advanced-search',
    /**
     * Component initialisation
     */
    componentDidMount() {
        this._registerListeners();
        this.search();
    },
    /**
     * Actions before component will unmount.
     * @constructor
     */
    componentWillUnmount() {
        this._unRegisterListeners();
    },
    /** @inheritedDoc
     */
    getDefaultProps() {
        return {
            facetConfig: {},
            idField: 'id', //To remove?
            isSelection: true,
            hasBackToTop: true,
            BackToTopComponent: BackToTopComponent
        };
    },
    propTypes: {
        facetConfig: type('object'),
        idField: type('string'),
        isSelection: type('bool'),
        scope: type('string'),
        query: type('string'),
        exportAction: type(['function', 'object']),
        unselectedScopeAction: type(['function', 'object'])
    },
    /**
     * Init default state.
     * @returns {object} Initialized state.
     */
    getInitialState() {
        return assign({
            facetList: {},
            selectedFacetList: {},
            openedFacetList: this.props.openedFacetList,
            selectionStatus: 'none',
            orderSelected: undefined,
            groupSelectedKey: undefined,
            scope: this.props.scope,
            query: this.props.query
        });
    },
    componentWillReceiveProps(nextProps) {
        this.setState(reduce(nextProps, (newState, key, value) => {
            if (includes(['scope', 'query'], key)) {
                newState[key] = value;
            }
            return newState;
        }, {}));
    },
    /**
     * Get the state from store.
     * @returns {object} Dtat to update store.
     */
    _getStateFromStore() {
        if (this.props.store) {
            let data = this.props.store.get();
            return assign({
                facetList: data.facet
            }, this.getScrollState());
        }
    },

    /**
     * Register a listener on the store.
     * @private
     */
    _registerListeners() {
        if (this.props.store) {
            this.props.store.addSearchChangeListener(this._onSearchChange);
        }
    },
    /**
     * Unregister a listener on the store.
     * @private
     */
    _unRegisterListeners() {
        if (this.props.store) {
            this.props.store.removeSearchChangeListener(this._onSearchChange);
        }
    },

    /**
     * Handler when store emit a change event.
     */
    _onSearchChange() {
        this.setState(this._getStateFromStore());
    },
    /**
     * Get the list of facet to print into the top bar.
     * @returns {{}} Facets object : [facet1: 'Label of facet1', facet2: 'Label of facet2'}.
     * @private
     */
    _getFacetListForBar() {
        let facetList = {};
        for (let key in this.state.selectedFacetList) {
            let facet = this.state.selectedFacetList[key];
            facetList[key] = facet.data.label;
        }
        return facetList;
    },
    /**
     * Click on bar facet action handler.
     * @param key [string}  Key of the clicked facet.
     * @private
     */
    _facetBarClick(key) {
        let selectedFacetList = this.state.selectedFacetList;
        delete selectedFacetList[key];

        this.state.selectedFacetList = selectedFacetList;
        this.setState(
            assign(
                {selectedFacetList: selectedFacetList},
                this.getNoFetchState())
            , this.search);
    },
    /**
     * Group action click handler.
     * @param {string} key Name of the column to group (if null => ungroup action).
     * @private
     */
    _groupClick(key) {
        console.log('Group by : ' + key);
        this.setState(
            assign(
                {groupSelectedKey: key},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Order action click handler.
     * @param {string} key Column to order.
     * @param {string} order Order  asc/desc
     * @private
     */
    _orderClick(key, order) {
        console.log('Order : ' + key + ' - ' + order);
        this.setState(
            assign(
                {orderSelected: {key: key, order: order}},
                this.getNoFetchState()
            ), this.search);
    },
    /**
     * Selection action handler.
     * @param selectionStatus Current selection status.
     * @private
     */
    _selectionGroupLineClick(selectionStatus) {
        console.log('Selection status : ' + selectionStatus);
        this.setState({
            selectionStatus
        });
    },
    /**
     * Handler called when facet is selected.
     * @param facetComponentData Data of facet.
     */
    _facetSelectionClick(facetComponentData, isDisableGroup) {
        console.warn('Facet selection ');
        console.log(facetComponentData.selectedFacetList);

        let newState = {
            selectedFacetList: facetComponentData.selectedFacetList,
            openedFacetList: facetComponentData.openedFacetList
        };
        if (isDisableGroup) {
            newState.groupSelectedKey = undefined;
        }

        this.setState(assign(newState, this.getNoFetchState()), this.search);
    },
    /**
     * Line selection handler.
     * @param item Line checked/unchecked.
     */
    _selectItem(item) {
        this.setState({selectionStatus: 'partial'});
    },
    /**
     * Export action handler.
     */
    _exportHandler() {
        this.props.exportAction();
    },
    /**
     * Click on scope action handler.
     */
    _scopeClick() {
        this.props.unselectScopeAction();
    },
    /**
     * Action on line click.
     * @param {object} item  the item clicked
     */
    _lineClick(item) {
        if (this.props.onLineClick) {
            this.props.onLineClick(item);
        }
    },
    /**
     * Render the show all button  seect the group corresponding facet.
     * @param groupKey Group key.
     * @returns {Function} Function to select the facet.
     */
    showAllGroupListHandler(groupKey) {
        return (event)=> {
            let selectedFacetList = this.state.selectedFacetList;

            let facet = this.props.store.getFacet();
            selectedFacetList[this.state.groupSelectedKey] = {
                data: facet[this.state.groupSelectedKey][groupKey],
                key: groupKey
            };
            this._facetSelectionClick({
                selectedFacetList: selectedFacetList,
                facetComponentData: this.state.openedFacetList
            }, true);
        };
    },

    /**
     * Render the facet box.
     * @returns {XML} Render the facetBox.
     */
    getFacetBoxComponent() {
        return (
            <FacetBox
                data-focus='advanced-search-facet-box'
                facetList={this.state.facetList}
                selectedFacetList={this.state.selectedFacetList}
                openedFacetList={this.state.openedFacetList}
                config={this.props.facetConfig}
                dataSelectionHandler={this._facetSelectionClick}
                />
        );
    },
    /**
     * Render the list summary component.
     * @returns {XML} Htm code.
     */
    getListSummaryComponent() {
        let scopeList = {scope: this.props.scope};
        return (
            <ListSummary
                data-focus='advanced-search-list-summary'
                nb={this.state.totalRecords}
                queryText={this.props.query}
                scopeList={scopeList}
                scopeClickAction={this._scopeClick}
                exportAction={this._exportHandler}/>
        );
    },
    /**
     * Render the action bar.
     * @returns {XML} Rendering of the action bar.
     */
    getActionBarComponent() {
        let groupableColumnList = Object.keys(this.state.facetList).reduce((result, facetKey) => {
            result[facetKey] = facetKey;
            return result;
        }, {});
        return (
            <ListActionBar data-focus='advanced-search-action-bar'
                           selectionStatus={this.state.selectionStatus}
                           selectionAction={this._selectionGroupLineClick}
                           orderableColumnList={this.props.orderableColumnList}
                           orderAction={this._orderClick}
                           orderSelected={this.state.orderSelected}
                           groupableColumnList={groupableColumnList}
                           groupAction={this._groupClick}
                           groupSelectedKey={this.state.groupSelectedKey}
                           facetList={this._getFacetListForBar()}
                           facetClickAction={this._facetBarClick}
                           operationList={this.props.lineOperationList}/>
        );
    },
    render: function render() {
        return (

                    {this.getFacetBoxComponent()}

                    {this.getListSummaryComponent()}
                    {this.getActionBarComponent()}
                    {this.getResultListComponent(true)}

                {this.props.hasBackToTop && <this.props.BackToTopComponent/>}

        );
    }
};

module.exports = builder(AdvancedSearch);
<|endoftext|>