<commit_before>const path = require('path')
const fs = require('fs');
const glob = require('glob')
const webpack = require('webpack')

// webpack plugins
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CompressionPlugin = require("compression-webpack-plugin")
const GenSourceCode = require('./webpack.gensrc')
const WebpackI18nPlugin = require("./webpack.i18n");

const date = new Date()
const DEV_MODE = process.env.NODE_ENV !== 'production' && process.argv.indexOf('-p') === -1,
    BUILD_NUMBER = `${date.getYear() - 100}${date.getMonth() + 1}${date.getDate()}.${Math.ceil((date - new Date().setHours(0, 0, 0, 0)) / 8641)}`

/*---------------------------------------------------
 Define which directories are included from the build based on the config file
 ---------------------------------------------------*/

const EXCLUDE_FROM_BUILD = [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, 'test'),
    path.resolve(__dirname, 'server'),
    path.resolve(__dirname, 'build'),
    path.resolve(__dirname, 'extensions'),
    path.resolve(__dirname, 'client/components/ui'),
    path.resolve(__dirname, './api')]

const INCLUDE_IN_BUILD = []

const APP_CONFIG = require('./buildconfig.json')
const PACKAGE_JSON = require('./package.json')

const APP_VALUES = {
    DEV_MODE,
    BUILD_NUMBER,
    APP_NAME: PACKAGE_JSON.name,
    APP_VERSION: PACKAGE_JSON.version,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_COLOR: '#2196f3',
    ...APP_CONFIG.options
}

if (APP_CONFIG.extensions) {
    for (const extensionName in APP_CONFIG.extensions) {
        if (APP_CONFIG.extensions[extensionName].active) {
            INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'extensions/' + extensionName))
        }
    }
}

if (APP_CONFIG.ui) {
    APP_CONFIG.ui.forEach(ui => {
        INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'client/components/ui/impl/' + ui.impl))
    })
}

const excludeFunction = (path) => {

    for (let i = 0; i < EXCLUDE_FROM_BUILD.length; i++) {
        if (path.indexOf(EXCLUDE_FROM_BUILD[i]) === 0) {
            // it belongs to the excluded files

            for (let j = 0; j < INCLUDE_IN_BUILD.length; j++) {
                if (path.indexOf(INCLUDE_IN_BUILD[j]) === 0) {
                    // it is an exception and should be included anyway
                    return false
                }
            }

            return true
        }
    }
    return false
}

const replacePlaceholders = (content, path) => {

    const result = new Function('const {' + Object.keys(APP_VALUES).join(',') + '} = this.APP_VALUES;return `' + content + '`').call({APP_VALUES})
    return result
}

const config = {
    entry: './client/index.js',
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].bundle.js?v=' + BUILD_NUMBER,
        chunkFilename: '[name].bundle.js?v=' + BUILD_NUMBER,
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: excludeFunction,
                loader: 'babel-loader'
            },
            {
                test: /\.global\.css$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.global\.less$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "less-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            }
        ]
    },
    plugins: [
        new GenSourceCode(APP_VALUES), /* Generate some source code based on the buildconfig.json file */
        new MiniCssExtractPlugin({
            filename: 'style.css',
            allChunks: true
        }), /* Extract css from bundle */
        new WebpackI18nPlugin({
            src: './**/*.tr.json',
            dest: '[name].js'
        })
    ],
    optimization: {
        /*splitChunks: {
         cacheGroups: {
         style: {
         name: 'style',
         test: (c) => {
         if (c.type === 'css/mini-extract') {
         const path = c._identifier
         //console.log(path.substring(path.lastIndexOf('/')+1))
         return true
         }
         return false
         },
         chunks: 'all',
         enforce: true
         }
         }
         },*/
        minimizer: []
    }/*optimization: {
     // We no not want to minimize our code.
     minimize: false
     }*/
}

const CopyWebpackPlugin = require('copy-webpack-plugin')
config.plugins.push(
    new CopyWebpackPlugin([
        {
            from: 'index.html', to: 'index.html',
            transform: replacePlaceholders
        },
        {
            from: 'index.min.html', to: 'index.min.html',
            transform: replacePlaceholders
        },
        {
            from: 'serviceworker.js', to: 'serviceworker.js',
            transform: replacePlaceholders
        },
        {
            from: 'manifest.json', to: 'manifest.json',
            transform: replacePlaceholders
        },
        {from: 'favicon.ico', to: 'favicon.ico'},
        {from: 'favicon.svg', to: 'favicon.svg'},
        {from: 'favicon-192x192.png', to: 'favicon-192x192.png'},
        {from: 'favicon-512x512.png', to: 'favicon-512x512.png'}
    ])
)

/**
 *  Developer / Debug Config
 */
if (DEV_MODE) {
    console.log('Build for developing')
    config.mode = 'development'

    const PORT = (process.env.PORT || 8080)
    const API_PORT = (process.env.API_PORT || 3000)

    config.devServer = {
        contentBase: [path.join(__dirname, ''), path.join(__dirname, 'static')],
        historyApiFallback: true,
        inline: true,
        hot: true,
        stats: 'errors-only',
        port: PORT,
        host: '0.0.0.0',
        proxy: {
            '/graphql': {target: `http://0.0.0.0:${API_PORT}`},
            '/ws': {
                target: `ws://localhost:${API_PORT}`,
                ws: true
            }
        }
    }

    /* For Debugging porpuses */
    config.devtool = 'eval'

    config.plugins.push(new webpack.HotModuleReplacementPlugin())

} else {
    console.log('Build for production')
    config.mode = 'production'

    config.plugins.push(
        new CompressionPlugin({
            minRatio: 0.95
        })
    )

    config.optimization.minimizer.push(
        new UglifyJSPlugin({
            uglifyOptions: {
                compress: {
                    drop_console: true
                },
                output: {
                    comments: false,
                    semicolons: true,
                    shebang: true,
                    beautify: false
                }
            }
        }))

    /*const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
     config.plugins.push(new BundleAnalyzerPlugin())*/

    //config.devtool = 'source-map'
    config.devtool = 'none'
}

module.exports = config

/* --port 8080 --hot --host 0.0.0.0 --content-base . */
<commit_msg>Small improvements<commit_after>const path = require('path')
const fs = require('fs');
const glob = require('glob')
const webpack = require('webpack')

// webpack plugins
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CompressionPlugin = require("compression-webpack-plugin")
const GenSourceCode = require('./webpack.gensrc')
const WebpackI18nPlugin = require("./webpack.i18n");

const date = new Date()
const DEV_MODE = process.env.NODE_ENV !== 'production' && process.argv.indexOf('-p') === -1,
    BUILD_NUMBER = `${date.getYear() - 100}${date.getMonth() + 1}${date.getDate()}.${Math.ceil((date - new Date().setHours(0, 0, 0, 0)) / 8641)}`

/*---------------------------------------------------
 Define which directories are included from the build based on the config file
 ---------------------------------------------------*/

const EXCLUDE_FROM_BUILD = [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, 'test'),
    path.resolve(__dirname, 'server'),
    path.resolve(__dirname, 'build'),
    path.resolve(__dirname, 'extensions'),
    path.resolve(__dirname, 'client/components/ui'),
    path.resolve(__dirname, './api')]

const INCLUDE_IN_BUILD = []

const APP_CONFIG = require('./buildconfig.json')
const PACKAGE_JSON = require('./package.json')

const APP_VALUES = {
    DEV_MODE,
    BUILD_NUMBER,
    APP_NAME: PACKAGE_JSON.name,
    APP_VERSION: PACKAGE_JSON.version,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_COLOR: '#2196f3',
    ...APP_CONFIG.options
}

if (APP_CONFIG.extensions) {
    for (const extensionName in APP_CONFIG.extensions) {
        if (APP_CONFIG.extensions[extensionName].active) {
            INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'extensions/' + extensionName))
        }
    }
}

if (APP_CONFIG.ui) {
    APP_CONFIG.ui.forEach(ui => {
        INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'client/components/ui/impl/' + ui.impl))
    })
}

const excludeFunction = (path) => {

    for (let i = 0; i < EXCLUDE_FROM_BUILD.length; i++) {
        if (path.indexOf(EXCLUDE_FROM_BUILD[i]) === 0) {
            // it belongs to the excluded files

            for (let j = 0; j < INCLUDE_IN_BUILD.length; j++) {
                if (path.indexOf(INCLUDE_IN_BUILD[j]) === 0) {
                    // it is an exception and should be included anyway
                    return false
                }
            }

            return true
        }
    }
    return false
}

const replacePlaceholders = (content, path) => {

    const result = new Function('const {' + Object.keys(APP_VALUES).join(',') + '} = this.APP_VALUES;return `' + content + '`').call({APP_VALUES})
    return result
}

const config = {
    entry: './client/index.js',
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].bundle.js?v=' + BUILD_NUMBER,
        chunkFilename: '[name].bundle.js?v=' + BUILD_NUMBER,
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: excludeFunction,
                loader: 'babel-loader'
            },
            {
                test: /\.global\.css$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.global\.less$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "less-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            }
        ]
    },
    plugins: [
        new GenSourceCode(APP_VALUES), /* Generate some source code based on the buildconfig.json file */
        new MiniCssExtractPlugin({
            filename: 'style.css',
            allChunks: true
        }), /* Extract css from bundle */
        new WebpackI18nPlugin({
            src: './**/*.tr.json',
            dest: '[name].js'
        })
    ],
    optimization: {
        /*splitChunks: {
         cacheGroups: {
         style: {
         name: 'style',
         test: (c) => {
         if (c.type === 'css/mini-extract') {
         const path = c._identifier
         //console.log(path.substring(path.lastIndexOf('/')+1))
         return true
         }
         return false
         },
         chunks: 'all',
         enforce: true
         }
         }
         },*/
        minimizer: []
    }/*optimization: {
     // We no not want to minimize our code.
     minimize: false
     }*/
}

