<commit_before>var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = {{#if_or unit e2e}}process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : {{/if_or}}config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  {{#if_eq projectType "lib"}}entry: {
    lib: './src'
  },{{/if_eq}}
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,{{#unless_eq projectType "lib"}}
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    {{/unless_eq}}{{#if_eq projectType "lib"}}
    library: '[name]',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    publicPath: process.env.NODE_ENV === 'production'
    ? config.build.assetsPublicPath
    : config.dev.assetsPublicPath
    {{/if_eq}}
  },{{#if_eq projectType "lib"}}
  externals: utils.buildExternalsFromDependencies(),{{/if_eq}}
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),{{#unless_eq projectType "lib"}}
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),{{/unless_eq}}
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath({{#unless_eq projectType "lib"}}'css/[name].[contenthash].css'{{/unless_eq}}{{#if_eq projectType "lib"}}'[name].css'{{/if_eq}})
    }),{{#unless_eq projectType "lib"}}
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: {{#if_or unit e2e}}process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : {{/if_or}}config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vender modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),{{/unless_eq}}
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
{{#unless_eq projectType "lib"}}
module.exports = webpackConfig{{/unless_eq}}{{#if_eq projectType "lib"}}
webpackMinifiedConfig = merge(webpackConfig, {
  output: {
    filename: '[name].min.js',
    chunkFilename: '[id].min.js',
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: '[name].min.css'
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    })
  ]
})

module.exports = [webpackConfig, webpackMinifiedConfig]{{/if_eq}}
<commit_msg>Fix css file output directory<commit_after>var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = {{#if_or unit e2e}}process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : {{/if_or}}config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  {{#if_eq projectType "lib"}}entry: {
    lib: './src'
  },{{/if_eq}}
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,{{#unless_eq projectType "lib"}}
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    {{/unless_eq}}{{#if_eq projectType "lib"}}
    library: '[name]',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    publicPath: process.env.NODE_ENV === 'production'
    ? config.build.assetsPublicPath
    : config.dev.assetsPublicPath
    {{/if_eq}}
  },{{#if_eq projectType "lib"}}
  externals: utils.buildExternalsFromDependencies(),{{/if_eq}}
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),{{#unless_eq projectType "lib"}}
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),{{/unless_eq}}
    // extract css into its own file
    new ExtractTextPlugin({
      filename: {{#unless_eq projectType "lib"}}utils.assetsPath('css/[name].[contenthash].css'){{/unless_eq}}{{#if_eq projectType "lib"}}'[name].css'{{/if_eq}}
    }),{{#unless_eq projectType "lib"}}
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: {{#if_or unit e2e}}process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : {{/if_or}}config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vender modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),{{/unless_eq}}
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
{{#unless_eq projectType "lib"}}
module.exports = webpackConfig{{/unless_eq}}{{#if_eq projectType "lib"}}
webpackMinifiedConfig = merge(webpackConfig, {
  output: {
    filename: '[name].min.js',
    chunkFilename: '[id].min.js',
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: '[name].min.css'
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    })
  ]
})

module.exports = [webpackConfig, webpackMinifiedConfig]{{/if_eq}}
<|endoftext|>


<commit_before>module.exports = {
    presets: [
        [
            '@babel/preset-env', {
                useBuiltIns: 'entry',
                corejs: 3,
                debug: false,
                // https://browserl.ist/?q=%3E1%25%2C+last+2+versions%2C+not+op_mini+all%2C+not+ie+%3E+0%2C+not+dead%2C+safari+%3E%3D+10%2C+iOS+%3E+8
                targets: ['>1%', 'last 2 versions', 'not op_mini all', 'not ie > 0', 'safari >= 10', 'iOS > 8', 'not dead'],
            },
        ],
        '@babel/preset-react',
    ],
    plugins: [
        '@babel/transform-runtime',
        '@babel/plugin-proposal-optional-chaining',

        ['@babel/plugin-proposal-decorators', { legacy: true } ],
        ['@babel/plugin-proposal-class-properties', { loose: true } ],
        ['babel-plugin-transform-imports', {
            'react-bootstrap': {
                transform: 'react-bootstrap/${member}',
                'preventFullImport': true,
            },
            lodash: {
                transform: 'lodash/${member}',
                preventFullImport: ('test' === process.env.NODE_ENV) ? false : true,
            },
        }],
        [ 'babel-plugin-styled-components', {
            fileName: false,
        }],
        '@babel/plugin-proposal-export-default-from',
        '@babel/plugin-syntax-dynamic-import',
    ],
};
<commit_msg>switch to loose: false as recommended by mobx<commit_after>module.exports = {
    presets: [
        [
            '@babel/preset-env', {
                useBuiltIns: 'entry',
                corejs: 3,
                debug: false,
                // https://browserl.ist/?q=%3E1%25%2C+last+2+versions%2C+not+op_mini+all%2C+not+ie+%3E+0%2C+not+dead%2C+safari+%3E%3D+10%2C+iOS+%3E+8
                targets: ['>1%', 'last 2 versions', 'not op_mini all', 'not ie > 0', 'safari >= 10', 'iOS > 8', 'not dead'],
            },
        ],
        '@babel/preset-react',
    ],
    plugins: [
        '@babel/transform-runtime',
        '@babel/plugin-proposal-optional-chaining',

        ['@babel/plugin-proposal-decorators', { legacy: true } ],
        ['@babel/plugin-proposal-class-properties', { loose: false } ],
        ['babel-plugin-transform-imports', {
            'react-bootstrap': {
                transform: 'react-bootstrap/${member}',
                'preventFullImport': true,
            },
            lodash: {
                transform: 'lodash/${member}',
                preventFullImport: ('test' === process.env.NODE_ENV) ? false : true,
            },
        }],
        [ 'babel-plugin-styled-components', {
            fileName: false,
        }],
        '@babel/plugin-proposal-export-default-from',
        '@babel/plugin-syntax-dynamic-import',
    ],
};
<|endoftext|>


<commit_before>module.exports = {
    "sourceMaps": "inline",
    "presets": [
        ["@babel/preset-env", {
            "targets": {
                "browsers": [
                    "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions"
                ]
            },
            "modules": "commonjs"
        }],
        "@babel/preset-typescript",
        "@babel/preset-flow",
        "@babel/preset-react"
    ],
    "plugins": [
        ["@babel/plugin-proposal-decorators", {"legacy": false, decoratorsBeforeExport: true}],
        "@babel/plugin-proposal-export-default-from",
        "@babel/plugin-proposal-numeric-separator",
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-proposal-object-rest-spread",
        "@babel/plugin-transform-flow-comments",
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-transform-runtime"
    ]
};
<commit_msg>Remove legacy<commit_after>module.exports = {
    "sourceMaps": "inline",
    "presets": [
        ["@babel/preset-env", {
            "targets": {
                "browsers": [
                    "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions"
                ]
            },
            "modules": "commonjs"
        }],
        "@babel/preset-typescript",
        "@babel/preset-flow",
        "@babel/preset-react"
    ],
    "plugins": [
        ["@babel/plugin-proposal-decorators", {decoratorsBeforeExport: true}],
        "@babel/plugin-proposal-export-default-from",
        "@babel/plugin-proposal-numeric-separator",
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-proposal-object-rest-spread",
        "@babel/plugin-transform-flow-comments",
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-transform-runtime"
    ]
};
<|endoftext|>


<commit_before>const {app, dialog, shell, Menu} = require('electron')

const fs = require('fs')
const path = require('path')
const repl = require('repl')
const url = require('url')

// Parse command line options.
const argv = process.argv.slice(1)
const option = { file: null, help: null, version: null, webdriver: null, modules: [] }
for (let i = 0; i < argv.length; i++) {
  if (argv[i] === '--version' || argv[i] === '-v') {
    option.version = true
    break
  } else if (argv[i].match(/^--app=/)) {
    option.file = argv[i].split('=')[1]
    break
  } else if (argv[i] === '--help' || argv[i] === '-h') {
    option.help = true
    break
  } else if (argv[i] === '--interactive' || argv[i] === '-i') {
    option.interactive = true
  } else if (argv[i] === '--test-type=webdriver') {
    option.webdriver = true
  } else if (argv[i] === '--require' || argv[i] === '-r') {
    option.modules.push(argv[++i])
    continue
  } else if (argv[i][0] === '-') {
    continue
  } else {
    option.file = argv[i]
    break
  }
}

// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', () => {
  if (app.listeners('window-all-closed').length === 1 && !option.interactive) {
    app.quit()
  }
})

// Create default menu.
app.once('ready', () => {
  if (Menu.getApplicationMenu()) return

  const template = [
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Undo',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo'
        },
        {
          label: 'Redo',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo'
        },
        {
          type: 'separator'
        },
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        }
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click (item, focusedWindow) {
            if (focusedWindow) focusedWindow.reload()
          }
        },
        {
          label: 'Toggle Full Screen',
          accelerator: (() => {
            return (process.platform === 'darwin') ? 'Ctrl+Command+F' : 'F11'
          })(),
          click (item, focusedWindow) {
            if (focusedWindow) focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
          }
        },
        {
          label: 'Toggle Developer Tools',
          accelerator: (() => {
            return (process.platform === 'darwin') ? 'Alt+Command+I' : 'Ctrl+Shift+I'
          })(),
          click (item, focusedWindow) {
            if (focusedWindow) focusedWindow.toggleDevTools()
          }
        }
      ]
    },
    {
      label: 'Window',
      role: 'window',
      submenu: [
        {
          label: 'Minimize',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: 'Close',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Help',
      role: 'help',
      submenu: [
        {
          label: 'Learn More',
          click () {
            shell.openExternal('http://electron.atom.io')
          }
        },
        {
          label: 'Documentation',
          click () {
            shell.openExternal(
              `https://github.com/electron/electron/tree/v${process.versions.electron}/docs#readme`
            )
          }
        },
        {
          label: 'Community Discussions',
          click () {
            shell.openExternal('https://discuss.atom.io/c/electron')
          }
        },
        {
          label: 'Search Issues',
          click () {
            shell.openExternal('https://github.com/electron/electron/issues')
          }
        }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    template.unshift({
      label: 'Electron',
      submenu: [
        {
          label: 'About Electron',
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide Electron',
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click () { app.quit() }
        }
      ]
    })
    template[3].submenu.push(
      {
        type: 'separator'
      },
      {
        label: 'Bring All to Front',
        role: 'front'
      }
    )
  }

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
})

if (option.modules.length > 0) {
  require('module')._preloadModules(option.modules)
}

function loadApplicationPackage (packagePath) {
  // Add a flag indicating app is started from default app.
  process.defaultApp = true

  try {
    // Override app name and version.
    packagePath = path.resolve(packagePath)
    const packageJsonPath = path.join(packagePath, 'package.json')
    if (fs.existsSync(packageJsonPath)) {
      const packageJson = JSON.parse(fs.readFileSync(packageJsonPath))
      if (packageJson.version) app.setVersion(packageJson.version)

      if (packageJson.productName) {
        app.setName(packageJson.productName)
      } else if (packageJson.name) {
        app.setName(packageJson.name)
      }

      app.setPath('userData', path.join(app.getPath('appData'), app.getName()))
      app.setPath('userCache', path.join(app.getPath('cache'), app.getName()))
      app.setAppPath(packagePath)
    }

    // Run the app.
    require('module')._load(packagePath, module, true)
  } catch (e) {
    if (e.code === 'MODULE_NOT_FOUND') {
      app.focus()
      dialog.showErrorBox(
        'Error opening app',
        'The app provided is not a valid Electron app, please read the docs on how to write one:\n' +
        `https://github.com/electron/electron/tree/v${process.versions.electron}/docs

${e.toString()}`
      )
      process.exit(1)
    } else {
      console.error('App threw an error when running', e)
      throw e
    }
  }
}

function loadApplicationByUrl (appUrl) {
  require('./default_app').load(appUrl)
}

function startRepl () {
  repl.start('> ').on('exit', () => {
    process.exit(0)
  })
}

// Start the specified app if there is one specified in command line, otherwise
// start the default app.
if (option.file && !option.webdriver) {
  const file = option.file
  const protocol = url.parse(file).protocol
  const extension = path.extname(file)
  if (protocol === 'http:' || protocol === 'https:' || protocol === 'file:') {
    loadApplicationByUrl(file)
  } else if (extension === '.html' || extension === '.htm') {
    loadApplicationByUrl('file://' + path.resolve(file))
  } else {
    loadApplicationPackage(file)
  }
} else if (option.version) {
  console.log('v' + process.versions.electron)
  process.exit(0)
} else if (option.help) {
  const helpMessage = `Electron v${process.versions.electron} - Cross Platform Desktop Application Shell

  Usage: electron [options] [path]

  A path to an Electron application may be specified.
  The path must be one of the following:

    - index.js file.
    - Folder containing a package.json file.
    - Folder containing an index.js file.
    - .html/.htm file.
    - http://, https://, or file:// URL.

  Options:
    -h, --help            Print this usage message.
    -i, --interactive     Open a REPL to the main process.
    -r, --require         Module to preload (option can be repeated)
    -v, --version         Print the version.`
  console.log(helpMessage)
  process.exit(0)
} else if (option.interactive) {
  startRepl()
} else {
  const indexPath = path.join(__dirname, '/index.html')
  loadApplicationByUrl(`file://${indexPath}`)
}
<commit_msg>The "Error opening app" dialog, now with less attitude<commit_after>const {app, dialog, shell, Menu} = require('electron')

const fs = require('fs')
const path = require('path')
const repl = require('repl')
const url = require('url')

// Parse command line options.
const argv = process.argv.slice(1)
const option = { file: null, help: null, version: null, webdriver: null, modules: [] }
for (let i = 0; i < argv.length; i++) {
  if (argv[i] === '--version' || argv[i] === '-v') {
    option.version = true
    break
  } else if (argv[i].match(/^--app=/)) {
    option.file = argv[i].split('=')[1]
    break
  } else if (argv[i] === '--help' || argv[i] === '-h') {
    option.help = true
    break
  } else if (argv[i] === '--interactive' || argv[i] === '-i') {
    option.interactive = true
  } else if (argv[i] === '--test-type=webdriver') {
    option.webdriver = true
  } else if (argv[i] === '--require' || argv[i] === '-r') {
    option.modules.push(argv[++i])
    continue
  } else if (argv[i][0] === '-') {
    continue
  } else {
    option.file = argv[i]
    break
  }
}

// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', () => {
  if (app.listeners('window-all-closed').length === 1 && !option.interactive) {
    app.quit()
  }
})

// Create default menu.
app.once('ready', () => {
  if (Menu.getApplicationMenu()) return

  const template = [
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Undo',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo'
        },
        {
          label: 'Redo',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo'
        },
        {
          type: 'separator'
        },
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        }
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click (item, focusedWindow) {
            if (focusedWindow) focusedWindow.reload()
          }
        },
        {
          label: 'Toggle Full Screen',
          accelerator: (() => {
            return (process.platform === 'darwin') ? 'Ctrl+Command+F' : 'F11'
          })(),
          click (item, focusedWindow) {
            if (focusedWindow) focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
          }
        },
        {
          label: 'Toggle Developer Tools',
          accelerator: (() => {
            return (process.platform === 'darwin') ? 'Alt+Command+I' : 'Ctrl+Shift+I'
          })(),
          click (item, focusedWindow) {
            if (focusedWindow) focusedWindow.toggleDevTools()
          }
        }
      ]
    },
    {
      label: 'Window',
      role: 'window',
      submenu: [
        {
          label: 'Minimize',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: 'Close',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Help',
      role: 'help',
      submenu: [
        {
          label: 'Learn More',
          click () {
            shell.openExternal('http://electron.atom.io')
          }
        },
        {
          label: 'Documentation',
          click () {
            shell.openExternal(
              `https://github.com/electron/electron/tree/v${process.versions.electron}/docs#readme`
            )
          }
        },
        {
          label: 'Community Discussions',
          click () {
            shell.openExternal('https://discuss.atom.io/c/electron')
          }
        },
        {
          label: 'Search Issues',
          click () {
            shell.openExternal('https://github.com/electron/electron/issues')
          }
        }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    template.unshift({
      label: 'Electron',
      submenu: [
        {
          label: 'About Electron',
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide Electron',
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click () { app.quit() }
        }
      ]
    })
    template[3].submenu.push(
      {
        type: 'separator'
      },
      {
        label: 'Bring All to Front',
        role: 'front'
      }
    )
  }

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
})

if (option.modules.length > 0) {
  require('module')._preloadModules(option.modules)
}

function loadApplicationPackage (packagePath) {
  // Add a flag indicating app is started from default app.
  process.defaultApp = true

  try {
    // Override app name and version.
    packagePath = path.resolve(packagePath)
    const packageJsonPath = path.join(packagePath, 'package.json')
    if (fs.existsSync(packageJsonPath)) {
      const packageJson = JSON.parse(fs.readFileSync(packageJsonPath))
      if (packageJson.version) app.setVersion(packageJson.version)

      if (packageJson.productName) {
        app.setName(packageJson.productName)
      } else if (packageJson.name) {
        app.setName(packageJson.name)
      }

      app.setPath('userData', path.join(app.getPath('appData'), app.getName()))
      app.setPath('userCache', path.join(app.getPath('cache'), app.getName()))
      app.setAppPath(packagePath)
    }

    // Run the app.
    require('module')._load(packagePath, module, true)
  } catch (e) {
    if (e.code === 'MODULE_NOT_FOUND') {
      app.focus()
      dialog.showErrorBox(
        'Error opening app',
        'Unable to open or find an Electron app. The docs on how to write an app can be found here:\n' +
        `https://github.com/electron/electron/tree/v${process.versions.electron}/docs

${e.toString()}`
      )
      process.exit(1)
    } else {
      console.error('App threw an error when running', e)
      throw e
    }
  }
}

function loadApplicationByUrl (appUrl) {
  require('./default_app').load(appUrl)
}

function startRepl () {
  repl.start('> ').on('exit', () => {
    process.exit(0)
  })
}

// Start the specified app if there is one specified in command line, otherwise
// start the default app.
if (option.file && !option.webdriver) {
  const file = option.file
  const protocol = url.parse(file).protocol
  const extension = path.extname(file)
  if (protocol === 'http:' || protocol === 'https:' || protocol === 'file:') {
    loadApplicationByUrl(file)
  } else if (extension === '.html' || extension === '.htm') {
    loadApplicationByUrl('file://' + path.resolve(file))
  } else {
    loadApplicationPackage(file)
  }
} else if (option.version) {
  console.log('v' + process.versions.electron)
  process.exit(0)
} else if (option.help) {
  const helpMessage = `Electron v${process.versions.electron} - Cross Platform Desktop Application Shell

  Usage: electron [options] [path]

  A path to an Electron application may be specified.
  The path must be one of the following:

    - index.js file.
    - Folder containing a package.json file.
    - Folder containing an index.js file.
    - .html/.htm file.
    - http://, https://, or file:// URL.

  Options:
    -h, --help            Print this usage message.
    -i, --interactive     Open a REPL to the main process.
    -r, --require         Module to preload (option can be repeated)
    -v, --version         Print the version.`
  console.log(helpMessage)
  process.exit(0)
} else if (option.interactive) {
  startRepl()
} else {
  const indexPath = path.join(__dirname, '/index.html')
  loadApplicationByUrl(`file://${indexPath}`)
}
<|endoftext|>


<commit_before>import React, {Component} from "react"
import Popup from './components/Popup'
import Gallery from './components/Gallery'
import vanillaColorPicker from '../helpers/VanillaColorPicker';
import RxCheckBox from './components/RxCheckBox';
import i18n from '../i18n';

export default class ImageManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isVisible: false,
            settings: {},
            proportions: true,
            uploading: false,
            uploadError: null
        };

        this.updateImageList();

    }

    updateImageList() {
        this.props.api && this.props.api.getImageList && this.props.api.getImageList(this.state.pieceRef).then((list) => {
            // add index to item if not set by the server
            list.forEach((item, index) => {
                if (!item.id) {
                    item.id = index;
                }
            });
            this.setState({gallery: list})
        });
    }

    toggleImagePopup() {
        this.setState({isVisible: !this.state.isVisible})
    }

    onClose() {
        this.toggleImagePopup();
        this.state.onClose && this.state.onClose();
        this.resetData();
    }

    onSave() {
        this.toggleImagePopup();
        this.state.onSave && this.state.onSave(this.getImageData());
        this.resetData();
    }

    onUrlChange(imageData) {
        this.setState({url: imageData.url, alt: ""});
        this.getImageSize(imageData);
    }

    getImageSize(imageData, getOriginalSizeOnly) {

        //if is image from gallery
        if (imageData.width && imageData.height) {
            !getOriginalSizeOnly && this.setState({width: imageData.width, height: imageData.height});
            this.setState({originalWidth: imageData.width, originalHeight: imageData.height});
        } else {
            //if set by hands
            var that = this;
            var img = new Image();
            img.onload = function () {
                !getOriginalSizeOnly && that.setState({width: this.width, height: this.height});
                that.setState({originalWidth: this.width, originalHeight: this.height});
            };
            img.src = imageData.url;
        }

    }

    setBgSize(e) {
        let bgSize = e.target.value;
        this.setState({bgSize});
    }

    setBgPosition(e) {
        let bgPosition = e.target.value;
        this.setState({bgPosition});
    }

    setBgColor(e) {
        let bgColor = e.target.value;
        this.setState({bgColor});
    }

    pickBgColor(e) {
        this.attachPickerAndInvoke();
    }

    setBgRepeat(e) {
        let bgRepeat = e.target.value;
        this.setState({bgRepeat});
    }

    attachPickerAndInvoke() {
        // colors for picker
        let pickerColors = [
            "inherit",
            "#9b59b6",
            "#34495e",
            "#16a085",
            "#27ae60",
            "#2980b9",
            "#8e44ad",
            "#2c3e50",
            "#f1c40f",
            "#e67e22",
            "#e74c3c",
            "#bdc3c7",
            "#95a5a6",
            "#666",
            "#212121",
            "#f39c12",
            "#d2d064",
            "#4fbbf7",
            "#ffffff"
        ];

        /**
         * If we have previously created color picker that is not bound to correct element, kill it
         */
        if (this.picker) {
            if (this.picker.__boundElement != this.colorDiv) {
                this.picker.destroyPicker();
                this.picker = null;
            }
        }

        /**
         * If we still have a picker, open it
         */
        if (this.picker) {
            this.picker.openPicker();
        } else {
            //Create new picker
            this.picker = vanillaColorPicker(this.colorDiv);
            this.picker.set("customColors", pickerColors);
            this.picker.set("positionOnTop");
            this.picker.openPicker();
            this.picker.on("colorChosen", (color) => {
                if (color == "inherit") {
                    this.setState({
                        bgColor: ""
                    })
                } else {
                    this.setState({
                        bgColor: color
                    })
                }
            });
            this.picker.__boundElement = this.colorDiv;
        }
    }

    onWidthChange(e) {
        let newWidth = e.target.value;
        this.setState({width: newWidth});
        if (this.state.proportions) {
            this.setState({height: parseInt(newWidth * this.state.originalHeight / this.state.originalWidth)});
        }
    }

    onHeightChange(e) {
        let newHeight = e.target.value;
        this.setState({height: newHeight});
        if (this.state.proportions) {
            this.setState({width: parseInt(newHeight * this.state.originalWidth / this.state.originalHeight)});
        }
    }

    closePopup() {
        this.setState({isVisible: false})
    }

    showPopup() {
        this.setState({isVisible: true})
    }

    getImageData() {
        let data = {
            url: this.state.url,
            alt: this.state.alt || "",
            title: this.state.title || "",
        };

        /**
         * If image was resized, export new sizes
         */
        if (this.state.originalHeight != this.state.height || this.state.originalWidth != this.state.width) {
            data = {
                width: this.state.width,
                height: this.state.height,
                ...data
            }
        }

        /**
         * If editing background, pass backgrounds too
         */
        if (this.state.settings.editBackground) {
            data = {
                bgColor: this.state.bgColor,
                bgPosition: this.state.bgPosition,
                bgRepeat: this.state.bgRepeat,
                bgSize: this.state.bgSize,
                ...data
            }
        }

        return data;
    }

    setImageData(data) {
        data.alt = data.alt || "";
        data.title = data.title || "";
        this.setState(data);
        data.url && this.getImageSize(data, !!data.width);
        this.updateImageList();
    }

  sendFile(files) {
    if (this.props.api.uploadImage) {
      //if (!this.state.file || !this.state.file[0]) return;
      var formdata = new FormData();

      for(let i = 0; i < files.file.length; i++ ) {
        formdata.append("images[]", files.file[i], files.file[i].name);
      }
      this.setState({uploading: true});
      this.props.api.uploadImage(formdata).then((response) => {
        let newImageData = {
          url: response.url,
          thumbnailUrl: response.thumbnailUrl,
          width: response.width,
          height: response.height,
          id: response.id || this.state.gallery.length
        };

        this.onUrlChange(newImageData);
        if (this.state.gallery) {
          this.state.gallery.push(newImageData);
        }
        this.setState({file: null, uploading: false, uploadError: null});
      }, (e)=> {
        this.setState({file: null, uploading: false, uploadError: "Failed to Upload, Sorry"});
        console.error(e);
      });
    }
  }

    /**
     * save new images data
     * @param data {object} new image data
     */
    selectGalleryItem(data) {

        //change URL
        if (data.url != this.state.url) {
            this.onUrlChange(data)
        }
        data.pieceRef = this.state.pieceRef;
        this.setImageData(data)

    }

    deleteGalleryItem(id) {
        if (this.props.api.deleteImage) {
            this.props.api.deleteImage(id).then(() => {
                var index = this.state.gallery.findIndex(element => element.id === id);
                this.state.gallery.splice(index, 1);
                this.forceUpdate()
            })
        }
    }

    resetData() {
        this.setState({
            url: null,
            alt: null,
            title: null,
            api: {},
            width: null,
            height: null,
            originalHeight: null,
            originalWidth: null,
            onClose: null,
            onSave: null,
            settings: {}
        })
    }

    render() {
        return (

                { this.state.isVisible && <Popup isOpen={this.state.isVisible}>

                        Insert Image

                                Enter Image URL
                                <input onChange={e => this.onUrlChange.call(this, {url: e.target.value})}
                                       placeholder="http://domain.com/image.png" value={this.state.url || ""}/>

                            {!this.state.settings.editBackground &&

                                Add Image Alt Tag
                                <input onChange={e => this.setState({alt: e.target.value})}
                                       placeholder="Example: Dalmatian puppy playing fetch"
                                       value={this.state.alt || ""}/>

                            }

                                Enter Title Tag
                                <input onChange={e => this.setState({title: e.target.value})}
                                       placeholder="Image title" value={this.state.title || ""}/>

                            {this.state.settings.editDimensions &&

                                Customize Image Dimensions

                                    <input onChange={this.onWidthChange.bind(this)}
                                           placeholder="width" value={this.state.width || ""}
                                           style={{width: "65px", marginRight: "5px"}}/>

×

                                    <input onChange={this.onHeightChange.bind(this)}
                                           placeholder="height" value={this.state.height || ""}
                                           style={{width: "65px", marginLeft: "10px"}}/>

 {
                                    this.setState({proportions: !this.state.proportions})
                                }}>
                                    <RxCheckBox checked={this.state.proportions}/>
                                    Constrain proportions

                            }
                            {this.state.settings.editBackground &&

                                Customize Background Tiling & Fitting

                                    <select name="background-size" value={this.state.bgSize}
                                            onChange={this.setBgSize.bind(this)}>
                                        <option value="">Don't Resize</option>
                                        <option value="cover">Resize to Fill</option>
                                        <option value="contain">Resize to Fit</option>
                                    </select>

                                    <select name="background-repeat" value={this.state.bgRepeat}
                                            onChange={this.setBgRepeat.bind(this)}>
                                        <option value="no-repeat">No Tiling</option>
                                        <option value="repeat">Tile</option>
                                        <option value="repeat-x">Tile Horizontally</option>
                                        <option value="repeat-y">Tile Vertically</option>
                                    </select>

                                    <select name="background-position" value={this.state.bgPosition}
                                            onChange={this.setBgPosition.bind(this)}>
                                        <option value="50% 50%">Center</option>
                                        <option value="0px 0px">Top Left</option>
                                    </select>

}

                            {this.state.settings.editBackground &&

                                Specify Background Color

                                    <input ref={(input) => {
                                        this.colorInput = input;
                                    }} onChange={this.setBgColor.bind(this)}
                                           onClick={this.pickBgColor.bind(this)}
                                           placeholder="CSS Color" value={this.state.bgColor || ""}
                                           style={{width: "130px", marginRight: "5px"}}/>

 {
                                        this.colorDiv = div;
                                    }} onClick={this.pickBgColor.bind(this)} className="color-pick"
                                         style={{backgroundColor: this.state.bgColor || ""}}>

Click to pick a Color

                            }

                            <div className={"preview-wrapper " + (this.props.api.uploadImage ? "upload" : "no-upload") + (this.state.uploading ? " uploading": "")}
                                 style={{backgroundImage: `url(${this.state.url})`}}>
                                {this.props.api.uploadImage &&
                                <input type="file" className="upload" title="Choose a file to upload"
                                       onChange={(e) => {
                                           this.setState({file: e.target.files});
                                           this.sendFile({file: e.target.files});
                                       }}/>}

                            {!this.state.uploadError && this.props.api.uploadImage &&
Click Image to Upload
}
                            {this.state.uploadError &&
{this.state.uploadError}
}

Save

                    {
                        this.state.gallery &&
                        <Gallery gallery={this.state.gallery} api={this.props.api}
                                 onChange={(imageData) => {
                                     this.selectGalleryItem.call(this, imageData)
                                 }}
                                 onDelete={(id) => this.deleteGalleryItem.call(this, id)}
                        />
                    }

                </Popup>
                }

        )
    }
}
<commit_msg>changed an uploading of multiple images to the uploading single image<commit_after>import React, {Component} from "react"
import Popup from './components/Popup'
import Gallery from './components/Gallery'
import vanillaColorPicker from '../helpers/VanillaColorPicker';
import RxCheckBox from './components/RxCheckBox';
import i18n from '../i18n';

export default class ImageManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isVisible: false,
            settings: {},
            proportions: true,
            uploading: false,
            uploadError: null
        };

        this.updateImageList();

    }

    updateImageList() {
        this.props.api && this.props.api.getImageList && this.props.api.getImageList(this.state.pieceRef).then((list) => {
            // add index to item if not set by the server
            list.forEach((item, index) => {
                if (!item.id) {
                    item.id = index;
                }
            });
            this.setState({gallery: list})
        });
    }

    toggleImagePopup() {
        this.setState({isVisible: !this.state.isVisible})
    }

    onClose() {
        this.toggleImagePopup();
        this.state.onClose && this.state.onClose();
        this.resetData();
    }

    onSave() {
        this.toggleImagePopup();
        this.state.onSave && this.state.onSave(this.getImageData());
        this.resetData();
    }

    onUrlChange(imageData) {
        this.setState({url: imageData.url, alt: ""});
        this.getImageSize(imageData);
    }

    getImageSize(imageData, getOriginalSizeOnly) {

        //if is image from gallery
        if (imageData.width && imageData.height) {
            !getOriginalSizeOnly && this.setState({width: imageData.width, height: imageData.height});
            this.setState({originalWidth: imageData.width, originalHeight: imageData.height});
        } else {
            //if set by hands
            var that = this;
            var img = new Image();
            img.onload = function () {
                !getOriginalSizeOnly && that.setState({width: this.width, height: this.height});
                that.setState({originalWidth: this.width, originalHeight: this.height});
            };
            img.src = imageData.url;
        }

    }

    setBgSize(e) {
        let bgSize = e.target.value;
        this.setState({bgSize});
    }

    setBgPosition(e) {
        let bgPosition = e.target.value;
        this.setState({bgPosition});
    }

    setBgColor(e) {
        let bgColor = e.target.value;
        this.setState({bgColor});
    }

    pickBgColor(e) {
        this.attachPickerAndInvoke();
    }

    setBgRepeat(e) {
        let bgRepeat = e.target.value;
        this.setState({bgRepeat});
    }

    attachPickerAndInvoke() {
        // colors for picker
        let pickerColors = [
            "inherit",
            "#9b59b6",
            "#34495e",
            "#16a085",
            "#27ae60",
            "#2980b9",
            "#8e44ad",
            "#2c3e50",
            "#f1c40f",
            "#e67e22",
            "#e74c3c",
            "#bdc3c7",
            "#95a5a6",
            "#666",
            "#212121",
            "#f39c12",
            "#d2d064",
            "#4fbbf7",
            "#ffffff"
        ];

        /**
         * If we have previously created color picker that is not bound to correct element, kill it
         */
        if (this.picker) {
            if (this.picker.__boundElement != this.colorDiv) {
                this.picker.destroyPicker();
                this.picker = null;
            }
        }

        /**
         * If we still have a picker, open it
         */
        if (this.picker) {
            this.picker.openPicker();
        } else {
            //Create new picker
            this.picker = vanillaColorPicker(this.colorDiv);
            this.picker.set("customColors", pickerColors);
            this.picker.set("positionOnTop");
            this.picker.openPicker();
            this.picker.on("colorChosen", (color) => {
                if (color == "inherit") {
                    this.setState({
                        bgColor: ""
                    })
                } else {
                    this.setState({
                        bgColor: color
                    })
                }
            });
            this.picker.__boundElement = this.colorDiv;
        }
    }

    onWidthChange(e) {
        let newWidth = e.target.value;
        this.setState({width: newWidth});
        if (this.state.proportions) {
            this.setState({height: parseInt(newWidth * this.state.originalHeight / this.state.originalWidth)});
        }
    }

    onHeightChange(e) {
        let newHeight = e.target.value;
        this.setState({height: newHeight});
        if (this.state.proportions) {
            this.setState({width: parseInt(newHeight * this.state.originalWidth / this.state.originalHeight)});
        }
    }

    closePopup() {
        this.setState({isVisible: false})
    }

    showPopup() {
        this.setState({isVisible: true})
    }

    getImageData() {
        let data = {
            url: this.state.url,
            alt: this.state.alt || "",
            title: this.state.title || "",
        };

        /**
         * If image was resized, export new sizes
         */
        if (this.state.originalHeight != this.state.height || this.state.originalWidth != this.state.width) {
            data = {
                width: this.state.width,
                height: this.state.height,
                ...data
            }
        }

        /**
         * If editing background, pass backgrounds too
         */
        if (this.state.settings.editBackground) {
            data = {
                bgColor: this.state.bgColor,
                bgPosition: this.state.bgPosition,
                bgRepeat: this.state.bgRepeat,
                bgSize: this.state.bgSize,
                ...data
            }
        }

        return data;
    }

    setImageData(data) {
        data.alt = data.alt || "";
        data.title = data.title || "";
        this.setState(data);
        data.url && this.getImageSize(data, !!data.width);
        this.updateImageList();
    }

  sendFile(files) {
    if (this.props.api.uploadImage) {
      //if (!this.state.file || !this.state.file[0]) return;
      var formdata = new FormData();

      //save code. If it will necessary use multiple files uploadin then just uncomment this code
    /*  for(let i = 0; i < files.file.length; i++ ) {
        formdata.append("images[]", files.file[i], files.file[i].name);
      }*/
      formdata.append("image", files.file[0]);
      this.setState({uploading: true});
      this.props.api.uploadImage(formdata).then((response) => {
        let newImageData = {
          url: response.url,
          thumbnailUrl: response.thumbnailUrl,
          width: response.width,
          height: response.height,
          id: response.id || this.state.gallery.length
        };

        this.onUrlChange(newImageData);
        if (this.state.gallery) {
          this.state.gallery.push(newImageData);
        }
        this.setState({file: null, uploading: false, uploadError: null});
      }, (e)=> {
        this.setState({file: null, uploading: false, uploadError: "Failed to Upload, Sorry"});
        console.error(e);
      });
    }
  }

    /**
     * save new images data
     * @param data {object} new image data
     */
    selectGalleryItem(data) {

        //change URL
        if (data.url != this.state.url) {
            this.onUrlChange(data)
        }
        data.pieceRef = this.state.pieceRef;
        this.setImageData(data)

    }

    deleteGalleryItem(id) {
        if (this.props.api.deleteImage) {
            this.props.api.deleteImage(id).then(() => {
                var index = this.state.gallery.findIndex(element => element.id === id);
                this.state.gallery.splice(index, 1);
                this.forceUpdate()
            })
        }
    }

    resetData() {
        this.setState({
            url: null,
            alt: null,
            title: null,
            api: {},
            width: null,
            height: null,
            originalHeight: null,
            originalWidth: null,
            onClose: null,
            onSave: null,
            settings: {}
        })
    }

    render() {
        return (

                { this.state.isVisible && <Popup isOpen={this.state.isVisible}>

                        Insert Image

                                Enter Image URL
                                <input onChange={e => this.onUrlChange.call(this, {url: e.target.value})}
                                       placeholder="http://domain.com/image.png" value={this.state.url || ""}/>

                            {!this.state.settings.editBackground &&

                                Add Image Alt Tag
                                <input onChange={e => this.setState({alt: e.target.value})}
                                       placeholder="Example: Dalmatian puppy playing fetch"
                                       value={this.state.alt || ""}/>

                            }

                                Enter Title Tag
                                <input onChange={e => this.setState({title: e.target.value})}
                                       placeholder="Image title" value={this.state.title || ""}/>

                            {this.state.settings.editDimensions &&

                                Customize Image Dimensions

                                    <input onChange={this.onWidthChange.bind(this)}
                                           placeholder="width" value={this.state.width || ""}
                                           style={{width: "65px", marginRight: "5px"}}/>

×

                                    <input onChange={this.onHeightChange.bind(this)}
                                           placeholder="height" value={this.state.height || ""}
                                           style={{width: "65px", marginLeft: "10px"}}/>

 {
                                    this.setState({proportions: !this.state.proportions})
                                }}>
                                    <RxCheckBox checked={this.state.proportions}/>
                                    Constrain proportions

                            }
                            {this.state.settings.editBackground &&

                                Customize Background Tiling & Fitting

                                    <select name="background-size" value={this.state.bgSize}
                                            onChange={this.setBgSize.bind(this)}>
                                        <option value="">Don't Resize</option>
                                        <option value="cover">Resize to Fill</option>
                                        <option value="contain">Resize to Fit</option>
                                    </select>

                                    <select name="background-repeat" value={this.state.bgRepeat}
                                            onChange={this.setBgRepeat.bind(this)}>
                                        <option value="no-repeat">No Tiling</option>
                                        <option value="repeat">Tile</option>
                                        <option value="repeat-x">Tile Horizontally</option>
                                        <option value="repeat-y">Tile Vertically</option>
                                    </select>

                                    <select name="background-position" value={this.state.bgPosition}
                                            onChange={this.setBgPosition.bind(this)}>
                                        <option value="50% 50%">Center</option>
                                        <option value="0px 0px">Top Left</option>
                                    </select>

}

                            {this.state.settings.editBackground &&

                                Specify Background Color

                                    <input ref={(input) => {
                                        this.colorInput = input;
                                    }} onChange={this.setBgColor.bind(this)}
                                           onClick={this.pickBgColor.bind(this)}
                                           placeholder="CSS Color" value={this.state.bgColor || ""}
                                           style={{width: "130px", marginRight: "5px"}}/>

 {
                                        this.colorDiv = div;
                                    }} onClick={this.pickBgColor.bind(this)} className="color-pick"
                                         style={{backgroundColor: this.state.bgColor || ""}}>

Click to pick a Color

                            }

                            <div className={"preview-wrapper " + (this.props.api.uploadImage ? "upload" : "no-upload") + (this.state.uploading ? " uploading": "")}
                                 style={{backgroundImage: `url(${this.state.url})`}}>
                                {this.props.api.uploadImage &&
                                <input type="file" className="upload" title="Choose a file to upload"
                                       onChange={(e) => {
                                           this.setState({file: e.target.files});
                                           this.sendFile({file: e.target.files});
                                       }}/>}

                            {!this.state.uploadError && this.props.api.uploadImage &&
Click Image to Upload
}
                            {this.state.uploadError &&
{this.state.uploadError}
}

Save

                    {
                        this.state.gallery &&
                        <Gallery gallery={this.state.gallery} api={this.props.api}
                                 onChange={(imageData) => {
                                     this.selectGalleryItem.call(this, imageData)
                                 }}
                                 onDelete={(id) => this.deleteGalleryItem.call(this, id)}
                        />
                    }

                </Popup>
                }

        )
    }
}
<|endoftext|>


<commit_before>const path = require('path');

module.exports = {
  extends: path.resolve(process.cwd(), './node_modules/carbon-factory/babel.config.js')
};
<commit_msg>chore: move babel config into carbon<commit_after>module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        useBuiltIns: 'usage',
        targets: {
          browsers: 'IE 11'
        },
        corejs: 3
      }
    ],
    '@babel/preset-react',
    '@babel/preset-typescript'
  ],
  plugins: [
    '@babel/plugin-proposal-function-bind',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-proposal-object-rest-spread',
    '@babel/plugin-syntax-dynamic-import'
  ]
};
<|endoftext|>


<commit_before>const {app, shell, BrowserWindow, ipcMain} = require('electron');
const os = require('os');
const fs = require('fs');
const stream = require('stream');
const path = require('path');
const readline = require('readline');
const liburl = require('url');
const http = require('http');

const {DEFAULT_CONFIG_STRUCTURE} = require('./defs/bs-config-template');

const {
  MAIN_INIT,
  MAIN_ERROR,
  MAIN_START_BS,
  MAIN_START_PAC,
  MAIN_STOP_PAC,
  MAIN_STOP_BS,
  MAIN_SET_SYS_PAC,
  MAIN_SET_SYS_PROXY,
  MAIN_RESTORE_SYS_PAC,
  MAIN_RESTORE_SYS_PROXY,
  RENDERER_INIT,
  RENDERER_START_BS,
  RENDERER_STOP_BS,
  RENDERER_START_PAC,
  RENDERER_STOP_PAC,
  RENDERER_SAVE_CONFIG,
  RENDERER_SET_SYS_PAC,
  RENDERER_SET_SYS_PROXY,
  RENDERER_RESTORE_SYS_PAC,
  RENDERER_RESTORE_SYS_PROXY
} = require('./defs/events');

const packageJson = require('./package.json');

const {Hub} = require('blinksocks');
const {createSysProxy} = require('./system/create');
const {createPacService} = require('./services/pac');

const HOME_DIR = os.homedir();
const BLINKSOCKS_DIR = path.join(HOME_DIR, '.blinksocks');
const DEFAULT_GFWLIST_PATH = path.join(BLINKSOCKS_DIR, 'gfwlist.txt');

// create .blinksocks directory if not exist
try {
  fs.lstatSync(BLINKSOCKS_DIR);
} catch (err) {
  if (err.code === 'ENOENT') {
    fs.mkdirSync(BLINKSOCKS_DIR);
  }
}

// copy built-in gfwlist.txt if not exist
try {
  fs.lstatSync(DEFAULT_GFWLIST_PATH);
} catch (err) {
  if (err.code === 'ENOENT') {
    const data = fs.readFileSync(path.join(__dirname, 'resources/gfwlist.txt'));
    fs.writeFileSync(DEFAULT_GFWLIST_PATH, data);
  }
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
let config;
let bs; // blinksocks client
let pacService;
let sysProxy;

const __PRODUCTION__ =
  (typeof process.env.NODE_ENV === 'undefined') || process.env.NODE_ENV === 'production';

const DEFAULT_CONFIG_FILE = path.join(BLINKSOCKS_DIR, 'blinksocks.client.js');

function loadConfig() {
  let json;
  // resolve to absolute path
  const file = DEFAULT_CONFIG_FILE;
  try {
    const ext = path.extname(file);
    if (ext === '.js') {
      // require .js directly
      delete require.cache[require.resolve(file)];
      json = require(file);
    } else {
      // others are treated as .json
      const jsonFile = fs.readFileSync(file);
      json = JSON.parse(jsonFile);
    }
  } catch (err) {
    if (err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND') {
      saveConfig(DEFAULT_CONFIG_STRUCTURE);
      return DEFAULT_CONFIG_STRUCTURE;
    }
    throw Error(`fail to load/parse your '${DEFAULT_CONFIG_FILE}': ${err}`);
  }
  return json;
}

function saveConfig(json) {
  const data = `module.exports = ${JSON.stringify(json, null, '  ')};`;
  fs.writeFile(DEFAULT_CONFIG_FILE, data, (err) => {
    if (err) {
      console.error(err);
    }
  });
}

function parseRules(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        reject(err);
      } else {
        const sr = new stream.PassThrough();
        sr.end(Buffer.from(data, 'base64').toString('ascii'));
        const rl = readline.createInterface({input: sr});
        let index = 0;
        const domains = [];
        rl.on('line', (line) => {
          if (!(line.startsWith('!')) && line.length > 0 && index !== 0) {
            domains.push(line);
          }
          index += 1;
        });
        rl.on('close', () => resolve(domains));
      }
    });
  });
}

function onAppClose() {
  // 1. shutdown pac service
  if (pacService) {
    pacService.stop();
    pacService = null;
  }
  // 2. shutdown blinksocks client
  if (bs) {
    bs.terminate();
    bs = null;
  }
  // 3. restore all system settings
  if (sysProxy) {
    Promise
      .all([
        sysProxy.restoreGlobal({
          host: config.host,
          port: config.port,
          bypass: config.bypass
        }),
        sysProxy.restorePAC({url: config.pac})
      ])
      .then(() => null);
  }
  // 4. save config
  saveConfig(Object.assign({}, config, {app_status: 0, pac_status: 0}));
}

// Electron stuff

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    title: `${packageJson.name} v${packageJson.version}`,
    width: 380,
    height: 620,
    minWidth: 380,
    minHeight: 620
  });

  // and load the index.html of the app.
  if (__PRODUCTION__) {
    win.loadURL(liburl.format({
      pathname: path.join(__dirname, 'build/index.html'),
      protocol: 'file:',
      slashes: true
    }));
  } else {
    win.loadURL(liburl.format({
      pathname: 'localhost:3000',
      protocol: 'http:',
      slashes: true
    }));
  }

  // Open the DevTools.
  if (!__PRODUCTION__) {
    win.webContents.openDevTools();
  }

  win.webContents.on('new-window', function (e, url) {
    e.preventDefault();
    shell.openExternal(url);
  });

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null;
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  try {
    // 1. initialize then cache
    config = loadConfig();
    sysProxy = await createSysProxy();
    pacService = createPacService();
    // 2. display window
    createWindow();
  } catch (err) {
    console.error(err);
    process.exit(-1);
  }
});

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow();
  }
});

