<commit_before>'use strict';

var fs = require('fs'),
    assert = require('assert'),
    path = require('path'),
    rc = require('betterc'),
    Promise = require('pinkie-promise'),
    flatten = require('lodash.flatten'),
    merge = require('./lib/merge'),
    resolveSets = require('./lib/resolve-sets'),

    basePlugins = [require('./plugins/resolve-level')];

/**
 * Constructor
 * @param {Object} [options] object
 * @param {String} [options.name='bem'] - config filename.
 * @param {String} [options.cwd=process.cwd()] project root directory.
 * @param {Object} [options.defaults={}] use this object as fallback for found configs
 * @param {String} [options.pathToConfig] custom path to config on FS via command line argument `--config`
 * @constructor
 */
function BemConfig(options) {
    this._options = options || {};
    // TODO: use cwd for resolver
    this._options.cwd || (this._options.cwd = process.cwd());
    // TODO: use cache
    // this._cache = {};
}

/**
 * Returns all found configs
 *
 * @param {boolean} [isSync=false] - flag to resolve configs synchronously
 * @returns {Promise|Array}
 */
BemConfig.prototype.configs = function(isSync) {
    var options = this._options,
        cwd = options.cwd,
        rcOpts = {
            defaults: options.defaults && JSON.parse(JSON.stringify(options.defaults)),
            cwd: cwd,
            fsRoot: options.fsRoot,
            fsHome: options.fsHome,
            name: options.name || 'bem',
            extendBy: options.extendBy
        };

    if (options.pathToConfig) {
        rcOpts.argv = { config: options.pathToConfig };
    }

    var plugins = [].concat(basePlugins, options.plugins || []);

    if (isSync) {
        var configs = doSomeMagicProcedure(this._configs || (this._configs = rc.sync(rcOpts)));

        this._root = getConfigsRootDir(configs);

        return plugins.reduce(function(acc, plugin) {
            return acc.map(function(config) {
                return plugin(config, acc, options);
            });
        }, configs);
    }

    var _this = this,
        _thisConfigs = this._configs || rc(rcOpts).then(function(cfgs) { _this._configs = cfgs; return cfgs; });

    return Promise.resolve(_thisConfigs).then(function(cfgs) {
        doSomeMagicProcedure(cfgs);

        _this._root = getConfigsRootDir(cfgs);

        return plugins.reduce(
            function(cfgsPromise, plugin) {
                return cfgsPromise.then(function(configs_) {
                    return Promise.all(configs_.map(function(config) {
                        return new Promise(function(resolve) {
                            plugin(config, configs_, options, resolve);
                        });
                    }));
                });
            },
            Promise.resolve(cfgs));
    });
};

/**
 * Returns project root
 * @returns {Promise}
 */
BemConfig.prototype.root = function() {
    if (this._root) {
        return Promise.resolve(this._root);
    }

    var _this = this;
    return this.configs().then(function() {
        return _this._root;
    });
};

/**
 * Returns merged config
 * @returns {Promise}
 */
BemConfig.prototype.get = function() {
    return this.configs().then(function(configs) {
        return merge(configs);
    });
};

/**
 * Resolves config for given level
 * @param {String} pathToLevel - level path
 * @returns {Promise}
 */
BemConfig.prototype.level = function(pathToLevel) {
    var _this = this;

    return this.configs()
        .then(function(configs) {
            return getLevelByConfigs(
                pathToLevel,
                _this._options,
                configs,
                _this._root);
        });
};

/**
 * Returns config for given library
 * @param {String} libName - library name
 * @returns {Promise}
 */
BemConfig.prototype.library = function(libName) {
    return this.get()
        .then(function(config) {
            var libs = config.libs,
                lib = libs && libs[libName];

            if (lib !== undefined && typeof lib !== 'object') {
                return Promise.reject('Invalid `libs` format');
            }

            var cwd = lib && lib.path || path.resolve('node_modules', libName);

            return new Promise(function(resolve, reject) {
                fs.exists(cwd, function(doesExist) {
                    if (!doesExist) {
                        return reject('Library ' + libName + ' was not found at ' + cwd);
                    }

                    resolve(cwd);
                })
            });
        })
        .then(cwd => new BemConfig({ cwd }));
};

/**
 * Returns map of settings for each of level
 * @returns {Promise}
 */
BemConfig.prototype.levelMap = function() {
    var _this = this;

    return this.get().then(function(config) {
        var projectLevels = config.levels || [],
            libNames = config.libs ? Object.keys(config.libs) : [];

        return Promise.all(libNames.map(function(libName) {
            return _this.library(libName).then(function(bemLibConf) {
                return bemLibConf.get().then(function(libConfig) {
                    return libConfig.levels;
                });
            });
        })).then(function(libLevels) {
            var allLevels = [].concat.apply([], libLevels).concat(projectLevels);

            return allLevels.reduce((res, lvl) => {
                res[lvl.path] = merge(res[lvl.path] || {}, lvl);
                return res;
            }, {});
        });
    });
};

BemConfig.prototype.levels = function(setName) {
    var _this = this;

    return this.get().then(function(config) {
        var levels = config.levels || [],
            sets = config.sets || {};

        if (!sets[setName]) { return []; }

        var resolvedSets = resolveSets(sets),
            set = resolvedSets[setName];

        if (!set || !set.length) { return []; }

        // TODO: uniq
        return Promise.all(set.map(chunk => {
            if (chunk.library) {
                return _this.library(chunk.library).then(libConfig => {
                    assert(libConfig, 'Library `' + chunk.library + '` was not found');

                    return libConfig.levels(chunk.set || setName);
                });
            }

            if (chunk.set) {
                return _this.levels(chunk.set);
            }

            var level = levels.find(lvl => {
                return lvl.layer === chunk.layer;
            }) || {};

            var levelPath = level.path || (level.layer + '.blocks'); // ← TODO: Use @bem/sdk.file.naming

            return _this.levelMap().then(levelsMap => levelsMap[levelPath]);
        })).then(flatten);
    });
};

/**
 * Returns config for given module name
 * @param {String} moduleName - name of module
 * @returns {Promise}
 */
BemConfig.prototype.module = function(moduleName) {
    return this.get().then(function(config) {
        var modules = config.modules;

        return modules && modules[moduleName];
    });
};

/**
 * Returns project root
 * @returns {String}
 */
BemConfig.prototype.rootSync = function() {
    if (this._root) {
        return this._root;
    }

    this.configs(true);
    return this._root;
};

/**
 * Returns merged config synchronously
 * @returns {Object}
 */
BemConfig.prototype.getSync = function() {
    return merge(this.configs(true));
}

/**
 * Resolves config for given level synchronously
 * @param {String} pathToLevel - level path
 * @returns {Object}
 */
BemConfig.prototype.levelSync = function(pathToLevel) {
    // TODO: cache
    return getLevelByConfigs(
        pathToLevel,
        this._options,
        this.configs(true),
        this._root);
};

/**
 * Returns config for given library synchronously
 * @param {String} libName - library name
 * @returns {Object}
 */
BemConfig.prototype.librarySync = function(libName) {
    var config = this.getSync(),
        libs = config.libs,
        lib = libs && libs[libName];

    assert(lib === undefined || typeof lib === 'object', 'Invalid `libs` format');

    var cwd = lib && lib.path || path.resolve('node_modules', libName);

    assert(fs.existsSync(cwd), 'Library ' + libName + ' was not found at ' + cwd);

    return new BemConfig({ cwd });
};

/**
 * Returns map of settings for each of level synchronously
 * @returns {Object}
 */
BemConfig.prototype.levelMapSync = function() {
    var config = this.getSync(),
        projectLevels = config.levels || [],
        libNames = config.libs ? Object.keys(config.libs) : [];

    var libLevels = [].concat.apply([], libNames.map(function(libName) {
        var bemLibConf = this.librarySync(libName),
            libConfig = bemLibConf.getSync();

        return libConfig.levels;
    }, this));

    var allLevels = [].concat(libLevels, projectLevels); // hm.
    return allLevels.reduce(function(acc, level) {
        acc[level.path] = level;
        return acc;
    }, {});
};

BemConfig.prototype.levelsSync = function(setName) {
    var _this = this,
        config = this.getSync(),
        levels = config.levels || [],
        levelsMap = this.levelMapSync(),
        sets = config.sets || {};

    if (!sets[setName]) { return []; }

    var resolvedSets = resolveSets(sets),
        set = resolvedSets[setName];

    // TODO: uniq
    return set.reduce((acc, chunk) => {
        if (chunk.library) {
            var libConfig = _this.librarySync(chunk.library);

            assert(libConfig, 'Library `' + chunk.library + '` was not found');

            return acc.concat(libConfig.levelsSync(chunk.set));
        }

        if (chunk.set) {
            return acc.concat(_this.levelsSync(chunk.set));
        }

        var level = levels.find(lvl => {
            return lvl.layer === chunk.layer;
        }) || {};

        var levelPath = level.path || (level.layer + '.blocks'); // TODO: Use `@bem/sdk.file.naming`

        acc.push(levelsMap[levelPath]);

        return acc;
    }, []);
};

/**
 * Returns config for given module name synchronously
 * @param {String} moduleName - name of module
 * @returns {Object}
 */
BemConfig.prototype.moduleSync = function(moduleName) {
    var modules = this.getSync().modules;

    return modules && modules[moduleName];
};

function getConfigsRootDir(configs) {
    var rootCfg = [].concat(configs).reverse().find(function(cfg) { return cfg.root && cfg.__source; });
    if (rootCfg) { return path.dirname(rootCfg.__source); }
}

function getLevelByConfigs(pathToLevel, options, allConfigs, root) {
    var absLevelPath = path.resolve(root || options.cwd, pathToLevel),
        levelOpts = {},
        commonOpts = {};

    for (var i = allConfigs.length - 1; i >= 0; i--) {
        var conf = allConfigs[i],
            levels = conf.levels || [];

        commonOpts = merge({}, conf, commonOpts);

        for (var j = 0; j < levels.length; j++) {
            var level = levels[j];

            if (level === undefined || level.path !== absLevelPath) { continue; }

            // works like deep extend but overrides arrays
            levelOpts = merge({}, level, levelOpts);
        }

        if (conf.root) { break; }
    }

    levelOpts = merge(commonOpts, levelOpts);

    delete levelOpts.__source;
    delete levelOpts.path;
    delete levelOpts.levels;
    delete levelOpts.root;

    return Object.keys(levelOpts).length ? levelOpts : undefined;
}

