<commit_before>
setTimeout(() => {

  var TodoElement = function TodoElement() {
    var ClockElement = __Element(__.intervalSeq(Immutable.Range(), 100).__(function() {
      return React.createElement(
        'div',
        null,
        moment().format('MMMM Do YYYY, h:mm:ss a')
      );
    }));
    var __fdList = __().__(function(val) {
      return __.log.t = val;
    });
    var __lists = __(true).__(function(__list) {
      return __fdList.t = __lists.length;
    });
    var ListofListElement = __Element(__([__lists]).__(function() {
      return __lists.map(function(list, i) {
        return React.createElement(
          'button',
          {
            onClick: function onClick() {
              return __.log.t = __fdList.t = i;
            }
          },
          'List#' + (i + 1)
        );
      });
    }));
    var InputElement = function InputElement() {
      var __value = __();
      var onChange = function onChange(e) {
        return __value.t = e.target.value;
      };
      var onClick = function onClick() {
        return __.log.t = __lists[__fdList.t].t = __value.t;
      };
      var onClickNL = function onClickNL() {
        return __.log.t = __lists.t = __(true);
      };
      var __seqEl = __([__value]).__(function(value) {
        return React.createElement(
          'div',
          null,
          React.createElement(
            'h4',
            null,
            'List#' + (__fdList.t + 1),
            React.createElement(
              'button',
              {
                onClick: onClickNL
              },
              'NewList'
            )
          ),
          __lists[__fdList.t].map(function(item) {
            return React.createElement(
              'li',
              null,
              item
            );
          }),
          React.createElement('input', {
            type: 'text',
            value: value,
            onChange: onChange
          }),
          React.createElement(
            'button',
            {
              onClick: onClick
            },
            'NewToDo#' + (__lists[__fdList.t].length + 1)
          )
        );
      });
      __.log.__(function() {
        return __value.t = "";
      });
      return __Element(__seqEl);
    };
    __lists.t = __(true); //new items-list
    var __delay = __.intervalSeq(Immutable.Seq.of("started!"), 1000).__(function() {
      return __.log.t = "showInput";
    });
    return React.createElement(
      'div',
      null,
      React.createElement(
        'h2',
        null,
        'ToDo'
      ),
      ClockElement,
      React.createElement('p', null),
      ListofListElement,
      React.createElement('p', null),
      InputElement()
    );
  };
  var mount = ReactDOM.render(TodoElement(), document.getElementById('todo'));
  //---------

}, 1000);
<commit_msg>commit<commit_after>
setTimeout(() => {

  var TodoElement = function TodoElement() {
    var ClockElement = __Element(__.intervalSeq(Immutable.Range(), 100).__(function() {
      return React.createElement(
        'div',
        null,
        moment().format('MMMM Do YYYY, h:mm:ss a')
      );
    }));
    var __fdList = __().__(function(val) {
      return __.log.t = val;
    });
    var __lists = __(true).__(function(__list) {
      return __fdList.t = __lists.length;
    });
    var ListofListElement = __Element(__([__lists]).__(function() {
      return __lists.map(function(list, i) {
        return React.createElement(
          'button',
          {
            onClick: function onClick() {
              return __.log.t = __fdList.t = i;
            }
          },
          'List#' + (i + 1)
        );
      });
    }));
    var InputElement = function InputElement() {
      var __value = __();
      var onChange = function onChange(e) {
        return __value.t = e.target.value;
      };
      var onClick = function onClick() {
        return __.log.t = __lists[__fdList.t].t = __value.t;
      };
      var onClickNL = function onClickNL() {
        return __.log.t = __lists.t = __(true);
      };
      var __seqEl = __([__value]).__(function(value) {
        return React.createElement(
          'div',
          null,
          React.createElement(
            'h4',
            null,
            'List#' + (__fdList.t + 1),
            React.createElement(
              'button',
              {
                onClick: onClickNL
              },
              'NewList'
            )
          ),
          __lists[__fdList.t].map(function(item) {
            return React.createElement(
              'li',
              null,
              item
            );
          }),
          React.createElement('input', {
            type: 'text',
            value: value,
            onChange: onChange
          }),
          React.createElement(
            'button',
            {
              onClick: onClick
            },
            'NewToDo#' + (__lists[__fdList.t].length + 1)
          )
        );
      });
      __.log.__(function() {
        return __value.t = "";
      });
      return __Element(__seqEl);
    };
    __lists.t = __(true); //new items-list
    var __delay = __.intervalSeq(Immutable.Seq.of("started!"), 1000).__(function() {
      return __.log.t = "showInput";
    });
    return React.createElement(
      'div',
      null,
      React.createElement(
        'h2',
        null,
        'ToDo'
      ),
      ClockElement,
      React.createElement('p', null),
      ListofListElement,
      React.createElement('p', null),
      InputElement()
    );
  };
  var mount = ReactDOM.render(TodoElement(), document.getElementById('todo2'));
  //---------

}, 1000);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 by CoNarrative
 */
glu.model = function (config) {
    //clean up arguments...
    if (glu.isString(config)) {
        config = {
            mtype : config
        };
    }
    if (config.mtype && config.mtype.indexOf('.')>-1){
        var split = glu._splitReference(config.mtype);
        config.ns = split.ns;
        config.mtype = split.name;
    }

    function upcastIfNeeded (cfg){
        if (cfg.mtype==='viewmodel' &&  (cfg.fields || cfg.recType || cfg.modelType || cfg.model)) {
            return 'datamodel';
        }
        return cfg.mtype;
    }

    config.mtype = config.mtype || 'viewmodel';
    config.mtype = upcastIfNeeded(config);
    var mtype = config.mtype;
    var ns = config.ns;
    var viewModelRegistry = ns ? glu.walk(ns + '.' + glu.conventions.viewmodelNs) : {};
    if (glu.mtypeRegistry.hasOwnProperty(mtype)) {
        //not a view model
        var mixins = config.mixins || [], applyMixins=[], i=0;
        for (; i < mixins.length; i++) {
            var mixinConfig = mixins[i], mixinName;
            if( glu.isObject(mixinConfig) )
                mixinName = mixinConfig.type;
            else
                mixinName = mixinConfig;
            var mixin = viewModelRegistry[mixinName] || glu.mtypeRegistry[mixinName];
            if (mixin === undefined) {
                var factory = viewModelRegistry[mixinName + 'Factory'];
                if (factory === undefined)     throw ('Unable to find mixin: ' + mixinName );
                mixin = factory(config);
            }
            if( glu.isObject(mixinConfig) )
                glu.apply(mixin, mixinConfig);
            glu.deepApply(config, mixin, true);
            applyMixins.push(mixin);
            if( glu.mtypeRegistry[mixinName] )
                delete config.mixins;
        }
        var temp = new glu.mtypeRegistry[mtype](config);
        for( i=0; i < applyMixins.length; i++ ){
            if( applyMixins[i].initMixin )
                applyMixins[i].initMixin.apply(temp);
        }
        return temp;
    }
    //try seeing if it is a view model in the namespace
    glu.log.debug(mtype + ' is not a built-in type, checking for a view model under the namespace. ');
    if (!ns) {
        throw ('Unable to create model: attempting to create a specified view model without a namespace (ns).');
    }
    var className = mtype;
    var vmSpecBase = viewModelRegistry[className];
    if (vmSpecBase === undefined) {
        //check for factory
        var factory = viewModelRegistry[className + 'Factory'];
        if (factory === undefined) {
            throw ('Unable to create model: Could not find specification for view model ' + className);
        }
        vmSpecBase = factory(config);
    }
    //make a copy...
    var vmSpec = {};
    //apply mixins...
    //applyMixins(vmSpecBase);

    //apply the specification
    glu.deepApply(vmSpec, vmSpecBase);
    //apply unique configs over top...
    glu.deepApply(vmSpec, config);
    vmSpec.mtype = vmSpecBase.mtype || 'viewmodel';
    vmSpec.mtype = upcastIfNeeded(vmSpec);
    vmSpec.ns = ns;
    vmSpec.viewmodelName = className;
    vmSpec.referenceName = vmSpec.referenceName || 'root';
    return new glu.model(vmSpec);
};<commit_msg>Added support for this.model ('modelname',{def:true}) signature<commit_after>/*
 * Copyright (C) 2012 by CoNarrative
 */
glu.model = function (mtype, config) {
    //clean up arguments...
    if (glu.isObject(mtype)) {
        config = mtype;
        mtype = null;
    }
    if (config==null){
        config = {};
    }
    config.mtype=config.mtype || mtype || 'viewmodel';

    if (config.mtype && config.mtype.indexOf('.')>-1){
        var split = glu._splitReference(config.mtype);
        config.ns = split.ns;
        config.mtype = split.name;
    }

    function upcastIfNeeded (cfg){
        if (cfg.mtype==='viewmodel' &&  (cfg.fields || cfg.recType || cfg.modelType || cfg.model)) {
            return 'datamodel';
        }
        return cfg.mtype;
    }

    config.mtype = config.mtype || 'viewmodel';
    config.mtype = upcastIfNeeded(config);
    var mtype = config.mtype;
    var ns = config.ns;
    var viewModelRegistry = ns ? glu.walk(ns + '.' + glu.conventions.viewmodelNs) : {};
    if (glu.mtypeRegistry.hasOwnProperty(mtype)) {
        //not a view model
        var mixins = config.mixins || [], applyMixins=[], i=0;
        for (; i < mixins.length; i++) {
            var mixinConfig = mixins[i], mixinName;
            if( glu.isObject(mixinConfig) )
                mixinName = mixinConfig.type;
            else
                mixinName = mixinConfig;
            var mixin = viewModelRegistry[mixinName] || glu.mtypeRegistry[mixinName];
            if (mixin === undefined) {
                var factory = viewModelRegistry[mixinName + 'Factory'];
                if (factory === undefined)     throw ('Unable to find mixin: ' + mixinName );
                mixin = factory(config);
            }
            if( glu.isObject(mixinConfig) )
                glu.apply(mixin, mixinConfig);
            glu.deepApply(config, mixin, true);
            applyMixins.push(mixin);
            if( glu.mtypeRegistry[mixinName] )
                delete config.mixins;
        }
        var temp = new glu.mtypeRegistry[mtype](config);
        for( i=0; i < applyMixins.length; i++ ){
            if( applyMixins[i].initMixin )
                applyMixins[i].initMixin.apply(temp);
        }
        return temp;
    }
    //try seeing if it is a view model in the namespace
    glu.log.debug(mtype + ' is not a built-in type, checking for a view model under the namespace. ');
    if (!ns) {
        throw ('Unable to create model: attempting to create a specified view model without a namespace (ns).');
    }
    var className = mtype;
    var vmSpecBase = viewModelRegistry[className];
    if (vmSpecBase === undefined) {
        //check for factory
        var factory = viewModelRegistry[className + 'Factory'];
        if (factory === undefined) {
            throw ('Unable to create model: Could not find specification for view model ' + className);
        }
        vmSpecBase = factory(config);
    }
    //make a copy...
    var vmSpec = {};
    //apply mixins...
    //applyMixins(vmSpecBase);

    //apply the specification
    glu.deepApply(vmSpec, vmSpecBase);
    //apply unique configs over top...
    glu.deepApply(vmSpec, config);
    vmSpec.mtype = vmSpecBase.mtype || 'viewmodel';
    vmSpec.mtype = upcastIfNeeded(vmSpec);
    vmSpec.ns = ns;
    vmSpec.viewmodelName = className;
    vmSpec.referenceName = vmSpec.referenceName || 'root';
    return new glu.model(vmSpec);
};<|endoftext|>