app.on('before-quit', onAppClose);

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

const ipcHandlers = {
  [RENDERER_INIT]: (e) => {
    if (process.platform === 'win32') {
      require('readline').createInterface({
        input: process.stdin,
        output: process.stdout
      }).on('SIGINT', function () {
        process.emit('SIGINT');
      });
    }

    process.on('SIGINT', onAppClose);
    process.on('SIGTERM', onAppClose);
    process.on('uncaughtException', (err) => {
      switch (err.code) {
        case 'EADDRINUSE':
          bs.terminate();
          bs = null;
          break;
        default:
          break;
      }
      e.sender.send(MAIN_ERROR, err);
      console.error(err);
    });

    e.sender.send(MAIN_INIT, {config});
  },
  [RENDERER_START_BS]: (e, {config}) => {
    if (!bs) {
      bs = new Hub(config);
      bs.run(() => e.sender.send(MAIN_START_BS));
    }
  },
  [RENDERER_STOP_BS]: (e) => {
    if (bs) {
      bs.terminate();
      bs = null;
    }
    e.sender.send(MAIN_STOP_BS);
  },
  [RENDERER_SAVE_CONFIG]: (e, json) => {
    saveConfig(json);
    config = json; // update cached global.config
  },
  [RENDERER_START_PAC]: async (e, {url}) => {
    const {host, port} = liburl.parse(url);
    if (pacService) {
      const rules = await parseRules(DEFAULT_GFWLIST_PATH);
      pacService.start({
        host,
        port,
        proxyHost: config.host,
        proxyPort: config.port,
        rules
      });
      e.sender.send(MAIN_START_PAC);
    }
  },
  [RENDERER_STOP_PAC]: (e) => {
    if (pacService) {
      pacService.stop();
    }
    e.sender.send(MAIN_STOP_PAC);
  },
  [RENDERER_SET_SYS_PROXY]: async (e, {host, port, bypass}) => {
    await sysProxy.setGlobal({host, port, bypass});
    e.sender.send(MAIN_SET_SYS_PROXY);
  },
  [RENDERER_SET_SYS_PAC]: async (e, {url}) => {
    await sysProxy.setPAC({url});
    e.sender.send(MAIN_SET_SYS_PAC);
  },
  [RENDERER_RESTORE_SYS_PROXY]: async (e, {host, port, bypass}) => {
    await sysProxy.restoreGlobal({host, port, bypass});
    e.sender.send(MAIN_RESTORE_SYS_PROXY);
  },
  [RENDERER_RESTORE_SYS_PAC]: async (e, {url}) => {
    await sysProxy.restorePAC({url});
    e.sender.send(MAIN_RESTORE_SYS_PAC);
  }
};