/**
 * Modifies passed configs set — adds path property if empty
 *
 * @param {Array<{layer: String, path: ?String}>} configs
 * @returns {Array<{layer: String, path: String}>}
 */
function doSomeMagicProcedure(configs) {
    let levels;

    configs.forEach(config => {
        levels = config.levels;

        if (!levels) { return; }

        if (!Array.isArray(levels)) {
            config.levels = Object.keys(levels).map(levelPath => Object.assign({ path: levelPath }, levels[levelPath]));
        } else {
            levels.forEach(level => level.path || (level.path = level.layer + '.blocks'));
        }
    });

    return configs;
}

module.exports = function(opts) {
    return new BemConfig(opts);
};
<commit_msg>config: Support rel paths to libs<commit_after>'use strict';

var fs = require('fs'),
    assert = require('assert'),
    path = require('path'),
    rc = require('betterc'),
    Promise = require('pinkie-promise'),
    flatten = require('lodash.flatten'),
    merge = require('./lib/merge'),
    resolveSets = require('./lib/resolve-sets'),

    basePlugins = [require('./plugins/resolve-level')];

/**
 * Constructor
 * @param {Object} [options] object
 * @param {String} [options.name='bem'] - config filename.
 * @param {String} [options.cwd=process.cwd()] project root directory.
 * @param {Object} [options.defaults={}] use this object as fallback for found configs
 * @param {String} [options.pathToConfig] custom path to config on FS via command line argument `--config`
 * @constructor
 */
function BemConfig(options) {
    this._options = options || {};
    // TODO: use cwd for resolver
    this._options.cwd || (this._options.cwd = process.cwd());
    // TODO: use cache
    // this._cache = {};
}

/**
 * Returns all found configs
 *
 * @param {boolean} [isSync=false] - flag to resolve configs synchronously
 * @returns {Promise|Array}
 */
BemConfig.prototype.configs = function(isSync) {
    var options = this._options,
        cwd = options.cwd,
        rcOpts = {
            defaults: options.defaults && JSON.parse(JSON.stringify(options.defaults)),
            cwd: cwd,
            fsRoot: options.fsRoot,
            fsHome: options.fsHome,
            name: options.name || 'bem',
            extendBy: options.extendBy
        };

    if (options.pathToConfig) {
        rcOpts.argv = { config: options.pathToConfig };
    }

    var plugins = [].concat(basePlugins, options.plugins || []);

    if (isSync) {
        var configs = doSomeMagicProcedure(this._configs || (this._configs = rc.sync(rcOpts)));

        this._root = getConfigsRootDir(configs);

        return plugins.reduce(function(acc, plugin) {
            return acc.map(function(config) {
                return plugin(config, acc, options);
            });
        }, configs);
    }

    var _this = this,
        _thisConfigs = this._configs || rc(rcOpts).then(function(cfgs) { _this._configs = cfgs; return cfgs; });

    return Promise.resolve(_thisConfigs).then(function(cfgs) {
        doSomeMagicProcedure(cfgs);

        _this._root = getConfigsRootDir(cfgs);

        return plugins.reduce(
            function(cfgsPromise, plugin) {
                return cfgsPromise.then(function(configs_) {
                    return Promise.all(configs_.map(function(config) {
                        return new Promise(function(resolve) {
                            plugin(config, configs_, options, resolve);
                        });
                    }));
                });
            },
            Promise.resolve(cfgs));
    });
};

/**
 * Returns project root
 * @returns {Promise}
 */
BemConfig.prototype.root = function() {
    if (this._root) {
        return Promise.resolve(this._root);
    }

    var _this = this;
    return this.configs().then(function() {
        return _this._root;
    });
};

/**
 * Returns merged config
 * @returns {Promise}
 */
BemConfig.prototype.get = function() {
    return this.configs().then(function(configs) {
        return merge(configs);
    });
};

/**
 * Resolves config for given level
 * @param {String} pathToLevel - level path
 * @returns {Promise}
 */
BemConfig.prototype.level = function(pathToLevel) {
    var _this = this;

    return this.configs()
        .then(function(configs) {
            return getLevelByConfigs(
                pathToLevel,
                _this._options,
                configs,
                _this._root);
        });
};

/**
 * Returns config for given library
 * @param {String} libName - library name
 * @returns {Promise}
 */
BemConfig.prototype.library = function(libName) {
    return this.get()
        .then(function(config) {
            var libs = config.libs,
                lib = libs && libs[libName];

            if (lib !== undefined && typeof lib !== 'object') {
                return Promise.reject('Invalid `libs` format');
            }

            var cwd = lib && lib.path || path.resolve('node_modules', libName);

            return new Promise(function(resolve, reject) {
                fs.exists(cwd, function(doesExist) {
                    if (!doesExist) {
                        return reject('Library ' + libName + ' was not found at ' + cwd);
                    }

                    resolve(cwd);
                })
            });
        })
        .then(cwd => new BemConfig({ cwd: path.resolve(cwd) }));
};

/**
 * Returns map of settings for each of level
 * @returns {Promise}
 */
BemConfig.prototype.levelMap = function() {
    var _this = this;

    return this.get().then(function(config) {
        var projectLevels = config.levels || [],
            libNames = config.libs ? Object.keys(config.libs) : [];

        return Promise.all(libNames.map(function(libName) {
            return _this.library(libName).then(function(bemLibConf) {
                return bemLibConf.get().then(function(libConfig) {
                    return libConfig.levels;
                });
            });
        })).then(function(libLevels) {
            var allLevels = [].concat.apply([], libLevels.filter(Boolean)).concat(projectLevels);

            return allLevels.reduce((res, lvl) => {
                res[lvl.path] = merge(res[lvl.path] || {}, lvl);
                return res;
            }, {});
        });
    });
};

BemConfig.prototype.levels = function(setName) {
    var _this = this;

    return this.get().then(function(config) {
        var levels = config.levels || [],
            sets = config.sets || {};

        if (!sets[setName]) { return []; }

        var resolvedSets = resolveSets(sets),
            set = resolvedSets[setName];

        if (!set || !set.length) { return []; }

        // TODO: uniq
        return Promise.all(set.map(chunk => {
            if (chunk.library) {
                return _this.library(chunk.library).then(libConfig => {
                    assert(libConfig, 'Library `' + chunk.library + '` was not found');

                    return libConfig.levels(chunk.set || setName);
                });
            }

            if (chunk.set) {
                return _this.levels(chunk.set);
            }

            var level = levels.find(lvl => {
                return lvl.layer === chunk.layer;
            }) || {};

            var levelPath = level.path || (level.layer + '.blocks'); // ← TODO: Use @bem/sdk.file.naming

            return _this.levelMap().then(levelsMap => levelsMap[levelPath]);
        })).then(setLevels => setLevels.filter(Boolean)).then(flatten);
    });
};

/**
 * Returns config for given module name
 * @param {String} moduleName - name of module
 * @returns {Promise}
 */
BemConfig.prototype.module = function(moduleName) {
    return this.get().then(function(config) {
        var modules = config.modules;

        return modules && modules[moduleName];
    });
};

/**
 * Returns project root
 * @returns {String}
 */
BemConfig.prototype.rootSync = function() {
    if (this._root) {
        return this._root;
    }

    this.configs(true);
    return this._root;
};

/**
 * Returns merged config synchronously
 * @returns {Object}
 */
BemConfig.prototype.getSync = function() {
    return merge(this.configs(true));
}

/**
 * Resolves config for given level synchronously
 * @param {String} pathToLevel - level path
 * @returns {Object}
 */
BemConfig.prototype.levelSync = function(pathToLevel) {
    // TODO: cache
    return getLevelByConfigs(
        pathToLevel,
        this._options,
        this.configs(true),
        this._root);
};

/**
 * Returns config for given library synchronously
 * @param {String} libName - library name
 * @returns {Object}
 */
BemConfig.prototype.librarySync = function(libName) {
    var config = this.getSync(),
        libs = config.libs,
        lib = libs && libs[libName];

    assert(lib === undefined || typeof lib === 'object', 'Invalid `libs` format');

    var cwd = lib && lib.path || path.resolve('node_modules', libName);

    assert(fs.existsSync(cwd), 'Library ' + libName + ' was not found at ' + cwd);

    return new BemConfig({ cwd: path.resolve(cwd) });
};

/**
 * Returns map of settings for each of level synchronously
 * @returns {Object}
 */
BemConfig.prototype.levelMapSync = function() {
    var config = this.getSync(),
        projectLevels = config.levels || [],
        libNames = config.libs ? Object.keys(config.libs) : [];

    var libLevels = [].concat.apply([], libNames.map(function(libName) {
        var bemLibConf = this.librarySync(libName),
            libConfig = bemLibConf.getSync();

        return libConfig.levels;
    }, this)).filter(Boolean);

    var allLevels = [].concat(libLevels, projectLevels); // hm.
    return allLevels.reduce(function(acc, level) {
        acc[level.path] = level;
        return acc;
    }, {});
};

BemConfig.prototype.levelsSync = function(setName) {
    var _this = this,
        config = this.getSync(),
        levels = config.levels || [],
        levelsMap = this.levelMapSync(),
        sets = config.sets || {};

    if (!sets[setName]) { return []; }

    var resolvedSets = resolveSets(sets),
        set = resolvedSets[setName];

    // TODO: uniq
    return set.reduce((acc, chunk) => {
        if (chunk.library) {
            var libConfig = _this.librarySync(chunk.library);

            assert(libConfig, 'Library `' + chunk.library + '` was not found');

            return acc.concat(libConfig.levelsSync(chunk.set));
        }

        if (chunk.set) {
            return acc.concat(_this.levelsSync(chunk.set));
        }

        var level = levels.find(lvl => {
            return lvl.layer === chunk.layer;
        }) || {};

        var levelPath = level.path || (level.layer + '.blocks'); // TODO: Use `@bem/sdk.file.naming`

        levelsMap[levelPath] && acc.push(levelsMap[levelPath]);

        return acc;
    }, []);
};

/**
 * Returns config for given module name synchronously
 * @param {String} moduleName - name of module
 * @returns {Object}
 */
