<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
// @remove-on-eject-end
'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: shouldUseSourceMap ? 'source-map' : false,
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      // @remove-on-eject-begin
      // Resolve Babel runtime relative to react-scripts.
      // It usually still works on npm 3 without this but it would be
      // unfortunate to rely on, as react-scripts could be symlinked,
      // and thus babel-runtime might not be resolvable from the source.
      'babel-runtime': path.dirname(
        require.resolve('babel-runtime/package.json')
      ),
      // @remove-on-eject-end
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx|mjs)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              // @remove-on-eject-begin
              // TODO: consider separate config for production,
              // e.g. to enable no-console and no-debugger only in production.
              baseConfig: {
                extends: [require.resolve('eslint-config-react-app')],
              },
              ignore: false,
              useEslintrc: false,
              // @remove-on-eject-end
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              // @remove-on-eject-begin
              babelrc: false,
              presets: [require.resolve('babel-preset-react-app')],
              // @remove-on-eject-end
              compact: true,
            },
          },
          // The notation here is somewhat confusing.
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader normally turns CSS into JS modules injecting <style>,
          // but unlike in development configuration, we do something different.
          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
          // (second argument), then grabs the result CSS and puts it into a
          // separate file in our build process. This way we actually ship
          // a single CSS file in production instead of JS code injecting <style>
          // tags. If you use code splitting, however, any async bundles will still
          // use the "style" loader inside the async code so CSS from them won't be
          // in the main CSS file.
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract(
              Object.assign(
                {
                  fallback: {
                    loader: require.resolve('style-loader'),
                    options: {
                      hmr: false,
                    },
                  },
                  use: [
                    {
                      loader: require.resolve('css-loader'),
                      options: {
                        importLoaders: 1,
                        minimize: true,
                        sourceMap: shouldUseSourceMap,
                      },
                    },
                    {
                      loader: require.resolve('postcss-loader'),
                      options: {
                        // Necessary for external CSS imports to work
                        // https://github.com/facebookincubator/create-react-app/issues/2677
                        ident: 'postcss',
                        plugins: () => [
                          require('postcss-flexbugs-fixes'),
                          autoprefixer({
                            browsers: [
                              '>1%',
                              'last 4 versions',
                              'Firefox ESR',
                              'not ie < 9', // React doesn't support IE8 anyway
                            ],
                            flexbox: 'no-2009',
                          }),
                        ],
                      },
                    },
                  ],
                },
                extractTextPluginOptions
              )
            ),
            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: require.resolve('file-loader'),
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ],
      },
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false,
      },
      mangle: {
        safari10: true,
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true,
      },
      sourceMap: shouldUseSourceMap,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
      publicPath: publicPath
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the Webpack build.
    new SWPrecacheWebpackPlugin({
      // By default, a cache-busting query parameter is appended to requests
      // used to populate the caches, to ensure the responses are fresh.
      // If a URL is already hashed by Webpack, then there is no concern
      // about it being stale, and the cache-busting can be skipped.
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
      logger(message) {
        if (message.indexOf('Total precache size is') === 0) {
          // This message occurs for every build and is a bit too noisy.
          return;
        }
        if (message.indexOf('Skipping static resource') === 0) {
          // This message obscures real errors so we ignore it.
          // https://github.com/facebookincubator/create-react-app/issues/2612
          return;
        }
        console.log(message);
      },
      minify: true,
      // For unknown URLs, fallback to the index page
      navigateFallback: publicUrl + '/index.html',
      // Ignores URLs starting from /__ (useful for Firebase):
      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
      navigateFallbackWhitelist: [/^(?!\/__).*/],
      // Don't precache sourcemaps (they're large) and build asset manifest:
      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
};
<commit_msg>Revert "Set the public path to the asset manifest entries (#2544)"<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
// @remove-on-eject-end
'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: shouldUseSourceMap ? 'source-map' : false,
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      // @remove-on-eject-begin
      // Resolve Babel runtime relative to react-scripts.
      // It usually still works on npm 3 without this but it would be
      // unfortunate to rely on, as react-scripts could be symlinked,
      // and thus babel-runtime might not be resolvable from the source.
      'babel-runtime': path.dirname(
        require.resolve('babel-runtime/package.json')
      ),
      // @remove-on-eject-end
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx|mjs)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              // @remove-on-eject-begin
              // TODO: consider separate config for production,
              // e.g. to enable no-console and no-debugger only in production.
              baseConfig: {
                extends: [require.resolve('eslint-config-react-app')],
              },
              ignore: false,
              useEslintrc: false,
              // @remove-on-eject-end
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              // @remove-on-eject-begin
              babelrc: false,
              presets: [require.resolve('babel-preset-react-app')],
              // @remove-on-eject-end
              compact: true,
            },
          },
          // The notation here is somewhat confusing.
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader normally turns CSS into JS modules injecting <style>,
          // but unlike in development configuration, we do something different.
          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
          // (second argument), then grabs the result CSS and puts it into a
          // separate file in our build process. This way we actually ship
          // a single CSS file in production instead of JS code injecting <style>
          // tags. If you use code splitting, however, any async bundles will still
          // use the "style" loader inside the async code so CSS from them won't be
          // in the main CSS file.
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract(
              Object.assign(
                {
                  fallback: {
                    loader: require.resolve('style-loader'),
                    options: {
                      hmr: false,
                    },
                  },
                  use: [
                    {
                      loader: require.resolve('css-loader'),
                      options: {
                        importLoaders: 1,
                        minimize: true,
                        sourceMap: shouldUseSourceMap,
                      },
                    },
                    {
                      loader: require.resolve('postcss-loader'),
                      options: {
                        // Necessary for external CSS imports to work
                        // https://github.com/facebookincubator/create-react-app/issues/2677
                        ident: 'postcss',
                        plugins: () => [
                          require('postcss-flexbugs-fixes'),
                          autoprefixer({
                            browsers: [
                              '>1%',
                              'last 4 versions',
                              'Firefox ESR',
                              'not ie < 9', // React doesn't support IE8 anyway
                            ],
                            flexbox: 'no-2009',
                          }),
                        ],
                      },
                    },
                  ],
                },
                extractTextPluginOptions
              )
            ),
            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: require.resolve('file-loader'),
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ],
      },
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false,
      },
      mangle: {
        safari10: true,
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true,
      },
      sourceMap: shouldUseSourceMap,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the Webpack build.
    new SWPrecacheWebpackPlugin({
      // By default, a cache-busting query parameter is appended to requests
      // used to populate the caches, to ensure the responses are fresh.
      // If a URL is already hashed by Webpack, then there is no concern
      // about it being stale, and the cache-busting can be skipped.
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
      logger(message) {
        if (message.indexOf('Total precache size is') === 0) {
          // This message occurs for every build and is a bit too noisy.
          return;
        }
        if (message.indexOf('Skipping static resource') === 0) {
          // This message obscures real errors so we ignore it.
          // https://github.com/facebookincubator/create-react-app/issues/2612
          return;
        }
        console.log(message);
      },
      minify: true,
      // For unknown URLs, fallback to the index page
      navigateFallback: publicUrl + '/index.html',
      // Ignores URLs starting from /__ (useful for Firebase):
      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
      navigateFallbackWhitelist: [/^(?!\/__).*/],
      // Don't precache sourcemaps (they're large) and build asset manifest:
      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
};
<|endoftext|>


<commit_before>var scanner = cordova.require("cordova/plugin/BarcodeScanner");

// Application module
var app = (function() {

    // Server URL components
    var URL = 'http://koti.kapsi.fi/~oturpe/barcode-agent';
    var PRODUCTS_URL = '/newproduct.cgi';

    // Last read bar code
    var barcode = undefined;

    // Creates REST URL for given product ID
    var toProductURL = function() {
        return URL + PRODUCTS_URL + '/' + barcode;
    };

    var log = function(message) {
        console.log('BA: ' + message);
    };

    // Application Constructor
    var initialize = function() {
        bindEvents();
    };

    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    var bindEvents = function() {
        var scanButton;
        var postButton;

        document.addEventListener('deviceready',onDeviceReady,false);

        scanButton = document.getElementById('scanbutton');
        scanButton.addEventListener('click',scan,false);

        postButton = document.getElementById('postbutton');
        postButton.addEventListener('click',post,false);
    };

    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the
    // 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    var onDeviceReady = function() {
        receivedEvent('deviceready');
    };

    // Update DOM on a Received Event
    var receivedEvent = function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style','display:none;');
        receivedElement.setAttribute('style','display:block;');

        log('Received Event: ' + id);
    };

    // Scan barcode
    //
    // Calls barcode scanner plugin code.
    var scan = function() {
        log('scanning');
        try {
            scanner.scan(function(result) {
                log('Scanner result: \n' +
                    'text: ' +
                    result.text +
                    '\n' +
                    'format: ' +
                    result.format +
                    '\n' +
                    'cancelled: ' +
                    result.cancelled +
                    '\n');

                barcode = result.text;
                document.getElementById('scanresult').innerHTML = barcode;
            },function(error) {
                log('Scanning failed: ',error);
            });
        } catch(ex) {
            log(ex.message);
        }

        log('stored barcode: ' + barcode);
    };

    var post = function() {
        var request;
        var response;

        if(!barcode) {
            log('ERROR: Called "post" without barcode');
            return;
        }

        log('posting');

        try {
            request = new XMLHttpRequest();
            request.open('GET',toProductURL(barcode),true);

            request.onreadystatechange = function() {
                if(request.readyState !== 4)
                    return;

                if(request.status === 200) {
                    response = request.responseText;

                    log('Response received:');
                    log(response);

                    gotoPage('productview',JSON.parse(response));
                } else if(request.status === 404) {
                    gotoPage('productadd',{
                        barcode: barcode
                    });
                }
            };

            request.send(null);

            // Not needed now, maybe later?
            /*
            function toQueryString(obj) {
              var query = '';
              var key;
              var keys =  Object.keys(obj);
              var length = keys.length;
              var i;

              for(i=0; i<length; i++) {
                key = keys[i];

                if(i>0)
                  query += '&';

                query += key + '=' + encodeURIComponent(obj[key]);

              }
            }
            */
        } catch(ex) {
            log(ex.message);
        }
    };

    // Switches virtual page within the single page model. Context parameter
    // is a JS object containing page-specific initialization data.
    //
    // Initialization of page with given id is handled by specialized handler
    // function, registered in gotoPage.handlers object.
    var gotoPage = function(id,context) {
        var handler = gotoPage.handlers[id];

        if(id === undefined) {
            log('Unknown page id: ' + id);
            return;
        }

        handler(context);
    };

    gotoPage.handlers = {};

    // Handler for product view.
    gotoPage.handlers['productview'] = function(context) {
        var nameElement, commentsElement, commentObject, commentElement, comments, i, commentsLength;

        nameElement = document.getElementById('productname');
        nameElement.innerHTML = context.name;

        commentsElement = document.getElementById('productcomments');
        log('commentsElement:' + commentsElement);

        comments = context.comments;
        commentsLength = comments.length;
        for(i = 0; i < commentsLength; i += 1) {
            commentObject = comments[i];
            commentElement = document.createElement('p');
            commentElement.innerHTML = commentObject.text;
            commentsElement.appendChild(commentElement);
        }
    };

    gotoPage.handlers['productadd'] = function(context) {
        var idElement;

        idElement = document.getElementById('newproductid');
        idElement.value = context.barcode;
        idElement.readOnly = true;
        // TODO: Images
        // TODO: Posting the form
    };

    // Publish interface
    return {
        initialize: initialize
    };
})();
<commit_msg>Remove barcode static variable, pass it around as function argument<commit_after>var scanner = cordova.require("cordova/plugin/BarcodeScanner");