Object.keys(ipcHandlers).forEach(
  (eventName) => ipcMain.on(eventName, ipcHandlers[eventName])
);
<commit_msg>fix(main): quit app when all windows closed<commit_after>const {app, shell, BrowserWindow, ipcMain} = require('electron');
const os = require('os');
const fs = require('fs');
const stream = require('stream');
const path = require('path');
const readline = require('readline');
const liburl = require('url');
const http = require('http');

const {DEFAULT_CONFIG_STRUCTURE} = require('./defs/bs-config-template');

const {
  MAIN_INIT,
  MAIN_ERROR,
  MAIN_START_BS,
  MAIN_START_PAC,
  MAIN_STOP_PAC,
  MAIN_STOP_BS,
  MAIN_SET_SYS_PAC,
  MAIN_SET_SYS_PROXY,
  MAIN_RESTORE_SYS_PAC,
  MAIN_RESTORE_SYS_PROXY,
  RENDERER_INIT,
  RENDERER_START_BS,
  RENDERER_STOP_BS,
  RENDERER_START_PAC,
  RENDERER_STOP_PAC,
  RENDERER_SAVE_CONFIG,
  RENDERER_SET_SYS_PAC,
  RENDERER_SET_SYS_PROXY,
  RENDERER_RESTORE_SYS_PAC,
  RENDERER_RESTORE_SYS_PROXY
} = require('./defs/events');

