<commit_before>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Ext.define('viewer.LayoutManager', {
    defaultRegionSettings: {
        header: {region: 'north', useTabs: false, defaultLayout: {height: 150}},
        leftmargin_top: {region:'west', subregion:'center', columnOrientation: 'vertical', useTabs: true, defaultLayout: {width: 250}},
        leftmargin_bottom: {region:'west', subregion:'south', columnOrientation: 'vertical', useTabs: true, defaultLayout: {height: 250}},
        left_menu: {region:'center', subregion:'west', columnOrientation: 'horizontal', useTabs: false, defaultLayout: {width: 150}},
        top_menu: {region:'none'},
        content: {region:'center', subregion:'center', columnOrientation: 'horizontal', useTabs: false, defaultLayout: {}},
        popupwindow: {},
        rightmargin_top: {region:'east', subregion:'center', columnOrientation: 'vertical', useTabs: true, defaultLayout: {width: 250}},
        rightmargin_bottom: {region:'east', subregion:'south', columnOrientation: 'vertical', useTabs: true, defaultLayout: {height: 250}},
        footer: {region:'south', useTabs: false, defaultLayout: {height: 150}}
    },
    layout: {},
    layoutItems: {},
    mapId: '',
    componentList: [],
    wrapperId: 'wrapper',
    autoRender: true,

    constructor: function(config) {
        Ext.apply(this, config || {});
        if(this.autoRender) {
            this.createLayout();
        }
    },

    createLayout: function() {
        var me = this;
        //console.log('LAYOUTMANAGER: ', me);
        var regionList = me.createRegionList();
        //console.log('REGIONLIST: ', regionList);
        var viewportItems = me.buildLayoutRegions(regionList);
        //console.log('VIEWPORTITEMS: ', viewportItems);
        me.renderLayout(viewportItems);
    },

    createRegionList: function() {
        var me = this;
        var layoutItems = {};

        Ext.Object.each(me.layout, function(regionid, regionconfig) {
            // If region has components, add it to the list
            if(regionconfig.components.length > 0) {
                // Fetch default config
                var defaultConfig = me.defaultRegionSettings[regionid];
                // Layoutregions are added throug array because 1 Ext region (e.g. west) can have multiple regions
                if(!Ext.isDefined(layoutItems[defaultConfig.region])) {
                    layoutItems[defaultConfig.region] = [];
                }
                // Push the layout to the array
                layoutItems[me.defaultRegionSettings[regionid].region].push({
                    // Region holds the defaultConfig region
                    region: defaultConfig,
                    // Regionconfig holds the regionconfig from the layoutmanager
                    regionconfig: regionconfig,
                    // Region name
                    name: regionid,
                    // Layout of the region (widths, heights, etc.)
                    layout: defaultConfig.defaultLayout
                });
            }
        });
        return layoutItems;
    },

    buildLayoutRegions: function(regionList) {
        var viewportItems = [];
        var me = this;
        Ext.Object.each(regionList, function(region, value) {
            viewportItems.push(me.getLayoutRegion(region, value));
        });
        return viewportItems;
    },

    getLayoutRegion: function(region, value) {
        var me = this;
        var layout = {
            width: 0,
            height: 0
        };
        var regionlayout = null;
        if(value.length > 1) {
            var items = me.getSubLayoutRegion(value);
            var centerItem = me.getSubRegionCenterItem(value);
            if(items.length > 0 && centerItem != null) {
                var extLayout = 'vbox';
                if(centerItem.region.columnOrientation == 'horizontal') extLayout = 'hbox';
                if(region != 'center') {
                    layout.width = centerItem.layout.width;
                    if(centerItem.regionconfig.layout) {
                        regionlayout = centerItem.regionconfig.layout;
                        if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
                            layout.width = parseInt(regionlayout.width);
                        } else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
                            layout.flex = parseInt(regionlayout.width) / 100;
                        }
                    }
                }
                return Ext.apply({
                    xtype: 'container',
                    region: region,
                    layout: extLayout,
                    items: items
                }, layout);
            }
        } else {
            var componentItems = me.createComponents(value[0].regionconfig.components, value[0].region);
            componentItems = me.getRegionContent(value[0].region, componentItems);
            if(value[0].region.region != "none") {
                layout = value[0].layout;
                if(value[0].regionconfig.layout) {
                    regionlayout = value[0].regionconfig.layout;
                    if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
                        layout.width = parseInt(regionlayout.width);
                    } else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
                        layout.flex = parseInt(regionlayout.width) / 100;
                    }
                    if(regionlayout.height != '' && regionlayout.heightmeasure == 'px') {
                        layout.height = parseInt(regionlayout.height);
                    } else if(regionlayout.height != '' && regionlayout.heightmeasure == '%') {
                        layout.flex = parseInt(regionlayout.height) / 100;
                    }
                }
                return Ext.apply({
                    xtype: 'container',
                    region: region,
                    layout: 'vbox',
                    items: componentItems
                }, layout);
            }
        }
        return {};
    },

    getSubLayoutRegion: function(value) {
        var me = this;
        var items = [];
        Ext.Array.each(value, function(item, index) {
            var sublayout = {};
            var componentItems = me.createComponents(item.regionconfig.components, item.region);
            componentItems = me.getRegionContent(item.region, componentItems);
            if(item.regionconfig.layout) {
                var regionlayout = item.regionconfig.layout;
                if(item.region.columnOrientation == 'vertical') {
                    if(item.region.subregion != 'center') {
                        sublayout = Ext.apply({
                            width: 0
                        }, item.layout);
                        if(regionlayout.height != '' && regionlayout.heightmeasure == 'px') {
                            sublayout.height = parseInt(regionlayout.height);
                        } else if(regionlayout.height != '' && regionlayout.heightmeasure == '%') {
                            sublayout.flex = parseInt(regionlayout.height) / 100;
                        }
                    } else {
                        sublayout.flex = 1;
                    }
                    sublayout.width = '100%';
                }
                if(item.region.columnOrientation == 'horizontal') {
                    if(item.region.subregion != 'center') {
                        sublayout = Ext.apply({
                            height: 0
                        }, item.layout);
                        if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
                            sublayout.width = parseInt(regionlayout.width);
                        } else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
                            sublayout.flex = parseInt(regionlayout.width) / 100;
                        }
                    } else {
                        sublayout.flex = 1;
                    }
                    sublayout.height = '100%';
                }
            }
            var extLayout = 'fit';
            if(item.region.useTabs == false && componentItems.length > 1) {
                extLayout = 'vbox';
                if(item.region.orientation == 'horizontal') {
                    extLayout = 'hbox';
                }
            }
            if(item.region.subregion != "none") {
                items.push(Ext.apply({
                    xtype: 'container',
                    items: componentItems,
                    layout: extLayout
                }, sublayout));
            }
        });
        return items;
    },

    getSubRegionCenterItem: function(value) {
        var centerItem = null;
        Ext.Array.each(value, function(item, index) {
            if(item.region.subregion == 'center') {
                centerItem =  item;
            }
        });
        return centerItem;
    },

    createComponents: function(components, region) {
        var componentItems = [];
        var cmpId = null;
        var me = this;

        Ext.Array.each(components, function(component) {
            cmpId = Ext.id();
            var compStyle = {width: '100%',height: '100%'};
            var compFlex = 0;
            if(region.useTabs == false) {
                compStyle = {width: '100%'};
                if(region.orientation == 'horizontal') {
                    compStyle = {height: '100%'};
                }
                compFlex = 1;
            }
            var cmpView = {
                xtype: 'container',
                // Title is used in tabs
                title: component.name,
                cls: 'component-view',
                tpl: '<tpl for=".">

</tpl>',
                data: {
                    id: cmpId,
                    cmp_name: component.name
                },
                layout: 'fit',
                hideMode: 'offsets',
                style: compStyle,
                flex: compFlex
            };
            componentItems.push(cmpView);
            me.componentList.push({
                htmlId: cmpId,
                componentName: component.name,
                componentClass: component.componentClass
            });
            if(component.componentClass == "FlamingoMap") {
                me.mapId = cmpId;
            }
        });

        return componentItems;
    },

    getRegionContent: function(region, componentItems) {
        if(Ext.isDefined(region.useTabs) && region.useTabs && componentItems.length > 1) {
            var cmpId = Ext.id();
            var tabcomponent = {
                xtype: 'tabpanel',
                id: cmpId,
                activeTab: 0,
                deferredRender: false,
                defaults: {
                    hideMode: 'offsets'
                },
                items: componentItems
            };
            return tabcomponent;
        }
        return componentItems;
    },

    renderLayout: function(viewportItems) {
        var me = this;
        Ext.create('Ext.container.Container', {
            layout: 'border',
            items: viewportItems,
            renderTo: me.wrapperId,
            height: '100%',
            width: '100%'
        });
    },

    getMapId: function() {
        return this.mapId;
    },

    getComponentList: function() {
        return this.componentList;
    }
});
<commit_msg>LayoutManager v0.9<commit_after>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Ext.define('viewer.LayoutManager', {
    defaultRegionSettings: {
        header: {region: 'north', columnOrientation: 'horizontal', useTabs: false, defaultLayout: {height: 150}},
        leftmargin_top: {region:'west', subregion:'center', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {width: 250}},
        leftmargin_bottom: {region:'west', subregion:'south', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {height: 250}},
        left_menu: {region:'center', subregion:'west', columnOrientation: 'horizontal', subRegionOrientation: 'vertical', singleComponentBlock: true, useTabs: false, defaultLayout: {width: 150}},
        top_menu: {region:'none'},
        content: {region:'center', subregion:'center', columnOrientation: 'horizontal', subRegionOrientation: 'vertical', useTabs: false, defaultLayout: {}},
        popupwindow: {},
        rightmargin_top: {region:'east', subregion:'center', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {width: 250}},
        rightmargin_bottom: {region:'east', subregion:'south', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {height: 250}},
        footer: {region:'south', columnOrientation: 'horizontal', useTabs: false, defaultLayout: {height: 150}}
    },
    layout: {},
    layoutItems: {},
    mapId: '',
    componentList: [],
    wrapperId: 'wrapper',
    autoRender: true,

    constructor: function(config) {
        Ext.apply(this, config || {});
        if(this.autoRender) {
            this.createLayout();
        }
    },

    createLayout: function() {
        var me = this;
        console.log('LAYOUTMANAGER: ', me);
        var regionList = me.createRegionList();
        console.log('REGIONLIST: ', regionList);
        var viewportItems = me.buildLayoutRegions(regionList);
        console.log('VIEWPORTITEMS: ', viewportItems);
        me.renderLayout(viewportItems);
    },

    createRegionList: function() {
        var me = this;
        var layoutItems = {};

        Ext.Object.each(me.layout, function(regionid, regionconfig) {
            // If region has components, add it to the list
            if(regionconfig.components.length > 0) {
                // Fetch default config
                var defaultConfig = me.defaultRegionSettings[regionid];
                // Layoutregions are added throug array because 1 Ext region (e.g. west) can have multiple regions
                if(!Ext.isDefined(layoutItems[defaultConfig.region])) {
                    layoutItems[defaultConfig.region] = [];
                }
                // Push the layout to the array
                layoutItems[me.defaultRegionSettings[regionid].region].push({
                    // Region name
                    name: regionid,
                    // regionConfig holds the regionconfig from the layoutmanager
                    regionConfig: regionconfig,
                    // regionDefaultConfig holds the defaultConfig region
                    regionDefaultConfig: defaultConfig
                });
            }
        });
        return layoutItems;
    },

    buildLayoutRegions: function(regionList) {
        var viewportItems = [];
        var me = this;
        Ext.Object.each(regionList, function(region, value) {
            viewportItems.push(me.getLayoutRegion(region, value));
        });
        return viewportItems;
    },

    getLayoutRegion: function(regionid, regionitems) {
        var me = this;
        var layout = {
            width: 0,
            height: 0
        };
        var regionlayout = null;
        var extLayout = '';
        if(regionitems.length > 1) {
            var items = me.getSubLayoutRegion(regionitems);
            var centerItem = me.getSubRegionCenterItem(regionitems);
            if(items.length > 0 && centerItem != null) {
                extLayout = { type: 'vbox', align: 'stretch' };
                if(centerItem.regionDefaultConfig.columnOrientation == 'horizontal') extLayout = { type: 'hbox', align: 'stretch' };
                if(regionid != 'center') {
                    layout.width = centerItem.regionDefaultConfig.defaultLayout.width;
                    regionlayout = centerItem.regionConfig.layout;
                    if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
                        layout.width = parseInt(regionlayout.width);
                    } else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
                        layout.flex = parseInt(regionlayout.width) / 100;
                    }
                } else {
                    layout.flex = 1;
                    layout.height = '100%';
                }
                return Ext.apply({
                    xtype: 'container',
                    region: regionid,
                    layout: extLayout,
                    items: items
                }, layout);
            }
        } else {
            regionlayout = regionitems[0].regionConfig.layout;
            var componentItems = me.createComponents(regionitems[0].regionConfig.components, regionitems[0].regionDefaultConfig, regionlayout);
            componentItems = me.getRegionContent(componentItems, regionlayout);
            if(regionitems[0].regionDefaultConfig.region != "none") {
                layout = regionitems[0].regionDefaultConfig.defaultLayout;
                if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
                    layout.width = parseInt(regionlayout.width);
                } else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
                    layout.flex = parseInt(regionlayout.width) / 100;
                }
                if(regionlayout.height != '' && regionlayout.heightmeasure == 'px') {
                    layout.height = parseInt(regionlayout.height);
                } else if(regionlayout.height != '' && regionlayout.heightmeasure == '%') {
                    layout.flex = parseInt(regionlayout.height) / 100;
                }

                extLayout = 'fit';
                if(regionlayout.useTabs == false && componentItems.length > 1 && !Ext.isDefined(regionitems[0].regionDefaultConfig.singleComponentBlock) && !regionitems[0].regionDefaultConfig.singleComponentBlock) {
                    extLayout = { type: 'vbox', align: 'stretch' };
                    if(regionitems[0].regionDefaultConfig.columnOrientation == 'horizontal') {
                        extLayout = { type: 'hbox', align: 'stretch' };
                    }
                }
                return Ext.apply({
                    xtype: 'container',
                    region: regionid,
                    layout: extLayout,
                    items: componentItems
                }, layout);
            }
        }
        return {};
    },

    getSubLayoutRegion: function(regionitems) {
        var me = this;
        var items = {};
        Ext.Array.each(regionitems, function(item, index) {
            var sublayout = {};
            var regionlayout = item.regionConfig.layout;
            var componentItems = me.createComponents(item.regionConfig.components, item.regionDefaultConfig, regionlayout);
            componentItems = me.getRegionContent(componentItems, regionlayout);
            if(item.regionDefaultConfig.columnOrientation == 'vertical') {
                if(item.regionDefaultConfig.subregion != 'center') {
                    sublayout = Ext.apply({
                        width: 0
                    }, item.regionDefaultConfig.defaultLayout);
                    if(regionlayout.height != '' && regionlayout.heightmeasure == 'px') {
                        sublayout.height = parseInt(regionlayout.height);
                    } else if(regionlayout.height != '' && regionlayout.heightmeasure == '%') {
                        sublayout.flex = parseInt(regionlayout.height) / 100;
                    }
                } else {
                    sublayout.flex = 1;
                }
                sublayout.width = '100%';
            }
            if(item.regionDefaultConfig.columnOrientation == 'horizontal') {
                if(item.regionDefaultConfig.subregion != 'center') {
                    sublayout = Ext.apply({
                        height: 0
                    }, item.regionDefaultConfig.defaultLayout);
                    if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
                        sublayout.width = parseInt(regionlayout.width);
                    } else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
                        sublayout.flex = parseInt(regionlayout.width) / 100;
                    }
                } else {
                    sublayout.flex = 1;
                }
                sublayout.height = '100%';
            }

            var extLayout = 'fit';
            if(regionlayout.useTabs == false && componentItems.length > 1 && !Ext.isDefined(item.regionDefaultConfig.singleComponentBlock) && !item.regionDefaultConfig.singleComponentBlock) {
                extLayout = { type: 'vbox', align: 'stretch' };
                if(item.regionDefaultConfig.subRegionOrientation == 'horizontal') {
                    extLayout = { type: 'hbox', align: 'stretch' };
                }
            }
            if(item.regionDefaultConfig.subregion != "none") {
                items[item.regionDefaultConfig.subregion] = Ext.apply({
                    xtype: 'container',
                    items: componentItems,
                    layout: extLayout
                }, sublayout);
            }
        });
        return me.reorderSubRegions(items);
    },

    reorderSubRegions: function(subregions) {
        var order = ['north','west','center','east','south'];
        var items = [];
        Ext.Array.each(order, function(regionname) {
            if(Ext.isDefined(subregions[regionname])) {
                items.push(subregions[regionname]);
            }
        });
        return items;
    },

    getSubRegionCenterItem: function(regionitems) {
        var centerItem = null;
        Ext.Array.each(regionitems, function(item, index) {
            if(item.regionDefaultConfig.subregion == 'center') {
                centerItem =  item;
            }
        });
        return centerItem;
    },

    createComponents: function(components, regionDefaultConfig, regionlayout) {
        var componentItems = [];
        var cmpId = null;
        var me = this;
        var first = true;
        var singleBlock = (Ext.isDefined(regionDefaultConfig.singleComponentBlock) && regionDefaultConfig.singleComponentBlock);

        Ext.Array.each(components, function(component) {
            if(!singleBlock || (singleBlock && first)) {
                cmpId = Ext.id();
            }
            var compStyle = {width: '100%',height: '100%'};
            var compFlex = 0;
            if(regionlayout.useTabs == false && !singleBlock) {
                compStyle = {width: '100%'};
                if(Ext.isDefined(regionDefaultConfig.subRegionOrientation)) {
                    if(regionDefaultConfig.subRegionOrientation == 'horizontal') {
                        compStyle = {height: '100%'};
                    }
                } else {
                    if(regionDefaultConfig.columnOrientation == 'horizontal') {
                        compStyle = {height: '100%'};
                    }
                }
                compFlex = 1;
            }
            var cmpView = {
                xtype: 'container',
                // Title is used in tabs
                title: component.name,
                cls: 'component-view',
                tpl: '<tpl for=".">

</tpl>',
                data: {
                    id: cmpId,
                    cmp_name: component.name
                },
                layout: 'fit',
                hideMode: 'offsets',
                style: compStyle,
                flex: compFlex
            };
            if(!singleBlock || (singleBlock && first)) {
                componentItems.push(cmpView);
            }
            me.componentList.push({
                htmlId: cmpId,
                componentName: component.name,
                componentClass: component.componentClass
            });
            if(component.componentClass == "FlamingoMap") {
                me.mapId = cmpId;
            }
            first = false;
        });

        return componentItems;
    },

    getRegionContent: function(componentItems, regionlayout) {
        if(Ext.isDefined(regionlayout.useTabs) && regionlayout.useTabs && componentItems.length > 1) {
            var cmpId = Ext.id();
            var tabcomponent = {
                xtype: 'tabpanel',
                id: cmpId,
                activeTab: 0,
                deferredRender: false,
                defaults: {
                    hideMode: 'offsets'
                },
                items: componentItems
            };
            return tabcomponent;
        }
        return componentItems;
    },

    renderLayout: function(viewportItems) {
        var me = this;
        Ext.create('Ext.container.Container', {
            layout: 'border',
            items: viewportItems,
            renderTo: me.wrapperId,
            height: '100%',
            width: '100%'
        });
    },

    getMapId: function() {
        return this.mapId;
    },

    getComponentList: function() {
        return this.componentList;
    }
});
<|endoftext|>