// Application module
var app = (function() {

    // Server URL components
    var URL = 'http://koti.kapsi.fi/~oturpe/barcode-agent';
    var PRODUCTS_URL = '/newproduct.cgi';

    // Creates REST URL for given product ID
    var toProductURL = function(barcode) {
        return URL + PRODUCTS_URL + '/' + barcode;
    };

    var log = function(message) {
        console.log('BA: ' + message);
    };

    // Application Constructor
    var initialize = function() {
        bindEvents();
    };

    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    var bindEvents = function() {
        var scanButton;
        var postButton;

        document.addEventListener('deviceready',onDeviceReady,false);

        scanButton = document.getElementById('scanbutton');
        scanButton.addEventListener('click',scan,false);

        postButton = document.getElementById('postbutton');
        postButton.addEventListener('click',post,false);
    };

    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the
    // 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    var onDeviceReady = function() {
        receivedEvent('deviceready');
    };

    // Update DOM on a Received Event
    var receivedEvent = function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style','display:none;');
        receivedElement.setAttribute('style','display:block;');

        log('Received Event: ' + id);
    };

    // Scan barcode
    //
    // Calls barcode scanner plugin code.
    var scan = function() {
        log('scanning');
        try {
            scanner.scan(function(result) {
                log('Scanner result: \n' +
                    'text: ' +
                    result.text +
                    '\n' +
                    'format: ' +
                    result.format +
                    '\n' +
                    'cancelled: ' +
                    result.cancelled +
                    '\n');

                post(result.text);
            },function(error) {
                log('Scanning failed: ',error);
            });
        } catch(ex) {
            log(ex.message);
        }
    };

    var post = function(barcode) {
        var request;
        var response;

        if(!barcode) {
            log('ERROR: Called "post" without barcode');
            return;
        }

        log('posting');

        try {
            request = new XMLHttpRequest();
            request.open('GET',toProductURL(barcode),true);

            request.onreadystatechange = function() {
                if(request.readyState !== 4)
                    return;

                if(request.status === 200) {
                    response = request.responseText;

                    log('Response received:');
                    log(response);

                    gotoPage('productview',JSON.parse(response));
                } else if(request.status === 404) {
                    gotoPage('productadd',{
                        barcode: barcode
                    });
                }
            };

            request.send(null);

            // Not needed now, maybe later?
            /*
            function toQueryString(obj) {
              var query = '';
              var key;
              var keys =  Object.keys(obj);
              var length = keys.length;
              var i;

              for(i=0; i<length; i++) {
                key = keys[i];

                if(i>0)
                  query += '&';

                query += key + '=' + encodeURIComponent(obj[key]);

              }
            }
            */
        } catch(ex) {
            log(ex.message);
        }
    };

    // Switches virtual page within the single page model. Context parameter
    // is a JS object containing page-specific initialization data.
    //
    // Initialization of page with given id is handled by specialized handler
    // function, registered in gotoPage.handlers object.
    var gotoPage = function(id,context) {
        var handler = gotoPage.handlers[id];

        if(id === undefined) {
            log('Unknown page id: ' + id);
            return;
        }

        handler(context);
    };

    gotoPage.handlers = {};

    // Handler for product view.
    gotoPage.handlers['productview'] = function(context) {
        var nameElement, commentsElement, commentObject, commentElement, comments, i, commentsLength;

        nameElement = document.getElementById('productname');
        nameElement.innerHTML = context.name;

        commentsElement = document.getElementById('productcomments');
        log('commentsElement:' + commentsElement);

        comments = context.comments;
        commentsLength = comments.length;
        for(i = 0; i < commentsLength; i += 1) {
            commentObject = comments[i];
            commentElement = document.createElement('p');
            commentElement.innerHTML = commentObject.text;
            commentsElement.appendChild(commentElement);
        }
    };

    gotoPage.handlers['productadd'] = function(context) {
        var idElement;

        idElement = document.getElementById('newproductid');
        idElement.value = context.barcode;
        idElement.readOnly = true;
        // TODO: Images
        // TODO: Posting the form
    };

    // Publish interface
    return {
        initialize: initialize
    };
})();
<|endoftext|>