const packageJson = require('./package.json');

const {Hub} = require('blinksocks');
const {createSysProxy} = require('./system/create');
const {createPacService} = require('./services/pac');

const HOME_DIR = os.homedir();
const BLINKSOCKS_DIR = path.join(HOME_DIR, '.blinksocks');
const DEFAULT_GFWLIST_PATH = path.join(BLINKSOCKS_DIR, 'gfwlist.txt');

// create .blinksocks directory if not exist
try {
  fs.lstatSync(BLINKSOCKS_DIR);
} catch (err) {
  if (err.code === 'ENOENT') {
    fs.mkdirSync(BLINKSOCKS_DIR);
  }
}

// copy built-in gfwlist.txt if not exist
try {
  fs.lstatSync(DEFAULT_GFWLIST_PATH);
} catch (err) {
  if (err.code === 'ENOENT') {
    const data = fs.readFileSync(path.join(__dirname, 'resources/gfwlist.txt'));
    fs.writeFileSync(DEFAULT_GFWLIST_PATH, data);
  }
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
let config;
let bs; // blinksocks client
let pacService;
let sysProxy;

const __PRODUCTION__ =
  (typeof process.env.NODE_ENV === 'undefined') || process.env.NODE_ENV === 'production';

const DEFAULT_CONFIG_FILE = path.join(BLINKSOCKS_DIR, 'blinksocks.client.js');

function loadConfig() {
  let json;
  // resolve to absolute path
  const file = DEFAULT_CONFIG_FILE;
  try {
    const ext = path.extname(file);
    if (ext === '.js') {
      // require .js directly
      delete require.cache[require.resolve(file)];
      json = require(file);
    } else {
      // others are treated as .json
      const jsonFile = fs.readFileSync(file);
      json = JSON.parse(jsonFile);
    }
  } catch (err) {
    if (err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND') {
      saveConfig(DEFAULT_CONFIG_STRUCTURE);
      return DEFAULT_CONFIG_STRUCTURE;
    }
    throw Error(`fail to load/parse your '${DEFAULT_CONFIG_FILE}': ${err}`);
  }
  return json;
}

function saveConfig(json) {
  const data = `module.exports = ${JSON.stringify(json, null, '  ')};`;
  fs.writeFile(DEFAULT_CONFIG_FILE, data, (err) => {
    if (err) {
      console.error(err);
    }
  });
}

function parseRules(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        reject(err);
      } else {
        const sr = new stream.PassThrough();
        sr.end(Buffer.from(data, 'base64').toString('ascii'));
        const rl = readline.createInterface({input: sr});
        let index = 0;
        const domains = [];
        rl.on('line', (line) => {
          if (!(line.startsWith('!')) && line.length > 0 && index !== 0) {
            domains.push(line);
          }
          index += 1;
        });
        rl.on('close', () => resolve(domains));
      }
    });
  });
}