<commit_before>var mongoose = require('mongoose');

var eventSchema = new mongoose.Schema({
  name: String, // "Bob's Shindig"
  hash: String, // "3JHG63JKH6G3J4HG6" // a URL safe hash that identifies the event
  organizer: [String], // ["2dhf5dyd6d83v63vxmv724"] // One or more user hashes
  skin: String // "Night"
  // _id: "577079c2583eab030090ae97"
});

var model = mongoose.model('Event', eventSchema);

module.exports = model;
<commit_msg>added a few fields to the event model<commit_after>var mongoose = require('mongoose');

var eventSchema = new mongoose.Schema({
  name: String, // "Bob's Shindig"
  hash: String, // "3JHG63JKH6G3J4HG6" // a URL safe hash that identifies the event
  organizer: [String], // ["2dhf5dyd6d83v63vxmv724"] // One or more user hashes
  skin: String, // "Night"
  location: String,
  date: String,
  times: String,
  description: String
  // _id: "577079c2583eab030090ae97"
});

var model = mongoose.model('Event', eventSchema);

module.exports = model;
<|endoftext|>


<commit_before>/*jslint node: true */
module.exports = function (config) {
    'use strict';

    var customLaunchers = {
        sl_chrome: {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform : 'Linux',
            version: '37'
        },
        sl_firefox: {
            base: 'SauceLabs',
            browserName: 'firefox',
            platform: 'Linux',
            version: '33'
        },
        sl_ie_11: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8.1',
            version: '11'
        },
        sl_ie_10: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8',
            version: '10'
        },
        sl_ie_9: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '9'
        },
        sl_safari: {
            base: 'SauceLabs',
            browserName: 'safari',
            platform: 'OS X 10.9',
            version: '7'
        }
    };

    config.set({

        basePath: '',

        files: [
            'app/bower_components/angular/angular.js',
            'app/bower_components/angular-route/angular-route.js',
            'app/bower_components/angular-mocks/angular-mocks.js',
            'app/bower_components/angular-cookies/angular-cookies.js',
            'app/bower_components/angular-bootstrap/ui-bootstrap.js',
            'app/bower_components/underscore/underscore.js',
            'app/bower_components/jquery/dist/jquery.js',
            'app/js/app.js',
            'app/js/**/*.js',
            'test/client/**/*.js'
        ],

        sauceLabs: {
            testName: 'Juice-Shop Angular Unit Tests',
            tags: [process.env.TRAVIS_BRANCH],
            recordScreenshots: false
        },

        colors: true,
        singleRun: true,

        frameworks: ['jasmine'],

        browsers: Object.keys(customLaunchers),

        customLaunchers: customLaunchers,

        reporters: ['dots', 'saucelabs']

    });
};
<commit_msg>increased tolerance/timeouts for connections with saucelabs<commit_after>/*jslint node: true */
module.exports = function (config) {
    'use strict';

    var customLaunchers = {
        sl_chrome: {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform : 'Linux',
            version: '37'
        },
        sl_firefox: {
            base: 'SauceLabs',
            browserName: 'firefox',
            platform: 'Linux',
            version: '33'
        },
        sl_ie_11: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8.1',
            version: '11'
        },
        sl_ie_10: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8',
            version: '10'
        },
        sl_ie_9: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '9'
        },
        sl_safari: {
            base: 'SauceLabs',
            browserName: 'safari',
            platform: 'OS X 10.9',
            version: '7'
        },
        sl_ios: {
            base: 'SauceLabs',
            browserName: 'iPad',
            platform: 'OS X 10.9',
            version: '8.0'
        },
        sl_android: {
            base: 'SauceLabs',
            browserName: 'android',
            platform: 'Linux',
            version: '4.4'
        }
    };

    config.set({

        basePath: '',

        files: [
            'app/bower_components/angular/angular.js',
            'app/bower_components/angular-route/angular-route.js',
            'app/bower_components/angular-mocks/angular-mocks.js',
            'app/bower_components/angular-cookies/angular-cookies.js',
            'app/bower_components/angular-bootstrap/ui-bootstrap.js',
            'app/bower_components/underscore/underscore.js',
            'app/bower_components/jquery/dist/jquery.js',
            'app/js/app.js',
            'app/js/**/*.js',
            'test/client/**/*.js'
        ],

        sauceLabs: {
            testName: 'Juice-Shop Angular Unit Tests',
            tags: [process.env.TRAVIS_BRANCH],
            recordScreenshots: false,

        },

        browserDisconnectTimeout : 10000,
        browserDisconnectTolerance : 1,
        browserNoActivityTimeout : 4*60*1000,
        captureTimeout : 4*60*1000,

        colors: true,
        singleRun: true,

        frameworks: ['jasmine'],

        browsers: Object.keys(customLaunchers),

        customLaunchers: customLaunchers,

        reporters: ['dots', 'saucelabs']

    });
};
<|endoftext|>


<commit_before>/**
 * Created by Manhhailua on 11/24/16.
 */

/* eslint-disable import/prefer-default-export */

import Response from './Response';
import Zone from './Zone';
import Share from './Share';
import Placement from './Placement';
import Banner from './Banner';

export {
  Response,
  Zone,
  Share,
  Placement,
  Banner,
};
<commit_msg>remove model:Response<commit_after>/**
 * Created by Manhhailua on 11/24/16.
 */

/* eslint-disable import/prefer-default-export */

export Zone from './Zone';
export Share from './Share';
export Placement from './Placement';
export Banner from './Banner';
<|endoftext|>


<commit_before>const customLaunchers = {
  sl_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'Windows 7',
  },
  sl_firefox: {
    base: 'SauceLabs',
    browserName: 'firefox',
  },
  sl_mac_safari: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.10',
  },
  sl_ie_9: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '9',
  },
  sl_ie_10: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 8',
    version: '10',
  },
  sl_ie_11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 8.1',
    version: '11',
  },
  sl_edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10',
  },
  sl_ios_safari_8: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '8.4',
  },
  sl_ios_safari_9: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '9.3',
  },
  sl_android_5_1: {
    base: 'SauceLabs',
    browserName: 'android',
    version: '5.1',
  },
};

module.exports = (config) => {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: ['src/**/*.js', 'test/**/*.spec.js'],
    reporters: ['dots', 'saucelabs', 'coverage', 'coveralls'],
    preprocessors: {
      '**/src/**/*.js': ['babel'],
      'test/**/*.spec.js': ['babel'],
    },
    babelPreprocessor: {
      filename(file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName(file) {
        return file.originalPath;
      },
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      testName: 'Flextype',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
      startConnect: false,
    },
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/',
    },
    customLaunchers,
    browsers: Object.keys(customLaunchers),
    singleRun: true,
    captureTimeout: 300000,
    browserNoActivityTimeout: 300000,
  });
};
<commit_msg>Add coverage preprocessor<commit_after>const customLaunchers = {
  sl_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'Windows 7',
  },
  sl_firefox: {
    base: 'SauceLabs',
    browserName: 'firefox',
  },
  sl_mac_safari: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.10',
  },
  sl_ie_9: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '9',
  },
  sl_ie_10: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 8',
    version: '10',
  },
  sl_ie_11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 8.1',
    version: '11',
  },
  sl_edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10',
  },
  sl_ios_safari_8: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '8.4',
  },
  sl_ios_safari_9: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '9.3',
  },
  sl_android_5_1: {
    base: 'SauceLabs',
    browserName: 'android',
    version: '5.1',
  },
};