BemConfig.prototype.moduleSync = function(moduleName) {
    var modules = this.getSync().modules;

    return modules && modules[moduleName];
};

function getConfigsRootDir(configs) {
    var rootCfg = [].concat(configs).reverse().find(function(cfg) { return cfg.root && cfg.__source; });
    if (rootCfg) { return path.dirname(rootCfg.__source); }
}

function getLevelByConfigs(pathToLevel, options, allConfigs, root) {
    var absLevelPath = path.resolve(root || options.cwd, pathToLevel),
        levelOpts = {},
        commonOpts = {};

    for (var i = allConfigs.length - 1; i >= 0; i--) {
        var conf = allConfigs[i],
            levels = conf.levels || [];

        commonOpts = merge({}, conf, commonOpts);

        for (var j = 0; j < levels.length; j++) {
            var level = levels[j];

            if (level === undefined || level.path !== absLevelPath) { continue; }

            // works like deep extend but overrides arrays
            levelOpts = merge({}, level, levelOpts);
        }

        if (conf.root) { break; }
    }

    levelOpts = merge(commonOpts, levelOpts);

    delete levelOpts.__source;
    delete levelOpts.path;
    delete levelOpts.levels;
    delete levelOpts.root;

    return Object.keys(levelOpts).length ? levelOpts : undefined;
}

/**
 * Modifies passed configs set — adds path property if empty
 *
 * @param {Array<{layer: String, path: ?String}>} configs
 * @returns {Array<{layer: String, path: String}>}
 */
function doSomeMagicProcedure(configs) {
    let levels;

    configs.forEach(config => {
        levels = config.levels;

        if (!levels) { return; }

        if (!Array.isArray(levels)) {
            config.levels = Object.keys(levels).map(levelPath => Object.assign({ path: levelPath }, levels[levelPath]));
        } else {
            levels.forEach(level => level.path || (level.path = level.layer + '.blocks'));
        }
    });

    return configs;
}

module.exports = function(opts) {
    return new BemConfig(opts);
};
<|endoftext|>


<commit_before>Package.describe({
  name: 'violet:core',
  version: '0.1.0',
  summary: 'core package of violet',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  var packages = [
    'violet:category',
    'violet:topic',
    'violet:post',
    'violet:user'
  ];

  api.use(packages);
  api.imply(packages);

  api.addFiles([
    'both/routes.js'
  ], ['client', 'server']);

  api.addFiles([
    'client/subscriptions.js',
    'client/templates/shared/layout.html',
    'client/templates/shared/head.html',
    'client/templates/shared/header.html',
    'client/templates/shared/loading.html',
    'client/templates/home.html',
    'client/templates/admins/adminSettings.html',
    'client/templates/admins/adminSettings.js',
    'client/templates/admins/adminCategories.html',
    'client/templates/admins/adminCategories.js',
    'client/templates/admins/adminEditCategory.html',
    'client/templates/admins/adminEditCategory.js',
    'client/templates/errors/404.html'
  ], 'client');
});

Package.onTest(function(api) {
  api.use('violet:core');
});
<commit_msg>Specify version constraint<commit_after>Package.describe({
  name: 'violet:core',
  version: '0.1.0',
  summary: 'core package of violet',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  var packages = [
    'violet:category@0.1.0',
    'violet:topic@0.1.0',
    'violet:post@0.1.0',
    'violet:user@0.1.0'
  ];

  api.use(packages);
  api.imply(packages);

  api.addFiles([
    'both/routes.js'
  ], ['client', 'server']);

  api.addFiles([
    'client/subscriptions.js',
    'client/templates/shared/layout.html',
    'client/templates/shared/head.html',
    'client/templates/shared/header.html',
    'client/templates/shared/loading.html',
    'client/templates/home.html',
    'client/templates/admins/adminSettings.html',
    'client/templates/admins/adminSettings.js',
    'client/templates/admins/adminCategories.html',
    'client/templates/admins/adminCategories.js',
    'client/templates/admins/adminEditCategory.html',
    'client/templates/admins/adminEditCategory.js',
    'client/templates/errors/404.html'
  ], 'client');
});

Package.onTest(function(api) {
  api.use('violet:core');
});
<|endoftext|>


<commit_before>/**
 * Calculate relative number by relative min and max sources
 *
 * @version r1
 * @author Viacheslav Lotsmanov
 * @license GNU/GPLv3 by Free Software Foundation (https://github.com/unclechu/js-useful-amd-modules/blob/master/GPLv3-LICENSE)
 * @see {@link https://github.com/unclechu/js-useful-amd-modules/|GitHub}
 */

define(['jquery'], function ($) {

	var exports, undefined;

	// helpers {{{1

	function inherit(proto) {
		if (Object.create) return Object.create(proto);
		function F() {}
		F.prototype = proto;
		return new F();
	}

	// helpers }}}1

	/**
	 * @typedef params
	 * @type {Object.<Number|Float|Boolean>}
	 * @prop {Number|Float} relVal - Current relative value
	 * @prop {Number|Float} relMin - Relative minimum value
	 * @prop {Number|Float} relMax - Relative maximum value
	 * @prop {Number|Float} min - Minimum value for calculating by "relMin"
	 * @prop {Number|Float} max - maximum value for calculating by "relMax"
	 * @prop {Boolean} [limitMin=true] - Limit "relVal" by "relMin"
	 * @prop {Boolean} [limitMax=true] - Limit "relVal" by "relMax"
	 */
	var defaultParams = { // {{{1
		relVal: null,
		relMin: null,
		relMax: null,
		min: null,
		max: null,
		limitMin: true,
		limitMax: true,
	}; // defaultParams }}}1

	/**
	 * @private
	 * @inner
	 * @param {params} params
	 * @return Calculated value
	 * @TODO relMin less than zero
	 * @TODO invert min/max
	 */
	function model(params) { // {{{1

		var result = 0;
		var relVal = params.relVal;

		if (params.limitMin && relVal < params.relMin)
			relVal = params.relMin;
		else if (params.limitMax && relVal > params.relMax)
			relVal = params.relMax;

		var relValLow = relVal - params.relMin;
		var relMaxLow = params.relMax - params.relMin;
		var maxLow = params.max - params.min;

		result = relValLow * (maxLow) / relMaxLow;
		result += params.min;

		return result;

	} // model() }}}1

	/**
	 * @public
	 * @static
	 * @param {params} params
	 * @return Calculated value
	 * @throws {Error} IncorrectParamsType
	 * @throws {Error} RequiredParam
	 * @throws {Error} UnknownParam
	 * @throws {Error} IncorrectParamValue
	 */
	exports = function controller(params) { // {{{1

		var key;

		// validate params {{{2

		// check for correct params type
		if (!$.isPlainObject(params))
			throw new exceptions.IncorrectParamsType(null, $.type(params));

		// check for required params
		for (key in defaultParams) {
			if (key === 'limitMin' || key === 'limitMax')
				continue;
			else if (!(key in params))
				throw new exceptions.RequiredParam(null, key);
		}

		// check for unknown params
		for (key in params)
			if (!(key in defaultParams))
				throw new exceptions.UnknownParam(null, key);

		// check for correct params type
		for (key in defaultParams) {
			if (key === 'limitMin' || key === 'limitMax') {
				if (key in params && $.type(params[key]) !== 'boolean')
					throw new exceptions.IncorrectParamValue(
						null, key, $.type(params[key]), 'boolean');
			} else if ($.type(params[key]) !== 'number') {
				throw new exceptions.IncorrectParamValue(
					null, key, $.type(params[key]), 'number');
			}
		}

		// validate params }}}2

		params = $.extend({}, defaultParams, params);

		return model(params);

	}; // exports() = controller() }}}1

	/* exceptions {{{1 */

	/**
	 * @public
	 * @static
	 * @readOnly
	 * @type {Object.<Error>}
	 * @prop {Error} IncorrectParamsType
	 * @prop {Error} RequiredParam
	 * @prop {Error} UnknownParam
	 * @prop {Error} IncorrectParamValue
	 */
	var exceptions = exports.exceptions = {};

	/** @typedef {Error} IncorrectParamsType */
	exceptions.IncorrectParamsType = function (message, paramsType) {
		Error.call(this);
		this.name = 'IncorrectParamsType';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Params must be a plain object';
			if (paramsType) this.message += ' (now is "'+ paramsType +'")';
			this.message += '.';
		}
	};

	/** @typedef {Error} RequiredParam */
	exceptions.RequiredParam = function (message, paramName) {
		Error.call(this);
		this.name = 'RequiredParam';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Required param ';
			if (paramName) this.message += ' "'+ paramName +'"';
			this.message += '.';
		}
	};

	/** @typedef {Error} UnknownParam */
	exceptions.UnknownParam = function (message, paramName) {
		Error.call(this);
		this.name = 'UnknownParam';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Unknown param ';
			if (paramName) this.message += ' "'+ paramName +'"';
			this.message += '.';
		}
	};

	/** @typedef {Error} IncorrectParamValue */
	exceptions.IncorrectParamValue =
	function (message, paramName, paramType, mustBeType) {
		Error.call(this);
		this.name = 'IncorrectParamValue';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect';
			if (paramName) this.message += ' "'+ paramName +'"';
			this.message += ' param value type';
			if (paramType) this.message += ': "'+ paramType +'"';
			if (mustBeType) this.message += ', must be a "'+ mustBeType +'"';
			this.message += '.';
		}
	};

	for (var key in exceptions)
		exceptions[key].prototype = inherit(Error.prototype);

	/* exceptions }}}1 */

	return exports;

}); // define()
<commit_msg>removed TODO markers from "relative number" because invert value and min less than zero already works<commit_after>/**
 * Calculate relative number by relative min and max sources
 *
 * @version r1
 * @author Viacheslav Lotsmanov
 * @license GNU/GPLv3 by Free Software Foundation (https://github.com/unclechu/js-useful-amd-modules/blob/master/GPLv3-LICENSE)
 * @see {@link https://github.com/unclechu/js-useful-amd-modules/|GitHub}
 */