function onAppClose() {
  // 1. shutdown pac service
  if (pacService) {
    pacService.stop();
    pacService = null;
  }
  // 2. shutdown blinksocks client
  if (bs) {
    bs.terminate();
    bs = null;
  }
  // 3. restore all system settings
  if (sysProxy) {
    Promise
      .all([
        sysProxy.restoreGlobal({
          host: config.host,
          port: config.port,
          bypass: config.bypass
        }),
        sysProxy.restorePAC({url: config.pac})
      ])
      .then(() => null);
  }
  // 4. save config
  saveConfig(Object.assign({}, config, {app_status: 0, pac_status: 0}));
}

// Electron stuff

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    title: `${packageJson.name} v${packageJson.version}`,
    width: 380,
    height: 620,
    minWidth: 380,
    minHeight: 620
  });

  // and load the index.html of the app.
  if (__PRODUCTION__) {
    win.loadURL(liburl.format({
      pathname: path.join(__dirname, 'build/index.html'),
      protocol: 'file:',
      slashes: true
    }));
  } else {
    win.loadURL(liburl.format({
      pathname: 'localhost:3000',
      protocol: 'http:',
      slashes: true
    }));
  }

  // Open the DevTools.
  if (!__PRODUCTION__) {
    win.webContents.openDevTools();
  }

  win.webContents.on('new-window', function (e, url) {
    e.preventDefault();
    shell.openExternal(url);
  });

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null;
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  try {
    // 1. initialize then cache
    config = loadConfig();
    sysProxy = await createSysProxy();
    pacService = createPacService();
    // 2. display window
    createWindow();
  } catch (err) {
    console.error(err);
    process.exit(-1);
  }
});

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow();
  }
});