<commit_before>'use strict'; // eslint-disable-line

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const BabiliPlugin = require('babili-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

const nodeEnv = process.env.NODE_ENV || 'development';
const isDev = nodeEnv !== 'production';

const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./WIT.config')).development(isDev);

// Disable CSSModules here
const CSSModules = true;
// Disable js lint error terminating here
const eslint = true;
// Disable style lint error terminating here
const stylelint = true;
// Register vendors here
const vendor = [
  'react',
  'react-dom',
  'redux',
  'react-redux',
  'redux-thunk',
  'react-hot-loader',
  'react-router-dom',
  'history',
  'react-router-redux',
  'react-helmet',
  'axios',
  'redbox-react',
  'chalk',
  'lodash',
  'babel-polyfill', // Support promise for IE browser (for prod)
];

// Setting the plugins for development/prodcution
const getPlugins = () => {
  // Common
  const plugins = [
    new ExtractTextPlugin({
      filename: '[name].[contenthash:8].css',
      allChunks: true,
      disable: isDev, // Disable css extracting on development
      ignoreOrder: CSSModules,
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        // Javascript lint
        eslint: { failOnError: eslint },
        debug: isDev,
        minimize: !isDev,
      },
    }),
    // Style lint
    new StyleLintPlugin({ syntax: 'scss', failOnError: stylelint }),
    // Setup enviorment variables for client
    new webpack.EnvironmentPlugin({ NODE_ENV: JSON.stringify(nodeEnv) }),
    // Setup global variables for client
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEV__: isDev,
    }),
    new webpack.NoEmitOnErrorsPlugin(),
    webpackIsomorphicToolsPlugin,
  ];

  if (isDev) { // For development
    plugins.push(
      new webpack.HotModuleReplacementPlugin(),
      // Prints more readable module names in the browser console on HMR updates
      new webpack.NamedModulesPlugin(),
      new webpack.IgnorePlugin(/webpack-stats\.json$/) // eslint-disable-line comma-dangle
    );
  } else {
    plugins.push( // For production
      new BabiliPlugin(),
      new webpack.HashedModuleIdsPlugin(),
      new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity }),
      new webpack.optimize.ModuleConcatenationPlugin(),
      new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.jsx?$|\.css$|\.(scss|sass)$|\.html$/,
        threshold: 10240,
        minRatio: 0.8,
        deleteOriginalAssets: true,
      }) // eslint-disable-line comma-dangle
    );
  }

  return plugins;
};

