<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { ConcatSource, RawSource } = require("webpack-sources");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const NormalModule = require("./NormalModule");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const ConcatenatedModule = require("./optimize/ConcatenatedModule");
const { absolutify } = require("./util/identifier");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").DevTool} DevToolOptions */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("./Compiler")} Compiler */

/** @type {WeakMap<Source, Source>} */
const cache = new WeakMap();

const devtoolWarning = new RawSource(`/*
 * ATTENTION: An "eval-source-map" devtool has been used.
 * This devtool is not neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
`);

class EvalSourceMapDevToolPlugin {
	/**
	 * @param {SourceMapDevToolPluginOptions|string} inputOptions Options object
	 */
	constructor(inputOptions) {
		/** @type {SourceMapDevToolPluginOptions} */
		let options;
		if (typeof inputOptions === "string") {
			options = {
				append: inputOptions
			};
		} else {
			options = inputOptions;
		}
		this.sourceMapComment =
			options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]";
		this.moduleFilenameTemplate =
			options.moduleFilenameTemplate ||
			"webpack://[namespace]/[resource-path]?[hash]";
		this.namespace = options.namespace || "";
		this.options = options;
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const options = this.options;
		compiler.hooks.compilation.tap(
			"EvalSourceMapDevToolPlugin",
			compilation => {
				const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
				new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
				const matchModule = ModuleFilenameHelpers.matchObject.bind(
					ModuleFilenameHelpers,
					options
				);
				hooks.renderModuleContent.tap(
					"EvalSourceMapDevToolPlugin",
					(source, m, { runtimeTemplate, chunkGraph }) => {
						const cachedSource = cache.get(source);
						if (cachedSource !== undefined) {
							return cachedSource;
						}

						if (m instanceof NormalModule) {
							const module = /** @type {NormalModule} */ (m);
							if (!matchModule(module.resource)) {
								return source;
							}
						} else if (m instanceof ConcatenatedModule) {
							const concatModule = /** @type {ConcatenatedModule} */ (m);
							if (concatModule.rootModule instanceof NormalModule) {
								const module = /** @type {NormalModule} */ (concatModule.rootModule);
								if (!matchModule(module.resource)) {
									return source;
								}
							} else {
								return source;
							}
						} else {
							return source;
						}

						/** @type {{ [key: string]: TODO; }} */
						let sourceMap;
						let content;
						if (source.sourceAndMap) {
							const sourceAndMap = source.sourceAndMap(options);
							sourceMap = sourceAndMap.map;
							content = sourceAndMap.source;
						} else {
							sourceMap = source.map(options);
							content = source.source();
						}
						if (!sourceMap) {
							return source;
						}

						// Clone (flat) the sourcemap to ensure that the mutations below do not persist.
						sourceMap = { ...sourceMap };
						const context = compiler.options.context;
						const root = compiler.root;
						const modules = sourceMap.sources.map(source => {
							if (!source.startsWith("webpack://")) return source;
							source = absolutify(context, source.slice(10), root);
							const module = compilation.findModule(source);
							return module || source;
						});
						let moduleFilenames = modules.map(module => {
							return ModuleFilenameHelpers.createFilename(
								module,
								{
									moduleFilenameTemplate: this.moduleFilenameTemplate,
									namespace: this.namespace
								},
								{
									requestShortener: runtimeTemplate.requestShortener,
									chunkGraph
								}
							);
						});
						moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(
							moduleFilenames,
							(filename, i, n) => {
								for (let j = 0; j < n; j++) filename += "*";
								return filename;
							}
						);
						sourceMap.sources = moduleFilenames;
						sourceMap.sourceRoot = options.sourceRoot || "";
						const moduleId = chunkGraph.getModuleId(m);
						sourceMap.file = `${moduleId}.js`;

						const footer =
							this.sourceMapComment.replace(
								/\[url\]/g,
								`data:application/json;charset=utf-8;base64,${Buffer.from(
									JSON.stringify(sourceMap),
									"utf8"
								).toString("base64")}`
							) + `\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug

						const evalSource = new RawSource(
							`eval(${JSON.stringify(content + footer)});`
						);

						cache.set(source, evalSource);

						return evalSource;
					}
				);
				hooks.render.tap(
					"EvalSourceMapDevToolPlugin",
					source => new ConcatSource(devtoolWarning, source)
				);
				hooks.chunkHash.tap("EvalSourceMapDevToolPlugin", (chunk, hash) => {
					hash.update("EvalSourceMapDevToolPlugin");
					hash.update("2");
				});
			}
		);
	}
}

module.exports = EvalSourceMapDevToolPlugin;
<commit_msg>add caching to eval-source-map<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { ConcatSource, RawSource } = require("webpack-sources");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const NormalModule = require("./NormalModule");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const ConcatenatedModule = require("./optimize/ConcatenatedModule");
const { absolutify } = require("./util/identifier");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").DevTool} DevToolOptions */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("./Compiler")} Compiler */

/** @type {WeakMap<Source, Source>} */
const cache = new WeakMap();

const devtoolWarning = new RawSource(`/*
 * ATTENTION: An "eval-source-map" devtool has been used.
 * This devtool is not neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
`);

class EvalSourceMapDevToolPlugin {
	/**
	 * @param {SourceMapDevToolPluginOptions|string} inputOptions Options object
	 */
	constructor(inputOptions) {
		/** @type {SourceMapDevToolPluginOptions} */
		let options;
		if (typeof inputOptions === "string") {
			options = {
				append: inputOptions
			};
		} else {
			options = inputOptions;
		}
		this.sourceMapComment =
			options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]";
		this.moduleFilenameTemplate =
			options.moduleFilenameTemplate ||
			"webpack://[namespace]/[resource-path]?[hash]";
		this.namespace = options.namespace || "";
		this.options = options;
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const options = this.options;
		compiler.hooks.compilation.tap(
			"EvalSourceMapDevToolPlugin",
			compilation => {
				const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
				new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
				const matchModule = ModuleFilenameHelpers.matchObject.bind(
					ModuleFilenameHelpers,
					options
				);
				hooks.renderModuleContent.tap(
					"EvalSourceMapDevToolPlugin",
					(source, m, { runtimeTemplate, chunkGraph }) => {
						const cachedSource = cache.get(source);
						if (cachedSource !== undefined) {
							return cachedSource;
						}

						const result = r => {
							cache.set(source, r);
							return r;
						};

						if (m instanceof NormalModule) {
							const module = /** @type {NormalModule} */ (m);
							if (!matchModule(module.resource)) {
								return result(source);
							}
						} else if (m instanceof ConcatenatedModule) {
							const concatModule = /** @type {ConcatenatedModule} */ (m);
							if (concatModule.rootModule instanceof NormalModule) {
								const module = /** @type {NormalModule} */ (concatModule.rootModule);
								if (!matchModule(module.resource)) {
									return result(source);
								}
							} else {
								return result(source);
							}
						} else {
							return result(source);
						}

						/** @type {{ [key: string]: TODO; }} */
						let sourceMap;
						let content;
						if (source.sourceAndMap) {
							const sourceAndMap = source.sourceAndMap(options);
							sourceMap = sourceAndMap.map;
							content = sourceAndMap.source;
						} else {
							sourceMap = source.map(options);
							content = source.source();
						}
						if (!sourceMap) {
							return result(source);
						}

						// Clone (flat) the sourcemap to ensure that the mutations below do not persist.
						sourceMap = { ...sourceMap };
						const context = compiler.options.context;
						const root = compiler.root;
						const modules = sourceMap.sources.map(source => {
							if (!source.startsWith("webpack://")) return source;
							source = absolutify(context, source.slice(10), root);
							const module = compilation.findModule(source);
							return module || source;
						});
						let moduleFilenames = modules.map(module => {
							return ModuleFilenameHelpers.createFilename(
								module,
								{
									moduleFilenameTemplate: this.moduleFilenameTemplate,
									namespace: this.namespace
								},
								{
									requestShortener: runtimeTemplate.requestShortener,
									chunkGraph
								}
							);
						});
						moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(
							moduleFilenames,
							(filename, i, n) => {
								for (let j = 0; j < n; j++) filename += "*";
								return filename;
							}
						);
						sourceMap.sources = moduleFilenames;
						sourceMap.sourceRoot = options.sourceRoot || "";
						const moduleId = chunkGraph.getModuleId(m);
						sourceMap.file = `${moduleId}.js`;

						const footer =
							this.sourceMapComment.replace(
								/\[url\]/g,
								`data:application/json;charset=utf-8;base64,${Buffer.from(
									JSON.stringify(sourceMap),
									"utf8"
								).toString("base64")}`
							) + `\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug

						return result(
							new RawSource(`eval(${JSON.stringify(content + footer)});`)
						);
					}
				);
				hooks.render.tap(
					"EvalSourceMapDevToolPlugin",
					source => new ConcatSource(devtoolWarning, source)
				);
				hooks.chunkHash.tap("EvalSourceMapDevToolPlugin", (chunk, hash) => {
					hash.update("EvalSourceMapDevToolPlugin");
					hash.update("2");
				});
			}
		);
	}
}

module.exports = EvalSourceMapDevToolPlugin;
<|endoftext|>


<commit_before>function toBlurArray(player) {
  return player.blurs && player.blurs.bits ? player.blurs.bits.split('') : [];
}
lichess.advantageChart = function (data, trans, el) {
  lichess.loadScript('javascripts/chart/common.js').then(function () {
    lichess.loadScript('javascripts/chart/division.js').then(function () {
      lichess.chartCommon('highchart').then(function () {
        lichess.advantageChart.update = function (d) {
          el.highcharts && el.highcharts.series[0].setData(makeSerieData(d));
        };

        var blurs = [toBlurArray(data.player), toBlurArray(data.opponent)];
        if (data.player.color === 'white') blurs.reverse();

        var makeSerieData = function (d) {
          var partial = !d.analysis || d.analysis.partial;
          return d.treeParts.slice(1).map(function (node) {
            var color = node.ply & 1,
              cp;

            if (node.eval && node.eval.mate) {
              cp = node.eval.mate > 0 ? Infinity : -Infinity;
            } else if (node.san.includes('#')) {
              cp = color === 1 ? Infinity : -Infinity;
              if (d.game.variant.key === 'antichess') cp = -cp;
            } else if (node.eval && typeof node.eval.cp !== 'undefined') {
              cp = node.eval.cp;
            } else
              return {
                y: null,
              };

            var turn = Math.floor((node.ply - 1) / 2) + 1;
            var dots = color === 1 ? '.' : '...';
            var point = {
              name: turn + dots + ' ' + node.san,
              y: 2 / (1 + Math.exp(-0.004 * cp)) - 1,
            };
            if (!partial && blurs[color].shift() === '1') {
              point.marker = {
                symbol: 'square',
                radius: 3,
                lineWidth: '1px',
                lineColor: '#d85000',
                fillColor: color ? '#fff' : '#333',
              };
              point.name += ' [blur]';
            }
            return point;
          });
        };

        var disabled = {
          enabled: false,
        };
        var noText = {
          text: null,
        };
        var serieData = makeSerieData(data);
        el.highcharts = Highcharts.chart(el, {
          credits: disabled,
          legend: disabled,
          series: [
            {
              name: trans('advantage'),
              data: serieData,
            },
          ],
          chart: {
            type: 'area',
            spacing: [3, 0, 3, 0],
            animation: false,
          },
          plotOptions: {
            series: {
              animation: false,
            },
            area: {
              fillColor: Highcharts.theme.lichess.area.white,
              negativeFillColor: Highcharts.theme.lichess.area.black,
              threshold: 0,
              lineWidth: 1,
              color: '#d85000',
              allowPointSelect: true,
              cursor: 'pointer',
              states: {
                hover: {
                  lineWidth: 1,
                },
              },
              events: {
                click: function (event) {
                  if (event.point) {
                    event.point.select();
                    lichess.pubsub.emit('analysis.chart.click', event.point.x);
                  }
                },
              },
              marker: {
                radius: 1,
                states: {
                  hover: {
                    radius: 4,
                    lineColor: '#d85000',
                  },
                  select: {
                    radius: 4,
                    lineColor: '#d85000',
                  },
                },
              },
            },
          },
          tooltip: {
            pointFormatter: function (format) {
              format = format.replace('{series.name}', trans('advantage'));
              var eval = data.treeParts[this.x + 1].eval;
              if (!eval) return;
              else if (eval.mate) return format.replace('{point.y}', '#' + eval.mate);
              else if (typeof eval.cp !== 'undefined') {
                var e = Math.max(Math.min(Math.round(eval.cp / 10) / 10, 99), -99);
                if (e > 0) e = '+' + e;
                return format.replace('{point.y}', e);
              }
            },
          },
          title: noText,
          xAxis: {
            title: noText,
            labels: disabled,
            lineWidth: 0,
            tickWidth: 0,
            plotLines: lichess.divisionLines(data.game.division, trans),
          },
          yAxis: {
            title: noText,
            min: -1.1,
            max: 1.1,
            startOnTick: false,
            endOnTick: false,
            labels: disabled,
            lineWidth: 1,
            gridLineWidth: 0,
            plotLines: [
              {
                color: Highcharts.theme.lichess.text.weak,
                width: 1,
                value: 0,
              },
            ],
          },
        });
        el.highcharts.selectPly = ply => {
          const point = el.highcharts.series[0].data[ply - 1 - data.game.startedAtTurn];
          if (point) point.select(true);
          else el.highcharts.getSelectedPoints().forEach(point => point.select(false));
        };
        lichess.pubsub.emit('analysis.change.trigger');
      });
    });
  });
};
<commit_msg>do not bind name eval<commit_after>function toBlurArray(player) {
  return player.blurs && player.blurs.bits ? player.blurs.bits.split('') : [];
}
lichess.advantageChart = function (data, trans, el) {
  lichess.loadScript('javascripts/chart/common.js').then(function () {
    lichess.loadScript('javascripts/chart/division.js').then(function () {
      lichess.chartCommon('highchart').then(function () {
        lichess.advantageChart.update = function (d) {
          el.highcharts && el.highcharts.series[0].setData(makeSerieData(d));
        };

        var blurs = [toBlurArray(data.player), toBlurArray(data.opponent)];
        if (data.player.color === 'white') blurs.reverse();

        var makeSerieData = function (d) {
          var partial = !d.analysis || d.analysis.partial;
          return d.treeParts.slice(1).map(function (node) {
            var color = node.ply & 1,
              cp;

            if (node.eval && node.eval.mate) {
              cp = node.eval.mate > 0 ? Infinity : -Infinity;
            } else if (node.san.includes('#')) {
              cp = color === 1 ? Infinity : -Infinity;
              if (d.game.variant.key === 'antichess') cp = -cp;
            } else if (node.eval && typeof node.eval.cp !== 'undefined') {
              cp = node.eval.cp;
            } else
              return {
                y: null,
              };

            var turn = Math.floor((node.ply - 1) / 2) + 1;
            var dots = color === 1 ? '.' : '...';
            var point = {
              name: turn + dots + ' ' + node.san,
              y: 2 / (1 + Math.exp(-0.004 * cp)) - 1,
            };
            if (!partial && blurs[color].shift() === '1') {
              point.marker = {
                symbol: 'square',
                radius: 3,
                lineWidth: '1px',
                lineColor: '#d85000',
                fillColor: color ? '#fff' : '#333',
              };
              point.name += ' [blur]';
            }
            return point;
          });
        };

        var disabled = {
          enabled: false,
        };
        var noText = {
          text: null,
        };
        var serieData = makeSerieData(data);
        el.highcharts = Highcharts.chart(el, {
          credits: disabled,
          legend: disabled,
          series: [
            {
              name: trans('advantage'),
              data: serieData,
            },
          ],
          chart: {
            type: 'area',
            spacing: [3, 0, 3, 0],
            animation: false,
          },
          plotOptions: {
            series: {
              animation: false,
            },
            area: {
              fillColor: Highcharts.theme.lichess.area.white,
              negativeFillColor: Highcharts.theme.lichess.area.black,
              threshold: 0,
              lineWidth: 1,
              color: '#d85000',
              allowPointSelect: true,
              cursor: 'pointer',
              states: {
                hover: {
                  lineWidth: 1,
                },
              },
              events: {
                click: function (event) {
                  if (event.point) {
                    event.point.select();
                    lichess.pubsub.emit('analysis.chart.click', event.point.x);
                  }
                },
              },
              marker: {
                radius: 1,
                states: {
                  hover: {
                    radius: 4,
                    lineColor: '#d85000',
                  },
                  select: {
                    radius: 4,
                    lineColor: '#d85000',
                  },
                },
              },
            },
          },
          tooltip: {
            pointFormatter: function (format) {
              format = format.replace('{series.name}', trans('advantage'));
              const ev = data.treeParts[this.x + 1].eval;
              if (!ev) return;
              else if (ev.mate) return format.replace('{point.y}', '#' + ev.mate);
              else if (typeof ev.cp !== 'undefined') {
                var e = Math.max(Math.min(Math.round(ev.cp / 10) / 10, 99), -99);
                if (e > 0) e = '+' + e;
                return format.replace('{point.y}', e);
              }
            },
          },
          title: noText,
          xAxis: {
            title: noText,
            labels: disabled,
            lineWidth: 0,
            tickWidth: 0,
            plotLines: lichess.divisionLines(data.game.division, trans),
          },
          yAxis: {
            title: noText,
            min: -1.1,
            max: 1.1,
            startOnTick: false,
            endOnTick: false,
            labels: disabled,
            lineWidth: 1,
            gridLineWidth: 0,
            plotLines: [
              {
                color: Highcharts.theme.lichess.text.weak,
                width: 1,
                value: 0,
              },
            ],
          },
        });
        el.highcharts.selectPly = ply => {
          const point = el.highcharts.series[0].data[ply - 1 - data.game.startedAtTurn];
          if (point) point.select(true);
          else el.highcharts.getSelectedPoints().forEach(point => point.select(false));
        };
        lichess.pubsub.emit('analysis.change.trigger');
      });
    });
  });
};
<|endoftext|>


<commit_before>Ext.define('Slate.model.progress.SectionInterimReport', {
    extend: 'Ext.data.Model',
    requires: [
        'Slate.proxy.Records',
        'Ext.data.identifier.Negative'
    ],

    idProperty: 'ID',
    identifier: 'negative',

    fields: [
        {
            name: 'ID',
            type: 'int',
            allowNull: true
        },
        {
            name: 'Class',
            type: 'string',
            defaultValue: 'Slate\\Progress\\SectionInterimReport'
        },
        {
            name: 'Created',
            type: 'date',
            dateFormat: 'timestamp',
            allowNull: true,
            persist: false
        },
        {
            name: 'CreatorID',
            type: 'int',
            allowNull: true,
            persist: false
        },
        {
            name: 'Modified',
            type: 'date',
            dateFormat: 'timestamp',
            allowNull: true,
            persist: false
        },
        {
            name: 'ModifierID',
            type: 'int',
            allowNull: true,
            persist: false
        },
        {
            name: 'StudentID',
            type: 'int'
        },
        {
            name: 'SectionID',
            type: 'int'
        },
        {
            name: 'TermID',
            type: 'int'
        },
        {
            name: 'Status',
            type: 'string',
            defaultValue: 'draft'
        },
        {
            name: 'Notes',
            type: 'string',
            allowNull: true
        },
        {
            name: 'NotesFormat',
            type: 'string',
            defaultValue: 'markdown'
        },

        // virtual fields
        {
            name: 'StudentFirstName',
            type: 'string',
            allowNull: true,
            mapping: 'Student.FirstName'
        },
        {
            name: 'StudentLastName',
            type: 'string',
            allowNull: true,
            mapping: 'Student.LastName'
        },

        // local-only fileds
        {
            name: 'student',
            persist: false
        },
        {
            name: 'section',
            persist: false
        },
        {
            name: 'term',
            persist: false
        }
    ],

    proxy: {
        type: 'slate-records',
        url: '/progress/interims/reports',
        limitParam: null,
        startParam: null
    }
});<commit_msg>Fix typo in comment<commit_after>Ext.define('Slate.model.progress.SectionInterimReport', {
    extend: 'Ext.data.Model',
    requires: [
        'Slate.proxy.Records',
        'Ext.data.identifier.Negative'
    ],

    idProperty: 'ID',
    identifier: 'negative',

    fields: [
        {
            name: 'ID',
            type: 'int',
            allowNull: true
        },
        {
            name: 'Class',
            type: 'string',
            defaultValue: 'Slate\\Progress\\SectionInterimReport'
        },
        {
            name: 'Created',
            type: 'date',
            dateFormat: 'timestamp',
            allowNull: true,
            persist: false
        },
        {
            name: 'CreatorID',
            type: 'int',
            allowNull: true,
            persist: false
        },
        {
            name: 'Modified',
            type: 'date',
            dateFormat: 'timestamp',
            allowNull: true,
            persist: false
        },
        {
            name: 'ModifierID',
            type: 'int',
            allowNull: true,
            persist: false
        },
        {
            name: 'StudentID',
            type: 'int'
        },
        {
            name: 'SectionID',
            type: 'int'
        },
        {
            name: 'TermID',
            type: 'int'
        },
        {
            name: 'Status',
            type: 'string',
            defaultValue: 'draft'
        },
        {
            name: 'Notes',
            type: 'string',
            allowNull: true
        },
        {
            name: 'NotesFormat',
            type: 'string',
            defaultValue: 'markdown'
        },

        // virtual fields
        {
            name: 'StudentFirstName',
            type: 'string',
            allowNull: true,
            mapping: 'Student.FirstName'
        },
        {
            name: 'StudentLastName',
            type: 'string',
            allowNull: true,
            mapping: 'Student.LastName'
        },

        // local-only fields
        {
            name: 'student',
            persist: false
        },
        {
            name: 'section',
            persist: false
        },
        {
            name: 'term',
            persist: false
        }
    ],

    proxy: {
        type: 'slate-records',
        url: '/progress/interims/reports',
        limitParam: null,
        startParam: null
    }
});<|endoftext|>


<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

var extensions;
var modules;
var tmpl;
var urlparser = require('./../modules/urlparser');
var urlVars = urlparser.urlVars;
var backboneEvents;

const semver = require('semver');
require("bootstrap");

module.exports = {

    /**
     *
     * @param o
     * @returns {exports}
     */
    set: function (o) {
        modules = o;
        backboneEvents = o.backboneEvents;
        return this;
    },

    /**
     *
     */
    init: function () {
        var me = this, configFile, stop = false;

        var loadConfig = function () {
            $.getJSON("/api/config/" + urlparser.db + "/" + configFile, function (data) {
                window.vidiConfig.brandName = data.brandName ? data.brandName : window.vidiConfig.brandName;
                window.vidiConfig.baseLayers = data.baseLayers ? data.baseLayers : window.vidiConfig.baseLayers;
                window.vidiConfig.enabledExtensions = data.enabledExtensions ? data.enabledExtensions : window.vidiConfig.enabledExtensions;
                window.vidiConfig.searchConfig = data.searchConfig ? data.searchConfig : window.vidiConfig.searchConfig;
                window.vidiConfig.aboutBox = data.aboutBox ? data.aboutBox : window.vidiConfig.aboutBox;
                window.vidiConfig.enabledSearch = data.enabledSearch ? data.enabledSearch : window.vidiConfig.enabledSearch;
                window.vidiConfig.schemata = data.schemata ? data.schemata : window.vidiConfig.schemata;
                window.vidiConfig.template = data.template ? data.template : window.vidiConfig.template;
                window.vidiConfig.enabledPrints = data.enabledPrints ? data.enabledPrints : window.vidiConfig.enabledPrints;
                window.vidiConfig.activateMainTab = data.activateMainTab ? data.activateMainTab : window.vidiConfig.activateMainTab;
                window.vidiConfig.extensionConfig = data.extensionConfig ? data.extensionConfig : window.vidiConfig.extensionConfig;
                window.vidiConfig.singleTiled = data.singleTiled ? data.singleTiled : window.vidiConfig.singleTiled;
                window.vidiConfig.doNotCloseLoadScreen = data.doNotCloseLoadScreen ? data.doNotCloseLoadScreen : window.vidiConfig.doNotCloseLoadScreen;
            }).fail(function () {
                console.log("Could not load: " + configFile);

                if (stop) {
                    me.render();
                    return;
                }

                if (window.vidiConfig.defaultConfig) {
                    configFile = window.vidiConfig.defaultConfig;
                    stop = true;
                    loadConfig();
                } else {
                    me.render();
                }
            }).done(function () {
                $.getJSON(`/app/${urlparser.db}/public/version.json`, function (data) {
                    window.vidiConfig.appVersion = data.version;
                }).fail(function () {
                    console.error(`Unable to detect the current application version`);
                }).done(function () {
                    me.render();
                });
            });
        };

        if (urlVars.config) {
            configFile = urlVars.config;
        } else if (window.vidiConfig.autoLoadingConfig) {
            configFile = urlparser.db + ".json";
        } else if (window.vidiConfig.defaultConfig) {
            configFile = window.vidiConfig.defaultConfig;
        }

        if (configFile) {
            loadConfig();
        } else {
            me.render();
        }

    },

    /**
     *
     */
    render: function () {
        var me = this;

        // Render template and set some styling
        // ====================================

        if (typeof window.vidiConfig.template === "undefined") {
            tmpl = "default.tmpl";
        } else {
            tmpl = window.vidiConfig.template;
        }

        // Check if template is set in URL vars
        // ====================================

        if (typeof urlVars.tmpl !== "undefined") {
            var par = urlVars.tmpl.split("#");
            if (par.length > 1) {
                par.pop();
            }
            tmpl = par.join();
        }

        // If px and py is provided for print templates,
        // add the values to the dict before rendering
        // =============================================

        if (urlVars.px && urlVars.py) {
            gc2i18n.dict.printWidth = urlVars.px + "px";
            gc2i18n.dict.printHeight = urlVars.py + "px";
            gc2i18n.dict.printDataTime = decodeURIComponent(urlVars.td); // TODO typo
            gc2i18n.dict.printDateTime = decodeURIComponent(urlVars.td);
            gc2i18n.dict.printDate = decodeURIComponent(urlVars.d);
            window.vidiTimeout = 1000;
        } else {
            window.vidiTimeout = 0;
        }

        if (urlVars.l) {
            gc2i18n.dict._showLegend = urlVars.l;
        }
        gc2i18n.dict._showHeader = urlVars.h || "inline";
        gc2i18n.dict.brandName = window.vidiConfig.brandName;
        gc2i18n.dict.aboutBox = window.vidiConfig.aboutBox;

        // Render the page
        // ===============

        if (typeof Templates[tmpl] !== "undefined") {
            $("#main-container").html(Templates[tmpl].render(gc2i18n.dict));
            console.info("Using pre-processed template: " + tmpl);
            me.startApp();
        } else {
            $.get("/api/template/" + urlparser.db + "/" + tmpl, function (template) {
                var rendered = Mustache.render(template, gc2i18n.dict);
                $("#main-container").html(rendered);
                console.info("Loaded external template: " + tmpl);
                me.startApp();
            }).fail(function () {
                alert("Could not load template: " + tmpl);
            })
        }
    },

    /**
     *
     */
    startApp: function () {

        // Load style sheet
        //===================

        $('<link/>').attr({
            rel: 'stylesheet',
            type: 'text/css',
            href: '/css/styles.css'
        }).appendTo('head');

        // Add the tooltip div
        // ===================

        $("body").append('

');

        // Detect the database and schema
        let splitLocation = window.location.pathname.split(`/`);
        if (splitLocation.length === 4 || splitLocation.length === 5) {
            let database = splitLocation[2];
            let schema = splitLocation[3];
            if (!database || database.length === 0 || !schema || schema.length === 0) {
                console.warn(`Unable to detect current database and schema`);
            } else {
                window.vidiConfig.appDatabase = database;
                window.vidiConfig.appSchema = schema;
            }
        } else {
            console.warn(`Unable to detect current database and schema`);
        }

        // Init the modules
        // ================

        modules.cloud.init();
        modules.state.setExtent();

        // Calling mandatory init method
        [`backboneEvents`, `socketId`, `bindEvent`, `baseLayer`, `infoClick`,
            `advancedInfo`, `draw`, `measurements`, `stateSnapshots`, `print`, `layerTree`].map(name => {
            modules[name].init();
        });

        /**
         * Fetch meta > initialize settings > create layer tree >
         * initialize state > load layers > initialize extensions > finish
         */
        modules.meta.init().then(() => {
            return modules.setting.init();
        }, (error) => {
            console.log(error); // Stacktrace
            alert("Vidi is loaded without schema. Can't set extent or add layers");
            backboneEvents.get().trigger("ready:meta");
        }).then(() => {
            return modules.layerTree.create();
        }).finally(() => {
            modules.state.init().then(() => {

                try {

                // Require search module
                // =====================

                // Hack to compile Glob files. Don´t call this function!
                function ಠ_ಠ() {
                    require('./search/*.js', {glob: true});
                }

                if (typeof vidiConfig.searchModules !== "undefined") {
                    $.each(vidiConfig.searchModules, function (i, v) {
                        modules.search[v] = require('./search/' + v + '.js');
                        modules.search[v].set(modules);
                    });
                    modules.search[window.vidiConfig.enabledSearch].init();
                }

                // Require extensions modules
                // ==========================

                //Hack to compile Glob files. Don´t call this function!
                function ಠ_ಠ() {
                    require('./../../extensions/*/browser/*.js', {glob: true});
                    require('./../../extensions/*/browser/*/*.js', {glob: true});
                }

                if (typeof vidiConfig.extensions !== "undefined" && typeof vidiConfig.extensions.browser !== "undefined") {
                    $.each(vidiConfig.extensions.browser, function (i, v) {
                        modules.extensions[Object.keys(v)[0]] = {};
                        $.each(v[Object.keys(v)[0]], function (n, m) {
                            modules.extensions[Object.keys(v)[0]][m] = require('./../../extensions/' + Object.keys(v)[0] + '/browser/' + m + ".js");
                            modules.extensions[Object.keys(v)[0]][m].set(modules);
                        })
                    });

                    if (typeof window.vidiConfig.enabledExtensions === "object") {
                        $.each(vidiConfig.extensions.browser, function (i, v) {
                            $.each(v[Object.keys(v)[0]], function (n, m) {
                                if (window.vidiConfig.enabledExtensions.indexOf(Object.keys(v)[0]) > -1) {
                                    modules.extensions[Object.keys(v)[0]][m].init();
                                }
                            })
                        });
                    }
                }

                // Init some GUI stuff after modules are loaded
                // ============================================
                $("[data-toggle=tooltip]").tooltip();

                $.material.init();
                touchScroll(".tab-pane");
                touchScroll("#info-modal-body-wrapper");
                $("#loadscreentext").html(__("Loading data"));
                if (window.vidiConfig.activateMainTab) {
                    setTimeout(function () {
                        $('#main-tabs a[href="#' + window.vidiConfig.activateMainTab + '-content"]').tab('show');
                    }, 200);
                }

                $(window).resize(_.debounce(function () {
                    $("#myNavmenu").offcanvas('hide');
                    setTimeout(function () {
                        modules.cloud.get().map.invalidateSize();
                    }, 100);
                }, 0));

                } catch (e) {
                    console.error("Could not perform application initialization", error);
                }
            });
        });

        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/service-worker.bundle.js').then((registration) => {
                console.log('Service worker registration succeeded');
            }).catch(error => {
                console.error(`Unable to register the service worker, please load the application over HTTPS in order to use its full functionality`);
            });
        } else {
            console.warn(`Service workers are not supported in this browser, some features may be unavailable`);
        }

        if (window.localforage) {
            localforage.getItem('appVersion').then(value => {

                if (value === null) {
                    localforage.setItem('appVersion', window.vidiConfig.appVersion).then(() => {
                        console.log(`Versioning: setting new application version (${window.vidiConfig.appVersion})`);
                    }).catch(error => {
                        throw new Error(`Unable to store current application version`);
                    });
                } else {

                    console.log(`### value`, window.vidiConfig.appVersion, semver.valid(window.vidiConfig.appVersion), semver.valid(value));

                    // If two versions are correctly detected
                    if (semver.valid(window.vidiConfig.appVersion) !== null && semver.valid(value) !== null) {
                        if (semver.gt(window.vidiConfig.appVersion, value)) {
                            if (confirm(`Update application to the newest version (current: ${value}, latest: ${window.vidiConfig.appVersion})?`)) {
                                let unregisteringRequests = [];

                                // Unregister service worker
                                navigator.serviceWorker.getRegistrations().then((registrations) => {
                                    for(let registration of registrations) {
                                        console.log(`Versioning: unregistering service worker`, registration);
                                        unregisteringRequests.push(registration.unregister());
                                        registration.unregister();
                                    }
                                });

                                Promise.all(unregisteringRequests).then((values) => {
                                    // Clear caches
                                    caches.keys().then(function(names) {
                                        for (let name of names) {
                                            console.log(`Versioning: clearing cache`, name);
                                            caches.delete(name);
                                        }
                                    });

                                    // Remove current app version
                                    localforage.removeItem('appVersion').then(() => {
                                        location.reload();
                                    });
                                });
                            }
                        } else {
                            console.log('Versioning: new application version is not available');
                        }
                    } else if (semver.valid(value) === null) {
                        console.warn(`Seems like current application version is invalid, resetting it`);
                        localforage.setItem('appVersion', '1.0.0').then(() => {}).catch(error => {
                            throw new Error(`Unable to store current application version`);
                        });
                    }
                }
            });
        } else {
            throw new Error(`localforage is not available`);
        }
    }
};<commit_msg>Using always instead of done<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

var extensions;
var modules;
var tmpl;
var urlparser = require('./../modules/urlparser');
var urlVars = urlparser.urlVars;
var backboneEvents;

const semver = require('semver');
require("bootstrap");

module.exports = {

    /**
     *
     * @param o
     * @returns {exports}
     */
    set: function (o) {
        modules = o;
        backboneEvents = o.backboneEvents;
        return this;
    },

    /**
     *
     */
    init: function () {
        var me = this, configFile, stop = false;

        var loadConfig = function () {
            $.getJSON("/api/config/" + urlparser.db + "/" + configFile, function (data) {
                window.vidiConfig.brandName = data.brandName ? data.brandName : window.vidiConfig.brandName;
                window.vidiConfig.baseLayers = data.baseLayers ? data.baseLayers : window.vidiConfig.baseLayers;
                window.vidiConfig.enabledExtensions = data.enabledExtensions ? data.enabledExtensions : window.vidiConfig.enabledExtensions;
                window.vidiConfig.searchConfig = data.searchConfig ? data.searchConfig : window.vidiConfig.searchConfig;
                window.vidiConfig.aboutBox = data.aboutBox ? data.aboutBox : window.vidiConfig.aboutBox;
                window.vidiConfig.enabledSearch = data.enabledSearch ? data.enabledSearch : window.vidiConfig.enabledSearch;
                window.vidiConfig.schemata = data.schemata ? data.schemata : window.vidiConfig.schemata;
                window.vidiConfig.template = data.template ? data.template : window.vidiConfig.template;
                window.vidiConfig.enabledPrints = data.enabledPrints ? data.enabledPrints : window.vidiConfig.enabledPrints;
                window.vidiConfig.activateMainTab = data.activateMainTab ? data.activateMainTab : window.vidiConfig.activateMainTab;
                window.vidiConfig.extensionConfig = data.extensionConfig ? data.extensionConfig : window.vidiConfig.extensionConfig;
                window.vidiConfig.singleTiled = data.singleTiled ? data.singleTiled : window.vidiConfig.singleTiled;
                window.vidiConfig.doNotCloseLoadScreen = data.doNotCloseLoadScreen ? data.doNotCloseLoadScreen : window.vidiConfig.doNotCloseLoadScreen;
            }).fail(function () {
                console.log("Could not load: " + configFile);

                if (stop) {
                    me.render();
                    return;
                }

                if (window.vidiConfig.defaultConfig) {
                    configFile = window.vidiConfig.defaultConfig;
                    stop = true;
                    loadConfig();
                } else {
                    me.render();
                }
            }).always(function () {
                $.getJSON(`/app/${urlparser.db}/public/version.json`, function (data) {
                    window.vidiConfig.appVersion = data.version;
                }).fail(function () {
                    console.error(`Unable to detect the current application version`);
                }).done(function () {
                    me.render();
                });
            });
        };

        if (urlVars.config) {
            configFile = urlVars.config;
        } else if (window.vidiConfig.autoLoadingConfig) {
            configFile = urlparser.db + ".json";
        } else if (window.vidiConfig.defaultConfig) {
            configFile = window.vidiConfig.defaultConfig;
        }

        if (configFile) {
            loadConfig();
        } else {
            me.render();
        }

    },

    /**
     *
     */
    render: function () {
        var me = this;

        // Render template and set some styling
        // ====================================

        if (typeof window.vidiConfig.template === "undefined") {
            tmpl = "default.tmpl";
        } else {
            tmpl = window.vidiConfig.template;
        }

        // Check if template is set in URL vars
        // ====================================

        if (typeof urlVars.tmpl !== "undefined") {
            var par = urlVars.tmpl.split("#");
            if (par.length > 1) {
                par.pop();
            }
            tmpl = par.join();
        }

        // If px and py is provided for print templates,
        // add the values to the dict before rendering
        // =============================================

        if (urlVars.px && urlVars.py) {
            gc2i18n.dict.printWidth = urlVars.px + "px";
            gc2i18n.dict.printHeight = urlVars.py + "px";
            gc2i18n.dict.printDataTime = decodeURIComponent(urlVars.td); // TODO typo
            gc2i18n.dict.printDateTime = decodeURIComponent(urlVars.td);
            gc2i18n.dict.printDate = decodeURIComponent(urlVars.d);
            window.vidiTimeout = 1000;
        } else {
            window.vidiTimeout = 0;
        }

        if (urlVars.l) {
            gc2i18n.dict._showLegend = urlVars.l;
        }
        gc2i18n.dict._showHeader = urlVars.h || "inline";
        gc2i18n.dict.brandName = window.vidiConfig.brandName;
        gc2i18n.dict.aboutBox = window.vidiConfig.aboutBox;

        // Render the page
        // ===============

        if (typeof Templates[tmpl] !== "undefined") {
            $("#main-container").html(Templates[tmpl].render(gc2i18n.dict));
            console.info("Using pre-processed template: " + tmpl);
            me.startApp();
        } else {
            $.get("/api/template/" + urlparser.db + "/" + tmpl, function (template) {
                var rendered = Mustache.render(template, gc2i18n.dict);
                $("#main-container").html(rendered);
                console.info("Loaded external template: " + tmpl);
                me.startApp();
            }).fail(function () {
                alert("Could not load template: " + tmpl);
            })
        }
    },

    /**
     *
     */
    startApp: function () {

        // Load style sheet
        //===================

        $('<link/>').attr({
            rel: 'stylesheet',
            type: 'text/css',
            href: '/css/styles.css'
        }).appendTo('head');

        // Add the tooltip div
        // ===================

        $("body").append('

');

        // Detect the database and schema
        let splitLocation = window.location.pathname.split(`/`);
        if (splitLocation.length === 4 || splitLocation.length === 5) {
            let database = splitLocation[2];
            let schema = splitLocation[3];
            if (!database || database.length === 0 || !schema || schema.length === 0) {
                console.warn(`Unable to detect current database and schema`);
            } else {
                window.vidiConfig.appDatabase = database;
                window.vidiConfig.appSchema = schema;
            }
        } else {
            console.warn(`Unable to detect current database and schema`);
        }

        // Init the modules
        // ================

        modules.cloud.init();
        modules.state.setExtent();

        // Calling mandatory init method
        [`backboneEvents`, `socketId`, `bindEvent`, `baseLayer`, `infoClick`,
            `advancedInfo`, `draw`, `measurements`, `stateSnapshots`, `print`, `layerTree`].map(name => {
            modules[name].init();
        });

        /**
         * Fetch meta > initialize settings > create layer tree >
         * initialize state > load layers > initialize extensions > finish
         */
        modules.meta.init().then(() => {
            return modules.setting.init();
        }, (error) => {
            console.log(error); // Stacktrace
            alert("Vidi is loaded without schema. Can't set extent or add layers");
            backboneEvents.get().trigger("ready:meta");
        }).then(() => {
            return modules.layerTree.create();
        }).finally(() => {
            modules.state.init().then(() => {

                try {

                // Require search module
                // =====================

                // Hack to compile Glob files. Don´t call this function!
                function ಠ_ಠ() {
                    require('./search/*.js', {glob: true});
                }

                if (typeof vidiConfig.searchModules !== "undefined") {
                    $.each(vidiConfig.searchModules, function (i, v) {
                        modules.search[v] = require('./search/' + v + '.js');
                        modules.search[v].set(modules);
                    });
                    modules.search[window.vidiConfig.enabledSearch].init();
                }

                // Require extensions modules
                // ==========================

                //Hack to compile Glob files. Don´t call this function!
                function ಠ_ಠ() {
                    require('./../../extensions/*/browser/*.js', {glob: true});
                    require('./../../extensions/*/browser/*/*.js', {glob: true});
                }

                if (typeof vidiConfig.extensions !== "undefined" && typeof vidiConfig.extensions.browser !== "undefined") {
                    $.each(vidiConfig.extensions.browser, function (i, v) {
                        modules.extensions[Object.keys(v)[0]] = {};
                        $.each(v[Object.keys(v)[0]], function (n, m) {
                            modules.extensions[Object.keys(v)[0]][m] = require('./../../extensions/' + Object.keys(v)[0] + '/browser/' + m + ".js");
                            modules.extensions[Object.keys(v)[0]][m].set(modules);
                        })
                    });

                    if (typeof window.vidiConfig.enabledExtensions === "object") {
                        $.each(vidiConfig.extensions.browser, function (i, v) {
                            $.each(v[Object.keys(v)[0]], function (n, m) {
                                if (window.vidiConfig.enabledExtensions.indexOf(Object.keys(v)[0]) > -1) {
                                    modules.extensions[Object.keys(v)[0]][m].init();
                                }
                            })
                        });
                    }
                }

                // Init some GUI stuff after modules are loaded
                // ============================================
                $("[data-toggle=tooltip]").tooltip();

                $.material.init();
                touchScroll(".tab-pane");
                touchScroll("#info-modal-body-wrapper");
                $("#loadscreentext").html(__("Loading data"));
                if (window.vidiConfig.activateMainTab) {
                    setTimeout(function () {
                        $('#main-tabs a[href="#' + window.vidiConfig.activateMainTab + '-content"]').tab('show');
                    }, 200);
                }

                $(window).resize(_.debounce(function () {
                    $("#myNavmenu").offcanvas('hide');
                    setTimeout(function () {
                        modules.cloud.get().map.invalidateSize();
                    }, 100);
                }, 0));

                } catch (e) {
                    console.error("Could not perform application initialization", error);
                }
            });
        });

        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/service-worker.bundle.js').then((registration) => {
                console.log('Service worker registration succeeded');
            }).catch(error => {
                console.error(`Unable to register the service worker, please load the application over HTTPS in order to use its full functionality`);
            });
        } else {
            console.warn(`Service workers are not supported in this browser, some features may be unavailable`);
        }

        if (window.localforage) {
            localforage.getItem('appVersion').then(value => {

                if (value === null) {
                    localforage.setItem('appVersion', window.vidiConfig.appVersion).then(() => {
                        console.log(`Versioning: setting new application version (${window.vidiConfig.appVersion})`);
                    }).catch(error => {
                        throw new Error(`Unable to store current application version`);
                    });
                } else {

                    console.log(`### value`, window.vidiConfig.appVersion, semver.valid(window.vidiConfig.appVersion), semver.valid(value));

                    // If two versions are correctly detected
                    if (semver.valid(window.vidiConfig.appVersion) !== null && semver.valid(value) !== null) {
                        if (semver.gt(window.vidiConfig.appVersion, value)) {
                            if (confirm(`Update application to the newest version (current: ${value}, latest: ${window.vidiConfig.appVersion})?`)) {
                                let unregisteringRequests = [];

                                // Unregister service worker
                                navigator.serviceWorker.getRegistrations().then((registrations) => {
                                    for(let registration of registrations) {
                                        console.log(`Versioning: unregistering service worker`, registration);
                                        unregisteringRequests.push(registration.unregister());
                                        registration.unregister();
                                    }
                                });

                                Promise.all(unregisteringRequests).then((values) => {
                                    // Clear caches
                                    caches.keys().then(function(names) {
                                        for (let name of names) {
                                            console.log(`Versioning: clearing cache`, name);
                                            caches.delete(name);
                                        }
                                    });

                                    // Remove current app version
                                    localforage.removeItem('appVersion').then(() => {
                                        location.reload();
                                    });
                                });
                            }
                        } else {
                            console.log('Versioning: new application version is not available');
                        }
                    } else if (semver.valid(value) === null) {
                        console.warn(`Seems like current application version is invalid, resetting it`);
                        localforage.setItem('appVersion', '1.0.0').then(() => {}).catch(error => {
                            throw new Error(`Unable to store current application version`);
                        });
                    }
                }
            });
        } else {
            throw new Error(`localforage is not available`);
        }
    }
};<|endoftext|>


<commit_before>import {helper} from '@ember/component/helper';

export const DEFAULT_QUERY_PARAMS = {
    posts: {
        type: null,
        visibility: null,
        author: null,
        tag: null,
        order: null
    },
    pages: {
        type: null,
        visibility: null,
        author: null,
        tag: null,
        order: null
    },
    'members.index': {
        label: null,
        paid: null,
        search: '',
        order: null
    }
};

// in order to reset query params to their defaults when using <LinkTo> or
// `transitionTo` it's necessary to explicitly set each param. This helper makes
// it easier to provide a "resetting" link, especially when used with custom views

export function resetQueryParams(routeName, newParams) {
    return Object.assign({}, DEFAULT_QUERY_PARAMS[routeName], newParams);
}

export default helper(function (params/*, hash*/) {
    return resetQueryParams(...params);
});
<commit_msg>Reset filter query params on "Members" click in sidebar<commit_after>import {helper} from '@ember/component/helper';

export const DEFAULT_QUERY_PARAMS = {
    posts: {
        type: null,
        visibility: null,
        author: null,
        tag: null,
        order: null
    },
    pages: {
        type: null,
        visibility: null,
        author: null,
        tag: null,
        order: null
    },
    'members.index': {
        label: null,
        paid: null,
        search: '',
        filter: null,
        order: null
    }
};

// in order to reset query params to their defaults when using <LinkTo> or
// `transitionTo` it's necessary to explicitly set each param. This helper makes
// it easier to provide a "resetting" link, especially when used with custom views

export function resetQueryParams(routeName, newParams) {
    return Object.assign({}, DEFAULT_QUERY_PARAMS[routeName], newParams);
}

export default helper(function (params/*, hash*/) {
    return resetQueryParams(...params);
});
<|endoftext|>


<commit_before>function init() {
  screenElement = document.getElementById("screen");
  screenElement.width = document.body.clientWidth;
  screenElement.height = document.body.clientHeight;

  backElement = document.createElement("canvas");
  backElement.width = document.body.clientWidth;
  backElement.height = document.body.clientHeight;

  mouse = {x: 0, y: 0, down: false};
  document.addEventListener("mousemove", function(event) {
    mouse.x = event.pageX;
    mouse.y = event.pageY;
  });
  document.addEventListener("mousedown", function(event) {
    mouse.down = true;
  });
  document.addEventListener("mouseup", function(event) {
    mouse.down = false;
  });

  state = {
    lastMouse: {},
    lastPos: {x: 0, y: 0},
    secondaryPos: {x: 0, y: 0},
    secondaryVel: {x: 0, y: 0}
  };
  Object.assign(state.lastMouse, mouse);

  window.requestAnimationFrame(render.bind(render, state, mouse, screenElement.getContext("2d"), backElement.getContext("2d")));
}

function render(state, mouse, screen, back) {

  state.secondaryVel.x += 0.05*(mouse.x - state.secondaryPos.x) - 0.01 * state.secondaryVel.x;
  state.secondaryVel.y += 0.05*(mouse.y - state.secondaryPos.y) - 0.01 * state.secondaryVel.y;
  state.secondaryPos.x += state.secondaryVel.x;
  state.secondaryPos.y += state.secondaryVel.y;

  //  screen.clearRect(0, 0, screen.width, screen.height);
  back.globalAlpha = 0.1;
  back.globalCompositeOperation='destination-out';
  back.fillRect(0, 0, back.canvas.width, back.canvas.height)

  back.globalAlpha = 1;
  back.globalCompositeOperation='source-over';
  back.lineCap = "round";
  back.lineWidth = 5;
  back.beginPath();
  back.moveTo(state.lastPos.x, state.lastPos.y);
  back.lineTo(state.secondaryPos.x, state.secondaryPos.y);
  //back.arc(mouse.x, mouse.y, 5, 0, 2*Math.PI);
  back.stroke();

  screen.fillStyle = "#fff";
  screen.fillRect(0, 0, screen.canvas.width, screen.canvas.height)
  screen.drawImage(back.canvas, 0, 0)

  screen.fillStyle = "#000";
  screen.beginPath();
  screen.arc(mouse.x, mouse.y, 5, 0, 2*Math.PI);
  screen.fill();

  screen.fillStyle = "#f0f";
  screen.beginPath();
  screen.arc(state.secondaryPos.x, state.secondaryPos.y, 5, 0, 2*Math.PI);
  screen.fill();

  // mouse just released
  /* if (state.lastMouse.down = true && !mouse.down) {
    state.pointer
    state.releasePoint =
  } */

  //back.clearRect(0, 0, back.canvas.width, back.canvas.)

  Object.assign(state.lastMouse, mouse)
  Object.assign(state.lastPos, state.secondaryPos)
  argumentsArray = Array.from(arguments);
  window.requestAnimationFrame(function () { render.apply(render, argumentsArray); });
}

document.addEventListener("DOMContentLoaded", init);<commit_msg>Proper figures and quicker rendering.<commit_after>function init() {
  screenElement = document.getElementById("screen");
  screenElement.width = document.body.clientWidth;
  screenElement.height = document.body.clientHeight;

  backElement = document.createElement("canvas");
  backElement.width = document.body.clientWidth;
  backElement.height = document.body.clientHeight;

  mouse = {x: 0, y: 0, down: false};
  document.addEventListener("mousemove", function(event) {
    mouse.x = event.pageX;
    mouse.y = event.pageY;
  });
  document.addEventListener("mousedown", function(event) {
    mouse.down = true;
  });
  document.addEventListener("mouseup", function(event) {
    mouse.down = false;
  });

  state = {
    lastMouse: {},
    lastPos: {x: screenElement.width/2, y: screenElement.height/2},
    //origin: {x: screenElement.width/2, y: screenElement.height/2},
    primaryPos: {x: screenElement.width/2, y: screenElement.height/2},
    primaryVel: {x: 0, y: 0},
    secondaryPos: {x: screenElement.width/2, y: screenElement.height/2},
    secondaryVel: {x: 0, y: 0},
    steps: 10
  };
  Object.assign(state.lastMouse, mouse);

  window.requestAnimationFrame(render.bind(render, state, mouse, screenElement.getContext("2d"), backElement.getContext("2d")));
}

function step(state, mouse, origin, dt) {
  if (mouse.down) {
    state.primaryVel.x += dt*0.25*(mouse.x - state.primaryPos.x)
    state.primaryVel.y += dt*0.25*(mouse.y - state.primaryPos.y);
    state.primaryVel.x -= dt*0.6 * state.primaryVel.x;
    state.primaryVel.y -= dt*0.6 * state.primaryVel.y;
  } else {
    state.primaryVel.x += dt*0.02*(origin.x - state.primaryPos.x)
    state.primaryVel.y += dt*0.02*(origin.y - state.primaryPos.y);
    state.primaryVel.x += dt*0.05*(state.secondaryPos.x - state.primaryPos.x)
    state.primaryVel.y += dt*0.05*(state.secondaryPos.y - state.primaryPos.y);
    state.primaryVel.x -= dt*0.0001 * state.primaryVel.x;
    state.primaryVel.y -= dt*0.0001 * state.primaryVel.y;
  }

  state.secondaryVel.x += dt*0.05*(state.primaryPos.x - state.secondaryPos.x)
  state.secondaryVel.y += dt*0.05*(state.primaryPos.y - state.secondaryPos.y);
  state.secondaryVel.x -= dt*0.0001 * state.secondaryVel.x;
  state.secondaryVel.y -= dt*0.0001 * state.secondaryVel.y;

  state.primaryPos.x += dt*state.primaryVel.x;
  state.primaryPos.y += dt*state.primaryVel.y;
  state.secondaryPos.x += dt*state.secondaryVel.x;
  state.secondaryPos.y += dt*state.secondaryVel.y;

  if (mouse.down) {
    if (!state.lastMouse.down) {
      state.primaryVel = {x: 0, y: 0};
      state.secondaryVel = {x: 0, y: 0};
      state.primaryPos = {x: mouse.x, y: mouse.y};
      state.primaryPos = {x: mouse.x, y: mouse.y};
      state.secondaryPos = {x: mouse.x, y: mouse.y};
      state.secondaryPos = {x: mouse.x, y: mouse.y};
    }
  }
}

function render(state, mouse, screen, back) {
  if (mouse.down) {
    if (!state.lastMouse.down) {
      back.clearRect(0, 0, back.canvas.width, back.canvas.height);
      state.steps = 10;
    }
  } else {
    if (state.steps < 1000) {
      state.steps *= 1.02;
    }
  }

  for (var i = 0; i < state.steps; i++) {
    step(state, mouse, {x: screen.canvas.width/2, y: screen.canvas.height/2}, 0.1);

    if (!mouse.down) {
      back.lineCap = "round";
      back.lineWidth = 1;
      back.strokeStyle = "rgba(0, 0, 0, 0.2)"
      back.beginPath();
      back.moveTo(state.lastPos.x, state.lastPos.y);
      back.lineTo(state.primaryPos.x, state.primaryPos.y);
      //back.arc(mouse.x, mouse.y, 5, 0, 2*Math.PI);
      back.stroke();
    }

    Object.assign(state.lastPos, state.primaryPos)
  }

  /*back.globalAlpha = 0.1;
  back.globalCompositeOperation='destination-out';
  back.fillRect(0, 0, back.canvas.width, back.canvas.height)
  back.globalAlpha = 1.0;
  back.globalCompositeOperation='source-over';*/

  screen.clearRect(0, 0, screen.canvas.width, screen.canvas.height)

  if (mouse.down) {
    screen.fillStyle = "#000";
    screen.beginPath();
    screen.arc(mouse.x, mouse.y, 5, 0, 2*Math.PI);
    screen.fill();

    screen.fillStyle = "#f0f";
    screen.beginPath();
    screen.arc(state.secondaryPos.x, state.secondaryPos.y, 5, 0, 2*Math.PI);
    screen.fill();

    screen.fillStyle = "#0ff";
    screen.beginPath();
    screen.arc(state.primaryPos.x, state.primaryPos.y, 5, 0, 2*Math.PI);
    screen.fill();
  } else {
    screen.drawImage(back.canvas, 0, 0)
  }

  // mouse just released
  /* if (state.lastMouse.down = true && !mouse.down) {
    state.pointer
    state.releasePoint =
  } */

  //back.clearRect(0, 0, back.canvas.width, back.canvas.)

  Object.assign(state.lastMouse, mouse)
  argumentsArray = Array.from(arguments);
  window.requestAnimationFrame(function () { render.apply(render, argumentsArray); });
}

document.addEventListener("DOMContentLoaded", init);<|endoftext|>


<commit_before>const pckg = require('../../package.json')
const VERSION = process.env.VERSION || pckg.version
const GA_MEASUREMENT_ID = 'UA-82107035-1'

module.exports = {
  locales: {
    '/': {
      lang: 'en-US',
      title: 'Fuse.js',
      description: 'Lightweight fuzzy-search library, in JavaScript'
    }
  },
  head: getHead(),
  plugins: getPlugins(),
  serviceWorker: true,
  themeConfig: {
    logo: '/assets/img/logo.png',
    repo: 'krisk/fuse',
    base: 'docs',
    lastUpdated: 'Last Updated',
    docsDir: 'docs',
    docsBranch: 'master',
    editLinks: true,
    version: VERSION,
    GA_MEASUREMENT_ID,
    displayAllHeaders: true,
    locales: {
      '/': {
        label: 'English',
        selectText: 'Languages',
        editLinkText: 'Edit this page on GitHub',
        nav: require('./nav/en'),
        sidebar: {
          // '/blog': getBlogSidebar(),
          '/': getGuideSidebar()
        }
      }
    }
  }
}

function getGuideSidebar() {
  return [
    {
      title: 'Getting Started',
      collapsable: false,
      sidebarDepth: 0,
      children: [
        '/getting-started/installation',
        '/getting-started/different-builds'
      ]
    },
    '/demo',
    {
      title: 'API Reference',
      collapsable: false,
      children: ['/api/options', '/api/indexing']
    },
    '/examples',
    {
      title: 'Concepts',
      collapsable: false,
      children: ['/concepts/scoring-theory']
    }
  ]
}

// function getBlogSidebar() {
//   return []
// }

function getPlugins() {
  return [
    require('./plugins/google-analytics'),
    'vuepress-plugin-smooth-scroll',
    'vuepress-plugin-element-tabs',
    [
      'social-share',
      {
        networks: ['twitter', 'facebook', 'reddit', 'email', 'linkedin'],
        extendsNetworks: {
          email: {
            sharer: 'mailto:?subject=@title&body=@url%0D%0A%0D%0A@description',
            type: 'direct',
            icon: '/assets/img/email.png'
          },
          linkedin: {
            sharer:
              'https://www.linkedin.com/sharing/share-offsite/?mini=true&url=@url&title=@title&summary=@description',
            type: 'popup',
            color: '#1786b1',
            icon:
              '<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M910.336 0H113.664A114.005333 114.005333 0 0 0 0 113.664v796.672A114.005333 114.005333 0 0 0 113.664 1024h796.672A114.005333 114.005333 0 0 0 1024 910.336V113.664A114.005333 114.005333 0 0 0 910.336 0zM352.256 796.330667H207.189333V375.466667h145.066667z m-72.021333-477.866667a77.824 77.824 0 0 1-81.237334-74.069333A77.824 77.824 0 0 1 280.234667 170.666667a77.824 77.824 0 0 1 81.237333 73.728 77.824 77.824 0 0 1-81.237333 73.386666z m582.314666 477.866667H716.8v-227.669334c0-46.762667-18.432-93.525333-73.045333-93.525333a84.992 84.992 0 0 0-81.237334 94.549333v226.304h-140.629333V375.466667h141.653333v60.757333a155.989333 155.989333 0 0 1 136.533334-71.338667c60.416 0 163.498667 30.378667 163.498666 194.901334z" /></svg>'
          }
        },
        twitterUser: 'kirorisk',
        autoQuote: true,
        isPlain: false,
        noGlobalSocialShare: true
      }
    ]
  ]
}

function getHead() {
  const appleTouchIcons = [
    { sizes: '57x57', href: 'apple-icon-57x57.png' },
    { sizes: '60x60', href: 'apple-icon-60x60.png' },
    { sizes: '72x72', href: 'apple-icon-72x72.png' },
    { sizes: '76x76', href: 'apple-icon-76x76.png' },
    { sizes: '114x114', href: 'apple-icon-114x114.png' },
    { sizes: '120x120', href: 'apple-icon-120x120.png' },
    { sizes: '144x144', href: 'apple-icon-144x144.png' },
    { sizes: '152x152', href: 'apple-icon-152x152.png' },
    { sizes: '180x180', href: 'apple-icon-180x180.png' }
  ].map(({ sizes, href }) => [
    'link',
    { rel: 'apple-touch-icon', sizes, href: `/icons/${href}` }
  ])

  const sizedIcons = [
    {
      sizes: '192x192',
      href: 'android-icon-192x192.png'
    },
    { sizes: '32x32', href: 'favicon-32x32.png' },
    { sizes: '96x96', href: 'favicon-96x96.png' },
    { sizes: '16x16', href: 'favicon-16x16.png' }
  ].map(({ sizes, href }) => [
    'link',
    { rel: 'icon', type: 'image/png', sizes, href: `/icons/${href}` }
  ])

  const meta = [
    { name: 'msapplication-TileColor', content: '#ffffff' },
    { name: 'msapplication-TileImage', content: '/ms-icon-144x144.png' },
    { name: 'theme-color', content: '#ffffff' }
  ].map(({ name, content }) => ['meta', { name, content: `/icons/${content}` }])

  return [
    ...appleTouchIcons,
    ...sizedIcons,
    ...meta,
    ['link', { rel: 'manifest', href: '/icons/manifest.json' }]
  ]
}
<commit_msg>Added gtag verification<commit_after>const pckg = require('../../package.json')
const VERSION = process.env.VERSION || pckg.version
const GA_MEASUREMENT_ID = 'UA-82107035-1'

module.exports = {
  locales: {
    '/': {
      lang: 'en-US',
      title: 'Fuse.js',
      description: 'Lightweight fuzzy-search library, in JavaScript'
    }
  },
  head: getHead(),
  plugins: getPlugins(),
  serviceWorker: true,
  themeConfig: {
    logo: '/assets/img/logo.png',
    repo: 'krisk/fuse',
    base: 'docs',
    lastUpdated: 'Last Updated',
    docsDir: 'docs',
    docsBranch: 'master',
    editLinks: true,
    version: VERSION,
    GA_MEASUREMENT_ID,
    displayAllHeaders: true,
    locales: {
      '/': {
        label: 'English',
        selectText: 'Languages',
        editLinkText: 'Edit this page on GitHub',
        nav: require('./nav/en'),
        sidebar: {
          // '/blog': getBlogSidebar(),
          '/': getGuideSidebar()
        }
      }
    }
  }
}

function getGuideSidebar() {
  return [
    {
      title: 'Getting Started',
      collapsable: false,
      sidebarDepth: 0,
      children: [
        '/getting-started/installation',
        '/getting-started/different-builds'
      ]
    },
    '/demo',
    {
      title: 'API Reference',
      collapsable: false,
      children: ['/api/options', '/api/indexing']
    },
    '/examples',
    {
      title: 'Concepts',
      collapsable: false,
      children: ['/concepts/scoring-theory']
    }
  ]
}

// function getBlogSidebar() {
//   return []
// }

function getPlugins() {
  return [
    require('./plugins/google-analytics'),
    'vuepress-plugin-smooth-scroll',
    'vuepress-plugin-element-tabs',
    [
      'social-share',
      {
        networks: ['twitter', 'facebook', 'reddit', 'email', 'linkedin'],
        extendsNetworks: {
          email: {
            sharer: 'mailto:?subject=@title&body=@url%0D%0A%0D%0A@description',
            type: 'direct',
            icon: '/assets/img/email.png'
          },
          linkedin: {
            sharer:
              'https://www.linkedin.com/sharing/share-offsite/?mini=true&url=@url&title=@title&summary=@description',
            type: 'popup',
            color: '#1786b1',
            icon:
              '<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M910.336 0H113.664A114.005333 114.005333 0 0 0 0 113.664v796.672A114.005333 114.005333 0 0 0 113.664 1024h796.672A114.005333 114.005333 0 0 0 1024 910.336V113.664A114.005333 114.005333 0 0 0 910.336 0zM352.256 796.330667H207.189333V375.466667h145.066667z m-72.021333-477.866667a77.824 77.824 0 0 1-81.237334-74.069333A77.824 77.824 0 0 1 280.234667 170.666667a77.824 77.824 0 0 1 81.237333 73.728 77.824 77.824 0 0 1-81.237333 73.386666z m582.314666 477.866667H716.8v-227.669334c0-46.762667-18.432-93.525333-73.045333-93.525333a84.992 84.992 0 0 0-81.237334 94.549333v226.304h-140.629333V375.466667h141.653333v60.757333a155.989333 155.989333 0 0 1 136.533334-71.338667c60.416 0 163.498667 30.378667 163.498666 194.901334z" /></svg>'
          }
        },
        twitterUser: 'kirorisk',
        autoQuote: true,
        isPlain: false,
        noGlobalSocialShare: true
      }
    ]
  ]
}

function getHead() {
  const appleTouchIcons = [
    { sizes: '57x57', href: 'apple-icon-57x57.png' },
    { sizes: '60x60', href: 'apple-icon-60x60.png' },
    { sizes: '72x72', href: 'apple-icon-72x72.png' },
    { sizes: '76x76', href: 'apple-icon-76x76.png' },
    { sizes: '114x114', href: 'apple-icon-114x114.png' },
    { sizes: '120x120', href: 'apple-icon-120x120.png' },
    { sizes: '144x144', href: 'apple-icon-144x144.png' },
    { sizes: '152x152', href: 'apple-icon-152x152.png' },
    { sizes: '180x180', href: 'apple-icon-180x180.png' }
  ].map(({ sizes, href }) => [
    'link',
    { rel: 'apple-touch-icon', sizes, href: `/icons/${href}` }
  ])

  const sizedIcons = [
    {
      sizes: '192x192',
      href: 'android-icon-192x192.png'
    },
    { sizes: '32x32', href: 'favicon-32x32.png' },
    { sizes: '96x96', href: 'favicon-96x96.png' },
    { sizes: '16x16', href: 'favicon-16x16.png' }
  ].map(({ sizes, href }) => [
    'link',
    { rel: 'icon', type: 'image/png', sizes, href: `/icons/${href}` }
  ])

  const meta = [
    { name: 'msapplication-TileColor', content: '#ffffff' },
    { name: 'msapplication-TileImage', content: '/icons/ms-icon-144x144.png' },
    { name: 'theme-color', content: '#ffffff' },
    {
      name: 'google-site-verification',
      content: '4nm40QLVcDJmEJSAbrMfZ7fpBJZIXL1oSngBAYrZopY'
    }
  ].map(({ name, content }) => ['meta', { name, content }])

  return [
    ...appleTouchIcons,
    ...sizedIcons,
    ...meta,
    ['link', { rel: 'manifest', href: '/icons/manifest.json' }]
  ]
}
<|endoftext|>


<commit_before>/*global global, module*/
(function () {

	// Make a module
	var atom = (function (name) {
		var rt = typeof window !== 'undefined' ? window : global,
			had = rt.hasOwnProperty(name), prev = rt[name], me = rt[name] = {};
		if (typeof module !== 'undefined' && module.exports) {
			module.exports = me;
		}
		me.noConflict = function () {
			delete rt[name];
			if (had) {
				rt[name] = prev;
			}
			return this;
		};
		return me;
	}('atom'));

	atom.VERSION = '0.1.0';

	// Convenience methods
	var slice = Array.prototype.slice;
	var isArray = Array.isArray || function (obj) {
		return Object.prototype.toString.call(obj) === '[object Array]';
	};
	function inArray(arr, value) {
		for (var i = arr.length; --i >= 0;) {
			if (arr[i] === value) {
				return true;
			}
		}
	}
	function toArray(obj) {
		return isArray(obj) ? obj : [obj];
	}
	function isEmpty(obj) {
		for (var p in obj) {
			if (obj.hasOwnProperty(p)) {
				return false;
			}
		}
		return true;
	}

	// Property getter
	function get(nucleus, keyOrList, func) {
		var isList = isArray(keyOrList), keys = isList ? keyOrList : [keyOrList],
			key, values = [], props = nucleus.props, missing = {},
			result = { values: values };
		for (var i = keys.length; --i >= 0;) {
			key = keys[i];
			if (!props.hasOwnProperty(key)) {
				result.missing = missing;
				missing[key] = true;
			}
			values.unshift(props[key]);
		}
		return func ? func.apply({}, values) : result;
	}

	function removeListener(listeners, listener) {
		for (var i = listeners.length; --i >= 0;) {
			if (!listeners[i].calls) {
				return listeners.splice(i, 1);
			}
		}
	}

	// Used to detect listener recursion; a given object may only appear once.
	var objStack = [];

	// Property setter
	function set(nucleus, key, value) {
		var keys, listener, listeners = nucleus.listeners, values, missing,
			listenersCopy = [].concat(listeners), i = listenersCopy.length,
			props = nucleus.props, oldValue = props[key],
			had = props.hasOwnProperty(key),
			isObj = value && typeof value === 'object';
		props[key] = value;
		if (!had || oldValue !== value || (isObj && !inArray(objStack, value))) {
			if (isObj) {
				objStack.push(value);
			}
			while (--i >= 0) {
				listener = listenersCopy[i];
				keys = listener.keys;
				missing = listener.missing;
				if (missing) {
					if (missing.hasOwnProperty(key)) {
						delete missing[key];
						if (isEmpty(missing)) {
							listener.cb.apply({}, get(nucleus, keys).values);
							listener.calls--;
						}
					}
				} else if (inArray(keys, key)) {
					listener.cb.apply({}, get(nucleus, keys).values);
					listener.calls--;
				}
				if (!listener.calls) {
					removeListener(listeners, listener);
				}
			}
			delete nucleus.needs[key];
			if (isObj) {
				objStack.pop();
			}
		}
	}

	function provide(nucleus, key, provider) {
		provider(function (result) {
			set(nucleus, key, result);
		});
	}

	atom.create = function () {
		var
			nucleus = { props: {}, needs: {}, providers: {}, listeners: [] },
			props = nucleus.props,
			needs = nucleus.needs,
			providers = nucleus.providers,
			listeners = nucleus.listeners,
			q = []
		;
		function doNext() {
			if (q) {
				q.pending = q.next = (!q.next && q.length) ?
					q.shift() : q.next;
				q.args = slice.call(arguments, 0);
				if (q.pending) {
					q.next = null;
					q.pending.apply({}, [doNext].concat(q.args));
				}
			}
		}
		var me = {

			// Call `func` whenever any of the specified keys change.  The values
			// of the keys will be provided as args to func.
			bind: function (keyOrList, func) { // alias: `on`
				listeners.unshift({ keys: toArray(keyOrList), cb: func,
					calls: Infinity });
			},

			// Add a function or functions to the async queue.  Functions added
			// thusly must call their first arg as a callback when done.  Any args
			// provided to the callback will be passed in to the next function in
			// the queue.
			chain: function () {
				if (q) {
					for (var i = 0, len = arguments.length; i < len; i++) {
						q.push(arguments[i]);
						if (!q.pending) {
							doNext.apply({}, q.args);
						}
					}
				}
			},

			// Remove references to all properties and listeners.  This releases
			// memory, and effective stops the atom from working.
			destroy: function () {
				delete nucleus.props;
				delete nucleus.needs;
				delete nucleus.providers;
				delete nucleus.listeners;
				while (q.length) {
					q.pop();
				}
				nucleus = props = needs = providers = listeners =
					q = q.pending = q.next = q.args = null;
			},

			// Call `func` on each of the specified keys.  The key is provided as
			// the first arg, and the value as the second.
			each: function (keyOrList, func) {
				var keys = toArray(keyOrList), i = -1, len = keys.length, key;
				while (++i < len) {
					key = keys[i];
					func(key, me.get(key));
				}
			},

			// Establish two-way binding between a key or list of keys for two
			// different atoms, so that changing a property on either atom will
			// propagate to the other.  If a map is provided for `keyOrListOrMap`,
			// properties on this atom may be bound to differently named properties
			// on `otherAtom`.
			entangle: function (otherAtom, keyOrListOrMap) {
				var
					isList = isArray(keyOrListOrMap),
					isMap = !isList && typeof keyOrListOrMap === 'object',
					i, key,
					keys = isList ? keyOrListOrMap : isMap ? [] : [keyOrListOrMap],
					map = isMap ? keyOrListOrMap : {}
				;
				if (isMap) {
					for (key in map) {
						if (map.hasOwnProperty(key)) {
							keys.push(key);
						}
					}
				} else {
					for (i = keys.length; --i >= 0;) {
						key = keys[i];
						map[key] = key;
					}
				}
				me.each(keys, function (key) {
					var otherKey = map[key];
					me.bind(key, function (value) {
						otherAtom.set(otherKey, value);
					});
					otherAtom.bind(otherKey, function (value) {
						me.set(key, value);
					});
				});
			},

			// Get current values for the specified keys.  If `func` is provided,
			// it will be called with the values as args.
			get: function (keyOrList, func) {
				var result = get(nucleus, keyOrList, func);
				return func ? result : typeof keyOrList === 'string' ?
					result.values[0] : result.values;
			},

			// Returns true iff all of the specified keys exist (regardless of
			// value).
			has: function (keyOrList) {
				var keys = toArray(keyOrList);
				for (var i = keys.length; --i >= 0;) {
					if (!props.hasOwnProperty(keys[i])) {
						return false;
					}
				}
				return true;
			},

			// Return a list of all keys.
			keys: function () {
				var keys = [];
				for (var key in props) {
					if (props.hasOwnProperty(key)) {
						keys.push(key);
					}
				}
				return keys;
			},

			// Add arbitrary properties to this atom's interface.
			mixin: function (obj) {
				for (var p in obj) {
					if (obj.hasOwnProperty(p)) {
						me[p] = obj[p];
					}
				}
				return me;
			},

			// Call `func` as soon as all of the specified keys have been set.  If
			// they are already set, the function will be called immediately, with
			// all the values provided as args.  In this, it is identical to
			// `once()`.  However, calling `need()` will additionally invoke
			// providers when possible, in order to try and create the required
			// values.
			need: function (keyOrList, func) {
				var key, keys = toArray(keyOrList), values, provider;
				for (var i = keys.length; --i >= 0;) {
					key = keys[i];
					provider = providers[key];
					if (!props.hasOwnProperty(key) && provider) {
						provide(nucleus, key, provider);
						delete providers[key];
					} else {
						needs[key] = true;
					}
				}
				me.once(keys, func);
			},

			// Call `func` whenever any of the specified keys is next changed.  The
			// values of all keys will be provided as args to the function.  The
			// function will automatically be unbound after being called the first
			// time, so it is guaranteed to be called no more than once.
			next: function (keyOrList, func) {
				listeners.unshift(
					{ keys: toArray(keyOrList), cb: func, calls: 1 });
			},

			// Call `func` as soon as all of the specified keys have been set.  If
			// they are already set, the function will be called immediately, with
			// all the values provided as args.  Guaranteed to be called no more
			// than once.
			once: function (keyOrList, func) {
				var keys = toArray(keyOrList),
					results = get(nucleus, keys),
					values = results.values,
					missing = results.missing;
				if (!missing) {
					func.apply({}, values);
				} else {
					listeners.unshift(
						{ keys: keys, cb: func, missing: missing, calls: 1 });
				}
			},

			// Register a provider for a particular key.  The provider `func` is a
			// function that will be called if there is a need to create the key.
			// It must call its first arg as a callback, with the value.  Provider
			// functions will be called at most once.
			provide: function (key, func) {
				if (needs[key]) {
					provide(nucleus, key, func);
				} else if (!providers[key]) {
					providers[key] = func;
				}
			},

			// Set value for a key, or if `keyOrMap` is an object then set all the
			// keys' corresponding values.
			set: function (keyOrMap, value) {
				if (typeof keyOrMap === 'object') {
					for (var key in keyOrMap) {
						if (keyOrMap.hasOwnProperty(key)) {
							set(nucleus, key, keyOrMap[key]);
						}
					}
				} else {
					set(nucleus, keyOrMap, value);
				}
			},

			// Unregister a listener `func` that was previously registered using
			// `bind()`, `need()`, `next()` or `once()`.
			unbind: function (func) { // alias: `off`
				for (var i = listeners.length; --i >= 0;) {
					if (listeners[i].cb === func) {
						listeners.splice(i, 1);
					}
				}
			}
		};
		me.on = me.bind;
		me.off = me.unbind;
		return me;
	};

}());
<commit_msg>Remove unused function argument<commit_after>/*global global, module*/
(function () {

	// Make a module
	var atom = (function (name) {
		var rt = typeof window !== 'undefined' ? window : global,
			had = rt.hasOwnProperty(name), prev = rt[name], me = rt[name] = {};
		if (typeof module !== 'undefined' && module.exports) {
			module.exports = me;
		}
		me.noConflict = function () {
			delete rt[name];
			if (had) {
				rt[name] = prev;
			}
			return this;
		};
		return me;
	}('atom'));

	atom.VERSION = '0.1.1';

	// Convenience methods
	var slice = Array.prototype.slice;
	var isArray = Array.isArray || function (obj) {
		return Object.prototype.toString.call(obj) === '[object Array]';
	};
	function inArray(arr, value) {
		for (var i = arr.length; --i >= 0;) {
			if (arr[i] === value) {
				return true;
			}
		}
	}
	function toArray(obj) {
		return isArray(obj) ? obj : [obj];
	}
	function isEmpty(obj) {
		for (var p in obj) {
			if (obj.hasOwnProperty(p)) {
				return false;
			}
		}
		return true;
	}

	// Property getter
	function get(nucleus, keyOrList, func) {
		var isList = isArray(keyOrList), keys = isList ? keyOrList : [keyOrList],
			key, values = [], props = nucleus.props, missing = {},
			result = { values: values };
		for (var i = keys.length; --i >= 0;) {
			key = keys[i];
			if (!props.hasOwnProperty(key)) {
				result.missing = missing;
				missing[key] = true;
			}
			values.unshift(props[key]);
		}
		return func ? func.apply({}, values) : result;
	}

	// Helper to remove an exausted listener from the listeners array
	function removeListener(listeners) {
		for (var i = listeners.length; --i >= 0;) {
			// There should only be ONE exhausted listener, so we don't bother
			// comparing it to the 'listener' parameter.
			if (!listeners[i].calls) {
				return listeners.splice(i, 1);
			}
		}
	}

	// Used to detect listener recursion; a given object may only appear once.
	var objStack = [];

	// Property setter
	function set(nucleus, key, value) {
		var keys, listener, listeners = nucleus.listeners, values, missing,
			listenersCopy = [].concat(listeners), i = listenersCopy.length,
			props = nucleus.props, oldValue = props[key],
			had = props.hasOwnProperty(key),
			isObj = value && typeof value === 'object';
		props[key] = value;
		if (!had || oldValue !== value || (isObj && !inArray(objStack, value))) {
			if (isObj) {
				objStack.push(value);
			}
			while (--i >= 0) {
				listener = listenersCopy[i];
				keys = listener.keys;
				missing = listener.missing;
				if (missing) {
					if (missing.hasOwnProperty(key)) {
						delete missing[key];
						if (isEmpty(missing)) {
							listener.cb.apply({}, get(nucleus, keys).values);
							listener.calls--;
						}
					}
				} else if (inArray(keys, key)) {
					listener.cb.apply({}, get(nucleus, keys).values);
					listener.calls--;
				}
				if (!listener.calls) {
					removeListener(listeners);
				}
			}
			delete nucleus.needs[key];
			if (isObj) {
				objStack.pop();
			}
		}
	}

	function provide(nucleus, key, provider) {
		provider(function (result) {
			set(nucleus, key, result);
		});
	}

	atom.create = function () {
		var
			nucleus = { props: {}, needs: {}, providers: {}, listeners: [] },
			props = nucleus.props,
			needs = nucleus.needs,
			providers = nucleus.providers,
			listeners = nucleus.listeners,
			q = []
		;

		function doNext() {
			if (q) {
				q.pending = q.next = (!q.next && q.length) ?
					q.shift() : q.next;
				q.args = slice.call(arguments, 0);
				if (q.pending) {
					q.next = null;
					q.pending.apply({}, [doNext].concat(q.args));
				}
			}
		}

		var me = {

			// Call `func` whenever any of the specified keys change.  The values
			// of the keys will be provided as args to func.
			bind: function (keyOrList, func) { // alias: `on`
				listeners.unshift({ keys: toArray(keyOrList), cb: func,
					calls: Infinity });
			},

			// Add a function or functions to the async queue.  Functions added
			// thusly must call their first arg as a callback when done.  Any args
			// provided to the callback will be passed in to the next function in
			// the queue.
			chain: function () {
				if (q) {
					for (var i = 0, len = arguments.length; i < len; i++) {
						q.push(arguments[i]);
						if (!q.pending) {
							doNext.apply({}, q.args);
						}
					}
				}
			},

			// Remove references to all properties and listeners.  This releases
			// memory, and effective stops the atom from working.
			destroy: function () {
				delete nucleus.props;
				delete nucleus.needs;
				delete nucleus.providers;
				delete nucleus.listeners;
				while (q.length) {
					q.pop();
				}
				nucleus = props = needs = providers = listeners =
					q = q.pending = q.next = q.args = null;
			},

			// Call `func` on each of the specified keys.  The key is provided as
			// the first arg, and the value as the second.
			each: function (keyOrList, func) {
				var keys = toArray(keyOrList), i = -1, len = keys.length, key;
				while (++i < len) {
					key = keys[i];
					func(key, me.get(key));
				}
			},

			// Establish two-way binding between a key or list of keys for two
			// different atoms, so that changing a property on either atom will
			// propagate to the other.  If a map is provided for `keyOrListOrMap`,
			// properties on this atom may be bound to differently named properties
			// on `otherAtom`.
			entangle: function (otherAtom, keyOrListOrMap) {
				var
					isList = isArray(keyOrListOrMap),
					isMap = !isList && typeof keyOrListOrMap === 'object',
					i, key,
					keys = isList ? keyOrListOrMap : isMap ? [] : [keyOrListOrMap],
					map = isMap ? keyOrListOrMap : {}
				;
				if (isMap) {
					for (key in map) {
						if (map.hasOwnProperty(key)) {
							keys.push(key);
						}
					}
				} else {
					for (i = keys.length; --i >= 0;) {
						key = keys[i];
						map[key] = key;
					}
				}
				me.each(keys, function (key) {
					var otherKey = map[key];
					me.bind(key, function (value) {
						otherAtom.set(otherKey, value);
					});
					otherAtom.bind(otherKey, function (value) {
						me.set(key, value);
					});
				});
			},

			// Get current values for the specified keys.  If `func` is provided,
			// it will be called with the values as args.
			get: function (keyOrList, func) {
				var result = get(nucleus, keyOrList, func);
				return func ? result : typeof keyOrList === 'string' ?
					result.values[0] : result.values;
			},

			// Returns true iff all of the specified keys exist (regardless of
			// value).
			has: function (keyOrList) {
				var keys = toArray(keyOrList);
				for (var i = keys.length; --i >= 0;) {
					if (!props.hasOwnProperty(keys[i])) {
						return false;
					}
				}
				return true;
			},

			// Return a list of all keys.
			keys: function () {
				var keys = [];
				for (var key in props) {
					if (props.hasOwnProperty(key)) {
						keys.push(key);
					}
				}
				return keys;
			},

			// Add arbitrary properties to this atom's interface.
			mixin: function (obj) {
				for (var p in obj) {
					if (obj.hasOwnProperty(p)) {
						me[p] = obj[p];
					}
				}
				return me;
			},

			// Call `func` as soon as all of the specified keys have been set.  If
			// they are already set, the function will be called immediately, with
			// all the values provided as args.  In this, it is identical to
			// `once()`.  However, calling `need()` will additionally invoke
			// providers when possible, in order to try and create the required
			// values.
			need: function (keyOrList, func) {
				var key, keys = toArray(keyOrList), values, provider;
				for (var i = keys.length; --i >= 0;) {
					key = keys[i];
					provider = providers[key];
					if (!props.hasOwnProperty(key) && provider) {
						provide(nucleus, key, provider);
						delete providers[key];
					} else {
						needs[key] = true;
					}
				}
				me.once(keys, func);
			},

			// Call `func` whenever any of the specified keys is next changed.  The
			// values of all keys will be provided as args to the function.  The
			// function will automatically be unbound after being called the first
			// time, so it is guaranteed to be called no more than once.
			next: function (keyOrList, func) {
				listeners.unshift(
					{ keys: toArray(keyOrList), cb: func, calls: 1 });
			},

			// Call `func` as soon as all of the specified keys have been set.  If
			// they are already set, the function will be called immediately, with
			// all the values provided as args.  Guaranteed to be called no more
			// than once.
			once: function (keyOrList, func) {
				var keys = toArray(keyOrList),
					results = get(nucleus, keys),
					values = results.values,
					missing = results.missing;
				if (!missing) {
					func.apply({}, values);
				} else {
					listeners.unshift(
						{ keys: keys, cb: func, missing: missing, calls: 1 });
				}
			},

			// Register a provider for a particular key.  The provider `func` is a
			// function that will be called if there is a need to create the key.
			// It must call its first arg as a callback, with the value.  Provider
			// functions will be called at most once.
			provide: function (key, func) {
				if (needs[key]) {
					provide(nucleus, key, func);
				} else if (!providers[key]) {
					providers[key] = func;
				}
			},

			// Set value for a key, or if `keyOrMap` is an object then set all the
			// keys' corresponding values.
			set: function (keyOrMap, value) {
				if (typeof keyOrMap === 'object') {
					for (var key in keyOrMap) {
						if (keyOrMap.hasOwnProperty(key)) {
							set(nucleus, key, keyOrMap[key]);
						}
					}
				} else {
					set(nucleus, keyOrMap, value);
				}
			},

			// Unregister a listener `func` that was previously registered using
			// `bind()`, `need()`, `next()` or `once()`.
			unbind: function (func) { // alias: `off`
				for (var i = listeners.length; --i >= 0;) {
					if (listeners[i].cb === func) {
						listeners.splice(i, 1);
					}
				}
			}
		};
		me.on = me.bind;
		me.off = me.unbind;
		return me;
	};

}());
<|endoftext|>