module.exports = (config) => {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: ['src/**/*.js', 'test/**/*.spec.js'],
    reporters: ['dots', 'saucelabs', 'coverage', 'coveralls'],
    preprocessors: {
      '**/src/**/*.js': ['coverage', 'babel'],
      'test/**/*.spec.js': ['babel'],
    },
    babelPreprocessor: {
      filename(file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName(file) {
        return file.originalPath;
      },
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      testName: 'Flextype',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
      startConnect: false,
    },
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/',
    },
    customLaunchers,
    browsers: Object.keys(customLaunchers),
    singleRun: true,
    captureTimeout: 300000,
    browserNoActivityTimeout: 300000,
  });
};
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = function (config) {

    // Use ENV vars on Travis and sauce.json locally to get credentials
    if (!process.env.SAUCE_USERNAME) {
        if (!fs.existsSync('sauce.json')) {
            console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.');
            process.exit(1);
        } else {
            process.env.SAUCE_USERNAME = require('./sauce').username;
            process.env.SAUCE_ACCESS_KEY = require('./sauce').accessKey;
        }
    }

    // Browsers to run on Sauce Labs
    var customLaunchers = {
        sl_win7_ie9: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '9.0'
        },
        //sl_win7_ie10: {
        //    base: 'SauceLabs',
        //    browserName: 'internet explorer',
        //    platform: 'Windows 7',
        //    version: '10.0'
        //},
        //sl_win7_ie11: {
        //    base: 'SauceLabs',
        //    browserName: 'internet explorer',
        //    platform: 'Windows 7',
        //    version: '11.0'
        //},
        sl_win8_ie10: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8',
            version: '10.0'
        },
        sl_win81_ie11: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8.1',
            version: '11.0'
        },
        //sl_winXP_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows XP',
        //    version: '43.0'
        //},
        //sl_winXP_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows XP',
        //    version: '38.0'
        //},
        //sl_win7_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows 7',
        //    version: '43.0'
        //},
        //sl_win7_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows 7',
        //    version: '38.0'
        //},
        //sl_win8_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows 8',
        //    version: '43.0'
        //},
        //sl_win8_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows 8',
        //    version: '38.0'
        //},
        //sl_win81_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows 8.1',
        //    version: '43.0'
        //},
        //sl_win81_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows 81',
        //    version: '38.0'
        //},
        sl_mac10_chrome: {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform: 'OSX 10.10',
            version: '43.0'
        },
        //sl_mac10_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'OSX 10.10',
        //    version: '38.0'
        //},
        //sl_mac10_safari: {
        //    base: 'SauceLabs',
        //    browserName: 'safari',
        //    platform: 'OS X 10.10',
        //    version: '8.0'
        //},
        //sl_mac9_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'OSX 10.9',
        //    version: '43.0'
        //},
        //sl_mac9_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'OSX 10.9',
        //    version: '38.0'
        //},
        //sl_mac9_safari: {
        //    base: 'SauceLabs',
        //    browserName: 'safari',
        //    platform: 'OS X 10.9',
        //    version: '7.0'
        //},
        //sl_linux_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Linux',
        //    version: '43.0'
        //},
        sl_linux_firefox: {
            base: 'SauceLabs',
            browserName: 'firefox',
            platform: 'Linux',
            version: '38.0'
        },
        sl_linux_opera: {
            base: 'SauceLabs',
            browserName: 'opera',
            platform: 'Linux',
            version: '12.15'
        }
    };

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha'],

        // list of files / patterns to load in the browser
        files: [
            './lib/opendolphin/opendolphin-0.11.js',
            './bower_components/observe-js/src/observe.js',
            './test/build/**/test-*.js'
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['saucelabs', 'teamcity'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        sauceLabs: {
            testName: 'dolphin-js Unit Tests',
            //startConnect: true
            recordScreenshots: false,
            recordVideo: false
        },
        captureTimeout: 120000,
        browserDisconnectTimeout: 10 * 1000,
        browserDisconnectTolerance: 3,
        browserNoActivityTimeout: 20 * 1000,

        customLaunchers: customLaunchers,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: Object.keys(customLaunchers)

    });
};
<commit_msg>Enable some of the configured browsers<commit_after>var fs = require('fs');

module.exports = function (config) {

    // Use ENV vars on Travis and sauce.json locally to get credentials
    if (!process.env.SAUCE_USERNAME) {
        if (!fs.existsSync('sauce.json')) {
            console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.');
            process.exit(1);
        } else {
            process.env.SAUCE_USERNAME = require('./sauce').username;
            process.env.SAUCE_ACCESS_KEY = require('./sauce').accessKey;
        }
    }

    // Browsers to run on Sauce Labs
    var customLaunchers = {
        sl_win7_ie9: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '9.0'
        },
        sl_win7_ie10: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '10.0'
        },
        sl_win7_ie11: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '11.0'
        },
        sl_win8_ie10: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8',
            version: '10.0'
        },
        sl_win81_ie11: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8.1',
            version: '11.0'
        },
        //sl_winXP_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows XP',
        //    version: '43.0'
        //},
        //sl_winXP_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows XP',
        //    version: '38.0'
        //},
        //sl_win7_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows 7',
        //    version: '43.0'
        //},
        //sl_win7_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows 7',
        //    version: '38.0'
        //},
        //sl_win8_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows 8',
        //    version: '43.0'
        //},
        //sl_win8_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows 8',
        //    version: '38.0'
        //},
        //sl_win81_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Windows 8.1',
        //    version: '43.0'
        //},
        //sl_win81_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'Windows 81',
        //    version: '38.0'
        //},
        sl_mac10_chrome: {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform: 'OSX 10.10',
            version: '43.0'
        },
        //sl_mac10_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'OSX 10.10',
        //    version: '38.0'
        //},
        //sl_mac10_safari: {
        //    base: 'SauceLabs',
        //    browserName: 'safari',
        //    platform: 'OS X 10.10',
        //    version: '8.0'
        //},
        //sl_mac9_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'OSX 10.9',
        //    version: '43.0'
        //},
        //sl_mac9_firefox: {
        //    base: 'SauceLabs',
        //    browserName: 'firefox',
        //    platform: 'OSX 10.9',
        //    version: '38.0'
        //},
        //sl_mac9_safari: {
        //    base: 'SauceLabs',
        //    browserName: 'safari',
        //    platform: 'OS X 10.9',
        //    version: '7.0'
        //},
        //sl_linux_chrome: {
        //    base: 'SauceLabs',
        //    browserName: 'chrome',
        //    platform: 'Linux',
        //    version: '43.0'
        //},
        sl_linux_firefox: {
            base: 'SauceLabs',
            browserName: 'firefox',
            platform: 'Linux',
            version: '38.0'
        },
        sl_linux_opera: {
            base: 'SauceLabs',
            browserName: 'opera',
            platform: 'Linux',
            version: '12.15'
        }
    };

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha'],

        // list of files / patterns to load in the browser
        files: [
            './lib/opendolphin/opendolphin-0.11.js',
            './bower_components/observe-js/src/observe.js',
            './test/build/**/test-*.js'
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['saucelabs', 'teamcity'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        sauceLabs: {
            testName: 'dolphin-js Unit Tests',
            //startConnect: true
            recordScreenshots: false,
            recordVideo: false
        },
        captureTimeout: 120000,
        browserDisconnectTimeout: 10 * 1000,
        browserDisconnectTolerance: 3,
        browserNoActivityTimeout: 20 * 1000,

        customLaunchers: customLaunchers,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: Object.keys(customLaunchers)

    });
};
<|endoftext|>


<commit_before>module.exports = function(config) {

  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    process.exit(1);
  }

  // Browsers to run on Sauce Labs
  // Check out https://saucelabs.com/platforms for all browser/OS combos
  var customLaunchers = {

    sl_ms_edge: {
      base: "SauceLabs",
      browserName: "microsoftedge",
      platform: "Windows 10",
    },

    sl_ie_11: {
      base: "SauceLabs",
      browserName: "Internet Explorer",
      platform: "Windows 8.1",
      version: "11"
    },
    sl_ie_10: {
      base: "SauceLabs",
      browserName: "Internet Explorer",
      platform: "Windows 8",
      version: "10"
    },
    sl_ie_9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    sl_ie_8: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '8'
    }
  };

  var sauceLabs = {
    startConnect: false,
    testName: 'availity-angular',
    recordScreenshots: false,
  };

  if(process.env.TRAVIS_JOB_NUMBER) {
    sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
  } else {
    sauceLabs.startConnect = true;
  }

  config.set({
    basePath: '',
    autoWatch: false,
    browsers: Object.keys(customLaunchers),
    customLaunchers: customLaunchers,
    frameworks: ['jasmine', 'fixture'],
    reporters: ['mocha', 'saucelabs'],
    port: 9876,
    colors: true,
    sauceLabs: sauceLabs,
    logLevel: config.LOG_INFO,
    captureTimeout: 120000,
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 2,
    browserNoActivityTimeout: 20000,
    singleRun: true,
    preprocessors: {
      '**/*-tpl.html': ['ng-html2js'],
      '**/*-fixture.html': ['ng-html2js']
    },
    ngHtml2JsPreprocessor: {
      // strip this from the file path
      stripPrefix: 'lib/',
      moduleName: 'availity.ui.templates'
    }
  });
};
<commit_msg>disable some browser for saucelabs<commit_after>module.exports = function(config) {

  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    process.exit(1);
  }

  // Browsers to run on Sauce Labs
  // Check out https://saucelabs.com/platforms for all browser/OS combos
  var customLaunchers = {

    // sl_ms_edge: {
    //   base: "SauceLabs",
    //   browserName: "microsoftedge",
    //   platform: "Windows 10",
    // },
    // sl_ie_11: {
    //   base: "SauceLabs",
    //   browserName: "Internet Explorer",
    //   platform: "Windows 8.1",
    //   version: "11"
    // },
    // sl_ie_10: {
    //   base: "SauceLabs",
    //   browserName: "Internet Explorer",
    //   platform: "Windows 8",
    //   version: "10"
    // },
    sl_ie_9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    sl_ie_8: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '8'
    }
  };

  var sauceLabs = {
    startConnect: false,
    testName: 'availity-angular',
    recordScreenshots: false,
  };

  if(process.env.TRAVIS_JOB_NUMBER) {
    sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
  } else {
    sauceLabs.startConnect = true;
  }

  config.set({
    basePath: '',
    autoWatch: false,
    browsers: Object.keys(customLaunchers),
    customLaunchers: customLaunchers,
    frameworks: ['jasmine', 'fixture'],
    reporters: ['mocha', 'saucelabs'],
    port: 9876,
    colors: true,
    sauceLabs: sauceLabs,
    logLevel: config.LOG_INFO,
    captureTimeout: 120000,
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 2,
    browserNoActivityTimeout: 20000,
    singleRun: true,
    preprocessors: {
      '**/*-tpl.html': ['ng-html2js'],
      '**/*-fixture.html': ['ng-html2js']
    },
    ngHtml2JsPreprocessor: {
      // strip this from the file path
      stripPrefix: 'lib/',
      moduleName: 'availity.ui.templates'
    }
  });
};
<|endoftext|>