app.on('before-quit', onAppClose);

app.on('window-all-closed', app.quit);

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

const ipcHandlers = {
  [RENDERER_INIT]: (e) => {
    if (process.platform === 'win32') {
      require('readline').createInterface({
        input: process.stdin,
        output: process.stdout
      }).on('SIGINT', function () {
        process.emit('SIGINT');
      });
    }

    process.on('SIGINT', onAppClose);
    process.on('SIGTERM', onAppClose);
    process.on('uncaughtException', (err) => {
      switch (err.code) {
        case 'EADDRINUSE':
          bs.terminate();
          bs = null;
          break;
        default:
          break;
      }
      e.sender.send(MAIN_ERROR, err);
      console.error(err);
    });

    e.sender.send(MAIN_INIT, {config});
  },
  [RENDERER_START_BS]: (e, {config}) => {
    if (!bs) {
      bs = new Hub(config);
      bs.run(() => e.sender.send(MAIN_START_BS));
    }
  },
  [RENDERER_STOP_BS]: (e) => {
    if (bs) {
      bs.terminate();
      bs = null;
    }
    e.sender.send(MAIN_STOP_BS);
  },
  [RENDERER_SAVE_CONFIG]: (e, json) => {
    saveConfig(json);
    config = json; // update cached global.config
  },
  [RENDERER_START_PAC]: async (e, {url}) => {
    const {host, port} = liburl.parse(url);
    if (pacService) {
      const rules = await parseRules(DEFAULT_GFWLIST_PATH);
      pacService.start({
        host,
        port,
        proxyHost: config.host,
        proxyPort: config.port,
        rules
      });
      e.sender.send(MAIN_START_PAC);
    }
  },
  [RENDERER_STOP_PAC]: (e) => {
    if (pacService) {
      pacService.stop();
    }
    e.sender.send(MAIN_STOP_PAC);
  },
  [RENDERER_SET_SYS_PROXY]: async (e, {host, port, bypass}) => {
    await sysProxy.setGlobal({host, port, bypass});
    e.sender.send(MAIN_SET_SYS_PROXY);
  },
  [RENDERER_SET_SYS_PAC]: async (e, {url}) => {
    await sysProxy.setPAC({url});
    e.sender.send(MAIN_SET_SYS_PAC);
  },
  [RENDERER_RESTORE_SYS_PROXY]: async (e, {host, port, bypass}) => {
    await sysProxy.restoreGlobal({host, port, bypass});
    e.sender.send(MAIN_RESTORE_SYS_PROXY);
  },
  [RENDERER_RESTORE_SYS_PAC]: async (e, {url}) => {
    await sysProxy.restorePAC({url});
    e.sender.send(MAIN_RESTORE_SYS_PAC);
  }
};

Object.keys(ipcHandlers).forEach(
  (eventName) => ipcMain.on(eventName, ipcHandlers[eventName])
);
<|endoftext|>


<commit_before>
gridWidth = grid[0].length;
gridHeight = grid.length;

canvasWidth = 1000; //window.innerWidth;
canvasHeight = 650; //(window.innerHeight / 100) * 80;

players = [];
velocity = [2,2];

startX = 0;
startY = 0;

$(document).ready(function() {

  var interval;
  $("header").mouseover(function() {
    interval = setInterval(function() {
      $("h1").css({ color: getRandomColor() });
    }, 100);
  });
  $("header").mouseout(function() {
    clearInterval(interval);
    $("h1").css({ color: "rgb(80,80,80)" });
  });

  conn = new WebSocket('ws://109.109.137.94:8080');
  conn.onopen = function(e) {
    console.log("Connection established!");
  };

  conn.onmessage = function(e) {
    console.log(e.data);
    splitData = e.data.split(" ");
    if (splitData[0] === "move") {
      movePlayer(parseInt(splitData[1]), parseInt(splitData[2]), parseInt(splitData[3]));
    } else if (splitData[0] === "add") {
      addPlayer();
    }
  };

  conn.onclose = function(e) {
    console.log("Connection closed!");
  };

  stage = new Kinetic.Stage({
    container: "game-container",
    width: canvasWidth,
    height: canvasHeight
  });
  layer = new Kinetic.Layer();

  mazeBlockWidth = Math.round(canvasWidth / gridWidth);
  mazeBlockHeight = Math.round(canvasHeight / gridHeight);

  buildMaze();

  // Add the layer to the stage
  stage.add(layer);

  // Add test players
  addPlayer();

  // Test move
  // setTimeout(function() {
  //   movePlayer(players[0], 800, 500);
  // }, 1000);

});

function buildMaze() {
  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid[i].length; j++) {
      buildMazeBlock(i,j);
    };
  };
}

function buildMazeBlock(i,j) {
  var blockFill = ""
  if (grid[j][i] === " ") {
     return;
  } else if (grid[j][i] === "#") {
    blockFill = "rgb(100,100,100)";
  } else if (grid[j][i] === "s") {
    startX = j;
    startY = i;
    return;
  }

  var block = new Kinetic.Rect({
    x: i * mazeBlockWidth,
    y: j * mazeBlockHeight,
    width: mazeBlockWidth,
    height: mazeBlockHeight,
    fill: blockFill
  });

  if (grid[j][i] === "e") {
    console.log(j,i);
    setInterval(function() {
      console.log("Aaaaah");
      block.setFill(getRandomColor());
      layer.draw();
    },100);
  }

  layer.add(block);
  layer.draw();
}

function addPlayer() {
  var newPlayer = new Kinetic.Rect({
    x: startX * mazeBlockWidth,
    y: startY * mazeBlockHeight,
    width: mazeBlockWidth,
    height: mazeBlockHeight,
    fill: getRandomColor()
  });

  players.push(newPlayer);

  // add the shape to the layer
  layer.add(newPlayer);

  layer.draw();
}