<commit_before>(function() {

  'use strict';

  require('./components.nav-more.js');
  require('./components.messenger.js');

  require('./scopes.header.js');
  require('./scopes.entry.js');
  require('./scopes.chat.js');

})();
<commit_msg>update index js with import<commit_after>import Application from './scopes.application';
<|endoftext|>


<commit_before>/*
  Serializer to assure proper Parse-to-Ember encodings
*/
EmberParseAdapter.Serializer = DS.RESTSerializer.extend({

  primaryKey: "objectId",

  extractArray: function(store, primaryType, payload){
    var namespacedPayload = {};
    namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.results;
    return this._super(store, primaryType, namespacedPayload);
  },

  extractSingle: function(store, primaryType, payload, recordId){
    var namespacedPayload = {};
    namespacedPayload[primaryType.typeKey] = payload; // this.normalize(primaryType, payload);
    return this._super(store, primaryType, namespacedPayload, recordId);
  },

  typeForRoot: function(key) {
    return Ember.String.dasherize(Ember.String.singularize(key));
  },

  /**
   * Because Parse only returns the updatedAt/createdAt values on updates
   * we have to intercept it here to assure that the adapter knows which
   * record ID we are dealing with (using the primaryKey).
   */
  extract: function(store, type, payload, id, requestType){
    if(id !== null && (requestType === "updateRecord" || requestType === "deleteRecord")){
      payload[this.get('primaryKey')] = id;
    }
    return this._super(store, type, payload, id, requestType);
  },

  /**
   * Extracts count from the payload so that you can get the total number
   * of records in Parse if you're using skip and limit.
   */
  extractMeta: function(store, type, payload) {
    if (payload && payload.count) {
      store.metaForType(type, {count: payload.count});
      delete payload.count;
    }
  },

  /**
   * Special handling for the Date objects inside the properties of
   * Parse responses.
   */
  normalizeAttributes: function(type, hash){
    type.eachAttribute(function(key, meta){
      if(meta.type === "date" && Ember.typeOf(hash[key]) === "object" && hash[key].iso){
        hash[key] = hash[key].iso; //new Date(hash[key].iso).toISOString();
      }
    });
    this._super(type, hash);
  },

  /**
   * Special handling of the Parse relation types. In certain
   * conditions there is a secondary query to retrieve the "many"
   * side of the "hasMany".
   */
  normalizeRelationships: function(type, hash){
    var store = this.get('store');
    var serializer = this;

    type.eachRelationship(function(key, relationship) {

      var options = relationship.options;

      // Handle the belongsTo relationships
      if(hash[key] && relationship.kind === 'belongsTo'){
        hash[key] = hash[key].objectId;
      }

      // Handle the hasMany relationships
      if(hash[key] && relationship.kind === 'hasMany'){

        // If this is a Relation hasMany then we need to supply
        // the links property so the adapter can async call the
        // relationship.
        // The adapter findHasMany has been overridden to make use of this.
        if(options.relation) {
          // hash[key] contains the response of Parse.com: eg {__type: Relation, className: MyParseClassName}
          // this is an object that make ember-data fail, as it expects nothing or an array ids that represent the records
          hash[key] = [];

          // ember-data expects the link to be a string
          // The adapter findHasMany will parse it
          hash.links = {};
          hash.links[key] = JSON.stringify({type: relationship.type, key: key});
        }

        if(options.array){
          // Parse will return [null] for empty relationships
          if(hash[key].length && hash[key]){
            hash[key].forEach(function(item, index, items){
              // When items are pointers we just need the id
              // This occurs when request was made without the include query param.
              if(item.__type === "Pointer"){
                items[index] = item.objectId;
              } else {
                // When items are objects we need to clean them and add them to the store.
                // This occurs when request was made with the include query param.
                delete item.__type;
                delete item.className;
                item.id = item.objectId;
                delete item.objectId;
                item.type = relationship.type;
                serializer.normalizeAttributes(relationship.type, item);
                serializer.normalizeRelationships(relationship.type, item);
                store.push(relationship.type, item);
              }
            });
          }
        }

      }
    }, this);

    this._super(type, hash);
  },

  serializeIntoHash: function(hash, type, snapshot, options){
    Ember.merge(hash, this.serialize(snapshot, options));
  },

  serializeAttribute: function(snapshot, json, key, attribute) {
    // These are Parse reserved properties and we won't send them.
    if( key === 'createdAt' ||
        key === 'updatedAt' ||
        key === 'emailVerified' ||
        key === 'sessionToken' ){
      delete json[key];
    } else {
      this._super(snapshot, json, key, attribute);
    }
  },

  serializeBelongsTo: function(snapshot, json, relationship){
    var key = relationship.key;
    var belongsTo = snapshot.belongsTo(key);
    if(belongsTo){
      // TODO: Perhaps this is working around a bug in Ember-Data? Why should
      // promises be returned here.
      if (belongsTo instanceof DS.PromiseObject) {
        if (!belongsTo.attr('isFulfilled')) {
          throw new Error("belongsTo values *must* be fulfilled before attempting to serialize them");
        }
        belongsTo = belongsTo.attr('content');
      }

      json[key] = {
        "__type": "Pointer",
        "className": this.parseClassName(belongsTo.constructor.typeKey),
        "objectId": belongsTo.attr('id')
      };
    }
  },

  parseClassName: function(key) {
    if (key === "parseUser") {
      return "_User";
    } else {
      return Ember.String.capitalize(Ember.String.camelize(key));
    }
  },

  serializeHasMany: function(snapshot, json, relationship){
    var key = relationship.key;
    var hasMany = snapshot.hasMany(key);
    var options = relationship.options;
    if(hasMany && hasMany.attr('length') > 0){

      json[key] = { "objects": [] };

      if(options.relation){
        json[key].__op = "AddRelation";
      }

      if(options.array){
        json[key].__op = "AddUnique";
      }

      var _this = this;

      hasMany.forEach(function(child){
        json[key].objects.push({
          "__type": "Pointer",
          "className": _this.parseClassName(child.constructor.typeKey),
          "objectId": child.attr('id')
        });
      });

      if(hasMany._deletedItems && hasMany._deletedItems.length){
        if(options.relation){
          var addOperation = json[key];
          var deleteOperation = { "__op": "RemoveRelation", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            deleteOperation.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
          json[key] = { "__op": "Batch", "ops": [addOperation, deleteOperation] };
        }
        if(options.array){
          json[key].deleteds = { "__op": "Remove", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            json[key].deleteds.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
        }
      }
    } else {
      json[key] = [];
    }
  }

});
<commit_msg>fixed deprecation warnings<commit_after>/*
  Serializer to assure proper Parse-to-Ember encodings
*/
EmberParseAdapter.Serializer = DS.RESTSerializer.extend({

  primaryKey: "objectId",

  extractArray: function(store, primaryType, payload){
    var namespacedPayload = {};
    namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.results;
    return this._super(store, primaryType, namespacedPayload);
  },

  extractSingle: function(store, primaryType, payload, recordId){
    var namespacedPayload = {};
    namespacedPayload[primaryType.typeKey] = payload; // this.normalize(primaryType, payload);
    return this._super(store, primaryType, namespacedPayload, recordId);
  },

  typeForRoot: function(key) {
    return Ember.String.dasherize(Ember.String.singularize(key));
  },

  /**
   * Because Parse only returns the updatedAt/createdAt values on updates
   * we have to intercept it here to assure that the adapter knows which
   * record ID we are dealing with (using the primaryKey).
   */
  extract: function(store, type, payload, id, requestType){
    if(id !== null && (requestType === "updateRecord" || requestType === "deleteRecord")){
      payload[this.get('primaryKey')] = id;
    }
    return this._super(store, type, payload, id, requestType);
  },

  /**
   * Extracts count from the payload so that you can get the total number
   * of records in Parse if you're using skip and limit.
   */
  extractMeta: function(store, type, payload) {
    if (payload && payload.count) {
      store.metaForType(type, {count: payload.count});
      delete payload.count;
    }
  },

  /**
   * Special handling for the Date objects inside the properties of
   * Parse responses.
   */
  normalizeAttributes: function(type, hash){
    type.eachAttribute(function(key, meta){
      if(meta.type === "date" && Ember.typeOf(hash[key]) === "object" && hash[key].iso){
        hash[key] = hash[key].iso; //new Date(hash[key].iso).toISOString();
      }
    });
    this._super(type, hash);
  },

  /**
   * Special handling of the Parse relation types. In certain
   * conditions there is a secondary query to retrieve the "many"
   * side of the "hasMany".
   */
  normalizeRelationships: function(type, hash){
    var store = this.get('store');
    var serializer = this;

    type.eachRelationship(function(key, relationship) {

      var options = relationship.options;

      // Handle the belongsTo relationships
      if(hash[key] && relationship.kind === 'belongsTo'){
        hash[key] = hash[key].objectId;
      }

      // Handle the hasMany relationships
      if(hash[key] && relationship.kind === 'hasMany'){

        // If this is a Relation hasMany then we need to supply
        // the links property so the adapter can async call the
        // relationship.
        // The adapter findHasMany has been overridden to make use of this.
        if(options.relation) {
          // hash[key] contains the response of Parse.com: eg {__type: Relation, className: MyParseClassName}
          // this is an object that make ember-data fail, as it expects nothing or an array ids that represent the records
          hash[key] = [];

          // ember-data expects the link to be a string
          // The adapter findHasMany will parse it
          hash.links = {};
          hash.links[key] = JSON.stringify({type: relationship.type, key: key});
        }

        if(options.array){
          // Parse will return [null] for empty relationships
          if(hash[key].length && hash[key]){
            hash[key].forEach(function(item, index, items){
              // When items are pointers we just need the id
              // This occurs when request was made without the include query param.
              if(item.__type === "Pointer"){
                items[index] = item.objectId;
              } else {
                // When items are objects we need to clean them and add them to the store.
                // This occurs when request was made with the include query param.
                delete item.__type;
                delete item.className;
                item.id = item.objectId;
                delete item.objectId;
                item.type = relationship.type;
                serializer.normalizeAttributes(relationship.type, item);
                serializer.normalizeRelationships(relationship.type, item);
                store.push(relationship.type, item);
              }
            });
          }
        }

      }
    }, this);

    this._super(type, hash);
  },

  serializeIntoHash: function(hash, type, snapshot, options){
    Ember.merge(hash, this.serialize(snapshot, options));
  },

  serializeAttribute: function(snapshot, json, key, attribute) {
    // These are Parse reserved properties and we won't send them.
    if( key === 'createdAt' ||
        key === 'updatedAt' ||
        key === 'emailVerified' ||
        key === 'sessionToken' ){
      delete json[key];
    } else {
      this._super(snapshot, json, key, attribute);
    }
  },

  serializeBelongsTo: function(snapshot, json, relationship){
    var key = relationship.key;
    var belongsTo = snapshot.belongsTo(key);
    if(belongsTo){
      // TODO: Perhaps this is working around a bug in Ember-Data? Why should
      // promises be returned here.
      if (belongsTo instanceof DS.PromiseObject) {
        if (!belongsTo.attr('isFulfilled')) {
          throw new Error("belongsTo values *must* be fulfilled before attempting to serialize them");
        }
        belongsTo = belongsTo.attr('content');
      }

      json[key] = {
        "__type": "Pointer",
        "className": this.parseClassName(belongsTo.constructor.typeKey),
        "objectId": belongsTo.attr('id')
      };
    }
  },

  parseClassName: function(key) {
    if (key === "parseUser") {
      return "_User";
    } else {
      return Ember.String.capitalize(Ember.String.camelize(key));
    }
  },

  serializeHasMany: function(snapshot, json, relationship){
    var key = relationship.key;
    var hasMany = snapshot.hasMany(key);
    var options = relationship.options;
    if(hasMany && hasMany.attr('length') > 0){

      json[key] = { "objects": [] };

      if(options.relation){
        json[key].__op = "AddRelation";
      }

      if(options.array){
        json[key].__op = "AddUnique";
      }

      var _this = this;

      hasMany.forEach(function(child){
        json[key].objects.push({
          "__type": "Pointer",
          "className": _this.parseClassName(child.type.typeKey),
          "objectId": child.attr('id')
        });
      });

      if(hasMany._deletedItems && hasMany._deletedItems.length){
        if(options.relation){
          var addOperation = json[key];
          var deleteOperation = { "__op": "RemoveRelation", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            deleteOperation.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
          json[key] = { "__op": "Batch", "ops": [addOperation, deleteOperation] };
        }
        if(options.array){
          json[key].deleteds = { "__op": "Remove", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            json[key].deleteds.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
        }
      }
    } else {
      json[key] = [];
    }
  }

});
<|endoftext|>


<commit_before>var express = require('express');
var proxies = require('./proxies');
var exception = require('./exceptions');
var logic = require('./controller');

var app = express.createServer();

 var conf = {
  id: "guardian",
  name: "The Guardian News Reader",
  description: "All the latest from around the world",
  version: "0.0.0.1",
  baseDir: __dirname + "/templates/",
  clientDir: __dirname + "/client/",
  categories: ["technology", "business", "politics", "lifeandstyle", "music", "culture"]
};

/*
var conf = {
  id: "npr",
  name: "The NPR News Reader",
  description: "All the latest from around the world",
  version: "0.0.0.1",
  baseDir: __dirname + "/templates/",
  clientDir: __dirname + "/client/",
  categories: ["1019"]
};*/

var cache = {};

function bustCache(req, res, next) {
  res.setHeader("Expires","Mon, 26 Jul 1997 05:00:00 GMT");
  res.setHeader("Last-Modified", +new Date);
  res.setHeader("Cache-Control","no-store, no-cache, must-revalidate, max-age=0");
  res.setHeader("Cache-Control", "post-check=0, pre-check=0");
  res.setHeader("Pragma","no-cache");
  next();
}

var Cache = function(timeout) {
  var cache = {};
  var clearCacheItem = function(url) {
    delete cache[url];
  };

  return function(req, res, next){
    if(!!cache[req.url] == false) {
      next();
      var end = res.end;
      res.end = function(data, encoding) {
        res.end = end;
        cache[req.url] = data;

        setTimeout(clearCacheItem, timeout * 1000);

        res.end(data, encoding);
      }
    }
    else {
      res.send(cache[req.url]);
    }
  };
};

/*
  By default the code runs in test mode.  This means it use the development versions of the code but uses a dummy "test" data source.
*/
app.configure(function() {
  app.use(app.router);
});

app.configure('test', function() {
  app.use(express.static(conf.clientDir));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  conf.id = "test"; // force test mode.
  console.log("Running in Test");
});

/*
  Development mode runs all the code uncompressed
*/
app.configure('development', function() {
  app.use(bustCache);
  app.use(express.static(conf.clientDir));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  console.log("Running in Development");
});

/*
  Production mode, is nearly the same as development mode, but all the client-side code
  is minified.  Exceptions are not shown either.
*/
app.configure('production', function() {
  conf.clientDir = __dirname + "/client-min";
  app.use(express.static(cond.clientDir));
  console.log("Running in Production");
});

app.get('/', Cache(60), function(req, res) {
  var format = "html";
  var controller = new logic.Controller(conf);
  if(cache[req.url]) {
    res.send(cache[req.url]);
  }
  else {
    controller.fetchCategories(format, function(output) {
      cache[req.url] = output;
      res.send(output);
    });
  }
});

app.get('/index.:format', function(req, res) {
  var format = req.params.format;
  var controller = new logic.Controller(conf);
  if(cache[req.url]) {
    res.send(cache[req.url]);
  }
  else {
    controller.fetchCategories(format, function(output) {
      cache[req.url] = output;
      res.send(output);
    });
  }
});

/*
 *  The AppCache.
 */
app.get('/app.cache', function(req, res) {
  var controller = new logic.Controller(conf);
  controller.renderAppCache(function(output) {
    res.header("Content-type: text/manifest\n\n");
    res.send(output);
  });
});

app.get('/reader/:category.:format?', function(req, res) {
  var category = req.params.category;
  var format = req.params.format || "html";
  var controller = new logic.Controller(conf);
  // request the category list i

  if(cache[req.url]) {
    res.send(cache[req.url]);
  }
  else {
    controller.fetchCategory(category, format, function(output) {
      cache[req.url] = output;
      res.send(output);
    });
  }
});

app.get('/reader/:category/:article.:format?', function(req, res) {
  var category = req.params.category;
  var article = req.params.article;
  var format = req.params.format || "html";
  var controller = new logic.Controller(conf);

  if(cache[req.url]) {
    res.send(cache[req.url]);
  }
  else {
    controller.fetchArticle(article, category, format, function(output) {
      cache[req.url] = output;
      res.send(output);
    });
  }
});

app.listen(3000);

console.log('Server running at http://127.0.0.1:3000/');
<commit_msg>Ripping out Caching in the url handlers - we can add Cache(x) to each request. see:/<commit_after>var express = require('express');
var proxies = require('./proxies');
var exception = require('./exceptions');
var logic = require('./controller');

var app = express.createServer();

 var conf = {
  id: "guardian",
  name: "The Guardian News Reader",
  description: "All the latest from around the world",
  version: "0.0.0.1",
  baseDir: __dirname + "/templates/",
  clientDir: __dirname + "/client/",
  categories: ["technology", "business", "politics", "lifeandstyle", "music", "culture"]
};

/*
var conf = {
  id: "npr",
  name: "The NPR News Reader",
  description: "All the latest from around the world",
  version: "0.0.0.1",
  baseDir: __dirname + "/templates/",
  clientDir: __dirname + "/client/",
  categories: ["1019"]
};*/

var cache = {};

function bustCache(req, res, next) {
  res.setHeader("Expires","Mon, 26 Jul 1997 05:00:00 GMT");
  res.setHeader("Last-Modified", +new Date);
  res.setHeader("Cache-Control","no-store, no-cache, must-revalidate, max-age=0");
  res.setHeader("Cache-Control", "post-check=0, pre-check=0");
  res.setHeader("Pragma","no-cache");
  next();
}

var Cache = function(timeout) {
  var cache = {};
  var clearCacheItem = function(url) {
    delete cache[url];
  };

  return function(req, res, next){
    if(!!cache[req.url] == false) {
      next();
      var end = res.end;
      res.end = function(data, encoding) {
        res.end = end;
        cache[req.url] = data;

        setTimeout(clearCacheItem, timeout * 1000);

        res.end(data, encoding);
      }
    }
    else {
      res.send(cache[req.url]);
    }
  };
};

/*
  By default the code runs in test mode.  This means it use the development versions of the code but uses a dummy "test" data source.
*/
app.configure(function() {
  app.use(app.router);
});

app.configure('test', function() {
  app.use(express.static(conf.clientDir));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  conf.id = "test"; // force test mode.
  console.log("Running in Test");
});

/*
  Development mode runs all the code uncompressed
*/
app.configure('development', function() {
  app.use(bustCache);
  app.use(express.static(conf.clientDir));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  console.log("Running in Development");
});

/*
  Production mode, is nearly the same as development mode, but all the client-side code
  is minified.  Exceptions are not shown either.
*/
app.configure('production', function() {
  conf.clientDir = __dirname + "/client-min";
  app.use(express.static(cond.clientDir));
  console.log("Running in Production");
});

app.get('/', Cache(60), function(req, res) {
  var format = "html";
  var controller = new logic.Controller(conf);

  controller.fetchCategories(format, function(output) {
    res.send(output);
  });
});

app.get('/index.:format', function(req, res) {
  var format = req.params.format;
  var controller = new logic.Controller(conf);

  controller.fetchCategories(format, function(output) {
    res.send(output);
  });
});

/*
 *  The AppCache.
 */
app.get('/app.cache', function(req, res) {
  var controller = new logic.Controller(conf);
  controller.renderAppCache(function(output) {
    res.header("Content-type: text/manifest\n\n");
    res.send(output);
  });
});

app.get('/reader/:category.:format?', function(req, res) {
  var category = req.params.category;
  var format = req.params.format || "html";
  var controller = new logic.Controller(conf);
  // request the category list i

  controller.fetchCategory(category, format, function(output) {
    res.send(output);
  });
});

app.get('/reader/:category/:article.:format?', function(req, res) {
  var category = req.params.category;
  var article = req.params.article;
  var format = req.params.format || "html";
  var controller = new logic.Controller(conf);

  controller.fetchArticle(article, category, format, function(output) {
    res.send(output);
  });
});

app.listen(3000);

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


<commit_before>[
    'lib/tinymce/tinymce.min.js',

    'lib/tinymce/langs/en_us.js',

    'lib/tinymce/plugins/paste/plugin.min.js',
    'lib/tinymce/plugins/anchor/plugin.min.js',
    'lib/tinymce/plugins/charmap/plugin.min.js',
    'lib/tinymce/plugins/table/plugin.min.js',
    'lib/tinymce/plugins/lists/plugin.min.js',
    'lib/tinymce/plugins/advlist/plugin.min.js',
    'lib/tinymce/plugins/hr/plugin.min.js',
    'lib/tinymce/plugins/autolink/plugin.min.js',
    'lib/tinymce/plugins/directionality/plugin.min.js',
    'lib/tinymce/plugins/tabfocus/plugin.min.js',
    'lib/tinymce/plugins/searchreplace/plugin.min.js',
    'lib/tinymce/plugins/fullscreen/plugin.min.js',
    'lib/tinymce/plugins/noneditable/plugin.min.js'
]
<commit_msg>Pre-loading this lang JS file does not seem to help Tiny as it does not check its already loaded & it reloads itself anyway (But the plugins work all fine & are checked by Tiny to see if they have been loaded)<commit_after>[
    'lib/tinymce/tinymce.min.js',

    'lib/tinymce/plugins/paste/plugin.min.js',
    'lib/tinymce/plugins/anchor/plugin.min.js',
    'lib/tinymce/plugins/charmap/plugin.min.js',
    'lib/tinymce/plugins/table/plugin.min.js',
    'lib/tinymce/plugins/lists/plugin.min.js',
    'lib/tinymce/plugins/advlist/plugin.min.js',
    'lib/tinymce/plugins/hr/plugin.min.js',
    'lib/tinymce/plugins/autolink/plugin.min.js',
    'lib/tinymce/plugins/directionality/plugin.min.js',
    'lib/tinymce/plugins/tabfocus/plugin.min.js',
    'lib/tinymce/plugins/searchreplace/plugin.min.js',
    'lib/tinymce/plugins/fullscreen/plugin.min.js',
    'lib/tinymce/plugins/noneditable/plugin.min.js'
]
<|endoftext|>


<commit_before>'use strict'

//Globals will be the stage which is the parrent of all graphics, canvas object for resizing and the renderer which is pixi.js framebuffer.
var stage = new PIXI.Container();;
var canvas = document.getElementById("game");;
var renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );
var graphics = new PIXI.Graphics();

// Create or grab the application
var app = app || {};

function init(){
        resize();
        renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );
        renderer.backgroundColor = 0x50503E;
        canvas.focus();

        app.Game.init(renderer, window, canvas, stage);
}

function resize(){
	var gameWidth = window.innerWidth;
	var gameHeight = window.innerHeight;
	var scaleToFitX = gameWidth / 1000;
	var scaleToFitY = gameHeight / 500;
	// Scaling statement belongs to: https://www.davrous.com/2012/04/06/modernizing-your-html5-canvas-games-part-1-hardware-scaling-css3/
	var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
	var currentScreenRatio = gameWidth / gameHeight;
	if(currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
		canvas.style.width = gameWidth + "px";
		canvas.style.height = gameHeight + "px";
	}else{
		canvas.style.width = 1000 * optimalRatio + "px";
		canvas.style.height = 500 * optimalRatio + "px";
	}
}

//Creates a person
function makePerson(){
	var head = new PIXI.Graphics();
	var body = new PIXI.Graphics();
	var personCon = new PIXI.Container();

	head.lineStyle(2, 0x000000);
	head.beginFill(0xFFFF08, 0.5);
	head.drawCircle(100, 50, 30);
	head.endFill();

	body.lineStyle(2, 0x000000);
	body.beginFill(0xff0000, 0.5);
	body.drawEllipse(100, 50, 100, 50);
	body.endFill();

	personCon.addChild(body);
	personCon.addChild(head);
	stage.addChild(personCon);
}

//takes two arrays
// the w_array is an array of column width values [w1, w2, w3, ...], y_array is
//3d array setup as such [[row 1], [row 2], [row3]] and the rows are arrays
// that contain pairs of y,l values where y is the fixed corner of the
//rectangle and L is the height of the rectangle.
function level(w_array, y_array){

    // drawRect( xstart, ystart, x size side, y size side)

    // set a fill and a line style again and draw a rectangle
    graphics.lineStyle(2, 0x995702, 1);
    graphics.beginFill(0x71FF33, 1);

    var x = 0;
    //reset the x
    x = 0;
    //post fence post
    for(h = 0, hlen = y_array.length; h < hlen; h++){
        for(i = 0, len = w_array.length; i < len; i++){
            //setup the y value
            graphics.drawRect(x, y_array[h][i][0], w_array[i], y_array[h][i][1]);
            x += w_array[i];
        }
        //reset the x
        x = 0;
    }

    stage.addChild(graphics);
}

window.addEventListener('resize', resize, false);
window.addEventListener('orientationchange', resize, false);
<commit_msg>Updated level and testing json<commit_after>'use strict'

//Globals will be the stage which is the parrent of all graphics, canvas object for resizing and the renderer which is pixi.js framebuffer.
var stage = new PIXI.Container();;
var canvas = document.getElementById("game");;
var renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );
var graphics = new PIXI.Graphics();

// Create or grab the application
var app = app || {};

function init(){
        resize();
        renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );
        renderer.backgroundColor = 0x50503E;

        canvas.focus();

        app.Game.init(renderer, window, canvas, stage);
}