<commit_before>import {TakeRequest, PutRequest} from './channel'
import {SelectRequest} from './select'

/**
 * Get the next value and pass an optional returnValue to the
 * iterator.
 */
function nextRequest(iterator, returnValue) {
  const {value, done} = iterator.next(returnValue)
  return {value, done}
}

function processGoRoutines(
  {goRoutines, lastSelectedChannel, channelBuffers},
) {
  goRoutines.forEach((goRoutine, i) => {
    const {iterator} = goRoutine
    // The current iterator value
    let {request} = goRoutine
    // If no request, then get one
    if (!request) {
      const {value, done} = nextRequest(iterator)
      Object.assign(goRoutine, {request: value, done})
    }
    // otherwise we "block" i.e., don't get anymore requests until we
    // satisfy the current request
    if (request instanceof TakeRequest) {
      // do we have put data?
      const {chanId} = request
      const channelData = channelBuffers[chanId].pop()
      if (channelData) {
        // Return the value to the iterator i.e., whoever made the
        // take request and get the next request. Yea this is wierd
        // but this is how iterators work.
        const {value, done} = nextRequest(iterator, {value: channelData})
        Object.assign(goRoutine, {request: value, done})
      }
    } else if (request instanceof PutRequest) {
      // we gots data to give
      const {chanId, msg} = request
      // Store the value in the buffer
      channelBuffers[chanId].add(msg)
      // Then get the next request
      const {value, done} = nextRequest(iterator)
      Object.assign(goRoutine, {request: value, done})
    } else if (request instanceof SelectRequest) {
      const {channels} = request
      const lastChannel = lastSelectedChannel[channels] || 0
      delete lastSelectedChannel[channels]
      // Just fire the first channel that receives a message: go thru
      // the selected channels and try to get values.  stop at the
      // first that has a value.  The problem is that a chatty
      // goroutine can drown out other channels. So next time we get
      // the same reselect, we need to pickup where we left off.
      const channelData = new Array(channels.length)
      let hasData = false
      for(let i=lastChannel; i<channelData.length; i++) {
        const chanId = channels[i]._id
        const data = channelBuffers[chanId].pop()
        if (typeof data !== 'undefined') {
          channelData[i] = data
          hasData = true
          if (i < channelData.length - 1) {
            lastSelectedChannel[channels] = i + 1
          }
          break
        }
      }
      if (hasData) {
        const {value, done} = nextRequest(iterator, {value: channelData})
        Object.assign(goRoutine, {request: value, done})
      }
    }
  })
}

/**
 * Returns a new array of goRoutines with the dones removed.
 * Note that as per https://jsperf.com/array-filter-performance,
 * Array.filter isn't as performant.
 */
function clearDones(goRoutines) {
  const countDones = goRoutines.reduce(
    (total, goRoutine) => { return goRoutine.done ? total + 1 : total },
    0
  )
  // first handle some simple cases first
  if (!countDones) {
    return goRoutines
  } else if (goRoutines.length === countDones) {
    return []
  }
  // then return a new array with all the done goRoutines removed
  let len = 0
  return goRoutines.reduce(
    (newGoRoutines, goRoutine, i) => {
      if (!goRoutine.done) {
        newGoRoutines[len++] = goRoutine
      }
      return newGoRoutines
    },
    new Array(goRoutines.length - countDones)
  )
}

function dispatcher(state) {
  processGoRoutines(state)
  state.goRoutines = clearDones(state.goRoutines)
  // recursively call itself
  runDispatcher(state)
}

/**
 * @param {array[]} state.goRoutines
 * @param {map} state.channelBuffers
 */
export function runDispatcher(state) {
  const {goRoutines} = state
  if (goRoutines.length) {
    setTimeout(() => dispatcher(state), 0)
  }
}
<commit_msg>[core] also killing selected channels on go routine ending<commit_after>import {TakeRequest, PutRequest} from './channel'
import {SelectRequest} from './select'

/**
 * Get the next value and pass an optional returnValue to the
 * iterator.
 */
function nextRequest(iterator, returnValue) {
  const {value, done} = iterator.next(returnValue)
  return {value, done}
}

function processGoRoutines(
  {goRoutines, lastSelectedChannel, channelBuffers},
) {
  goRoutines.forEach((goRoutine, i) => {
    const {iterator} = goRoutine
    // The current iterator value
    let {request} = goRoutine
    // If no request, then get one
    if (!request) {
      const {value, done} = nextRequest(iterator)
      Object.assign(goRoutine, {request: value, done})
    }
    // otherwise we "block" i.e., don't get anymore requests until we
    // satisfy the current request
    if (request instanceof TakeRequest) {
      // do we have put data?
      const {chanId} = request
      const channelData = channelBuffers[chanId].pop()
      if (channelData) {
        // Return the value to the iterator i.e., whoever made the
        // take request and get the next request. Yea this is wierd
        // but this is how iterators work.
        const {value, done} = nextRequest(iterator, {value: channelData})
        Object.assign(goRoutine, {request: value, done})
      }
    } else if (request instanceof PutRequest) {
      // we gots data to give
      const {chanId, msg} = request
      // Store the value in the buffer
      channelBuffers[chanId].add(msg)
      // Then get the next request
      const {value, done} = nextRequest(iterator)
      Object.assign(goRoutine, {request: value, done})
    } else if (request instanceof SelectRequest) {
      const {channels} = request
      const lastChannel = lastSelectedChannel[channels] || 0
      delete lastSelectedChannel[channels]
      // Just fire the first channel that receives a message: go thru
      // the selected channels and try to get values.  stop at the
      // first that has a value.  The problem is that a chatty
      // goroutine can drown out other channels. So next time we get
      // the same reselect, we need to pickup where we left off.
      const channelData = new Array(channels.length)
      let hasData = false
      for(let i=lastChannel; i<channelData.length; i++) {
        const chanId = channels[i]._id
        const data = channelBuffers[chanId].pop()
        if (typeof data !== 'undefined') {
          channelData[i] = data
          hasData = true
          if (i < channelData.length - 1) {
            lastSelectedChannel[channels] = i + 1
          }
          break
        }
      }
      if (hasData) {
        const {value, done} = nextRequest(iterator, {value: channelData})
        Object.assign(goRoutine, {request: value, done})
      }
    }
  })
}

/**
 * Returns a new array of goRoutines with the dones removed.
 * Note that as per https://jsperf.com/array-filter-performance,
 * Array.filter isn't as performant.
 */
function clearDones(state) {
  const countDones = state.goRoutines.reduce(
    (total, goRoutine) => { return goRoutine.done ? total + 1 : total },
    0
  )
  // first handle some simple cases first
  if (!countDones) {
    return
  } else if (state.goRoutines.length === countDones) {
    state.goRoutines = []
    state.lastSelectedChannel = {}
    return
  }
  // then return a new array with all the done goRoutines removed
  let len = 0
  state.goRoutes = state.goRoutines.reduce(
    (newGoRoutines, goRoutine, i) => {
      if (!goRoutine.done) {
        newGoRoutines[len++] = goRoutine
      }
      return newGoRoutines
    },
    new Array(state.goRoutines.length - countDones)
  )
  state.lastSelectedChannel = {}
}

function dispatcher(state) {
  processGoRoutines(state)
  clearDones(state)
  // recursively call itself
  runDispatcher(state)
}

/**
 * @param {array[]} state.goRoutines
 * @param {map} state.channelBuffers
 */