function movePlayer(playerIndex, i, j) {
  console.log(players[playerIndex]);

  var tween = new Kinetic.Tween({
    node: players[playerIndex],
    duration: 1,
    x: i * mazeBlockWidth,
    y: j * mazeBlockHeight,
    opacity: 1
  });

  tween.play();
}

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}<commit_msg>bug fixes<commit_after>
gridWidth = grid[0].length;
gridHeight = grid.length;

canvasWidth = 1000; //window.innerWidth;
canvasHeight = 650; //(window.innerHeight / 100) * 80;

players = [];
velocity = [2,2];

startX = 0;
startY = 0;

$(document).ready(function() {

  var interval;
  $("header").mouseover(function() {
    interval = setInterval(function() {
      $("h1").css({ color: getRandomColor() });
    }, 100);
  });
  $("header").mouseout(function() {
    clearInterval(interval);
    $("h1").css({ color: "rgb(80,80,80)" });
  });

  conn = new WebSocket('ws://109.109.137.94:8080');
  conn.onopen = function(e) {
    console.log("Connection established!");
  };

  conn.onmessage = function(e) {
    console.log(e.data);
    splitData = e.data.split(" ");
    if (splitData[0] === "move") {
      movePlayer(parseInt(splitData[1]), parseInt(splitData[2]), parseInt(splitData[3]));
    } else if (splitData[0] === "add") {
      addPlayer();
    }
  };

  conn.onclose = function(e) {
    console.log("Connection closed!");
  };

  stage = new Kinetic.Stage({
    container: "game-container",
    width: canvasWidth,
    height: canvasHeight
  });
  layer = new Kinetic.Layer();

  mazeBlockWidth = Math.round(canvasWidth / gridWidth);
  mazeBlockHeight = Math.round(canvasHeight / gridHeight);

  buildMaze();

  // Add the layer to the stage
  stage.add(layer);

  // Add test players
  addPlayer();

  // Test move
  // setTimeout(function() {
  //   movePlayer(players[0], 800, 500);
  // }, 1000);

});

function buildMaze() {
  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid[i].length; j++) {
      buildMazeBlock(i,j);
    };
  };
}

function buildMazeBlock(i,j) {
  var blockFill = ""
  if (grid[j][i] === " ") {
     return;
  } else if (grid[j][i] === "#") {
    blockFill = "rgb(100,100,100)";
  } else if (grid[j][i] === "s") {
    startX = i;
    startY = j;
    return;
  }

  var block = new Kinetic.Rect({
    x: i * mazeBlockWidth,
    y: j * mazeBlockHeight,
    width: mazeBlockWidth,
    height: mazeBlockHeight,
    fill: blockFill
  });

  if (grid[j][i] === "e") {
    console.log(j,i);
    setInterval(function() {
      block.setFill(getRandomColor());
      layer.draw();
    },100);
  }

  layer.add(block);
  layer.draw();
}

function addPlayer() {
  var newPlayer = new Kinetic.Rect({
    x: startX * mazeBlockWidth,
    y: startY * mazeBlockHeight,
    width: mazeBlockWidth,
    height: mazeBlockHeight,
    fill: getRandomColor()
  });

  players.push(newPlayer);

  // add the shape to the layer
  layer.add(newPlayer);

  layer.draw();
}

function movePlayer(playerIndex, i, j) {
  console.log(players[playerIndex]);

  var tween = new Kinetic.Tween({
    node: players[playerIndex],
    duration: 1,
    x: i * mazeBlockWidth,
    y: j * mazeBlockHeight,
    opacity: 1
  });

  tween.play();
}

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}<|endoftext|>


<commit_before>var get_relative_time = exports.get_relative_time = function(date){
	var text;
	var dateTime = date.split(' ');

	var pDate = dateTime[0].split('-');
	pYear = parseInt(pDate[0],10);
	pMonth = parseInt(pDate[1],10);
	pDay= parseInt(pDate[2],10);

	var pTime = dateTime[1].split(':');
	pHour = parseInt(pTime[0],10);
	pMin = parseInt(pTime[1],10);

	var currentTime = new Date();
	var hours = parseInt(currentTime.getUTCHours(),10);
	var minutes = parseInt(currentTime.getUTCMinutes(),10);
	var year = parseInt(currentTime.getUTCFullYear(),10);
	var month = parseInt(currentTime.getUTCMonth()+1,10);
	var day = parseInt(currentTime.getUTCDate(),10);

	if (year == pYear && month == pMonth && day == pDay){

		if (pHour == hours){
			if (pMin == minutes)
				text = 'Just now';
			else{
				diff = Math.abs(pMin - minutes);
				text = diff == 1? diff + ' minute ago' : diff + ' minutes ago';
			}
		}
		else{
			diff = Math.abs(pHour - hours);
			if (diff == 1){
				diff = pMin - minutes;

				if (diff > 0){
					diff = 60 - diff;
					text = diff == 1? diff + ' minute ago' : diff + ' minutes ago';
				}
				else
					text = 'an hour ago';
			}
			else{
				text = diff + ' hours ago';
			}
		}
	}
	else{
		if (pYear == year){
			if (pMonth == month){
				diff = Math.abs(pDay - day);
				text = diff == 1? 'Yesterday' : diff + ' days ago';
			}
			else{
				diff = Math.abs(pMonth - month);
				text = diff == 1? 'Last month' : diff + ' months ago';
			}
		}
		else{
			diff = Math.abs(pYear - year);
			text = diff == 1? 'Last year' : diff + ' years ago';
		}
	}

	return text;
};

var create_date_label = function(date){

	var text = get_relative_time(date);

	var dateLabel = Ti.UI.createLabel({
		text: text,
		backgroundColor: 'transparent',
		font:{
			fontSize: '12dp',
			fontFamily: 'Helvetica-Bold',
		},
		color: 'gray',
		bottom: 0,
	});
	return dateLabel;
};

exports.make_content_view = function(title, content, thumbnail, url, id, date, author, modified, loadFromDictionary) {

	var content_view = Ti.UI.createView({
		height: Ti.Gesture.landscape? '110dp': '90dp',
		width: Titanium.Platform.displayCaps.platformWidth,
		left: 0,
		backgroundColor: 'white',
		zIndex: 500,
	});

	var thumb = Ti.UI.createImageView({
		height: Ti.Gesture.landscape? '90dp': '70dp',
		width: Ti.Gesture.landscape? '90dp': '70dp',
		left: '5dp',
		image: thumbnail,
	});

	var textView = Ti.UI.createView({
		//top: '0dp',
		left: Ti.Gesture.landscape? '105dp': '85dp',
		right: '20dp',
		height: Ti.Gesture.landscape? '90dp':'70dp',
		backgroundColor:'transparent',
		layout: 'vertical',
	});

	var authorTimeView = Ti.UI.createView({
		//top: '2dp',
		// left: '80dp',
		// right: '20dp',
		left: 0,
		backgroundColor:'transparent',
		layout: 'horizontal',
	});

	var titleLabel = Ti.UI.createLabel({
		text: title,
		color:'#4A4A4A',
		ellipsize: true,
		left: 0,
		height: '57dp',
		verticalAlign: Titanium.UI.TEXT_VERTICAL_ALIGNMENT_TOP,
		font: {
			fontSize: Ti.Gesture.landscape? '18dp': '15dp',
			fontFamily: 'Helvetica-Bold',
		},
		backgroundColor:'transparent',
	});

	var authorLabel = Ti.UI.createLabel({
		text: author,
		color:'#70193c',
		// top: '0dp',
		// left: '80dp',
		// right: '20dp',
		left: '3dp',
		height: Ti.UI.SIZE,
		font: {
			fontSize: '12dp',
			fontFamily: 'Helvetica',
		},
		backgroundColor:'transparent',
	});

	var date_label = create_date_label(date);
	textView.add(titleLabel);
	authorTimeView.add(date_label);
	authorTimeView.add(authorLabel);
	textView.add(authorTimeView);
	content_view.add(thumb);
	content_view.add(textView);

	var row = Ti.UI.createTableViewRow({
		height: Ti.Gesture.landscape? '110dp' : '90dp',
		width: Ti.Platform.displayCaps.platformWidth,
		backgroundColor:'#fff',
		className: 'article',
		url: url,
		content: content,
		articleTitle: title,
		id: id,
		author: author,
		date: date,
		modified: modified,
		date_label: date_label,
		title_label: titleLabel,
		text_view: textView,
		content_view: content_view,
		thumb: thumb,
	});

	row.articleRow = content_view;
	row.sharing = create_sharing_options_view(url, title, content, thumbnail, id, date, author);
	row.add(row.sharing);
	row.add(row.articleRow);

	row.addEventListener('swipe', sharing_animation);

	row.articleRow.addEventListener ('click', function(e){
		var articleWindow;
		if (loadFromDictionary)
			articleWindow = Ti.UI.createWindow({
				backgroundColor:'#fff',
				url: 'detail.js',
				modal: true,
				content: table_rows[id].content,
				id: table_rows[id].id,
				articleUrl: table_rows[id].url,
				articleTitle: table_rows[id].articleTitle,
				thumbnail: table_rows[id].thumb.image,
				date: table_rows[id].date,
				author: table_rows[id].author,
			});
		else
			articleWindow = Ti.UI.createWindow({
				backgroundColor:'#fff',
				url: 'detail.js',
				modal: true,
				content: content,
				id: id,
				articleUrl: url,
				articleTitle: title,
				thumbnail: thumbnail,
				date: date,
				author: author,
			});
		articleWindow.addEventListener('close',function(){
			Ti.UI.currentTab.fireEvent('focus');
		});
		articleWindow.open({
			animated:true,
		});

		if (!!current_row) {
			current_row.articleRow.animate({
				left: 0,
				duration: 500
			});
			current_row = null;
		}
	});

	return row;
};