define(['jquery'], function ($) {

	var exports, undefined;

	// helpers {{{1

	function inherit(proto) {
		if (Object.create) return Object.create(proto);
		function F() {}
		F.prototype = proto;
		return new F();
	}

	// helpers }}}1

	/**
	 * @typedef params
	 * @type {Object.<Number|Float|Boolean>}
	 * @prop {Number|Float} relVal - Current relative value
	 * @prop {Number|Float} relMin - Relative minimum value
	 * @prop {Number|Float} relMax - Relative maximum value
	 * @prop {Number|Float} min - Minimum value for calculating by "relMin"
	 * @prop {Number|Float} max - maximum value for calculating by "relMax"
	 * @prop {Boolean} [limitMin=true] - Limit "relVal" by "relMin"
	 * @prop {Boolean} [limitMax=true] - Limit "relVal" by "relMax"
	 */
	var defaultParams = { // {{{1
		relVal: null,
		relMin: null,
		relMax: null,
		min: null,
		max: null,
		limitMin: true,
		limitMax: true,
	}; // defaultParams }}}1

	/**
	 * @private
	 * @inner
	 * @param {params} params
	 * @return Calculated value
	 */
	function model(params) { // {{{1

		var result = 0;
		var relVal = params.relVal;

		if (params.limitMin && relVal < params.relMin)
			relVal = params.relMin;
		else if (params.limitMax && relVal > params.relMax)
			relVal = params.relMax;

		var relValLow = relVal - params.relMin;
		var relMaxLow = params.relMax - params.relMin;
		var maxLow = params.max - params.min;

		result = relValLow * (maxLow) / relMaxLow;
		result += params.min;

		return result;

	} // model() }}}1

	/**
	 * @public
	 * @static
	 * @param {params} params
	 * @return Calculated value
	 * @throws {Error} IncorrectParamsType
	 * @throws {Error} RequiredParam
	 * @throws {Error} UnknownParam
	 * @throws {Error} IncorrectParamValue
	 */
	exports = function controller(params) { // {{{1

		var key;

		// validate params {{{2

		// check for correct params type
		if (!$.isPlainObject(params))
			throw new exceptions.IncorrectParamsType(null, $.type(params));

		// check for required params
		for (key in defaultParams) {
			if (key === 'limitMin' || key === 'limitMax')
				continue;
			else if (!(key in params))
				throw new exceptions.RequiredParam(null, key);
		}

		// check for unknown params
		for (key in params)
			if (!(key in defaultParams))
				throw new exceptions.UnknownParam(null, key);

		// check for correct params type
		for (key in defaultParams) {
			if (key === 'limitMin' || key === 'limitMax') {
				if (key in params && $.type(params[key]) !== 'boolean')
					throw new exceptions.IncorrectParamValue(
						null, key, $.type(params[key]), 'boolean');
			} else if ($.type(params[key]) !== 'number') {
				throw new exceptions.IncorrectParamValue(
					null, key, $.type(params[key]), 'number');
			}
		}

		// validate params }}}2

		params = $.extend({}, defaultParams, params);

		return model(params);

	}; // exports() = controller() }}}1

	/* exceptions {{{1 */

	/**
	 * @public
	 * @static
	 * @readOnly
	 * @type {Object.<Error>}
	 * @prop {Error} IncorrectParamsType
	 * @prop {Error} RequiredParam
	 * @prop {Error} UnknownParam
	 * @prop {Error} IncorrectParamValue
	 */
	var exceptions = exports.exceptions = {};

	/** @typedef {Error} IncorrectParamsType */
	exceptions.IncorrectParamsType = function (message, paramsType) {
		Error.call(this);
		this.name = 'IncorrectParamsType';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Params must be a plain object';
			if (paramsType) this.message += ' (now is "'+ paramsType +'")';
			this.message += '.';
		}
	};

	/** @typedef {Error} RequiredParam */
	exceptions.RequiredParam = function (message, paramName) {
		Error.call(this);
		this.name = 'RequiredParam';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Required param ';
			if (paramName) this.message += ' "'+ paramName +'"';
			this.message += '.';
		}
	};

	/** @typedef {Error} UnknownParam */
	exceptions.UnknownParam = function (message, paramName) {
		Error.call(this);
		this.name = 'UnknownParam';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Unknown param ';
			if (paramName) this.message += ' "'+ paramName +'"';
			this.message += '.';
		}
	};

	/** @typedef {Error} IncorrectParamValue */
	exceptions.IncorrectParamValue =
	function (message, paramName, paramType, mustBeType) {
		Error.call(this);
		this.name = 'IncorrectParamValue';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect';
			if (paramName) this.message += ' "'+ paramName +'"';
			this.message += ' param value type';
			if (paramType) this.message += ': "'+ paramType +'"';
			if (mustBeType) this.message += ', must be a "'+ mustBeType +'"';
			this.message += '.';
		}
	};

	for (var key in exceptions)
		exceptions[key].prototype = inherit(Error.prototype);

	/* exceptions }}}1 */

	return exports;

}); // define()
<|endoftext|>


<commit_before>/*global window: false */
"use strict";

var moment = require('moment');
moment = typeof(moment) === 'function' ? moment : window.moment;