export function runDispatcher(state) {
  const {goRoutines} = state
  if (goRoutines.length) {
    setTimeout(() => dispatcher(state), 0)
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';
import Helmet from 'react-helmet';
import { StyleSheet, StyleSheetServer } from 'aphrodite';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './redux/rootReducer';
import HtmlWrapper from './components/HtmlWrapper';
import Frontend from './FrontendApp';
import Editor from './editor/Editor';
import './index.css';

const createApp = (Component, preloadedState = {}) => {
  const store = createStore(rootReducer, preloadedState);
  return (
    <Provider store={store}>
      <Component isDevelopment={process.env.NODE_ENV === 'development'} />
    </Provider>
  );
};

const renderApp = app => ReactDOM.render(app, document.getElementById('root'));

if (typeof document !== 'undefined') {
  if (window.location.pathname.startsWith('/editor')) {
    renderApp(createApp(Editor));
  } else {
    StyleSheet.rehydrate(window.__PRELOADED_STYLES__);
    delete window.__PRELOADED_STYLES__;

    const preloadedState = window.__PRELOADED_STATE__;
    delete window.__PRELOADED_STATE__;

    renderApp(createApp(Frontend, preloadedState));
  }
}

export default (locals, callback) => {
  window.location = {
    pathname: locals.path,
  };

  const preloadedState = {
    page: locals.content[locals.path],
  };

  const {
    html: content,
    css: aphroditeCSS,
  } = StyleSheetServer.renderStatic(() => {
    return ReactDOMServer.renderToString(createApp(Frontend, preloadedState));
  });
  const head = Helmet.rewind();

  const assets = Object.keys(locals.webpackStats.compilation.assets);
  const stylesheets = assets.filter(value => value.match(/\.css$/));
  const scripts = assets.filter(value => value.match(/\.js$/));

  const page = ReactDOMServer.renderToStaticMarkup(
    <HtmlWrapper
      head={head}
      stylesheets={stylesheets}
      scripts={scripts}
      state={preloadedState}
      aphroditeCSS={aphroditeCSS}
    >
      {content}
    </HtmlWrapper>
  );

  callback(null, page);
};
<commit_msg>Use webpack code splitting to include editor code only when needed<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';
import Helmet from 'react-helmet';
import { StyleSheet, StyleSheetServer } from 'aphrodite';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './redux/rootReducer';
import HtmlWrapper from './components/HtmlWrapper';
import Frontend from './FrontendApp';
import './index.css';
const createApp = (Component, preloadedState = {}) => {
  const store = createStore(rootReducer, preloadedState);
  return (
    <Provider store={store}>
      <Component isDevelopment={process.env.NODE_ENV === 'development'} />
    </Provider>
  );
};

const renderApp = app => ReactDOM.render(app, document.getElementById('root'));

if (typeof document !== 'undefined') {
  if (window.location.pathname.startsWith('/editor')) {
    require.ensure(['./editor/Editor'], require => {
      const Editor = require('./editor/Editor').default;
      renderApp(createApp(Editor));
    });
  } else {
    StyleSheet.rehydrate(window.__PRELOADED_STYLES__);
    delete window.__PRELOADED_STYLES__;

    const preloadedState = window.__PRELOADED_STATE__;
    delete window.__PRELOADED_STATE__;

    renderApp(createApp(Frontend, preloadedState));
  }
}

export default (locals, callback) => {
  window.location = {
    pathname: locals.path,
  };

  const preloadedState = {
    page: locals.content[locals.path],
  };

  const {
    html: content,
    css: aphroditeCSS,
  } = StyleSheetServer.renderStatic(() => {
    return ReactDOMServer.renderToString(createApp(Frontend, preloadedState));
  });
  const head = Helmet.rewind();

  const assets = Object.keys(locals.webpackStats.compilation.assets);
  const stylesheets = assets.filter(value => value.match(/\.css$/));
  const scripts = assets.filter(value => value.match(/\.js$/));

  const page = ReactDOMServer.renderToStaticMarkup(
    <HtmlWrapper
      head={head}
      stylesheets={stylesheets}
      scripts={scripts}
      state={preloadedState}
      aphroditeCSS={aphroditeCSS}
    >
      {content}
    </HtmlWrapper>
  );

  callback(null, page);
};
<|endoftext|>


<commit_before>require('list-view/list_item_view');

var get = Ember.get, set = Ember.set,
min = Math.min, max = Math.max, floor = Math.floor,
ceil = Math.ceil;

function addContentArrayObserver() {
  var content = get(this, 'content');
  if (content) {
    content.addArrayObserver(this);
  }
}

function removeAndDestroy(object){
  this.removeObject(object);
  object.destroy();
}

function syncChildViews(){
  Ember.run.once(this, '_syncChildViews');
}

function sortByContentIndex (viewOne, viewTwo){
  return get(viewOne, 'contentIndex') - get(viewTwo, 'contentIndex');
}

function detectListItemViews(childView) {
  return Ember.ListItemView.detectInstance(childView);
}

function notifyMutationListeners() {
  if (Ember.View.notifyMutationListeners) {
    Ember.run.once(Ember.View, 'notifyMutationListeners');
  }
}

var domManager = Ember.create(Ember.ContainerView.proto().domManager);

domManager.prepend = function(view, html) {
  view.$('.ember-list-container').prepend(html);
  notifyMutationListeners();
};

Ember.ListViewMixin = Ember.Mixin.create({
  itemViewClass: Ember.ListItemView,
  classNames: ['ember-list-view'],
  attributeBindings: ['style'],
  domManager: domManager,
  scrollTop: 0,
  _lastEndingIndex: 0,
  paddingCount: 1, // One row for padding

  init: function() {
    this._super();
    addContentArrayObserver.call(this);
    this._syncChildViews();
    this.columnCountDidChange();
  },

  render: function(buffer) {
    buffer.push('
');
    this._super(buffer);
    buffer.push('
');
  },

  style: Ember.computed('height', 'width', function() {
    var height, width, style, css;

    height = get(this, 'height');
    width = get(this, 'width');
    css = get(this, 'css');

    style = '';

    if (height) { style += 'height:' + height + 'px;'; }
    if (width)  { style += 'width:'  + width  + 'px;'; }

    for ( var rule in css ){
      if (css.hasOwnProperty(rule)) {
        style += rule + ':' + css[rule] + ';';
      }
    }

    return style;
  }),
  scrollTo: function(y) {
    throw "must override to perform the visual scroll and effectively delegate to _scrollContentTo";
  },
  _scrollContentTo: function(scrollTop, options) {
    var contentLength, childViews, childViewsLength,
        startingIndex, endingIndex, childView, attrs,
        contentIndex, visibleEndingIndex, maxContentIndex,
        contentIndexEnd;

    options = options || { };

    set(this, 'scrollTop', scrollTop);
    contentLength = get(this, 'content.length');
    maxContentIndex = max(contentLength - 1, 0);
    childViews = get(this, 'listItemViews');
    childViewsLength =  childViews.length;

    startingIndex = this._startingIndex();
    visibleEndingIndex = startingIndex + this._numChildViewsForViewport();

    endingIndex = min(maxContentIndex, visibleEndingIndex);

    if (!options.force && startingIndex === this._lastStartingIndex && endingIndex === this._lastEndingIndex) {
      return;
    }

    contentIndexEnd = min(visibleEndingIndex, startingIndex + childViewsLength);

    for (contentIndex = startingIndex; contentIndex < contentIndexEnd; contentIndex++) {
      childView = childViews[contentIndex % childViewsLength];
      this._reuseChildForContentIndex(childView, contentIndex, options);
    }

    this._lastStartingIndex = startingIndex;
    this._lastEndingIndex = endingIndex;
  },

  childViewsWillSync: Ember.K,
  childViewsDidSync: Ember.K,

  totalHeight: Ember.computed('content.length', 'rowHeight', 'columnCount', function() {
    var contentLength, rowHeight, columnCount;

    contentLength = get(this, 'content.length');
    rowHeight = get(this, 'rowHeight');
    columnCount = get(this, 'columnCount');

    return (ceil(contentLength / columnCount)) * rowHeight;
  }),

  _prepareChildForReuse: function(childView) {
    childView.prepareForReuse();
  },

  _reuseChildForContentIndex: function(childView, contentIndex, options) {
    var content, childsCurrentContentIndex, position;

    content = get(this, 'content');
    childsCurrentContentIndex = get(childView, 'contentIndex');

    options = options || {};
    this._prepareChildForReuse(childView);

    if (childsCurrentContentIndex !== contentIndex || options.force) {
      position = this.positionForIndex(contentIndex);

      set(childView, 'position', position);
      set(childView, 'contentIndex', contentIndex);
      set(childView, 'context', content.objectAt(contentIndex));
    }
  },

  positionForIndex: function(index){
    var elementWidth, width, columnCount, rowHeight, y, x;

    elementWidth = get(this, 'elementWidth') || 1;
    width = get(this, 'width') || 1;
    columnCount = get(this, 'columnCount');
    rowHeight = get(this, 'rowHeight');

    y = (rowHeight * floor(index/columnCount));
    x = (index % columnCount) * elementWidth;

    return {
      y: y,
      x: x
    };
  },

  _childViewCount: function() {
    var contentLength, childViewCountForHeight;

    contentLength = get(this, 'content.length');
    childViewCountForHeight = this._numChildViewsForViewport();

    return min(contentLength, childViewCountForHeight);
  },

  columnCount: Ember.computed('width', 'elementWidth', function() {
    var elementWidth, width, count;

    elementWidth = get(this, 'elementWidth');
    width = get(this, 'width');

    if (elementWidth) {
      count = floor(width / elementWidth);
    } else {
      count = 1;
    }

    return count;
  }),

  columnCountDidChange: Ember.observer(function(){
    var ratio, currentScrollTop, proposedScrollTop, maxScrollTop,
        scrollTop, lastColumnCount, newColumnCount;

    lastColumnCount = this._lastColumnCount;

    currentScrollTop = get(this, 'scrollTop');
    newColumnCount = get(this, 'columnCount');
    maxScrollTop = get(this, 'maxScrollTop');

    this._lastColumnCount = newColumnCount;

    if (lastColumnCount) {
      ratio = (lastColumnCount / newColumnCount);
      proposedScrollTop = currentScrollTop * ratio;
      scrollTop = min(maxScrollTop, proposedScrollTop);
      set(this, 'scrollTop', scrollTop);
    }
  }, 'columnCount'),

  maxScrollTop: Ember.computed('height', 'totalHeight', function(){
    var totalHeight, viewportHeight;

    totalHeight = get(this, 'totalHeight'),
    viewportHeight = get(this, 'height');

    return max(0, totalHeight - viewportHeight);
  }),

  _numChildViewsForViewport: function() {
    var height, rowHeight, paddingCount, columnCount;

    height = get(this, 'height');
    rowHeight = get(this, 'rowHeight');
    paddingCount = get(this, 'paddingCount');
    columnCount = get(this, 'columnCount');

    return (ceil(height / rowHeight) * columnCount) + (paddingCount * columnCount);
  },

  _startingIndex: function() {
    var scrollTop, rowHeight, columnCount, calculatedStartingIndex,
        contentLength, largestStartingIndex;

    contentLength = get(this, 'content.length');
    scrollTop = get(this, 'scrollTop');
    rowHeight = get(this, 'rowHeight');
    columnCount = get(this, 'columnCount');

    calculatedStartingIndex = floor(scrollTop / rowHeight) * columnCount;

    largestStartingIndex = max(contentLength - 1, 0);

    return min(calculatedStartingIndex, largestStartingIndex);
  },

  contentWillChange: Ember.beforeObserver(function() {
    var content;

    content = get(this, 'content');

    if (content) {
      content.removeArrayObserver(this);
    }
  }, 'content'),

  contentDidChange: Ember.observer(function() {
    addContentArrayObserver.call(this);
    syncChildViews.call(this);
  }, 'content'),

  needsSyncChildViews: Ember.observer(syncChildViews, 'height', 'width', 'columnCount'),

  _addItemView: function(contentIndex){
    var itemViewClass, childView;

    itemViewClass = get(this, 'itemViewClass');
    childView = itemViewClass.create();

    this._reuseChildForContentIndex(childView, contentIndex);

    this.pushObject(childView);
   },

  /**
   @private

   Intelligently manages the number of childviews.

   @method _syncChildViews
   **/
  _syncChildViews: function(){
    var itemViewClass, startingIndex, childViewCount,
        endingIndex, numberOfChildViews, numberOfChildViewsNeeded,
        childViews, count, delta, index, childViewsLength, contentIndex;

    if (get(this, 'isDestroyed') || get(this, 'isDestroying')) {
      return;
    }

    this.childViewsWillSync();

    childViewCount = this._childViewCount();
    childViews = this.positionOrderedChildViews();

    startingIndex = this._startingIndex();
    endingIndex = startingIndex + childViewCount;

    numberOfChildViewsNeeded = childViewCount;
    numberOfChildViews = childViews.length;

    delta = numberOfChildViewsNeeded - numberOfChildViews;

    if (delta === 0) {
      // no change
    } else if (delta > 0) { // more views are needed
      contentIndex = this._lastEndingIndex;

      for (count = 0; count < delta; count++, contentIndex++) {
        this._addItemView(contentIndex);
      }

    } else { // less views are needed
      childViews.
        splice(numberOfChildViewsNeeded, numberOfChildViews).
        forEach(removeAndDestroy, this);
    }

    this._scrollContentTo(get(this, 'scrollTop'), { force: true });

    this._lastStartingIndex = startingIndex;
    this._lastEndingIndex   = this._lastEndingIndex + delta;

    this.childViewsDidSync();
  },

  listItemViews: Ember.computed('[]', function(){
    return this.filter(detectListItemViews);
  }),

  positionOrderedChildViews: function() {
    return get(this, 'listItemViews').sort(sortByContentIndex);
  },

  arrayWillChange: Ember.K,

  // TODO: refactor
  arrayDidChange: function(content, start, removedCount, addedCount) {
    var index, contentIndex;

    if (this.state === 'inDOM') {
      // ignore if all changes are out of the visible change
      if( start >= this._lastStartingIndex || start < this._lastEndingIndex) {
        index = 0;
        // ignore all changes not in the visible range
        this.positionOrderedChildViews().
          slice(start, start + addedCount).
          forEach(function(childView){
            contentIndex = this._lastStartingIndex + index;
            this._reuseChildForContentIndex(childView, contentIndex, { force: true });
            index++;
          }, this);
      }

      syncChildViews.call(this);
    }
  }
});
<commit_msg>ember-list-container now has a dynamic width<commit_after>require('list-view/list_item_view');

var get = Ember.get, set = Ember.set,
min = Math.min, max = Math.max, floor = Math.floor,
ceil = Math.ceil;

function addContentArrayObserver() {
  var content = get(this, 'content');
  if (content) {
    content.addArrayObserver(this);
  }
}

function removeAndDestroy(object){
  this.removeObject(object);
  object.destroy();
}

function syncChildViews(){
  Ember.run.once(this, '_syncChildViews');
}

function sortByContentIndex (viewOne, viewTwo){
  return get(viewOne, 'contentIndex') - get(viewTwo, 'contentIndex');
}

function detectListItemViews(childView) {
  return Ember.ListItemView.detectInstance(childView);
}

function notifyMutationListeners() {
  if (Ember.View.notifyMutationListeners) {
    Ember.run.once(Ember.View, 'notifyMutationListeners');
  }
}

var domManager = Ember.create(Ember.ContainerView.proto().domManager);

domManager.prepend = function(view, html) {
  view.$('.ember-list-container').prepend(html);
  notifyMutationListeners();
};

function syncListContainerWidth(){
  var elementWidth, columnCount, containerWidth, element;

  elementWidth = get(this, 'elementWidth');
  columnCount = get(this, 'columnCount');
  containerWidth = elementWidth * columnCount;
  element = this.$('.ember-list-container');

  if (containerWidth && element) {
    element.css('width', containerWidth);
  }
}

Ember.ListViewMixin = Ember.Mixin.create({
  itemViewClass: Ember.ListItemView,
  classNames: ['ember-list-view'],
  attributeBindings: ['style'],
  domManager: domManager,
  scrollTop: 0,
  _lastEndingIndex: 0,
  paddingCount: 1, // One row for padding

  init: function() {
    this._super();
    addContentArrayObserver.call(this);
    this._syncChildViews();
    this.columnCountDidChange();
    this.on('didInsertElement', syncListContainerWidth);
  },

  render: function(buffer) {
    buffer.push('
');
    this._super(buffer);
    buffer.push('
');
  },

  style: Ember.computed('height', 'width', function() {
    var height, width, style, css;

    height = get(this, 'height');
    width = get(this, 'width');
    css = get(this, 'css');

    style = '';

    if (height) { style += 'height:' + height + 'px;'; }
    if (width)  { style += 'width:'  + width  + 'px;'; }

    for ( var rule in css ){
      if (css.hasOwnProperty(rule)) {
        style += rule + ':' + css[rule] + ';';
      }
    }

    return style;
  }),
  scrollTo: function(y) {
    throw "must override to perform the visual scroll and effectively delegate to _scrollContentTo";
  },
  _scrollContentTo: function(scrollTop, options) {
    var contentLength, childViews, childViewsLength,
        startingIndex, endingIndex, childView, attrs,
        contentIndex, visibleEndingIndex, maxContentIndex,
        contentIndexEnd;

    options = options || { };

    set(this, 'scrollTop', scrollTop);
    contentLength = get(this, 'content.length');
    maxContentIndex = max(contentLength - 1, 0);
    childViews = get(this, 'listItemViews');
    childViewsLength =  childViews.length;

    startingIndex = this._startingIndex();
    visibleEndingIndex = startingIndex + this._numChildViewsForViewport();

    endingIndex = min(maxContentIndex, visibleEndingIndex);

    if (!options.force && startingIndex === this._lastStartingIndex && endingIndex === this._lastEndingIndex) {
      return;
    }

    contentIndexEnd = min(visibleEndingIndex, startingIndex + childViewsLength);

    for (contentIndex = startingIndex; contentIndex < contentIndexEnd; contentIndex++) {
      childView = childViews[contentIndex % childViewsLength];
      this._reuseChildForContentIndex(childView, contentIndex, options);
    }

    this._lastStartingIndex = startingIndex;
    this._lastEndingIndex = endingIndex;
  },

  childViewsWillSync: Ember.K,
  childViewsDidSync: Ember.K,

  totalHeight: Ember.computed('content.length', 'rowHeight', 'columnCount', function() {
    var contentLength, rowHeight, columnCount;

    contentLength = get(this, 'content.length');
    rowHeight = get(this, 'rowHeight');
    columnCount = get(this, 'columnCount');

    return (ceil(contentLength / columnCount)) * rowHeight;
  }),

  _prepareChildForReuse: function(childView) {
    childView.prepareForReuse();
  },

  _reuseChildForContentIndex: function(childView, contentIndex, options) {
    var content, childsCurrentContentIndex, position;

    content = get(this, 'content');
    childsCurrentContentIndex = get(childView, 'contentIndex');

    options = options || {};
    this._prepareChildForReuse(childView);

    if (childsCurrentContentIndex !== contentIndex || options.force) {
      position = this.positionForIndex(contentIndex);

      set(childView, 'position', position);
      set(childView, 'contentIndex', contentIndex);
      set(childView, 'context', content.objectAt(contentIndex));
    }
  },

  positionForIndex: function(index){
    var elementWidth, width, columnCount, rowHeight, y, x;

    elementWidth = get(this, 'elementWidth') || 1;
    width = get(this, 'width') || 1;
    columnCount = get(this, 'columnCount');
    rowHeight = get(this, 'rowHeight');

    y = (rowHeight * floor(index/columnCount));
    x = (index % columnCount) * elementWidth;

    return {
      y: y,
      x: x
    };
  },

  _childViewCount: function() {
    var contentLength, childViewCountForHeight;

    contentLength = get(this, 'content.length');
    childViewCountForHeight = this._numChildViewsForViewport();

    return min(contentLength, childViewCountForHeight);
  },

  columnCount: Ember.computed('width', 'elementWidth', function() {
    var elementWidth, width, count;

    elementWidth = get(this, 'elementWidth');
    width = get(this, 'width');

    if (elementWidth) {
      count = floor(width / elementWidth);
    } else {
      count = 1;
    }

    return count;
  }),

  columnCountDidChange: Ember.observer(function(){
    var ratio, currentScrollTop, proposedScrollTop, maxScrollTop,
        scrollTop, lastColumnCount, newColumnCount;

    lastColumnCount = this._lastColumnCount;

    currentScrollTop = get(this, 'scrollTop');
    newColumnCount = get(this, 'columnCount');
    maxScrollTop = get(this, 'maxScrollTop');

    this._lastColumnCount = newColumnCount;

    if (lastColumnCount) {
      ratio = (lastColumnCount / newColumnCount);
      proposedScrollTop = currentScrollTop * ratio;
      scrollTop = min(maxScrollTop, proposedScrollTop);
      set(this, 'scrollTop', scrollTop);
    }

    if (arguments.length > 0) {
      // invoked by observer
      Ember.run.schedule('afterRender', this, syncListContainerWidth);

    }
  }, 'columnCount'),

  maxScrollTop: Ember.computed('height', 'totalHeight', function(){
    var totalHeight, viewportHeight;

    totalHeight = get(this, 'totalHeight'),
    viewportHeight = get(this, 'height');

    return max(0, totalHeight - viewportHeight);
  }),

  _numChildViewsForViewport: function() {
    var height, rowHeight, paddingCount, columnCount;

    height = get(this, 'height');
    rowHeight = get(this, 'rowHeight');
    paddingCount = get(this, 'paddingCount');
    columnCount = get(this, 'columnCount');

    return (ceil(height / rowHeight) * columnCount) + (paddingCount * columnCount);
  },

  _startingIndex: function() {
    var scrollTop, rowHeight, columnCount, calculatedStartingIndex,
        contentLength, largestStartingIndex;

    contentLength = get(this, 'content.length');
    scrollTop = get(this, 'scrollTop');
    rowHeight = get(this, 'rowHeight');
    columnCount = get(this, 'columnCount');

    calculatedStartingIndex = floor(scrollTop / rowHeight) * columnCount;

    largestStartingIndex = max(contentLength - 1, 0);

    return min(calculatedStartingIndex, largestStartingIndex);
  },

  contentWillChange: Ember.beforeObserver(function() {
    var content;

    content = get(this, 'content');

    if (content) {
      content.removeArrayObserver(this);
    }
  }, 'content'),

  contentDidChange: Ember.observer(function() {
    addContentArrayObserver.call(this);
    syncChildViews.call(this);
  }, 'content'),

  needsSyncChildViews: Ember.observer(syncChildViews, 'height', 'width', 'columnCount'),

  _addItemView: function(contentIndex){
    var itemViewClass, childView;

    itemViewClass = get(this, 'itemViewClass');
    childView = itemViewClass.create();

    this._reuseChildForContentIndex(childView, contentIndex);

    this.pushObject(childView);
   },

  /**
   @private

   Intelligently manages the number of childviews.

   @method _syncChildViews
   **/
  _syncChildViews: function(){
    var itemViewClass, startingIndex, childViewCount,
        endingIndex, numberOfChildViews, numberOfChildViewsNeeded,
        childViews, count, delta, index, childViewsLength, contentIndex;

    if (get(this, 'isDestroyed') || get(this, 'isDestroying')) {
      return;
    }

    this.childViewsWillSync();

    childViewCount = this._childViewCount();
    childViews = this.positionOrderedChildViews();

    startingIndex = this._startingIndex();
    endingIndex = startingIndex + childViewCount;

    numberOfChildViewsNeeded = childViewCount;
    numberOfChildViews = childViews.length;

    delta = numberOfChildViewsNeeded - numberOfChildViews;

    if (delta === 0) {
      // no change
    } else if (delta > 0) { // more views are needed
      contentIndex = this._lastEndingIndex;

      for (count = 0; count < delta; count++, contentIndex++) {
        this._addItemView(contentIndex);
      }

    } else { // less views are needed
      childViews.
        splice(numberOfChildViewsNeeded, numberOfChildViews).
        forEach(removeAndDestroy, this);
    }

    this._scrollContentTo(get(this, 'scrollTop'), { force: true });

    this._lastStartingIndex = startingIndex;
    this._lastEndingIndex   = this._lastEndingIndex + delta;

    this.childViewsDidSync();
  },

  listItemViews: Ember.computed('[]', function(){
    return this.filter(detectListItemViews);
  }),

  positionOrderedChildViews: function() {
    return get(this, 'listItemViews').sort(sortByContentIndex);
  },

  arrayWillChange: Ember.K,

  // TODO: refactor
  arrayDidChange: function(content, start, removedCount, addedCount) {
    var index, contentIndex;

    if (this.state === 'inDOM') {
      // ignore if all changes are out of the visible change
      if( start >= this._lastStartingIndex || start < this._lastEndingIndex) {
        index = 0;
        // ignore all changes not in the visible range
        this.positionOrderedChildViews().
          slice(start, start + addedCount).
          forEach(function(childView){
            contentIndex = this._lastStartingIndex + index;
            this._reuseChildForContentIndex(childView, contentIndex, { force: true });
            index++;
          }, this);
      }

      syncChildViews.call(this);
    }
  }
});
<|endoftext|>


<commit_before>import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
import Modal from '../Modal';
import Backdrop from '../Backdrop';
import Fade from '../Fade';
import { duration } from '../styles/transitions';
import Paper from '../Paper';

export const styles = (theme) => ({
  /* Styles applied to the root element. */
  root: {
    '@media print': {
      // Use !important to override the Modal inline-style.
      position: 'absolute !important',
    },
  },
  /* Styles applied to the container element if `scroll="paper"`. */
  scrollPaper: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  /* Styles applied to the container element if `scroll="body"`. */
  scrollBody: {
    overflowY: 'auto',
    overflowX: 'hidden',
    textAlign: 'center',
    '&:after': {
      content: '""',
      display: 'inline-block',
      verticalAlign: 'middle',
      height: '100%',
      width: '0',
    },
  },
  /* Styles applied to the container element. */
  container: {
    height: '100%',
    '@media print': {
      height: 'auto',
    },
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0,
  },
  /* Styles applied to the `Paper` component. */
  paper: {
    margin: 32,
    position: 'relative',
    overflowY: 'auto', // Fix IE 11 issue, to remove at some point.
    '@media print': {
      overflowY: 'visible',
      boxShadow: 'none',
    },
  },
  /* Styles applied to the `Paper` component if `scroll="paper"`. */
  paperScrollPaper: {
    display: 'flex',
    flexDirection: 'column',
    maxHeight: 'calc(100% - 64px)',
  },
  /* Styles applied to the `Paper` component if `scroll="body"`. */
  paperScrollBody: {
    display: 'inline-block',
    verticalAlign: 'middle',
    textAlign: 'left', // 'initial' doesn't work on IE 11
  },
  /* Styles applied to the `Paper` component if `maxWidth=false`. */
  paperWidthFalse: {
    maxWidth: 'calc(100% - 64px)',
  },
  /* Styles applied to the `Paper` component if `maxWidth="xs"`. */
  paperWidthXs: {
    maxWidth: Math.max(theme.breakpoints.values.xs, 444),
    '&$paperScrollBody': {
      [theme.breakpoints.down(Math.max(theme.breakpoints.values.xs, 444) + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="sm"`. */
  paperWidthSm: {
    maxWidth: theme.breakpoints.values.sm,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.sm + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="md"`. */
  paperWidthMd: {
    maxWidth: theme.breakpoints.values.md,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.md + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="lg"`. */
  paperWidthLg: {
    maxWidth: theme.breakpoints.values.lg,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.lg + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="xl"`. */
  paperWidthXl: {
    maxWidth: theme.breakpoints.values.xl,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.xl + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `fullWidth={true}`. */
  paperFullWidth: {
    width: 'calc(100% - 64px)',
  },
  /* Styles applied to the `Paper` component if `fullScreen={true}`. */
  paperFullScreen: {
    margin: 0,
    width: '100%',
    maxWidth: '100%',
    height: '100%',
    maxHeight: 'none',
    borderRadius: 0,
    '&$paperScrollBody': {
      margin: 0,
      maxWidth: '100%',
    },
  },
});

const defaultTransitionDuration = { enter: duration.enteringScreen, exit: duration.leavingScreen };
/**
 * Dialogs are overlaid modal paper based components with a backdrop.
 */
const Dialog = React.forwardRef(function Dialog(props, ref) {
  const {
    BackdropProps,
    children,
    classes,
    className,
    disableBackdropClick = false,
    disableEscapeKeyDown = false,
    fullScreen = false,
    fullWidth = false,
    maxWidth = 'sm',
    onBackdropClick,
    onClose,
    onEscapeKeyDown,
    open,
    PaperComponent = Paper,
    PaperProps = {},
    scroll = 'paper',
    TransitionComponent = Fade,
    transitionDuration = defaultTransitionDuration,
    TransitionProps,
    'aria-describedby': ariaDescribedby,
    'aria-labelledby': ariaLabelledby,
    ...other
  } = props;

  const mouseDownTarget = React.useRef();
  const handleMouseDown = (event) => {
    mouseDownTarget.current = event.currentTarget;
  };
  const handleBackdropClick = (event) => {
    // Make sure the event starts and ends on the same DOM element.
    if (event.target !== mouseDownTarget.current) {
      return;
    }

    mouseDownTarget.current = null;

    if (onBackdropClick) {
      onBackdropClick(event);
    }

    if (!disableBackdropClick && onClose) {
      onClose(event, 'backdropClick');
    }
  };

  return (
    <Modal
      className={clsx(classes.root, className)}
      BackdropComponent={Backdrop}
      BackdropProps={{
        transitionDuration,
        ...BackdropProps,
      }}
      closeAfterTransition
      disableBackdropClick={disableBackdropClick}
      disableEscapeKeyDown={disableEscapeKeyDown}
      onEscapeKeyDown={onEscapeKeyDown}
      onClose={onClose}
      open={open}
      ref={ref}
      onClick={handleBackdropClick}
      {...other}
    >
      <TransitionComponent
        appear
        in={open}
        timeout={transitionDuration}
        role="none presentation"
        {...TransitionProps}
      >
        {/* roles are applied via cloneElement from TransitionComponent */}
        {/* roles needs to be applied on the immediate child of Modal or it'll inject one */}
        {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
        <div
          className={clsx(classes.container, classes[`scroll${capitalize(scroll)}`])}
          onMouseDown={handleMouseDown}
          data-mui-test="FakeBackdrop"
        >
          <PaperComponent
            elevation={24}
            role="dialog"
            aria-describedby={ariaDescribedby}
            aria-labelledby={ariaLabelledby}
            {...PaperProps}
            className={clsx(
              classes.paper,
              classes[`paperScroll${capitalize(scroll)}`],
              classes[`paperWidth${capitalize(String(maxWidth))}`],
              {
                [classes.paperFullScreen]: fullScreen,
                [classes.paperFullWidth]: fullWidth,
              },
              PaperProps.className,
            )}
          >
            {children}
          </PaperComponent>
        </div>
      </TransitionComponent>
    </Modal>
  );
});

Dialog.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The id(s) of the element(s) that describe the dialog.
   */
  'aria-describedby': PropTypes.string,
  /**
   * The id(s) of the element(s) that label the dialog.
   */
  'aria-labelledby': PropTypes.string,
  /**
   * @ignore
   */
  BackdropProps: PropTypes.object,
  /**
   * Dialog children, usually the included sub-components.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, clicking the backdrop will not fire the `onClose` callback.
   */
  disableBackdropClick: PropTypes.bool,
  /**
   * If `true`, hitting escape will not fire the `onClose` callback.
   */
  disableEscapeKeyDown: PropTypes.bool,
  /**
   * If `true`, the dialog will be full-screen
   */
  fullScreen: PropTypes.bool,
  /**
   * If `true`, the dialog stretches to `maxWidth`.
   *
   * Notice that the dialog width grow is limited by the default margin.
   */
  fullWidth: PropTypes.bool,
  /**
   * Determine the max-width of the dialog.
   * The dialog width grows with the size of the screen.
   * Set to `false` to disable `maxWidth`.
   */
  maxWidth: PropTypes.oneOf(['lg', 'md', 'sm', 'xl', 'xs', false]),
  /**
   * Callback fired when the backdrop is clicked.
   */
  onBackdropClick: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   *
   * @param {object} event The event source of the callback.
   * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
   */
  onClose: PropTypes.func,
  /**
   * Callback fired when the escape key is pressed,
   * `disableKeyboard` is false and the modal is in focus.
   */
  onEscapeKeyDown: PropTypes.func,
  /**
   * If `true`, the Dialog is open.
   */
  open: PropTypes.bool.isRequired,
  /**
   * The component used to render the body of the dialog.
   */
  PaperComponent: PropTypes.elementType,
  /**
   * Props applied to the [`Paper`](/api/paper/) element.
   */
  PaperProps: PropTypes.object,
  /**
   * Determine the container for scrolling the dialog.
   */
  scroll: PropTypes.oneOf(['body', 'paper']),
  /**
   * The component used for the transition.
   * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   */
  TransitionComponent: PropTypes.elementType,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   */
  transitionDuration: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.shape({
      appear: PropTypes.number,
      enter: PropTypes.number,
      exit: PropTypes.number,
    }),
  ]),
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component.
   */
  TransitionProps: PropTypes.object,
};

export default withStyles(styles, { name: 'MuiDialog' })(Dialog);
<commit_msg>[Dialog] Fix unexpected close when releasing click on backdrop (#22310)<commit_after>import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
import Modal from '../Modal';
import Backdrop from '../Backdrop';
import Fade from '../Fade';
import { duration } from '../styles/transitions';
import Paper from '../Paper';

export const styles = (theme) => ({
  /* Styles applied to the root element. */
  root: {
    '@media print': {
      // Use !important to override the Modal inline-style.
      position: 'absolute !important',
    },
  },
  /* Styles applied to the container element if `scroll="paper"`. */
  scrollPaper: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  /* Styles applied to the container element if `scroll="body"`. */
  scrollBody: {
    overflowY: 'auto',
    overflowX: 'hidden',
    textAlign: 'center',
    '&:after': {
      content: '""',
      display: 'inline-block',
      verticalAlign: 'middle',
      height: '100%',
      width: '0',
    },
  },
  /* Styles applied to the container element. */
  container: {
    height: '100%',
    '@media print': {
      height: 'auto',
    },
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0,
  },
  /* Styles applied to the `Paper` component. */
  paper: {
    margin: 32,
    position: 'relative',
    overflowY: 'auto', // Fix IE 11 issue, to remove at some point.
    '@media print': {
      overflowY: 'visible',
      boxShadow: 'none',
    },
  },
  /* Styles applied to the `Paper` component if `scroll="paper"`. */
  paperScrollPaper: {
    display: 'flex',
    flexDirection: 'column',
    maxHeight: 'calc(100% - 64px)',
  },
  /* Styles applied to the `Paper` component if `scroll="body"`. */
  paperScrollBody: {
    display: 'inline-block',
    verticalAlign: 'middle',
    textAlign: 'left', // 'initial' doesn't work on IE 11
  },
  /* Styles applied to the `Paper` component if `maxWidth=false`. */
  paperWidthFalse: {
    maxWidth: 'calc(100% - 64px)',
  },
  /* Styles applied to the `Paper` component if `maxWidth="xs"`. */
  paperWidthXs: {
    maxWidth: Math.max(theme.breakpoints.values.xs, 444),
    '&$paperScrollBody': {
      [theme.breakpoints.down(Math.max(theme.breakpoints.values.xs, 444) + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="sm"`. */
  paperWidthSm: {
    maxWidth: theme.breakpoints.values.sm,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.sm + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="md"`. */
  paperWidthMd: {
    maxWidth: theme.breakpoints.values.md,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.md + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="lg"`. */
  paperWidthLg: {
    maxWidth: theme.breakpoints.values.lg,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.lg + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `maxWidth="xl"`. */
  paperWidthXl: {
    maxWidth: theme.breakpoints.values.xl,
    '&$paperScrollBody': {
      [theme.breakpoints.down(theme.breakpoints.values.xl + 32 * 2)]: {
        maxWidth: 'calc(100% - 64px)',
      },
    },
  },
  /* Styles applied to the `Paper` component if `fullWidth={true}`. */
  paperFullWidth: {
    width: 'calc(100% - 64px)',
  },
  /* Styles applied to the `Paper` component if `fullScreen={true}`. */
  paperFullScreen: {
    margin: 0,
    width: '100%',
    maxWidth: '100%',
    height: '100%',
    maxHeight: 'none',
    borderRadius: 0,
    '&$paperScrollBody': {
      margin: 0,
      maxWidth: '100%',
    },
  },
});

const defaultTransitionDuration = { enter: duration.enteringScreen, exit: duration.leavingScreen };
/**
 * Dialogs are overlaid modal paper based components with a backdrop.
 */
const Dialog = React.forwardRef(function Dialog(props, ref) {
  const {
    BackdropProps,
    children,
    classes,
    className,
    disableBackdropClick = false,
    disableEscapeKeyDown = false,
    fullScreen = false,
    fullWidth = false,
    maxWidth = 'sm',
    onBackdropClick,
    onClose,
    onEscapeKeyDown,
    open,
    PaperComponent = Paper,
    PaperProps = {},
    scroll = 'paper',
    TransitionComponent = Fade,
    transitionDuration = defaultTransitionDuration,
    TransitionProps,
    'aria-describedby': ariaDescribedby,
    'aria-labelledby': ariaLabelledby,
    ...other
  } = props;

  const backdropClick = React.useRef();
  const handleMouseDown = (event) => {
    // We don't want to close the dialog when clicking the dialog content.
    // Make sure the event starts and ends on the same DOM element.
    backdropClick.current = event.target === event.currentTarget;
  };
  const handleBackdropClick = (event) => {
    // Ignore the events not coming from the "backdrop".
    if (!backdropClick.current) {
      return;
    }

    backdropClick.current = null;

    if (onBackdropClick) {
      onBackdropClick(event);
    }

    if (!disableBackdropClick && onClose) {
      onClose(event, 'backdropClick');
    }
  };

  return (
    <Modal
      className={clsx(classes.root, className)}
      BackdropComponent={Backdrop}
      BackdropProps={{
        transitionDuration,
        ...BackdropProps,
      }}
      closeAfterTransition
      disableBackdropClick={disableBackdropClick}
      disableEscapeKeyDown={disableEscapeKeyDown}
      onEscapeKeyDown={onEscapeKeyDown}
      onClose={onClose}
      open={open}
      ref={ref}
      onClick={handleBackdropClick}
      {...other}
    >
      <TransitionComponent
        appear
        in={open}
        timeout={transitionDuration}
        role="none presentation"
        {...TransitionProps}
      >
        {/* roles are applied via cloneElement from TransitionComponent */}
        {/* roles needs to be applied on the immediate child of Modal or it'll inject one */}
        {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
        <div
          className={clsx(classes.container, classes[`scroll${capitalize(scroll)}`])}
          onMouseDown={handleMouseDown}
          data-mui-test="FakeBackdrop"
        >
          <PaperComponent
            elevation={24}
            role="dialog"
            aria-describedby={ariaDescribedby}
            aria-labelledby={ariaLabelledby}
            {...PaperProps}
            className={clsx(
              classes.paper,
              classes[`paperScroll${capitalize(scroll)}`],
              classes[`paperWidth${capitalize(String(maxWidth))}`],
              {
                [classes.paperFullScreen]: fullScreen,
                [classes.paperFullWidth]: fullWidth,
              },
              PaperProps.className,
            )}
          >
            {children}
          </PaperComponent>
        </div>
      </TransitionComponent>
    </Modal>
  );
});

Dialog.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The id(s) of the element(s) that describe the dialog.
   */
  'aria-describedby': PropTypes.string,
  /**
   * The id(s) of the element(s) that label the dialog.
   */
  'aria-labelledby': PropTypes.string,
  /**
   * @ignore
   */
  BackdropProps: PropTypes.object,
  /**
   * Dialog children, usually the included sub-components.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, clicking the backdrop will not fire the `onClose` callback.
   */
  disableBackdropClick: PropTypes.bool,
  /**
   * If `true`, hitting escape will not fire the `onClose` callback.
   */
  disableEscapeKeyDown: PropTypes.bool,
  /**
   * If `true`, the dialog will be full-screen
   */
  fullScreen: PropTypes.bool,
  /**
   * If `true`, the dialog stretches to `maxWidth`.
   *
   * Notice that the dialog width grow is limited by the default margin.
   */
  fullWidth: PropTypes.bool,
  /**
   * Determine the max-width of the dialog.
   * The dialog width grows with the size of the screen.
   * Set to `false` to disable `maxWidth`.
   */
  maxWidth: PropTypes.oneOf(['lg', 'md', 'sm', 'xl', 'xs', false]),
  /**
   * Callback fired when the backdrop is clicked.
   */
  onBackdropClick: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   *
   * @param {object} event The event source of the callback.
   * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
   */
  onClose: PropTypes.func,
  /**
   * Callback fired when the escape key is pressed,
   * `disableKeyboard` is false and the modal is in focus.
   */
  onEscapeKeyDown: PropTypes.func,
  /**
   * If `true`, the Dialog is open.
   */
  open: PropTypes.bool.isRequired,
  /**
   * The component used to render the body of the dialog.
   */
  PaperComponent: PropTypes.elementType,
  /**
   * Props applied to the [`Paper`](/api/paper/) element.
   */
  PaperProps: PropTypes.object,
  /**
   * Determine the container for scrolling the dialog.
   */
  scroll: PropTypes.oneOf(['body', 'paper']),
  /**
   * The component used for the transition.
   * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   */
  TransitionComponent: PropTypes.elementType,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   */
  transitionDuration: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.shape({
      appear: PropTypes.number,
      enter: PropTypes.number,
      exit: PropTypes.number,
    }),
  ]),
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component.
   */
  TransitionProps: PropTypes.object,
};

export default withStyles(styles, { name: 'MuiDialog' })(Dialog);
<|endoftext|>