const CopyWebpackPlugin = require('copy-webpack-plugin')
config.plugins.push(
    new CopyWebpackPlugin([
        {
            from: 'index.html', to: 'index.html',
            transform: replacePlaceholders
        },
        {
            from: 'index.min.html', to: 'index.min.html',
            transform: replacePlaceholders
        },
        {
            from: 'serviceworker.js', to: 'serviceworker.js',
            transform: replacePlaceholders
        },
        {
            from: 'manifest.json', to: 'manifest.json',
            transform: replacePlaceholders
        },
        {from: 'favicon.ico', to: 'favicon.ico'},
        {from: 'favicon.svg', to: 'favicon.svg'},
        {from: 'favicon-192x192.png', to: 'favicon-192x192.png'},
        {from: 'favicon-512x512.png', to: 'favicon-512x512.png'}
    ])
)

/**
 *  Developer / Debug Config
 */
if (DEV_MODE) {
    console.log('Build for developing')
    config.mode = 'development'

    const PORT = (process.env.PORT || 8080)
    const API_PORT = (process.env.API_PORT || 3000)

    config.devServer = {
        contentBase: [path.join(__dirname, ''), path.join(__dirname, 'static')],
        historyApiFallback: true,
        inline: true,
        hot: true,
        stats: 'errors-only',
        port: PORT,
        host: '0.0.0.0',
        proxy: {
            '/graphql': {target: `http://0.0.0.0:${API_PORT}`},
            '/ws': {
                target: `ws://localhost:${API_PORT}`,
                ws: true
            }
        }
    }

    /* For Debugging porpuses */
    config.devtool = 'eval'

    config.plugins.push(new webpack.HotModuleReplacementPlugin())

} else {
    console.log('Build for production')
    config.mode = 'production'

    config.plugins.push(
        new CompressionPlugin({
            minRatio: 0.95
        })
    )

    config.optimization.minimizer.push(
        new UglifyJSPlugin({
            uglifyOptions: {
                compress: {
                    drop_console: true
                },
                output: {
                    comments: false,
                    semicolons: true,
                    shebang: true,
                    beautify: false
                }
            }
        }))

    /*const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
     config.plugins.push(new BundleAnalyzerPlugin())*/

    //config.devtool = 'source-map'
    config.devtool = 'none'
}

module.exports = config

/* --port 8080 --hot --host 0.0.0.0 --content-base . */
<|endoftext|>


<commit_before>// Copy from: https://github.com/mxstbr/react-boilerplate
// Copyright (c) 2016 Maximilian Stoiber. For more information see LICENSE.md.

/* eslint-disable no-console */

const chalk = require('chalk');
const ip = require('ip');

const divider = chalk.gray('\n---------------------------------------------');

/**
 * Logger middleware, you can customize it to make messages more personal
 */