module.exports = function(Chart) {

	var helpers = Chart.helpers;
	var time = {
		units: [{
			name: 'millisecond',
			steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
		}, {
			name: 'second',
			steps: [1, 2, 5, 10, 30]
		}, {
			name: 'minute',
			steps: [1, 2, 5, 10, 30]
		}, {
			name: 'hour',
			steps: [1, 2, 3, 6, 12]
		}, {
			name: 'day',
			steps: [1, 2, 5]
		}, {
			name: 'week',
			maxStep: 4
		}, {
			name: 'month',
			maxStep: 3
		}, {
			name: 'quarter',
			maxStep: 4
		}, {
			name: 'year',
			maxStep: false
		}]
	};

	var defaultConfig = {
		position: "bottom",

		time: {
			parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
			format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
			unit: false, // false == automatic or override with week, month, year, etc.
			round: false, // none, or override with week, month, year, etc.
			displayFormat: false, // DEPRECATED

			// defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
			displayFormats: {
				'millisecond': 'h:mm:ss.SSS a', // 11:20:01.123 AM,
				'second': 'h:mm:ss a', // 11:20:01 AM
				'minute': 'h:mm:ss a', // 11:20:01 AM
				'hour': 'MMM D, hA', // Sept 4, 5PM
				'day': 'll', // Sep 4 2015
				'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
				'month': 'MMM YYYY', // Sept 2015
				'quarter': '[Q]Q - YYYY', // Q3
				'year': 'YYYY' // 2015
			}
		},
		ticks: {
			autoSkip: false
		}
	};

	var TimeScale = Chart.Scale.extend({
		initialize: function() {
			if (!moment) {
				throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com');
			}

			Chart.Scale.prototype.initialize.call(this);
		},
		getLabelMoment: function(datasetIndex, index) {
			return this.labelMoments[datasetIndex][index];
		},
		determineDataLimits: function() {
			this.labelMoments = [];

			// Only parse these once. If the dataset does not have data as x,y pairs, we will use
			// these
			var scaleLabelMoments = [];
			if (this.chart.data.labels && this.chart.data.labels.length > 0) {
				helpers.each(this.chart.data.labels, function(label, index) {
					var labelMoment = this.parseTime(label);
					if (this.options.time.round) {
						labelMoment.startOf(this.options.time.round);
					}
					scaleLabelMoments.push(labelMoment);
				}, this);

				this.firstTick = moment.min.call(this, scaleLabelMoments);
				this.lastTick = moment.max.call(this, scaleLabelMoments);
			} else {
				this.firstTick = null;
				this.lastTick = null;
			}

			helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
				var momentsForDataset = [];

				if (typeof dataset.data[0] === 'object') {
					helpers.each(dataset.data, function(value, index) {
						var labelMoment = this.parseTime(this.getRightValue(value));
						if (this.options.time.round) {
							labelMoment.startOf(this.options.time.round);
						}
						momentsForDataset.push(labelMoment);

						// May have gone outside the scale ranges, make sure we keep the first and last ticks updated
						this.firstTick = this.firstTick !== null ? moment.min(this.firstTick, labelMoment) : labelMoment;
						this.lastTick = this.lastTick !== null ? moment.max(this.lastTick, labelMoment) : labelMoment;
					}, this);
				} else {
					// We have no labels. Use the ones from the scale
					momentsForDataset = scaleLabelMoments;
				}

				this.labelMoments.push(momentsForDataset);
			}, this);

			// Set these after we've done all the data
			if (this.options.time.min) {
				this.firstTick = this.parseTime(this.options.time.min);
			}

			if (this.options.time.max) {
				this.lastTick = this.parseTime(this.options.time.max);
			}

			// We will modify these, so clone for later
			this.firstTick = (this.firstTick || moment()).clone();
			this.lastTick = (this.lastTick || moment()).clone();
		},
		buildTicks: function(index) {

			this.ctx.save();
			var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize);
			var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle);
			var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily);
			var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
			this.ctx.font = tickLabelFont;

			this.ticks = [];
			this.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step
			this.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc)

			// Set unit override if applicable
			if (this.options.time.unit) {
				this.tickUnit = this.options.time.unit || 'day';
				this.displayFormat = this.options.time.displayFormats[this.tickUnit];
				this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true);
				this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, 1);
			} else {
				// Determine the smallest needed unit of the time
				var innerWidth = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom);

				// Crude approximation of what the label length might be
				var tempFirstLabel = this.tickFormatFunction(this.firstTick, 0, []);
				var tickLabelWidth = this.ctx.measureText(tempFirstLabel).width;
				var cosRotation = Math.cos(helpers.toRadians(this.options.ticks.maxRotation));
				var sinRotation = Math.sin(helpers.toRadians(this.options.ticks.maxRotation));
				tickLabelWidth = (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
				var labelCapacity = innerWidth / (tickLabelWidth);

				// Start as small as possible
				this.tickUnit = 'millisecond';
				this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true);
				this.displayFormat = this.options.time.displayFormats[this.tickUnit];

				var unitDefinitionIndex = 0;
				var unitDefinition = time.units[unitDefinitionIndex];

				// While we aren't ideal and we don't have units left
				while (unitDefinitionIndex < time.units.length) {
					// Can we scale this unit. If `false` we can scale infinitely
					this.unitScale = 1;

					if (helpers.isArray(unitDefinition.steps) && Math.ceil(this.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) {
						// Use one of the prefedined steps
						for (var idx = 0; idx < unitDefinition.steps.length; ++idx) {
							if (unitDefinition.steps[idx] >= Math.ceil(this.scaleSizeInUnits / labelCapacity)) {
								this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, unitDefinition.steps[idx]);
								break;
							}
						}

						break;
					} else if ((unitDefinition.maxStep === false) || (Math.ceil(this.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) {
						// We have a max step. Scale this unit
						this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, Math.ceil(this.scaleSizeInUnits / labelCapacity));
						break;
					} else {
						// Move to the next unit up
						++unitDefinitionIndex;
						unitDefinition = time.units[unitDefinitionIndex];

						this.tickUnit = unitDefinition.name;
						this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true);
						this.displayFormat = this.options.time.displayFormats[unitDefinition.name];
					}
				}
			}

			var roundedStart;

			// Only round the first tick if we have no hard minimum
			if (!this.options.time.min) {
				this.firstTick.startOf(this.tickUnit);
				roundedStart = this.firstTick;
			} else {
				roundedStart = this.firstTick.clone().startOf(this.tickUnit);
			}

			// Only round the last tick if we have no hard maximum
			if (!this.options.time.max) {
				this.lastTick.endOf(this.tickUnit);
			}

			this.smallestLabelSeparation = this.width;

			helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
				for (var i = 1; i < this.labelMoments[datasetIndex].length; i++) {
					this.smallestLabelSeparation = Math.min(this.smallestLabelSeparation, this.labelMoments[datasetIndex][i].diff(this.labelMoments[datasetIndex][i - 1], this.tickUnit, true));
				}
			}, this);

			// Tick displayFormat override
			if (this.options.time.displayFormat) {
				this.displayFormat = this.options.time.displayFormat;
			}

			// first tick. will have been rounded correctly if options.time.min is not specified
			this.ticks.push(this.firstTick.clone());

			// For every unit in between the first and last moment, create a moment and add it to the ticks tick
			for (var i = 1; i < this.scaleSizeInUnits; ++i) {
				var newTick = roundedStart.clone().add(i, this.tickUnit);

				// Are we greater than the max time
				if (this.options.time.max && newTick.diff(this.lastTick, this.tickUnit, true) >= 0) {
					break;
				}

				if (i % this.unitScale === 0) {
					this.ticks.push(newTick);
				}
			}

			// Always show the right tick
			if (this.ticks[this.ticks.length - 1].diff(this.lastTick, this.tickUnit) !== 0 || this.scaleSizeInUnits === 0) {
			// this is a weird case. If the <max> option is the same as the end option, we can't just diff the times because the tick was created from the roundedStart
			// but the last tick was not rounded.
				if (this.options.time.max) {
					this.ticks.push(this.lastTick.clone());
					this.scaleSizeInUnits = this.lastTick.diff(this.ticks[0], this.tickUnit, true);
				} else {
					this.scaleSizeInUnits = Math.ceil(this.scaleSizeInUnits / this.unitScale) * this.unitScale;
					this.ticks.push(this.firstTick.clone().add(this.scaleSizeInUnits, this.tickUnit));
					this.lastTick = this.ticks[this.ticks.length - 1].clone();
				}
			}
			this.ctx.restore();
		},
		// Get tooltip label
		getLabelForIndex: function(index, datasetIndex) {
			var label = this.chart.data.labels && index < this.chart.data.labels.length ? this.chart.data.labels[index] : '';

			if (typeof this.chart.data.datasets[datasetIndex].data[0] === 'object') {
				label = this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
			}

			// Format nicely
			if (this.options.time.tooltipFormat) {
				label = this.parseTime(label).format(this.options.time.tooltipFormat);
			}

			return label;
		},
		// Function to format an individual tick mark
		tickFormatFunction: function tickFormatFunction(tick, index, ticks) {
			var formattedTick = tick.format(this.displayFormat);

			if (this.options.ticks.userCallback) {
				return this.options.ticks.userCallback(formattedTick, index, ticks);
			} else {
				return formattedTick;
			}
		},
		convertTicksToLabels: function() {
			this.ticks = this.ticks.map(this.tickFormatFunction, this);
		},
		getPixelForValue: function(value, index, datasetIndex, includeOffset) {
			var labelMoment = this.getLabelMoment(datasetIndex, index);

			if (labelMoment) {
				var offset = labelMoment.diff(this.firstTick, this.tickUnit, true);

				var decimal = offset / this.scaleSizeInUnits;

				if (this.isHorizontal()) {
					var innerWidth = this.width - (this.paddingLeft + this.paddingRight);
					var valueWidth = innerWidth / Math.max(this.ticks.length - 1, 1);
					var valueOffset = (innerWidth * decimal) + this.paddingLeft;

					return this.left + Math.round(valueOffset);
				} else {
					var innerHeight = this.height - (this.paddingTop + this.paddingBottom);
					var valueHeight = innerHeight / Math.max(this.ticks.length - 1, 1);
					var heightOffset = (innerHeight * decimal) + this.paddingTop;

					return this.top + Math.round(heightOffset);
				}
			}
		},
		parseTime: function(label) {
			if (typeof this.options.time.parser === 'string') {
				return moment(label, this.options.time.parser);
			}
			if (typeof this.options.time.parser === 'function') {
				return this.options.time.parser(label);
			}
			// Date objects
			if (typeof label.getMonth === 'function' || typeof label === 'number') {
				return moment(label);
			}
			// Moment support
			if (label.isValid && label.isValid()) {
				return label;
			}
			// Custom parsing (return an instance of moment)
			if (typeof this.options.time.format !== 'string' && this.options.time.format.call) {
				console.warn("options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale");
				return this.options.time.format(label);
			}
			// Moment format parsing
			return moment(label, this.options.time.format);
		}
	});
	Chart.scaleService.registerScaleType("time", TimeScale, defaultConfig);

};
<commit_msg>Only use valid label moments<commit_after>/*global window: false */
"use strict";

var moment = require('moment');
moment = typeof(moment) === 'function' ? moment : window.moment;