// Setting the entry for development/prodcution
const getEntry = () => {
  // For development
  let entry = [
    'babel-polyfill', // Support promise for IE browser (for dev)
    'react-hot-loader/patch',
    'webpack-hot-middleware/client?reload=true',
    './src/client.js',
  ];

  // For prodcution
  if (!isDev) {
    entry = {
      main: './src/client.js',
      // Register vendors here
      vendor,
    };
  }

  return entry;
};

// Setting webpack config
module.exports = {
  name: 'client',
  target: 'web',
  cache: isDev,
  devtool: isDev ? 'cheap-module-eval-source-map' : 'hidden-source-map',
  context: path.join(process.cwd()),
  entry: getEntry(),
  output: {
    path: path.join(process.cwd(), './public/assets'),
    publicPath: '/assets/',
    // Don't use chunkhash in development it will increase compilation time
    filename: isDev ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDev ? '[name].chunk.js' : '[name].[chunkhash:8].chunk.js',
    pathinfo: isDev,
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        enforce: 'pre',
        exclude: /node_modules/,
        loader: 'eslint',
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        options: {
          cacheDirectory: isDev,
          babelrc: false,
          presets: [['env', { modules: false }], 'react', 'stage-0'],
          env: { production: { plugins: ['transform-remove-console'] } },
          plugins: ['react-hot-loader/babel'],
        },
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            {
              loader: 'css',
              options: {
                importLoaders: 1,
                sourceMap: true,
                modules: CSSModules,
                // "context" and "localIdentName" need to be the same with server config,
                // or the style will flick when page first loaded
                context: path.join(process.cwd(), './src'),
                localIdentName: '[name]__[local]___[hash:base64:5]',
                minimize: !isDev,
              },
            },
            { loader: 'postcss', options: { sourceMap: true } },
          ],
        }),
      },
      {
        test: /\.(scss|sass)$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            {
              loader: 'css',
              options: {
                importLoaders: 2,
                sourceMap: true,
                modules: CSSModules,
                context: path.join(process.cwd(), './src'),
                localIdentName: '[name]__[local]___[hash:base64:5]',
                minimize: !isDev,
              },
            },
            { loader: 'postcss', options: { sourceMap: true } },
            {
              loader: 'sass',
              options: {
                outputStyle: 'expanded',
                sourceMap: true,
                sourceMapContents: !isDev,
              },
            },
          ],
        }),
      },
      {
        test: /\.(woff2?|ttf|eot|svg)$/,
        loader: 'url',
        options: { limit: 10000 },
      },
      {
        test: webpackIsomorphicToolsPlugin.regular_expression('images'),
        // Any image below or equal to 10K will be converted to inline base64 instead
        use: [
          {
            loader: 'url',
            options: { limit: 10240 },
          },
          // Using for image optimization
          {
            loader: 'image-webpack',
            options: { bypassOnDebug: true },
          },
        ],
      },
    ],
  },
  plugins: getPlugins(),
  resolveLoader: {
    // Use loaders without the -loader suffix
    moduleExtensions: ['-loader'],
  },
  resolve: {
    modules: ['src', 'node_modules'],
    descriptionFiles: ['package.json'],
    extensions: ['.js', '.jsx', '.json'],
  },
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.github.io/docs/configuration.html#node
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    vm: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};
<commit_msg>Refine css modules format<commit_after>'use strict'; // eslint-disable-line

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const BabiliPlugin = require('babili-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

const nodeEnv = process.env.NODE_ENV || 'development';
const isDev = nodeEnv !== 'production';

const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./WIT.config')).development(isDev);

// Disable CSSModules here
const CSSModules = true;
// Disable js lint error terminating here
const eslint = true;
// Disable style lint error terminating here
const stylelint = true;
// Register vendors here
const vendor = [
  'react',
  'react-dom',
  'redux',
  'react-redux',
  'redux-thunk',
  'react-hot-loader',
  'react-router-dom',
  'history',
  'react-router-redux',
  'react-helmet',
  'axios',
  'redbox-react',
  'chalk',
  'lodash',
  'babel-polyfill', // Support promise for IE browser (for prod)
];

// Setting the plugins for development/prodcution
const getPlugins = () => {
  // Common
  const plugins = [
    new ExtractTextPlugin({
      filename: '[name].[contenthash:8].css',
      allChunks: true,
      disable: isDev, // Disable css extracting on development
      ignoreOrder: CSSModules,
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        // Javascript lint
        eslint: { failOnError: eslint },
        debug: isDev,
        minimize: !isDev,
      },
    }),
    // Style lint
    new StyleLintPlugin({ syntax: 'scss', failOnError: stylelint }),
    // Setup enviorment variables for client
    new webpack.EnvironmentPlugin({ NODE_ENV: JSON.stringify(nodeEnv) }),
    // Setup global variables for client
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEV__: isDev,
    }),
    new webpack.NoEmitOnErrorsPlugin(),
    webpackIsomorphicToolsPlugin,
  ];

  if (isDev) { // For development
    plugins.push(
      new webpack.HotModuleReplacementPlugin(),
      // Prints more readable module names in the browser console on HMR updates
      new webpack.NamedModulesPlugin(),
      new webpack.IgnorePlugin(/webpack-stats\.json$/) // eslint-disable-line comma-dangle
    );
  } else {
    plugins.push( // For production
      new BabiliPlugin(),
      new webpack.HashedModuleIdsPlugin(),
      new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity }),
      new webpack.optimize.ModuleConcatenationPlugin(),
      new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.jsx?$|\.css$|\.(scss|sass)$|\.html$/,
        threshold: 10240,
        minRatio: 0.8,
        deleteOriginalAssets: true,
      }) // eslint-disable-line comma-dangle
    );
  }

  return plugins;
};