function resize(){
	var gameWidth = window.innerWidth;
	var gameHeight = window.innerHeight;
	var scaleToFitX = gameWidth / 1000;
	var scaleToFitY = gameHeight / 500;
	// Scaling statement belongs to: https://www.davrous.com/2012/04/06/modernizing-your-html5-canvas-games-part-1-hardware-scaling-css3/
	var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
	var currentScreenRatio = gameWidth / gameHeight;
	if(currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
		canvas.style.width = gameWidth + "px";
		canvas.style.height = gameHeight + "px";
	}else{
		canvas.style.width = 1000 * optimalRatio + "px";
		canvas.style.height = 500 * optimalRatio + "px";
	}
}

//Creates a person
function makePerson(){
	var head = new PIXI.Graphics();
	var body = new PIXI.Graphics();
	var personCon = new PIXI.Container();

	head.lineStyle(2, 0x000000);
	head.beginFill(0xFFFF08, 0.5);
	head.drawCircle(100, 50, 30);
	head.endFill();

	body.lineStyle(2, 0x000000);
	body.beginFill(0xff0000, 0.5);
	body.drawEllipse(100, 50, 100, 50);
	body.endFill();

	personCon.addChild(body);
	personCon.addChild(head);
	stage.addChild(personCon);
}

//takes two arrays
// the w_array is an array of column width values [w1, w2, w3, ...], y_array is
//3d array setup as such [[row 1], [row 2], [row3]] and the rows are arrays
// that contain pairs of y,l values where y is the fixed corner of the
//rectangle and L is the height of the rectangle.
function level(w_array, y_array){

    // drawRect( xstart, ystart, x size side, y size side)

    // set a fill and a line style again and draw a rectangle
    graphics.lineStyle(2, 0x995702, 1);
    graphics.beginFill(0x71FF33, 1);

    var x = 0;
    //reset the x
    x = 0;
    //post fence post
    for(var h = 0, hlen = y_array.length; h < hlen; h++){
        for( var i = 0, len = w_array.length; i < len; i++){
            //setup the y value
            graphics.drawRect(x, y_array[h][i][0], w_array[i], y_array[h][i][1]);
            x += w_array[i];
        }
        //reset the x
        x = 0;
    }

    stage.addChild(graphics);
}