module.exports = function(Chart) {

	var helpers = Chart.helpers;
	var time = {
		units: [{
			name: 'millisecond',
			steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
		}, {
			name: 'second',
			steps: [1, 2, 5, 10, 30]
		}, {
			name: 'minute',
			steps: [1, 2, 5, 10, 30]
		}, {
			name: 'hour',
			steps: [1, 2, 3, 6, 12]
		}, {
			name: 'day',
			steps: [1, 2, 5]
		}, {
			name: 'week',
			maxStep: 4
		}, {
			name: 'month',
			maxStep: 3
		}, {
			name: 'quarter',
			maxStep: 4
		}, {
			name: 'year',
			maxStep: false
		}]
	};

	var defaultConfig = {
		position: "bottom",

		time: {
			parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
			format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
			unit: false, // false == automatic or override with week, month, year, etc.
			round: false, // none, or override with week, month, year, etc.
			displayFormat: false, // DEPRECATED

			// defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
			displayFormats: {
				'millisecond': 'h:mm:ss.SSS a', // 11:20:01.123 AM,
				'second': 'h:mm:ss a', // 11:20:01 AM
				'minute': 'h:mm:ss a', // 11:20:01 AM
				'hour': 'MMM D, hA', // Sept 4, 5PM
				'day': 'll', // Sep 4 2015
				'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
				'month': 'MMM YYYY', // Sept 2015
				'quarter': '[Q]Q - YYYY', // Q3
				'year': 'YYYY' // 2015
			}
		},
		ticks: {
			autoSkip: false
		}
	};

	var TimeScale = Chart.Scale.extend({
		initialize: function() {
			if (!moment) {
				throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com');
			}

			Chart.Scale.prototype.initialize.call(this);
		},
		getLabelMoment: function(datasetIndex, index) {
			return this.labelMoments[datasetIndex][index];
		},
		determineDataLimits: function() {
			this.labelMoments = [];

			// Only parse these once. If the dataset does not have data as x,y pairs, we will use
			// these
			var scaleLabelMoments = [];
			if (this.chart.data.labels && this.chart.data.labels.length > 0) {
				helpers.each(this.chart.data.labels, function(label, index) {
					var labelMoment = this.parseTime(label);

					if (labelMoment.isValid()) {
						if (this.options.time.round) {
							labelMoment.startOf(this.options.time.round);
						}
						scaleLabelMoments.push(labelMoment);
					}
				}, this);

				this.firstTick = moment.min.call(this, scaleLabelMoments);
				this.lastTick = moment.max.call(this, scaleLabelMoments);
			} else {
				this.firstTick = null;
				this.lastTick = null;
			}

			helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
				var momentsForDataset = [];

				if (typeof dataset.data[0] === 'object') {
					helpers.each(dataset.data, function(value, index) {
						var labelMoment = this.parseTime(this.getRightValue(value));

						if (labelMoment.isValid()) {
							if (this.options.time.round) {
								labelMoment.startOf(this.options.time.round);
							}
							momentsForDataset.push(labelMoment);

							// May have gone outside the scale ranges, make sure we keep the first and last ticks updated
							this.firstTick = this.firstTick !== null ? moment.min(this.firstTick, labelMoment) : labelMoment;
							this.lastTick = this.lastTick !== null ? moment.max(this.lastTick, labelMoment) : labelMoment;
						}
					}, this);
				} else {
					// We have no labels. Use the ones from the scale
					momentsForDataset = scaleLabelMoments;
				}

				this.labelMoments.push(momentsForDataset);
			}, this);

			// Set these after we've done all the data
			if (this.options.time.min) {
				this.firstTick = this.parseTime(this.options.time.min);
			}

			if (this.options.time.max) {
				this.lastTick = this.parseTime(this.options.time.max);
			}

			// We will modify these, so clone for later
			this.firstTick = (this.firstTick || moment()).clone();
			this.lastTick = (this.lastTick || moment()).clone();
		},
		buildTicks: function(index) {

			this.ctx.save();
			var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize);
			var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle);
			var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily);
			var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
			this.ctx.font = tickLabelFont;

			this.ticks = [];
			this.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step
			this.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc)

			// Set unit override if applicable
			if (this.options.time.unit) {
				this.tickUnit = this.options.time.unit || 'day';
				this.displayFormat = this.options.time.displayFormats[this.tickUnit];
				this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true);
				this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, 1);
			} else {
				// Determine the smallest needed unit of the time
				var innerWidth = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom);

				// Crude approximation of what the label length might be
				var tempFirstLabel = this.tickFormatFunction(this.firstTick, 0, []);
				var tickLabelWidth = this.ctx.measureText(tempFirstLabel).width;
				var cosRotation = Math.cos(helpers.toRadians(this.options.ticks.maxRotation));
				var sinRotation = Math.sin(helpers.toRadians(this.options.ticks.maxRotation));
				tickLabelWidth = (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
				var labelCapacity = innerWidth / (tickLabelWidth);

				// Start as small as possible
				this.tickUnit = 'millisecond';
				this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true);
				this.displayFormat = this.options.time.displayFormats[this.tickUnit];

				var unitDefinitionIndex = 0;
				var unitDefinition = time.units[unitDefinitionIndex];

				// While we aren't ideal and we don't have units left
				while (unitDefinitionIndex < time.units.length) {
					// Can we scale this unit. If `false` we can scale infinitely
					this.unitScale = 1;

					if (helpers.isArray(unitDefinition.steps) && Math.ceil(this.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) {
						// Use one of the prefedined steps
						for (var idx = 0; idx < unitDefinition.steps.length; ++idx) {
							if (unitDefinition.steps[idx] >= Math.ceil(this.scaleSizeInUnits / labelCapacity)) {
								this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, unitDefinition.steps[idx]);
								break;
							}
						}

						break;
					} else if ((unitDefinition.maxStep === false) || (Math.ceil(this.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) {
						// We have a max step. Scale this unit
						this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, Math.ceil(this.scaleSizeInUnits / labelCapacity));
						break;
					} else {
						// Move to the next unit up
						++unitDefinitionIndex;
						unitDefinition = time.units[unitDefinitionIndex];

						this.tickUnit = unitDefinition.name;
						this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true);
						this.displayFormat = this.options.time.displayFormats[unitDefinition.name];
					}
				}
			}

			var roundedStart;

			// Only round the first tick if we have no hard minimum
			if (!this.options.time.min) {
				this.firstTick.startOf(this.tickUnit);
				roundedStart = this.firstTick;
			} else {
				roundedStart = this.firstTick.clone().startOf(this.tickUnit);
			}

			// Only round the last tick if we have no hard maximum
			if (!this.options.time.max) {
				this.lastTick.endOf(this.tickUnit);
			}

			this.smallestLabelSeparation = this.width;

			helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
				for (var i = 1; i < this.labelMoments[datasetIndex].length; i++) {
					this.smallestLabelSeparation = Math.min(this.smallestLabelSeparation, this.labelMoments[datasetIndex][i].diff(this.labelMoments[datasetIndex][i - 1], this.tickUnit, true));
				}
			}, this);

			// Tick displayFormat override
			if (this.options.time.displayFormat) {
				this.displayFormat = this.options.time.displayFormat;
			}

			// first tick. will have been rounded correctly if options.time.min is not specified
			this.ticks.push(this.firstTick.clone());

			// For every unit in between the first and last moment, create a moment and add it to the ticks tick
			for (var i = 1; i < this.scaleSizeInUnits; ++i) {
				var newTick = roundedStart.clone().add(i, this.tickUnit);

				// Are we greater than the max time
				if (this.options.time.max && newTick.diff(this.lastTick, this.tickUnit, true) >= 0) {
					break;
				}

				if (i % this.unitScale === 0) {
					this.ticks.push(newTick);
				}
			}

			// Always show the right tick
			if (this.ticks[this.ticks.length - 1].diff(this.lastTick, this.tickUnit) !== 0 || this.scaleSizeInUnits === 0) {
			// this is a weird case. If the <max> option is the same as the end option, we can't just diff the times because the tick was created from the roundedStart
			// but the last tick was not rounded.
				if (this.options.time.max) {
					this.ticks.push(this.lastTick.clone());
					this.scaleSizeInUnits = this.lastTick.diff(this.ticks[0], this.tickUnit, true);
				} else {
					this.scaleSizeInUnits = Math.ceil(this.scaleSizeInUnits / this.unitScale) * this.unitScale;
					this.ticks.push(this.firstTick.clone().add(this.scaleSizeInUnits, this.tickUnit));
					this.lastTick = this.ticks[this.ticks.length - 1].clone();
				}
			}
			this.ctx.restore();
		},
		// Get tooltip label
		getLabelForIndex: function(index, datasetIndex) {
			var label = this.chart.data.labels && index < this.chart.data.labels.length ? this.chart.data.labels[index] : '';

			if (typeof this.chart.data.datasets[datasetIndex].data[0] === 'object') {
				label = this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
			}

			// Format nicely
			if (this.options.time.tooltipFormat) {
				label = this.parseTime(label).format(this.options.time.tooltipFormat);
			}

			return label;
		},
		// Function to format an individual tick mark
		tickFormatFunction: function tickFormatFunction(tick, index, ticks) {
			var formattedTick = tick.format(this.displayFormat);

			if (this.options.ticks.userCallback) {
				return this.options.ticks.userCallback(formattedTick, index, ticks);
			} else {
				return formattedTick;
			}
		},
		convertTicksToLabels: function() {
			this.ticks = this.ticks.map(this.tickFormatFunction, this);
		},
		getPixelForValue: function(value, index, datasetIndex, includeOffset) {
			var labelMoment = this.getLabelMoment(datasetIndex, index);

			if (labelMoment) {
				var offset = labelMoment.diff(this.firstTick, this.tickUnit, true);

				var decimal = offset / this.scaleSizeInUnits;

				if (this.isHorizontal()) {
					var innerWidth = this.width - (this.paddingLeft + this.paddingRight);
					var valueWidth = innerWidth / Math.max(this.ticks.length - 1, 1);
					var valueOffset = (innerWidth * decimal) + this.paddingLeft;

					return this.left + Math.round(valueOffset);
				} else {
					var innerHeight = this.height - (this.paddingTop + this.paddingBottom);
					var valueHeight = innerHeight / Math.max(this.ticks.length - 1, 1);
					var heightOffset = (innerHeight * decimal) + this.paddingTop;

					return this.top + Math.round(heightOffset);
				}
			}
		},
		parseTime: function(label) {
			if (typeof this.options.time.parser === 'string') {
				return moment(label, this.options.time.parser);
			}
			if (typeof this.options.time.parser === 'function') {
				return this.options.time.parser(label);
			}
			// Date objects
			if (typeof label.getMonth === 'function' || typeof label === 'number') {
				return moment(label);
			}
			// Moment support
			if (label.isValid && label.isValid()) {
				return label;
			}
			// Custom parsing (return an instance of moment)
			if (typeof this.options.time.format !== 'string' && this.options.time.format.call) {
				console.warn("options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale");
				return this.options.time.format(label);
			}
			// Moment format parsing
			return moment(label, this.options.time.format);
		}
	});
	Chart.scaleService.registerScaleType("time", TimeScale, defaultConfig);

};
<|endoftext|>