// Setting the entry for development/prodcution
const getEntry = () => {
  // For development
  let entry = [
    'babel-polyfill', // Support promise for IE browser (for dev)
    'react-hot-loader/patch',
    'webpack-hot-middleware/client?reload=true',
    './src/client.js',
  ];

  // For prodcution
  if (!isDev) {
    entry = {
      main: './src/client.js',
      // Register vendors here
      vendor,
    };
  }

  return entry;
};

// Setting webpack config
module.exports = {
  name: 'client',
  target: 'web',
  cache: isDev,
  devtool: isDev ? 'cheap-module-eval-source-map' : 'hidden-source-map',
  context: path.join(process.cwd()),
  entry: getEntry(),
  output: {
    path: path.join(process.cwd(), './public/assets'),
    publicPath: '/assets/',
    // Don't use chunkhash in development it will increase compilation time
    filename: isDev ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDev ? '[name].chunk.js' : '[name].[chunkhash:8].chunk.js',
    pathinfo: isDev,
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        enforce: 'pre',
        exclude: /node_modules/,
        loader: 'eslint',
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        options: {
          cacheDirectory: isDev,
          babelrc: false,
          presets: [['env', { modules: false }], 'react', 'stage-0'],
          env: { production: { plugins: ['transform-remove-console'] } },
          plugins: ['react-hot-loader/babel'],
        },
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            {
              loader: 'css',
              options: {
                importLoaders: 1,
                sourceMap: true,
                modules: CSSModules,
                // "context" and "localIdentName" need to be the same with server config,
                // or the style will flick when page first loaded
                context: path.join(process.cwd(), './src'),
                localIdentName: '[name]__[local]--[hash:base64:5]',
                minimize: !isDev,
              },
            },
            { loader: 'postcss', options: { sourceMap: true } },
          ],
        }),
      },
      {
        test: /\.(scss|sass)$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            {
              loader: 'css',
              options: {
                importLoaders: 2,
                sourceMap: true,
                modules: CSSModules,
                context: path.join(process.cwd(), './src'),
                localIdentName: '[name]__[local]--[hash:base64:5]',
                minimize: !isDev,
              },
            },
            { loader: 'postcss', options: { sourceMap: true } },
            {
              loader: 'sass',
              options: {
                outputStyle: 'expanded',
                sourceMap: true,
                sourceMapContents: !isDev,
              },
            },
          ],
        }),
      },
      {
        test: /\.(woff2?|ttf|eot|svg)$/,
        loader: 'url',
        options: { limit: 10000 },
      },
      {
        test: webpackIsomorphicToolsPlugin.regular_expression('images'),
        // Any image below or equal to 10K will be converted to inline base64 instead
        use: [
          {
            loader: 'url',
            options: { limit: 10240 },
          },
          // Using for image optimization
          {
            loader: 'image-webpack',
            options: { bypassOnDebug: true },
          },
        ],
      },
    ],
  },
  plugins: getPlugins(),
  resolveLoader: {
    // Use loaders without the -loader suffix
    moduleExtensions: ['-loader'],
  },
  resolve: {
    modules: ['src', 'node_modules'],
    descriptionFiles: ['package.json'],
    extensions: ['.js', '.jsx', '.json'],
  },
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.github.io/docs/configuration.html#node
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    vm: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};
<|endoftext|>


<commit_before>//__BEGIN_LICENSE__
// Copyright (c) 2015, United States Government, as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All rights reserved.
//
// The xGDS platform is 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.
//__END_LICENSE__

;(function($, undefined) {
     "use strict";
     $.ui.fancytree.registerExtension({
         name: "transparency_slider",
         version: "0.0.A",

         /* We overload nodeRenderTitle to apply the slider to each node*/
         nodeRenderTitle: function(ctx, title) {
            var node = ctx.node;
            this._superApply(arguments);

            if (node.data.transparency != undefined)
            {
            	var sliderID =  node.key + '_slider';
            	var sliderHtml = '

'
                $("span.fancytree-title", node.span).append(' ').append( $(sliderHtml) );
            }
         }
     });
 }(jQuery));

transparencySlidersVisible = false;
persistTransparency = false;

handleTransparencySliderChange = function(event, ui) {
	var newValue = ui.value;
	var node_id = ui.handle.parentElement.id.substring(0, ui.handle.parentElement.id.length - 7);
	var node = app.tree.getNodeByKey(node_id);
	if (node.mapView != undefined) {
		node.mapView.setTransparency(newValue);
	}
	// set the printed value
	var transparencyValueID = '#' + node_id + '_transparencyValue';
	var transparencyValueSpan = $(ui.handle.parentElement.parentElement).find(transparencyValueID);
	$(transparencyValueSpan).html(newValue);

	if (!persistTransparency) {
		// set the cookie
		Cookies.set(node_id, {transparency:newValue});
	}
};

saveTransparency = function(event, ui){
	// save the transparency to the server when the slider stops moving
	var newValue = ui.value;
	var node_id = ui.handle.parentElement.id.substring(0, ui.handle.parentElement.id.length - 7);
	var node = app.tree.getNodeByKey(node_id);
	theUrl = '/xgds_map_server/setTransparency/' + node_id + '/' + node.data.type + '/' + newValue;
	$.ajax({
        url: theUrl,
        dataType: "json",
        error: function(data){
        	alert('Problem saving transparency.');
        }
      });
};

showTransparencySliders = function(node){
	node.visit(function(node) {
		if (node.data.transparency != undefined){
			var el = $(node.li)
			var value_span = el.find(".transparency_value");

			if (value_span.length == 0){
				var slider_div = el.find(".transparency_slider");
				var theSlider = slider_div.slider({value:node.data.transparency,
					   							   slide: handleTransparencySliderChange});
				if (persistTransparency){
					theSlider.on('slidestop', saveTransparency);
				}

				// add the value
				var transparencyValueID = node.key + '_transparencyValue';
				var transparencyHtml = '' + node.data.transparency + '';
				$(slider_div).parent().append($(transparencyHtml));
			} else {
				var slider_div = $(value_span).prev();
				slider_div.toggle();
				value_span.toggle();
			}
		}
		return true;
	});
};

toggleTransparencySliders = function(rootNode) {
	transparencySlidersVisible = !transparencySlidersVisible;
	if (transparencySlidersVisible){
		if (rootNode == undefined){
			rootNode = app.tree.rootNode;
		}
		showTransparencySliders(rootNode);
	} else {
		$(".transparency_value").hide();
		$(".transparency_slider").hide(); //.slider("destroy");
	}
}<commit_msg>check for null node before looking for its data when saving transparency value<commit_after>//__BEGIN_LICENSE__
// Copyright (c) 2015, United States Government, as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All rights reserved.
//
// The xGDS platform is 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.
//__END_LICENSE__

;(function($, undefined) {
     "use strict";
     $.ui.fancytree.registerExtension({
         name: "transparency_slider",
         version: "0.0.A",

         /* We overload nodeRenderTitle to apply the slider to each node*/
         nodeRenderTitle: function(ctx, title) {
            var node = ctx.node;
            this._superApply(arguments);

            if (node.data.transparency != undefined)
            {
            	var sliderID =  node.key + '_slider';
            	var sliderHtml = '

'
                $("span.fancytree-title", node.span).append(' ').append( $(sliderHtml) );
            }
         }
     });
 }(jQuery));

transparencySlidersVisible = false;
persistTransparency = false;

handleTransparencySliderChange = function(event, ui) {
	var newValue = ui.value;
	var node_id = ui.handle.parentElement.id.substring(0, ui.handle.parentElement.id.length - 7);
	var node = app.tree.getNodeByKey(node_id);
	if (node.mapView != undefined) {
		node.mapView.setTransparency(newValue);
	}
	// set the printed value
	var transparencyValueID = '#' + node_id + '_transparencyValue';
	var transparencyValueSpan = $(ui.handle.parentElement.parentElement).find(transparencyValueID);
	$(transparencyValueSpan).html(newValue);

	if (!persistTransparency) {
		// set the cookie
		Cookies.set(node_id, {transparency:newValue});
	}
};

saveTransparency = function(event, ui){
	// save the transparency to the server when the slider stops moving
	var newValue = ui.value;
	var node_id = ui.handle.parentElement.id.substring(0, ui.handle.parentElement.id.length - 7);
	var node = app.tree.getNodeByKey(node_id);
	if (node != null) {
		theUrl = '/xgds_map_server/setTransparency/' + node_id + '/' + node.data.type + '/' + newValue;
		$.ajax({
	        url: theUrl,
	        dataType: "json",
	        error: function(data){
	        	alert('Problem saving transparency.');
	        }
	      });
	}
};