window.addEventListener('resize', resize, false);
window.addEventListener('orientationchange', resize, false);
<|endoftext|>


<commit_before>/*
 * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function($) {
  function sorted_each(hash,fn,map) {
    var arr = [];
    if(!map) { map = {}; }
    $.each(hash,function(k,v) { arr.push([k,v]); });
    arr.sort(function(a,b) {
      var al = a[0].toLowerCase();
      var bl = b[0].toLowerCase();
      if(map[a[0]]) { al = map[a[0]]; }
      if(map[b[0]]) { bl = map[b[0]]; }
      if(al<bl) { return -1; }
      if(al>bl) { return 1; }
      return 0;
    });
    $.each(arr,function(i,e) {
      fn(e[0],e[1]);
    });
  }

  function beat(def) {
    return def.then(function(data) {
      var d = $.Deferred();
      setTimeout(function() { d.resolve(data); },0);
      return d;
    });
  }

  function loop(def,fn,group,part) {
    return def.then(function(raw_input) {
      var input = [];
      $.each(raw_input,function(a,b) { input.push([a,b]); });
      d = $.Deferred().resolve(input);
      var output = [];
      for(var i=0;i<input.length;i+=group) {
        d = beat(d.then(function(j) {
          for(j=0;j<group && i+j<input.length;j++) {
            var c = fn(input[i+j][0],input[i+j][1]);
            if(c !== undefined) {
              output.push(c);
            }
          }
          return $.Deferred().resolve(output);
        }));
      }
      return d;
    });
  }

  function fire(def,fn) {
    return def.then(function(data) {
      fn();
      return $.Deferred().resolve(data);
    });
  }

  function fix_letters(text,ref,seq) {
    var out = "";

    var s = undefined;
    if(!seq.letter) { seq.letter = []; }
    for(var i=0;i<text.length;i++) {
      if(i < seq.letter.length) { s = seq.letter[i]; }
      if(s) {
        out += ref.letter[s];
      } else {
        out += text.substr(i,1);
      }
    }
    return out;
  }

  function unprefix(ref) {
    var len = 0;
    for(var i=0;i<ref.length;i++) {
      len += ref[i][0];
      if(len) {
        ref[i][0] = ref[i-1].substr(0,len);
      } else {
        ref[i][0] = "";
      }
      ref[i] = ref[i][0] + ref[i][1];
    }
    return ref;
  }

  function unrle(seq) {
    var prev = undefined;
    var out = [];

    if(!$.isArray(seq)) { return seq; }
    for(var i=0;i<seq.length;i++) {
      if(seq[i]<0) {
        for(var j=0;j<-seq[i];j++) { out.push(prev); }
      } else {
        out.push(seq[i]);
        prev = seq[i];
      }
    }
    return out;
  }

  function make_groups(seq,textlen) {
    var styles = [];
    $.each(seq,function(key,values) {
      var value = undefined;
      for(var i=0;i<textlen;i++) {
        if(i < values.length) { value = values[i]; }
        if(!styles[i]) { styles[i] = {}; }
        styles[i][key] = value;
      }
    });
    var last = null;
    $.each(styles,function(i,cur) {
      if(last) {
        var diffs = 0;
        $.each(seq,function(k,v) {
          if(k == 'letter') { return; }
          if(last[k] || cur[k]) {
            if(!last[k] || !cur[k] || last[k]!=cur[k]) { diffs = 1; }
          }
        });
        if(!diffs) { cur.__repeat = 1; }
      }
      last = cur;
    });
    var groups = [];
    $.each(styles,function(i,cur) {
      if(cur.__repeat) {
        groups[groups.length-1].__len++;
      } else {
        cur.__len = 1;
        groups.push(cur);
      }
    });
    return groups;
  }

  function adorn_group(ref,group,text) {
    var otag = "span";
    var ctag = "span";
    if(group.href) {
      otag = "a class='sequence_info'";
      ctag = "a";
    }
    if(group.tag) {
      otag = ref.tag[group.tag];
      ctag = ref.tag[group.tag];
    }
    $.each(['href','title','style'],function(i,k) {
      if(group[k]) {
        otag += ' '+k+'="'+ref[k][group[k]]+'"';
      }
    });
    return "<"+otag+">"+text+"</"+ctag+">";
  }

  function prepare_adorn_span(text,ref,seq,xxx) {
    text = fix_letters(text,ref,seq);
    var groups = make_groups(seq,text.length);
    var pos = 0;
    var out = '';
    $.each(groups,function(i,group) {
      out += adorn_group(ref,group,text.substr(pos,group.__len));
      pos += group.__len;
    });
    return out;
  }

  function add_legend($outer,legend,loading) {
    var $key = $outer.parents('.js_panel').find('.adornment-key');
    // Add new legend to data
    var data = $key.data('data');
    if(!data) { data = {}; }
    if(legend) {
      $.each(legend,function(cn,cv) {
        if(!data[cn] || data[cn] === -1) { data[cn] = {}; }
        if(cn == '_messages') {
          $.each(cv,function(i,ev) {
            data[cn][ev] = 1;
          });
        } else {
          $.each(cv,function(en,ev) {
            data[cn][en] = ev;
          });
        }
      });
    }
    delete data['Basic Annotation'];
    var any = 0;
    $.each(data,function(a,b) { any = 1; });
    if(!any) {
      data['Basic Annotation'] = -1;
    }
    $.each(loading,function(i,load) {
      if(!data[load]) { data[load] = -1; }
    });
    $key.data('data',data);
    // Replace legend with new data
    var key = '';
    sorted_each(data,function(cn,cv) {
      if(cn == '_messages') { return; }
      var row = '';
      if(cv === -1) {
        row += '
loading
';
      } else {
        sorted_each(cv,function(en,ev) {
          var style = '';
          if(!ev) { return; }
          if(ev['default']) {
            style += "background-color: " + ev['default'] + ";";
          }
          if(ev.label) { style += "color: " + ev.label + ";"; }
          if(ev.extra_css) { style += ev.extra_css; }
          row += '
' +
            ev.text + '
';
        });
      }
      if(row) {
        var name = cn.substr(0,1).toUpperCase()+cn.substr(1);
        name = name.replace(/([\/-])/g,"$1 ");
        key += '
'+name+'

'+row+'

';
      }
    },{ other: "~" });
    var messages = '';
    if(data._messages) {
      $.each(data._messages,function(message,v) {
        messages += '
'+message+'
';
      });
    }
    var html = '
Key:
';
    if(key) { html += '
' + key +'
'; }
    if(messages) { html += '
' + messages + '
'; }
    $key.html(html);
  }

  function _do_adorn(outer,fixups,data) {
    var $outer = $(outer);
    if(($outer.hasClass('adornment-running') && !data) ||
       $outer.hasClass('adornment-done')) {
      return $.Deferred().resolve(0);
    }
    var wrapper = $outer.wrap("

").parent();
    $outer.addClass('adornment-running');
    if(!data) {
      data = $.parseJSON($('.adornment-data',outer).text());
    }
    add_legend($outer,null,data.loading||data.provisional.loading);
    var d;
    if(data.url) {
      d = $.Deferred().resolve(data.provisional);
    } else {
      d = $.Deferred().resolve(data);
    }
    d = d.then(function(data) {
      $.each(data.ref,function(k,v) {
        data.ref[k] = unprefix(data.ref[k]);
      });
      $.each(data.seq,function(k,v) {
        if($.isPlainObject(data.seq[k])) {
          $.each(data.seq[k],function(a,b) {
            data.seq[k][a] = unrle(data.seq[k][a]);
          });
        }
      });
      data.seq = unrle(data.seq);
      return loop($.Deferred().resolve(data.seq),function(key,values) {
        if(values) {
          var el = $('.adorn-'+key,outer);
          if(el.length) {
            var fl = {};
            $.each(data.flourishes,function(k,v) {
              var f = v[key];
              var fl_el = $('.ad-'+k+'-'+key,outer);
              if(f && fl_el.length) {
                fl[k] = [fl_el,$.parseJSON(f).v];
              }
            });
            return [el,el.text(),data.ref,values,key,fl];
          } else {
            return undefined;
          }
        }
      },1000,'a');
    });
    d = loop(d,function(i,task) {
      var out = prepare_adorn_span(task[1],task[2],task[3],task[4]);
      return [task[0],out,task[5]];
    },1000,'b');
    d = loop(d,function(i,change) {
      change[0].html(change[1]);
      $.each(change[2],function(i,fl) {
        fl[0].html(fl[1]);
      });
    },1000,'c');
    d = fire(d,function() {
      $('.adornment-data',outer).remove();
      $outer.appendTo(wrapper);
      add_legend($outer,data.legend||data.provisional.legend,
                        data.loading||data.provisional.loading);
    });
    if(data.url) {
      d = d.then(function() {
        $.paced_ajax({ dataType: "html", url: data.url}).then(function(page) {
          var data = $.parseJSON($('.adornment-data',page).text());
          _do_adorn(outer,fixups,data);
        });
      });
    } else {
      d = fire(d,function() {
        $outer.addClass('adornment-done');
        $outer.removeClass('adornment-running');
      });
    }
    d = d.then(function() { fixups(outer); });
    return d;
  }

  $.fn.adorn = function(fixups) {
    var all = [];
    this.each(function(i,outer) {
      beat(_do_adorn(outer,fixups));
    });
    return d;
  };

})(jQuery);
<commit_msg>Emty key removal. Again!<commit_after>/*
 * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function($) {
  function sorted_each(hash,fn,map) {
    var arr = [];
    if(!map) { map = {}; }
    $.each(hash,function(k,v) { arr.push([k,v]); });
    arr.sort(function(a,b) {
      var al = a[0].toLowerCase();
      var bl = b[0].toLowerCase();
      if(map[a[0]]) { al = map[a[0]]; }
      if(map[b[0]]) { bl = map[b[0]]; }
      if(al<bl) { return -1; }
      if(al>bl) { return 1; }
      return 0;
    });
    $.each(arr,function(i,e) {
      fn(e[0],e[1]);
    });
  }

  function beat(def) {
    return def.then(function(data) {
      var d = $.Deferred();
      setTimeout(function() { d.resolve(data); },0);
      return d;
    });
  }

  function loop(def,fn,group,part) {
    return def.then(function(raw_input) {
      var input = [];
      $.each(raw_input,function(a,b) { input.push([a,b]); });
      d = $.Deferred().resolve(input);
      var output = [];
      for(var i=0;i<input.length;i+=group) {
        d = beat(d.then(function(j) {
          for(j=0;j<group && i+j<input.length;j++) {
            var c = fn(input[i+j][0],input[i+j][1]);
            if(c !== undefined) {
              output.push(c);
            }
          }
          return $.Deferred().resolve(output);
        }));
      }
      return d;
    });
  }

  function fire(def,fn) {
    return def.then(function(data) {
      fn();
      return $.Deferred().resolve(data);
    });
  }

  function fix_letters(text,ref,seq) {
    var out = "";

    var s = undefined;
    if(!seq.letter) { seq.letter = []; }
    for(var i=0;i<text.length;i++) {
      if(i < seq.letter.length) { s = seq.letter[i]; }
      if(s) {
        out += ref.letter[s];
      } else {
        out += text.substr(i,1);
      }
    }
    return out;
  }

  function unprefix(ref) {
    var len = 0;
    for(var i=0;i<ref.length;i++) {
      len += ref[i][0];
      if(len) {
        ref[i][0] = ref[i-1].substr(0,len);
      } else {
        ref[i][0] = "";
      }
      ref[i] = ref[i][0] + ref[i][1];
    }
    return ref;
  }

  function unrle(seq) {
    var prev = undefined;
    var out = [];

    if(!$.isArray(seq)) { return seq; }
    for(var i=0;i<seq.length;i++) {
      if(seq[i]<0) {
        for(var j=0;j<-seq[i];j++) { out.push(prev); }
      } else {
        out.push(seq[i]);
        prev = seq[i];
      }
    }
    return out;
  }

  function make_groups(seq,textlen) {
    var styles = [];
    $.each(seq,function(key,values) {
      var value = undefined;
      for(var i=0;i<textlen;i++) {
        if(i < values.length) { value = values[i]; }
        if(!styles[i]) { styles[i] = {}; }
        styles[i][key] = value;
      }
    });
    var last = null;
    $.each(styles,function(i,cur) {
      if(last) {
        var diffs = 0;
        $.each(seq,function(k,v) {
          if(k == 'letter') { return; }
          if(last[k] || cur[k]) {
            if(!last[k] || !cur[k] || last[k]!=cur[k]) { diffs = 1; }
          }
        });
        if(!diffs) { cur.__repeat = 1; }
      }
      last = cur;
    });
    var groups = [];
    $.each(styles,function(i,cur) {
      if(cur.__repeat) {
        groups[groups.length-1].__len++;
      } else {
        cur.__len = 1;
        groups.push(cur);
      }
    });
    return groups;
  }

  function adorn_group(ref,group,text) {
    var otag = "span";
    var ctag = "span";
    if(group.href) {
      otag = "a class='sequence_info'";
      ctag = "a";
    }
    if(group.tag) {
      otag = ref.tag[group.tag];
      ctag = ref.tag[group.tag];
    }
    $.each(['href','title','style'],function(i,k) {
      if(group[k]) {
        otag += ' '+k+'="'+ref[k][group[k]]+'"';
      }
    });
    return "<"+otag+">"+text+"</"+ctag+">";
  }

  function prepare_adorn_span(text,ref,seq,xxx) {
    text = fix_letters(text,ref,seq);
    var groups = make_groups(seq,text.length);
    var pos = 0;
    var out = '';
    $.each(groups,function(i,group) {
      out += adorn_group(ref,group,text.substr(pos,group.__len));
      pos += group.__len;
    });
    return out;
  }

  function add_legend($outer,legend,loading) {
    var $key = $outer.parents('.js_panel').find('.adornment-key');
    // Add new legend to data
    var data = $key.data('data');
    if(!data) { data = {}; }
    if(legend) {
      $.each(legend,function(cn,cv) {
        if(!data[cn] || data[cn] === -1) { data[cn] = {}; }
        if(cn == '_messages') {
          $.each(cv,function(i,ev) {
            data[cn][ev] = 1;
          });
        } else {
          $.each(cv,function(en,ev) {
            data[cn][en] = ev;
          });
        }
      });
    }
    delete data['Basic Annotation'];
    var any = 0;
    $.each(data,function(a,b) { any = 1; });
    if(!any) {
      data['Basic Annotation'] = -1;
    }
    $.each(loading,function(i,load) {
      if(!data[load]) { data[load] = -1; }
    });
    $key.data('data',data);
    // Replace legend with new data
    var key = '';
    sorted_each(data,function(cn,cv) {
      if(cn == '_messages') { return; }
      var row = '';
      if(cv === -1) {
        row += '
loading
';
      } else {
        sorted_each(cv,function(en,ev) {
          var style = '';
          if(!ev) { return; }
          if(ev['default']) {
            style += "background-color: " + ev['default'] + ";";
          }
          if(ev.label) { style += "color: " + ev.label + ";"; }
          if(ev.extra_css) { style += ev.extra_css; }
          row += '
' +
            ev.text + '
';
        });
      }
      if(row) {
        var name = cn.substr(0,1).toUpperCase()+cn.substr(1);
        name = name.replace(/([\/-])/g,"$1 ");
        key += '
'+name+'

'+row+'

';
      }
    },{ other: "~" });
    var messages = '';
    if(data._messages) {
      $.each(data._messages,function(message,v) {
        messages += '
'+message+'
';
      });
    }
    var html = '';
    if(key || messages) { html += '
Key:
'; }
    if(key) { html += '
' + key +'
'; }
    if(messages) { html += '
' + messages + '
'; }
    $key.html(html);
  }

  function _do_adorn(outer,fixups,data) {
    var $outer = $(outer);
    if(($outer.hasClass('adornment-running') && !data) ||
       $outer.hasClass('adornment-done')) {
      return $.Deferred().resolve(0);
    }
    var wrapper = $outer.wrap("

").parent();
    $outer.addClass('adornment-running');
    if(!data) {
      data = $.parseJSON($('.adornment-data',outer).text());
    }
    add_legend($outer,null,data.loading||data.provisional.loading);
    var d;
    if(data.url) {
      d = $.Deferred().resolve(data.provisional);
    } else {
      d = $.Deferred().resolve(data);
    }
    d = d.then(function(data) {
      $.each(data.ref,function(k,v) {
        data.ref[k] = unprefix(data.ref[k]);
      });
      $.each(data.seq,function(k,v) {
        if($.isPlainObject(data.seq[k])) {
          $.each(data.seq[k],function(a,b) {
            data.seq[k][a] = unrle(data.seq[k][a]);
          });
        }
      });
      data.seq = unrle(data.seq);
      return loop($.Deferred().resolve(data.seq),function(key,values) {
        if(values) {
          var el = $('.adorn-'+key,outer);
          if(el.length) {
            var fl = {};
            $.each(data.flourishes,function(k,v) {
              var f = v[key];
              var fl_el = $('.ad-'+k+'-'+key,outer);
              if(f && fl_el.length) {
                fl[k] = [fl_el,$.parseJSON(f).v];
              }
            });
            return [el,el.text(),data.ref,values,key,fl];
          } else {
            return undefined;
          }
        }
      },1000,'a');
    });
    d = loop(d,function(i,task) {
      var out = prepare_adorn_span(task[1],task[2],task[3],task[4]);
      return [task[0],out,task[5]];
    },1000,'b');
    d = loop(d,function(i,change) {
      change[0].html(change[1]);
      $.each(change[2],function(i,fl) {
        fl[0].html(fl[1]);
      });
    },1000,'c');
    d = fire(d,function() {
      $('.adornment-data',outer).remove();
      $outer.appendTo(wrapper);
      add_legend($outer,data.legend||data.provisional.legend,
                        data.loading||data.provisional.loading);
    });
    if(data.url) {
      d = d.then(function() {
        $.paced_ajax({ dataType: "html", url: data.url}).then(function(page) {
          var data = $.parseJSON($('.adornment-data',page).text());
          _do_adorn(outer,fixups,data);
        });
      });
    } else {
      d = fire(d,function() {
        $outer.addClass('adornment-done');
        $outer.removeClass('adornment-running');
      });
    }
    d = d.then(function() { fixups(outer); });
    return d;
  }

  $.fn.adorn = function(fixups) {
    var all = [];
    this.each(function(i,outer) {
      beat(_do_adorn(outer,fixups));
    });
    return d;
  };

})(jQuery);
<|endoftext|>