<commit_before>import React, { useCallback, useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import { noop, debounce } from 'lodash';
import ReactModal from 'react-modal';
import tinycolor from 'tinycolor2';

import useUniqueId from '../../util/useUniqueId';
import { useRootNodeLocator } from '../../util/useRootNode';
import { ModalContext } from './ModalContext';
import Header from './ModalHeader';
import Body from './ModalBody';
import Footer from './ModalFooter';

const modalSize = {
  small: '300px',
  medium: '600px',
  large: '900px'
};

const animationTimeMs = 300;

const getModalMargin = (windowHeight, modalHeight) => {
  const fullMargin = windowHeight - modalHeight;
  const thirdTopMargin = fullMargin / 3;
  return Math.max(thirdTopMargin, 50);
};

const openClass = 'modal-open';

const ModalStyles = createGlobalStyle`
  .${openClass} {
    overflow: hidden;

    .background-overlay {
      bottom: 0;
      background-color: ${props => {
        const color = tinycolor(props.theme.colors.gray9);
        color.setAlpha(0);
        return color.toRgbString();
      }};

      left: 0;
      max-height: 100%;
      overflow-y: auto;
      position: fixed;
      right: 0;
      top: 0;
      transition: background-color ${() => animationTimeMs / 2}ms linear;
      z-index: 1030;
      -webkit-overflow-scrolling: touch;

      &.ReactModal__Overlay--after-open {
        ${props => {
          if (!props.showBackdrop) return '';

          const color = tinycolor(props.theme.colors.gray9);
          color.setAlpha(0.5);
          return `background-color: ${color.toRgbString()};`;
        }}

        &.ReactModal__Overlay--before-close {
          background-color: ${props => {
            const color = tinycolor(props.theme.colors.gray9);
            color.setAlpha(0);
            return color.toRgbString();
          }};
        }
      }
    }

    .modal-content {
      background-clip: padding-box;
      background-color: ${props => props.theme.colors.white};
      border-radius: 3px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
      font-family: 'Source Sans Pro', 'Segoe UI', Segoe, Calibri, Tahoma, sans-serif;
      font-size: ${props => props.theme.font.baseFontSize};
      margin: 0.5rem;
      outline: 0;
      opacity: 0;
      position: absolute;
      left: 0;
      transform: translateY(0);
      transition:
        transform ${() => animationTimeMs}ms ease-out ${() =>
  animationTimeMs / 4}ms,
        opacity ${() => animationTimeMs}ms ease-out ${() =>
  animationTimeMs / 4}ms;
      ${props =>
        props.showAnimation
          ? `
            transform: translateY(-50px);
          `
          : ''};

      &.ReactModal__Content--after-open {
        opacity: 1;
        ${props =>
          props.showAnimation
            ? `
              transform: translateY(0);
            `
            : ''};

        &.ReactModal__Content--before-close {
          opacity: 0;
          ${props =>
            props.showAnimation
              ? `
                transform: translateY(-50px);
              `
              : ''};
        }
      }

      &.small {
        @media (min-width: ${props => props.theme.screenSize.phone}) {
          position: relative;
          margin: ${({ theme }) =>
            getModalMargin(theme.windowHeight, theme.modalHeight)}px auto;
          width: ${modalSize.small};
        }
      }

      &.medium {
        @media (min-width: ${props => props.theme.screenSize.tablet}) {
          position: relative;
          margin: ${({ theme }) =>
            getModalMargin(theme.windowHeight, theme.modalHeight)}px auto;
          width: ${modalSize.medium};
        }
      }

      &.large {
        @media (min-width: ${props => props.theme.screenSize.desktop}) {
          position: relative;
          margin: ${({ theme }) =>
            getModalMargin(theme.windowHeight, theme.modalHeight)}px auto;
          width: ${modalSize.large};
        }
      }
    }
  }
`;

function Modal({
  animation,
  backdrop,
  children,
  escapeExits,
  onEnter,
  onExit,
  onHide,
  show,
  size,
  parentSelector,
  className,
  overlayRef,
  contentRef,
  ...other
}) {
  const ariaId = useUniqueId(other.id);
  const [rootNode, RootNodeLocator] = useRootNodeLocator(document.body);
  const [modalHeight, setModalHeight] = useState(300);
  const [shouldShow, setShouldShow] = useState(show);
  const [windowHeight, setWindowHeight] = useState(window.innerHeight);
  const modalRef = useRef(null);
  const innerContentRef = useRef(null);
  const callRef = (ref, element) => {
    if (ref) {
      if (typeof ref === 'function') {
        ref(element);
      } else {
        // eslint-disable-next-line no-param-reassign
        ref.current = element;
      }
    }
  };
  const setContentRef = useCallback(contentElement => {
    callRef(contentRef, contentElement);
    innerContentRef.current = contentElement;
  });

  const modalHeightRef = useCallback(modalElement => {
    callRef(overlayRef, modalElement);
    let newHeight = 0;
    if (modalElement) {
      modalRef.current = modalElement;
      newHeight = modalElement.offsetHeight;
    }
    if (innerContentRef.current) {
      const contRefHeight = innerContentRef.current.offsetHeight;
      if (contRefHeight < newHeight) newHeight = contRefHeight;
    }
    setModalHeight(newHeight);
  });

  const modalParentSelector =
    parentSelector || useCallback(() => rootNode, [rootNode]);

  useEffect(() => {
    if (!animation || show) {
      setShouldShow(show);
      return noop;
    }

    let mounted = true;
    setTimeout(() => {
      if (!mounted) return;

      setShouldShow(false);
    }, animationTimeMs);

    return () => {
      mounted = false;
    };
  }, [show, animation]);

  useEffect(() => {
    const setHeight = debounce(() => setWindowHeight(window.innerHeight), 100);
    window.addEventListener('resize', setHeight);
    return () => window.removeEventListener('resize', setHeight);
  }, []);

  useEffect(() => {
    if (modalRef.current && modalRef.current.scroll) {
      modalRef.current.scroll(0, 0);
    }
  }, [modalRef.current]);

  useEffect(() => {
    if (rootNode === document.body) return;

    const targetNode = rootNode.querySelector(':host > *');

    if (shouldShow) {
      targetNode.className += openClass;
    } else {
      targetNode.className = targetNode.className.replace(openClass, '');
    }
  }, [shouldShow, rootNode]);

  const shouldCloseOnOverlayClick = backdrop !== 'static' && backdrop;

  return (
    <ThemeProvider theme={{ modalHeight, windowHeight }}>
      <RootNodeLocator />
      {shouldShow ? (
        <ModalStyles showAnimation={animation} showBackdrop={backdrop} />
      ) : null}
      <ModalContext.Provider value={{ onHide, ariaId }}>
        <ReactModal
          bodyOpenClassName={openClass}
          className={`${className} ${size} modal-content`}
          overlayClassName="background-overlay"
          closeTimeoutMS={animation ? animationTimeMs : null}
          isOpen={show}
          aria={{
            labelledby: ariaId
          }}
          shouldCloseOnOverlayClick={shouldCloseOnOverlayClick}
          onRequestClose={onHide}
          onAfterOpen={onEnter}
          onAfterClose={onExit}
          shouldCloseOnEsc={escapeExits}
          parentSelector={modalParentSelector}
          contentRef={setContentRef}
          overlayRef={modalHeightRef}
          {...other}
        >
          {children}
        </ReactModal>
      </ModalContext.Provider>
    </ThemeProvider>
  );
}

Modal.propTypes = {
  /** Open and close the Modal with transitions. */
  animation: PropTypes.bool,
  /**
   * Include a backdrop component. Specify 'static' for a backdrop that doesn't
   * trigger an "onHide" when clicked.
   */
  backdrop: PropTypes.oneOf(['static', true, false]),
  /**
   * Usually contains a Modal.Header, Modal.Body, and Modal.Footer
   * but can contain any content
   */
  children: PropTypes.any,
  /** Set whether the Escape key exits the modal */
  escapeExits: PropTypes.bool,
  /** Callback fired when the Modal transitions in */
  onEnter: PropTypes.func,
  /** Callback fired when the modal transitions out */
  onExit: PropTypes.func,
  /**
   * A callback fired when the header closeButton or non-static backdrop is
   * clicked. Required if either are specified.
   */
  onHide: PropTypes.func,
  /** When `true` The modal will show itself. */
  show: PropTypes.bool,
  /** Sets the size of the modal */
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  /** Selects the parent */
  parentSelector: PropTypes.func,
  className: PropTypes.string,
  overlayRef: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({ current: PropTypes.any })
  ]),
  contentRef: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({ current: PropTypes.any })
  ])
};

Modal.defaultProps = {
  animation: true,
  backdrop: true,
  escapeExits: true,
  onEnter: noop,
  onExit: noop,
  onHide: noop,
  show: false,
  size: 'medium',
  children: undefined,
  parentSelector: null,
  className: null,
  overlayRef: null,
  contentRef: null
};

Modal.Header = Header;
Modal.Body = Body;
Modal.Footer = Footer;

export default Modal;
<commit_msg>Fix: really fixing modals for Web Components<commit_after>import React, { useCallback, useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import { noop, debounce } from 'lodash';
import ReactModal from 'react-modal';
import tinycolor from 'tinycolor2';

import useUniqueId from '../../util/useUniqueId';
import { useRootNodeLocator } from '../../util/useRootNode';
import { ModalContext } from './ModalContext';
import Header from './ModalHeader';
import Body from './ModalBody';
import Footer from './ModalFooter';

const modalSize = {
  small: '300px',
  medium: '600px',
  large: '900px'
};

const animationTimeMs = 300;

const getModalMargin = (windowHeight, modalHeight) => {
  const fullMargin = windowHeight - modalHeight;
  const thirdTopMargin = fullMargin / 3;
  return Math.max(thirdTopMargin, 50);
};

const ModalStyles = createGlobalStyle`
  .${({ theme }) => theme.portalClassName} {
    .background-overlay {
      bottom: 0;
      background-color: ${props => {
        const color = tinycolor(props.theme.colors.gray9);
        color.setAlpha(0);
        return color.toRgbString();
      }};

      left: 0;
      max-height: 100%;
      overflow-y: auto;
      position: fixed;
      right: 0;
      top: 0;
      transition: background-color ${() => animationTimeMs / 2}ms linear;
      z-index: 1030;
      -webkit-overflow-scrolling: touch;

      &.ReactModal__Overlay--after-open {
        ${props => {
          if (!props.showBackdrop) return '';

          const color = tinycolor(props.theme.colors.gray9);
          color.setAlpha(0.5);
          return `background-color: ${color.toRgbString()};`;
        }}

        &.ReactModal__Overlay--before-close {
          background-color: ${props => {
            const color = tinycolor(props.theme.colors.gray9);
            color.setAlpha(0);
            return color.toRgbString();
          }};
        }
      }
    }

    .modal-content {
      background-clip: padding-box;
      background-color: ${props => props.theme.colors.white};
      border-radius: 3px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
      font-family: 'Source Sans Pro', 'Segoe UI', Segoe, Calibri, Tahoma, sans-serif;
      font-size: ${props => props.theme.font.baseFontSize};
      margin: 0.5rem;
      outline: 0;
      opacity: 0;
      position: absolute;
      left: 0;
      transform: translateY(0);
      transition:
        transform ${() => animationTimeMs}ms ease-out ${() =>
  animationTimeMs / 4}ms,
        opacity ${() => animationTimeMs}ms ease-out ${() =>
  animationTimeMs / 4}ms;
      ${props =>
        props.showAnimation
          ? `
            transform: translateY(-50px);
          `
          : ''};

      &.ReactModal__Content--after-open {
        opacity: 1;
        ${props =>
          props.showAnimation
            ? `
              transform: translateY(0);
            `
            : ''};

        &.ReactModal__Content--before-close {
          opacity: 0;
          ${props =>
            props.showAnimation
              ? `
                transform: translateY(-50px);
              `
              : ''};
        }
      }

      &.small {
        @media (min-width: ${props => props.theme.screenSize.phone}) {
          position: relative;
          margin: ${({ theme }) =>
            getModalMargin(theme.windowHeight, theme.modalHeight)}px auto;
          width: ${modalSize.small};
        }
      }

      &.medium {
        @media (min-width: ${props => props.theme.screenSize.tablet}) {
          position: relative;
          margin: ${({ theme }) =>
            getModalMargin(theme.windowHeight, theme.modalHeight)}px auto;
          width: ${modalSize.medium};
        }
      }

      &.large {
        @media (min-width: ${props => props.theme.screenSize.desktop}) {
          position: relative;
          margin: ${({ theme }) =>
            getModalMargin(theme.windowHeight, theme.modalHeight)}px auto;
          width: ${modalSize.large};
        }
      }
    }
  }
`;

function Modal({
  animation,
  backdrop,
  children,
  escapeExits,
  onEnter,
  onExit,
  onHide,
  show,
  size,
  parentSelector,
  className,
  overlayRef,
  contentRef,
  ...other
}) {
  const ariaId = useUniqueId(other.id);
  const portalClassName = `ReactModalPortal-${useUniqueId()}`;
  const [rootNode, RootNodeLocator] = useRootNodeLocator(document.body);
  const [modalHeight, setModalHeight] = useState(300);
  const [shouldShow, setShouldShow] = useState(show);
  const [windowHeight, setWindowHeight] = useState(window.innerHeight);
  const modalRef = useRef(null);
  const innerContentRef = useRef(null);
  const callRef = (ref, element) => {
    if (ref) {
      if (typeof ref === 'function') {
        ref(element);
      } else {
        // eslint-disable-next-line no-param-reassign
        ref.current = element;
      }
    }
  };
  const setContentRef = useCallback(contentElement => {
    callRef(contentRef, contentElement);
    innerContentRef.current = contentElement;
  });

  const modalHeightRef = useCallback(modalElement => {
    callRef(overlayRef, modalElement);
    let newHeight = 0;
    if (modalElement) {
      modalRef.current = modalElement;
      newHeight = modalElement.offsetHeight;
    }
    if (innerContentRef.current) {
      const contRefHeight = innerContentRef.current.offsetHeight;
      if (contRefHeight < newHeight) newHeight = contRefHeight;
    }
    setModalHeight(newHeight);
  });

  const modalParentSelector =
    parentSelector || useCallback(() => rootNode, [rootNode]);

  useEffect(() => {
    if (!animation || show) {
      setShouldShow(show);
      return noop;
    }

    let mounted = true;
    setTimeout(() => {
      if (!mounted) return;

      setShouldShow(false);
    }, animationTimeMs);

    return () => {
      mounted = false;
    };
  }, [show, animation]);

  useEffect(() => {
    const setHeight = debounce(() => setWindowHeight(window.innerHeight), 100);
    window.addEventListener('resize', setHeight);
    return () => window.removeEventListener('resize', setHeight);
  }, []);

  useEffect(() => {
    if (modalRef.current && modalRef.current.scroll) {
      modalRef.current.scroll(0, 0);
    }
  }, [modalRef.current]);

  useEffect(() => {
    const newStyle = 'overflow: hidden;';
    const currentStyle = document.body.getAttribute('style');
    if (shouldShow) {
      document.body.setAttribute('style', `${currentStyle} ${newStyle}`);
    } else {
      document.body.setAttribute('style', currentStyle.replace(newStyle, ''));
    }
  }, [shouldShow]);

  const shouldCloseOnOverlayClick = backdrop !== 'static' && backdrop;

  return (
    <ThemeProvider theme={{ modalHeight, windowHeight, portalClassName }}>
      <RootNodeLocator />
      {shouldShow ? (
        <ModalStyles showAnimation={animation} showBackdrop={backdrop} />
      ) : null}
      <ModalContext.Provider value={{ onHide, ariaId }}>
        <ReactModal
          portalClassName={portalClassName}
          className={`${className} ${size} modal-content`}
          overlayClassName="background-overlay"
          closeTimeoutMS={animation ? animationTimeMs : null}
          isOpen={show}
          aria={{
            labelledby: ariaId
          }}
          shouldCloseOnOverlayClick={shouldCloseOnOverlayClick}
          onRequestClose={onHide}
          onAfterOpen={onEnter}
          onAfterClose={onExit}
          shouldCloseOnEsc={escapeExits}
          parentSelector={modalParentSelector}
          contentRef={setContentRef}
          overlayRef={modalHeightRef}
          {...other}
        >
          {children}
        </ReactModal>
      </ModalContext.Provider>
    </ThemeProvider>
  );
}

Modal.propTypes = {
  /** Open and close the Modal with transitions. */
  animation: PropTypes.bool,
  /**
   * Include a backdrop component. Specify 'static' for a backdrop that doesn't
   * trigger an "onHide" when clicked.
   */
  backdrop: PropTypes.oneOf(['static', true, false]),
  /**
   * Usually contains a Modal.Header, Modal.Body, and Modal.Footer
   * but can contain any content
   */
  children: PropTypes.any,
  /** Set whether the Escape key exits the modal */
  escapeExits: PropTypes.bool,
  /** Callback fired when the Modal transitions in */
  onEnter: PropTypes.func,
  /** Callback fired when the modal transitions out */
  onExit: PropTypes.func,
  /**
   * A callback fired when the header closeButton or non-static backdrop is
   * clicked. Required if either are specified.
   */
  onHide: PropTypes.func,
  /** When `true` The modal will show itself. */
  show: PropTypes.bool,
  /** Sets the size of the modal */
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  /** Selects the parent */
  parentSelector: PropTypes.func,
  className: PropTypes.string,
  overlayRef: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({ current: PropTypes.any })
  ]),
  contentRef: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({ current: PropTypes.any })
  ])
};