showTransparencySliders = function(node){
	node.visit(function(node) {
		if (node.data.transparency != undefined){
			var el = $(node.li)
			var value_span = el.find(".transparency_value");

			if (value_span.length == 0){
				var slider_div = el.find(".transparency_slider");
				var theSlider = slider_div.slider({value:node.data.transparency,
					   							   slide: handleTransparencySliderChange});
				if (persistTransparency){
					theSlider.on('slidestop', saveTransparency);
				}

				// add the value
				var transparencyValueID = node.key + '_transparencyValue';
				var transparencyHtml = '' + node.data.transparency + '';
				$(slider_div).parent().append($(transparencyHtml));
			} else {
				var slider_div = $(value_span).prev();
				slider_div.toggle();
				value_span.toggle();
			}
		}
		return true;
	});
};

toggleTransparencySliders = function(rootNode) {
	transparencySlidersVisible = !transparencySlidersVisible;
	if (transparencySlidersVisible){
		if (rootNode == undefined){
			rootNode = app.tree.rootNode;
		}
		showTransparencySliders(rootNode);
	} else {
		$(".transparency_value").hide();
		$(".transparency_slider").hide(); //.slider("destroy");
	}
}<|endoftext|>


<commit_before>var FinanceApp = angular.module('FinanceApp', []);

function FinanceController () {
	console.log("foo");
}<commit_msg>adding controllers<commit_after>var FinanceApp = angular.module('FinanceApp', []);

FinanceApp.controller('FinanceController', function ($scope) {
	$scope.stocks = [
		{"company": "google", "name": "goog", "value": 1000.0},
		{"company": "facebook", "name": "fb", "value": 900.0},
		{"company": "twitter", "name": "tw", "value": 800.0},
	];
});<|endoftext|>


<commit_before>import createGuid from '../Core/createGuid.js';
import defaultValue from '../Core/defaultValue.js';
import defined from '../Core/defined.js';
import defineProperties from '../Core/defineProperties.js';
import destroyObject from '../Core/destroyObject.js';
import DeveloperError from '../Core/DeveloperError.js';

    /**
     * A collection of primitives.  This is most often used with {@link Scene#primitives},
     * but PrimitiveCollection is also a primitive itself so collections can
     * be added to collections forming a hierarchy.
     *
     * @alias PrimitiveCollection
     * @constructor
     *
     * @param {Object} [options] Object with the following properties:
     * @param {Boolean} [options.show=true] Determines if the primitives in the collection will be shown.
     * @param {Boolean} [options.destroyPrimitives=true] Determines if primitives in the collection are destroyed when they are removed.
     *
     * @example
     * var billboards = new Cesium.BillboardCollection();
     * var labels = new Cesium.LabelCollection();
     *
     * var collection = new Cesium.PrimitiveCollection();
     * collection.add(billboards);
     *
     * scene.primitives.add(collection);  // Add collection
     * scene.primitives.add(labels);      // Add regular primitive
     */
    function PrimitiveCollection(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        this._primitives = [];
        this._guid = createGuid();

        // Used by the OrderedGroundPrimitiveCollection
        this._zIndex = undefined;

        /**
         * Determines if primitives in this collection will be shown.
         *
         * @type {Boolean}
         * @default true
         */
        this.show = defaultValue(options.show, true);

        /**
         * Determines if primitives in the collection are destroyed when they are removed by
         * {@link PrimitiveCollection#destroy} or  {@link PrimitiveCollection#remove} or implicitly
         * by {@link PrimitiveCollection#removeAll}.
         *
         * @type {Boolean}
         * @default true
         *
         * @example
         * // Example 1. Primitives are destroyed by default.
         * var primitives = new Cesium.PrimitiveCollection();
         * var labels = primitives.add(new Cesium.LabelCollection());
         * primitives = primitives.destroy();
         * var b = labels.isDestroyed(); // true
         *
         * @example
         * // Example 2. Do not destroy primitives in a collection.
         * var primitives = new Cesium.PrimitiveCollection();
         * primitives.destroyPrimitives = false;
         * var labels = primitives.add(new Cesium.LabelCollection());
         * primitives = primitives.destroy();
         * var b = labels.isDestroyed(); // false
         * labels = labels.destroy();    // explicitly destroy
         */
        this.destroyPrimitives = defaultValue(options.destroyPrimitives, true);
    }

    defineProperties(PrimitiveCollection.prototype, {
        /**
         * Gets the number of primitives in the collection.
         *
         * @memberof PrimitiveCollection.prototype
         *
         * @type {Number}
         * @readonly
         */
        length : {
            get : function() {
                return this._primitives.length;
            }
        }
    });

    /**
     * Adds a primitive to the collection.
     *
     * @param {Object} primitive The primitive to add.
     * @param {Number} [index] the index to add the layer at.  If omitted, the primitive will
     *                         added at the bottom  of all existing primitives.
     * @returns {Object} The primitive added to the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @example
     * var billboards = scene.primitives.add(new Cesium.BillboardCollection());
     */
    PrimitiveCollection.prototype.add = function(primitive, index) {
        var hasIndex = defined(index);

        //>>includeStart('debug', pragmas.debug);
        if (!defined(primitive)) {
            throw new DeveloperError('primitive is required.');
        }
        if (hasIndex) {
            if (index < 0) {
                throw new DeveloperError('index must be greater than or equal to zero.');
            } else if (index > this._primitives.length) {
                throw new DeveloperError('index must be less than or equal to the number of primitives.');
            }
        }
        //>>includeEnd('debug');

        var external = (primitive._external = primitive._external || {});
        var composites = (external._composites = external._composites || {});
        composites[this._guid] = {
            collection : this
        };

        if (!hasIndex) {
            this._primitives.push(primitive);
        } else {
            this._primitives.splice(index, 0, primitive);
        }

        return primitive;
    };

    /**
     * Removes a primitive from the collection.
     *
     * @param {Object} [primitive] The primitive to remove.
     * @returns {Boolean} true if the primitive was removed; false if the primitive is undefined or was not found in the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * var billboards = scene.primitives.add(new Cesium.BillboardCollection());
     * scene.primitives.remove(p);  // Returns true
     *
     * @see PrimitiveCollection#destroyPrimitives
     */
    PrimitiveCollection.prototype.remove = function(primitive) {
        // PERFORMANCE_IDEA:  We can obviously make this a lot faster.
        if (this.contains(primitive)) {
            var index = this._primitives.indexOf(primitive);
            if (index !== -1) {
                this._primitives.splice(index, 1);

                delete primitive._external._composites[this._guid];

                if (this.destroyPrimitives) {
                    primitive.destroy();
                }

                return true;
            }
            // else ... this is not possible, I swear.
        }

        return false;
    };

    /**
     * Removes and destroys a primitive, regardless of destroyPrimitives setting.
     * @private
     */
    PrimitiveCollection.prototype.removeAndDestroy = function(primitive) {
        var removed = this.remove(primitive);
        if (removed && !this.destroyPrimitives) {
            primitive.destroy();
        }
        return removed;
    };

    /**
     * Removes all primitives in the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#destroyPrimitives
     */
    PrimitiveCollection.prototype.removeAll = function() {
        var primitives = this._primitives;
        var length = primitives.length;
        for (var i = 0; i < length; ++i) {
            delete primitives[i]._external._composites[this._guid];
            if (this.destroyPrimitives) {
                primitives[i].destroy();
            }
        }
        this._primitives = [];
    };

    /**
     * Determines if this collection contains a primitive.
     *
     * @param {Object} [primitive] The primitive to check for.
     * @returns {Boolean} true if the primitive is in the collection; false if the primitive is undefined or was not found in the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#get
     */
    PrimitiveCollection.prototype.contains = function(primitive) {
        return !!(defined(primitive) &&
                  primitive._external &&
                  primitive._external._composites &&
                  primitive._external._composites[this._guid]);
    };

    function getPrimitiveIndex(compositePrimitive, primitive) {
        //>>includeStart('debug', pragmas.debug);
        if (!compositePrimitive.contains(primitive)) {
            throw new DeveloperError('primitive is not in this collection.');
        }
        //>>includeEnd('debug');

        return compositePrimitive._primitives.indexOf(primitive);
    }

    /**
     * Raises a primitive "up one" in the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive up one.
     *
     * @param {Object} [primitive] The primitive to raise.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#raiseToTop
     * @see PrimitiveCollection#lower
     * @see PrimitiveCollection#lowerToBottom
     */
    PrimitiveCollection.prototype.raise = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== primitives.length - 1) {
                var p = primitives[index];
                primitives[index] = primitives[index + 1];
                primitives[index + 1] = p;
            }
        }
    };

    /**
     * Raises a primitive to the "top" of the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive to the top.
     *
     * @param {Object} [primitive] The primitive to raise the top.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#raise
     * @see PrimitiveCollection#lower
     * @see PrimitiveCollection#lowerToBottom
     */
    PrimitiveCollection.prototype.raiseToTop = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== primitives.length - 1) {
                // PERFORMANCE_IDEA:  Could be faster
                primitives.splice(index, 1);
                primitives.push(primitive);
            }
        }
    };

    /**
     * Lowers a primitive "down one" in the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive down one.
     *
     * @param {Object} [primitive] The primitive to lower.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#lowerToBottom
     * @see PrimitiveCollection#raise
     * @see PrimitiveCollection#raiseToTop
     */
    PrimitiveCollection.prototype.lower = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== 0) {
                var p = primitives[index];
                primitives[index] = primitives[index - 1];
                primitives[index - 1] = p;
            }
        }
    };

    /**
     * Lowers a primitive to the "bottom" of the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive to the bottom.
     *
     * @param {Object} [primitive] The primitive to lower to the bottom.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#lower
     * @see PrimitiveCollection#raise
     * @see PrimitiveCollection#raiseToTop
     */
    PrimitiveCollection.prototype.lowerToBottom = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== 0) {
                // PERFORMANCE_IDEA:  Could be faster
                primitives.splice(index, 1);
                primitives.unshift(primitive);
            }
        }
    };

    /**
     * Returns the primitive in the collection at the specified index.
     *
     * @param {Number} index The zero-based index of the primitive to return.
     * @returns {Object} The primitive at the index.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * // Toggle the show property of every primitive in the collection.
     * var primitives = scene.primitives;
     * var length = primitives.length;
     * for (var i = 0; i < length; ++i) {
     *   var p = primitives.get(i);
     *   p.show = !p.show;
     * }
     *
     * @see PrimitiveCollection#length
     */
    PrimitiveCollection.prototype.get = function(index) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(index)) {
            throw new DeveloperError('index is required.');
        }
        //>>includeEnd('debug');

        return this._primitives[index];
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.update = function(frameState) {
        if (!this.show) {
            return;
        }

        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            primitives[i].update(frameState);
        }
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.prePassesUpdate = function(frameState) {
        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            var primitive = primitives[i];
            if (defined(primitive.prePassesUpdate)) {
                primitive.prePassesUpdate(frameState);
            }
        }
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.updateForPass = function(frameState, passState) {
        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            var primitive = primitives[i];
            if (defined(primitive.updateForPass)) {
                primitive.updateForPass(frameState, passState);
            }
        }
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.postPassesUpdate = function(frameState) {
        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            var primitive = primitives[i];
            if (defined(primitive.postPassesUpdate)) {
                primitive.postPassesUpdate(frameState);
            }
        }
    };

    /**
     * Returns true if this object was destroyed; otherwise, false.
     *

     * If this object was destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.
     *
     * @returns {Boolean} True if this object was destroyed; otherwise, false.
     *
     * @see PrimitiveCollection#destroy
     */
    PrimitiveCollection.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * Destroys the WebGL resources held by each primitive in this collection.  Explicitly destroying this
     * collection allows for deterministic release of WebGL resources, instead of relying on the garbage
     * collector to destroy this collection.
     *

     * Since destroying a collection destroys all the contained primitives, only destroy a collection
     * when you are sure no other code is still using any of the contained primitives.
     *

     * Once this collection is destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.  Therefore,
     * assign the return value (undefined) to the object as done in the example.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * primitives = primitives && primitives.destroy();
     *
     * @see PrimitiveCollection#isDestroyed
     */
    PrimitiveCollection.prototype.destroy = function() {
        this.removeAll();
        return destroyObject(this);
    };