export default {

  log: (...msg) => {
    console.log(msg);
  },

  info: (...msg) => {
    console.info(chalk.green(msg));
  },

  // Called whenever there's an error on the server we want to print
  error: (...err) => {
    console.error(chalk.red(err));
  },

  // Called when express.js app starts on given port w/o errors
  serverStarted: (port, publicPath='/', tunnelStarted=false) => {
    console.log(`Server started ${chalk.green('✓')}`);

    // If the tunnel started, log that and the URL it's available at
    if (tunnelStarted) {
      console.log(`Tunnel initialised ${chalk.green('✓')}`);
    }

    console.log(`
${chalk.bold('Access URLs:')}${divider}
Localhost: ${chalk.magenta(`http://localhost:${port}${publicPath}`)}
      LAN: ${chalk.magenta(`http://${ip.address()}:${port}${publicPath}`) +
    (tunnelStarted ? `\n    Proxy: ${chalk.magenta(tunnelStarted)}` : '')}${divider}
${chalk.blue(`Press ${chalk.italic('CTRL-C')} to stop`)}
    `);
  },
};

<commit_msg>Improved server logger startup message<commit_after>// Copy from: https://github.com/mxstbr/react-boilerplate
// Copyright (c) 2016 Maximilian Stoiber. For more information see LICENSE.md.

/* eslint-disable no-console */

const chalk = require('chalk');
const ip = require('ip');

const divider = chalk.gray('\n---------------------------------------------');

/**
 * Logger middleware, you can customize it to make messages more personal
 */
export default {

  log: (...msg) => {
    console.log(msg);
  },

  info: (...msg) => {
    console.info(chalk.green(msg));
  },

  // Called whenever there's an error on the server we want to print
  error: (...err) => {
    console.error(chalk.red(err));
  },

  // Called when express.js app starts on given port w/o errors
  serverStarted: (port, publicPath='/', isHot=false, tunnelStarted=false) => {
    console.log(`${isHot ? 'HMR ' : ''}Server started ${chalk.green('✓')}`);

    // If the tunnel started, log that and the URL it's available at
    if (tunnelStarted) {
      console.log(`Tunnel initialised ${chalk.green('✓')}`);
    }

    console.log(`
${chalk.bold('Access URLs:')}${divider}
Localhost: ${chalk.magenta(`http://localhost:${port}${publicPath}`)}
      LAN: ${chalk.magenta(`http://${ip.address()}:${port}${publicPath}`) +
    (tunnelStarted ? `\n    Proxy: ${chalk.magenta(tunnelStarted)}` : '')}${divider}
${chalk.blue(`Press ${chalk.italic('CTRL-C')} to stop`)}
    `);
  },

};

<|endoftext|>


<commit_before>'use strict'
let webpack = require('webpack')

module.exports = {
  context: __dirname + '/app',
  entry: {
    muzhack: [
      'babel-polyfill',
      './entry.js',
    ],
    workshops: [
      'babel-polyfill',
      './workshopsEntry.js',
    ],
  },
  output: {
    path: __dirname + '/dist',
    filename: '[name].bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel',
      },
      {
        test: /\.styl$/,
        loader: 'style-loader!raw!stylus-loader',
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
      },
      {
        test: /\.(eot|woff|woff2|ttf|svg)($|\?)/,
        loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]',
      },
      {
        test: /(isotope|masonry|outlayer|item|get-size|fizzy-ui-utils\/utils)\.js$/,
        loader: 'imports?define=>false',
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
      },
      {
        test: /\.coffee$/,
        loader: 'coffee-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.scss$/,
        loader: 'style!css!sass',
        exclude: /node_modules/,
      },
    ],
  },
  debug: false,
  resolve: {
    root: ['/',],
    modulesDirectories: ['node_modules', 'lib',],
    extensions: ['', '.js',],
  },
  devServer: {
    historyApiFallback: false,
    proxy: {
      '**': 'http://localhost:8000',
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      __IS_BROWSER__: true,
    }),
  ],
}
<commit_msg>Disable React dev features in production<commit_after>'use strict'
let webpack = require('webpack')
let isProduction = process.env.NODE_ENV === 'production'

let plugins = [
  new webpack.DefinePlugin({
    __IS_BROWSER__: true,
  }),
]
if (isProduction) {
   // Disable development features in React in production build
  plugins = plugins.concat(new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify('production'),
    },
  }))
}

module.exports = {
  context: __dirname + '/app',
  entry: {
    muzhack: [
      'babel-polyfill',
      './entry.js',
    ],
    workshops: [
      'babel-polyfill',
      './workshopsEntry.js',
    ],
  },
  output: {
    path: __dirname + '/dist',
    filename: '[name].bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel',
      },
      {
        test: /\.styl$/,
        loader: 'style-loader!raw!stylus-loader',
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
      },
      {
        test: /\.(eot|woff|woff2|ttf|svg)($|\?)/,
        loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]',
      },
      {
        test: /(isotope|masonry|outlayer|item|get-size|fizzy-ui-utils\/utils)\.js$/,
        loader: 'imports?define=>false',
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
      },
      {
        test: /\.coffee$/,
        loader: 'coffee-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.scss$/,
        loader: 'style!css!sass',
        exclude: /node_modules/,
      },
    ],
  },
  debug: false,
  resolve: {
    root: ['/',],
    modulesDirectories: ['node_modules', 'lib',],
    extensions: ['', '.js',],
  },
  devServer: {
    historyApiFallback: false,
    proxy: {
      '**': 'http://localhost:8000',
    },
  },
  plugins,
}
<|endoftext|>


<commit_before>process.traceDeprecation = true;
const path = require("path");
const patternslib_config = require("@patternslib/patternslib/webpack/webpack.config");
const svelte_config = require("@patternslib/pat-content-browser/webpack.svelte");

module.exports = async (env, argv, build_dirname = __dirname) => {
    let config = {
        entry: {
            "bundle.min": path.resolve(__dirname, "src/index.js"),
        },
        externals: {
            window: "window",
            $: 'jquery',
            jquery: 'jQuery',
            "window.jquery": 'jQuery',
        },
    };

    config = svelte_config(env, argv, patternslib_config(env, argv, config, ["mockup"]));
    config.output.path = path.resolve(__dirname, "dist/");

    if (process.env.NODE_ENV === "development") {
        // Note: ``publicPath`` is set to "auto" in Patternslib,
        //        so for the devServer the public path set to "/".
        config.devServer.port = "8000";
        config.devServer.static.directory = path.resolve(__dirname, "./docs/_site/");
    }

    if (env && env.DEPLOYMENT === "plone") {
        config.output.path = path.resolve(
            build_dirname,
            "../plone.staticresources/src/plone/staticresources/static/bundle-plone/"
        );
    }

    return config;
};
<commit_msg>Optimize chunks<commit_after>process.traceDeprecation = true;
const path = require("path");
const patternslib_config = require("@patternslib/patternslib/webpack/webpack.config");
const svelte_config = require("@patternslib/pat-content-browser/webpack.svelte");

module.exports = async (env, argv, build_dirname = __dirname) => {
    let config = {
        entry: {
            "bundle.min": path.resolve(__dirname, "src/index.js"),
        },
        externals: {
            window: "window",
            $: 'jquery',
            jquery: 'jQuery',
            "window.jquery": 'jQuery',
        },
        optimization: {
            splitChunks: {
                cacheGroups: {
                    tinymce: {
                        name: "tinymce",
                            test: /[\\/]node_modules[\\/]tinymce.*[\\/]/,
                            chunks: "all",
                    },
                    datatables: {
                        name: "datatables",
                            test: /[\\/]node_modules[\\/]datatables.net.*[\\/]/,
                            chunks: "all",
                    },
                    select2: {
                        name: "select2",
                            test: /[\\/]node_modules[\\/]select2.*[\\/]/,
                            chunks: "all",
                    },
                    jquery_plugins: {
                        name: "jquery_plugins",
                            test: /[\\/]node_modules[\\/]jquery\..*[\\/]/,
                            chunks: "all",
                    },
                },
            },
        },
    };

    config = svelte_config(env, argv, patternslib_config(env, argv, config, ["mockup"]));
    config.output.path = path.resolve(__dirname, "dist/");

    if (process.env.NODE_ENV === "development") {
        // Note: ``publicPath`` is set to "auto" in Patternslib,
        //        so for the devServer the public path set to "/".
        config.devServer.port = "8000";
        config.devServer.static.directory = path.resolve(__dirname, "./docs/_site/");
    }

    if (env && env.DEPLOYMENT === "plone") {
        config.output.path = path.resolve(
            build_dirname,
            "../plone.staticresources/src/plone/staticresources/static/bundle-plone/"
        );
    }

    return config;
};
<|endoftext|>


<commit_before>const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  entry: {
    main: __dirname + "/src/InfiniteAnyHeight.jsx",
  },

  output: {
    filename: "[name].js",
    path: __dirname + "/dist",
    library: "InfiniteAnyHeight",
    libraryTarget: "umd",
  },

  devtool: "source-map",

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/],
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true },
          }
        ]
      },
    ],
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html",
    })
  ],
}
<commit_msg>Use main file name as umd library name<commit_after>const HtmlWebPackPlugin = require("html-webpack-plugin")

const mainFile = "InfiniteAnyHeight.jsx"

module.exports = {
  entry: {
    main: __dirname + "/src/" + mainFile,
  },

  output: {
    filename: "[name].js",
    path: __dirname + "/dist",
    library: mainFile.substring (0, mainFile.indexOf(".")),
    libraryTarget: "umd",
  },

  devtool: "source-map",

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/],
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true },
          }
        ]
      },
    ],
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html",
    })
  ],
}
<|endoftext|>


<commit_before>var Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .autoProvidejQuery()
    .autoProvideVariables({
        "window.jQuery": "jquery",
        "window.Bloodhound": require.resolve('bloodhound-js'),
        "jQuery.tagsinput": "bootstrap-tagsinput"
    })
    .enableSassLoader()
    .enableVersioning(false)
    .createSharedEntry('js/common', ['jquery'])
    .addEntry('js/app', './assets/js/app.js')
    .addEntry('js/login', './assets/js/login.js')
    .addEntry('js/admin', './assets/js/admin.js')
    .addEntry('js/search', './assets/js/search.js')
    .addStyleEntry('css/app', ['./assets/scss/app.scss'])
    .addStyleEntry('css/admin', ['./assets/scss/admin.scss'])
;

module.exports = Encore.getWebpackConfig();
<commit_msg>minor #694 Removed jQuery from auto provided variables in webpack config (mathop)<commit_after>var Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .autoProvidejQuery()
    .autoProvideVariables({
        "window.Bloodhound": require.resolve('bloodhound-js'),
        "jQuery.tagsinput": "bootstrap-tagsinput"
    })
    .enableSassLoader()
    .enableVersioning(false)
    .createSharedEntry('js/common', ['jquery'])
    .addEntry('js/app', './assets/js/app.js')
    .addEntry('js/login', './assets/js/login.js')
    .addEntry('js/admin', './assets/js/admin.js')
    .addEntry('js/search', './assets/js/search.js')
    .addStyleEntry('css/app', ['./assets/scss/app.scss'])
    .addStyleEntry('css/admin', ['./assets/scss/admin.scss'])
;

module.exports = Encore.getWebpackConfig();
<|endoftext|>


<commit_before>module.exports = {
  entry: "./src/app/components/tracker-body.js",
  output: {
    path: __dirname + "/dist",
    filename: "all.js"
  },
  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
    ]
  }
};
<commit_msg>Emit source maps for easier debugging<commit_after>module.exports = {
  entry: "./src/app/components/tracker-body.js",
  devtool: 'source-map',
  output: {
    path: __dirname + "/dist",
    filename: "all.js"
  },
  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
    ]
  }
};
<|endoftext|>


<commit_before>/**
 * This is the configuration file for webpack. It is designed to work side-by-side with gulp. We do
 * not use webpack as a task runner, instead us gulp.
*/

const webpack = require('webpack');

module.exports = {
  /**
   * This is the entry point
   */
  entry: './src/js/main.js',

  /**
   * We enable source maps, but do not reference it in the bundle to save space
   */
  devtool: 'hidden-source-map',

  /**
   * The name of the bundle
   */
  output: {
    filename: 'main.bundle.js'
  },
  module: {
    rules: [{
      /**
       * We look for all JS files, and optionally JSX files
       */
      test: /\.jsx?$/,

      /**
       * Ignore all the npm files otherwise it'd be super big
       */
      exclude: /(node_modules|bower_components)/,

      /**
       * When the test is matched, use babel-loader to transplile to ES5
       */
      use: {
        loader: 'babel-loader',
        options: {
          /**
           * Enable Caching can speed up transpiling by 2x
           */
          cacheDirectory: true,

          /**
           * This preset replaces the old ES2015 prest
           */
          presets: ['babel-preset-env'],

          /**
           * This will make your code smaller by adding all the polyfills at once at
           * the top of the JS File. If you don't use much JS, then comment this out
           * as you probably don't want all the polyfills
           */
          plugins: ['transform-runtime'],
        }
      }
    }],
  },

  /**
   * Enable parallel processing of JS
   */
  parallelism: 4,

  plugins: [
    /**
     * Uglify the output, but still generate a sitemap
     */
    new webpack.optimize.UglifyJsPlugin({
      parallel: true,
      sourceMap: true
    }),
  ],

  /**
   * Set the target environment to 'web'
   */
  target: 'web',

  /**
   * Do not watch by default, we do it via gulp
   */
  watch: false,
};
<commit_msg>update: No JS maps by default<commit_after>/**
 * This is the configuration file for webpack. It is designed to work side-by-side with gulp. We do
 * not use webpack as a task runner, instead us gulp.
*/

const webpack = require('webpack');

module.exports = {
  /**
   * This is the entry point
   */
  entry: './src/js/main.js',

  /**
   * We enable source maps, but do not reference it in the bundle to save space
   *
   * Prod: none
   * Dev:  hidden-source-map
   */
  devtool: 'none',

  /**
   * The name of the bundle
   */
  output: {
    filename: 'main.bundle.js'
  },
  module: {
    rules: [{
      /**
       * We look for all JS files, and optionally JSX files
       */
      test: /\.jsx?$/,

      /**
       * Ignore all the npm files otherwise it'd be super big
       */
      exclude: /(node_modules|bower_components)/,

      /**
       * When the test is matched, use babel-loader to transplile to ES5
       */
      use: {
        loader: 'babel-loader',
        options: {
          /**
           * Enable Caching can speed up transpiling by 2x
           */
          cacheDirectory: true,

          /**
           * This preset replaces the old ES2015 prest
           */
          presets: ['babel-preset-env'],

          /**
           * This will make your code smaller by adding all the polyfills at once at
           * the top of the JS File. If you don't use much JS, then comment this out
           * as you probably don't want all the polyfills
           */
          plugins: ['transform-runtime'],
        }
      }
    }],
  },

  /**
   * Enable parallel processing of JS
   */
  parallelism: 4,

  plugins: [
    /**
     * Uglify the output, but still generate a sitemap
     */
    new webpack.optimize.UglifyJsPlugin({
      parallel: true,
      sourceMap: true
    }),
  ],

  /**
   * Set the target environment to 'web'
   */
  target: 'web',

  /**
   * Do not watch by default, we do it via gulp
   */
  watch: false,
};
<|endoftext|>


<commit_before>// @AngularClass

/*
 * Helper: root(), and rootDir() are defined at the bottom
 */
var path = require('path');
var webpack = require('webpack');
var CopyWebpackPlugin  = require('copy-webpack-plugin');
var HtmlWebpackPlugin  = require('html-webpack-plugin');
var ENV = process.env.ENV = process.env.NODE_ENV = 'development';

var metadata = {
  title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV
};
/*
 * Config
 */
module.exports = {
  // static data for index.html
  metadata: metadata,
  // for faster builds use 'eval'
  devtool: 'source-map',
  debug: true,
  // cache: false,

  // our angular app
  entry: { 'polyfills': './src/polyfills.ts', 'main': './src/main.ts' },

  // Config for our build files
  output: {
    path: root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  resolve: {
    // ensure loader extensions match
    extensions: prepend(['.ts','.js','.json','.css','.html'], '.async') // ensure .async.ts etc also works
  },

  module: {
    preLoaders: [
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ root('node_modules') ] },
      // TODO(gdi2290): `exclude: [ root('node_modules/rxjs') ]` fixed with rxjs 5 beta.2 release
      { test: /\.js$/, loader: "source-map-loader", exclude: [ root('node_modules/rxjs') ] }
    ],
    loaders: [
      // Support Angular 2 async routes via .async.ts
      { test: /\.async\.ts$/, loaders: ['es6-promise-loader', 'ts-loader'], exclude: [ /\.(spec|e2e)\.ts$/ ] },

      // Support for .ts files.
      { test: /\.ts$/, loader: 'ts-loader', exclude: [ /\.(spec|e2e|async)\.ts$/ ] },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,  loader: 'raw-loader', exclude: [ root('src/index.html') ] }

      // if you add a loader include the resolve file extension above
    ]
  },

  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: 'polyfills', filename: 'polyfills.bundle.js', minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
    // generating html
    new HtmlWebpackPlugin({ template: 'src/index.html' }),
    // replace
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(metadata.ENV),
        'NODE_ENV': JSON.stringify(metadata.ENV)
      }
    })
  ],

  // Other module loader config
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src'
  },
  // our Webpack Development Server config
  devServer: {
    port: metadata.port,
    host: metadata.host,
    // contentBase: 'src/',
    historyApiFallback: true,
    watchOptions: { aggregateTimeout: 300, poll: 1000 }
  },
  // we need this due to problems with es6-shim
  node: {global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false}
};

// Helper functions

function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}

function prepend(extensions, args) {
  args = args || [];
  if (!Array.isArray(args)) { args = [args] }
  return extensions.reduce(function(memo, val) {
    return memo.concat(val, args.map(function(prefix) {
      return prefix + val
    }));
  }, ['']);
}
function rootNode(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return root.apply(path, ['node_modules'].concat(args));
}
<commit_msg>Enable tslint for webpack.<commit_after>// @AngularClass

/*
 * Helper: root(), and rootDir() are defined at the bottom
 */
var path = require('path');
var webpack = require('webpack');
var CopyWebpackPlugin  = require('copy-webpack-plugin');
var HtmlWebpackPlugin  = require('html-webpack-plugin');
var ENV = process.env.ENV = process.env.NODE_ENV = 'development';

var metadata = {
  title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV
};
/*
 * Config
 */
module.exports = {
  // static data for index.html
  metadata: metadata,
  // for faster builds use 'eval'
  devtool: 'source-map',
  debug: true,
  // cache: false,

  // our angular app
  entry: { 'polyfills': './src/polyfills.ts', 'main': './src/main.ts' },

  // Config for our build files
  output: {
    path: root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  resolve: {
    // ensure loader extensions match
    extensions: prepend(['.ts','.js','.json','.css','.html'], '.async') // ensure .async.ts etc also works
  },

  module: {
    preLoaders: [
      {test: /\.ts$/, loader: 'tslint-loader', exclude: [root('node_modules')]},
      // TODO(gdi2290): `exclude: [ root('node_modules/rxjs') ]` fixed with rxjs 5 beta.2 release
      { test: /\.js$/, loader: "source-map-loader", exclude: [ root('node_modules/rxjs') ] }
    ],
    loaders: [
      // Support Angular 2 async routes via .async.ts
      { test: /\.async\.ts$/, loaders: ['es6-promise-loader', 'ts-loader'], exclude: [ /\.(spec|e2e)\.ts$/ ] },

      // Support for .ts files.
      { test: /\.ts$/, loader: 'ts-loader', exclude: [ /\.(spec|e2e|async)\.ts$/ ] },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,  loader: 'raw-loader', exclude: [ root('src/index.html') ] }

      // if you add a loader include the resolve file extension above
    ]
  },

  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: 'polyfills', filename: 'polyfills.bundle.js', minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
    // generating html
    new HtmlWebpackPlugin({ template: 'src/index.html' }),
    // replace
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(metadata.ENV),
        'NODE_ENV': JSON.stringify(metadata.ENV)
      }
    })
  ],

  // Other module loader config
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src'
  },
  // our Webpack Development Server config
  devServer: {
    port: metadata.port,
    host: metadata.host,
    // contentBase: 'src/',
    historyApiFallback: true,
    watchOptions: { aggregateTimeout: 300, poll: 1000 }
  },
  // we need this due to problems with es6-shim
  node: {global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false}
};

// Helper functions

function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}

function prepend(extensions, args) {
  args = args || [];
  if (!Array.isArray(args)) { args = [args] }
  return extensions.reduce(function(memo, val) {
    return memo.concat(val, args.map(function(prefix) {
      return prefix + val
    }));
  }, ['']);
}
function rootNode(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return root.apply(path, ['node_modules'].concat(args));
}
<|endoftext|>


<commit_before>/**
 * @author Juliano Castilho <julianocomg@gmail.com>
 */
import React from 'react'
import {View} from 'react-native'
import serialize from './serialize'

class Form extends React.Component {
  /**
   * @param {Object} props
   */
  constructor(props) {
    super(props)

    this.fields = {}
    this.formFields = {};
  }

  /**
   * @private
   * @param {String} id
   * @param {String} name
   * @param {String} value
   */
  _persistFieldValue(id, name, value) {
    this.fields[id] = {name, value}
  }

  /**
   * @returns {Object}
   */
  getValues() {
    let fieldsArray = []

    Object.keys(this.fields).map((id, index) => {
      fieldsArray[index] = this.fields[id]
    })

    return serialize(fieldsArray)
  }

  /**
  * @private
  * @param {String} id
  * @param {String} name
  * @param {String} ref
  */
  _persistFieldRef(id, name, value) {
      this.formFields[id] = {name, value}
  }

  /**
  * @returns {Object}
  */
  getRefs() {
      let fieldsArray = []

      Object.keys(this.formFields).map((id, index) => {
          var tempRef = Object.assign({}, this.formFields[id])
          var _refs = this.refs
          // value 其实就是 ref 参数的名字 // value actually is 'ref'
          tempRef.name = tempRef.value // 这里其实只用value // here just same as the value
          tempRef.value = _refs[tempRef.value] // 这里获得对应的ref // here get the ref
          fieldsArray[index] = tempRef
      })

      return serialize(fieldsArray)
  }

  /**
   * @returns {Object}
   */
  _getAllowedFormFieldTypes() {
    return {
      ...this.props.customFields,

      'TextInput': {
        defaultValue: '',
        valueProp: 'defaultValue',
        callbackProp: 'onChangeText'
      },
      'Switch': {
        controlled: true,
        valueProp: 'value',
        callbackProp: 'onValueChange'
      },
      'SliderIOS': {
        valueProp: 'value',
        callbackProp: 'onSlidingComplete'
      },
      'Slider': {
        valueProp: 'value',
        callbackProp: 'onSlidingComplete'
      },
      'Picker': {
        controlled: true,
        valueProp: 'selectedValue',
        callbackProp: 'onValueChange'
      },
      'PickerIOS': {
        controlled: true,
        valueProp: 'selectedValue',
        callbackProp: 'onValueChange'
      },
      'DatePickerIOS': {
        controlled: true,
        valueProp: 'date',
        callbackProp: 'onDateChange'
      }
    }
  }

  /**
   * @return [ReactComponent]
   */
  _createFormFields(elements) {
    const allowedFieldTypes = this._getAllowedFormFieldTypes()

    return React.Children.map(elements, (element, fieldIndex) => {
      if (typeof element !== 'object') {
        return element
      }
      console.log('element', element)

      const fieldType = element.props.type
      const fieldName = element.props.name
      const allowedField = allowedFieldTypes[fieldType]
      const isValidField = !!(allowedField && fieldName)
      const fieldId = fieldName + element.key

      let props = {}

      if (fieldName) {
        // set refs
        if (!this.formFields[fieldId]) {
            this._persistFieldRef(
              fieldId,
              fieldName,
              (element.ref || element.props.name) || fieldName
            )
        }

        props.ref = this.formFields[fieldId].value;
      };

      // binding values changed
      if (! isValidField) {
        if (fieldType == 'Accordion') {
          return React.cloneElement(element, {
            ...props,
            children: this._createFormFields(element.props.content)
          })
        } else {
          return React.cloneElement(element, {
            ...props,
            children: this._createFormFields(element.props.children)
          })
        }
      }

      props[allowedField.callbackProp] = value => {
        this._persistFieldValue(
          fieldId,
          fieldName,
          value
        )

        if (allowedField.controlled) {
          this.forceUpdate()
        }

        const proxyCallback = element.props[allowedField.callbackProp]

        if (typeof proxyCallback === 'function') {
          proxyCallback(value)
        }
      }

      if (!this.fields[fieldId]) {
        this._persistFieldValue(
          fieldId,
          fieldName,
          (element.props[allowedField.valueProp] || element.props.value) || allowedField.defaultValue
        )
      }

      if (allowedField.controlled) {
        props[allowedField.valueProp] = this.fields[fieldId].value
      }

      return React.cloneElement(element, {
        ...props,
        children: this._createFormFields(element.props.children)
      })
    })
  }

  /**
   * @returns {ReactComponent}
   */
  render() {
    return (
      <View {...this.props}>
        {this._createFormFields(this.props.children)}
      </View>
    )
  }
}

/**
 * @type {Object}
 */
Form.defaultProps = {
  customFields: {}
}

export default Form
<commit_msg>add “element is null” check<commit_after>/**
 * @author Juliano Castilho <julianocomg@gmail.com>
 */
import React from 'react'
import {View} from 'react-native'
import serialize from './serialize'

class Form extends React.Component {
  /**
   * @param {Object} props
   */
  constructor(props) {
    super(props)

    this.fields = {}
    this.formFields = {};
  }

  /**
   * @private
   * @param {String} id
   * @param {String} name
   * @param {String} value
   */
  _persistFieldValue(id, name, value) {
    this.fields[id] = {name, value}
  }

  /**
   * @returns {Object}
   */
  getValues() {
    let fieldsArray = []

    Object.keys(this.fields).map((id, index) => {
      fieldsArray[index] = this.fields[id]
    })

    return serialize(fieldsArray)
  }

  /**
  * @private
  * @param {String} id
  * @param {String} name
  * @param {String} ref
  */
  _persistFieldRef(id, name, value) {
      this.formFields[id] = {name, value}
  }

  /**
  * @returns {Object}
  */
  getRefs() {
      let fieldsArray = []

      Object.keys(this.formFields).map((id, index) => {
          var tempRef = Object.assign({}, this.formFields[id])
          var _refs = this.refs
          // value 其实就是 ref 参数的名字 // value actually is 'ref'
          tempRef.name = tempRef.value // 这里其实只用value // here just same as the value
          tempRef.value = _refs[tempRef.value] // 这里获得对应的ref // here get the ref
          fieldsArray[index] = tempRef
      })

      return serialize(fieldsArray)
  }

  /**
   * @returns {Object}
   */
  _getAllowedFormFieldTypes() {
    return {
      ...this.props.customFields,

      'TextInput': {
        defaultValue: '',
        valueProp: 'defaultValue',
        callbackProp: 'onChangeText'
      },
      'Switch': {
        controlled: true,
        valueProp: 'value',
        callbackProp: 'onValueChange'
      },
      'SliderIOS': {
        valueProp: 'value',
        callbackProp: 'onSlidingComplete'
      },
      'Slider': {
        valueProp: 'value',
        callbackProp: 'onSlidingComplete'
      },
      'Picker': {
        controlled: true,
        valueProp: 'selectedValue',
        callbackProp: 'onValueChange'
      },
      'PickerIOS': {
        controlled: true,
        valueProp: 'selectedValue',
        callbackProp: 'onValueChange'
      },
      'DatePickerIOS': {
        controlled: true,
        valueProp: 'date',
        callbackProp: 'onDateChange'
      }
    }
  }

  /**
   * @return [ReactComponent]
   */
  _createFormFields(elements) {
    const allowedFieldTypes = this._getAllowedFormFieldTypes()

    return React.Children.map(elements, (element, fieldIndex) => {
      if (typeof element !== 'object' || element === null) {
        return element
      }

      const fieldType = element.props.type
      const fieldName = element.props.name
      const allowedField = allowedFieldTypes[fieldType]
      const isValidField = !!(allowedField && fieldName)
      const fieldId = fieldName + element.key

      let props = {}

      if (fieldName) {
        // set refs
        if (!this.formFields[fieldId]) {
            this._persistFieldRef(
              fieldId,
              fieldName,
              (element.ref || element.props.name) || fieldName
            )
        }

        props.ref = this.formFields[fieldId].value;
      };

      // binding values changed
      if (! isValidField) {
        if (fieldType == 'Accordion') {
          return React.cloneElement(element, {
            ...props,
            children: this._createFormFields(element.props.content)
          })
        } else {
          return React.cloneElement(element, {
            ...props,
            children: this._createFormFields(element.props.children)
          })
        }
      }

      props[allowedField.callbackProp] = value => {
        this._persistFieldValue(
          fieldId,
          fieldName,
          value
        )

        if (allowedField.controlled) {
          this.forceUpdate()
        }

        const proxyCallback = element.props[allowedField.callbackProp]

        if (typeof proxyCallback === 'function') {
          proxyCallback(value)
        }
      }

      if (!this.fields[fieldId]) {
        this._persistFieldValue(
          fieldId,
          fieldName,
          (element.props[allowedField.valueProp] || element.props.value) || allowedField.defaultValue
        )
      }

      if (allowedField.controlled) {
        props[allowedField.valueProp] = this.fields[fieldId].value
      }

      return React.cloneElement(element, {
        ...props,
        children: this._createFormFields(element.props.children)
      })
    })
  }

  /**
   * @returns {ReactComponent}
   */
  render() {
    return (
      <View {...this.props}>
        {this._createFormFields(this.props.children)}
      </View>
    )
  }
}

/**
 * @type {Object}
 */
Form.defaultProps = {
  customFields: {}
}

export default Form
<|endoftext|>


<commit_before>'use strict';

// Libs
const path = require('path');
const webpack = require('webpack');
const exec = require('child_process').exec;

// Watch SASS
(() => {
    let sass = exec('sass --sourcemap=none --watch ./src/Client/Style/client.scss:./public/css/client.css');

    sass.stdout.on('data', (data) => {
        console.log(data);
    });

    sass.stderr.on('data', (data) => {
        console.log(data);
    });
})();

// Define settings
module.exports = {
    // Input .js
    entry: {
        client: './src/Client/client.js',
        dashboard: './src/Client/dashboard.js',
        demo: './src/Client/demo.js'
    },

    // Output .js
    output: {
        filename: './public/js/[name].js'
    },

    // Define loaders
    module: {
        rules: [
            // Babel.js
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['@babel/preset-env', { loose: true, modules: false }]
                        ]
                    }
                }
            },

            // JSON
            {
                test: /\.(json|schema)$/,
                use: 'json-loader'
            },
        ]
    },

    // Automatically accept these extensions
    resolve: {
        modules: [path.resolve(__dirname), path.resolve(__dirname, 'src'), 'node_modules'],
        extensions: ['.js', '.json']
    }
};
<commit_msg>Built SASS watch script into Webpack config<commit_after>'use strict';

// Libs
const path = require('path');
const webpack = require('webpack');
const exec = require('child_process').exec;

// Watch SASS
let sass = exec('sass --sourcemap=none --watch ./src/Client/Style/client.scss:./public/css/client.css');

sass.stdout.on('data', (data) => {
    console.log(data);
});

sass.stderr.on('data', (data) => {
    console.log(data);
});

// Define settings
module.exports = {
    // Input .js
    entry: {
        client: './src/Client/client.js',
        dashboard: './src/Client/dashboard.js',
        demo: './src/Client/demo.js'
    },

    // Output .js
    output: {
        filename: './public/js/[name].js'
    },

    // Define loaders
    module: {
        rules: [
            // Babel.js
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['@babel/preset-env', { loose: true, modules: false }]
                        ]
                    }
                }
            },

            // JSON
            {
                test: /\.(json|schema)$/,
                use: 'json-loader'
            },
        ]
    },

    // Automatically accept these extensions
    resolve: {
        modules: [path.resolve(__dirname), path.resolve(__dirname, 'src'), 'node_modules'],
        extensions: ['.js', '.json']
    }
};
<|endoftext|>


<commit_before>/**
 * React Native Webpack Starter Kit
 * https://github.com/jhabdas/react-native-webpack-starter-kit
 */
(function() {
  'use strict'

  var path = require('path')
  var webpack = require('webpack')

  module.exports = {
    debug: true,
    devtool: 'source-map',
    entry: {
      'index.ios': ['./src/main.ios.js'],
      //'index.android': ['./src/main.android.js'],
    },
    output: {
      path: path.resolve(__dirname, 'build'),
      filename: '[name].js',
    },
    module: {
      preLoaders: [
        {
          test: /\.(js|jsx|es6)$/,
          include: path.resolve(__dirname, 'src'),
          loader: 'eslint-loader',
        }
      ],
      loaders: [
        {
          test: /\.js$/,
          include: /node_modules\/react-native/,
          loader: 'babel',
          query: {
            cacheDirectory: true,
            presets: ['es2015', 'stage-1', 'react']
          }
        },
        {
          test: /\.(js|jsx|es6)$/,
          exclude: /node_modules/,
          loader: 'babel',
          query: {
            cacheDirectory: true,
            presets: ['es2015', 'stage-1', 'react']
          }
        }
      ]
    }
  }
}())
<commit_msg>Added added aliases to Webpack<commit_after>(function() {
  'use strict';

  var path = require('path');
  var webpack = require('webpack');

  module.exports = {
    debug: true,
    devtool: 'source-map',
    entry: {
      'index.ios': ['./src/main.ios.js'],
      //'index.android': ['./src/main.android.js'],
    },

    output: {
      path: path.resolve(__dirname, 'build'),
      filename: '[name].js',
    },

    resolve: {
      alias: {
        util:   __dirname + "/src/util",
        shared: __dirname + "/src/components/shared"
      }
    },

    module: {
      preLoaders: [
        {
          test: /\.(js|jsx|es6)$/,
          include: path.resolve(__dirname, 'src'),
          loader: 'eslint-loader',
        }
      ],
      loaders: [
        {
          test: /\.js$/,
          include: /node_modules\/react-native/,
          loader: 'babel',
          query: {
            cacheDirectory: true,
            presets: ['es2015', 'stage-1', 'react']
          }
        },
        {
          test: /\.(js|jsx|es6)$/,
          exclude: /node_modules/,
          loader: 'babel',
          query: {
            cacheDirectory: true,
            presets: ['es2015', 'stage-1', 'react']
          }
        }
      ]
    }
  }
}())
<|endoftext|>


<commit_before>/* eslint-disable */
const { getConfig, dev } = require('./webpack.config.base');
const { spawn } = require('child_process');
const CopyPlugin = require('copy-webpack-plugin');
let terser = require('terser');
/* eslint-enable */

let electronProcess;

const mainConfig = getConfig({
  target: 'electron-main',

  devtool: 'inline-source-map',

  watch: dev,

  entry: {
    main: './src/main',
  },

  plugins: [
    new CopyPlugin(
      [
        {
          from:
            'node_modules/@cliqz/adblocker-electron-preload/dist/preload.cjs.js',
          to: 'preload.js',
          transform: (fileContent, path) => {
            return terser.minify(fileContent.toString()).code.toString();
          },
        },
        {
          from: 'node_modules/electron-extensions/preload.js',
          to: 'extensions-preload.js',
        },
      ],
      { copyUnmodified: true },
    ),
  ],
});

const preloadConfig = getConfig({
  target: 'electron-renderer',

  watch: dev,

  entry: {
    'view-preload': './src/preloads/view-preload',
    'popup-preload': './src/preloads/popup-preload',
  },

  plugins: [],
});

if (process.env.START === '1') {
  mainConfig.plugins.push({
    apply: compiler => {
      compiler.hooks.afterEmit.tap('AfterEmitPlugin', () => {
        if (electronProcess) {
          electronProcess.kill();
        }

        electronProcess = spawn('npm', ['start'], {
          shell: true,
          env: process.env,
          stdio: 'inherit',
        })
          .on('close', code => process.exit(code))
          .on('error', spawnError => console.error(spawnError));
      });
    },
  });
}

module.exports = [mainConfig, preloadConfig];
<commit_msg>fix: restarting electron in dev mode<commit_after>/* eslint-disable */
const { getConfig, dev } = require('./webpack.config.base');
const { spawn, execSync } = require('child_process');
const CopyPlugin = require('copy-webpack-plugin');
let terser = require('terser');
/* eslint-enable */

let electronProcess;

const mainConfig = getConfig({
  target: 'electron-main',

  devtool: 'inline-source-map',

  watch: dev,

  entry: {
    main: './src/main',
  },

  plugins: [
    new CopyPlugin(
      [
        {
          from:
            'node_modules/@cliqz/adblocker-electron-preload/dist/preload.cjs.js',
          to: 'preload.js',
          transform: (fileContent, path) => {
            return terser.minify(fileContent.toString()).code.toString();
          },
        },
        {
          from: 'node_modules/electron-extensions/preload.js',
          to: 'extensions-preload.js',
        },
      ],
      { copyUnmodified: true },
    ),
  ],
});

const preloadConfig = getConfig({
  target: 'electron-renderer',

  watch: dev,

  entry: {
    'view-preload': './src/preloads/view-preload',
    'popup-preload': './src/preloads/popup-preload',
  },

  plugins: [],
});

if (process.env.START === '1') {
  mainConfig.plugins.push({
    apply: compiler => {
      compiler.hooks.afterEmit.tap('AfterEmitPlugin', () => {
        if (electronProcess) {
          if (process.platform === 'win32') {
            execSync(`taskkill /pid ${electronProcess.pid} /f /t`);
          } else {
            electronProcess.kill();
          }

          electronProcess = null;
        }

        electronProcess = spawn('npm', ['start'], {
          shell: true,
          env: process.env,
          stdio: 'inherit',
        });
      });
    },
  });
}

module.exports = [mainConfig, preloadConfig];
<|endoftext|>


<commit_before>'use strict';

var extend = require('extend'),
    path = require('path'),
    fs = require('fs'),
    mkdirp = require('mkdirp');

function beforeInstall(config, utils, next) {
  utils.log('► Add views dependencies... ');

  config.package = extend(true, {
    dependencies: {
      gulp: '^3.9.0',
      'gulp-rename': '^1.2.2',
      'gulp-sourcemaps': '^1.5.2',
      'gulp-uglify': '^1.1.0',
      glob: '^5.0.10',
      page: '^1.6.3'
    }
  }, config.package);

  if (config.install.plumes) {
    config.package = extend(true, {
      dependencies: {
        jquery: '^2.1.3',
        ractive: '^0.7.1',
        'ractive-require': '^0.2.2',
        plumes: config.install['plumes-unstable'] ? 'git+ssh://git@github.com/CodeCorico/plumes.git' : '^0.1.0'
      }
    }, config.package);
  }

  utils.log('[OK]\n');

  next();
}

function afterInstall(config, utils, next) {
  var source = path.resolve(__dirname, 'resources'),
      featuresDest = path.resolve(utils.path, 'features');

  utils.log('► Create common views folders... ');

  mkdirp.sync(path.join(featuresDest, 'common/views/less'));
  mkdirp.sync(path.join(featuresDest, 'common/views/css'));
  mkdirp.sync(path.join(featuresDest, 'common/views/html'));

  mkdirp.sync(path.join(featuresDest, config.install.name, 'views/html'));
  mkdirp.sync(path.join(featuresDest, config.install.name, 'views/resources'));
  mkdirp.sync(path.join(featuresDest, config.install.name, 'views/css'));
  mkdirp.sync(path.join(featuresDest, config.install.name, 'controllers'));

  utils.log('[OK]\n');

  if (config.install.plumes) {
    utils.log('► Create common less mixins... ');

    utils.copy(path.resolve(utils.path, 'node_modules/plumes/features/common/less/common-mixins.less'), path.join(featuresDest, 'common/views/less/common-mixins.less'));
    utils.copy(path.resolve(utils.path, 'node_modules/plumes/features/common/less/common-variables.less'), path.join(featuresDest, 'common/views/less/common-variables.less'));

    utils.log('[OK]\n');
  }

  utils.log('► Create "' + config.install.name + '" view files... ');

  var featurePath = path.join(featuresDest, config.install.name),
      viewsDir = featurePath + '/views/',
      viewsPath = viewsDir + '/' + config.install.name + '-',
      htmlPath = viewsDir + 'html/' + config.install.name + '-',
      cssPath = viewsDir + 'css/' + config.install.name + '-',
      controllerPath = featurePath + '/controllers/' + config.install.name + '-',
      copyFiles = [{
        source: path.join(source, 'project-index.html'),
        destination: htmlPath + 'index.html'
      }, {
        source: path.join(source, 'project-start-mask.less'),
        destination: cssPath + 'start-mask.less'
      }, {
        source: path.join(source, 'project-index.js'),
        destination: viewsPath + 'index.js'
      }, {
        source: path.join(source, 'project-404-route.js'),
        destination: controllerPath + '404-route.js'
      }];

  copyFiles.forEach(function(file) {
    if (!fs.existsSync(file.destination)) {
      var content = utils.getContent(file.source);

      for (var item in config.install) {
        content = content.replace(new RegExp('{{' + item + '}}', 'g'), config.install[item]);
      }

      utils.putContent(content, file.destination);
    }
  });

  var fileDest = path.join(featuresDest, config.install.name, '/views/resources/favicon.ico');

  if (!fs.existsSync(fileDest)) {
    utils.copy(path.join(source, 'favicon.ico'), fileDest);
  }

  fileDest = path.join(featuresDest, config.install.name, '/views/resources/favicon.png');

  if (!fs.existsSync(fileDest)) {
    utils.copy(path.join(source, 'favicon.png'), fileDest);
  }

  utils.log('[OK]\n');

  utils.log('► Create gulpfile... ');

  utils.copy(path.join(source, 'gulpfile.js'), path.resolve(utils.path, 'gulpfile.js'));
  utils.copy(path.join(source, 'common-resources-gulpfile.js'), path.join(featuresDest, 'common/common-resources-gulpfile.js'));
  utils.copy(path.join(source, 'common-routes-gulpfile.js'), path.join(featuresDest, 'common/common-routes-gulpfile.js'));
  utils.copy(path.join(source, 'common-routes-template.js'), path.join(featuresDest, 'common/common-routes-template.js'));
  utils.copy(path.join(source, 'common-route-template.js'), path.join(featuresDest, 'common/common-route-template.js'));
  utils.copy(path.join(source, 'common-bootstrap.js'), path.join(featuresDest, 'common/views/common-bootstrap.js'));

  if (config.install.plumes) {
    utils.copy(path.join(source, 'common-plumes-gulpfile.js'), path.join(featuresDest, 'common/common-plumes-gulpfile.js'));
  }

  utils.log('[OK]\n');

  next();
}

module.exports = {
  install: [{
    type: 'confirm',
    name: 'plumes',
    message: 'Use jQuery + Ractive.js + Plumes?',
    default: true
  }, {
    type: 'confirm',
    name: 'plumes-unstable',
    message: 'Use Plumes #master version (unstable)?',
    default: false,
    when: function(answers) {
      return answers.plumes;
    }
  }],
  beforeInstall: beforeInstall,
  afterInstall: afterInstall,
  env: [{
    type: 'confirm',
    name: 'MINIFIED',
    message: 'Use minified asset files (js, css, ...)?',
    default: false
  }, {
    type: 'confirm',
    name: 'WATCHER',
    message: 'Watch files modifications (dev)?',
    default: true
  }]
};
<commit_msg>fix(views cli): update gulp-uglify to 1.2.0<commit_after>'use strict';

var extend = require('extend'),
    path = require('path'),
    fs = require('fs'),
    mkdirp = require('mkdirp');

function beforeInstall(config, utils, next) {
  utils.log('► Add views dependencies... ');

  config.package = extend(true, {
    dependencies: {
      gulp: '^3.9.0',
      'gulp-rename': '^1.2.2',
      'gulp-sourcemaps': '^1.5.2',
      'gulp-uglify': '^1.2.0',
      glob: '^5.0.10',
      page: '^1.6.3'
    }
  }, config.package);

  if (config.install.plumes) {
    config.package = extend(true, {
      dependencies: {
        jquery: '^2.1.3',
        ractive: '^0.7.1',
        'ractive-require': '^0.2.2',
        plumes: config.install['plumes-unstable'] ? 'git+ssh://git@github.com/CodeCorico/plumes.git' : '^0.1.0'
      }
    }, config.package);
  }

  utils.log('[OK]\n');

  next();
}

function afterInstall(config, utils, next) {
  var source = path.resolve(__dirname, 'resources'),
      featuresDest = path.resolve(utils.path, 'features');

  utils.log('► Create common views folders... ');

  mkdirp.sync(path.join(featuresDest, 'common/views/less'));
  mkdirp.sync(path.join(featuresDest, 'common/views/css'));
  mkdirp.sync(path.join(featuresDest, 'common/views/html'));

  mkdirp.sync(path.join(featuresDest, config.install.name, 'views/html'));
  mkdirp.sync(path.join(featuresDest, config.install.name, 'views/resources'));
  mkdirp.sync(path.join(featuresDest, config.install.name, 'views/css'));
  mkdirp.sync(path.join(featuresDest, config.install.name, 'controllers'));

  utils.log('[OK]\n');

  if (config.install.plumes) {
    utils.log('► Create common less mixins... ');

    utils.copy(path.resolve(utils.path, 'node_modules/plumes/features/common/less/common-mixins.less'), path.join(featuresDest, 'common/views/less/common-mixins.less'));
    utils.copy(path.resolve(utils.path, 'node_modules/plumes/features/common/less/common-variables.less'), path.join(featuresDest, 'common/views/less/common-variables.less'));

    utils.log('[OK]\n');
  }

  utils.log('► Create "' + config.install.name + '" view files... ');

  var featurePath = path.join(featuresDest, config.install.name),
      viewsDir = featurePath + '/views/',
      viewsPath = viewsDir + '/' + config.install.name + '-',
      htmlPath = viewsDir + 'html/' + config.install.name + '-',
      cssPath = viewsDir + 'css/' + config.install.name + '-',
      controllerPath = featurePath + '/controllers/' + config.install.name + '-',
      copyFiles = [{
        source: path.join(source, 'project-index.html'),
        destination: htmlPath + 'index.html'
      }, {
        source: path.join(source, 'project-start-mask.less'),
        destination: cssPath + 'start-mask.less'
      }, {
        source: path.join(source, 'project-index.js'),
        destination: viewsPath + 'index.js'
      }, {
        source: path.join(source, 'project-404-route.js'),
        destination: controllerPath + '404-route.js'
      }];

  copyFiles.forEach(function(file) {
    if (!fs.existsSync(file.destination)) {
      var content = utils.getContent(file.source);

      for (var item in config.install) {
        content = content.replace(new RegExp('{{' + item + '}}', 'g'), config.install[item]);
      }

      utils.putContent(content, file.destination);
    }
  });

  var fileDest = path.join(featuresDest, config.install.name, '/views/resources/favicon.ico');

  if (!fs.existsSync(fileDest)) {
    utils.copy(path.join(source, 'favicon.ico'), fileDest);
  }

  fileDest = path.join(featuresDest, config.install.name, '/views/resources/favicon.png');

  if (!fs.existsSync(fileDest)) {
    utils.copy(path.join(source, 'favicon.png'), fileDest);
  }

  utils.log('[OK]\n');

  utils.log('► Create gulpfile... ');

  utils.copy(path.join(source, 'gulpfile.js'), path.resolve(utils.path, 'gulpfile.js'));
  utils.copy(path.join(source, 'common-resources-gulpfile.js'), path.join(featuresDest, 'common/common-resources-gulpfile.js'));
  utils.copy(path.join(source, 'common-routes-gulpfile.js'), path.join(featuresDest, 'common/common-routes-gulpfile.js'));
  utils.copy(path.join(source, 'common-routes-template.js'), path.join(featuresDest, 'common/common-routes-template.js'));
  utils.copy(path.join(source, 'common-route-template.js'), path.join(featuresDest, 'common/common-route-template.js'));
  utils.copy(path.join(source, 'common-bootstrap.js'), path.join(featuresDest, 'common/views/common-bootstrap.js'));

  if (config.install.plumes) {
    utils.copy(path.join(source, 'common-plumes-gulpfile.js'), path.join(featuresDest, 'common/common-plumes-gulpfile.js'));
  }

  utils.log('[OK]\n');

  next();
}

module.exports = {
  install: [{
    type: 'confirm',
    name: 'plumes',
    message: 'Use jQuery + Ractive.js + Plumes?',
    default: true
  }, {
    type: 'confirm',
    name: 'plumes-unstable',
    message: 'Use Plumes #master version (unstable)?',
    default: false,
    when: function(answers) {
      return answers.plumes;
    }
  }],
  beforeInstall: beforeInstall,
  afterInstall: afterInstall,
  env: [{
    type: 'confirm',
    name: 'MINIFIED',
    message: 'Use minified asset files (js, css, ...)?',
    default: false
  }, {
    type: 'confirm',
    name: 'WATCHER',
    message: 'Watch files modifications (dev)?',
    default: true
  }]
};
<|endoftext|>


<commit_before>var webpack = require("webpack");

module.exports = {
	entry: {
		"index": [ // page
			'./src/riot/parts_1_router.tag', // parts 1
			'./src/riot/parts_2_router.tag', // parts 2
			'./src/riot/index.js'            // Need to last.
		]
	},
	output: {
		path: __dirname + '/dist/riot',
		filename: '[name].bundle.js',
		publicPath: '/'
	},
	watchOptions: { // Enabeling "webpack --watch" on Vagrant.
		poll: 1000
	},
	module: {
		rules: [
			{
				test: /\.tag$/,
				exclude: /node_modules/,
				enforce: 'pre',
				use: [
					{
						loader: 'riotjs-loader',
						options: {
							type: 'none' // Required 'none' for use Babel.
						}
					}
				]
			},
			{
				test: /\.js|\.tag$/,
				exclude: /node_modules/,
				enforce: 'post',
				use: [
					{
						loader: 'babel-loader',
						options: {}
					}
			 	]
			}
		]
	},
	resolve: {
			extensions: ['.js', '.tag']
	},
	plugins: [
		new webpack.optimize.CommonsChunkPlugin({ // Common function Storage.
			name:   'index',
			chunks: [ 'index', 'index.bundle.js' ],
		}),
		new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false
			}
		}),
		new webpack.ProvidePlugin({ riot: 'riot' })
	],
}
<commit_msg>Chang webpack polling time.<commit_after>var webpack = require("webpack");

module.exports = {
	entry: {
		"index": [ // page
			'./src/riot/parts_1_router.tag', // parts 1
			'./src/riot/parts_2_router.tag', // parts 2
			'./src/riot/index.js'            // Need to last.
		]
	},
	output: {
		path: __dirname + '/dist/riot',
		filename: '[name].bundle.js',
		publicPath: '/'
	},
	watchOptions: { // Enabeling "webpack --watch" on Vagrant.
		poll: 500
	},
	module: {
		rules: [
			{
				test: /\.tag$/,
				exclude: /node_modules/,
				enforce: 'pre',
				use: [
					{
						loader: 'riotjs-loader',
						options: {
							type: 'none' // Required 'none' for use Babel.
						}
					}
				]
			},
			{
				test: /\.js|\.tag$/,
				exclude: /node_modules/,
				enforce: 'post',
				use: [
					{
						loader: 'babel-loader',
						options: {}
					}
			 	]
			}
		]
	},
	resolve: {
			extensions: ['.js', '.tag']
	},
	plugins: [
		new webpack.optimize.CommonsChunkPlugin({ // Common function Storage.
			name:   'index',
			chunks: [ 'index', 'index.bundle.js' ],
		}),
		new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false
			}
		}),
		new webpack.ProvidePlugin({ riot: 'riot' })
	],
}
<|endoftext|>


<commit_before>$(document).ready(function(){
    google.maps.event.addDomListener(window, 'load', initialize);

    var map;
    var markers = [];

    // Add a marker to the map and push to the array.
    function addMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            map: map,
            animation: google.maps.Animation.DROP
        });
        marker.setIcon('http://upload.wikimedia.org/wikipedia/commons/5/55/Map_marker_icon_%E2%80%93_Nicolas_Mollet_%E2%80%93_Mosque_%E2%80%93_Tourism_%E2%80%93_Light.png');

        markers.push(marker);
    }

    /*
    North Austin Muslim Community Center (30.389909, -97.683871)
Nueces Mosque (30.283071, -97.744403)
Islamic Center of Greater Austin (30.299660, -97.686769)
Masjid Ibrahim (30.226751, -97.784788)
Islamic Ahlul Bayt Association (30.440130, -97.760555)
Islamic Center of Brushy Creek (30.507722, 97.792039)
Islamic Center of Round Rock (30.494335, -97.654810)
     */

    function showMosqueMarkers() {
        console.log("here");
        trucks = [[30.389909, -97.683871],[30.283071, -97.744403],[30.299660, -97.686769],[30.226751, -97.784788],[30.440130, -97.760555],[30.507722, 97.792039],[30.494335, -97.654810]];
        for (var i = 0; i < trucks.length; i++) {
            var truckLatLng = new google.maps.LatLng(trucks[i][0], trucks[i][1]);
            addMarker(truckLatLng);
        }
        showMarkers();
    }

    function initialize() {

        var initialLon = -97.67315599999999;
        var initialLat = 30.32919;
        var initialLatLon = new google.maps.LatLng(initialLat, initialLon);

        //Set up google map on div map-canvas centering around initial
        //latitude and longitude
        var mapOptions = {
            center: initialLatLon,
            zoom: 10
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

        //add marker to initial latitude and longitude
        addMarker(initialLatLon);
    };

    // Sets the map on all markers in the array.
    function setAllMap(map) {
        for (var i=0; i < markers.length; i++) {
            markers[i].setMap(map);
        }
    }

    // Removes the markers from the map, but keeps them in the array.
    function clearMarkers() {
        setAllMap(null);
    }

    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
        clearMarkers();
        markers = [];
    }

    // Shows any markers currently in the array.
    function showMarkers() {
        setAllMap(map);
    }

    //use Google geocoding API to convert address to lat and lon
    function getLatLonFromAddress(search_text) {
        var api_call = "https://maps.googleapis.com/maps/api/geocode/json?address=" + search_text;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", api_call, false);
        xhr.send();

        var location = JSON.parse(xhr.response)['results'][0];
        var location = location['geometry']['location'];

        return location;
    }

    //Attach handler for enter pressed in search bar event
    $('#searchbox').bind('keypress', function(e) {
        if (e.keyCode==13){
            //window.location = "http://festively.herokuapp.com/search-results";

            //clear existing markers on map
            deleteMarkers();
            event.preventDefault();

            //exchange address for latitude and longitude
            var search_text = $('#searchbox').val();
            var location = getLatLonFromAddress(search_text);
            var latitude = location['lat'];
            var longitude = location['lng'];
            console.log(latitude);
            console.log(longitude);

            //Set up map center and zoom around new address
            var latlng = new google.maps.LatLng(latitude, longitude);
            addMarker(latlng);
            map.setCenter(latlng);
            map.setZoom(10);

            showMosqueMarkers();
        }
    });
});<commit_msg>Dont show marker initially<commit_after>$(document).ready(function(){
    google.maps.event.addDomListener(window, 'load', initialize);

    var map;
    var markers = [];

    // Add a marker to the map and push to the array.
    function addMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            map: map,
            animation: google.maps.Animation.DROP
        });
        marker.setIcon('http://upload.wikimedia.org/wikipedia/commons/5/55/Map_marker_icon_%E2%80%93_Nicolas_Mollet_%E2%80%93_Mosque_%E2%80%93_Tourism_%E2%80%93_Light.png');

        markers.push(marker);
    }

    /*
    North Austin Muslim Community Center (30.389909, -97.683871)
Nueces Mosque (30.283071, -97.744403)
Islamic Center of Greater Austin (30.299660, -97.686769)
Masjid Ibrahim (30.226751, -97.784788)
Islamic Ahlul Bayt Association (30.440130, -97.760555)
Islamic Center of Brushy Creek (30.507722, 97.792039)
Islamic Center of Round Rock (30.494335, -97.654810)
     */

    function showMosqueMarkers() {
        console.log("here");
        trucks = [[30.389909, -97.683871],[30.283071, -97.744403],[30.299660, -97.686769],[30.226751, -97.784788],[30.440130, -97.760555],[30.507722, 97.792039],[30.494335, -97.654810]];
        for (var i = 0; i < trucks.length; i++) {
            var truckLatLng = new google.maps.LatLng(trucks[i][0], trucks[i][1]);
            addMarker(truckLatLng);
        }
        showMarkers();
    }

    function initialize() {

        var initialLon = -97.67315599999999;
        var initialLat = 30.32919;
        var initialLatLon = new google.maps.LatLng(initialLat, initialLon);

        //Set up google map on div map-canvas centering around initial
        //latitude and longitude
        var mapOptions = {
            center: initialLatLon,
            zoom: 10
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

        //add marker to initial latitude and longitude
        //addMarker(initialLatLon);
    };

    // Sets the map on all markers in the array.
    function setAllMap(map) {
        for (var i=0; i < markers.length; i++) {
            markers[i].setMap(map);
        }
    }

    // Removes the markers from the map, but keeps them in the array.
    function clearMarkers() {
        setAllMap(null);
    }

    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
        clearMarkers();
        markers = [];
    }

    // Shows any markers currently in the array.
    function showMarkers() {
        setAllMap(map);
    }

    //use Google geocoding API to convert address to lat and lon
    function getLatLonFromAddress(search_text) {
        var api_call = "https://maps.googleapis.com/maps/api/geocode/json?address=" + search_text;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", api_call, false);
        xhr.send();

        var location = JSON.parse(xhr.response)['results'][0];
        var location = location['geometry']['location'];

        return location;
    }

    //Attach handler for enter pressed in search bar event
    $('#searchbox').bind('keypress', function(e) {
        if (e.keyCode==13){
            //window.location = "http://festively.herokuapp.com/search-results";

            //clear existing markers on map
            deleteMarkers();
            event.preventDefault();

            //exchange address for latitude and longitude
            var search_text = $('#searchbox').val();
            var location = getLatLonFromAddress(search_text);
            var latitude = location['lat'];
            var longitude = location['lng'];
            console.log(latitude);
            console.log(longitude);

            //Set up map center and zoom around new address
            var latlng = new google.maps.LatLng(latitude, longitude);
            addMarker(latlng);
            map.setCenter(latlng);
            map.setZoom(10);

            showMosqueMarkers();
        }
    });
});<|endoftext|>


<commit_before>describe('The earthmine-data-formatter service', function () {
    var earthmineDataFormatter,
        input,
        output;

    beforeEach(function () {
        angular.mock.module(
            'dpStraatbeeld'
        );

        angular.mock.inject(function (_earthmineDataFormatter_) {
            earthmineDataFormatter = _earthmineDataFormatter_;
        });

        input = {
            'pano-id': '1000014016370',
            timestamp: '2012-07-15 13:27:32',
            location: {
                lon: 4.9219423482803,
                lat: 52.37672892191
            },
            'pano-orientation': {
                yaw: 11.744057655334,
                pitch: 3.5506110191345
            },
            connections: [
                {
                    'relative-location': {
                        yaw: -168.26495451758,
                        pitch: -0.46371610026191,
                        distance: 5.4100728048995
                    },
                    'pano-id': '1000014016369'
                },
                {
                    'relative-location': {
                        yaw: 14.56514641488,
                        pitch: 0.3063689539213,
                        distance: 5.4159216166952
                    },
                    'pano-id': '1000014016371'
                }
            ]
        };

        output = earthmineDataFormatter.formatPanoramaState(input);
    });

    it('restructes data from earthmine', function () {
        expect(output.id).toBeDefined();
        expect(output.date).toBeDefined();
        expect(output.car.location).toEqual([52.37672892191, 4.9219423482803]);
    });

    it('converts the id from a String to a Number', function () {
        expect(angular.isString(input['pano-id'])).toBe(true);
        expect(input['pano-id']).toBe('1000014016370');

        expect(angular.isNumber(output.id)).toBe(true);
        expect(output.id).toBe(1000014016370);
    });

    it('converts the date from a String to a Date object', function () {
        expect(angular.isString(input.timestamp)).toBe(true);

        expect(angular.isDate(output.date)).toBe(true);
        expect(output.date.getFullYear()).toBe(2012);
        expect(output.date.getMonth()).toBe(6);
        expect(output.date.getDate()).toBe(15);
    });
});
<commit_msg>Unit tests for the hotspot data structure.<commit_after>describe('The earthmine-data-formatter service', function () {
    var earthmineDataFormatter,
        input,
        output;

    beforeEach(function () {
        angular.mock.module(
            'dpStraatbeeld',
            {
                angleConversion: {
                    degreesToRadians: function (input) {
                        return input - 1;
                    }
                }
            }
        );

        angular.mock.inject(function (_earthmineDataFormatter_) {
            earthmineDataFormatter = _earthmineDataFormatter_;
        });

        input = {
            'pano-id': '1000014016370',
            timestamp: '2012-07-15 13:27:32',
            location: {
                lon: 4.9219423482803,
                lat: 52.37672892191
            },
            'pano-orientation': {
                yaw: 11.744057655334,
                pitch: 3.5506110191345
            },
            connections: [
                {
                    'relative-location': {
                        yaw: 1,
                        pitch: 2,
                        distance: 3
                    },
                    'pano-id': '1000014016369'
                },
                {
                    'relative-location': {
                        yaw: 7,
                        pitch: 8,
                        distance: 9
                    },
                    'pano-id': '1000014016371'
                }
            ]
        };

        output = earthmineDataFormatter.formatPanoramaState(input);
    });

    it('restructes data from earthmine', function () {
        expect(output.id).toBeDefined();
        expect(output.date).toBeDefined();
        expect(output.car.location).toEqual([52.37672892191, 4.9219423482803]);
    });

    it('converts the id from a String to a Number', function () {
        expect(angular.isString(input['pano-id'])).toBe(true);
        expect(input['pano-id']).toBe('1000014016370');

        expect(angular.isNumber(output.id)).toBe(true);
        expect(output.id).toBe(1000014016370);
    });

    it('converts the date from a String to a Date object', function () {
        expect(angular.isString(input.timestamp)).toBe(true);

        expect(angular.isDate(output.date)).toBe(true);
        expect(output.date.getFullYear()).toBe(2012);
        expect(output.date.getMonth()).toBe(6);
        expect(output.date.getDate()).toBe(15);
    });

    describe('hotspots', function () {
        it('convert the IDs from String to Number', function () {
            expect(output.hotspots[0].id).toBe(1000014016369);
            expect(output.hotspots[1].id).toBe(1000014016371);
        });

        it('converts the yaw and pitch from degrees to radians', function () {
            expect(output.hotspots[0].relativeLocation.yaw).toBe(0);
            expect(output.hotspots[0].relativeLocation.pitch).toBe(1);

            expect(output.hotspots[1].relativeLocation.yaw).toBe(6);
            expect(output.hotspots[1].relativeLocation.pitch).toBe(7);
        });

        it('has a distance property for each hotspot', function () {
            expect(output.hotspots[0].relativeLocation.distance).toBe(3);
            expect(output.hotspots[1].relativeLocation.distance).toBe(9);
        });
    });
});
<|endoftext|>