exports.create_header = function(showInfo){
	var header = Titanium.UI.createView({
		backgroundColor: '#f8f8f8',
		top: 0,
		height: '45dp',
		zIndex: 2,
	});

	var headerlogo = Ti.UI.createImageView({
		image: 'images/ios-header.png',
		width: '150dp',
		height: '20dp',
		center: {x:Ti.Platform.displayCaps.platformWidth/2, y: 25},
	});

	var submit = Ti.UI.createImageView({
		image: 'images/submit.png',
		height: '30dp',
		width: '30dp',
		right: '5dp',
	});

	submit.addEventListener('click', function(){
		var win = Ti.UI.createWindow({
			backgroundColor:'white',
			url: 'upload_photo.js',
			modal: false,
			navBarHidden: true,
		});

		win.open({
			animated:true,
		});
	});

	var headerStrip = Titanium.UI.createView({
		backgroundColor: '#70193c',
		height: '5dp',
		top: 0,
		zIndex: 100,
	});

	var headerBottomBorder = Ti.UI.createView({
		backgroundColor: '#b2b2b2',
		height: '1dp',
		bottom: 0,
	});

	header.add(headerStrip);
	header.add(headerlogo);
	header.add(headerBottomBorder);
	header.add(submit);
	if (showInfo){
		header.add(info);
		var info = Ti.UI.createImageView({
			image: 'images/info_inactive.png',
			height: '30dp',
			width: '30dp',
			left: '5dp',
		});

		info.addEventListener('click', function(){
			var aboutWindow = Ti.UI.createWindow({
				backgroundColor:'white',
				url: 'about.js',
				modal: false,
				navBarHidden: true,
			});

			aboutWindow.open({
				animated:true,
			});
		});
	}
	return header;
};

exports.create_table_view = function(top){
	top = top || '90dp';
	var table = Ti.UI.createTableView({
		backgroundColor:'white',
		rowHeight: Ti.UI.SIZE,
		top: top,
		left: '5dp',
		right: '5dp',
		bubbleParent: false,
		selectionStyle: 'none',
		separatorColor: '#e9e5df',
	});

	return table;
};

exports.dialog = function(title, msg){
	title = title || 'Couldn\'t fetch your articles';
	msg = msg || 'Please check internet connectivity';

	var dialog = Ti.UI.createAlertDialog({
		message: msg,
		title: title,
		ok: 'Got it!',
		cancel: -1,
	});
	dialog.show();
};
<commit_msg>info icon header<commit_after>var get_relative_time = exports.get_relative_time = function(date){
	var text;
	var dateTime = date.split(' ');

	var pDate = dateTime[0].split('-');
	pYear = parseInt(pDate[0],10);
	pMonth = parseInt(pDate[1],10);
	pDay= parseInt(pDate[2],10);

	var pTime = dateTime[1].split(':');
	pHour = parseInt(pTime[0],10);
	pMin = parseInt(pTime[1],10);

	var currentTime = new Date();
	var hours = parseInt(currentTime.getUTCHours(),10);
	var minutes = parseInt(currentTime.getUTCMinutes(),10);
	var year = parseInt(currentTime.getUTCFullYear(),10);
	var month = parseInt(currentTime.getUTCMonth()+1,10);
	var day = parseInt(currentTime.getUTCDate(),10);

	if (year == pYear && month == pMonth && day == pDay){

		if (pHour == hours){
			if (pMin == minutes)
				text = 'Just now';
			else{
				diff = Math.abs(pMin - minutes);
				text = diff == 1? diff + ' minute ago' : diff + ' minutes ago';
			}
		}
		else{
			diff = Math.abs(pHour - hours);
			if (diff == 1){
				diff = pMin - minutes;

				if (diff > 0){
					diff = 60 - diff;
					text = diff == 1? diff + ' minute ago' : diff + ' minutes ago';
				}
				else
					text = 'an hour ago';
			}
			else{
				text = diff + ' hours ago';
			}
		}
	}
	else{
		if (pYear == year){
			if (pMonth == month){
				diff = Math.abs(pDay - day);
				text = diff == 1? 'Yesterday' : diff + ' days ago';
			}
			else{
				diff = Math.abs(pMonth - month);
				text = diff == 1? 'Last month' : diff + ' months ago';
			}
		}
		else{
			diff = Math.abs(pYear - year);
			text = diff == 1? 'Last year' : diff + ' years ago';
		}
	}

	return text;
};

var create_date_label = function(date){

	var text = get_relative_time(date);

	var dateLabel = Ti.UI.createLabel({
		text: text,
		backgroundColor: 'transparent',
		font:{
			fontSize: '12dp',
			fontFamily: 'Helvetica-Bold',
		},
		color: 'gray',
		bottom: 0,
	});
	return dateLabel;
};

exports.make_content_view = function(title, content, thumbnail, url, id, date, author, modified, loadFromDictionary) {

	var content_view = Ti.UI.createView({
		height: Ti.Gesture.landscape? '110dp': '90dp',
		width: Titanium.Platform.displayCaps.platformWidth,
		left: 0,
		backgroundColor: 'white',
		zIndex: 500,
	});

	var thumb = Ti.UI.createImageView({
		height: Ti.Gesture.landscape? '90dp': '70dp',
		width: Ti.Gesture.landscape? '90dp': '70dp',
		left: '5dp',
		image: thumbnail,
	});

	var textView = Ti.UI.createView({
		//top: '0dp',
		left: Ti.Gesture.landscape? '105dp': '85dp',
		right: '20dp',
		height: Ti.Gesture.landscape? '90dp':'70dp',
		backgroundColor:'transparent',
		layout: 'vertical',
	});

	var authorTimeView = Ti.UI.createView({
		//top: '2dp',
		// left: '80dp',
		// right: '20dp',
		left: 0,
		backgroundColor:'transparent',
		layout: 'horizontal',
	});

	var titleLabel = Ti.UI.createLabel({
		text: title,
		color:'#4A4A4A',
		ellipsize: true,
		left: 0,
		height: '57dp',
		verticalAlign: Titanium.UI.TEXT_VERTICAL_ALIGNMENT_TOP,
		font: {
			fontSize: Ti.Gesture.landscape? '18dp': '15dp',
			fontFamily: 'Helvetica-Bold',
		},
		backgroundColor:'transparent',
	});

	var authorLabel = Ti.UI.createLabel({
		text: author,
		color:'#70193c',
		// top: '0dp',
		// left: '80dp',
		// right: '20dp',
		left: '3dp',
		height: Ti.UI.SIZE,
		font: {
			fontSize: '12dp',
			fontFamily: 'Helvetica',
		},
		backgroundColor:'transparent',
	});

	var date_label = create_date_label(date);
	textView.add(titleLabel);
	authorTimeView.add(date_label);
	authorTimeView.add(authorLabel);
	textView.add(authorTimeView);
	content_view.add(thumb);
	content_view.add(textView);

	var row = Ti.UI.createTableViewRow({
		height: Ti.Gesture.landscape? '110dp' : '90dp',
		width: Ti.Platform.displayCaps.platformWidth,
		backgroundColor:'#fff',
		className: 'article',
		url: url,
		content: content,
		articleTitle: title,
		id: id,
		author: author,
		date: date,
		modified: modified,
		date_label: date_label,
		title_label: titleLabel,
		text_view: textView,
		content_view: content_view,
		thumb: thumb,
	});

	row.articleRow = content_view;
	row.sharing = create_sharing_options_view(url, title, content, thumbnail, id, date, author);
	row.add(row.sharing);
	row.add(row.articleRow);

	row.addEventListener('swipe', sharing_animation);

	row.articleRow.addEventListener ('click', function(e){
		var articleWindow;
		if (loadFromDictionary)
			articleWindow = Ti.UI.createWindow({
				backgroundColor:'#fff',
				url: 'detail.js',
				modal: true,
				content: table_rows[id].content,
				id: table_rows[id].id,
				articleUrl: table_rows[id].url,
				articleTitle: table_rows[id].articleTitle,
				thumbnail: table_rows[id].thumb.image,
				date: table_rows[id].date,
				author: table_rows[id].author,
			});
		else
			articleWindow = Ti.UI.createWindow({
				backgroundColor:'#fff',
				url: 'detail.js',
				modal: true,
				content: content,
				id: id,
				articleUrl: url,
				articleTitle: title,
				thumbnail: thumbnail,
				date: date,
				author: author,
			});
		articleWindow.addEventListener('close',function(){
			Ti.UI.currentTab.fireEvent('focus');
		});
		articleWindow.open({
			animated:true,
		});

		if (!!current_row) {
			current_row.articleRow.animate({
				left: 0,
				duration: 500
			});
			current_row = null;
		}
	});

	return row;
};

exports.create_header = function(hideInfo){
	var header = Titanium.UI.createView({
		backgroundColor: '#f8f8f8',
		top: 0,
		height: '45dp',
		zIndex: 2,
	});

	var headerlogo = Ti.UI.createImageView({
		image: 'images/ios-header.png',
		width: '150dp',
		height: '20dp',
		center: {x:Ti.Platform.displayCaps.platformWidth/2, y: 25},
	});

	var submit = Ti.UI.createImageView({
		image: 'images/submit.png',
		height: '30dp',
		width: '30dp',
		right: '5dp',
	});

	submit.addEventListener('click', function(){
		var win = Ti.UI.createWindow({
			backgroundColor:'white',
			url: 'upload_photo.js',
			modal: false,
			navBarHidden: true,
		});

		win.open({
			animated:true,
		});
	});

	var headerStrip = Titanium.UI.createView({
		backgroundColor: '#70193c',
		height: '5dp',
		top: 0,
		zIndex: 100,
	});

	var headerBottomBorder = Ti.UI.createView({
		backgroundColor: '#b2b2b2',
		height: '1dp',
		bottom: 0,
	});

	header.add(headerStrip);
	header.add(headerlogo);
	header.add(headerBottomBorder);
	header.add(submit);
	if (!hideInfo){
		header.add(info);
		var info = Ti.UI.createImageView({
			image: 'images/info_inactive.png',
			height: '30dp',
			width: '30dp',
			left: '5dp',
		});

		info.addEventListener('click', function(){
			var aboutWindow = Ti.UI.createWindow({
				backgroundColor:'white',
				url: 'about.js',
				modal: false,
				navBarHidden: true,
			});

			aboutWindow.open({
				animated:true,
			});
		});
	}
	return header;
};

exports.create_table_view = function(top){
	top = top || '90dp';
	var table = Ti.UI.createTableView({
		backgroundColor:'white',
		rowHeight: Ti.UI.SIZE,
		top: top,
		left: '5dp',
		right: '5dp',
		bubbleParent: false,
		selectionStyle: 'none',
		separatorColor: '#e9e5df',
	});

	return table;
};

exports.dialog = function(title, msg){
	title = title || 'Couldn\'t fetch your articles';
	msg = msg || 'Please check internet connectivity';

	var dialog = Ti.UI.createAlertDialog({
		message: msg,
		title: title,
		ok: 'Got it!',
		cancel: -1,
	});
	dialog.show();
};
<|endoftext|>