export default PrimitiveCollection;
<commit_msg>Fixes PrimitiveCollection documentation issue<commit_after>import createGuid from '../Core/createGuid.js';
import defaultValue from '../Core/defaultValue.js';
import defined from '../Core/defined.js';
import defineProperties from '../Core/defineProperties.js';
import destroyObject from '../Core/destroyObject.js';
import DeveloperError from '../Core/DeveloperError.js';

    /**
     * A collection of primitives.  This is most often used with {@link Scene#primitives},
     * but PrimitiveCollection is also a primitive itself so collections can
     * be added to collections forming a hierarchy.
     *
     * @alias PrimitiveCollection
     * @constructor
     *
     * @param {Object} [options] Object with the following properties:
     * @param {Boolean} [options.show=true] Determines if the primitives in the collection will be shown.
     * @param {Boolean} [options.destroyPrimitives=true] Determines if primitives in the collection are destroyed when they are removed.
     *
     * @example
     * var billboards = new Cesium.BillboardCollection();
     * var labels = new Cesium.LabelCollection();
     *
     * var collection = new Cesium.PrimitiveCollection();
     * collection.add(billboards);
     *
     * scene.primitives.add(collection);  // Add collection
     * scene.primitives.add(labels);      // Add regular primitive
     */
    function PrimitiveCollection(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        this._primitives = [];
        this._guid = createGuid();

        // Used by the OrderedGroundPrimitiveCollection
        this._zIndex = undefined;

        /**
         * Determines if primitives in this collection will be shown.
         *
         * @type {Boolean}
         * @default true
         */
        this.show = defaultValue(options.show, true);

        /**
         * Determines if primitives in the collection are destroyed when they are removed by
         * {@link PrimitiveCollection#destroy} or  {@link PrimitiveCollection#remove} or implicitly
         * by {@link PrimitiveCollection#removeAll}.
         *
         * @type {Boolean}
         * @default true
         *
         * @example
         * // Example 1. Primitives are destroyed by default.
         * var primitives = new Cesium.PrimitiveCollection();
         * var labels = primitives.add(new Cesium.LabelCollection());
         * primitives = primitives.destroy();
         * var b = labels.isDestroyed(); // true
         *
         * @example
         * // Example 2. Do not destroy primitives in a collection.
         * var primitives = new Cesium.PrimitiveCollection();
         * primitives.destroyPrimitives = false;
         * var labels = primitives.add(new Cesium.LabelCollection());
         * primitives = primitives.destroy();
         * var b = labels.isDestroyed(); // false
         * labels = labels.destroy();    // explicitly destroy
         */
        this.destroyPrimitives = defaultValue(options.destroyPrimitives, true);
    }

    defineProperties(PrimitiveCollection.prototype, {
        /**
         * Gets the number of primitives in the collection.
         *
         * @memberof PrimitiveCollection.prototype
         *
         * @type {Number}
         * @readonly
         */
        length : {
            get : function() {
                return this._primitives.length;
            }
        }
    });

    /**
     * Adds a primitive to the collection.
     *
     * @param {Object} primitive The primitive to add.
     * @param {Number} [index] the index to add the layer at.  If omitted, the primitive will
     *                         added at the bottom  of all existing primitives.
     * @returns {Object} The primitive added to the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @example
     * var billboards = scene.primitives.add(new Cesium.BillboardCollection());
     */
    PrimitiveCollection.prototype.add = function(primitive, index) {
        var hasIndex = defined(index);

        //>>includeStart('debug', pragmas.debug);
        if (!defined(primitive)) {
            throw new DeveloperError('primitive is required.');
        }
        if (hasIndex) {
            if (index < 0) {
                throw new DeveloperError('index must be greater than or equal to zero.');
            } else if (index > this._primitives.length) {
                throw new DeveloperError('index must be less than or equal to the number of primitives.');
            }
        }
        //>>includeEnd('debug');

        var external = (primitive._external = primitive._external || {});
        var composites = (external._composites = external._composites || {});
        composites[this._guid] = {
            collection : this
        };

        if (!hasIndex) {
            this._primitives.push(primitive);
        } else {
            this._primitives.splice(index, 0, primitive);
        }

        return primitive;
    };

    /**
     * Removes a primitive from the collection.
     *
     * @param {Object} [primitive] The primitive to remove.
     * @returns {Boolean} true if the primitive was removed; false if the primitive is undefined or was not found in the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * var billboards = scene.primitives.add(new Cesium.BillboardCollection());
     * scene.primitives.remove(billboards);  // Returns true
     *
     * @see PrimitiveCollection#destroyPrimitives
     */
    PrimitiveCollection.prototype.remove = function(primitive) {
        // PERFORMANCE_IDEA:  We can obviously make this a lot faster.
        if (this.contains(primitive)) {
            var index = this._primitives.indexOf(primitive);
            if (index !== -1) {
                this._primitives.splice(index, 1);

                delete primitive._external._composites[this._guid];

                if (this.destroyPrimitives) {
                    primitive.destroy();
                }

                return true;
            }
            // else ... this is not possible, I swear.
        }

        return false;
    };

    /**
     * Removes and destroys a primitive, regardless of destroyPrimitives setting.
     * @private
     */
    PrimitiveCollection.prototype.removeAndDestroy = function(primitive) {
        var removed = this.remove(primitive);
        if (removed && !this.destroyPrimitives) {
            primitive.destroy();
        }
        return removed;
    };

    /**
     * Removes all primitives in the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#destroyPrimitives
     */
    PrimitiveCollection.prototype.removeAll = function() {
        var primitives = this._primitives;
        var length = primitives.length;
        for (var i = 0; i < length; ++i) {
            delete primitives[i]._external._composites[this._guid];
            if (this.destroyPrimitives) {
                primitives[i].destroy();
            }
        }
        this._primitives = [];
    };

    /**
     * Determines if this collection contains a primitive.
     *
     * @param {Object} [primitive] The primitive to check for.
     * @returns {Boolean} true if the primitive is in the collection; false if the primitive is undefined or was not found in the collection.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#get
     */
    PrimitiveCollection.prototype.contains = function(primitive) {
        return !!(defined(primitive) &&
                  primitive._external &&
                  primitive._external._composites &&
                  primitive._external._composites[this._guid]);
    };

    function getPrimitiveIndex(compositePrimitive, primitive) {
        //>>includeStart('debug', pragmas.debug);
        if (!compositePrimitive.contains(primitive)) {
            throw new DeveloperError('primitive is not in this collection.');
        }
        //>>includeEnd('debug');

        return compositePrimitive._primitives.indexOf(primitive);
    }

    /**
     * Raises a primitive "up one" in the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive up one.
     *
     * @param {Object} [primitive] The primitive to raise.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#raiseToTop
     * @see PrimitiveCollection#lower
     * @see PrimitiveCollection#lowerToBottom
     */
    PrimitiveCollection.prototype.raise = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== primitives.length - 1) {
                var p = primitives[index];
                primitives[index] = primitives[index + 1];
                primitives[index + 1] = p;
            }
        }
    };

    /**
     * Raises a primitive to the "top" of the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive to the top.
     *
     * @param {Object} [primitive] The primitive to raise the top.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#raise
     * @see PrimitiveCollection#lower
     * @see PrimitiveCollection#lowerToBottom
     */
    PrimitiveCollection.prototype.raiseToTop = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== primitives.length - 1) {
                // PERFORMANCE_IDEA:  Could be faster
                primitives.splice(index, 1);
                primitives.push(primitive);
            }
        }
    };

    /**
     * Lowers a primitive "down one" in the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive down one.
     *
     * @param {Object} [primitive] The primitive to lower.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#lowerToBottom
     * @see PrimitiveCollection#raise
     * @see PrimitiveCollection#raiseToTop
     */
    PrimitiveCollection.prototype.lower = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== 0) {
                var p = primitives[index];
                primitives[index] = primitives[index - 1];
                primitives[index - 1] = p;
            }
        }
    };

    /**
     * Lowers a primitive to the "bottom" of the collection.  If all primitives in the collection are drawn
     * on the globe surface, this visually moves the primitive to the bottom.
     *
     * @param {Object} [primitive] The primitive to lower to the bottom.
     *
     * @exception {DeveloperError} primitive is not in this collection.
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see PrimitiveCollection#lower
     * @see PrimitiveCollection#raise
     * @see PrimitiveCollection#raiseToTop
     */
    PrimitiveCollection.prototype.lowerToBottom = function(primitive) {
        if (defined(primitive)) {
            var index = getPrimitiveIndex(this, primitive);
            var primitives = this._primitives;

            if (index !== 0) {
                // PERFORMANCE_IDEA:  Could be faster
                primitives.splice(index, 1);
                primitives.unshift(primitive);
            }
        }
    };

    /**
     * Returns the primitive in the collection at the specified index.
     *
     * @param {Number} index The zero-based index of the primitive to return.
     * @returns {Object} The primitive at the index.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * // Toggle the show property of every primitive in the collection.
     * var primitives = scene.primitives;
     * var length = primitives.length;
     * for (var i = 0; i < length; ++i) {
     *   var p = primitives.get(i);
     *   p.show = !p.show;
     * }
     *
     * @see PrimitiveCollection#length
     */
    PrimitiveCollection.prototype.get = function(index) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(index)) {
            throw new DeveloperError('index is required.');
        }
        //>>includeEnd('debug');

        return this._primitives[index];
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.update = function(frameState) {
        if (!this.show) {
            return;
        }

        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            primitives[i].update(frameState);
        }
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.prePassesUpdate = function(frameState) {
        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            var primitive = primitives[i];
            if (defined(primitive.prePassesUpdate)) {
                primitive.prePassesUpdate(frameState);
            }
        }
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.updateForPass = function(frameState, passState) {
        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            var primitive = primitives[i];
            if (defined(primitive.updateForPass)) {
                primitive.updateForPass(frameState, passState);
            }
        }
    };

    /**
     * @private
     */
    PrimitiveCollection.prototype.postPassesUpdate = function(frameState) {
        var primitives = this._primitives;
        // Using primitives.length in the loop is a temporary workaround
        // to allow quadtree updates to add and remove primitives in
        // update().  This will be changed to manage added and removed lists.
        for (var i = 0; i < primitives.length; ++i) {
            var primitive = primitives[i];
            if (defined(primitive.postPassesUpdate)) {
                primitive.postPassesUpdate(frameState);
            }
        }
    };

    /**
     * Returns true if this object was destroyed; otherwise, false.
     *

     * If this object was destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.
     *
     * @returns {Boolean} True if this object was destroyed; otherwise, false.
     *
     * @see PrimitiveCollection#destroy
     */
    PrimitiveCollection.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * Destroys the WebGL resources held by each primitive in this collection.  Explicitly destroying this
     * collection allows for deterministic release of WebGL resources, instead of relying on the garbage
     * collector to destroy this collection.
     *

     * Since destroying a collection destroys all the contained primitives, only destroy a collection
     * when you are sure no other code is still using any of the contained primitives.
     *

     * Once this collection is destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.  Therefore,
     * assign the return value (undefined) to the object as done in the example.
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * primitives = primitives && primitives.destroy();
     *
     * @see PrimitiveCollection#isDestroyed
     */
    PrimitiveCollection.prototype.destroy = function() {
        this.removeAll();
        return destroyObject(this);
    };