Modal.defaultProps = {
  animation: true,
  backdrop: true,
  escapeExits: true,
  onEnter: noop,
  onExit: noop,
  onHide: noop,
  show: false,
  size: 'medium',
  children: undefined,
  parentSelector: null,
  className: null,
  overlayRef: null,
  contentRef: null
};

Modal.Header = Header;
Modal.Body = Body;
Modal.Footer = Footer;

export default Modal;
<|endoftext|>


<commit_before>
var inspection = false
var state = 0
var chronoState = {
  STOPPED: 0,
  HOLDING_INSPECTION: 1,
  INSPECTION: 2,
  HOLDING_SOLVE: 3,
  SOLVING: 4,
  SOLVED: 5
};

function Input() {

  document.body.addEventListener("keyup", keyUp);
  document.body.addEventListener("keydown", keyDown);
  document.getElementById('toucharea').addEventListener('touchstart', keyDown);
  document.addEventListener('touchstart', screenTouchDown);
  document.getElementById('toucharea').addEventListener('touchend', keyUp);
  document.addEventListener('touchend', screenTouchUp);

  function startSolve() {
    chronoReset();
    if (state == chronoState.HOLDING_INSPECTION) {
      chronoStart();
      state = chronoState.INSPECTION
    } else if (state == chronoState.HOLDING_SOLVE) {
      chronoStop();
      chronoStart();
      state = chronoState.SOLVING
    }
    MainLayout.changeChronoColor(state)
    MainLayout.hideAll()
  }

  function screenTouchDown(event) {
    if (state == chronoState.SOLVING || state == chronoState.INSPECTION) {
      keyDown(event);
    }
  }

  function screenTouchUp(event) {
    if (state == chronoState.HOLDING_SOLVE || state == chronoState.HOLDING_INSPECTION) {
      keyUp(event);
    }
  }

  function stop() {
    chronoStop();
    state = chronoState.SOLVED
    Data.add();
    Data.refresh();
    MainLayout.scrollHistoryDown();
    MainLayout.showAll()
  }

  function keyUp(event) { // Starting at SPACE released

    if ( $('#newSessionText').is(":visible") || $('#newTimeText').is(":visible") ) { // entering new solve
      return
    }
    if (event.which == 32 || event.which == 0) { // SPACE or TOUCH
      if (state == chronoState.SOLVED) state = chronoState.STOPPED;
      else startSolve()
    }
  }

  function keyDown(event) { // Stoping at SPACE pressed
    if (state == 1 || state == 3 || state == 5) return; // don't repeat when holding down
    if ($('#newSessionText').is(":visible") || $('#newTimeText').is(":visible")) return; // entering new solve
    if (event.which == 32 || event.which == 0) { // SPACE or TOUCH
      if (state == chronoState.STOPPED) {
        state = inspection ? chronoState.HOLDING_INSPECTION : chronoState.HOLDING_SOLVE
        MainLayout.changeChronoColor(state)
      } else if (state == chronoState.INSPECTION) {
        state = chronoState.HOLDING_SOLVE
        MainLayout.changeChronoColor(state)
      } else {
        stop()
        if (event.which == 0) {        // when the chrono is stopped with touch, keyup event is not called
          state = chronoState.STOPPED; // so this fixes it
      }
    }
  }
}
<commit_msg>missing }<commit_after>
var inspection = false
var state = 0
var chronoState = {
  STOPPED: 0,
  HOLDING_INSPECTION: 1,
  INSPECTION: 2,
  HOLDING_SOLVE: 3,
  SOLVING: 4,
  SOLVED: 5
};

function Input() {

  document.body.addEventListener("keyup", keyUp);
  document.body.addEventListener("keydown", keyDown);
  document.getElementById('toucharea').addEventListener('touchstart', keyDown);
  document.addEventListener('touchstart', screenTouchDown);
  document.getElementById('toucharea').addEventListener('touchend', keyUp);
  document.addEventListener('touchend', screenTouchUp);

  function startSolve() {
    chronoReset();
    if (state == chronoState.HOLDING_INSPECTION) {
      chronoStart();
      state = chronoState.INSPECTION
    } else if (state == chronoState.HOLDING_SOLVE) {
      chronoStop();
      chronoStart();
      state = chronoState.SOLVING
    }
    MainLayout.changeChronoColor(state)
    MainLayout.hideAll()
  }

  function screenTouchDown(event) {
    if (state == chronoState.SOLVING || state == chronoState.INSPECTION) {
      keyDown(event);
    }
  }

  function screenTouchUp(event) {
    if (state == chronoState.HOLDING_SOLVE || state == chronoState.HOLDING_INSPECTION) {
      keyUp(event);
    }
  }

  function stop() {
    chronoStop();
    state = chronoState.SOLVED
    Data.add();
    Data.refresh();
    MainLayout.scrollHistoryDown();
    MainLayout.showAll()
  }

  function keyUp(event) { // Starting at SPACE released

    if ( $('#newSessionText').is(":visible") || $('#newTimeText').is(":visible") ) { // entering new solve
      return
    }
    if (event.which == 32 || event.which == 0) { // SPACE or TOUCH
      if (state == chronoState.SOLVED) state = chronoState.STOPPED;
      else startSolve()
    }
  }

  function keyDown(event) { // Stoping at SPACE pressed
    if (state == 1 || state == 3 || state == 5) return; // don't repeat when holding down
    if ($('#newSessionText').is(":visible") || $('#newTimeText').is(":visible")) return; // entering new solve
    if (event.which == 32 || event.which == 0) { // SPACE or TOUCH
      if (state == chronoState.STOPPED) {
        state = inspection ? chronoState.HOLDING_INSPECTION : chronoState.HOLDING_SOLVE
        MainLayout.changeChronoColor(state)
      } else if (state == chronoState.INSPECTION) {
        state = chronoState.HOLDING_SOLVE
        MainLayout.changeChronoColor(state)
      } else {
        stop()
        if (event.which == 0) {        // when the chrono is stopped with touch, keyup event is not called
          state = chronoState.STOPPED; // so this fixes it
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>var b = (function(){
    return{
        print:function(first,second){
            var result = a.add(first,second);

            return result;
        }
    }
})();
<commit_msg>update<commit_after>var b = (function(){
    return{
        print:function(first,second){
            var result = a.add(first,second);

            return result;

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