export default PrimitiveCollection;
<|endoftext|>


<commit_before>import React from 'react';
import { styled } from 'olymp';

export default styled(({ theme, size = 1, columns = 3, background = theme.dark5, color = theme.dark2, padding }) => ({
  width: `${100 / columns * size}%`,
  float: 'left',
  padding: `${theme.space3} 0 0 ${theme.space3}`,
  position: 'relative',
  textAlign: 'justify',
  display: 'flex',
  flexDirection: 'column',
  '> h2': {
    marginBottom: theme.space1,
    fontWeight: 300,
    fontStyle: 'italic',
  },
  '> p': {
    backgroundColor: background,
    color,
    padding: padding || `${theme.space2} 1.33rem 1.33rem ${theme.space2}`,
    borderBottomRightRadius: 100,
    display: 'flex',
    hyphens: 'auto',
    flex: '1 1',
    minHeight: 80,
    '> iframe': {
      display: 'block',
      borderBottomRightRadius: 100,
    }
  },
  onAfter: {
    content: '""',
    position: 'absolute',
    width: 33,
    height: 33,
    backgroundColor: theme.dark4,
    bottom: 0,
    borderTopLeftRadius: 30,
    right: 0,
  },
  onHover: {
    onAfter: {
      backgroundColor: theme.color,
    },
  },
  ifSmallDown: {
    width: '100%',
    float: 'none',
    paddingX: theme.space2,
    paddingTop: theme.space2,
    paddingBottom: theme.space0,
  }
}), ({ className, title, children }) => (

{title}

{children}

), p => p);
<commit_msg>small fix<commit_after>import React from 'react';
import { styled } from 'olymp';
import { fade } from 'olymp-fela';

export default styled(({ theme, size = 1, columns = 3, background = theme.dark5, color = theme.dark2, padding = `${theme.space2} 1.33rem 1.33rem ${theme.space2}` }) => ({
  width: `${100 / columns * size}%`,
  float: 'left',
  padding: `${theme.space3} 0 0 ${theme.space3}`,
  position: 'relative',
  textAlign: 'justify',
  display: 'flex',
  flexDirection: 'column',
  '> h2': {
    marginBottom: theme.space1,
    fontWeight: 300,
    fontStyle: 'italic',
  },
  '> p': {
    backgroundColor: background,
    color,
    padding,
    borderBottomRightRadius: 100,
    display: 'flex',
    hyphens: 'auto',
    flex: '1 1',
    minHeight: 90,
    '> iframe': {
      display: 'block',
      borderBottomRightRadius: 100,
    }
  },
  onAfter: {
    content: '""',
    position: 'absolute',
    width: 33,
    height: 33,
    backgroundColor: theme.dark4,
    bottom: 0,
    borderTopLeftRadius: 30,
    right: 0,
  },
  onHover: {
    onAfter: {
      backgroundColor: theme.color,
    },
  },
  ifSmallDown: {
    width: '100%',
    float: 'none',
    paddingX: theme.space2,
    paddingTop: theme.space2,
    paddingBottom: theme.space0,
  }
}), ({ className, title, children }) => (

{title}

{children}

), p => p);
<|endoftext|>


<commit_before>var SocketHelper = require('../helpers/SocketHelper');
var Room = require('../models/Room');
var ServiceHandler = require('./ServiceHandler');
var io;
var rooms=[];

function SocketHandler(IO){
    io = IO;
}

SocketHandler.prototype.HandleSocketConnect = function(){
    io.sockets.on('connection', function (socket){
    	currentRoomName = FindAndJoinChatRoom(socket);
        AlertMemberJoined(socket,currentRoomName);
        RegisterMessageEvent(socket,currentRoomName);
    });
}

function FindAndJoinChatRoom(socket){
     var SocketQuery = socket.handshake.query;
     var UserName = SocketQuery.UserName;
     var latNum = parseFloat(SocketQuery.Lat).toFixed(2);
     var lonNum = parseFloat(SocketQuery.Lon).toFixed(2);
     var CurrentRoomName = latNum + " " + lonNum;
     var currentRoomNameKey = '';

     //check if room exists
     var foundRoomName = new SocketHelper(io.sockets).FindRoomInRange(latNum,lonNum)

     if(foundRoomName != '')
     {
        socket.join(foundRoomName);
        CurrentRoomName = foundRoomName;
        currentRoomNameKey = CurrentRoomName.replace(/[\s\-\.]/g, '').toString();
        socket.emit('title',rooms[currentRoomNameKey].Neighborhood + '(' + CurrentRoomName + ')');
        PushUpdatedMemberList(CurrentRoomName,UserName,rooms[currentRoomNameKey].Clients);
        RegisterLeaveEvent(socket,rooms[currentRoomNameKey],CurrentRoomName);
        RegisterDisconnectEvent(socket,rooms[currentRoomNameKey],CurrentRoomName);
     }
     else //no room close enough, create
     {
        socket.join(CurrentRoomName);
        currentRoomNameKey = CurrentRoomName.replace(/[\s\-\.]/g, '').toString();
        var serviceHandler = new ServiceHandler();
        serviceHandler.GetNeighborhoodByCoords(latNum,lonNum,function(neighborhood){
               rooms[currentRoomNameKey] = new Room(CurrentRoomName.toString(),neighborhood);
               socket.emit('title',rooms[currentRoomNameKey].Neighborhood + '(' + CurrentRoomName + ')');
               PushUpdatedMemberList(CurrentRoomName,UserName,rooms[currentRoomNameKey].Clients);
               RegisterLeaveEvent(socket,rooms[currentRoomNameKey],CurrentRoomName); //needs to be in callback so you leave correct room
               RegisterDisconnectEvent(socket,rooms[currentRoomNameKey],CurrentRoomName);
        });
     }

     return CurrentRoomName;
}

function AlertMemberJoined(socket,RoomName){
    socket.broadcast.to(RoomName).emit('joined', socket.handshake.query.UserName);
    socket.emit('selfjoined',socket.handshake.query.UserName + " (You)");
}

function RegisterMessageEvent(socket,RoomName){
     socket.on('message', function(data){
        if(data.indexOf('<script>') < 0)
        {
            io.to(RoomName).emit('message',data);
        }
        else
        {
            io.to(RoomName).emit('message',socket.handshake.query.UserName +" tried to inject javascript and FAILED");
        }
     });
}

function RegisterLeaveEvent(socket,existingRooms,currentRoomName){
     socket.on('leave', function() {
            HandleLeave(socket,existingRooms, currentRoomName);
        })
}

function RegisterDisconnectEvent(socket,room,currentRoomName){
     socket.on('disconnect', function() {
        if(typeof room.Clients != 'undefined' && room.Clients.indexOf(socket.handshake.query.UserName) > -1)
        {
            io.to(currentRoomName).emit('left',socket.handshake.query.UserName);
        }
    })
}

function PushUpdatedMemberList(roomName,userName,clients){
    clients.push(userName);
    io.to(roomName).emit('usersInRoomUpdate',clients);
}

function HandleLeave(socket,CurrentRoom,CurrentRoomName){
    socket.leave(CurrentRoomName); //leave room
    io.to(CurrentRoomName).emit('left',socket.handshake.query.UserName); //tell everyone i left
    socket.emit('selfLeft'); //let myself know i left
    if(typeof CurrentRoom.Clients != 'undefined')
    {
        var removeIndex = CurrentRoom.Clients.indexOf(socket.handshake.query.UserName);
        CurrentRoom.Clients.splice(removeIndex,1);
        io.to(CurrentRoomName).emit('usersInRoomUpdate',CurrentRoom.Clients); //remove me from room for everyone in it
        socket.emit('usersInRoomUpdate',CurrentRoom.Clients); //remove me from dead room list
    }
}

module.exports = SocketHandler;<commit_msg>Adding logging for coords<commit_after>var SocketHelper = require('../helpers/SocketHelper');
var Room = require('../models/Room');
var ServiceHandler = require('./ServiceHandler');
var io;
var rooms=[];

function SocketHandler(IO){
    io = IO;
}

SocketHandler.prototype.HandleSocketConnect = function(){
    io.sockets.on('connection', function (socket){
    	currentRoomName = FindAndJoinChatRoom(socket);
        AlertMemberJoined(socket,currentRoomName);
        RegisterMessageEvent(socket,currentRoomName);
    });
}

function FindAndJoinChatRoom(socket){
     var SocketQuery = socket.handshake.query;
     var UserName = SocketQuery.UserName;
     var latNum = parseFloat(SocketQuery.Lat).toFixed(2);
     var lonNum = parseFloat(SocketQuery.Lon).toFixed(2);
     console.log(latNum);
     console.log(lonNum);
     var CurrentRoomName = latNum + " " + lonNum;
     var currentRoomNameKey = '';

     //check if room exists
     var foundRoomName = new SocketHelper(io.sockets).FindRoomInRange(latNum,lonNum)

     if(foundRoomName != '')
     {
        socket.join(foundRoomName);
        CurrentRoomName = foundRoomName;
        currentRoomNameKey = CurrentRoomName.replace(/[\s\-\.]/g, '').toString();
        socket.emit('title',rooms[currentRoomNameKey].Neighborhood + '(' + CurrentRoomName + ')');
        PushUpdatedMemberList(CurrentRoomName,UserName,rooms[currentRoomNameKey].Clients);
        RegisterLeaveEvent(socket,rooms[currentRoomNameKey],CurrentRoomName);
        RegisterDisconnectEvent(socket,rooms[currentRoomNameKey],CurrentRoomName);
     }
     else //no room close enough, create
     {
        socket.join(CurrentRoomName);
        currentRoomNameKey = CurrentRoomName.replace(/[\s\-\.]/g, '').toString();
        var serviceHandler = new ServiceHandler();
        serviceHandler.GetNeighborhoodByCoords(latNum,lonNum,function(neighborhood){
               rooms[currentRoomNameKey] = new Room(CurrentRoomName.toString(),neighborhood);
               socket.emit('title',rooms[currentRoomNameKey].Neighborhood + '(' + CurrentRoomName + ')');
               PushUpdatedMemberList(CurrentRoomName,UserName,rooms[currentRoomNameKey].Clients);
               RegisterLeaveEvent(socket,rooms[currentRoomNameKey],CurrentRoomName); //needs to be in callback so you leave correct room
               RegisterDisconnectEvent(socket,rooms[currentRoomNameKey],CurrentRoomName);
        });
     }

     return CurrentRoomName;
}

function AlertMemberJoined(socket,RoomName){
    socket.broadcast.to(RoomName).emit('joined', socket.handshake.query.UserName);
    socket.emit('selfjoined',socket.handshake.query.UserName + " (You)");
}

function RegisterMessageEvent(socket,RoomName){
     socket.on('message', function(data){
        if(data.indexOf('<script>') < 0)
        {
            io.to(RoomName).emit('message',data);
        }
        else
        {
            io.to(RoomName).emit('message',socket.handshake.query.UserName +" tried to inject javascript and FAILED");
        }
     });
}

function RegisterLeaveEvent(socket,existingRooms,currentRoomName){
     socket.on('leave', function() {
            HandleLeave(socket,existingRooms, currentRoomName);
        })
}

function RegisterDisconnectEvent(socket,room,currentRoomName){
     socket.on('disconnect', function() {
        if(typeof room.Clients != 'undefined' && room.Clients.indexOf(socket.handshake.query.UserName) > -1)
        {
            io.to(currentRoomName).emit('left',socket.handshake.query.UserName);
        }
    })
}

function PushUpdatedMemberList(roomName,userName,clients){
    clients.push(userName);
    io.to(roomName).emit('usersInRoomUpdate',clients);
}

function HandleLeave(socket,CurrentRoom,CurrentRoomName){
    socket.leave(CurrentRoomName); //leave room
    io.to(CurrentRoomName).emit('left',socket.handshake.query.UserName); //tell everyone i left
    socket.emit('selfLeft'); //let myself know i left
    if(typeof CurrentRoom.Clients != 'undefined')
    {
        var removeIndex = CurrentRoom.Clients.indexOf(socket.handshake.query.UserName);
        CurrentRoom.Clients.splice(removeIndex,1);
        io.to(CurrentRoomName).emit('usersInRoomUpdate',CurrentRoom.Clients); //remove me from room for everyone in it
        socket.emit('usersInRoomUpdate',CurrentRoom.Clients); //remove me from dead room list
    }
}

module.exports = SocketHandler;<|endoftext|>